diff --git a/packages/app/e2e/regression/session-location-sync.spec.ts b/packages/app/e2e/regression/session-location-sync.spec.ts index d189c92dca9..daf37da3403 100644 --- a/packages/app/e2e/regression/session-location-sync.spec.ts +++ b/packages/app/e2e/regression/session-location-sync.spec.ts @@ -115,9 +115,26 @@ test("replaces the composer when the location is not found and recovers by movin // A typed not-found answer is final; retrying cannot succeed until the folder changes. expect(requests).toBe(1) - await transport.waitForConnection() + const connection = await transport.waitForConnection() await page.getByRole("button", { name: "Choose worktree", exact: true }).click() - await page.getByRole("menuitem", { name: "existing-worktree", exact: true }).click() + const worktree = page.getByRole("menuitem", { name: "existing-worktree", exact: true }) + await expect(worktree).toBeVisible() + + // Reconnecting checks the folder again without remounting the missing view, so the open menu survives. + const rechecked = page.waitForResponse( + (response) => + new URL(response.url()).searchParams.get("location[directory]") === directory && response.status() === 404, + ) + + await transport.close() + await transport.waitForConnection({ after: connection.id }) + await rechecked + expect(requests).toBe(2) + await expect(worktree).toBeVisible() + // The open menu hides the page from role locators. + await expect(page.getByText("Session location unavailable", { exact: true })).toBeVisible() + + await worktree.click() await expect.poll(() => moves).toEqual([{ directory: destination }]) session.directory = destination diff --git a/packages/app/src/session/composer/region.tsx b/packages/app/src/session/composer/region.tsx index 7e9151d09bf..d02d8ba3f92 100644 --- a/packages/app/src/session/composer/region.tsx +++ b/packages/app/src/session/composer/region.tsx @@ -429,14 +429,24 @@ export function ActiveSessionComposerRegion(props: { const openRoute = useOpenSessionRoute() // Only the server's LocationNotFoundError for the session's own Location replaces the composer. - const missing = createMemo(() => { - const ref = location().missing - const info = props.session.data.info() + // A refetched session info (on reconnect) must not remount the keyed view and close its open menu. + const missing = createMemo( + () => { + const ref = location().missing + const info = props.session.data.info() - if (!ref || !info || !sameDirectory(info.location.directory, ref.directory)) return + if (!ref || !info || !sameDirectory(info.location.directory, ref.directory)) return - return { directory: info.location.directory, sessionID: info.id, projectID: info.projectID } - }) + return { directory: info.location.directory, sessionID: info.id, projectID: info.projectID } + }, + undefined, + { + equals: (previous, next) => + previous?.directory === next?.directory && + previous?.sessionID === next?.sessionID && + previous?.projectID === next?.projectID, + }, + ) // Subagents count while their session runs, or while their blocking call waits for its child session. const subagents = createMemo(() => diff --git a/packages/app/src/voice/call.ts b/packages/app/src/voice/call.ts index 224f6285a10..f898cf5067f 100644 --- a/packages/app/src/voice/call.ts +++ b/packages/app/src/voice/call.ts @@ -19,7 +19,6 @@ import { import { createVoiceDelegationState, delegating, - hasDelegation, responseEvent, transitionVoiceDelegation, type VoiceDelegationEffect, @@ -129,8 +128,8 @@ export function createVoiceCall(input: { const id = event.delegation.id const viewing = viewedSession(input.call()) - // A repeated event must not capture the transcript again: that would clear this delegation's reservation. - if (!viewing || hasDelegation(delegations, id)) return + // A repeated event is harmless: the tail keeps the reservation and the delegation machine ignores it. + if (!viewing) return dispatch({ type: "delegation.created", id, sessionID: viewing.id, transcript: tail.capture(id) }) return @@ -313,6 +312,7 @@ export function createVoiceCall(input: { connection = undefined dispatchReply({ type: "call.disconnected" }) dispatch({ type: "call.reset" }) + tail.clearReservations() if (!transport) return Promise.resolve() diff --git a/packages/app/src/voice/tail-machine.test.ts b/packages/app/src/voice/tail-machine.test.ts new file mode 100644 index 00000000000..c2671c8b445 --- /dev/null +++ b/packages/app/src/voice/tail-machine.test.ts @@ -0,0 +1,124 @@ +import { expect, test } from "bun:test" +import { + capturedLines, + createTranscriptTailState, + MAX_UTTERANCES, + transcriptLines, + transitionTranscriptTail, + type TranscriptRole, + type TranscriptTailEvent, + type TranscriptTailState, +} from "./tail-machine" + +const said = (role: TranscriptRole, delta: string, at: number): TranscriptTailEvent => ({ + type: "utterance.appended", + role, + delta, + at, +}) + +const captured = (id: string): TranscriptTailEvent => ({ type: "delegation.captured", id }) + +const accepted = (id: string): TranscriptTailEvent => ({ type: "delegation.accepted", id }) + +const released = (id: string): TranscriptTailEvent => ({ type: "delegation.released", id }) + +function replay(events: TranscriptTailEvent[], start = createTranscriptTailState()) { + return events.reduce(transitionTranscriptTail, start) +} + +function capture(state: TranscriptTailState, id: string) { + const next = transitionTranscriptTail(state, captured(id)) + + return { state: next, lines: capturedLines(next, id) } +} + +test("a repeated capture keeps the delegation's reservation", () => { + const first = capture(replay([said("user", "Fix the bug", 1_000)]), "del_1") + expect(first.lines).toEqual(["user: Fix the bug"]) + + const repeated = transitionTranscriptTail(first.state, captured("del_1")) + expect(repeated).toBe(first.state) + expect(capturedLines(repeated, "del_1")).toEqual(["user: Fix the bug"]) + // The words stay reserved, so an overlapping delegation does not take them. + const overlap = capture(repeated, "del_2") + expect(overlap.lines).toEqual([]) + + const done = replay([accepted("del_1")], overlap.state) + expect(done.entries[0]?.delivery).toEqual({ status: "sent", revision: 1 }) + expect(capture(done, "del_3").lines).toEqual([]) +}) + +test("blank deltas start no utterance and do not mark the next one as updated", () => { + const start = createTranscriptTailState() + const blank = replay([said("user", "", 1_000), said("user", " ", 1_100)], start) + expect(blank).toBe(start) + expect(blank.entries.at(-1)).toBeUndefined() + expect(transcriptLines(blank)).toBe("") + + const empty = capture(blank, "del_1") + expect(empty.lines).toEqual([]) + const spoken = replay([released("del_1"), said("user", "Hello", 1_200)], empty.state) + expect(capture(spoken, "del_2").lines).toEqual(["user: Hello"]) +}) + +test("trailing spacing on a sent utterance does not send it again", () => { + const sent = replay([said("user", "Hello", 1_000), captured("del_1"), accepted("del_1")]) + const spaced = transitionTranscriptTail(sent, said("user", " ", 1_200)) + expect(spaced.entries[0]?.text).toBe("Hello ") + expect(spaced.entries[0]?.delivery).toEqual({ status: "sent", revision: 1 }) + expect(capture(spaced, "del_2").lines).toEqual([]) + + const worded = transitionTranscriptTail(spaced, said("user", "world", 1_400)) + expect(worded.entries[0]?.delivery).toEqual({ status: "revised", revision: 2, sent: 1 }) + expect(capture(worded, "del_3").lines).toEqual(["user (updated utterance): Hello world"]) +}) + +test("an empty delta does not extend the merge window", () => { + const state = replay([said("user", "Hello", 1_000), said("user", "", 2_000)]) + expect(state.entries[0]?.at).toBe(1_000) + expect(transitionTranscriptTail(state, said("user", "Again", 2_600)).entries).toHaveLength(2) +}) + +test("clearing reservations offers their words to the next delegation", () => { + const reserved = replay([ + said("user", "Open the session", 1_000), + captured("del_1"), + said("assistant", "Opening it", 3_000), + captured("del_2"), + ]) + + expect(capture(reserved, "del_3").lines).toEqual([]) + + const cleared = transitionTranscriptTail(reserved, { type: "reservations.cleared" }) + expect(cleared.reservations.size).toBe(0) + expect(capture(cleared, "del_3").lines).toEqual(["user: Open the session", "assistant: Opening it"]) + expect(transitionTranscriptTail(cleared, { type: "reservations.cleared" })).toBe(cleared) +}) + +test("an unknown delegation changes nothing", () => { + const state = replay([said("user", "Hello", 1_000), captured("del_1")]) + expect(transitionTranscriptTail(state, accepted("del_x"))).toBe(state) + expect(transitionTranscriptTail(state, released("del_x"))).toBe(state) +}) + +test("a role switch or a 1.5 s pause starts a new utterance", () => { + const state = replay([ + said("user", "One", 1_000), + said("assistant", "Two", 1_100), + said("assistant", " more", 2_599), + said("assistant", "Three", 4_099), + ]) + + expect(state.entries.map((entry) => entry.text)).toEqual(["One", "Two more", "Three"]) +}) + +test("the transcript keeps the newest utterances", () => { + const state = replay( + Array.from({ length: MAX_UTTERANCES + 2 }, (_, index) => said("user", `Line ${index}`, index * 2_000)), + ) + + expect(state.entries).toHaveLength(MAX_UTTERANCES) + expect(state.entries[0]?.text).toBe("Line 2") + expect(state.nextID).toBe(MAX_UTTERANCES + 2) +}) diff --git a/packages/app/src/voice/tail-machine.ts b/packages/app/src/voice/tail-machine.ts new file mode 100644 index 00000000000..eb73ed6cd7b --- /dev/null +++ b/packages/app/src/voice/tail-machine.ts @@ -0,0 +1,155 @@ +export const UTTERANCE_MERGE_WINDOW = 1_500 + +export const MAX_UTTERANCES = 60 + +export type TranscriptRole = "user" | "assistant" + +/** How much of an utterance the delegator has heard; `sent` is the revision it last heard. */ +export type UtteranceDelivery = + | { readonly status: "unsent"; readonly revision: number } + | { readonly status: "sent"; readonly revision: number } + | { readonly status: "revised"; readonly revision: number; readonly sent: number } + +export type TranscriptUtterance = { + readonly id: number + readonly role: TranscriptRole + readonly text: string + readonly at: number + readonly delivery: UtteranceDelivery +} + +/** The utterance revisions an open delegation captured, and the lines it was given. */ +export type TranscriptReservation = { + readonly revisions: ReadonlyMap + readonly lines: readonly string[] +} + +export type TranscriptTailState = { + readonly nextID: number + readonly entries: readonly TranscriptUtterance[] + readonly reservations: ReadonlyMap +} + +export type TranscriptTailEvent = + | { readonly type: "utterance.appended"; readonly role: TranscriptRole; readonly delta: string; readonly at: number } + | { readonly type: "delegation.captured"; readonly id: string } + | { readonly type: "delegation.accepted"; readonly id: string } + | { readonly type: "delegation.released"; readonly id: string } + | { readonly type: "reservations.cleared" } + +export function createTranscriptTailState(): TranscriptTailState { + return { nextID: 0, entries: [], reservations: new Map() } +} + +// Live sends transcript deltas, not finalized messages. Keep one utterance across adjacent deltas, +// and reserve its revision while a delegation runs. +export function transitionTranscriptTail(state: TranscriptTailState, event: TranscriptTailEvent): TranscriptTailState { + if (event.type === "utterance.appended") return appended(state, event) + + if (event.type === "delegation.captured") { + // A repeated capture keeps the reservation it already holds. + if (state.reservations.has(event.id)) return state + const pending = state.entries.filter((entry) => entry.delivery.revision > covered(state, entry)) + + return { + ...state, + reservations: new Map(state.reservations).set(event.id, { + revisions: new Map(pending.map((entry) => [entry.id, entry.delivery.revision])), + lines: pending.map( + (entry) => + `${entry.role}${entry.delivery.status === "revised" ? " (updated utterance)" : ""}: ${entry.text.trim()}`, + ), + }), + } + } + + if (event.type === "reservations.cleared") + return state.reservations.size ? { ...state, reservations: new Map() } : state + const reservation = state.reservations.get(event.id) + + if (!reservation) return state + const reservations = new Map(state.reservations) + reservations.delete(event.id) + + if (event.type === "delegation.released") return { ...state, reservations } + + return { + ...state, + reservations, + entries: state.entries.map((entry) => { + const reserved = reservation.revisions.get(entry.id) + + if (reserved === undefined || reserved <= heard(entry.delivery)) return entry + + if (reserved >= entry.delivery.revision) + return { ...entry, delivery: { status: "sent", revision: entry.delivery.revision } } + + return { ...entry, delivery: { status: "revised", revision: entry.delivery.revision, sent: reserved } } + }), + } +} + +/** The recent transcript both sides spoke, for Live's instructions. */ +export function transcriptLines(state: TranscriptTailState) { + return state.entries + .slice(-12) + .map((entry) => `${entry.role}: ${entry.text}`) + .join("\n") + .slice(-2000) +} + +export function capturedLines(state: TranscriptTailState, id: string) { + return state.reservations.get(id)?.lines ?? [] +} + +function appended(state: TranscriptTailState, event: Extract) { + if (!event.delta) return state + const previous = state.entries.at(-1) + + if (previous?.role === event.role && event.at - previous.at < UTTERANCE_MERGE_WINDOW) { + const text = previous.text + event.delta + // Spacing is kept for the caption, but only new words make the utterance worth sending again. + const delivery = text.trim() === previous.text.trim() ? previous.delivery : revise(previous.delivery) + + return { ...state, entries: [...state.entries.slice(0, -1), { ...previous, text, at: event.at, delivery }] } + } + + if (!event.delta.trim()) return state + + return { + ...state, + nextID: state.nextID + 1, + entries: [ + ...state.entries, + { + id: state.nextID, + role: event.role, + text: event.delta, + at: event.at, + delivery: { status: "unsent", revision: 1 } as const, + }, + ].slice(-MAX_UTTERANCES), + } +} + +function revise(delivery: UtteranceDelivery): UtteranceDelivery { + if (delivery.status === "unsent") return { status: "unsent", revision: delivery.revision + 1 } + + return { status: "revised", revision: delivery.revision + 1, sent: heard(delivery) } +} + +function heard(delivery: UtteranceDelivery) { + if (delivery.status === "unsent") return 0 + + if (delivery.status === "sent") return delivery.revision + + return delivery.sent +} + +/** The newest revision of an utterance that the delegator has heard or an open delegation holds. */ +function covered(state: TranscriptTailState, entry: TranscriptUtterance) { + return Math.max( + heard(entry.delivery), + ...[...state.reservations.values()].map((reservation) => reservation.revisions.get(entry.id) ?? 0), + ) +} diff --git a/packages/app/src/voice/tail.ts b/packages/app/src/voice/tail.ts index 535fd798080..6c9c2ec3dee 100644 --- a/packages/app/src/voice/tail.ts +++ b/packages/app/src/voice/tail.ts @@ -1,65 +1,55 @@ -type Utterance = { id: number; role: "user" | "assistant"; text: string; at: number; version: number; sent: number } +import { + capturedLines, + createTranscriptTailState, + transcriptLines, + transitionTranscriptTail, + type TranscriptRole, + type TranscriptTailEvent, +} from "./tail-machine" -// Live sends transcript deltas, not finalized messages. Keep one utterance -// across adjacent deltas, and reserve its version while a delegation runs. +/** Drives the transcript machine in `tail-machine.ts` for one call. */ export class TranscriptTail { - private entries: Utterance[] = [] - private next = 0 - private reservations = new Map>() + private state = createTranscriptTailState() - append(role: Utterance["role"], delta: string) { - const previous = this.entries.at(-1) + /** The utterance's text so far, or "" when the delta added nothing to show. */ + append(role: TranscriptRole, delta: string) { + const previous = this.state + this.dispatch({ type: "utterance.appended", role, delta, at: Date.now() }) - if (previous?.role === role && Date.now() - previous.at < 1500) { - previous.text += delta - previous.at = Date.now() - previous.version++ + if (this.state === previous) return "" - return previous.text - } - - this.entries.push({ id: this.next++, role, text: delta, at: Date.now(), version: 1, sent: 0 }) - this.entries = this.entries.slice(-60) - - return delta + return this.state.entries.at(-1)?.text ?? "" } /** Both sides' lines since the previous delegation, as the iOS app's `transcript_delta`. */ capture(id: string) { - const pending = this.entries.filter( - (entry) => - entry.version > - Math.max(entry.sent, ...[...this.reservations.values()].map((versions) => versions.get(entry.id) ?? 0)), - ) + this.dispatch({ type: "delegation.captured", id }) - const versions = new Map(pending.map((entry) => [entry.id, entry.version])) - this.reservations.set(id, versions) - - return pending.map((entry) => `${entry.role}${entry.sent ? " (updated utterance)" : ""}: ${entry.text.trim()}`) + return [...capturedLines(this.state, id)] } accept(id: string) { - const versions = this.reservations.get(id) - this.entries.forEach((entry) => { - entry.sent = Math.max(entry.sent, versions?.get(entry.id) ?? 0) - }) - this.reservations.delete(id) + this.dispatch({ type: "delegation.accepted", id }) } release(id: string) { - this.reservations.delete(id) + this.dispatch({ type: "delegation.released", id }) + } + + clearReservations() { + this.dispatch({ type: "reservations.cleared" }) } get lines() { - return this.entries - .slice(-12) - .map((entry) => `${entry.role}: ${entry.text}`) - .join("\n") - .slice(-2000) + return transcriptLines(this.state) } /** The newest utterance; it changes only when `append` starts a new one. */ get latest() { - return this.entries.at(-1)?.id + return this.state.entries.at(-1)?.id + } + + private dispatch(event: TranscriptTailEvent) { + this.state = transitionTranscriptTail(this.state, event) } } diff --git a/packages/app/src/workspaces/location-machine.test.ts b/packages/app/src/workspaces/location-machine.test.ts new file mode 100644 index 00000000000..c549cf579d1 --- /dev/null +++ b/packages/app/src/workspaces/location-machine.test.ts @@ -0,0 +1,135 @@ +import { expect, test } from "bun:test" +import { + createLocationSyncState, + LOCATION_SYNC_TIMEOUT, + missingLocation, + transitionLocationSync, + type LocationSyncEffect, + type LocationSyncEvent, + type LocationSyncState, +} from "./location-machine" + +const deleted = { directory: "/projects/deleted-worktree" } + +const other = { directory: "/projects/existing-worktree" } + +const target = (location: { directory: string }, connected = true): LocationSyncEvent => ({ + type: "target.updated", + location, + connected, +}) + +function replay(events: LocationSyncEvent[], start: LocationSyncState = createLocationSyncState(deleted)) { + return events.reduce( + (result: { state: LocationSyncState; effects: LocationSyncEffect[] }, event) => { + const next = transitionLocationSync(result.state, event) + + return { state: next.state, effects: [...result.effects, ...next.effects] } + }, + { state: start, effects: [] }, + ) +} + +const missing = replay([target(deleted), { type: "sync.missing", attempt: 1 }]).state + +test("a missing folder stays missing while offline and while reconnecting checks it again", () => { + expect(missing.status).toBe("missing") + expect(missingLocation(missing, deleted)).toBe(deleted) + + const offline = transitionLocationSync(missing, target(deleted, false)) + expect(offline.state).toBe(missing) + expect(offline.effects).toEqual([]) + + const checking = transitionLocationSync(missing, target(deleted)) + expect(checking.state).toEqual({ status: "syncing", attempt: 2, retries: 0, location: deleted, missing: true }) + expect(checking.effects).toEqual([{ type: "sync", attempt: 2, location: deleted, timeout: LOCATION_SYNC_TIMEOUT }]) + expect(missingLocation(checking.state, deleted)).toBe(deleted) + + expect(replay([{ type: "sync.missing", attempt: 2 }], checking.state).state.status).toBe("missing") + // Neither a dropped connection nor transient failures prove the folder came back. + expect(replay([target(deleted, false)], checking.state).state).toEqual({ + status: "missing", + attempt: 3, + location: deleted, + }) + + const exhausted = replay( + [ + { type: "sync.failed", attempt: 2 }, + { type: "retry.due", attempt: 3 }, + { type: "sync.timed-out", attempt: 3 }, + { type: "retry.due", attempt: 4 }, + { type: "sync.failed", attempt: 4 }, + ], + checking.state, + ) + + expect(exhausted.state.status).toBe("missing") + expect(missingLocation(exhausted.state, deleted)).toBe(deleted) +}) + +test("a folder that comes back clears the missing view as soon as the server resolves it", () => { + const checking = transitionLocationSync(missing, target(deleted)).state + const resolved = transitionLocationSync(checking, { type: "info.resolved", attempt: 2 }).state + expect(missingLocation(resolved, deleted)).toBeUndefined() + expect(transitionLocationSync(resolved, { type: "sync.succeeded", attempt: 2 }).state.status).toBe("synced") +}) + +test("switching Location drops the previous one's missing state at once", () => { + expect(missingLocation(missing, other)).toBeUndefined() + + const switched = transitionLocationSync(missing, target(other)) + expect(switched.state).toEqual({ status: "syncing", attempt: 2, retries: 0, location: other, missing: false }) + expect(transitionLocationSync(switched.state, { type: "sync.missing", attempt: 1 }).state).toBe(switched.state) + + const offline = transitionLocationSync(missing, target(other, false)) + expect(offline.state).toEqual({ status: "idle", attempt: 2, location: other }) + expect(missingLocation(offline.state, other)).toBeUndefined() +}) + +test("generic failures back off twice and then fail without reporting a missing folder", () => { + const result = replay([ + target(deleted), + { type: "sync.failed", attempt: 1 }, + { type: "retry.due", attempt: 2 }, + { type: "sync.failed", attempt: 2 }, + { type: "retry.due", attempt: 3 }, + { type: "sync.failed", attempt: 3 }, + ]) + + expect(result.effects.filter((effect) => effect.type !== "sync")).toEqual([ + { type: "retry", attempt: 2, delay: 500 }, + { type: "retry", attempt: 3, delay: 1_000 }, + { type: "timer.clear" }, + ]) + expect(result.effects.filter((effect) => effect.type === "sync")).toHaveLength(3) + expect(result.state).toEqual({ status: "failed", attempt: 3, location: deleted }) + expect(missingLocation(result.state, deleted)).toBeUndefined() +}) + +test("a timed-out attempt retries and ignores its late result", () => { + const timedOut = replay([target(deleted), { type: "sync.timed-out", attempt: 1 }]).state + expect(timedOut).toEqual({ status: "waiting-retry", attempt: 2, retries: 1, location: deleted, missing: false }) + + for (const type of ["sync.succeeded", "sync.failed", "sync.missing"] as const) + expect(transitionLocationSync(timedOut, { type, attempt: 1 }).state).toBe(timedOut) +}) + +test("a settled Location syncs again after reconnecting", () => { + const synced = replay([target(deleted), { type: "sync.succeeded", attempt: 1 }]).state + expect(transitionLocationSync(synced, target(deleted)).state).toBe(synced) + + const result = replay([target(deleted, false), target(deleted)], synced) + expect(result.state).toEqual({ status: "syncing", attempt: 3, retries: 0, location: deleted, missing: false }) + expect(result.effects).toEqual([{ type: "sync", attempt: 3, location: deleted, timeout: LOCATION_SYNC_TIMEOUT }]) +}) + +test("disposal clears a pending timer and ignores everything after it", () => { + const syncing = replay([target(deleted)]).state + const disposed = transitionLocationSync(syncing, { type: "disposed" }) + expect(disposed).toEqual({ state: { status: "disposed" }, effects: [{ type: "timer.clear" }] }) + expect(transitionLocationSync(missing, { type: "disposed" }).effects).toEqual([]) + + for (const event of [target(deleted), { type: "sync.succeeded", attempt: 1 }] satisfies LocationSyncEvent[]) + expect(transitionLocationSync(disposed.state, event).state).toBe(disposed.state) +}) diff --git a/packages/app/src/workspaces/location-machine.ts b/packages/app/src/workspaces/location-machine.ts new file mode 100644 index 00000000000..3b2ac337bb4 --- /dev/null +++ b/packages/app/src/workspaces/location-machine.ts @@ -0,0 +1,159 @@ +import type { LocationRef } from "@opencode/client/promise" + +export const LOCATION_SYNC_RETRIES = 2 + +export const LOCATION_SYNC_RETRY_DELAY = 500 + +export const LOCATION_SYNC_TIMEOUT = 30_000 + +/** `missing` on an attempt: the folder was missing before, so the missing view stays while the server checks again. */ +export type LocationSyncState = + | { readonly status: "idle"; readonly attempt: number; readonly location: LocationRef } + | { + readonly status: "syncing" + readonly attempt: number + readonly retries: number + readonly location: LocationRef + readonly missing: boolean + } + | { + readonly status: "waiting-retry" + readonly attempt: number + readonly retries: number + readonly location: LocationRef + readonly missing: boolean + } + | { readonly status: "synced"; readonly attempt: number; readonly location: LocationRef } + | { readonly status: "missing"; readonly attempt: number; readonly location: LocationRef } + | { readonly status: "failed"; readonly attempt: number; readonly location: LocationRef } + | { readonly status: "disposed" } + +export type LocationSyncEvent = + | { readonly type: "target.updated"; readonly location: LocationRef; readonly connected: boolean } + /** The server resolved the Location, so its folder exists. */ + | { readonly type: "info.resolved"; readonly attempt: number } + | { readonly type: "sync.succeeded"; readonly attempt: number } + | { readonly type: "sync.missing"; readonly attempt: number } + | { readonly type: "sync.failed"; readonly attempt: number } + | { readonly type: "sync.timed-out"; readonly attempt: number } + | { readonly type: "retry.due"; readonly attempt: number } + | { readonly type: "disposed" } + +export type LocationSyncEffect = + | { readonly type: "sync"; readonly attempt: number; readonly location: LocationRef; readonly timeout: number } + | { readonly type: "retry"; readonly attempt: number; readonly delay: number } + | { readonly type: "timer.clear" } + +export type LocationSyncTransition = { + readonly state: LocationSyncState + readonly effects: readonly LocationSyncEffect[] +} + +export function createLocationSyncState(location: LocationRef): LocationSyncState { + return { status: "idle", attempt: 0, location } +} + +export function transitionLocationSync(state: LocationSyncState, event: LocationSyncEvent): LocationSyncTransition { + if (state.status === "disposed") return unchanged(state) + + if (event.type === "disposed") return { state: { status: "disposed" }, effects: clearTimer(state) } + + if (event.type === "target.updated") return targetUpdated(state, event) + + if (event.attempt !== state.attempt) return unchanged(state) + + if (event.type === "retry.due") { + if (state.status !== "waiting-retry") return unchanged(state) + + return { + state: { ...state, status: "syncing" }, + effects: [{ type: "sync", attempt: state.attempt, location: state.location, timeout: LOCATION_SYNC_TIMEOUT }], + } + } + + if (state.status !== "syncing") return unchanged(state) + + if (event.type === "info.resolved") + return state.missing ? { state: { ...state, missing: false }, effects: [] } : unchanged(state) + + if (event.type === "sync.succeeded") return settle(state, "synced") + + // A typed not-found answer is final; retrying cannot succeed until the folder changes. + if (event.type === "sync.missing") return settle(state, "missing") + + // Generic failures and timeouts do not prove the folder is missing. + if (state.retries < LOCATION_SYNC_RETRIES) + return { + state: { ...state, status: "waiting-retry", attempt: state.attempt + 1, retries: state.retries + 1 }, + effects: [{ type: "retry", attempt: state.attempt + 1, delay: LOCATION_SYNC_RETRY_DELAY * 2 ** state.retries }], + } + + return settle(state, state.missing ? "missing" : "failed") +} + +/** The Location whose folder is missing, only while it is still the current one. */ +export function missingLocation(state: LocationSyncState, current: LocationRef) { + if (state.status === "disposed" || !sameLocationRef(state.location, current)) return + + if (state.status === "missing") return state.location + + if ((state.status === "syncing" || state.status === "waiting-retry") && state.missing) return state.location +} + +export function sameLocationRef(a: LocationRef, b: LocationRef) { + return a.directory === b.directory && a.workspaceID === b.workspaceID +} + +function targetUpdated( + state: Exclude, + event: Extract, +): LocationSyncTransition { + const attempt = state.attempt + 1 + + // Another Location starts over: nothing about the previous folder carries over. + if (!sameLocationRef(state.location, event.location)) { + if (!event.connected) + return { state: { status: "idle", attempt, location: event.location }, effects: clearTimer(state) } + + return sync(event.location, attempt, false) + } + + if (event.connected) { + if (state.status === "idle") return sync(state.location, attempt, false) + + // Reconnecting checks the folder again without hiding the missing view meanwhile. + if (state.status === "missing") return sync(state.location, attempt, true) + + return unchanged(state) + } + + if (state.status === "idle" || state.status === "missing") return unchanged(state) + + // Offline proves nothing about the folder, so a missing one stays missing. + if ((state.status === "syncing" || state.status === "waiting-retry") && state.missing) + return { state: { status: "missing", attempt, location: state.location }, effects: clearTimer(state) } + + return { state: { status: "idle", attempt, location: state.location }, effects: clearTimer(state) } +} + +function sync(location: LocationRef, attempt: number, missing: boolean): LocationSyncTransition { + return { + state: { status: "syncing", attempt, retries: 0, location, missing }, + effects: [{ type: "sync", attempt, location, timeout: LOCATION_SYNC_TIMEOUT }], + } +} + +function settle( + state: Extract, + status: "synced" | "missing" | "failed", +): LocationSyncTransition { + return { state: { status, attempt: state.attempt, location: state.location }, effects: [{ type: "timer.clear" }] } +} + +function clearTimer(state: LocationSyncState): LocationSyncEffect[] { + return state.status === "syncing" || state.status === "waiting-retry" ? [{ type: "timer.clear" }] : [] +} + +function unchanged(state: LocationSyncState): LocationSyncTransition { + return { state, effects: [] } +} diff --git a/packages/app/src/workspaces/location.tsx b/packages/app/src/workspaces/location.tsx index eb1cf0872a9..2667d882e78 100644 --- a/packages/app/src/workspaces/location.tsx +++ b/packages/app/src/workspaces/location.tsx @@ -1,10 +1,16 @@ import { createSimpleContext } from "@opencode/ui/context" import { isLocationNotFoundError, type LocationGetOutput, type LocationRef } from "@opencode/client/promise" -import { retry } from "@opencode/util/retry" -import { type Accessor, createEffect, createMemo, onCleanup } from "solid-js" -import { createStore } from "solid-js/store" +import { type Accessor, createEffect, createMemo, createSignal, onCleanup, untrack } from "solid-js" import { type LocationContext, useServerSDK } from "@/runtime/server/client" import { useData, useServer } from "@/runtime/server/current" +import { + createLocationSyncState, + missingLocation, + sameLocationRef, + transitionLocationSync, + type LocationSyncEffect, + type LocationSyncEvent, +} from "./location-machine" export type WorkspaceLocation = LocationContext & { readonly ref: LocationRef @@ -26,36 +32,62 @@ const context = createSimpleContext({ workspaceID: props.workspaceID, }), undefined, - { - equals: (previous, next) => previous.directory === next.directory && previous.workspaceID === next.workspaceID, - }, + { equals: sameLocationRef }, ) const current = createMemo(() => data.location.info(ref())) - const [state, setState] = createStore<{ missing?: LocationRef }>({}) + const connected = createMemo(() => serverSDK.connection.status() === "connected") + const [syncState, setSyncState] = createSignal(createLocationSyncState(untrack(ref))) + // The retry delay or the running attempt's timeout; the machine decides when each ends. + let timer: ReturnType | undefined + + function dispatch(event: LocationSyncEvent) { + const next = transitionLocationSync(untrack(syncState), event) + setSyncState(next.state) + next.effects.forEach(perform) + } + + function perform(effect: LocationSyncEffect) { + clearTimeout(timer) + + if (effect.type === "timer.clear") return + + if (effect.type === "retry") { + timer = setTimeout(() => dispatch({ type: "retry.due", attempt: effect.attempt }), effect.delay) + + return + } + + timer = setTimeout(() => dispatch({ type: "sync.timed-out", attempt: effect.attempt }), effect.timeout) + // syncInfo caches its answer, so sync reuses it instead of reading the Location again. + void data.location + .syncInfo(effect.location) + .then(() => { + dispatch({ type: "info.resolved", attempt: effect.attempt }) + + return data.location.sync(effect.location) + }) + .then( + () => dispatch({ type: "sync.succeeded", attempt: effect.attempt }), + (error) => + dispatch({ + type: isLocationNotFoundError(error) ? "sync.missing" : "sync.failed", + attempt: effect.attempt, + }), + ) + } createEffect(() => { - const location = ref() - let stale = false - onCleanup(() => { - stale = true - }) - setState("missing", undefined) - - if (serverSDK.connection.status() !== "connected") return - // Generic sync failures do not prove the directory is missing; only the server's typed - // LocationNotFoundError does, and retrying it cannot succeed until the folder changes. - void retry(() => (stale ? Promise.resolve() : data.location.sync(location)), { - retryIf: (error) => !stale && !isLocationNotFoundError(error), - }).catch((error) => { - if (stale || !isLocationNotFoundError(error)) return - setState("missing", location) - }) + const event = { type: "target.updated", location: ref(), connected: connected() } as const + untrack(() => dispatch(event)) }) + onCleanup(() => dispatch({ type: "disposed" })) + const missing = createMemo(() => missingLocation(syncState(), ref())) + createEffect(() => { const id = current()?.project.id - if (!id || serverSDK.connection.status() !== "connected") return + if (!id || !connected()) return // Showing a Location is the demand for its project's worktree inventory (workspace styling, picker). void server.ctx.sync.worktrees.list(id).then(() => server.ctx.sync.worktrees.refresh(id)) }) @@ -66,7 +98,7 @@ const context = createSimpleContext({ ...location(), ref: ref(), current: current(), - missing: state.missing, + missing: missing(), })) }, })