From 3ca0739383061ab2c1a0280bc427af434c66a5c2 Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:34:59 -0600 Subject: [PATCH 001/200] fix(app): keep the activity pill clear of Working on touch (#61794) --- .../e2e/regression/timeline-geometry.spec.ts | 49 ++++++++++++++++--- .../src/session/composer/composer-lane.css | 1 + .../app/src/session/timeline/virtualizer.tsx | 17 ++++--- 3 files changed, 52 insertions(+), 15 deletions(-) diff --git a/packages/app/e2e/regression/timeline-geometry.spec.ts b/packages/app/e2e/regression/timeline-geometry.spec.ts index e1d41a7cf6c0..a2a54cf30066 100644 --- a/packages/app/e2e/regression/timeline-geometry.spec.ts +++ b/packages/app/e2e/regression/timeline-geometry.spec.ts @@ -633,10 +633,28 @@ async function captureCardEdges(page: Page, card: Locator) { ) } -test("scrolls the timeline behind the composer region, fading at the card, and keeps its end above the region", async ({ - page, -}) => { +// Without hover the activity pill grows to its 44px touch size, and the tail it floats in grows with it. +for (const input of [ + { name: "a pointer", touch: false, viewport: { width: 1400, height: 900 }, pill: 32 }, + { name: "touch", touch: true, viewport: { width: 390, height: 844 }, pill: 44 }, +]) { + test.describe(`with ${input.name}`, () => { + test.use({ hasTouch: input.touch, isMobile: input.touch }) + + test("scrolls the timeline behind the composer region, fading at the card, and keeps its end above the region", async ({ + page, + }) => { + await scrollsBehindComposerRegion(page, input) + }) + }) +} + +async function scrollsBehindComposerRegion( + page: Page, + input: { viewport: { width: number; height: number }; pill: number }, +) { await setupTimeline(page, { + viewport: input.viewport, sessionMessages: [ ...validateTimelineMessages(historyMessages(18)), { id: "msg_9000_user", type: "user", text: "Split the work.", time: { created: 1 } }, @@ -681,7 +699,10 @@ test("scrolls the timeline behind the composer region, fading at the card, and k const dock = region.getBoundingClientRect() const card = region.querySelector('[data-component="composer"]')!.getBoundingClientRect() const pill = region.querySelector('[data-slot="session-activity-chip"]')!.getBoundingClientRect() - const hint = viewport.querySelector('[data-component="session-background-hint-row"]')!.getBoundingClientRect() + const row = viewport.querySelector('[data-component="session-background-hint-row"]')! + const hint = row.getBoundingClientRect() + // The live status lane that holds Working and the background hint. + const lane = row.parentElement!.getBoundingClientRect() const parts = [...viewport.querySelectorAll("[data-timeline-part-id]")] const last = parts.find((element) => element.textContent?.includes("The last answer ends"))! @@ -695,13 +716,25 @@ test("scrolls the timeline behind the composer region, fading at the card, and k ), // The pill floats above the region out of flow, so it never changes the inset the timeline scrolls above. floats: pill.bottom <= dock.top, - // It floats in the timeline's reserved tail, below the background hint and the last answer. - reserved: hint.bottom <= pill.top && last.getBoundingClientRect().bottom <= hint.top, + pill: Math.round(pill.height), + // It floats in the timeline's reserved tail, a clear gap below the live status lane and the last answer. + clearance: Math.round(pill.top - lane.bottom), + reserved: lane.top <= hint.top && last.getBoundingClientRect().bottom <= hint.top, atEnd: viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop <= 1, } }) - const expected = { behind: 0, inset: 0, fade: 0, floats: true, reserved: true, atEnd: true } + const expected = { + behind: 0, + inset: 0, + fade: 0, + floats: true, + pill: input.pill, + clearance: 14, + reserved: true, + atEnd: true, + } + await expect.poll(geometry).toEqual(expected) const before = (await dock.boundingBox())!.height @@ -715,7 +748,7 @@ test("scrolls the timeline behind the composer region, fading at the card, and k await expect.poll(async () => (await dock.boundingBox())!.height).toBeGreaterThan(before + 40) await expect.poll(geometry).toEqual(expected) -}) +} test("groups consecutive sent prompts under the last one's meta line, with each bubble's actions beside it", async ({ page, diff --git a/packages/app/src/session/composer/composer-lane.css b/packages/app/src/session/composer/composer-lane.css index 43e5c5c163a8..64dfc1463c9b 100644 --- a/packages/app/src/session/composer/composer-lane.css +++ b/packages/app/src/session/composer/composer-lane.css @@ -53,6 +53,7 @@ } } + /* The timeline's tail reserves this height (tailSize in timeline/virtualizer.tsx); change both together. */ @media (hover: none) { min-height: 44px; } diff --git a/packages/app/src/session/timeline/virtualizer.tsx b/packages/app/src/session/timeline/virtualizer.tsx index 1eaedf02ae33..8949cfc26a43 100644 --- a/packages/app/src/session/timeline/virtualizer.tsx +++ b/packages/app/src/session/timeline/virtualizer.tsx @@ -35,10 +35,6 @@ import { defersAdjustments, END_EPSILON, MIN_OVERFLOW, needsEndProbe, ZOOM_SLACK const fallbackItemSize = 60 -// Reserved below the last row: a 36px lane for the live status row and its background hint, a 14px gap, then a 32px -// activity pill and its 10px composer gap. Both come and go inside it, so neither moves the rows above. -const tailSize = 92 - const pendingMarkdown = '[data-component="markdown"]:not([data-markdown-ready])' const upwardKeys = new Set(["up", "page-up", "home"]) @@ -116,6 +112,11 @@ export function createTimelineVirtualizer(input: Input) { const active = () => input.active?.() !== false const isDesktop = createMediaQuery("(min-width: 768px)") const topOffset = () => (input.showHeader() ? 64 : isDesktop() ? 0 : 16) + // Reserved below the last row: a 36px lane for the live status row and its background hint, a 14px gap, then the + // activity pill and its 10px composer gap. Without hover the pill grows from 32px to its 44px touch size + // (composer-lane.css), and the tail grows with it. Both come and go inside it, so neither moves the rows above. + const touch = createMediaQuery("(hover: none)") + const tailSize = () => (touch() ? 104 : 92) const ownerSessionKey = input.sessionKey() const entry = cache.get(ownerSessionKey) const cached = entry?.presentationKey === input.presentationKey?.() ? entry : undefined @@ -415,7 +416,9 @@ export function createTimelineVirtualizer(input: Input) { // Empty projections still need the bottom spacer for running status. return rows().length > 0 ? topOffset() : 0 }, - paddingEnd: tailSize, + get paddingEnd() { + return tailSize() + }, // Revealed prompts sit below the solid header and its 16px fade. get scrollPaddingStart() { return input.showHeader() ? headerHeight() + 16 : 0 @@ -1190,8 +1193,8 @@ export function createTimelineVirtualizer(input: Input) { data-timeline-row="bottom-spacer" class="absolute top-0 left-0 w-full" style={{ - height: `${tailSize}px`, - transform: `translateY(${virtualizer.getTotalSize() - tailSize - rendering.scrollAdjustment}px)`, + height: `${tailSize()}px`, + transform: `translateY(${virtualizer.getTotalSize() - tailSize() - rendering.scrollAdjustment}px)`, }} > {props.bottomSpacer} From e0300a9bfc849b2cf06b6507982977e86993a302 Mon Sep 17 00:00:00 2001 From: yangguan-xue Date: Thu, 5 Nov 2026 05:46:18 +0800 Subject: [PATCH 002/200] fix(core): stop repeated zsh q flags from freezing the shell scanner (#60791) Co-authored-by: yangguan-xue <184704694+yangguan-xue@users.noreply.github.com> Co-authored-by: Daniel Smolsky --- packages/core/src/shell/scan.ts | 2 +- packages/core/test/shell-scan/adversarial.test.ts | 7 +++++++ 2 files changed, 8 insertions(+), 1 deletion(-) diff --git a/packages/core/src/shell/scan.ts b/packages/core/src/shell/scan.ts index b6537ffdb48e..828ad20ff455 100644 --- a/packages/core/src/shell/scan.ts +++ b/packages/core/src/shell/scan.ts @@ -114,7 +114,7 @@ const FUNCTION_BODY_RE = const DO_AHEAD_RE = /(?:[ \t\n;]|\\\n|#[^\n]*(?:\n|$))*(?:do(?=(?:\\\n)*(?:[ \t\n;{(]|$))|\{(?=(?:\\\n)*[ \t\n]))/y const NOFORK_OPEN_RE = /\$\{(?:\\\n)*(?:[ \t\n]|\|)/y // Zsh flags that neither evaluate nor glob a value; s and j take an argument between repeated delimiters. -const ZSH_SAFE_FLAGS_RE = /\$\{\((?:[@AaBbCcDEfFikLMmNnOopPqStUuVvWwXZz0-]|q[-+]?|[js]([^({[<\\])(?:(?!\1)[^)])*\1)*\)/y +const ZSH_SAFE_FLAGS_RE = /\$\{\((?:[@AaBbCcDEfFikLMmNnOopPqStUuVvWwXZz0-]|q[+]|[js]([^({[<\\])(?:(?!\1)[^)])*\1)*\)/y const ZSH_QUOTED_FLAG_ARG_RE = /[js]([^({[<\\])(?:(?!\1)[^)])*\1/g const ZSH_GLOB_MODIFIER_RE = /(?:[\^=~#+]|\\\n)*~/y // Trailing Zsh glob qualifiers without code execution (e, +cmd), delimiters (f, u, g, P), modifiers (:), or math expressions. diff --git a/packages/core/test/shell-scan/adversarial.test.ts b/packages/core/test/shell-scan/adversarial.test.ts index a65a08f6114f..4a64505a4586 100644 --- a/packages/core/test/shell-scan/adversarial.test.ts +++ b/packages/core/test/shell-scan/adversarial.test.ts @@ -77,6 +77,13 @@ describe("ShellScan adversarial corpus", () => { expect(performance.now() - start).toBeLessThan(500) }) + test("scans repeated zsh q flags in bounded time", () => { + const start = performance.now() + ShellScan.scan("echo ${(" + "q".repeat(40) + "!x}", "zsh") + ShellScan.scan("echo ${(" + "q-".repeat(40) + "!x}", "zsh") + expect(performance.now() - start).toBeLessThan(500) + }) + test.each([ ['pwsh --command "Remove-Item victim.txt"', ["pwsh"]], ["Import-Module ./evil.psm1", ["Import-Module"]], From 65f646f8d768375c732c9e56715dbcbfb9151b29 Mon Sep 17 00:00:00 2001 From: Wish Date: Thu, 5 Nov 2026 03:21:07 +0530 Subject: [PATCH 003/200] fix(tui): stop session titles with newlines from crashing the TUI (#57523) Co-authored-by: Daniel Smolsky --- packages/tui/src/util/renderer.ts | 2 +- packages/tui/test/util/renderer.test.ts | 6 ++++++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/packages/tui/src/util/renderer.ts b/packages/tui/src/util/renderer.ts index 88296e44ed99..910f4f30e158 100644 --- a/packages/tui/src/util/renderer.ts +++ b/packages/tui/src/util/renderer.ts @@ -5,7 +5,7 @@ type TitleRenderer = Pick) { diff --git a/packages/tui/test/util/renderer.test.ts b/packages/tui/test/util/renderer.test.ts index f5b260a46aa9..b60573e811c3 100644 --- a/packages/tui/test/util/renderer.test.ts +++ b/packages/tui/test/util/renderer.test.ts @@ -3,6 +3,12 @@ import { RendererControlState } from "@opentui/core" import { createTestRenderer } from "@opentui/core/testing" import { destroyRenderer, setTerminalTitle } from "../../src/util/renderer" +test("sets a title that contains control characters", async () => { + await using setup = await createTestRenderer({ width: 10, height: 2 }) + await setup.renderer.setupTerminal() + expect(() => setTerminalTitle(setup.renderer, "Fix parser bug\nin tokenizer")).not.toThrow() +}) + test("clears the terminal title before destroying the renderer", () => { const calls: string[] = [] destroyRenderer({ From 4cb790123c32cb1376f760cff24d21968db5390f Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:56:00 -0600 Subject: [PATCH 004/200] fix(app): keep timeline Find on one fenced seek (#61727) --- packages/app/perf/README.md | 2 +- packages/app/perf/stream.bench.ts | 24 +- .../app/src/session/timeline/search-bar.tsx | 4 +- .../src/session/timeline/search-controller.ts | 310 ++++++++-------- .../session/timeline/search-machine.test.ts | 320 ++++++++++++++++ .../src/session/timeline/search-machine.ts | 342 ++++++++++++++++++ 6 files changed, 847 insertions(+), 155 deletions(-) create mode 100644 packages/app/src/session/timeline/search-machine.test.ts create mode 100644 packages/app/src/session/timeline/search-machine.ts diff --git a/packages/app/perf/README.md b/packages/app/perf/README.md index 6dd23c2beec4..dd934c10cad3 100644 --- a/packages/app/perf/README.md +++ b/packages/app/perf/README.md @@ -8,7 +8,7 @@ build on the e2e mock server, so they need no backend. | File | Cases | Workload | | --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------ | | `timeline.bench.ts` | scroll history · type in composer · find in session · expand an edit · drag the review's edge | A 120-turn session of markdown, code, tools and diffs. | -| `stream.bench.ts` | stream a reply · into a tool-heavy history · with review open · wait on a running session | 160 markdown deltas at 40 a second from a server that never waits. | +| `stream.bench.ts` | stream a reply · into a tool-heavy history · with review open · with Find open · wait on a running session | 160 markdown deltas at 40 a second from a server that never waits. | | `tabs.bench.ts` | switch tab (warm, review open, after a resize, 1,200 models) · away and back with review open · open an unvisited tab (± review) | Two tabs of 200 long markdown exchanges each, loaded in full. | | `navigation.bench.ts` | Home → session · close the last tab · new session (Home, titlebar) · new session page in and out · child session · restore 8 tabs · activate a restored tab · command palette (session, Home) | The stress fixture, paginated, from a fresh document every run. | | `home.bench.ts` | load home · update a session in the background | 500, 5,000 and 10,000 root sessions across 12 folders. | diff --git a/packages/app/perf/stream.bench.ts b/packages/app/perf/stream.bench.ts index 334b124a4bee..d63f38439804 100644 --- a/packages/app/perf/stream.bench.ts +++ b/packages/app/perf/stream.bench.ts @@ -1,6 +1,6 @@ // A reply streaming into a long session: 160 markdown deltas (bold text, tables, code fences) at 40 a second, from a // server that never waits for the renderer. Per-delta cost that grows with the reply or the history shows up here. -import { bench, web, type Case } from "@hona/strobe" +import { bench, web, type Case, type Page } from "@hona/strobe" import { reviewDiffs } from "./fixtures/diffs" import { cached } from "./fixtures/mock" import { openReview } from "./fixtures/review" @@ -8,6 +8,22 @@ import { mockTimelineSession, reply, streamedReply, timeline } from "./fixtures/ const { start, deltas } = streamedReply(160) +const withFind = "stream with Find open" + +const find = '[data-component="timeline-search-bar"] input' + +// A phrase only the reply's last delta holds, so Find stays on the reply while every delta rescans the transcript. +// One input event: typed key by key, its prefixes would match the history and seek the timeline away from the reply. +async function openFind(page: Page) { + await page.press("ControlOrMeta+f", { until: find }) + await page.eval(() => { + const input = document.querySelector('[data-component="timeline-search-bar"] input')! + input.value = "benchmark-complete" + input.dispatchEvent(new InputEvent("input", { bubbles: true })) + }) + await page.waitFor('[data-slot="timeline-search-count"]', { text: "0/0" }) +} + const stream: Case<{}> = { primary: "main.work", metrics: ["frames.interval.p95", "frames.dropped.pct", "main.script", "main.layout", "main.style"], @@ -23,6 +39,8 @@ const stream: Case<{}> = { await page.goto(prepared.path, { until: timeline, timeout: 60_000 }) if (name === "stream with review open") await openReview(page) + + if (name === withFind) await openFind(page) await page.idle() }, } @@ -49,6 +67,8 @@ export default bench({ if (name === "stream with review open") await openReview(page) + if (name === withFind) await openFind(page) + // Its animations never stop, and with the attribution probes on a slow machine their frames can run long enough // that the page never counts as idle. if (name === "wait on a running session") return page.wait(2000) @@ -64,6 +84,8 @@ export default bench({ "stream into a tool-heavy history": stream, // The review pane open beside the timeline on 72 changed files. "stream with review open": stream, + // Find open on a phrase that only the last delta holds: each delta rescans the 120-turn transcript for it. + [withFind]: stream, // Five seconds of a running session between deltas: the tab's spinner and the Working shimmer animate, and nothing // else changes. Animation the compositor runs costs the page's main thread nothing. "wait on a running session": { diff --git a/packages/app/src/session/timeline/search-bar.tsx b/packages/app/src/session/timeline/search-bar.tsx index a8f6e5eab891..f2dea7640ba2 100644 --- a/packages/app/src/session/timeline/search-bar.tsx +++ b/packages/app/src/session/timeline/search-bar.tsx @@ -56,12 +56,12 @@ export function TimelineSearchBar(props: { controller: TimelineSearchController }} /> - + - {c.result.count() > 0 ? c.result.activeIndex() + 1 : 0}/{c.result.count()} + {c.result.activeDisplay()}/{c.result.count()} + + + ) +} + /** Mermaid sources render through the same fenced-block pipeline the timeline uses. */ function ArtifactMermaid(props: { text: string; cacheKey?: string }) { const [view, setView] = createStore({ zoom: 1, width: 0 }) diff --git a/packages/gui-plugins/src/file/artifact.test.ts b/packages/gui-plugins/src/file/artifact.test.ts index bf3d70804a30..1e2e74ab3807 100644 --- a/packages/gui-plugins/src/file/artifact.test.ts +++ b/packages/gui-plugins/src/file/artifact.test.ts @@ -1,5 +1,5 @@ import { describe, expect, test } from "bun:test" -import { bytesFromContent, contentBytes, parseDelimited, resolveArtifactPath } from "./artifact" +import { bytesFromContent, contentBytes, parseDelimited, resolveArtifactPath, splitFrontmatter } from "./artifact" describe("binary content helpers", () => { test("reads size and independent byte copies from raw bytes", () => { @@ -57,3 +57,106 @@ describe("resolveArtifactPath", () => { expect(resolveArtifactPath(base, href)).toBeUndefined() }) }) + +describe("splitFrontmatter", () => { + const release = [{ key: "description", value: "Release", code: false }] + const primary = [{ key: "mode", value: "primary", code: false }] + + test.each([ + ["LF frontmatter and body", "---\ndescription: Release\n---\n# Title", { properties: release, body: "# Title" }], + [ + "CRLF and UTF-8 BOM", + "\uFEFF---\r\ndescription: Release\r\n---\r\n# Title\r\n", + { properties: release, body: "# Title\r\n" }, + ], + ["frontmatter at EOF", "---\nmode: primary\n---", { properties: primary, body: "" }], + ["frontmatter with trailing blank lines only", "---\nmode: primary\n---\n\n", { properties: primary, body: "\n" }], + [ + "empty frontmatter before a later thematic break", + "---\n---\n\nBody\n\n---\n\nFooter", + { body: "\nBody\n\n---\n\nFooter" }, + ], + ["whitespace-only frontmatter", "---\n \n---\n# Title", { body: "# Title" }], + ])("splits %s", (_, input, expected) => { + expect(splitFrontmatter(input)).toEqual(expected) + }) + + test("reads scalars, block scalars, and nested values", () => { + const yaml = [ + "# reviewer agent", + 'description: "Reviews code"', + "tools:", + " write: false", + " bash: false", + "skills:", + "- review", + "prompt: |", + " Line one", + "", + " Line two", + "summary: >", + " Folded", + " text", + "note: first", + " second", + "empty:", + "", + ].join("\n") + + expect(splitFrontmatter(`---\n${yaml}\n---\nBody`).properties).toEqual([ + { key: "description", value: "Reviews code", code: false }, + { key: "tools", value: "write: false\nbash: false", code: true }, + { key: "skills", value: "- review", code: true }, + { key: "prompt", value: "Line one\n\nLine two", code: false }, + { key: "summary", value: "Folded text", code: false }, + { key: "note", value: "first second", code: false }, + { key: "empty", value: "", code: false }, + ]) + }) + + test.each([ + ["a line that is not a key", "---\njust text\n---\n# Title", { body: "```yaml\njust text\n```\n\n# Title" }], + ["a top-level list", "---\n- one\n- two\n---", { body: "```yaml\n- one\n- two\n```" }], + [ + "backticks in unreadable frontmatter", + "---\n- ```ts\n---\n# Title", + { body: "````yaml\n- ```ts\n````\n\n# Title" }, + ], + ])("keeps %s as a YAML block", (_, input, expected) => { + expect(splitFrontmatter(input)).toEqual(expected) + }) + + test.each([ + ["a trailing comment", "temperature: 0.2 # lower"], + ["a comment in a plain multi-line value", "note: first\n second # more"], + ["a comment after a block scalar indicator", "prompt: | # keep\n Line"], + ["an escaped double-quoted value", 'title: "a \\"b\\""'], + ["an escaped single-quoted value", "title: 'it''s'"], + ["a quoted value that wraps", 'description: "foo\n bar"'], + ["a quoted value followed by a comment", 'title: "a" # note'], + ])("keeps %s as a YAML block", (_, yaml) => { + expect(splitFrontmatter(`---\n${yaml}\n---\nBody`)).toEqual({ body: `\`\`\`yaml\n${yaml}\n\`\`\`\n\nBody` }) + }) + + test("reads hashes that are not comments", () => { + const yaml = ['title: "a # b"', "tag: C#", "summary: >", " # not a comment", "prompt: |", " # heading"].join("\n") + + expect(splitFrontmatter(`---\n${yaml}\n---\nBody`).properties).toEqual([ + { key: "title", value: "a # b", code: false }, + { key: "tag", value: "C#", code: false }, + { key: "summary", value: "# not a comment", code: false }, + { key: "prompt", value: "# heading", code: false }, + ]) + }) + + test.each([ + ["plain markdown", "# Title\n\n---\n\nSection"], + ["unclosed opening delimiter", "---\ndescription: Release\n# Title"], + ["four-dash thematic break on line 1", "----\ndescription: Release\n---\n# Title"], + ["four-dash line instead of closing delimiter", "---\ndescription: Release\n----\n# Title"], + ["leading blank line before delimiter", "\n---\ndescription: Release\n---\n# Title"], + ["delimiter after prose", "Intro\n---\ndescription: Release\n---\n# Title"], + ])("leaves %s untouched", (_, input) => { + expect(splitFrontmatter(input)).toEqual({ body: input }) + }) +}) diff --git a/packages/gui-plugins/src/file/artifact.ts b/packages/gui-plugins/src/file/artifact.ts index 022cc0a6fd35..be3f1439be2d 100644 --- a/packages/gui-plugins/src/file/artifact.ts +++ b/packages/gui-plugins/src/file/artifact.ts @@ -141,3 +141,85 @@ export function resolveArtifactPath(base: string, href: string) { return `${dir.startsWith("/") ? "/" : ""}${segments.join("/")}` } + +const frontmatter = /^\uFEFF?---[ \t]*\r?\n(?:([\s\S]*?)\r?\n)??---[ \t]*(?:\r?\n|$)/ + +/** + * Split a leading YAML frontmatter block from Markdown so preview does not render its closing `---` + * as a setext heading. Top-level `key: value` entries come back as properties; frontmatter this + * reader cannot split stays in the body as a fenced `yaml` code block. Empty frontmatter is dropped. + */ +export function splitFrontmatter(text: string) { + const match = frontmatter.exec(text) + + if (!match) return { body: text } + const body = text.slice(match[0].length) + const yaml = (match[1] ?? "").replace(/\r\n?/g, "\n") + + if (!yaml.trim()) return { body } + const properties = readProperties(yaml) + + if (properties) return { properties, body } + const longest = Array.from(yaml.matchAll(/`+/g)).reduce((max, run) => Math.max(max, run[0].length), 0) + const fence = "`".repeat(Math.max(3, longest + 1)) + const block = `${fence}yaml\n${yaml}\n${fence}` + + return { body: body.trim() ? `${block}\n\n${body}` : block } +} + +/** One top-level frontmatter entry. `code` marks a nested map or list, shown as its YAML source. */ +export type FrontmatterProperty = { key: string; value: string; code: boolean } + +function readProperties(yaml: string) { + const lines = yaml.split("\n").filter((line) => !line.startsWith("#")) + // A top-level key starts at column 0; a column-0 "- " item belongs to the key above it. + const starts = lines.flatMap((line, index) => (/^[^\s-]|^-[^\s]/.test(line) ? [index] : [])) + + if (starts.length === 0 || lines.slice(0, starts[0]).some((line) => line.trim())) return + const properties = starts.map((start, index) => readProperty(lines[start], lines.slice(start + 1, starts[index + 1]))) + + if (!properties.every((property) => property !== undefined)) return + + return properties +} + +// A `#` at the start or after whitespace begins a YAML comment in a plain scalar. +const comment = /(?:^|\s)#/ + +function readProperty(head: string, rest: string[]): FrontmatterProperty | undefined { + const match = /^([^\s:][^:]*?):(?:[ \t]+(.*))?$/.exec(head) + + if (!match) return + const key = match[1] + const value = (match[2] ?? "").trim() + const block = rest.slice(0, rest.findLastIndex((line) => line.trim()) + 1) + + // Only quoted values that close on this line without escapes are read; others fall back to the YAML block. + if (/^["']/.test(value)) { + const quoted = /^"([^"\\]*)"$|^'([^']*)'$/.exec(value) + + if (!quoted || block.length > 0) return + + return { key, value: quoted[1] ?? quoted[2], code: false } + } + + if (comment.test(value)) return + + if (block.length === 0) return { key, value, code: false } + const indent = Math.min(...block.flatMap((line) => (line.trim() ? [line.length - line.trimStart().length] : []))) + const lines = block.map((line) => line.slice(indent)) + + if (/^\|[+-]?\d?$/.test(value)) return { key, value: lines.join("\n"), code: false } + + // Folded (`>`) and plain multi-line scalars read as one line. + if (value) { + const folded = /^>[+-]?\d?$/.test(value) + + if (!folded && lines.some((line) => comment.test(line))) return + const words = [folded ? "" : value, ...lines.map((line) => line.trim())] + + return { key, value: words.filter(Boolean).join(" "), code: false } + } + + return { key, value: lines.join("\n"), code: true } +} diff --git a/packages/gui-plugins/src/file/i18n/en.ts b/packages/gui-plugins/src/file/i18n/en.ts index 67378a94ad5c..2019a326fa47 100644 --- a/packages/gui-plugins/src/file/i18n/en.ts +++ b/packages/gui-plugins/src/file/i18n/en.ts @@ -24,6 +24,8 @@ export default { "view.table.copyCell": "Copy cell", "view.table.copyFailed": "Couldn't copy this cell.", "view.fontSample": "Sphinx of black quartz, judge my vow.", + "view.properties": "Properties", + "view.properties.showAll": "Show all {{count}} properties", "open.in": "Open in", "open.ariaLabel": "Open in {{app}}", "open.menu": "Open options", From 134d1b411c163cd29ade160f1416c02c0b444f07 Mon Sep 17 00:00:00 2001 From: Aiden Cline <63023139+rekram1-node@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:17:55 -0600 Subject: [PATCH 019/200] fix(app): read timeline follow state on composer submit (#61822) --- packages/app/src/session/composer/region.tsx | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx index 90b8dd5d11bb..33a0a9d29dc7 100644 --- a/packages/app/src/session/composer/region.tsx +++ b/packages/app/src/session/composer/region.tsx @@ -332,10 +332,11 @@ export function createActiveSessionRegion(input: { state, parentID: input.session.data.parentID, centered: input.screen.centered, - // Submitting keeps following only when already following. A reader scrolled up stays where they are; the - // jump-to-latest button takes them down. + // Submitting reads past the automatic unread marker. Keep a reader's own scroll or revealed tool in place. onResponseSubmit: () => { - if (input.timeline.view.pinned()) input.timeline.actions.resume() + const anchor = input.timeline.follow.anchor() + + if (input.timeline.follow.following() || (anchor && !anchor.partID)) input.timeline.actions.resume() }, openParent, focusPrompt: () => focusPrompt(), From a0c6df8fdedbb09eac46594c54298846a3b27bc0 Mon Sep 17 00:00:00 2001 From: Filip <34747899+neriousy@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:28:39 +0100 Subject: [PATCH 020/200] fix(core): start background compaction a fixed lead before the threshold (#60049) --- packages/core/src/session/compaction.ts | 67 ++++++--- packages/core/test/session-compaction.test.ts | 134 ++++++++++++++++-- services/www/src/docs/content/compaction.mdx | 16 ++- 3 files changed, 181 insertions(+), 36 deletions(-) diff --git a/packages/core/src/session/compaction.ts b/packages/core/src/session/compaction.ts index 41ccb1bd0878..6751a7de6afd 100644 --- a/packages/core/src/session/compaction.ts +++ b/packages/core/src/session/compaction.ts @@ -18,7 +18,7 @@ import type { StreamOptions } from "@opencode/ai/route" import type { SessionCompactionResult } from "@opencode/plugin/effect/session" import type { SessionError } from "@opencode/schema/session-error" import { makeLocationNode } from "@opencode/util/effect/app-node" -import { Context, Effect, Exit, Fiber, Layer, Result, Scope, Stream } from "effect" +import { Clock, Context, DateTime, Effect, Exit, Fiber, Layer, Result, Scope, Stream } from "effect" import { Agent } from "../agent.js" import { Bus } from "../bus.js" import { Database } from "../database/database.js" @@ -150,16 +150,23 @@ const TRANSCRIPT_LEVELS = [0, OUTPUTS_CLIPPED, OUTPUTS_REMOVED, USER_ONLY, OMITT const TRANSCRIPT_CLIP = 2_000 const IMAGE_TOKEN_ESTIMATE = 1_500 const PDF_TOKEN_ESTIMATE = 2_000 -/** Share of the compaction ceiling at which a background summary starts. */ -const PRECOMPUTE_RATIO = 0.85 -/** Measured prompt tokens below which a background summary is not worth its cost. */ -const PRECOMPUTE_MIN_TOKENS = 64_000 /** - * The most text a swapped-in summary keeps verbatim beside it: twice `keep`, at least 30k, at most a quarter of the - * budget. A longer tail would leave the context near the threshold, so compaction summarizes from scratch instead. + * Tokens before the ceiling at which a background summary starts. Writing one takes 30–60 s, and in that time the + * conversation grows by a few thousand tokens at the median but by 25k or more one time in twenty, when large file + * reads arrive together. How far ahead to start depends on that growth, not on the window, so the lead is fixed. */ -const PRECOMPUTED_TAIL_MIN = 30_000 -const PRECOMPUTED_TAIL_SHARE = 0.25 +const PRECOMPUTE_LEAD = 60_000 +/** Prompt caches expire this long after their last use unless the model sets `cache.ttl`. */ +const CACHE_LIFETIME = 5 * 60_000 +/** A background summary starts only while this much of the latest response's cache lifetime is left. */ +const CACHE_MARGIN = 30_000 +/** + * The most text a swapped-in summary keeps verbatim beside it, and the tail at which a held summary is replaced, as a + * share of the budget. Tails are usually far shorter; the limit is there for bursts of large tool inputs or pasted + * text. At 40%, a swapped-in context stays under about two thirds of the budget even with Claude's tokenizer, so the + * next cycle keeps room; a longer tail makes compaction summarize from scratch instead. + */ +const PRECOMPUTED_TAIL_SHARE = 0.4 /** Failed background summaries after which no new one starts until the next compaction. */ const PRECOMPUTE_MAX_FAILURES = 2 @@ -329,11 +336,14 @@ export const layer = Layer.effect( }) /** - * Once the context passes `PRECOMPUTE_RATIO` of the ceiling, summarizes everything before the latest response in - * the background. That is the prefix the provider just processed, so the summary request reads it from the prompt - * cache. The summary is held, not applied: swapping it in now would rewrite the prefix and throw away the cache - * for every step until compaction is actually due. One summary is held per Session until compaction takes it, or - * until it fails or falls too far behind, when a newer response replaces it. + * Once the context is within `PRECOMPUTE_LEAD` of the ceiling, summarizes everything before the latest response + * in the background. That is the prefix the provider just processed, so the summary request reads it from the + * prompt cache. The summary is held, not applied: swapping it in now would rewrite the prefix and throw away the + * cache for every step until compaction is actually due. One summary is held per Session until compaction takes + * it, or until it fails or falls too far behind, when a newer response replaces it. + * + * On a small window the lead is at most half the room the cycle started with, so the summary still covers more + * than the previous one. */ const precompute = Effect.fn("SessionCompaction.precompute")(function* ( load: Effect.Effect, @@ -347,12 +357,13 @@ export const layer = Layer.effect( if (!Number.isFinite(ceiling)) return const estimate = given ?? estimatePrompt(context) if (due(context, ceiling, estimate)) return - if (total(estimate) < ceiling * PRECOMPUTE_RATIO) return + const first = context.messages.find((message) => hasMeasuredPrompt(message, context.model.ref)) + const cycleStart = first?.type === "assistant" && first.tokens ? promptTokens(first.tokens) : 0 + if (total(estimate) < ceiling - Math.min(PRECOMPUTE_LEAD, (ceiling - cycleStart) / 2)) return const anchorIndex = context.messages.findLastIndex((message) => hasMeasuredPrompt(message, context.model.ref)) const anchor = context.messages[anchorIndex] if (anchorIndex <= 0 || anchor?.type !== "assistant" || !anchor.tokens) return - if (anchor.tokens.input + anchor.tokens.cache.read + anchor.tokens.cache.write < PRECOMPUTE_MIN_TOKENS) return const sessionID = context.session.id const existing = precomputed.get(sessionID) @@ -369,6 +380,10 @@ export const layer = Layer.effect( } // After a model switch nothing is cached for the new model yet; wait until its first response has written it. if (anchor.model.id !== context.model.ref.id || anchor.model.variant !== context.model.ref.variant) return + // The same once the latest response is older than the cache lifetime, as when the user comes back from a + // break: the summary would write the whole prefix again, at the same time as the next request. + const age = (yield* Clock.currentTimeMillis) - DateTime.toEpochMillis(anchor.time.created) + if (age > cacheLifetime(context.model.cache?.ttl) - CACHE_MARGIN) return const model = yield* selectModel(context, settings.buffer, false) const usage: SessionUsage.Recorded[] = [] @@ -381,7 +396,7 @@ export const layer = Layer.effect( keepID: anchor.id, model: context.model.ref, initial: Instructions.join(context.initial), - tailLimit: tailLimit(settings.keep, model.cap), + tailLimit: tailLimit(model.cap), failures, usage, fiber, @@ -406,7 +421,7 @@ export const layer = Layer.effect( trigger.reason !== "overflow" && context.model.compaction?.type !== "native" && index >= 0 && - tailTokens(context, index) <= tailLimit(settings.keep, budget) + tailTokens(context, index) <= tailLimit(budget) if (!usable) { yield* Fiber.interrupt(held.fiber) return undefined @@ -961,8 +976,18 @@ const heldIndex = (held: Precomputed, context: SessionContext.Loaded) => { const tailTokens = (context: SessionContext.Loaded, index: number) => Token.estimate(context.messages.slice(index).map(SessionRecentText.messageToText).filter(Boolean).join("\n\n")) -const tailLimit = (keep: number, budget: number) => - Math.min(Math.max(keep * 2, PRECOMPUTED_TAIL_MIN), Math.floor(budget * PRECOMPUTED_TAIL_SHARE)) +const tailLimit = (budget: number) => Math.floor(budget * PRECOMPUTED_TAIL_SHARE) + +const promptTokens = (tokens: { input: number; cache: { read: number; write: number } }) => + tokens.input + tokens.cache.read + tokens.cache.write + +const DURATION_UNITS = { ms: 1, s: 1_000, m: 60_000, h: 3_600_000, d: 86_400_000 } + +/** Milliseconds a prompt cache entry lives, from a `cache.ttl` such as "5m" or "1h". */ +const cacheLifetime = (ttl: string | undefined) => { + const match = ttl?.match(/^(\d+)(ms|s|m|h|d)$/) + return match ? Number(match[1]) * DURATION_UNITS[match[2] as keyof typeof DURATION_UNITS] : CACHE_LIFETIME +} /** History loads from the latest completed compaction, so a previous one is always the first message. */ const previousCompaction = (messages: ReadonlyArray) => { @@ -1166,7 +1191,7 @@ const hasMeasuredPrompt = (message: SessionMessage.Info, model: SessionContext.L message.model.providerID === model.providerID && !message.error && message.tokens !== undefined && - message.tokens.input + message.tokens.cache.read + message.tokens.cache.write > 0 + promptTokens(message.tokens) > 0 /** The prompt size, only while the model, variant and agent that were measured still match; they shape the request. */ const measuredPrompt = (context: SessionContext.Loaded) => { diff --git a/packages/core/test/session-compaction.test.ts b/packages/core/test/session-compaction.test.ts index b9d7aca62903..14b1ab94a889 100644 --- a/packages/core/test/session-compaction.test.ts +++ b/packages/core/test/session-compaction.test.ts @@ -44,6 +44,7 @@ import { Money } from "@opencode/schema/money" import { Skill } from "@opencode/schema/skill" import { Shell } from "@opencode/schema/shell" import { DateTime, Deferred, Effect, Fiber, Layer, Schema, Stream } from "effect" +import { TestClock } from "effect/testing" import { asc, eq, inArray, sql } from "drizzle-orm" import { testEffect } from "./lib/effect" @@ -1000,7 +1001,7 @@ it.effect("forked session compaction reuses the fork root prompt cache key", () }), ) -const measured = (text: string, input: number) => +const measured = (text: string, input: number, created = 0) => Schema.decodeUnknownSync(SessionMessage.Assistant)({ id: SessionMessage.ID.create(), type: "assistant", @@ -1008,12 +1009,12 @@ const measured = (text: string, input: number) => model: { id: "summary-model", providerID: "test" }, content: [{ type: "text", text }], tokens: { input, output: 100, reasoning: 0, cache: { read: 0, write: 0 } }, - time: { created: 0, completed: 1 }, + time: { created, completed: created + 1 }, }) /** - * A 200k window compacts at 170k and starts a background summary at 85% of that, 144.5k. `near` ends past that - * point; `due` continues it past the threshold. + * A 200k window compacts at 170k. The first response measured 80k, so a background summary starts half that room, + * 45k, before the threshold, at 125k. `near` ends past that point; `due` continues it past the threshold. */ const precomputeHistory = () => { const near = [textUser("First question"), measured("First answer", 80_000), textUser("Second question")] @@ -1061,7 +1062,8 @@ for (const background of [false, true]) { Effect.gen(function* () { const messages = [ textUser("Earlier question"), - oldReasoning(), + // The cycle starts low, so the latest response is past the point where a background summary starts. + oldReasoning(summaryInput / 4), textUser("Latest question"), measured("Latest answer", summaryInput), ] @@ -1329,8 +1331,9 @@ it.effect("a background summary that fell too far behind is replaced from a newe const compaction = yield* enablePrecompute const session = yield* insertSession(Session.ID.make("ses_precompute_behind")) const history = precomputeHistory() - // About 35k tokens arrived after the summarized prefix, past the 30k that may stay verbatim beside it. - const behind = [...history.near, textUser("x".repeat(140_000)), measured("Burst handled", 160_000)] + // About 75k tokens arrived after the summarized prefix, past the 68k (40% of the 170k budget) that may stay + // verbatim beside it. + const behind = [...history.near, textUser("x".repeat(300_000)), measured("Burst handled", 160_000)] yield* compaction.precompute(Effect.succeed(loaded(session, history.near))) yield* compaction.precompute(Effect.succeed(loaded(session, behind))) @@ -1393,8 +1396,8 @@ it.effect("compaction summarizes as usual when the background summary no longer return JSON.stringify(requests.at(-1)?.messages) }) - // About 35k tokens arrived after the summarized prefix, past the 30k that may stay verbatim beside it. - const burst = [...history.near, textUser("x".repeat(140_000)), measured("Burst handled", 182_000)] + // About 75k tokens arrived after the summarized prefix, past the 68k that may stay verbatim beside it. + const burst = [...history.near, textUser("x".repeat(300_000)), measured("Burst handled", 182_000)] expect(yield* compactAfterPrecompute(burst)).toContain("Burst handled") // A different model would replay a summary written for the previous one. @@ -1405,3 +1408,116 @@ it.effect("compaction summarizes as usual when the background summary no longer expect(yield* compactAfterPrecompute(history.due, switched)).toContain("Third answer") }), ) + +it.effect("a background summary keeps a tail longer than twice keep while it stays under 40% of the budget", () => + Effect.gen(function* () { + requests = [] + const compaction = yield* enablePrecompute + const session = yield* insertSession(Session.ID.make("ses_precompute_long_tail")) + const history = precomputeHistory() + // About 35k tokens arrived after the summarized prefix: more than twice keep, less than 68k. + const burst = [...history.near, textUser("x".repeat(140_000)), measured("Burst handled", 160_000)] + const due = [...burst, textUser("Next question"), measured("Next answer", 182_000)] + + yield* compaction.precompute(Effect.succeed(loaded(session, history.near))) + yield* compaction.precompute(Effect.succeed(loaded(session, burst))) + expect(yield* compaction.compact({ reason: "auto", context: loaded(session, due) })).toEqual({ + status: "completed", + }) + + // The first summary was kept and swapped in: one request, ending before the response it was started from. + expect(requests).toHaveLength(1) + const summarized = JSON.stringify(requests[0].messages) + expect(summarized).toContain("Second question") + expect(summarized).not.toContain("Second answer") + }), +) + +it.effect("a background summary starts a fixed lead before the threshold, not at a share of it", () => + Effect.gen(function* () { + requests = [] + const compaction = yield* enablePrecompute + const session = yield* insertSession(Session.ID.make("ses_precompute_lead")) + // A 1M window compacts at 850k, so a background summary starts 60k before that, at 790k. + const large = (messages: readonly SessionMessage.Info[]) => ({ + ...loaded(session, messages), + model: { ...resolved, limit: { context: 1_000_000, output: 128_000 } }, + }) + const early = [textUser("First question"), measured("First answer", 100_000), textUser("Second question")] + const before = [...early, measured("Second answer", 760_000)] + const within = [...before, textUser("Third question"), measured("Third answer", 800_000)] + const due = [...within, textUser("Fourth question"), measured("Fourth answer", 860_000)] + + // 760k is past 85% of the threshold, but still more than the lead away from it. + yield* compaction.precompute(Effect.succeed(large(before))) + yield* compaction.precompute(Effect.succeed(large(within))) + expect(yield* compaction.compact({ reason: "auto", context: large(due) })).toEqual({ status: "completed" }) + + expect(requests).toHaveLength(1) + const summarized = JSON.stringify(requests[0].messages) + expect(summarized).toContain("Third question") + expect(summarized).not.toContain("Third answer") + }), +) + +it.effect("a background summary starts on a window whose threshold is under 64k", () => + Effect.gen(function* () { + requests = [] + const compaction = yield* enablePrecompute + const session = yield* insertSession(Session.ID.make("ses_precompute_small")) + // A 64k window compacts at 48k. The first response measured 20k, so half that room, 14k, sets the start at 34k. + const small = (messages: readonly SessionMessage.Info[]) => ({ + ...loaded(session, messages), + model: { ...resolved, limit: { context: 64_000, output: 16_000 } }, + }) + const early = [textUser("First question"), measured("First answer", 20_000), textUser("Second question")] + const before = [...early, measured("Second answer", 30_000)] + const within = [...before, textUser("Third question"), measured("Third answer", 40_000)] + const due = [...within, textUser("Fourth question"), measured("Fourth answer", 50_000)] + + yield* compaction.precompute(Effect.succeed(small(before))) + yield* compaction.precompute(Effect.succeed(small(within))) + expect(yield* compaction.compact({ reason: "auto", context: small(due) })).toEqual({ status: "completed" }) + + expect(requests).toHaveLength(1) + const summarized = JSON.stringify(requests[0].messages) + expect(summarized).toContain("Third question") + expect(summarized).not.toContain("Third answer") + }), +) + +it.effect("a background summary waits for a response whose prompt is still cached", () => + Effect.gen(function* () { + const compaction = yield* enablePrecompute + const history = precomputeHistory() + const later = (created: number) => [ + ...history.near, + textUser("Third question"), + measured("Third answer", 160_000, created), + ] + const summarizedAfterBreak = (sessionID: string, ttl?: "1h") => + Effect.gen(function* () { + requests = [] + const session = yield* insertSession(Session.ID.make(sessionID)) + const context = (messages: readonly SessionMessage.Info[]) => ({ + ...loaded(session, messages), + model: { ...resolved, ...(ttl ? { cache: { ttl } } : {}) }, + }) + const now = DateTime.toEpochMillis(yield* DateTime.now) + // The latest response was written ten minutes ago; then a new one arrives. + yield* compaction.precompute(Effect.succeed(context(history.near))) + const resumed = later(now) + yield* compaction.precompute(Effect.succeed(context(resumed))) + const due = [...resumed, textUser("Fourth question"), measured("Fourth answer", 182_000, now)] + expect(yield* compaction.compact({ reason: "auto", context: context(due) })).toEqual({ status: "completed" }) + expect(requests).toHaveLength(1) + return JSON.stringify(requests[0].messages) + }) + + yield* TestClock.adjust("10 minutes") + // Past the default five-minute cache, the summary starts from the next response instead. + expect(yield* summarizedAfterBreak("ses_precompute_cold")).toContain("Third question") + // A model that keeps its cache for an hour summarizes the older response right away. + expect(yield* summarizedAfterBreak("ses_precompute_hour", "1h")).not.toContain("Third question") + }), +) diff --git a/services/www/src/docs/content/compaction.mdx b/services/www/src/docs/content/compaction.mdx index 8e2a06c50af3..47a373834cd9 100644 --- a/services/www/src/docs/content/compaction.mdx +++ b/services/www/src/docs/content/compaction.mdx @@ -137,16 +137,20 @@ writes the summary ahead of time and swaps it in when compaction is due: ``` ```text -85% of the threshold summary of the conversation so far starts in the background - the session keeps going; the summary is held, not applied -threshold the held summary is swapped in; everything since it is kept as is +60k tokens before the threshold summary of the conversation so far starts in the background + the session keeps going; the summary is held, not applied +threshold the held summary is swapped in; everything since it is kept as is ``` +On small context windows, the summary starts at most halfway between the first response after the last compaction +and the threshold. + | Rule | Behavior | | --- | --- | -| Cost | The summary request reuses the prompt cache. A summary that is never used still costs tokens. | -| Falls back | Compaction summarizes as usual if too much conversation arrived since the held summary, or if the model, instructions, or start of the conversation changed. | -| Skipped | Not used for native compaction, in sessions under about 64k tokens, right after a model switch, or when a provider rejects a request as too long. | +| Cost | The summary request reuses the prompt cache. A summary that is never used, for example because the session ends before the threshold, still costs tokens. | +| Waits | If the summary is still being written when compaction is due, the session waits for it to finish. | +| Falls back | Compaction summarizes as usual if the conversation since the held summary grew past about 40% of the threshold, or if the model, instructions, or start of the conversation changed. | +| Skipped | Not used for native compaction, right after a model switch, or when a provider rejects a request as too long. After a break longer than the prompt cache lifetime, it starts from the next response instead. | | Storage | Held summaries live in memory and are lost on restart. | ## Providers From 7ffde6cad975636e94c03f07e383d802cbd5c77f Mon Sep 17 00:00:00 2001 From: Luke Parker <10430890+Hona@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:31:07 -0600 Subject: [PATCH 021/200] fix(app): keep the server dialog open on an invalid address and close it once (#61815) --- .../app/e2e/regression/multi-server.spec.ts | 8 + packages/app/e2e/regression/settings.spec.ts | 38 ++ .../app/src/servers/connect/controller.ts | 158 +++++++ packages/app/src/servers/connect/dialog.tsx | 437 +++--------------- .../app/src/servers/connect/machine.test.ts | 390 ++++++++++++++++ packages/app/src/servers/connect/machine.ts | 333 +++++++++++++ packages/app/src/servers/connect/screen.tsx | 176 ++----- .../src/servers/registry/management.test.ts | 77 +-- .../app/src/servers/registry/management.ts | 41 +- 9 files changed, 1041 insertions(+), 617 deletions(-) create mode 100644 packages/app/src/servers/connect/controller.ts create mode 100644 packages/app/src/servers/connect/machine.test.ts create mode 100644 packages/app/src/servers/connect/machine.ts diff --git a/packages/app/e2e/regression/multi-server.spec.ts b/packages/app/e2e/regression/multi-server.spec.ts index 4809eb2ac5a0..7703ff343d47 100644 --- a/packages/app/e2e/regression/multi-server.spec.ts +++ b/packages/app/e2e/regression/multi-server.spec.ts @@ -160,6 +160,14 @@ test("a remote session whose server signed the app out asks to sign in again, th await expect(signedOut).toBeVisible() await page.getByRole("button", { name: "Sign in again", exact: true }).click() const editor = page.getByRole("dialog", { name: "Edit server" }) + + // An empty address explains itself instead of closing the dialog. + await editor.getByRole("button", { name: "Use password", exact: true }).click() + await editor.getByLabel("Server address", { exact: true }).fill("") + await editor.getByRole("button", { name: "Save", exact: true }).click() + await expect(editor.getByRole("alert")).toHaveText("Enter a valid HTTP or HTTPS server address.") + await editor.getByRole("button", { name: "Use pairing link", exact: true }).click() + await editor.getByLabel("Pairing link", { exact: true }).fill(`${REMOTE_SERVER}/auth/connect/one-time-code`) await editor.getByRole("button", { name: "Save", exact: true }).click() diff --git a/packages/app/e2e/regression/settings.spec.ts b/packages/app/e2e/regression/settings.spec.ts index babf27ad342a..2655f607e578 100644 --- a/packages/app/e2e/regression/settings.spec.ts +++ b/packages/app/e2e/regression/settings.spec.ts @@ -1916,6 +1916,44 @@ test("the add server dialog pairs from a one-time link and explains a spent one" ) }) +test("a server check that answers after its dialog closed saves nothing and leaves the next dialog open", async ({ + page, +}) => { + const late = "http://127.0.0.1:4098" + await mockRemoteServer(page, { directory: "/remote/settings-demo" }) + await mockOpenCodeServer(page, { + server: late, + directory: "/remote/late", + project: project({ id: "proj_late", directory: "/remote/late" }), + provider: NO_PROVIDER, + sessions: [], + pageMessages: () => ({ items: [] }), + }) + const check = await holdRoute(page, /^http:\/\/127\.0\.0\.1:4098\/api\/info/) + const { settings } = await open(page) + await settings.getByRole("tab", { name: "Servers", exact: true }).click() + await settings.getByRole("button", { name: "Add server" }).click() + const editor = page.getByRole("dialog", { name: "Add server" }) + await editor.getByRole("button", { name: "Use password", exact: true }).click() + await editor.getByLabel("Server address", { exact: true }).fill(late) + await editor.getByRole("button", { name: "Add server", exact: true }).click() + await check.arrived + await page.keyboard.press("Escape") + await expect(editor).toHaveCount(0) + + await settings.getByRole("button", { name: "Add server" }).click() + const link = editor.getByLabel("Pairing link", { exact: true }) + await expect(link).toBeFocused() + const answered = page.waitForResponse(/^http:\/\/127\.0\.0\.1:4098\/api\/info/) + check.release() + await answered + // A round trip after the answer: the cancelled check had every chance to save and close by now. + await link.fill("still open") + + await expect(link).toHaveValue("still open") + await expect(settings.getByText(late, { exact: true })).toHaveCount(0) +}) + test("a pairing code with several addresses keeps the first one that works with its token", async ({ page }) => { // Both addresses reach one server. The second spends the code first, so the first answers 401, and the token works on // it as on every address of that server. diff --git a/packages/app/src/servers/connect/controller.ts b/packages/app/src/servers/connect/controller.ts new file mode 100644 index 000000000000..b303e783333b --- /dev/null +++ b/packages/app/src/servers/connect/controller.ts @@ -0,0 +1,158 @@ +import { type Accessor, createEffect, createMemo, createSignal, on, onCleanup, untrack } from "solid-js" +import { useLanguage } from "@/runtime/i18n/language" +import { usePlatform } from "@/runtime/platform/platform" +import { useCheckServerHealth } from "@/runtime/server/health" +import { ServerConnection, useServers } from "@/runtime/server/registry" +import { replaceServerConnection } from "@/servers/registry/management" +import { + createServerConnectState, + selectServerConnectView, + transitionServerConnect, + type ServerConnectEffect, + type ServerConnectEvent, + type ServerConnectTarget, + type ServerOriginal, +} from "./machine" +import { useRedeemPairing } from "./redeem" + +export type ServerConnectControllerOptions = + | { readonly surface: "screen"; readonly target: Extract } + | { + readonly surface: "dialog" + readonly target: Exclude + /** The edited server as the registry lists it now; undefined once it is removed. */ + readonly original?: Accessor + readonly removeTabs: (key: ServerConnection.Key) => void + /** Closes the dialog. `saved` is the server a successful save stored. */ + readonly onClose: (saved: ServerConnection.Http | undefined) => void + } + +export function createServerConnectController(options: ServerConnectControllerOptions) { + const language = useLanguage() + const platform = usePlatform() + const servers = useServers() + 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)) + let timer: ReturnType | undefined + + const dispatch = (event: ServerConnectEvent) => { + const prev = untrack(machine) + const next = transitionServerConnect(prev, event) + + if (next.state !== prev) setMachine(next.state) + next.effects.forEach(run) + } + + const run = (effect: ServerConnectEffect) => { + if (effect.type === "timer.start") { + clearTimeout(timer) + timer = setTimeout(() => dispatch({ type: "submit.timed-out", attempt: effect.attempt }), effect.timeoutMs) + + return + } + + if (effect.type === "timer.stop") { + clearTimeout(timer) + timer = undefined + + return + } + + if (effect.type === "connect.http") { + const failed = () => + dispatch({ + type: "submit.failed", + attempt: effect.attempt, + error: { type: "connection-failed", url: effect.http.url }, + }) + + void Promise.try(() => check(effect.http)).then( + (result) => + result.type === "healthy" + ? dispatch({ type: "submit.succeeded", attempt: effect.attempt, http: effect.http }) + : failed(), + failed, + ) + + return + } + + if (effect.type === "connect.link") { + void Promise.try(() => pair(effect)).then(dispatch, () => + dispatch({ + type: "submit.failed", + attempt: effect.attempt, + error: { type: "connection-failed", url: effect.fallbackUrl }, + }), + ) + + return + } + + if (effect.type === "save") { + const action = effect.action + + if (action.type === "connect") { + // Signing in again keeps the name the user gave this server. + const existing = servers.list.find( + (server): server is ServerConnection.Http => server.type === "http" && server.http.url === action.http.url, + ) + + servers.add(existing ? { ...existing, http: action.http } : { type: "http", http: action.http }) + + return + } + + if (action.type === "add" || options.surface !== "dialog") return void servers.add(action.connection) + replaceServerConnection(ServerConnection.Key.make(action.originalUrl), action.connection, { + removeTabs: options.removeTabs, + add: (server) => servers.add(server), + remove: (key) => servers.remove(key), + }) + + return + } + + if (options.surface === "dialog") options.onClose(effect.saved) + } + + const pair = async (effect: Extract): Promise => { + const redeemed = await redeem(effect.link) + + if (!redeemed) return { type: "submit.failed", attempt: effect.attempt, error: { type: "link-invalid" } } + + if ("error" in redeemed) + return { type: "submit.failed", attempt: effect.attempt, error: { type: "redeem", message: redeemed.error } } + const password = redeemed.pairing.password + + if (effect.preferredUrl && effect.preferredUrl !== redeemed.pairing.url) { + const http = { url: effect.preferredUrl, password } + + if ((await check(http)).type === "healthy") return { type: "submit.succeeded", attempt: effect.attempt, http } + } + + const http = { url: redeemed.pairing.url, password } + + if ((await check(http)).type === "healthy") return { type: "submit.succeeded", attempt: effect.attempt, http } + + return { type: "submit.failed", attempt: effect.attempt, error: { type: "connection-failed", url: http.url } } + } + + // Runs once the dialog is in the stack, so a server removed before then closes this dialog, not the one below. + if (options.surface === "dialog" && options.original) + createEffect(on(options.original, (original) => dispatch({ type: "original.synced", original }))) + + onCleanup(() => dispatch({ type: "disposed" })) + + const view = createMemo(() => + selectServerConnectView(machine(), { + surface: options.surface, + pageHref: platform.platform === "web" ? location.href : undefined, + t: (key) => language.t(key), + }), + ) + + return { view, dispatch, redeem } +} diff --git a/packages/app/src/servers/connect/dialog.tsx b/packages/app/src/servers/connect/dialog.tsx index 9638f9b58ef3..2e90fab8f797 100644 --- a/packages/app/src/servers/connect/dialog.tsx +++ b/packages/app/src/servers/connect/dialog.tsx @@ -4,42 +4,21 @@ import { Divider } from "@opencode/ui/divider" import { Icon } from "@opencode/ui/icon" import { TextInput } from "@opencode/ui/text-input" import { useDialog } from "@opencode/ui/context/dialog" -import { useMutation } from "@tanstack/solid-query" -import { - type Component, - Show, - Suspense, - createEffect, - createMemo, - createSignal, - lazy, - onCleanup, - onMount, -} from "solid-js" -import { createStore } from "solid-js/store" -import { - createServerHealthPreview, - replaceServerConnection, - type ServerFormValues, -} from "@/servers/registry/management" +import { type Component, Show, Suspense, createMemo, lazy, untrack } from "solid-js" import { useGlobal } from "@/runtime/server/runtime" import { useLanguage } from "@/runtime/i18n/language" -import { normalizeServerUrl, ServerConnection, useServers } from "@/runtime/server/registry" +import { ServerConnection, useServers } from "@/runtime/server/registry" import { useTabs } from "@/shell/tabs/tabs" -import { useCheckServerHealth } from "@/runtime/server/health" -import { isServerFailed, isServerHealthy, isServerUnauthorized } from "@/runtime/server/health-machine" +import { isServerUnauthorized } from "@/runtime/server/health-machine" import { usePlatform } from "@/runtime/platform/platform" -import { isMixedContent } from "./browser" import { cameraHint, createCameraAvailability } from "./camera" -import { bareServerAddress, pairingLink, type Pairing } from "./pairing" -import { useRedeemPairing } from "./redeem" -import { ConnectMethodSwitch, type ConnectMethod } from "./method" +import { createServerConnectController } from "./controller" +import type { ServerConnectField, ServerOriginal } from "./machine" +import { ConnectMethodSwitch } from "./method" import "@/settings/settings.css" const PairingScanner = lazy(() => import("./scanner").then((module) => ({ default: module.PairingScanner }))) -type FormMode = "list" | "add" | "edit" - export const DialogServer: Component<{ mode: "add" | "edit" server?: ServerConnection.Http @@ -48,55 +27,63 @@ export const DialogServer: Component<{ 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 form = createFormController({ - // Close first: onSave may open the next dialog, such as the folder picker an interrupted action continues with. - onSelect: (server) => { - dialog.close() - props.onSave?.(server) - }, + const originalOf = (server: ServerConnection.Http): ServerOriginal => ({ + url: server.http.url, + displayName: server.displayName, + password: server.http.password, + unauthorized: isServerUnauthorized(global.servers.health[ServerConnection.key(server)]), }) - const [opened, setOpened] = createSignal(false) + const original = createMemo(() => { + const server = servers.list.find( + (item): item is ServerConnection.Http => item.type === "http" && item.http.url === edited?.http.url, + ) - onMount(() => { - if (props.mode === "add") form.start.add() - - if (props.mode === "edit" && props.server) form.start.edit(props.server) - setOpened(true) - }) - - onCleanup(() => { - form.reset() + return server && originalOf(server) }) - createEffect(() => { - if (!opened()) return + const form = createServerConnectController({ + surface: "dialog", + target: edited ? { kind: "edit", original: untrack(original) ?? originalOf(edited) } : { kind: "add" }, + original, + removeTabs: (key) => tabs.removeServer(key), + // Close first: onSave may open the next dialog, such as the folder picker an interrupted action continues with. + onClose: (saved) => { + dialog.close() - if (form.state.open()) return - dialog.close() + if (saved) props.onSave?.(saved) + }, }) + const view = form.view + const submit = () => form.dispatch({ type: "submitted" }) + const change = (field: ServerConnectField, value: string) => form.dispatch({ type: "field.changed", field, value }) + const keyDown = (event: KeyboardEvent) => { if (event.key !== "Enter" || event.isComposing) return event.preventDefault() - form.submit() + submit() } const title = () => props.mode === "add" ? language.t("dialog.server.add.title") : language.t("dialog.server.edit.title") const error = () => ( - + - {form.state.error()} + {view().error} ) const submitLabel = () => { - if (form.state.busy()) return language.t("dialog.server.add.checking") + if (view().busy) return language.t("dialog.server.add.checking") if (props.mode === "add") return language.t("dialog.server.add.button") @@ -111,29 +98,29 @@ export const DialogServer: Component<{ {language.t("server.connect.camera.starting")}

}> { - form.scan.stop() + form.dispatch({ type: "scan.cancelled" }) void camera.refetch() }} - redeem={form.scan.redeem} - onScan={form.scan.complete} + redeem={form.redeem} + onScan={(link) => form.dispatch({ type: "scan.completed", link })} /> } >
- +

