TypeScript
feat(desktop): keep running threads synced in the background (#13554)
Theo Browne99641fd09a50
diff --git a/apps/web/src/components/desktop/RunningThreadKeepAlive.tsx b/apps/web/src/components/desktop/RunningThreadKeepAlive.tsxnew file mode 100644index 00000000000..68c2c0cf609--- /dev/null+++ b/apps/web/src/components/desktop/RunningThreadKeepAlive.tsx@@ -0,0 +1,14 @@+import { useAtomMount } from "@effect/atom-react";++import { runningThreadKeepAliveAtom } from "../../state/threads";++/**+ * Desktop only. Keeps each running thread subscribed in every enabled+ * environment, so opening one shows live state without a replay or a sync+ * status flash. It mounts the atom without reading it, so thread updates+ * never re-render.+ */+export function RunningThreadKeepAlive() {+ useAtomMount(runningThreadKeepAliveAtom);+ return null;+}diff --git a/apps/web/src/routes/__root.tsx b/apps/web/src/routes/__root.tsxindex eee703ac3f4..8480dc70c71 100644--- a/apps/web/src/routes/__root.tsx+++ b/apps/web/src/routes/__root.tsx@@ -26,6 +26,7 @@ import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstallimport { SshPasswordPromptDialog } from "../components/desktop/SshPasswordPromptDialog";import { SnapShotCoordinator } from "../components/desktop/SnapShotCoordinator";import { DesktopAppActivationCoordinator } from "../components/desktop/DesktopAppActivationCoordinator";+import { RunningThreadKeepAlive } from "../components/desktop/RunningThreadKeepAlive";import { ProviderUpdateLaunchNotification } from "../components/ProviderUpdateLaunchNotification";import { ThreadNotificationCoordinator } from "../components/ThreadNotificationCoordinator";import { ProjectCloneToastCoordinator } from "../components/ProjectCloneToastCoordinator";@@ -43,6 +44,7 @@ import {toastManager,} from "../components/ui/toast";import { resolveAndPersistPreferredEditor } from "../editorPreferences";+import { isElectron } from "../env";import { applyAppearanceFontVariables } from "~/appearanceFonts";import { applyAppearanceContrast } from "~/appearanceContrast";import { useClientSettings } from "../hooks/useSettings";@@ -219,6 +221,7 @@ function RootRouteView() {>{primaryEnvironmentAuthenticated ? <AuthenticatedTracingBootstrap /> : null}{primaryEnvironmentAuthenticated ? <DesktopAppActivationCoordinator /> : null}+ {isElectron ? <RunningThreadKeepAlive /> : null}<RelayClientInstallDialog /><ConnectOnboardingDialog /><SshPasswordPromptDialog />diff --git a/apps/web/src/state/threads.test.ts b/apps/web/src/state/threads.test.tsnew file mode 100644index 00000000000..cf1fc877728--- /dev/null+++ b/apps/web/src/state/threads.test.ts@@ -0,0 +1,200 @@+import {+ EMPTY_ENVIRONMENT_THREAD_STATE,+ type EnvironmentThreadState,+} from "@t3tools/client-runtime/state/threads";+import {+ EnvironmentId,+ ProjectId,+ ProviderInstanceId,+ ThreadId,+ type OrchestrationSessionStatus,+ type OrchestrationThread,+ type OrchestrationThreadShell,+} from "@t3tools/contracts";+import * as Option from "effect/Option";+import { AsyncResult, Atom, AtomRegistry } from "effect/unstable/reactivity";+import { describe, expect, it } from "vite-plus/test";++import { createRunningThreadKeepAliveAtom } from "./threads";++const LOCAL = EnvironmentId.make("local");+const REMOTE = EnvironmentId.make("remote");++function session(threadId: ThreadId, status: OrchestrationSessionStatus) {+ return {+ threadId,+ status,+ providerName: "codex",+ runtimeMode: "full-access",+ activeTurnId: null,+ lastError: null,+ updatedAt: "2026-09-24T00:00:00.000Z",+ } satisfies OrchestrationThread["session"];+}++function shell(id: string, status: OrchestrationSessionStatus | null) {+ const threadId = ThreadId.make(id);+ return {+ id: threadId,+ session: status === null ? null : session(threadId, status),+ } satisfies Pick<OrchestrationThreadShell, "id" | "session">;+}++function detail(+ id: string,+ status: OrchestrationSessionStatus,+ overrides: Partial<EnvironmentThreadState> = {},+) {+ const threadId = ThreadId.make(id);+ const thread: OrchestrationThread = {+ id: threadId,+ projectId: ProjectId.make("project"),+ title: id,+ modelSelection: { instanceId: ProviderInstanceId.make("codex"), model: "gpt-5.4" },+ runtimeMode: "full-access",+ interactionMode: "default",+ branch: null,+ worktreePath: null,+ latestTurn: null,+ createdAt: "2026-09-24T00:00:00.000Z",+ updatedAt: "2026-09-24T00:00:00.000Z",+ archivedAt: null,+ settledOverride: null,+ settledAt: null,+ pullRequests: [],+ deletedAt: null,+ messages: [],+ proposedPlans: [],+ activities: [],+ checkpoints: [],+ session: session(threadId, status),+ };+ return AsyncResult.success<EnvironmentThreadState>({+ ...EMPTY_ENVIRONMENT_THREAD_STATE,+ status: "live",+ data: Option.some(thread),+ ...overrides,+ });+}++function makeHarness() {+ // Registry cleanup runs only on `flush`, like the real deferred task.+ const tasks: Array<() => void> = [];+ const registry = AtomRegistry.make({+ scheduleTask: (task) => {+ tasks.push(task);+ return () => {};+ },+ });+ const flush = () => {+ for (let task = tasks.shift(); task !== undefined; task = tasks.shift()) task();+ };+ const environmentIds = Atom.make<ReadonlyArray<EnvironmentId>>([LOCAL, REMOTE]).pipe(+ Atom.keepAlive,+ );+ const threads = Atom.family((_environmentId: EnvironmentId) =>+ Atom.make<ReadonlyArray<ReturnType<typeof shell>>>([]).pipe(Atom.keepAlive),+ );+ // Stand-ins for the thread state atoms. Each one lives only while mounted,+ // as the real stream does.+ const keys = new Set<string>();+ const states = Atom.family((_key: string) =>+ Atom.make<AsyncResult.AsyncResult<EnvironmentThreadState>>(+ AsyncResult.success(EMPTY_ENVIRONMENT_THREAD_STATE),+ ),+ );+ const stateAtom = (environmentId: EnvironmentId, threadId: string) => {+ const key = `${environmentId}:${threadId}`;+ keys.add(key);+ return states(key);+ };+ const keepAlive = createRunningThreadKeepAliveAtom({+ environmentIdsAtom: environmentIds,+ threadsAtom: threads,+ stateAtom,+ });+ registry.mount(keepAlive);+ return {+ registry,+ environmentIds,+ threads,+ stateAtom,+ keepAlive,+ openStreams: () => {+ flush();+ return [...keys].filter((key) => registry.getNodes().has(states(key))).toSorted();+ },+ };+}++describe("createRunningThreadKeepAliveAtom", () => {+ it("keeps running threads open across shell updates and thread view visits", () => {+ const h = makeHarness();+ h.registry.set(h.threads(LOCAL), [+ shell("a", "running"),+ shell("b", "ready"),+ shell("c", null),+ ]);+ h.registry.set(h.threads(REMOTE), [shell("d", "starting")]);+ expect(h.openStreams()).toEqual(["local:a", "remote:d"]);++ // A thread view that comes and goes shares the kept stream.+ const live = detail("a", "running");+ h.registry.set(h.stateAtom(LOCAL, "a"), live);+ h.registry.mount(h.stateAtom(LOCAL, "a"))();++ // A shell update that starts or stops nothing does not rebuild the set.+ const kept = h.registry.get(h.keepAlive);+ h.registry.set(h.threads(LOCAL), [shell("a", "running"), shell("b", "ready")]);+ expect(h.registry.get(h.keepAlive)).toBe(kept);+ expect(h.openStreams()).toEqual(["local:a", "remote:d"]);+ expect(h.registry.get(h.stateAtom(LOCAL, "a"))).toBe(live);+ });++ it("holds a stopped thread until its own stream is live and shows the stop", () => {+ const h = makeHarness();+ h.registry.set(h.threads(LOCAL), [+ shell("a", "running"),+ shell("b", "running"),+ shell("c", "running"),+ ]);+ // "b" has not loaded yet. "c" hit a stream error.+ h.registry.set(h.stateAtom(LOCAL, "a"), detail("a", "running"));+ h.registry.set(+ h.stateAtom(LOCAL, "c"),+ detail("c", "running", { status: "cached", error: Option.some("Could not sync.") }),+ );++ // The shell reports the stops first. A failed stream cannot deliver its+ // stop, so only it is released now.+ h.registry.set(h.threads(LOCAL), [+ shell("a", "ready"),+ shell("b", "ready"),+ shell("c", "ready"),+ ]);+ expect(h.openStreams()).toEqual(["local:a", "local:b"]);++ h.registry.set(h.stateAtom(LOCAL, "a"), detail("a", "ready"));+ h.registry.set(h.stateAtom(LOCAL, "b"), detail("b", "ready", { status: "synchronizing" }));+ expect(h.openStreams()).toEqual(["local:b"]);+ h.registry.set(h.stateAtom(LOCAL, "b"), detail("b", "ready"));+ expect(h.openStreams()).toEqual([]);+ });++ it("follows environments that connect and go away", () => {+ const h = makeHarness();+ h.registry.set(h.environmentIds, [LOCAL]);+ h.registry.set(h.threads(REMOTE), [shell("d", "running")]);+ expect(h.openStreams()).toEqual([]);++ h.registry.set(h.environmentIds, [LOCAL, REMOTE]);+ expect(h.openStreams()).toEqual(["remote:d"]);++ // Removal drops every mount, including one still waiting for its stop.+ h.registry.set(h.stateAtom(REMOTE, "d"), detail("d", "running"));+ h.registry.set(h.threads(REMOTE), [shell("d", "ready")]);+ expect(h.openStreams()).toEqual(["remote:d"]);+ h.registry.set(h.environmentIds, [LOCAL]);+ expect(h.openStreams()).toEqual([]);+ });+});diff --git a/apps/web/src/state/threads.ts b/apps/web/src/state/threads.tsindex deda3ca29e9..31f8fea47b3 100644--- a/apps/web/src/state/threads.ts+++ b/apps/web/src/state/threads.ts@@ -1,4 +1,6 @@import { useAtomValue } from "@effect/atom-react";+import { enabledEnvironmentIds } from "@t3tools/client-runtime/state/connections";+import { arrayElementsEqual } from "@t3tools/client-runtime/state/entities";import {createEnvironmentThreadDetailAtoms,createEnvironmentThreadShellAtoms,@@ -6,8 +8,9 @@ import {EMPTY_ENVIRONMENT_THREAD_STATE,type EnvironmentThreadState,createThreadEnvironmentAtoms,+ isThreadSessionRunning,} from "@t3tools/client-runtime/state/threads";-import type { EnvironmentId, ThreadId } from "@t3tools/contracts";+import type { EnvironmentId, OrchestrationThreadShell, ThreadId } from "@t3tools/contracts";import * as Option from "effect/Option";import { AsyncResult, Atom } from "effect/unstable/reactivity";@@ -46,3 +49,84 @@ export function useEnvironmentThread(() => EMPTY_ENVIRONMENT_THREAD_STATE,) as EnvironmentThreadState;}++type KeptThreads = ReadonlyMap<EnvironmentId, ReadonlySet<ThreadId>>;++// True once a thread's own stream no longer needs to stay open: it is in sync+// and shows a settled session, or it cannot progress (deleted or failed). A+// stream that is still loading or reconnecting keeps waiting for the stop.+function isDetailDone<E>(result: AsyncResult.AsyncResult<EnvironmentThreadState, E>): boolean {+ if (!AsyncResult.isSuccess(result)) return true;+ const { status, data, error } = result.value;+ if (status === "deleted" || Option.isSome(error)) return true;+ return (+ status === "live" && !Option.exists(data, (thread) => isThreadSessionRunning(thread.session))+ );+}++/**+ * Keeps the thread state atom mounted for each running thread in the listed+ * environments. Mount the result; its value is only bookkeeping.+ *+ * The shell and detail streams are independent, so the shell can report a+ * stop before the detail loads or catches up. A stopped thread stays mounted+ * until its own detail is live and shows the stop too. Then the stream closes+ * and saves the settled state to disk.+ */+export function createRunningThreadKeepAliveAtom<E>(input: {+ readonly environmentIdsAtom: Atom.Atom<ReadonlyArray<EnvironmentId>>;+ readonly threadsAtom: (+ environmentId: EnvironmentId,+ ) => Atom.Atom<ReadonlyArray<Pick<OrchestrationThreadShell, "id" | "session">>>;+ readonly stateAtom: (+ environmentId: EnvironmentId,+ threadId: ThreadId,+ ) => Atom.Atom<AsyncResult.AsyncResult<EnvironmentThreadState, E>>;+}) {+ // Keeps its identity until a thread starts or stops, so ordinary shell+ // updates do not rebuild the keep-alive set.+ const runningThreadIdsAtom = Atom.family((environmentId: EnvironmentId) => {+ let previous: ReadonlyArray<ThreadId> = [];+ return Atom.make((get) => {+ const running = get(input.threadsAtom(environmentId)).flatMap((thread) =>+ isThreadSessionRunning(thread.session) ? [thread.id] : [],+ );+ if (arrayElementsEqual(previous, running)) return previous;+ previous = running;+ return running;+ }).pipe(Atom.withLabel(`web-running-thread-ids:${environmentId}`));+ });++ return Atom.make((get): KeptThreads => {+ const previous = Option.getOrUndefined(get.self<KeptThreads>());+ const kept = new Map<EnvironmentId, ReadonlySet<ThreadId>>();+ // An environment that leaves the list is not visited, so its mounts drop.+ for (const environmentId of get(input.environmentIdsAtom)) {+ const threadIds = new Set(get(runningThreadIdsAtom(environmentId)));+ for (const threadId of previous?.get(environmentId) ?? []) {+ if (threadIds.has(threadId)) continue;+ const stateAtom = input.stateAtom(environmentId, threadId);+ // `once`, not `get`: a dependency on a stopped thread would hold its+ // stream open until some other change rebuilds this atom.+ if (isDetailDone(get.once(stateAtom))) continue;+ threadIds.add(threadId);+ // Rebuild when this detail is done, not on each update.+ get.subscribe(stateAtom, (state) => {+ if (isDetailDone(state)) get.refreshSelf();+ });+ }+ for (const threadId of threadIds) get.mount(input.stateAtom(environmentId, threadId));+ kept.set(environmentId, threadIds);+ }+ return kept;+ }).pipe(Atom.withLabel("web-running-thread-keep-alive"));+}++/** Mounted by `RunningThreadKeepAlive` on desktop, for every enabled environment. */+export const runningThreadKeepAliveAtom = createRunningThreadKeepAliveAtom({+ environmentIdsAtom: Atom.map(environmentCatalog.catalogValueAtom, (catalog) => [+ ...enabledEnvironmentIds(catalog),+ ]),+ threadsAtom: environmentThreadShells.environmentThreadsAtom,+ stateAtom: environmentThreads.stateAtom,+});diff --git a/docs/internals/connection-runtime.md b/docs/internals/connection-runtime.mdindex 797ff8fe31f..301e1e0ffec 100644--- a/docs/internals/connection-runtime.md+++ b/docs/internals/connection-runtime.md@@ -61,6 +61,15 @@ stream, which stops when the last consumer unmounts; hidden mounted routes stillcount. A registry-local cache retains state and its replay cursor for five idleminutes so back navigation can resume without another snapshot download.+The desktop app adds one consumer: a+[keep-alive](../../apps/web/src/state/threads.ts) mounts every thread whose+session is starting or running, in each enabled environment. Opening a running+thread then needs no replay. The shell and detail streams are independent, so+the shell can report a stop before the detail loads or catches up. A stopped+thread stays mounted until its own stream is live and shows the stop, and the+stream then closes and saves the settled state.+Web and mobile do not keep threads alive.+Retain state and cursor together only after an update finishes. Cancellation mustnot advance the cached cursor beyond the applied data, and an old scope must notoverwrite its successor's cache. Preserve pagination data on reuse, but cleardiff --git a/packages/client-runtime/src/state/threads.ts b/packages/client-runtime/src/state/threads.tsindex b7074b9304b..e0be27d3535 100644--- a/packages/client-runtime/src/state/threads.ts+++ b/packages/client-runtime/src/state/threads.ts@@ -126,9 +126,16 @@ function formatThreadError(cause: Cause.Cause<unknown>): string {: "Could not synchronize the thread.";}+/**+ * A starting or running session is mid-turn. Its detail can change many times+ * per second, so the disk cache waits for it to settle.+ */+export function isThreadSessionRunning(session: OrchestrationThread["session"]): boolean {+ return session?.status === "starting" || session?.status === "running";+}+function shouldPersistThread(thread: OrchestrationThread): boolean {- const status = thread.session?.status;- return status !== "starting" && status !== "running";+ return !isThreadSessionRunning(thread.session);}interface ThreadResumeSnapshot {