forked from anomalyco/opencode
-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathentry-android.tsx
More file actions
356 lines (326 loc) · 12.2 KB
/
Copy pathentry-android.tsx
File metadata and controls
356 lines (326 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
// @refresh reload
import { render } from "solid-js/web"
import { createResource, createSignal, onCleanup, onMount, Show } from "solid-js"
import { AppBaseProviders, AppInterface, PlatformProvider, ServerConnection, type Platform } from "@opencode-ai/app"
import { showToast } from "@opencode-ai/ui/toast"
import { requestPermissions } from "@tauri-apps/api/core"
import { impactFeedback, notificationFeedback } from "@tauri-apps/plugin-haptics"
import { isPermissionGranted, requestPermission, sendNotification } from "@tauri-apps/plugin-notification"
import { openUrl } from "@tauri-apps/plugin-opener"
import { Store } from "@tauri-apps/plugin-store"
import { bridge } from "./bridge"
import { createTauriStorage } from "./storage"
import { VoiceInputOverlay } from "./voice-input"
import { Onboarding } from "./onboarding"
import pkg from "../package.json"
type VoiceState = "prewarming" | "ready" | "recording" | "processing" | "error"
type VoiceStatus = {
state: VoiceState
ready: boolean
message?: string
}
type VoiceStartResult = {
ok: boolean
code?: string
message?: string
}
type VoiceStopResult = {
text: string
code?: string
message?: string
}
const SETTINGS_STORE = "opencode.settings.dat"
const DEFAULT_SERVER_URL_KEY = "defaultServerUrl"
const DEFAULT_SERVER_USERNAME_KEY = "defaultServerUsername"
const DEFAULT_SERVER_PASSWORD_KEY = "defaultServerPassword"
const DEFAULT_SERVER_DISPLAY_NAME_KEY = "defaultServerDisplayName"
const settingsStore = Store.load(SETTINGS_STORE)
type ServerConfig = { url: string; displayName?: string; username?: string; password?: string }
const normalizeServerUrl = (input: string) => {
const trimmed = input.trim()
if (!trimmed) return
const withProtocol = /^https?:\/\//.test(trimmed) ? trimmed : `http://${trimmed}`
return withProtocol.replace(/\/+$/, "")
}
const getDefaultServerConfig = async (): Promise<ServerConfig | null> => {
const store = await settingsStore
const url = await store.get(DEFAULT_SERVER_URL_KEY).catch(() => null)
if (typeof url !== "string") return null
const displayName = await store.get(DEFAULT_SERVER_DISPLAY_NAME_KEY).catch(() => null)
const username = await store.get(DEFAULT_SERVER_USERNAME_KEY).catch(() => null)
const password = await store.get(DEFAULT_SERVER_PASSWORD_KEY).catch(() => null)
return {
url,
displayName: typeof displayName === "string" ? displayName : undefined,
username: typeof username === "string" ? username : undefined,
password: typeof password === "string" ? password : undefined,
}
}
const setDefaultServerConfig = async (config: ServerConfig | null) => {
const store = await settingsStore
if (config) {
await store.set(DEFAULT_SERVER_URL_KEY, config.url).catch(() => undefined)
if (config.displayName) await store.set(DEFAULT_SERVER_DISPLAY_NAME_KEY, config.displayName).catch(() => undefined)
else await store.delete(DEFAULT_SERVER_DISPLAY_NAME_KEY).catch(() => undefined)
if (config.username) await store.set(DEFAULT_SERVER_USERNAME_KEY, config.username).catch(() => undefined)
else await store.delete(DEFAULT_SERVER_USERNAME_KEY).catch(() => undefined)
if (config.password) await store.set(DEFAULT_SERVER_PASSWORD_KEY, config.password).catch(() => undefined)
else await store.delete(DEFAULT_SERVER_PASSWORD_KEY).catch(() => undefined)
} else {
await store.delete(DEFAULT_SERVER_URL_KEY).catch(() => undefined)
await store.delete(DEFAULT_SERVER_DISPLAY_NAME_KEY).catch(() => undefined)
await store.delete(DEFAULT_SERVER_USERNAME_KEY).catch(() => undefined)
await store.delete(DEFAULT_SERVER_PASSWORD_KEY).catch(() => undefined)
}
await store.save().catch(() => undefined)
}
const getDefaultServerUrl = async () => {
const config = await getDefaultServerConfig()
return config?.url ? ServerConnection.Key.make(config.url) : null
}
const setDefaultServerUrl = async (url: ServerConnection.Key | null) => {
if (url) {
await setDefaultServerConfig({ url })
} else {
await setDefaultServerConfig(null)
}
}
const root = document.getElementById("root")
if (import.meta.env.DEV && !(root instanceof HTMLElement)) {
throw new Error("Root element not found")
}
const App = () => {
const [voice, setVoice] = createSignal<VoiceStatus>({ state: "prewarming", ready: false })
const emitTranscription = (text: string, isFinal?: boolean) => {
if (!text) return
window.dispatchEvent(new CustomEvent("opencode:transcription", { detail: { text, isFinal } }))
}
const emitResume = () => {
window.dispatchEvent(new Event("opencode:resume"))
}
const showVoiceError = (message?: string) => {
if (!message) return
showToast({
title: "Voice input failed",
description: message,
variant: "error",
})
}
const normalizeStatus = (value: unknown): VoiceStatus | null => {
if (!value || typeof value !== "object") return null
const state = (value as { state?: unknown }).state
if (
state !== "prewarming" &&
state !== "ready" &&
state !== "recording" &&
state !== "processing" &&
state !== "error"
) {
return null
}
return {
state,
ready: (value as { ready?: unknown }).ready === true,
message:
typeof (value as { message?: unknown }).message === "string"
? (value as { message: string }).message
: undefined,
}
}
const refreshVoice = async () => {
const result = await bridge.sendAsync<VoiceStatus>("isWhisperReady")
const status = normalizeStatus(result)
if (!status) return
setVoice(status)
}
const startVoiceInput = async (): Promise<VoiceStartResult> => {
await requestPermissions("mobile-bridge").catch(() => undefined)
const result = await bridge.sendAsync<VoiceStartResult>("startRecording")
if (result?.ok) {
setVoice({ state: "recording", ready: false })
return result
}
const message = result?.message ?? "Voice input is unavailable."
showVoiceError(message)
await refreshVoice()
return {
ok: false,
code: result?.code ?? "voice_start_failed",
message,
}
}
const stopVoiceInput = async (): Promise<VoiceStopResult> => {
setVoice((value) => (value.state === "recording" ? { ...value, state: "processing", ready: false } : value))
const result = await bridge.sendAsync<VoiceStopResult>("stopRecording")
if (!result) {
const message = "Voice input is unavailable."
showVoiceError(message)
await refreshVoice()
return {
text: "",
code: "voice_stop_failed",
message,
}
}
if (result.code) {
showVoiceError(result.message ?? "Voice transcription failed.")
await refreshVoice()
return result
}
await refreshVoice()
if (result.text) emitTranscription(result.text, true)
return result
}
const platform: Platform = {
platform: "android",
os: "android",
version: pkg.version,
openLink: (url: string) => {
void openUrl(url).catch(() => undefined)
},
notify: async (title: string, description?: string, href?: string, opts?: unknown) => {
void href
void opts
const granted = await isPermissionGranted().catch(() => false)
const permission = granted ? "granted" : await requestPermission().catch(() => "denied")
if (permission !== "granted") return
await Promise.resolve()
.then(() =>
sendNotification({
title,
body: description ?? "",
}),
)
.catch(() => undefined)
},
back: () => window.history.back(),
forward: () => window.history.forward(),
restart: async () => window.location.reload(),
voiceStatus: voice,
startVoiceInput,
stopVoiceInput,
haptic: (style: "light" | "medium" | "heavy" | "success" | "warning" | "error") => {
if (style === "success" || style === "warning" || style === "error") {
void notificationFeedback(style).catch(() => undefined)
return
}
void impactFeedback(style).catch(() => undefined)
},
share: async (data: { text?: string; url?: string }) => {
const result = await bridge.sendAsync<boolean>("share", data)
return result ?? false
},
getDefaultServer: getDefaultServerUrl,
setDefaultServer: setDefaultServerUrl,
storage: (name?: string) => createTauriStorage(name),
}
const [defaultConfig] = createResource(async () => {
const config = await getDefaultServerConfig()
return config ?? null
})
const [completedConfig, setCompletedConfig] = createSignal<ServerConfig | null>(null)
const handleOnboardingComplete = async (server: {
url: string
displayName?: string
username?: string
password?: string
}) => {
const normalized = normalizeServerUrl(server.url)
if (!normalized) return
const config: ServerConfig = {
url: normalized,
displayName: server.displayName,
username: server.username,
password: server.password,
}
await setDefaultServerConfig(config)
setCompletedConfig(config)
}
onMount(() => {
document.documentElement.dataset.platform = "android"
void refreshVoice()
const syncViewport = () => {
const height = window.visualViewport?.height ?? window.innerHeight
document.documentElement.style.setProperty("--android-viewport-height", `${height}px`)
}
syncViewport()
const handleClick = (event: MouseEvent) => {
const link = (event.target as HTMLElement | null)?.closest("a.external-link") as HTMLAnchorElement | null
if (!link?.href) return
event.preventDefault()
platform.openLink(link.href)
}
const onFocus = () => emitResume()
const onVisible = () => {
if (document.visibilityState !== "visible") return
emitResume()
}
const stopListening = bridge.on("transcription", (payload) => {
if (!payload || typeof payload !== "object") return
const detail = payload as { text?: string; isFinal?: boolean }
if (typeof detail.text !== "string") return
emitTranscription(detail.text, detail.isFinal)
})
const stopVoiceState = bridge.on("voiceState", (payload) => {
const status = normalizeStatus(payload)
if (!status) return
setVoice(status)
if (status.state === "error") showVoiceError(status.message)
})
document.addEventListener("click", handleClick)
window.addEventListener("focus", onFocus)
window.addEventListener("resize", syncViewport)
window.visualViewport?.addEventListener("resize", syncViewport)
window.visualViewport?.addEventListener("scroll", syncViewport)
document.addEventListener("visibilitychange", onVisible)
onCleanup(() => {
document.removeEventListener("click", handleClick)
window.removeEventListener("focus", onFocus)
window.removeEventListener("resize", syncViewport)
window.visualViewport?.removeEventListener("resize", syncViewport)
window.visualViewport?.removeEventListener("scroll", syncViewport)
document.removeEventListener("visibilitychange", onVisible)
stopListening()
stopVoiceState()
})
})
return (
<PlatformProvider value={platform}>
<AppBaseProviders>
<VoiceInputOverlay
state={() => {
const state = voice().state
if (state === "recording" || state === "processing") return state
return "hidden"
}}
onStop={() => void stopVoiceInput()}
/>
<Show when={!defaultConfig.loading}>
<Show
when={defaultConfig() || completedConfig()}
fallback={<Onboarding onComplete={handleOnboardingComplete} />}
>
<AppInterface
{...(() => {
const config = (defaultConfig() || completedConfig())!
const conn: ServerConnection.Http = {
type: "http",
displayName: config.displayName,
http: {
url: config.url,
username: config.username,
password: config.password,
},
}
return { defaultServer: ServerConnection.key(conn), servers: [conn] }
})()}
/>
</Show>
</Show>
</AppBaseProviders>
</PlatformProvider>
)
}
if (root instanceof HTMLElement) {
render(() => <App />, root)
}