{language.t("dialog.server.signedOut")}

- +
- + {language.t(cameraHint())}} @@ -228,27 +215,27 @@ export const DialogServer: Component<{ variant="neutral" size="large" class="!w-full self-stretch" - disabled={form.state.busy() || !camera.available.latest} - onClick={form.scan.start} + disabled={view().disabled || !camera.available.latest} + onClick={() => form.dispatch({ type: "scan.started" })} > {language.t("server.connect.scan")} form.dispatch({ type: "method.changed", method })} />
- + - - @@ -256,287 +243,3 @@ export const DialogServer: Component<{ ) } - -function createFormController(options: { onSelect?: (server: ServerConnection.Http) => void } = {}) { - const platform = usePlatform() - const server = useServers() - const tabs = useTabs() - const global = useGlobal() - const language = useLanguage() - const checkServerHealth = useCheckServerHealth() - const redeem = useRedeemPairing() - const healthPreview = createServerHealthPreview(checkServerHealth) - - const [store, setStore] = createStore<{ - mode: FormMode - method: ConnectMethod - originalUrl: string | undefined - link: string - values: ServerFormValues - scanning: boolean - error: string - status: boolean | undefined - }>({ - mode: "list", - method: "link", - originalUrl: undefined, - link: "", - values: { url: "", name: "", password: "" }, - scanning: false, - error: "", - status: undefined, - }) - - onCleanup(healthPreview.cancel) - - const reset = () => { - healthPreview.cancel() - setStore({ - mode: "list", - method: "link", - originalUrl: undefined, - link: "", - values: { url: "", name: "", password: "" }, - scanning: false, - error: "", - status: undefined, - }) - } - - const allServers = () => { - return server.list - } - - const editing = createMemo(() => - allServers().find( - (item): item is ServerConnection.Http => item.type === "http" && item.http.url === store.originalUrl, - ), - ) - - const add = (connection: ServerConnection.Http) => server.add(connection) - - const replace = (originalKey: ServerConnection.Key, next: ServerConnection.Http) => - replaceServerConnection(originalKey, next, { - removeTabs: (key) => tabs.removeServer(key), - add, - remove: (key) => server.remove(key), - }) - - // A pairing token works on every address of its server. Signing in again to the edited server keeps its address - // (e.g. localhost) even when the link names another one (e.g. 127.0.0.1 from opencode pair). - const paired = async (pairing: Pairing) => { - const original = store.mode === "edit" ? editing() : undefined - - if (!original || original.http.url === pairing.url) return pairing - const http = { url: original.http.url, password: pairing.password } - - return (await checkServerHealth(http)).type === "healthy" ? http : pairing - } - - // Where the form points: a scanned or pasted pairing link wins, else the address and password fields. - const target = async (): Promise => { - if (store.method === "link") { - const redeemed = await redeem(store.link) - - if (redeemed && "error" in redeemed) return void setStore("error", redeemed.error) - - if (redeemed) return paired(redeemed.pairing) - // A server address typed here belongs to the password form. - const address = bareServerAddress(store.link) - - if (address) { - setStore({ method: "password", link: "", values: { ...store.values, url: address } }) - preview() - - return - } - - return void setStore("error", language.t("server.connect.link.invalid")) - } - - // A pairing link pasted into the address field still pairs. - const redeemed = await redeem(store.values.url) - - if (redeemed && "error" in redeemed) return void setStore("error", redeemed.error) - - if (redeemed) return paired(redeemed.pairing) - const url = normalizeServerUrl(store.values.url) - - if (!url) return void reset() - - return { url, password: store.values.password || undefined } - } - - const request = useMutation(() => ({ - mutationFn: async () => { - const http = await target() - - if (!http) return - const normalized = http.url - const original = store.mode === "edit" ? editing() : undefined - - if (store.mode === "edit" && !original) return - const name = store.values.name.trim() || undefined - const password = http.password - - // Nothing changed: close, unless the server rejects these credentials, so saving checks them and the action that - // asked for sign-in can continue. - if ( - original?.type === "http" && - !isServerUnauthorized(global.servers.health[ServerConnection.key(original)]) && - normalized === original.http.url && - name === original.displayName && - password === original.http.password - ) { - reset() - - return - } - - const connection: ServerConnection.Http = { - type: "http", - displayName: name, - http: { - url: normalized, - password, - }, - } - - const result = await checkServerHealth(connection.http) - - if (result.type !== "healthy") { - setStore( - "error", - language.t( - platform.platform === "web" && isMixedContent(location.href, normalized) - ? "server.connect.mixedContent" - : "dialog.server.add.error", - ), - ) - - return - } - - if (original?.type === "http") { - if (normalized === original.http.url) add(connection) - - if (normalized !== original.http.url) replace(ServerConnection.key(original), connection) - reset() - options.onSelect?.(connection) - - return - } - - reset() - add(connection) - options.onSelect?.(connection) - }, - })) - - const preview = () => { - // A pairing link is not a server address until it is redeemed, and redeeming spends it. - if (store.method === "link" || pairingLink(store.values.url)) { - healthPreview.cancel() - setStore("status", undefined) - - return - } - - void healthPreview.preview(store.values, (status) => setStore("status", status)) - } - - const change = (field: keyof ServerFormValues, value: string) => { - if (request.isPending) return - setStore("values", field, value) - setStore("error", "") - - if (field !== "name") preview() - } - - const startAdd = () => { - reset() - setStore("mode", "add") - } - - const startEdit = (connection: ServerConnection.Http) => { - const health = global.servers.health[ServerConnection.key(connection)] - reset() - setStore({ - mode: "edit", - // A signed-out server needs a new pairing link; otherwise editing starts from its address. - method: isServerUnauthorized(health) ? "link" : "password", - originalUrl: connection.http.url, - values: { - url: connection.http.url, - name: connection.displayName ?? "", - password: connection.http.password ?? "", - }, - error: "", - status: isServerFailed(health) ? false : isServerHealthy(health) || undefined, - }) - } - - const submit = () => { - if (store.mode === "list" || request.isPending) return - setStore("error", "") - request.mutate() - } - - const pair = (link: string) => { - healthPreview.cancel() - setStore({ method: "link", link, scanning: false, error: "" }) - request.mutate() - } - - createEffect(() => { - if (store.mode !== "edit") return - - if (editing()) return - reset() - }) - - return { - state: { - mode: () => store.mode, - open: () => store.mode !== "list", - adding: () => store.mode === "add", - busy: () => request.isPending, - method: () => store.method, - link: () => store.link, - value: () => store.values.url, - name: () => store.values.name, - password: () => store.values.password, - scanning: () => store.scanning, - error: () => store.error, - status: () => store.status, - signedOut: () => { - const original = editing() - - return !!original && isServerUnauthorized(global.servers.health[ServerConnection.key(original)]) - }, - }, - change: { - method: (method: ConnectMethod) => { - if (request.isPending) return - setStore({ method, error: "" }) - preview() - }, - link: (value: string) => { - if (request.isPending) return - setStore({ link: value, error: "" }) - }, - value: (value: string) => change("url", value), - name: (value: string) => change("name", value), - password: (value: string) => change("password", value), - }, - scan: { - start: () => setStore("scanning", true), - stop: () => setStore("scanning", false), - complete: pair, - redeem, - }, - start: { add: startAdd, edit: startEdit }, - reset, - submit, - } -} diff --git a/packages/app/src/servers/connect/machine.test.ts b/packages/app/src/servers/connect/machine.test.ts new file mode 100644 index 000000000000..43dab56d5f2d --- /dev/null +++ b/packages/app/src/servers/connect/machine.test.ts @@ -0,0 +1,390 @@ +import { describe, expect, test } from "bun:test" +import { + createServerConnectState, + formatServerConnectError, + selectServerConnectView, + SERVER_CONNECT_TIMEOUT_MS, + transitionServerConnect, + type ServerConnectEffect, + type ServerConnectErrorContext, + type ServerConnectEvent, + type ServerConnectState, + type ServerConnectTarget, + type ServerOriginal, +} from "./machine" + +const original = (input: Partial = {}): ServerOriginal => ({ + url: "http://old:4096", + displayName: undefined, + password: undefined, + unauthorized: false, + ...input, +}) + +const edit = (input: Partial = {}): ServerConnectTarget => ({ kind: "edit", original: original(input) }) + +function replay(target: ServerConnectTarget, events: readonly ServerConnectEvent[]) { + 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: [] }, + ) +} + +const field = (name: "link" | "url" | "name" | "password", value: string): ServerConnectEvent => ({ + type: "field.changed", + field: name, + value, +}) + +const password: ServerConnectEvent = { type: "method.changed", method: "password" } + +const submitted: ServerConnectEvent = { type: "submitted" } + +const succeeded = (attempt: number, url: string, secret?: string): ServerConnectEvent => ({ + type: "submit.succeeded", + attempt, + http: secret ? { url, password: secret } : { url }, +}) + +const context: ServerConnectErrorContext = { surface: "dialog", pageHref: undefined, t: (key) => key } + +const closes = (effects: readonly ServerConnectEffect[]) => effects.filter((effect) => effect.type === "close") + +describe("server connect form", () => { + test.each([ + { name: "an empty address in a new server", target: { kind: "add" } as const, events: [password] }, + { name: "a cleared address in an edited server", target: edit(), events: [field("url", "")] }, + { + name: "an address with another scheme", + target: { kind: "add" } as const, + events: [password, field("url", "ftp://host")], + }, + { + name: "an address with credentials", + target: { kind: "add" } as const, + events: [password, field("url", "http://u:p@host")], + }, + ])("$name keeps the dialog open and explains the address", (input) => { + const result = replay(input.target, [...input.events, submitted]) + + expect(result.state).toMatchObject({ status: "editing", error: { type: "address-invalid" } }) + expect(result.effects).toEqual([]) + expect(selectServerConnectView(result.state, context).error).toBe("server.connect.address.invalid") + }) + + test.each([ + { + name: "adding", + target: { kind: "add" } as const, + action: { type: "add", connection: { type: "http", displayName: "Remote", http: { url: "http://new:4096" } } }, + }, + { + name: "moving an edited server", + target: edit(), + action: { + type: "replace", + originalUrl: "http://old:4096", + connection: { type: "http", displayName: "Remote", http: { url: "http://new:4096" } }, + }, + }, + ])("a save by $name closes the dialog once", (input) => { + const saved = replay(input.target, [ + password, + field("url", "new:4096"), + field("name", " Remote "), + submitted, + succeeded(1, "http://new:4096"), + ]) + + expect(saved.state.status).toBe("closed") + expect(saved.effects.slice(2)).toEqual([ + { type: "timer.stop" }, + { type: "save", action: input.action }, + { type: "close", saved: input.action.connection }, + ]) + + // The replacement removes the original from the registry, then the dialog unmounts. + const after = [{ type: "original.synced", original: undefined }, { type: "disposed" }] as const + after.forEach((event) => + expect(transitionServerConnect(saved.state, event)).toEqual({ state: saved.state, effects: [] }), + ) + }) + + test("a scan cannot start or land while a submit runs", () => { + const submitting = replay({ kind: "add" }, [field("link", "http://192.168.1.2:4096/auth/connect/abc"), submitted]) + expect(submitting.state.status).toBe("submitting") + + const overlapping: ServerConnectEvent[] = [ + { type: "scan.started" }, + { type: "scan.completed", link: "http://10.0.0.2:4096/auth/connect/xyz" }, + submitted, + field("link", "other"), + ] + + overlapping.forEach((event) => + expect(transitionServerConnect(submitting.state, event)).toEqual({ state: submitting.state, effects: [] }), + ) + }) + + 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" }, + ]) + + expect(scanned.state).toMatchObject({ status: "submitting", attempt: 1 }) + expect(scanned.effects).toEqual([ + { + type: "connect.link", + attempt: 1, + link: "http://192.168.1.2:4096/auth/connect/abc", + preferredUrl: undefined, + fallbackUrl: "http://192.168.1.2:4096", + }, + { type: "timer.start", attempt: 1, timeoutMs: SERVER_CONNECT_TIMEOUT_MS }, + ]) + expect( + transitionServerConnect(scanned.state, { + type: "scan.completed", + link: "http://192.168.1.2:4096/auth/connect/abc", + }).state, + ).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" }, + ]) + + expect(result.state).toMatchObject({ status: "editing", draft: { name: "Remote" } }) + expect(result.effects).toEqual([]) + }) + + test("a result after the dialog unmounts saves nothing", () => { + const disposed = replay(edit(), [password, field("url", "new:4096"), submitted, { type: "disposed" }]) + + expect(disposed.state.status).toBe("closed") + expect(disposed.effects.at(-1)).toEqual({ type: "timer.stop" }) + expect(transitionServerConnect(disposed.state, succeeded(1, "http://new:4096"))).toEqual({ + state: disposed.state, + effects: [], + }) + }) + + test("a server address in the link field moves to the password form", () => { + const result = replay({ kind: "add" }, [field("link", "192.168.1.2:4096"), submitted]) + + expect(result.state).toMatchObject({ + status: "editing", + error: undefined, + draft: { method: "password", link: "", url: "http://192.168.1.2:4096" }, + }) + expect(result.effects).toEqual([]) + }) + + test("a pairing link in the address field still pairs, at the edited address first", () => { + const result = replay(edit(), [field("url", "http://192.168.1.2:4096/auth/connect/abc_123"), submitted]) + + expect(result.state.status).toBe("submitting") + expect(result.effects[0]).toEqual({ + type: "connect.link", + attempt: 1, + link: "http://192.168.1.2:4096/auth/connect/abc_123", + preferredUrl: "http://old:4096", + fallbackUrl: "http://old:4096", + }) + }) + + test.each([ + { name: "link", events: [field("link", "http://host:4096/connect#secret")] }, + { name: "address", events: [password, field("url", "http://host:4096/connect#secret")] }, + ])("a legacy link in the $name field asks for a new one", (input) => { + const result = replay({ kind: "add" }, [...input.events, submitted]) + + expect(result.state).toMatchObject({ status: "editing", error: { type: "link-legacy" } }) + expect(result.effects).toEqual([]) + }) + + test("an invalid link explains itself, and editing clears the error", () => { + const invalid = replay({ kind: "add" }, [field("link", "not a link"), submitted]) + expect(invalid.state).toMatchObject({ status: "editing", error: { type: "link-invalid" } }) + + expect(transitionServerConnect(invalid.state, field("link", "not a link")).state).toMatchObject({ + error: undefined, + }) + expect(transitionServerConnect(invalid.state, password).state).toMatchObject({ error: undefined }) + + const clean = replay({ kind: "add" }, [field("link", "x")]).state + expect(transitionServerConnect(clean, field("link", "x")).state).toBe(clean) + }) + + test("an unchanged edit closes without saving", () => { + const result = replay(edit({ displayName: "Remote", password: "secret" }), [field("name", " Remote "), submitted]) + + expect(result.state.status).toBe("closed") + expect(result.effects).toEqual([{ type: "close" }]) + }) + + test("an unchanged edit of a signed-out server checks the credentials again", () => { + const result = replay(edit({ password: "secret", unauthorized: true }), [password, submitted]) + + expect(result.effects[0]).toEqual({ + type: "connect.http", + attempt: 1, + http: { url: "http://old:4096", password: "secret" }, + }) + + const saved = transitionServerConnect(result.state, succeeded(1, "http://old:4096", "secret")) + + const connection = { + type: "http", + displayName: undefined, + http: { url: "http://old:4096", password: "secret" }, + } as const + + expect(saved.effects).toEqual([ + { type: "timer.stop" }, + { type: "save", action: { type: "add", connection } }, + { type: "close", saved: connection }, + ]) + }) + + test("a retry ignores every result of the attempt before it", () => { + const failed = replay({ kind: "add" }, [ + password, + field("url", "new:4096"), + submitted, + { type: "submit.failed", attempt: 1, error: { type: "connection-failed", url: "http://new:4096" } }, + ]) + + expect(failed.state).toMatchObject({ status: "editing", error: { type: "connection-failed" } }) + expect(failed.effects.at(-1)).toEqual({ type: "timer.stop" }) + + const retried = transitionServerConnect(failed.state, submitted).state + expect(retried).toMatchObject({ status: "submitting", attempt: 2 }) + + const stale: ServerConnectEvent[] = [ + succeeded(1, "http://new:4096"), + { type: "submit.failed", attempt: 1, error: { type: "link-invalid" } }, + { type: "submit.timed-out", attempt: 1 }, + ] + + stale.forEach((event) => expect(transitionServerConnect(retried, event)).toEqual({ state: retried, effects: [] })) + }) + + test("a submit that never answers times out as a failed connection", () => { + const result = replay({ kind: "add" }, [ + password, + field("url", "new:4096"), + submitted, + { type: "submit.timed-out", attempt: 1 }, + ]) + + expect(result.state).toMatchObject({ + status: "editing", + error: { type: "connection-failed", url: "http://new:4096" }, + }) + expect(result.effects.at(-1)).toEqual({ type: "timer.stop" }) + }) + + test("an edited server removed while it saves closes the dialog", () => { + const result = replay(edit(), [ + password, + field("url", "new:4096"), + submitted, + { type: "original.synced", original: undefined }, + ]) + + expect(result.state.status).toBe("closed") + expect(result.effects.slice(-2)).toEqual([{ type: "timer.stop" }, { type: "close" }]) + expect(transitionServerConnect(result.state, succeeded(1, "http://new:4096")).effects).toEqual([]) + }) + + test("an edited server that signs out shows it without losing what was typed", () => { + const typing = replay(edit(), [password, field("url", "new:4096"), submitted]) + + const signedOut = transitionServerConnect(typing.state, { + type: "original.synced", + original: original({ unauthorized: true }), + }) + + expect(signedOut.effects).toEqual([]) + expect(signedOut.state).toMatchObject({ status: "submitting", attempt: 1, draft: { url: "new:4096" } }) + expect(selectServerConnectView(signedOut.state, context).signedOut).toBe(true) + expect( + transitionServerConnect(signedOut.state, { type: "original.synced", original: original({ unauthorized: true }) }) + .state, + ).toBe(signedOut.state) + }) + + test("signing in on the connect screen saves and stays on the form", () => { + const result = replay({ kind: "connect", url: "http://localhost:4096" }, [ + field("link", "http://127.0.0.1:4096/auth/connect/abc"), + submitted, + ]) + + expect(result.effects[0]).toMatchObject({ type: "connect.link", preferredUrl: "http://localhost:4096" }) + + const saved = transitionServerConnect(result.state, succeeded(1, "http://localhost:4096", "token")) + expect(saved.state.status).toBe("editing") + expect(closes(saved.effects)).toEqual([]) + expect(saved.effects).toContainEqual({ + type: "save", + action: { type: "connect", http: { url: "http://localhost:4096", password: "token" } }, + }) + }) + + test("an edit starts from the server, on a pairing link when it signed out", () => { + const view = (target: ServerConnectTarget) => selectServerConnectView(createServerConnectState(target), context) + + expect(view(edit({ displayName: "Remote", password: "secret" })).draft).toEqual({ + method: "password", + link: "", + url: "http://old:4096", + name: "Remote", + password: "secret", + }) + expect(view(edit({ unauthorized: true })).draft.method).toBe("link") + expect(view({ kind: "connect", url: "http://localhost:4096" }).draft.url).toBe("http://localhost:4096") + }) + + test.each([ + { + name: "a remote HTTP address from an HTTPS page", + url: "http://192.168.1.2:4096", + surface: "dialog", + key: "server.connect.mixedContent", + }, + { + name: "a loopback address on the dialog", + url: "http://127.0.0.1:4096", + surface: "dialog", + key: "dialog.server.add.error", + }, + { + name: "a loopback address on the screen", + url: "http://127.0.0.1:4096", + surface: "screen", + key: "server.connect.failed", + }, + ] as const)("a failed connection to $name explains why", (input) => { + expect( + formatServerConnectError( + { type: "connection-failed", url: input.url }, + { surface: input.surface, pageHref: "https://app.opencode.ai/", t: (key) => key }, + ), + ).toBe(input.key) + }) + + test("a failed connection off the web never blames mixed content", () => { + expect(formatServerConnectError({ type: "connection-failed", url: "http://192.168.1.2:4096" }, context)).toBe( + "dialog.server.add.error", + ) + }) +}) diff --git a/packages/app/src/servers/connect/machine.ts b/packages/app/src/servers/connect/machine.ts new file mode 100644 index 000000000000..4e442255be7c --- /dev/null +++ b/packages/app/src/servers/connect/machine.ts @@ -0,0 +1,333 @@ +import type { ServerConnection } from "@/runtime/server/registry" +import { isMixedContent } from "./browser" +import type { ConnectMethod } from "./method" +import { bareServerAddress, legacyPairingLink, pairingLink, serverAddress } from "./pairing" + +/** + * A backstop for a transport that ignores its abort signal. Above the slowest real path: redeeming a pairing link + * (5 s, then up to 6 s choosing an address) and two 30 s health checks (the edited address, then the paired one). + */ +export const SERVER_CONNECT_TIMEOUT_MS = 75_000 + +/** The saved server an edit form started from, as it is now. */ +export type ServerOriginal = { + readonly url: string + readonly displayName: string | undefined + readonly password: string | undefined + readonly unauthorized: boolean +} + +/** What the form saves to: the connect screen, a new server, or an edited one. */ +export type ServerConnectTarget = + | { readonly kind: "connect"; readonly url: string | undefined } + | { readonly kind: "add" } + | { readonly kind: "edit"; readonly original: ServerOriginal } + +export type ServerConnectDraft = { + readonly method: ConnectMethod + readonly link: string + readonly url: string + readonly name: string + readonly password: string +} + +export type ServerConnectField = "link" | "url" | "name" | "password" + +export type ServerConnectError = + | { readonly type: "link-invalid" } + | { readonly type: "link-legacy" } + | { readonly type: "address-invalid" } + /** Already localized by `useRedeemPairing`. */ + | { readonly type: "redeem"; readonly message: string } + | { readonly type: "connection-failed"; readonly url: string } + +export type ServerSaveAction = + | { readonly type: "connect"; readonly http: ServerConnection.HttpBase } + | { readonly type: "add"; readonly connection: ServerConnection.Http } + | { readonly type: "replace"; readonly originalUrl: string; readonly connection: ServerConnection.Http } + +type Form = { + readonly attempt: number + readonly target: ServerConnectTarget + readonly draft: ServerConnectDraft +} + +/** + * `submitting` carries the attempt its results must match. `closed` keeps the draft so the dialog shows its values + * while it animates out, and ignores every later event, so the form closes at most once. + */ +export type ServerConnectState = + | (Form & { readonly status: "editing"; readonly error?: ServerConnectError }) + | (Form & { readonly status: "scanning" }) + | (Form & { + readonly status: "submitting" + /** The address a timeout reports, to tell a blocked plain-HTTP address from an unreachable one. */ + readonly fallbackUrl: string + }) + | (Form & { readonly status: "closed" }) + +export type ServerConnectEvent = + | { readonly type: "method.changed"; readonly method: ConnectMethod } + | { readonly type: "field.changed"; readonly field: ServerConnectField; readonly value: string } + | { readonly type: "scan.started" } + | { readonly type: "scan.cancelled" } + | { readonly type: "scan.completed"; readonly link: string } + | { readonly type: "submitted" } + | { readonly type: "submit.succeeded"; readonly attempt: number; readonly http: ServerConnection.HttpBase } + | { readonly type: "submit.failed"; readonly attempt: number; readonly error: ServerConnectError } + | { readonly type: "submit.timed-out"; readonly attempt: number } + /** The edited server as the registry lists it now; undefined once it is removed. */ + | { readonly type: "original.synced"; readonly original: ServerOriginal | undefined } + | { readonly type: "disposed" } + +export type ServerConnectEffect = + | { + readonly type: "connect.link" + readonly attempt: number + readonly link: string + /** A pairing token works on every address of its server, so signing in again keeps this one when it answers. */ + readonly preferredUrl: string | undefined + readonly fallbackUrl: string + } + | { 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" } + | { readonly type: "save"; readonly action: ServerSaveAction } + | { readonly type: "close"; readonly saved?: ServerConnection.Http } + +export type ServerConnectTransition = { + readonly state: ServerConnectState + readonly effects: readonly ServerConnectEffect[] +} + +export function createServerConnectState(target: ServerConnectTarget): ServerConnectState { + return { status: "editing", attempt: 0, target, draft: initialDraft(target) } +} + +export function transitionServerConnect(state: ServerConnectState, event: ServerConnectEvent): ServerConnectTransition { + const same = { state, effects: [] } + + if (state.status === "closed") return same + + if (event.type === "disposed") + return { state: { ...form(state), status: "closed" }, effects: state.status === "submitting" ? [stop] : [] } + + if (event.type === "original.synced") return synced(state, event.original) + + if (state.status === "scanning") { + if (event.type === "scan.cancelled") return { state: { ...form(state), status: "editing" }, effects: [] } + + if (event.type === "scan.completed") return submit(state, { ...state.draft, method: "link", link: event.link }) + + return same + } + + if (state.status === "submitting") { + if ( + (event.type !== "submit.succeeded" && event.type !== "submit.failed" && event.type !== "submit.timed-out") || + event.attempt !== state.attempt + ) + return same + + if (event.type === "submit.succeeded") return saved(state, event.http) + + const error: ServerConnectError = + event.type === "submit.failed" ? event.error : { type: "connection-failed", url: state.fallbackUrl } + + return { state: { ...form(state), status: "editing", error }, effects: [stop] } + } + + if (event.type === "method.changed") { + if (state.draft.method === event.method && !state.error) return same + + return { state: editing(state, { ...state.draft, method: event.method }), effects: [] } + } + + if (event.type === "field.changed") { + if (state.draft[event.field] === event.value && !state.error) return same + + 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 === "submitted") return submit(state, state.draft) + + return same +} + +/** The i18n keys a connect error can show; a redeem error carries its own text. */ +export type ServerConnectErrorKey = + | "server.connect.link.invalid" + | "server.connect.link.legacy" + | "server.connect.address.invalid" + | "server.connect.mixedContent" + | "server.connect.failed" + | "dialog.server.add.error" + +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 +} + +export function formatServerConnectError(error: ServerConnectError, context: ServerConnectErrorContext) { + if (error.type === "redeem") return error.message + + if (error.type === "link-invalid") return context.t("server.connect.link.invalid") + + if (error.type === "link-legacy") return context.t("server.connect.link.legacy") + + if (error.type === "address-invalid") return context.t("server.connect.address.invalid") + + if (context.pageHref && isMixedContent(context.pageHref, error.url)) return context.t("server.connect.mixedContent") + + return context.t(context.surface === "screen" ? "server.connect.failed" : "dialog.server.add.error") +} + +export function selectServerConnectView(state: ServerConnectState, context: ServerConnectErrorContext) { + const primary = state.draft.method === "link" ? state.draft.link : state.draft.url + + return { + scanning: state.status === "scanning", + busy: state.status === "submitting", + disabled: state.status !== "editing", + canSubmit: state.status === "editing" && primary.trim().length > 0, + signedOut: state.target.kind === "edit" && state.target.original.unauthorized, + draft: state.draft, + error: state.status === "editing" && state.error ? formatServerConnectError(state.error, context) : undefined, + } +} + +export type ServerConnectView = ReturnType + +const stop = { type: "timer.stop" } as const + +function initialDraft(target: ServerConnectTarget): ServerConnectDraft { + if (target.kind !== "edit") + return { + method: "link", + link: "", + url: target.kind === "connect" ? (target.url ?? "") : "", + name: "", + password: "", + } + + // A signed-out server needs a new pairing link; otherwise editing starts from its address. + return { + method: target.original.unauthorized ? "link" : "password", + link: "", + url: target.original.url, + name: target.original.displayName ?? "", + password: target.original.password ?? "", + } +} + +function form(state: Form): Form { + return { attempt: state.attempt, 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 } +} + +// Where the form points: a pasted or scanned pairing link wins, in either field; else the address and password. +function submit(state: Form, draft: ServerConnectDraft): ServerConnectTransition { + const value = draft.method === "link" ? draft.link : draft.url + const link = pairingLink(value) + const attempt = state.attempt + 1 + const timer = { type: "timer.start", attempt, timeoutMs: SERVER_CONNECT_TIMEOUT_MS } as const + const original = state.target.kind === "edit" ? state.target.original : undefined + + if (link) { + const preferredUrl = original?.url ?? (state.target.kind === "connect" ? state.target.url : undefined) + const fallbackUrl = preferredUrl ?? link.urls[0] ?? value + + return { + state: { status: "submitting", attempt, target: state.target, draft, fallbackUrl }, + effects: [{ type: "connect.link", attempt, link: value, preferredUrl, fallbackUrl }, timer], + } + } + + if (legacyPairingLink(value)) return { state: editing(state, draft, { type: "link-legacy" }), effects: [] } + + if (draft.method === "link") { + const address = bareServerAddress(value) + + if (!address) return { state: editing(state, draft, { type: "link-invalid" }), effects: [] } + + // A server address typed here belongs to the password form. + return { state: editing(state, { ...draft, method: "password", link: "", url: address }), effects: [] } + } + + const url = serverAddress(value) + + if (!url) return { state: editing(state, draft, { type: "address-invalid" }), effects: [] } + const password = draft.password || undefined + + // Nothing changed: close, unless the server rejects these credentials, so saving checks them and the action that + // asked for sign-in can continue. + if ( + original && + !original.unauthorized && + url === original.url && + (draft.name.trim() || undefined) === original.displayName && + password === original.password + ) + return { state: { ...form(state), draft, status: "closed" }, effects: [{ type: "close" }] } + + const http = password ? { url, password } : { url } + + return { + state: { status: "submitting", attempt, target: state.target, draft, fallbackUrl: url }, + effects: [{ type: "connect.http", attempt, http }, timer], + } +} + +function saved(state: Form, http: ServerConnection.HttpBase): ServerConnectTransition { + if (state.target.kind === "connect") + return { + state: { ...form(state), status: "editing" }, + effects: [stop, { type: "save", action: { type: "connect", http } }], + } + + const connection: ServerConnection.Http = { type: "http", displayName: state.draft.name.trim() || undefined, http } + const original = state.target.kind === "edit" ? state.target.original : undefined + + const action: ServerSaveAction = + original && original.url !== http.url + ? { type: "replace", originalUrl: original.url, connection } + : { type: "add", connection } + + return { + state: { ...form(state), status: "closed" }, + effects: [stop, { type: "save", action }, { type: "close", saved: connection }], + } +} + +function synced( + state: Exclude, + original: ServerOriginal | undefined, +): ServerConnectTransition { + 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" }], + } + + const current = state.target.original + + if ( + current.url === original.url && + current.displayName === original.displayName && + current.password === original.password && + current.unauthorized === original.unauthorized + ) + return { state, effects: [] } + + return { state: { ...state, target: { kind: "edit", original } }, effects: [] } +} diff --git a/packages/app/src/servers/connect/screen.tsx b/packages/app/src/servers/connect/screen.tsx index 247c3604f1de..45598c4a87ce 100644 --- a/packages/app/src/servers/connect/screen.tsx +++ b/packages/app/src/servers/connect/screen.tsx @@ -1,18 +1,12 @@ import { lazy, Show, Suspense } from "solid-js" -import { createStore } from "solid-js/store" -import { useMutation } from "@tanstack/solid-query" 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 { useCheckServerHealth } from "@/runtime/server/health" -import { ServerConnection, useServers } from "@/runtime/server/registry" -import { bareServerAddress, serverAddress, type Pairing } from "./pairing" -import { useRedeemPairing } from "./redeem" -import { isMixedContent } from "./browser" import { cameraHint, createCameraAvailability } from "./camera" -import { ConnectMethodSwitch, type ConnectMethod } from "./method" +import { createServerConnectController } from "./controller" +import { ConnectMethodSwitch } from "./method" import "./screen.css" const PairingScanner = lazy(() => import("./scanner").then((module) => ({ default: module.PairingScanner }))) @@ -20,96 +14,10 @@ const PairingScanner = lazy(() => import("./scanner").then((module) => ({ defaul export function ConnectServerScreen(props: { url?: string } = {}) { const language = useLanguage() const platform = usePlatform() - const servers = useServers() - const check = useCheckServerHealth() - const redeem = useRedeemPairing() const camera = createCameraAvailability() - - const [state, setState] = createStore<{ - method: ConnectMethod - link: string - url: string - password: string - error: string - scanning: boolean - }>({ - method: "link", - link: "", - url: props.url ?? "", - password: "", - error: "", - scanning: false, - }) - - // A pairing token works on every address of its server. Signing in again to the server that signed out keeps its - // address (e.g. localhost) even when the link names another one (e.g. 127.0.0.1 from opencode pair). - const target = async (pairing: Pairing) => { - if (!props.url || props.url === pairing.url) return pairing - const http = { url: props.url, password: pairing.password } - - return (await check(http)).type === "healthy" ? http : pairing - } - - const connect = async (http: ServerConnection.HttpBase) => { - const result = await check(http) - - if (result.type !== "healthy") { - setState("error", connectionError(http.url)) - - return - } - - // Signing in again keeps the name the user gave this server. - const existing = servers.list.find( - (server): server is ServerConnection.Http => server.type === "http" && server.http.url === http.url, - ) - - servers.add(existing ? { ...existing, http } : { type: "http", http }) - } - - const connectionError = (url: string) => - language.t( - platform.platform === "web" && isMixedContent(location.href, url) - ? "server.connect.mixedContent" - : "server.connect.failed", - ) - - const request = useMutation(() => ({ - mutationFn: async () => { - if (state.method === "link") { - const redeemed = await redeem(state.link) - - if (redeemed && "error" in redeemed) return void setState("error", redeemed.error) - - if (redeemed) return connect(await target(redeemed.pairing)) - // A server address typed here belongs to the password form. - const address = bareServerAddress(state.link) - - if (address) return void setState({ method: "password", url: address, link: "", error: "" }) - - return void setState("error", language.t("server.connect.link.invalid")) - } - - // A pairing link pasted into the address field still pairs. - const redeemed = await redeem(state.url) - - if (redeemed && "error" in redeemed) return void setState("error", redeemed.error) - - if (redeemed) return connect(await target(redeemed.pairing)) - const url = serverAddress(state.url) - - if (!url) return void setState("error", language.t("server.connect.address.invalid")) - - await connect({ url, password: state.password || undefined }) - }, - onError: () => setState("error", connectionError(state.method === "link" ? state.link : state.url)), - })) - - const submit = () => { - if (request.isPending) return - setState("error", "") - request.mutate() - } + // 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 return (
@@ -120,23 +28,22 @@ export function ConnectServerScreen(props: { url?: string } = {}) {

{language.t("server.connect.title")}

- {language.t(state.method === "link" ? "server.connect.description.pairing" : "server.connect.description")} + {language.t( + view().draft.method === "link" ? "server.connect.description.pairing" : "server.connect.description", + )}

{language.t("server.connect.camera.starting")}

}> { - setState("scanning", false) + form.dispatch({ type: "scan.cancelled" }) void camera.refetch() }} - onScan={(link) => { - setState({ method: "link", link, error: "", scanning: false }) - request.mutate() - }} + onScan={(link) => form.dispatch({ type: "scan.completed", link })} /> } @@ -144,11 +51,11 @@ export function ConnectServerScreen(props: { url?: string } = {}) {
{ event.preventDefault() - submit() + form.dispatch({ type: "submitted" }) }} > @@ -163,10 +70,12 @@ export function ConnectServerScreen(props: { url?: string } = {}) { required appearance="large" placeholder={language.t("server.connect.link.placeholder")} - value={state.link} - disabled={request.isPending} - aria-describedby={state.error ? "server-connect-error" : undefined} - onInput={(event) => setState({ link: event.currentTarget.value, error: "" })} + value={view().draft.link} + disabled={view().disabled} + aria-describedby={view().error ? "server-connect-error" : undefined} + onInput={(event) => + form.dispatch({ type: "field.changed", field: "link", value: event.currentTarget.value }) + } /> } @@ -185,10 +94,12 @@ export function ConnectServerScreen(props: { url?: string } = {}) { required appearance="large" placeholder={language.t("dialog.server.add.placeholder")} - value={state.url} - disabled={request.isPending} - aria-describedby={state.error ? "server-connect-error" : undefined} - onInput={(event) => setState({ url: event.currentTarget.value, error: "" })} + value={view().draft.url} + disabled={view().disabled} + aria-describedby={view().error ? "server-connect-error" : undefined} + onInput={(event) => + form.dispatch({ type: "field.changed", field: "url", value: event.currentTarget.value }) + } />
@@ -199,31 +110,28 @@ export function ConnectServerScreen(props: { url?: string } = {}) { type="password" autocomplete="current-password" appearance="large" - value={state.password} - disabled={request.isPending} + value={view().draft.password} + disabled={view().disabled} aria-describedby="server-connect-password-hint" - onInput={(event) => setState({ password: event.currentTarget.value, error: "" })} + onInput={(event) => + form.dispatch({ type: "field.changed", field: "password", value: event.currentTarget.value }) + } />

{language.t("server.connect.password.hint")}

- + - - + {language.t(cameraHint())}

} @@ -231,19 +139,19 @@ export function ConnectServerScreen(props: { url?: string } = {}) {
setState({ method, error: "" })} + method={view().draft.method} + disabled={view().disabled} + onChange={(method) => form.dispatch({ type: "method.changed", method })} /> - +