feat(desktop): keep running threads synced in the background (#13554)
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
This commit is contained in:
1 parent
0c84b4289c
commit
99641fd09a
6 files changed
+320
-3
No files matched your search
@@ -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;
|
||||
}
|
||||
@@ -26,6 +26,7 @@ import { RelayClientInstallDialog } from "../components/cloud/RelayClientInstall
|
||||
import { 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 />
|
||||
|
||||
@@ -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([]);
|
||||
});
|
||||
});
|
||||
@@ -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,
|
||||
});
|
||||
@@ -61,6 +61,15 @@ stream, which stops when the last consumer unmounts; hidden mounted routes still
|
||||
count. A registry-local cache retains state and its replay cursor for five idle
|
||||
minutes 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 must
|
||||
not advance the cached cursor beyond the applied data, and an old scope must not
|
||||
overwrite its successor's cache. Preserve pagination data on reuse, but clear
|
||||
|
||||
@@ -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 {
|
||||
|
||||
Reference in new issue
Block a user