From b903ae5cc91a2a5dfdfd245ea1f1d581142e09bb Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:56:16 -0600 Subject: [PATCH] fix(app): switch language atomically and bound camera, sound preview and lab browsing (#62121) --- packages/app/e2e/regression/settings.spec.ts | 37 ++++ packages/app/src/components-lab/lab.tsx | 41 +++-- .../app/src/components-lab/machine.test.ts | 78 +++++++++ packages/app/src/components-lab/machine.ts | 88 ++++++++++ packages/app/src/runtime/i18n/en.ts | 1 + packages/app/src/runtime/i18n/language.tsx | 98 +++++++++-- packages/app/src/runtime/i18n/machine.test.ts | 148 ++++++++++++++++ packages/app/src/runtime/i18n/machine.ts | 164 ++++++++++++++++++ packages/app/src/servers/connect/camera.ts | 33 ---- .../app/src/servers/connect/controller.ts | 49 +++++- packages/app/src/servers/connect/dialog.tsx | 33 ++-- .../app/src/servers/connect/machine.test.ts | 111 ++++++++++-- packages/app/src/servers/connect/machine.ts | 134 +++++++++++--- packages/app/src/servers/connect/screen.tsx | 31 ++-- packages/app/src/settings/general/behavior.ts | 72 +++++--- .../general/sound-preview-machine.test.ts | 114 ++++++++++++ .../settings/general/sound-preview-machine.ts | 109 ++++++++++++ 17 files changed, 1173 insertions(+), 168 deletions(-) create mode 100644 packages/app/src/runtime/i18n/machine.test.ts create mode 100644 packages/app/src/runtime/i18n/machine.ts delete mode 100644 packages/app/src/servers/connect/camera.ts create mode 100644 packages/app/src/settings/general/sound-preview-machine.test.ts create mode 100644 packages/app/src/settings/general/sound-preview-machine.ts diff --git a/packages/app/e2e/regression/settings.spec.ts b/packages/app/e2e/regression/settings.spec.ts index 51f5589bed2..c4260f2ce98 100644 --- a/packages/app/e2e/regression/settings.spec.ts +++ b/packages/app/e2e/regression/settings.spec.ts @@ -96,6 +96,43 @@ test("a settings page survives refresh", async ({ page }) => { await expect(page).toHaveURL("/settings?tab=appearance") }) +// The Arabic dictionary chunks: built (`_assets/ar-.js`) and dev (`.../i18n/ar.ts`), for the app and the UI. +const arabic = /\/(?:_assets\/ar-[\w-]+\.js|i18n\/ar\.ts)(?:\?|$)/ + +async function pickArabic(page: Page) { + const { settings } = await open(page) + await settings.locator('[data-action="settings-language"]').click() + await page.getByRole("listbox").getByRole("option", { name: "العربية", exact: true }).click() + + return settings +} + +test("a language switch keeps settings on screen and flips direction only with the new strings", async ({ page }) => { + const chunks = await holdRoute(page, arabic) + const html = page.locator("html") + const settings = await pickArabic(page) + await chunks.arrived + + await expect(settings.getByText("Language", { exact: true })).toBeVisible() + await expect(html).toHaveAttribute("dir", "ltr") + await expect(html).toHaveAttribute("lang", "en") + + chunks.release() + await expect(settings.getByText("اللغة", { exact: true })).toBeVisible() + await expect(html).toHaveAttribute("dir", "rtl") + await expect(html).toHaveAttribute("lang", "ar") +}) + +test("a language whose chunk fails to load keeps English and says so", async ({ page }) => { + await page.route(arabic, (route) => route.abort("failed")) + const settings = await pickArabic(page) + + await expect(page.getByText("Failed to load العربية", { exact: true })).toBeVisible() + await expect(settings.getByText("Language", { exact: true })).toBeVisible() + await expect(page.locator("html")).toHaveAttribute("dir", "ltr") + await expect(settings.locator('[data-action="settings-language"]')).toContainText("English") +}) + test("Questions settings default independently of old Permissions settings and survive reload", async ({ page }) => { const { settings } = await open(page, { seed: { diff --git a/packages/app/src/components-lab/lab.tsx b/packages/app/src/components-lab/lab.tsx index fee9821ea84..3c2a6297f89 100644 --- a/packages/app/src/components-lab/lab.tsx +++ b/packages/app/src/components-lab/lab.tsx @@ -49,8 +49,12 @@ import { } from "./catalog" import { createLabStageState, + INITIAL_LAB_BROWSE_STATE, labStageIndex, + selectShouldToggleFolder, + transitionLabBrowse, transitionLabStage, + type LabBrowseEvent, type LabStageEffect, type LabStageEvent, } from "./machine" @@ -124,18 +128,20 @@ export default function ComponentsLab() { let palette: CommandPalette | undefined let toggle: ((id: string) => void) | undefined let focusTree: ((id?: string) => void) | undefined - // While browsing the tree by keys, a story that focuses something as it mounts (a dialog, a field) would take the - // keys away. A press or Tab anywhere ends browsing; a few returns at most, so a story that traps focus still wins. - let browsing = 0 - // The key behind the latest selection; none for a press. - let key: string | undefined + let browse = INITIAL_LAB_BROWSE_STATE + + const dispatchBrowse = (event: LabBrowseEvent) => { + const next = transitionLabBrowse(browse, event) + browse = next.state + next.effects.forEach(() => focusTree?.(params.story)) + } const entries = () => catalog()?.entries ?? [] const grid = () => params.view === "grid" const selected = createMemo(() => (grid() ? undefined : entries().find((entry) => entry.file === params.story))) const open = (file: string) => { - browsing = stories.contains(document.activeElement) ? 3 : 0 + dispatchBrowse({ type: "story.opened", fromTree: stories.contains(document.activeElement) }) setParams({ story: file, view: undefined }) } @@ -229,7 +235,7 @@ export default function ComponentsLab() { onSelect={(_, primary) => { if (!primary?.startsWith("folder:")) return primary && open(primary) - if (key === undefined || key === " ") toggle?.(primary) + if (selectShouldToggleFolder(browse)) toggle?.(primary) }} onActivate={(id) => (id.startsWith("folder:") ? toggle?.(id) : open(id))} /> @@ -261,20 +267,23 @@ export default function ComponentsLab() { )) - makeEventListener(window, "pointerdown", () => ((browsing = 0), (key = undefined)), { capture: true }) + const inTree = (event: Event) => event.target instanceof Node && stories.contains(event.target) + + makeEventListener(window, "pointerdown", (event) => dispatchBrowse({ type: "pointer.down", inTree: inTree(event) }), { + capture: true, + }) + // Bubbling, so the tree's own pointerup (which completes a press on a selected row) selects first. + makeEventListener(window, "pointerup", () => dispatchBrowse({ type: "pointer.ended" })) + makeEventListener(window, "pointercancel", () => dispatchBrowse({ type: "pointer.ended" })) makeEventListener( window, "keydown", - (event) => { - key = event.key - - if (event.key === "Tab") browsing = 0 - }, + (event) => dispatchBrowse({ type: "key.down", key: event.key, inTree: inTree(event) }), { capture: true }, ) - makeEventListener(stage, "focusin", () => { - if (browsing-- > 0) focusTree?.(params.story) - }) + makeEventListener(window, "keyup", () => dispatchBrowse({ type: "key.ended" })) + makeEventListener(window, "blur", () => dispatchBrowse({ type: "window.blurred" })) + makeEventListener(stage, "focusin", () => dispatchBrowse({ type: "stage.focused" })) let element!: HTMLDivElement diff --git a/packages/app/src/components-lab/machine.test.ts b/packages/app/src/components-lab/machine.test.ts index 2d3da783439..8650e39532d 100644 --- a/packages/app/src/components-lab/machine.test.ts +++ b/packages/app/src/components-lab/machine.test.ts @@ -1,13 +1,91 @@ import { expect, test } from "bun:test" import { createLabStageState, + INITIAL_LAB_BROWSE_STATE, labStageIndex, + selectShouldToggleFolder, + transitionLabBrowse, transitionLabStage, + type LabBrowseEvent, + type LabBrowseState, type LabStageEvent, type LabStageState, type LabStageTransition, } from "./machine" +/** Each event's effects from `state`, and the state after the last. */ +const browse = (state: LabBrowseState, ...events: LabBrowseEvent[]) => + events.reduce<{ state: LabBrowseState; effects: string[] }>( + (current, event) => { + const next = transitionLabBrowse(current.state, event) + + return { state: next.state, effects: [...current.effects, ...next.effects.map((effect) => effect.type)] } + }, + { state, effects: [] }, + ) + +test("focus moving inside the stage at rest stays at rest", () => { + const focused = browse(INITIAL_LAB_BROWSE_STATE, { type: "stage.focused" }, { type: "stage.focused" }) + + expect(focused.state).toBe(INITIAL_LAB_BROWSE_STATE) + expect(focused.effects).toEqual([]) + + // Many focus moves later, a story opened from the tree still gets exactly three returns. + const opened = browse( + focused.state, + { type: "story.opened", fromTree: true }, + ...Array.from({ length: 4 }, () => ({ type: "stage.focused" }) as const), + ) + + expect(opened.effects).toEqual(["focus.tree", "focus.tree", "focus.tree"]) + expect(opened.state).toBe(INITIAL_LAB_BROWSE_STATE) +}) + +test.each([{ type: "key.ended" }, { type: "window.blurred" }] as const)( + "a Space press in the tree no longer toggles folders after $type", + (end) => { + const pressed = browse(INITIAL_LAB_BROWSE_STATE, { type: "key.down", key: " ", inTree: true }) + + expect(selectShouldToggleFolder(pressed.state)).toBe(true) + expect(selectShouldToggleFolder(browse(pressed.state, end).state)).toBe(false) + }, +) + +test("a Space press outside the tree and arrow keys in it never toggle folders", () => { + expect(selectShouldToggleFolder(INITIAL_LAB_BROWSE_STATE)).toBe(false) + expect(browse(INITIAL_LAB_BROWSE_STATE, { type: "key.down", key: " ", inTree: false }).state).toBe( + INITIAL_LAB_BROWSE_STATE, + ) + expect( + selectShouldToggleFolder( + browse( + INITIAL_LAB_BROWSE_STATE, + { type: "key.down", key: " ", inTree: true }, + { type: "key.down", key: "ArrowDown", inTree: true }, + ).state, + ), + ).toBe(false) +}) + +test("a click in the tree toggles folders until the press ends", () => { + const pressed = browse(INITIAL_LAB_BROWSE_STATE, { type: "pointer.down", inTree: true }) + + expect(selectShouldToggleFolder(pressed.state)).toBe(true) + expect(browse(pressed.state, { type: "pointer.ended" }).state).toBe(INITIAL_LAB_BROWSE_STATE) +}) + +test.each([ + { type: "key.down", key: "Tab", inTree: true }, + { type: "pointer.down", inTree: false }, +] as const)("$type ends browsing before the stage takes focus", (exit) => { + const ended = browse(INITIAL_LAB_BROWSE_STATE, { type: "story.opened", fromTree: true }, exit, { + type: "stage.focused", + }) + + expect(ended.effects).toEqual([]) + expect(ended.state).toBe(INITIAL_LAB_BROWSE_STATE) +}) + const names = ["Closed", "Opening", "Open"] /** The last transition of `events` from `state`. */ diff --git a/packages/app/src/components-lab/machine.ts b/packages/app/src/components-lab/machine.ts index 7699bde89f5..1f1cd9b10ce 100644 --- a/packages/app/src/components-lab/machine.ts +++ b/packages/app/src/components-lab/machine.ts @@ -139,3 +139,91 @@ function show( function unchanged(state: LabStageState): LabStageTransition { return { state, effects: [] } } + +/** + * How a press reached the tree. A folder opens and closes only by a click or Space in the tree, so moving by arrows + * (which selects as it goes) or a selection from elsewhere leaves it as it is. + */ +export type LabTreeGesture = "none" | "pointer" | "space" + +/** + * While browsing the tree by keys, a story that focuses something as it mounts (a dialog, a field) would take the + * keys away. A press or Tab anywhere ends browsing; a few returns at most, so a story that traps focus still wins. + */ +export type LabBrowseState = + | { readonly status: "idle"; readonly gesture: LabTreeGesture } + | { readonly status: "browsing"; readonly redirects: 1 | 2 | 3; readonly gesture: LabTreeGesture } + +export type LabBrowseEvent = + | { readonly type: "pointer.down"; readonly inTree: boolean } + | { readonly type: "pointer.ended" } + | { readonly type: "key.down"; readonly key: string; readonly inTree: boolean } + | { readonly type: "key.ended" } + | { readonly type: "window.blurred" } + | { readonly type: "story.opened"; readonly fromTree: boolean } + /** Focus moved into the stage. */ + | { readonly type: "stage.focused" } + +export type LabBrowseEffect = { readonly type: "focus.tree" } + +export type LabBrowseTransition = { + readonly state: LabBrowseState + readonly effects: readonly LabBrowseEffect[] +} + +export const INITIAL_LAB_BROWSE_STATE: LabBrowseState = Object.freeze({ status: "idle", gesture: "none" }) + +export function transitionLabBrowse(state: LabBrowseState, event: LabBrowseEvent): LabBrowseTransition { + if (event.type === "pointer.down") { + const gesture = event.inTree ? "pointer" : "none" + + return { state: state.status === "idle" && state.gesture === gesture ? state : idle(gesture), effects: [] } + } + + if (event.type === "key.down") { + if (event.key === "Tab") return { state: INITIAL_LAB_BROWSE_STATE, effects: [] } + + return { state: withGesture(state, event.key === " " && event.inTree ? "space" : "none"), effects: [] } + } + + if (event.type === "pointer.ended") + return { state: state.gesture === "pointer" ? withGesture(state, "none") : state, effects: [] } + + if (event.type === "key.ended") + return { state: state.gesture === "space" ? withGesture(state, "none") : state, effects: [] } + + if (event.type === "window.blurred") return { state: INITIAL_LAB_BROWSE_STATE, effects: [] } + + if (event.type === "story.opened") { + if (!event.fromTree) return { state: idle(state.gesture), effects: [] } + + return { state: { status: "browsing", redirects: 3, gesture: state.gesture }, effects: [] } + } + + if (state.status === "idle") return { state, effects: [] } + + return { + state: + state.redirects === 1 + ? idle(state.gesture) + : { status: "browsing", redirects: state.redirects === 3 ? 2 : 1, gesture: state.gesture }, + effects: [{ type: "focus.tree" }], + } +} + +/** A selection of a folder toggles it only while a click or Space in the tree caused it. */ +export function selectShouldToggleFolder(state: LabBrowseState) { + return state.gesture !== "none" +} + +function idle(gesture: LabTreeGesture): LabBrowseState { + return gesture === "none" ? INITIAL_LAB_BROWSE_STATE : { status: "idle", gesture } +} + +function withGesture(state: LabBrowseState, gesture: LabTreeGesture): LabBrowseState { + if (state.gesture === gesture) return state + + if (state.status === "idle") return idle(gesture) + + return { ...state, gesture } +} diff --git a/packages/app/src/runtime/i18n/en.ts b/packages/app/src/runtime/i18n/en.ts index a7476df2a47..bf23389b00b 100644 --- a/packages/app/src/runtime/i18n/en.ts +++ b/packages/app/src/runtime/i18n/en.ts @@ -491,6 +491,7 @@ export const dict = { "toast.permissions.autoaccept.off.description": "Permission requests will require approval", "toast.file.loadFailed.title": "Failed to load file", + "toast.language.loadFailed.title": "Failed to load {{language}}", "toast.file.listFailed.title": "Failed to list files", "toast.context.noLineSelection.title": "No line selection", diff --git a/packages/app/src/runtime/i18n/language.tsx b/packages/app/src/runtime/i18n/language.tsx index 90e7792a1a0..4100d3560fe 100644 --- a/packages/app/src/runtime/i18n/language.tsx +++ b/packages/app/src/runtime/i18n/language.tsx @@ -1,7 +1,8 @@ -import { createEffect, createMemo, createResource, type JSX } from "solid-js" +import { batch, createEffect, createMemo, createSignal, on, onCleanup, untrack, type JSX } from "solid-js" import { createStore } from "solid-js/store" import { Option, Schema, SchemaGetter } from "effect" import { createSimpleContext } from "@opencode/ui/context" +import { showToast } from "@opencode/ui/toast" import { I18nProvider, type UiI18n, @@ -25,6 +26,14 @@ import { type DesktopNativeBundle, type DesktopNativeLocale, } from "@/runtime/i18n/desktop-native" +import { + createLanguageState, + selectDictionary, + selectLocale, + transitionLanguage, + type LanguageEffect, + type LanguageEvent, +} from "@/runtime/i18n/machine" export type Locale = DesktopNativeLocale @@ -242,7 +251,64 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont const initial = props.locale ?? readStoredLocale() ?? detectLocale() const [store, setStore, _, ready] = persisted(Persist.global("language"), languageSchema, { locale: initial }) - const locale = createMemo(() => store.locale) + const stored = untrack(() => store.locale) + + const boot = createLanguageState({ + initial: stored, + cached: dicts.get(stored), + fallbackLocale: "en", + fallbackDictionary: base, + }) + + const [machine, setMachine] = createSignal(boot.state) + let timer: ReturnType | undefined + + const dispatch = (event: LanguageEvent) => + batch(() => { + const prev = untrack(machine) + const next = transitionLanguage(prev, event) + + if (next.state !== prev) setMachine(next.state) + next.effects.forEach(run) + }) + + const run = (effect: LanguageEffect) => { + if (effect.type === "load") + return void Promise.try(() => loadDict(effect.locale)).then( + (dictionary) => dispatch({ type: "load.succeeded", attempt: effect.attempt, dictionary }), + () => dispatch({ type: "load.failed", attempt: effect.attempt }), + ) + + if (effect.type === "timer.start") { + clearTimeout(timer) + timer = setTimeout(() => dispatch({ type: "load.timed-out", attempt: effect.attempt }), effect.timeoutMs) + + return + } + + if (effect.type === "timer.stop") { + clearTimeout(timer) + timer = undefined + + return + } + + if (effect.type === "persist") { + if (untrack(() => store.locale) !== effect.locale) setStore("locale", effect.locale) + + return + } + + showToast({ + variant: "error", + title: t("toast.language.loadFailed.title", { language: label(effect.locale) }), + }) + } + + // The committed pair: every reader switches only once the dictionary for the new locale is in hand, so `t()` + // never suspends and the direction never flips ahead of the strings. + const locale = createMemo(() => selectLocale(machine())) + const dictionary = createMemo(() => selectDictionary(machine())) const intl = createMemo(() => INTL[locale()]) // SAFETY: widens the initial `undefined` so a direction can be stored later. const [layout, setLayout] = createStore({ direction: undefined as Direction | undefined }) @@ -255,15 +321,11 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont return layout.direction === "rtl" ? "ar" : "en" }) - const [dictionary] = createResource(locale, loadDict, { - initialValue: dicts.get(initial) ?? base, - }) - const t = >( key: TranslationKey, params?: Record, ) => { - const template: string | undefined = (dictionary() ?? base)[key] + const template: string | undefined = dictionary()[key] // A key outside the dictionary translates to nothing, as it did with the package translator. return template === undefined ? template : resolveTemplate(template, params) @@ -275,7 +337,7 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont params?: Record, ) => { // SAFETY: every dictionary value is a string (`language.test.ts`). - const current = (dictionary.loading ? base : (dictionary() ?? base)) as Record + const current = dictionary() as Record const candidate = `${key}.${category}` const fallback = `${key}.other` @@ -306,7 +368,7 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont params: Record, ) => { // SAFETY: every dictionary value is a string (`language.test.ts`). - const current = (dictionary.loading ? base : (dictionary() ?? base)) as Record + const current = dictionary() as Record return richTemplateParts(current[key] ?? key, params) } @@ -337,15 +399,26 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont }) createEffect(() => { - if (!props.onNativeTranslations || dictionary.loading) return + if (!props.onNativeTranslations) return const current = dictionary() - if (!current) return props.onNativeTranslations( createDesktopNativeBundle(locale(), (key) => current[key] ?? DESKTOP_NATIVE_ENGLISH[key]), ) }) + // Storage hydrating after mount, or another window picking a language. + createEffect( + on( + () => store.locale, + (next) => dispatch({ type: "locale.synced", locale: next, cached: dicts.get(next) }), + { defer: true }, + ), + ) + + onCleanup(() => dispatch({ type: "disposed" })) + boot.effects.forEach(run) + return { ready, locale, @@ -363,7 +436,8 @@ export const { use: useLanguage, provider: LanguageProvider } = createSimpleCont rich, list, setLocale(next: Locale) { - setStore("locale", normalizeLocale(next)) + const target = normalizeLocale(next) + dispatch({ type: "locale.requested", locale: target, cached: dicts.get(target) }) }, setDirection(next: Direction) { setLayout("direction", next === localeDirection(locale()) ? undefined : next) diff --git a/packages/app/src/runtime/i18n/machine.test.ts b/packages/app/src/runtime/i18n/machine.test.ts new file mode 100644 index 00000000000..98d9446b7a6 --- /dev/null +++ b/packages/app/src/runtime/i18n/machine.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, test } from "bun:test" +import { + createLanguageState, + LOCALE_LOAD_TIMEOUT_MS, + selectDictionary, + selectLocale, + transitionLanguage, + type LanguageEffect, + type LanguageEvent, + type LanguageState, +} from "./machine" + +type Dict = { readonly hello: string } + +const en: Dict = { hello: "Hello" } + +const de: Dict = { hello: "Hallo" } + +const ar: Dict = { hello: "مرحبا" } + +const readyOn = (locale: "en" | "de", dictionary: Dict) => + createLanguageState({ initial: locale, cached: dictionary, fallbackLocale: "en", fallbackDictionary: en }).state + +function replay(state: LanguageState, events: readonly LanguageEvent[]) { + return events.reduce<{ state: LanguageState; effects: LanguageEffect[] }>( + (result, event) => { + const next = transitionLanguage(result.state, event) + + return { state: next.state, effects: [...result.effects, ...next.effects] } + }, + { state, effects: [] }, + ) +} + +const shown = (state: LanguageState) => ({ locale: selectLocale(state), dictionary: selectDictionary(state) }) + +describe("language machine", () => { + test("a failed chunk for a picked language keeps the current one and says so", () => { + const loading = transitionLanguage(readyOn("en", en), { type: "locale.requested", locale: "ar", cached: undefined }) + + expect(loading.effects).toEqual([ + { type: "load", attempt: 1, locale: "ar" }, + { type: "timer.start", attempt: 1, timeoutMs: LOCALE_LOAD_TIMEOUT_MS }, + ]) + expect(shown(loading.state)).toEqual({ locale: "en", dictionary: en }) + + const failed = transitionLanguage(loading.state, { type: "load.failed", attempt: 1 }) + + expect(failed.state).toEqual({ status: "ready", issued: 1, locale: "en", dictionary: en }) + expect(failed.effects).toEqual([{ type: "timer.stop" }, { type: "notify.error", locale: "ar" }]) + }) + + test("a stored language whose chunk fails at startup falls back to English quietly", () => { + const boot = createLanguageState({ + initial: "ja", + cached: undefined, + fallbackLocale: "en", + fallbackDictionary: en, + }) + + expect(shown(boot.state)).toEqual({ locale: "en", dictionary: en }) + expect(boot.effects[0]).toEqual({ type: "load", attempt: 1, locale: "ja" }) + + const failed = transitionLanguage(boot.state, { type: "load.failed", attempt: 1 }) + + expect(shown(failed.state)).toEqual({ locale: "en", dictionary: en }) + expect(failed.effects).toEqual([{ type: "timer.stop" }]) + }) + + test("a switch keeps the previous language and direction until the new dictionary lands, then commits both", () => { + const loading = transitionLanguage(readyOn("de", de), { type: "locale.requested", locale: "ar", cached: undefined }) + + expect(shown(loading.state)).toEqual({ locale: "de", dictionary: de }) + + const loaded = transitionLanguage(loading.state, { type: "load.succeeded", attempt: 1, dictionary: ar }) + + expect(shown(loaded.state)).toEqual({ locale: "ar", dictionary: ar }) + expect(loaded.effects).toEqual([{ type: "timer.stop" }, { type: "persist", locale: "ar" }]) + }) + + test("a chunk that never answers times out back to the committed language", () => { + const result = replay(readyOn("en", en), [ + { type: "locale.requested", locale: "ar", cached: undefined }, + { type: "load.timed-out", attempt: 1 }, + ]) + + expect(shown(result.state)).toEqual({ locale: "en", dictionary: en }) + expect(result.effects.slice(-2)).toEqual([{ type: "timer.stop" }, { type: "notify.error", locale: "ar" }]) + }) + + test.each([ + { name: "another uncached language", next: { locale: "fr", cached: undefined }, shows: "en" }, + { name: "a cached language", next: { locale: "de", cached: de }, shows: "de" }, + ] as const)("picking $name ignores the earlier load's late result", (input) => { + const switched = replay(readyOn("en", en), [ + { type: "locale.requested", locale: "ar", cached: undefined }, + { type: "locale.requested", ...input.next }, + ]) + + expect(switched.effects).toContainEqual({ type: "timer.stop" }) + + const late = transitionLanguage(switched.state, { type: "load.succeeded", attempt: 1, dictionary: ar }) + + expect(late).toEqual({ state: switched.state, effects: [] }) + expect(selectLocale(late.state)).toBe(input.shows) + }) + + test("storage syncing during the user's own pick does not replace it", () => { + const loading = transitionLanguage(readyOn("en", en), { type: "locale.requested", locale: "ar", cached: undefined }) + + expect(transitionLanguage(loading.state, { type: "locale.synced", locale: "de", cached: de })).toEqual({ + state: loading.state, + effects: [], + }) + }) + + test("a synced language loads without storing or announcing anything", () => { + const result = replay(readyOn("en", en), [ + { type: "locale.synced", locale: "ar", cached: undefined }, + { type: "load.failed", attempt: 1 }, + ]) + + expect(result.effects.filter((effect) => effect.type === "persist" || effect.type === "notify.error")).toEqual([]) + }) + + test("picking the language that is already showing stores it without reloading", () => { + const state = readyOn("en", en) + + expect(transitionLanguage(state, { type: "locale.requested", locale: "en", cached: en })).toEqual({ + state, + effects: [{ type: "persist", locale: "en" }], + }) + }) + + test("disposal stops the load timer, keeps the dictionary readable and ignores later results", () => { + const disposed = replay(readyOn("en", en), [ + { type: "locale.requested", locale: "ar", cached: undefined }, + { type: "disposed" }, + ]) + + expect(disposed.effects.at(-1)).toEqual({ type: "timer.stop" }) + expect(shown(disposed.state)).toEqual({ locale: "en", dictionary: en }) + expect(transitionLanguage(disposed.state, { type: "load.succeeded", attempt: 1, dictionary: ar })).toEqual({ + state: disposed.state, + effects: [], + }) + }) +}) diff --git a/packages/app/src/runtime/i18n/machine.ts b/packages/app/src/runtime/i18n/machine.ts new file mode 100644 index 00000000000..7907f0dc84f --- /dev/null +++ b/packages/app/src/runtime/i18n/machine.ts @@ -0,0 +1,164 @@ +import type { DesktopNativeLocale } from "./desktop-native" + +/** A dynamic `import()` can hang on a stalled network; past this the switch gives up and keeps the current language. */ +export const LOCALE_LOAD_TIMEOUT_MS = 10_000 + +/** + * `locale` and `dictionary` are always the committed pair every reader shows. A load keeps them until its dictionary + * arrives, so the strings, plural rules, `lang`/`dir` and the stored choice switch together, never one ahead. + */ +export type LanguageState = + | { + readonly status: "ready" + readonly issued: number + readonly locale: DesktopNativeLocale + readonly dictionary: Dict + } + | { + readonly status: "loading" + readonly issued: number + readonly attempt: number + readonly locale: DesktopNativeLocale + readonly dictionary: Dict + /** The locale whose dictionary is loading. */ + readonly target: DesktopNativeLocale + /** The user chose it: success stores the choice and failure tells them. A synced load does neither. */ + readonly persist: boolean + } + | { readonly status: "disposed"; readonly locale: DesktopNativeLocale; readonly dictionary: Dict } + +export type LanguageEvent = + /** The user picked a language. `cached` is its dictionary when it already loaded. */ + | { readonly type: "locale.requested"; readonly locale: DesktopNativeLocale; readonly cached: Dict | undefined } + /** The stored choice changed under us: storage hydrated, or another window picked a language. */ + | { readonly type: "locale.synced"; readonly locale: DesktopNativeLocale; readonly cached: Dict | undefined } + | { readonly type: "load.succeeded"; readonly attempt: number; readonly dictionary: Dict } + | { readonly type: "load.failed"; readonly attempt: number } + | { readonly type: "load.timed-out"; readonly attempt: number } + | { readonly type: "disposed" } + +export type LanguageEffect = + | { readonly type: "load"; readonly attempt: number; readonly locale: DesktopNativeLocale } + | { readonly type: "timer.start"; readonly attempt: number; readonly timeoutMs: number } + | { readonly type: "timer.stop" } + /** Store the committed choice. */ + | { readonly type: "persist"; readonly locale: DesktopNativeLocale } + | { readonly type: "notify.error"; readonly locale: DesktopNativeLocale } + +export type LanguageTransition = { + readonly state: LanguageState + readonly effects: readonly LanguageEffect[] +} + +/** Starts on `initial` when its dictionary is cached, else on the fallback while `initial` loads. */ +export function createLanguageState(input: { + readonly initial: DesktopNativeLocale + readonly cached: Dict | undefined + readonly fallbackLocale: DesktopNativeLocale + readonly fallbackDictionary: Dict +}): LanguageTransition { + if (input.cached !== undefined) + return { state: { status: "ready", issued: 0, locale: input.initial, dictionary: input.cached }, effects: [] } + + return load( + { status: "ready", issued: 0, locale: input.fallbackLocale, dictionary: input.fallbackDictionary }, + input.initial, + false, + ) +} + +export function transitionLanguage( + state: LanguageState, + event: LanguageEvent, +): LanguageTransition { + if (state.status === "disposed") return { state, effects: [] } + + const stop = state.status === "loading" ? [STOP] : [] + + if (event.type === "disposed") + return { state: { status: "disposed", locale: state.locale, dictionary: state.dictionary }, effects: stop } + + if (event.type === "locale.requested") { + const persist = { type: "persist", locale: event.locale } as const + + // The stored choice can differ from the committed one after a failed load at startup, so it is written again. + if (state.status === "ready" && state.locale === event.locale) return { state, effects: [persist] } + + if (event.cached !== undefined) + return { state: ready(state, event.locale, event.cached), effects: [...stop, persist] } + + if (state.status === "loading" && state.target === event.locale) + return { state: state.persist ? state : { ...state, persist: true }, effects: [] } + + return load(state, event.locale, true) + } + + if (event.type === "locale.synced") { + // The user's own pick wins over the stored value it is about to replace. + if (state.status === "loading" && state.persist) return { state, effects: [] } + + if (state.status === "ready" && state.locale === event.locale) return { state, effects: [] } + + if (event.cached !== undefined) return { state: ready(state, event.locale, event.cached), effects: stop } + + if (state.status === "loading" && state.target === event.locale) return { state, effects: [] } + + return load(state, event.locale, false) + } + + if (state.status !== "loading" || event.attempt !== state.attempt) return { state, effects: [] } + + if (event.type === "load.succeeded") + return { + state: ready(state, state.target, event.dictionary), + effects: state.persist ? [STOP, { type: "persist", locale: state.target }] : [STOP], + } + + return { + state: ready(state, state.locale, state.dictionary), + effects: state.persist ? [STOP, { type: "notify.error", locale: state.target }] : [STOP], + } +} + +export function selectLocale(state: LanguageState) { + return state.locale +} + +export function selectDictionary(state: LanguageState) { + return state.dictionary +} + +const STOP = { type: "timer.stop" } as const + +function ready( + state: Exclude, { status: "disposed" }>, + locale: DesktopNativeLocale, + dictionary: Dict, +): LanguageState { + return { status: "ready", issued: state.issued, locale, dictionary } +} + +function load( + state: Exclude, { status: "disposed" }>, + target: DesktopNativeLocale, + persist: boolean, +): LanguageTransition { + const attempt = state.issued + 1 + + return { + state: { + status: "loading", + issued: attempt, + attempt, + locale: state.locale, + dictionary: state.dictionary, + target, + persist, + }, + effects: [ + ...(state.status === "loading" ? [STOP] : []), + { type: "load", attempt, locale: target }, + { type: "timer.start", attempt, timeoutMs: LOCALE_LOAD_TIMEOUT_MS }, + ], + } +} diff --git a/packages/app/src/servers/connect/camera.ts b/packages/app/src/servers/connect/camera.ts deleted file mode 100644 index 1f3adf17a19..00000000000 --- a/packages/app/src/servers/connect/camera.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { createResource } from "solid-js" -import { usePlatform } from "@/runtime/platform/platform" - -export function createCameraAvailability() { - const platform = usePlatform() - const supported = platform.platform === "web" && window.isSecureContext && !!navigator.mediaDevices?.getUserMedia - - const [available, actions] = createResource( - async () => { - if (!supported || !navigator.mediaDevices.enumerateDevices) return false - - const denied = await navigator.permissions?.query({ name: "camera" }).then( - (permission) => permission.state === "denied", - () => false, - ) - - if (denied) return false - - return navigator.mediaDevices.enumerateDevices().then( - (devices) => devices.some((device) => device.kind === "videoinput"), - () => false, - ) - }, - { initialValue: false }, - ) - - return { supported, available, refetch: actions.refetch } -} - -// Pages served over plain HTTP cannot open the camera. QR codes carry JSON, not a link, so the pasted link is the way in. -export function cameraHint() { - return window.isSecureContext ? "server.connect.camera.unavailable" : "server.connect.camera.native" -} diff --git a/packages/app/src/servers/connect/controller.ts b/packages/app/src/servers/connect/controller.ts index 8415c6756a6..f801b0d4ba5 100644 --- a/packages/app/src/servers/connect/controller.ts +++ b/packages/app/src/servers/connect/controller.ts @@ -5,9 +5,10 @@ import { useCheckServerHealth } from "@/runtime/server/health" import { ServerConnection, useServers } from "@/runtime/server/registry" import { replaceServerConnection } from "@/servers/registry/management" import { - createServerConnectState, selectServerConnectView, + startServerConnect, transitionServerConnect, + type ServerCameraSupport, type ServerConnectEffect, type ServerConnectEvent, type ServerConnectTarget, @@ -36,8 +37,10 @@ export function createServerConnectController(options: ServerConnectControllerOp const check = useCheckServerHealth() // Shared with the scanner, so a retry after a failed check reuses the token of a spent one-time code. const redeem = useRedeemPairing() - const [machine, setMachine] = createSignal(createServerConnectState(options.target)) + const initial = startServerConnect(options.target, cameraSupport(platform.platform)) + const [machine, setMachine] = createSignal(initial.state) let timer: ReturnType | undefined + let cameraTimer: ReturnType | undefined const dispatch = (event: ServerConnectEvent) => { const prev = untrack(machine) @@ -62,6 +65,24 @@ export function createServerConnectController(options: ServerConnectControllerOp return } + if (effect.type === "camera.probe") { + clearTimeout(cameraTimer) + cameraTimer = setTimeout(() => dispatch({ type: "camera.timed-out", attempt: effect.attempt }), effect.timeoutMs) + void Promise.try(probeCamera).then( + (available) => dispatch({ type: "camera.settled", attempt: effect.attempt, available }), + () => dispatch({ type: "camera.settled", attempt: effect.attempt, available: false }), + ) + + return + } + + if (effect.type === "camera.timer.stop") { + clearTimeout(cameraTimer) + cameraTimer = undefined + + return + } + if (effect.type === "connect.http") { const failed = () => dispatch({ @@ -154,6 +175,7 @@ export function createServerConnectController(options: ServerConnectControllerOp } onCleanup(() => dispatch({ type: "disposed" })) + initial.effects.forEach(run) const view = createMemo(() => selectServerConnectView(machine(), { @@ -165,3 +187,26 @@ export function createServerConnectController(options: ServerConnectControllerOp return { view, dispatch, redeem } } + +function cameraSupport(platform: string): ServerCameraSupport { + if (platform !== "web") return "none" + + if (!window.isSecureContext) return "insecure" + + if (!navigator.mediaDevices?.getUserMedia || !navigator.mediaDevices.enumerateDevices) return "unavailable" + + return "probe" +} + +async function probeCamera() { + const denied = await navigator.permissions?.query({ name: "camera" }).then( + (permission) => permission.state === "denied", + () => false, + ) + + if (denied) return false + + const devices = await navigator.mediaDevices.enumerateDevices() + + return devices.some((device) => device.kind === "videoinput") +} diff --git a/packages/app/src/servers/connect/dialog.tsx b/packages/app/src/servers/connect/dialog.tsx index 96d38e19366..a17e27c3d03 100644 --- a/packages/app/src/servers/connect/dialog.tsx +++ b/packages/app/src/servers/connect/dialog.tsx @@ -10,8 +10,6 @@ import { useLanguage } from "@/runtime/i18n/language" import { ServerConnection, useServers } from "@/runtime/server/registry" import { useTabs } from "@/shell/tabs/tabs" import { isServerUnauthorized } from "@/runtime/server/health-machine" -import { usePlatform } from "@/runtime/platform/platform" -import { cameraHint, createCameraAvailability } from "./camera" import { createServerConnectController } from "./controller" import type { ServerConnectField, ServerOriginal } from "./machine" import { ConnectMethodSwitch } from "./method" @@ -26,11 +24,9 @@ export const DialogServer: Component<{ }> = (props) => { const dialog = useDialog() const language = useLanguage() - const platform = usePlatform() const servers = useServers() const global = useGlobal() const tabs = useTabs() - const camera = createCameraAvailability() const edited = props.mode === "edit" ? props.server : undefined const originalOf = (server: ServerConnection.Http): ServerOriginal => ({ @@ -103,10 +99,7 @@ export const DialogServer: Component<{ fallback={ {language.t("server.connect.camera.starting")}

}> { - form.dispatch({ type: "scan.cancelled" }) - void camera.refetch() - }} + onCancel={() => form.dispatch({ type: "scan.cancelled" })} redeem={form.redeem} onScan={(link) => form.dispatch({ type: "scan.completed", link })} /> @@ -207,22 +200,18 @@ export const DialogServer: Component<{ - - {language.t(cameraHint())}} + + - + {language.t("server.connect.scan")} + + {(hint) => {hint()}} = {}): ServerOriginal => ({ const edit = (input: Partial = {}): ServerConnectTarget => ({ kind: "edit", original: original(input) }) -function replay(target: ServerConnectTarget, events: readonly ServerConnectEvent[]) { +function replay( + target: ServerConnectTarget, + events: readonly ServerConnectEvent[], + from: ServerConnectState = startServerConnect(target).state, +) { return events.reduce<{ state: ServerConnectState; effects: ServerConnectEffect[] }>( (result, event) => { const next = transitionServerConnect(result.state, event) return { state: next.state, effects: [...result.effects, ...next.effects] } }, - { state: createServerConnectState(target), effects: [] }, + { state: from, effects: [] }, ) } +/** The web app's form once its camera check found a camera. */ +const withCamera = (target: ServerConnectTarget) => + transitionServerConnect(startServerConnect(target, "probe").state, { + type: "camera.settled", + attempt: 1, + available: true, + }).state + const field = (name: "link" | "url" | "name" | "password", value: string): ServerConnectEvent => ({ type: "field.changed", field: name, @@ -131,10 +144,11 @@ describe("server connect form", () => { }) test("a scanned link submits once", () => { - const scanned = replay({ kind: "add" }, [ - { type: "scan.started" }, - { type: "scan.completed", link: "http://192.168.1.2:4096/auth/connect/abc" }, - ]) + const scanned = replay( + { kind: "add" }, + [{ type: "scan.started" }, { type: "scan.completed", link: "http://192.168.1.2:4096/auth/connect/abc" }], + withCamera({ kind: "add" }), + ) expect(scanned.state).toMatchObject({ status: "submitting", attempt: 1 }) expect(scanned.effects).toEqual([ @@ -155,15 +169,82 @@ describe("server connect form", () => { ).toBe(scanned.state) }) - test("a cancelled scan returns to the form with its values", () => { - const result = replay({ kind: "add" }, [ - field("name", "Remote"), - { type: "scan.started" }, - { type: "scan.cancelled" }, - ]) + test("a cancelled scan returns to the form with its values and checks the camera again", () => { + const result = replay( + { kind: "add" }, + [field("name", "Remote"), { type: "scan.started" }, { type: "scan.cancelled" }], + withCamera({ kind: "add" }), + ) expect(result.state).toMatchObject({ status: "editing", draft: { name: "Remote" } }) - expect(result.effects).toEqual([]) + expect(result.effects).toEqual([{ type: "camera.probe", attempt: 2, timeoutMs: CAMERA_PROBE_TIMEOUT_MS }]) + }) + + test("a camera check that never answers gives way to the hint", () => { + const start = startServerConnect({ kind: "add" }, "probe") + + expect(start.effects).toEqual([{ type: "camera.probe", attempt: 1, timeoutMs: CAMERA_PROBE_TIMEOUT_MS }]) + expect(selectServerConnectView(start.state, context)).toMatchObject({ + showScan: true, + canScan: false, + cameraHint: undefined, + }) + + const timedOut = transitionServerConnect(start.state, { type: "camera.timed-out", attempt: 1 }) + + expect(timedOut.effects).toEqual([{ type: "camera.timer.stop" }]) + expect(selectServerConnectView(timedOut.state, context)).toMatchObject({ + showScan: false, + canScan: false, + cameraHint: "server.connect.camera.unavailable", + }) + }) + + test("after a cancelled scan, Scan waits for the new camera check and follows its answer", () => { + const cancelled = replay( + { kind: "add" }, + [{ type: "scan.started" }, { type: "scan.cancelled" }], + withCamera({ kind: "add" }), + ) + + expect(selectServerConnectView(cancelled.state, context).canScan).toBe(false) + expect(transitionServerConnect(cancelled.state, { type: "scan.started" }).state).toBe(cancelled.state) + + // The answer of the first check is stale. + expect( + transitionServerConnect(cancelled.state, { type: "camera.settled", attempt: 1, available: true }).state, + ).toBe(cancelled.state) + + const denied = transitionServerConnect(cancelled.state, { type: "camera.settled", attempt: 2, available: false }) + + expect(selectServerConnectView(denied.state, context)).toMatchObject({ + canScan: false, + cameraHint: "server.connect.camera.unavailable", + }) + }) + + test.each([ + { support: "insecure", showScan: false, cameraHint: "server.connect.camera.native" }, + { support: "unavailable", showScan: false, cameraHint: "server.connect.camera.unavailable" }, + { support: "none", showScan: false, cameraHint: undefined }, + ] as const)("a $support camera shows its hint at once, with no check", (input) => { + const start = startServerConnect({ kind: "add" }, input.support) + + expect(start.effects).toEqual([]) + expect(selectServerConnectView(start.state, context)).toMatchObject({ + showScan: input.showScan, + cameraHint: input.cameraHint, + }) + expect(transitionServerConnect(start.state, { type: "scan.started" }).state).toBe(start.state) + }) + + test("closing during a camera check stops its timer and ignores its answer", () => { + const closed = transitionServerConnect(startServerConnect({ kind: "add" }, "probe").state, { type: "disposed" }) + + expect(closed.effects).toEqual([{ type: "camera.timer.stop" }]) + expect(transitionServerConnect(closed.state, { type: "camera.settled", attempt: 1, available: true }).state).toBe( + closed.state, + ) }) test("a result after the dialog unmounts saves nothing", () => { @@ -341,7 +422,7 @@ describe("server connect form", () => { }) test("an edit starts from the server, on a pairing link when it signed out", () => { - const view = (target: ServerConnectTarget) => selectServerConnectView(createServerConnectState(target), context) + const view = (target: ServerConnectTarget) => selectServerConnectView(startServerConnect(target).state, context) expect(view(edit({ displayName: "Remote", password: "secret" })).draft).toEqual({ method: "password", diff --git a/packages/app/src/servers/connect/machine.ts b/packages/app/src/servers/connect/machine.ts index 4e442255be7..eada0c85d03 100644 --- a/packages/app/src/servers/connect/machine.ts +++ b/packages/app/src/servers/connect/machine.ts @@ -9,6 +9,21 @@ import { bareServerAddress, legacyPairingLink, pairingLink, serverAddress } from */ export const SERVER_CONNECT_TIMEOUT_MS = 75_000 +/** A wedged camera daemon can leave `enumerateDevices` pending; past this the scan button gives way to the hint. */ +export const CAMERA_PROBE_TIMEOUT_MS = 3_000 + +/** What the page can tell about the camera before probing: nothing to show off the web, or a probe to run. */ +export type ServerCameraSupport = "none" | "insecure" | "unavailable" | "probe" + +export type ServerCameraState = + /** Not the web app: the native apps pair by pasted link. */ + | { readonly status: "hidden" } + /** A plain-HTTP page cannot open the camera. */ + | { readonly status: "insecure" } + | { readonly status: "probing"; readonly attempt: number } + | { readonly status: "available" } + | { readonly status: "unavailable" } + /** The saved server an edit form started from, as it is now. */ export type ServerOriginal = { readonly url: string @@ -48,6 +63,8 @@ export type ServerSaveAction = type Form = { readonly attempt: number + readonly cameraAttempt: number + readonly camera: ServerCameraState readonly target: ServerConnectTarget readonly draft: ServerConnectDraft } @@ -69,6 +86,8 @@ export type ServerConnectState = export type ServerConnectEvent = | { readonly type: "method.changed"; readonly method: ConnectMethod } | { readonly type: "field.changed"; readonly field: ServerConnectField; readonly value: string } + | { readonly type: "camera.settled"; readonly attempt: number; readonly available: boolean } + | { readonly type: "camera.timed-out"; readonly attempt: number } | { readonly type: "scan.started" } | { readonly type: "scan.cancelled" } | { readonly type: "scan.completed"; readonly link: string } @@ -92,6 +111,9 @@ export type ServerConnectEffect = | { readonly type: "connect.http"; readonly attempt: number; readonly http: ServerConnection.HttpBase } | { readonly type: "timer.start"; readonly attempt: number; readonly timeoutMs: number } | { readonly type: "timer.stop" } + /** Check for a camera, and dispatch `camera.timed-out` after `timeoutMs`. */ + | { readonly type: "camera.probe"; readonly attempt: number; readonly timeoutMs: number } + | { readonly type: "camera.timer.stop" } | { readonly type: "save"; readonly action: ServerSaveAction } | { readonly type: "close"; readonly saved?: ServerConnection.Http } @@ -100,8 +122,19 @@ export type ServerConnectTransition = { readonly effects: readonly ServerConnectEffect[] } -export function createServerConnectState(target: ServerConnectTarget): ServerConnectState { - return { status: "editing", attempt: 0, target, draft: initialDraft(target) } +export function startServerConnect( + target: ServerConnectTarget, + support: ServerCameraSupport = "none", +): ServerConnectTransition { + const base = { status: "editing", attempt: 0, cameraAttempt: 0, target, draft: initialDraft(target) } as const + + if (support === "probe") + return { + state: { ...base, cameraAttempt: 1, camera: { status: "probing", attempt: 1 } }, + effects: [probe(1)], + } + + return { state: { ...base, camera: { status: support === "none" ? "hidden" : support } }, effects: [] } } export function transitionServerConnect(state: ServerConnectState, event: ServerConnectEvent): ServerConnectTransition { @@ -109,13 +142,35 @@ export function transitionServerConnect(state: ServerConnectState, event: Server if (state.status === "closed") return same - if (event.type === "disposed") - return { state: { ...form(state), status: "closed" }, effects: state.status === "submitting" ? [stop] : [] } + if (event.type === "disposed") return close(state, state.status === "submitting" ? [stop] : []) if (event.type === "original.synced") return synced(state, event.original) + if (event.type === "camera.settled" || event.type === "camera.timed-out") { + if (state.camera.status !== "probing" || state.camera.attempt !== event.attempt) return same + const available = event.type === "camera.settled" && event.available + + return { + state: { ...state, camera: { status: available ? "available" : "unavailable" } }, + effects: [{ type: "camera.timer.stop" }], + } + } + if (state.status === "scanning") { - if (event.type === "scan.cancelled") return { state: { ...form(state), status: "editing" }, effects: [] } + // The scanner may have just been denied the camera, so it is checked again before Scan is offered. + if (event.type === "scan.cancelled") { + const cameraAttempt = state.cameraAttempt + 1 + + return { + state: { + ...form(state), + status: "editing", + cameraAttempt, + camera: { status: "probing", attempt: cameraAttempt }, + }, + effects: [probe(cameraAttempt)], + } + } if (event.type === "scan.completed") return submit(state, { ...state.draft, method: "link", link: event.link }) @@ -149,7 +204,11 @@ export function transitionServerConnect(state: ServerConnectState, event: Server return { state: editing(state, { ...state.draft, [event.field]: event.value }), effects: [] } } - if (event.type === "scan.started") return { state: { ...form(state), status: "scanning" }, effects: [] } + if (event.type === "scan.started") { + if (state.camera.status !== "available") return same + + return { state: { ...form(state), status: "scanning" }, effects: [] } + } if (event.type === "submitted") return submit(state, state.draft) @@ -165,11 +224,16 @@ export type ServerConnectErrorKey = | "server.connect.failed" | "dialog.server.add.error" +export type ServerConnectViewKey = + | ServerConnectErrorKey + | "server.connect.camera.unavailable" + | "server.connect.camera.native" + export type ServerConnectErrorContext = { readonly surface: "screen" | "dialog" /** Set on the web app, where an HTTPS page cannot reach a plain-HTTP address. */ readonly pageHref: string | undefined - readonly t: (key: ServerConnectErrorKey) => string + readonly t: (key: ServerConnectViewKey) => string } export function formatServerConnectError(error: ServerConnectError, context: ServerConnectErrorContext) { @@ -187,9 +251,15 @@ export function formatServerConnectError(error: ServerConnectError, context: Ser } export function selectServerConnectView(state: ServerConnectState, context: ServerConnectErrorContext) { - const primary = state.draft.method === "link" ? state.draft.link : state.draft.url + const link = state.draft.method === "link" + const primary = link ? state.draft.link : state.draft.url + const camera = state.camera.status return { + // Shown, disabled, while the camera check runs, so the hint does not flash in first. + showScan: link && (camera === "available" || camera === "probing"), + canScan: state.status === "editing" && link && camera === "available", + cameraHint: link ? cameraHint(camera, context) : undefined, scanning: state.status === "scanning", busy: state.status === "submitting", disabled: state.status !== "editing", @@ -202,8 +272,29 @@ export function selectServerConnectView(state: ServerConnectState, context: Serv export type ServerConnectView = ReturnType +// QR codes carry JSON, not a link, so on a plain-HTTP page the pasted link is the way in. +function cameraHint(camera: ServerCameraState["status"], context: ServerConnectErrorContext) { + if (camera === "insecure") return context.t("server.connect.camera.native") + + if (camera === "unavailable") return context.t("server.connect.camera.unavailable") + + return undefined +} + const stop = { type: "timer.stop" } as const +function probe(attempt: number): ServerConnectEffect { + return { type: "camera.probe", attempt, timeoutMs: CAMERA_PROBE_TIMEOUT_MS } +} + +/** Closes the form, stopping a camera check that is still running. */ +function close(state: Form, effects: readonly ServerConnectEffect[]): ServerConnectTransition { + return { + state: { ...form(state), status: "closed" }, + effects: state.camera.status === "probing" ? [...effects, { type: "camera.timer.stop" }] : effects, + } +} + function initialDraft(target: ServerConnectTarget): ServerConnectDraft { if (target.kind !== "edit") return { @@ -225,11 +316,17 @@ function initialDraft(target: ServerConnectTarget): ServerConnectDraft { } function form(state: Form): Form { - return { attempt: state.attempt, target: state.target, draft: state.draft } + return { + attempt: state.attempt, + cameraAttempt: state.cameraAttempt, + camera: state.camera, + target: state.target, + draft: state.draft, + } } function editing(state: Form, draft: ServerConnectDraft, error?: ServerConnectError): ServerConnectState { - return { status: "editing", attempt: state.attempt, target: state.target, draft, error } + return { ...form(state), status: "editing", draft, error } } // Where the form points: a pasted or scanned pairing link wins, in either field; else the address and password. @@ -245,7 +342,7 @@ function submit(state: Form, draft: ServerConnectDraft): ServerConnectTransition const fallbackUrl = preferredUrl ?? link.urls[0] ?? value return { - state: { status: "submitting", attempt, target: state.target, draft, fallbackUrl }, + state: { ...form(state), status: "submitting", attempt, draft, fallbackUrl }, effects: [{ type: "connect.link", attempt, link: value, preferredUrl, fallbackUrl }, timer], } } @@ -275,12 +372,12 @@ function submit(state: Form, draft: ServerConnectDraft): ServerConnectTransition (draft.name.trim() || undefined) === original.displayName && password === original.password ) - return { state: { ...form(state), draft, status: "closed" }, effects: [{ type: "close" }] } + return close({ ...state, draft }, [{ type: "close" }]) const http = password ? { url, password } : { url } return { - state: { status: "submitting", attempt, target: state.target, draft, fallbackUrl: url }, + state: { ...form(state), status: "submitting", attempt, draft, fallbackUrl: url }, effects: [{ type: "connect.http", attempt, http }, timer], } } @@ -300,10 +397,7 @@ function saved(state: Form, http: ServerConnection.HttpBase): ServerConnectTrans ? { type: "replace", originalUrl: original.url, connection } : { type: "add", connection } - return { - state: { ...form(state), status: "closed" }, - effects: [stop, { type: "save", action }, { type: "close", saved: connection }], - } + return close(state, [stop, { type: "save", action }, { type: "close", saved: connection }]) } function synced( @@ -313,11 +407,7 @@ function synced( if (state.target.kind !== "edit") return { state, effects: [] } // The edited server was removed elsewhere: there is nothing left to save to. - if (!original) - return { - state: { ...form(state), status: "closed" }, - effects: [...(state.status === "submitting" ? [stop] : []), { type: "close" }], - } + if (!original) return close(state, [...(state.status === "submitting" ? [stop] : []), { type: "close" }]) const current = state.target.original diff --git a/packages/app/src/servers/connect/screen.tsx b/packages/app/src/servers/connect/screen.tsx index 45598c4a87c..045209786b6 100644 --- a/packages/app/src/servers/connect/screen.tsx +++ b/packages/app/src/servers/connect/screen.tsx @@ -3,8 +3,6 @@ import { Button } from "@opencode/ui/button" import { TextInput } from "@opencode/ui/text-input" import { Wordmark } from "@opencode/ui/wordmark" import { useLanguage } from "@/runtime/i18n/language" -import { usePlatform } from "@/runtime/platform/platform" -import { cameraHint, createCameraAvailability } from "./camera" import { createServerConnectController } from "./controller" import { ConnectMethodSwitch } from "./method" import "./screen.css" @@ -13,8 +11,6 @@ const PairingScanner = lazy(() => import("./scanner").then((module) => ({ defaul export function ConnectServerScreen(props: { url?: string } = {}) { const language = useLanguage() - const platform = usePlatform() - const camera = createCameraAvailability() // Read once: the screen leaves when the server it signs in to answers, so its address does not change while it shows. const form = createServerConnectController({ surface: "screen", target: { kind: "connect", url: props.url } }) const view = form.view @@ -39,10 +35,7 @@ export function ConnectServerScreen(props: { url?: string } = {}) { {language.t("server.connect.camera.starting")}

}> { - form.dispatch({ type: "scan.cancelled" }) - void camera.refetch() - }} + onCancel={() => form.dispatch({ type: "scan.cancelled" })} onScan={(link) => form.dispatch({ type: "scan.completed", link })} />
@@ -131,21 +124,17 @@ export function ConnectServerScreen(props: { url?: string } = {}) { {language.t(view().busy ? "dialog.server.add.checking" : "server.connect.button")} - - {language.t(cameraHint())}

} + + - + {language.t("server.connect.scan")} +
+ {(hint) =>

{hint()}

}
Promise<(() => void) | undefined>) { - let cleanup: (() => void) | undefined - let timeout: ReturnType | undefined - let run = 0 + let state = createSoundPreviewState() + let timer: ReturnType | undefined - const stop = () => { - run += 1 - cleanup?.() - clearTimeout(timeout) - cleanup = undefined - timeout = undefined + const dispatch = (event: SoundPreviewEvent) => { + const next = transitionSoundPreview(state, event) + state = next.state + next.effects.forEach(run) } - const play = (id: string | undefined) => { - stop() + const run = (effect: SoundPreviewEffect) => { + if (effect.type === "timer.start") { + clearTimeout(timer) + timer = setTimeout( + () => + dispatch( + effect.kind === "debounce" + ? { type: "debounce.elapsed", attempt: effect.attempt } + : { type: "load.timed-out", attempt: effect.attempt }, + ), + effect.delayMs, + ) - if (!id) return - const current = ++run - timeout = setTimeout(() => { - timeout = undefined - void player(id).then((next) => { - if (run === current) { - cleanup = next + return + } - return - } + if (effect.type === "timer.stop") { + clearTimeout(timer) + timer = undefined - next?.() - }) - }, 100) + return + } + + if (effect.type === "audio.load") { + void Promise.try(() => player(effect.id)).then( + (active) => dispatch({ type: "load.succeeded", attempt: effect.attempt, active }), + () => dispatch({ type: "load.failed", attempt: effect.attempt }), + ) + + return + } + + effect.active() } - onCleanup(stop) + onCleanup(() => dispatch({ type: "disposed" })) - return { play, stop } + return { + play: (id: string | undefined) => dispatch({ type: "play.requested", id }), + stop: () => dispatch({ type: "stop.requested" }), + } } diff --git a/packages/app/src/settings/general/sound-preview-machine.test.ts b/packages/app/src/settings/general/sound-preview-machine.test.ts new file mode 100644 index 00000000000..5dd9070037c --- /dev/null +++ b/packages/app/src/settings/general/sound-preview-machine.test.ts @@ -0,0 +1,114 @@ +import { describe, expect, test } from "bun:test" +import { + createSoundPreviewState, + SOUND_PREVIEW_DEBOUNCE_MS, + SOUND_PREVIEW_LOAD_TIMEOUT_MS, + transitionSoundPreview, + type SoundPreviewEffect, + type SoundPreviewEvent, + type SoundPreviewState, +} from "./sound-preview-machine" + +type Stop = string + +function replay(events: readonly SoundPreviewEvent[], from = createSoundPreviewState()) { + return events.reduce<{ state: SoundPreviewState; effects: SoundPreviewEffect[] }>( + (result, event) => { + const next = transitionSoundPreview(result.state, event) + + return { state: next.state, effects: [...result.effects, ...next.effects] } + }, + { state: from, effects: [] }, + ) +} + +const loading = (id: string): SoundPreviewEvent[] => [ + { type: "play.requested", id }, + { type: "debounce.elapsed", attempt: 1 }, +] + +describe("sound preview machine", () => { + test.each([ + { name: "while waiting", events: [{ type: "play.requested", id: "alert-01" }], released: { type: "timer.stop" } }, + { + name: "while playing", + events: [...loading("alert-01"), { type: "load.succeeded", attempt: 1, active: "stop-a" }], + released: { type: "audio.stop", active: "stop-a" }, + }, + ] as const)("a preview asked for after unmount $name does nothing", (input) => { + const disposed = replay([...input.events, { type: "disposed" }]) + + expect(disposed.state).toEqual({ status: "disposed" }) + expect(disposed.effects.at(-1)).toEqual(input.released) + expect(transitionSoundPreview(disposed.state, { type: "play.requested", id: "alert-01" })).toEqual({ + state: disposed.state, + effects: [], + }) + }) + + test("a sound that loads after unmount is stopped as it arrives", () => { + const disposed = replay([...loading("alert-01"), { type: "disposed" }]) + + expect(transitionSoundPreview(disposed.state, { type: "load.succeeded", attempt: 1, active: "stop-a" })).toEqual({ + state: disposed.state, + effects: [{ type: "audio.stop", active: "stop-a" }], + }) + }) + + test.each([{ type: "load.failed", attempt: 1 } as const, { type: "load.timed-out", attempt: 1 } as const])( + "$type settles back to idle", + (event) => { + const result = replay([...loading("alert-01"), event]) + + expect(result.effects).toEqual([ + { type: "timer.start", kind: "debounce", attempt: 1, delayMs: SOUND_PREVIEW_DEBOUNCE_MS }, + { type: "audio.load", attempt: 1, id: "alert-01" }, + { type: "timer.start", kind: "load", attempt: 1, delayMs: SOUND_PREVIEW_LOAD_TIMEOUT_MS }, + { type: "timer.stop" }, + ]) + expect(result.state).toEqual({ status: "idle", attempt: 1 }) + + // A load that timed out and answers late plays nothing. + expect(transitionSoundPreview(result.state, { type: "load.succeeded", attempt: 1, active: "stop-a" })).toEqual({ + state: result.state, + effects: [{ type: "audio.stop", active: "stop-a" }], + }) + }, + ) + + test("a new preview stops the one playing and waits again", () => { + const playing = replay([...loading("alert-01"), { type: "load.succeeded", attempt: 1, active: "stop-a" }]) + + expect(transitionSoundPreview(playing.state, { type: "play.requested", id: "alert-02" }).effects).toEqual([ + { type: "audio.stop", active: "stop-a" }, + { type: "timer.start", kind: "debounce", attempt: 2, delayMs: SOUND_PREVIEW_DEBOUNCE_MS }, + ]) + }) + + test("a load superseded by another preview is stopped without touching the new one", () => { + const superseded = replay([...loading("alert-01"), { type: "play.requested", id: "alert-02" }]) + const late = transitionSoundPreview(superseded.state, { type: "load.succeeded", attempt: 1, active: "stop-a" }) + + expect(late).toEqual({ state: superseded.state, effects: [{ type: "audio.stop", active: "stop-a" }] }) + expect(late.state).toEqual({ status: "debouncing", attempt: 2, id: "alert-02" }) + }) + + test("only the last of several quick previews loads", () => { + const result = replay([ + { type: "play.requested", id: "alert-01" }, + { type: "play.requested", id: "alert-02" }, + { type: "debounce.elapsed", attempt: 1 }, + { type: "debounce.elapsed", attempt: 2 }, + ]) + + expect(result.effects.filter((effect) => effect.type === "audio.load")).toEqual([ + { type: "audio.load", attempt: 2, id: "alert-02" }, + ]) + }) + + test("stopping an idle preview changes nothing", () => { + const state = createSoundPreviewState() + + expect(transitionSoundPreview(state, { type: "stop.requested" })).toEqual({ state, effects: [] }) + }) +}) diff --git a/packages/app/src/settings/general/sound-preview-machine.ts b/packages/app/src/settings/general/sound-preview-machine.ts new file mode 100644 index 00000000000..601cd105b98 --- /dev/null +++ b/packages/app/src/settings/general/sound-preview-machine.ts @@ -0,0 +1,109 @@ +/** Moving through the sound list plays only the sound it settles on. */ +export const SOUND_PREVIEW_DEBOUNCE_MS = 100 + +/** A sound file that never loads gives up rather than playing long after the user moved on. */ +export const SOUND_PREVIEW_LOAD_TIMEOUT_MS = 5_000 + +export type SoundPreviewState void> = + | { readonly status: "idle"; readonly attempt: number } + | { readonly status: "debouncing"; readonly attempt: number; readonly id: string } + | { readonly status: "loading"; readonly attempt: number; readonly id: string } + | { readonly status: "playing"; readonly attempt: number; readonly id: string; readonly active: Stop } + | { readonly status: "disposed" } + +export type SoundPreviewEvent void> = + | { readonly type: "play.requested"; readonly id: string | undefined } + | { readonly type: "stop.requested" } + | { readonly type: "debounce.elapsed"; readonly attempt: number } + /** `active` stops the sound; none when nothing played. */ + | { readonly type: "load.succeeded"; readonly attempt: number; readonly active: Stop | undefined } + | { readonly type: "load.failed"; readonly attempt: number } + | { readonly type: "load.timed-out"; readonly attempt: number } + | { readonly type: "disposed" } + +export type SoundPreviewEffect void> = + /** Replaces any running timer; dispatches `debounce.elapsed` or `load.timed-out` with `attempt`. */ + | { + readonly type: "timer.start" + readonly kind: "debounce" | "load" + readonly attempt: number + readonly delayMs: number + } + | { readonly type: "timer.stop" } + | { readonly type: "audio.load"; readonly attempt: number; readonly id: string } + | { readonly type: "audio.stop"; readonly active: Stop } + +export type SoundPreviewTransition void> = { + readonly state: SoundPreviewState + readonly effects: readonly SoundPreviewEffect[] +} + +export function createSoundPreviewState void>(): SoundPreviewState { + return { status: "idle", attempt: 0 } +} + +export function transitionSoundPreview( + state: SoundPreviewState, + event: SoundPreviewEvent, +): SoundPreviewTransition { + // A sound that loads after it was superseded, stopped or unmounted is stopped as it arrives. + if (event.type === "load.succeeded" && (state.status !== "loading" || state.attempt !== event.attempt)) + return { state, effects: event.active === undefined ? [] : [{ type: "audio.stop", active: event.active }] } + + if (state.status === "disposed") return { state, effects: [] } + + if (event.type === "disposed") return { state: { status: "disposed" }, effects: release(state) } + + if (event.type === "play.requested" || event.type === "stop.requested") { + const id = event.type === "play.requested" ? event.id : undefined + + if (!id) { + if (state.status === "idle") return { state, effects: [] } + + return { state: { status: "idle", attempt: state.attempt + 1 }, effects: release(state) } + } + + const attempt = state.attempt + 1 + + return { + state: { status: "debouncing", attempt, id }, + effects: [ + ...(state.status === "playing" ? release(state) : []), + { type: "timer.start", kind: "debounce", attempt, delayMs: SOUND_PREVIEW_DEBOUNCE_MS }, + ], + } + } + + if (event.type === "debounce.elapsed") { + if (state.status !== "debouncing" || state.attempt !== event.attempt) return { state, effects: [] } + + return { + state: { status: "loading", attempt: state.attempt, id: state.id }, + effects: [ + { type: "audio.load", attempt: state.attempt, id: state.id }, + { type: "timer.start", kind: "load", attempt: state.attempt, delayMs: SOUND_PREVIEW_LOAD_TIMEOUT_MS }, + ], + } + } + + if (state.status !== "loading" || state.attempt !== event.attempt) return { state, effects: [] } + + if (event.type === "load.succeeded" && event.active !== undefined) + return { + state: { status: "playing", attempt: state.attempt, id: state.id, active: event.active }, + effects: [STOP], + } + + return { state: { status: "idle", attempt: state.attempt }, effects: [STOP] } +} + +const STOP = { type: "timer.stop" } as const + +/** What leaving `state` must stop: its timer or its sound. */ +function release(state: SoundPreviewState): SoundPreviewEffect[] { + if (state.status === "debouncing" || state.status === "loading") return [STOP] + + if (state.status === "playing") return [{ type: "audio.stop", active: state.active }] + + return [] +}