feat(updates): continue active threads across server restarts (#9167)

Co-authored-by: maria-rcks <[email protected]>
This commit is contained in:
mariaandmaria-rcks authored and GitHub committed 2026-09-02 04:28:16 -04:00
1 parent 14f15cfed4
commit 5b7d72aad1
26 files changed
+1296 -75

No files matched your search

@@ -23,6 +23,7 @@ const clientSettings: ClientSettings = {
confirmThreadArchive: true,
confirmThreadDelete: false,
confirmThreadUnpin: false,
continueThreadsAfterServerUpdate: true,
contextWindowMeterEnabled: false,
dismissedProviderUpdateNotificationKeys: [],
diffIgnoreWhitespace: true,
+217
View File
@@ -1,6 +1,8 @@
import * as NodeServices from "@effect/platform-node/NodeServices";
import { expect, it } from "@effect/vitest";
import { ServerSelfUpdateError, ThreadId } from "@t3tools/contracts";
import { HostProcessExecutablePath } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as FileSystem from "effect/FileSystem";
@@ -104,6 +106,221 @@ const makeHarness = Effect.fn("test.make_self_update_harness")(function* (
});
it.layer(NodeServices.layer)("server self update", (it) => {
it.effect("marks running threads at the boot-service handoff", () =>
Effect.gen(function* () {
const events: string[] = [];
const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
mode: "web",
selfUpdate: {
update: (_input, reportProgress = () => Effect.void) =>
reportProgress("downloading").pipe(
Effect.andThen(reportProgress("installing")),
Effect.as({
targetVersion: "1.1.0",
method: "boot-service" as const,
updateId: "update-id",
}),
),
commitDesktopUpdate: () => Effect.never,
},
prepare: Effect.sync(() => {
events.push("prepare");
return [ThreadId.make("thread-running")];
}),
clear: () => Effect.sync(() => void events.push("clear")),
});
yield* selfUpdate.update({ targetVersion: "1.1.0", continueRunningThreads: true }, (stage) =>
Effect.sync(() => void events.push(stage)),
);
expect(events).toEqual(["downloading", "prepare", "installing"]);
}),
);
it.effect("marks desktop threads only when the prepared update commits", () =>
Effect.gen(function* () {
const threadId = ThreadId.make("thread-running-desktop");
const events: string[] = [];
const commitError = new ServerSelfUpdateError({ reason: "install failed" });
const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
mode: "desktop",
selfUpdate: {
update: (_input, reportProgress = () => Effect.void) =>
reportProgress("installing").pipe(
Effect.as({
targetVersion: "1.2.0",
method: "desktop-app" as const,
desktopUpdateToken: "desktop-token",
}),
),
commitDesktopUpdate: () =>
Effect.sync(() => events.push("commit")).pipe(Effect.andThen(Effect.fail(commitError))),
},
prepare: Effect.sync(() => {
events.push("prepare");
return [threadId];
}),
clear: (threadIds) => Effect.sync(() => void events.push(`clear:${threadIds.join(",")}`)),
});
yield* selfUpdate.update({ targetVersion: "1.2.0", continueRunningThreads: true }, (stage) =>
Effect.sync(() => void events.push(stage)),
);
expect(events).toEqual(["installing"]);
expect(yield* selfUpdate.commitDesktopUpdate("desktop-token").pipe(Effect.flip)).toBe(
commitError,
);
expect(events).toEqual(["installing", "prepare", "commit", `clear:${threadId}`]);
expect(yield* selfUpdate.commitDesktopUpdate("desktop-token").pipe(Effect.flip)).toBe(
commitError,
);
expect(events).toEqual([
"installing",
"prepare",
"commit",
`clear:${threadId}`,
"prepare",
"commit",
`clear:${threadId}`,
]);
}),
);
it.effect("reports a failed continuation-marker cleanup", () =>
Effect.gen(function* () {
const updateError = new ServerSelfUpdateError({ reason: "update failed" });
const clearError = new ServerSelfUpdateError({ reason: "marker cleanup failed" });
const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
mode: "web",
selfUpdate: {
update: (_input, reportProgress = () => Effect.void) =>
reportProgress("installing").pipe(Effect.andThen(Effect.fail(updateError))),
commitDesktopUpdate: () => Effect.never,
},
prepare: Effect.succeed([ThreadId.make("thread-cleanup-failure")]),
clear: () => Effect.fail(clearError),
});
expect(
yield* selfUpdate
.update({ targetVersion: "1.1.0", continueRunningThreads: true })
.pipe(Effect.flip),
).toBe(clearError);
}),
);
it.effect("keeps continuation markers after the boot-service handoff is accepted", () =>
Effect.gen(function* () {
const events: string[] = [];
const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
mode: "web",
selfUpdate: {
update: (
_input,
reportProgress = () => Effect.void,
onHandoffAccepted = () => Effect.void,
) =>
reportProgress("installing").pipe(
Effect.andThen(onHandoffAccepted()),
Effect.andThen(Effect.interrupt),
),
commitDesktopUpdate: () => Effect.never,
},
prepare: Effect.sync(() => {
events.push("prepare");
return [ThreadId.make("thread-accepted-boot-handoff")];
}),
clear: () => Effect.sync(() => void events.push("clear")),
});
const exit = yield* selfUpdate
.update({ targetVersion: "1.1.0", continueRunningThreads: true })
.pipe(Effect.exit);
expect(exit._tag).toBe("Failure");
expect(events).toEqual(["prepare"]);
}),
);
it.effect("keeps continuation markers after the desktop handoff is accepted", () =>
Effect.gen(function* () {
const events: string[] = [];
const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
mode: "desktop",
selfUpdate: {
update: () =>
Effect.succeed({
targetVersion: "1.2.0",
method: "desktop-app" as const,
desktopUpdateToken: "accepted-desktop-token",
}),
commitDesktopUpdate: (_requestId, onHandoffAccepted = () => Effect.void) =>
onHandoffAccepted().pipe(Effect.andThen(Effect.interrupt)),
},
prepare: Effect.sync(() => {
events.push("prepare");
return [ThreadId.make("thread-accepted-desktop-handoff")];
}),
clear: () => Effect.sync(() => void events.push("clear")),
});
yield* selfUpdate.update({
targetVersion: "1.2.0",
continueRunningThreads: true,
});
const exit = yield* selfUpdate
.commitDesktopUpdate("accepted-desktop-token")
.pipe(Effect.exit);
expect(exit._tag).toBe("Failure");
expect(events).toEqual(["prepare"]);
}),
);
it.effect("clears continuation markers for mixed failure and interrupt causes", () =>
Effect.gen(function* () {
const events: string[] = [];
const commitError = new ServerSelfUpdateError({ reason: "install failed" });
const selfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
mode: "desktop",
selfUpdate: {
update: () =>
Effect.succeed({
targetVersion: "1.2.0",
method: "desktop-app" as const,
desktopUpdateToken: "failed-desktop-token",
}),
commitDesktopUpdate: (_requestId, onHandoffAccepted = () => Effect.void) =>
onHandoffAccepted().pipe(
Effect.andThen(
Effect.failCause(
Cause.fromReasons([
Cause.makeFailReason(commitError),
Cause.makeInterruptReason(),
]),
),
),
),
},
prepare: Effect.sync(() => [ThreadId.make("thread-failed-desktop-install")]),
clear: () => Effect.sync(() => void events.push("clear")),
});
yield* selfUpdate.update({
targetVersion: "1.2.0",
continueRunningThreads: true,
});
const exit = yield* selfUpdate.commitDesktopUpdate("failed-desktop-token").pipe(Effect.exit);
expect(exit._tag).toBe("Failure");
if (exit._tag === "Failure") {
expect(Cause.hasInterrupts(exit.cause)).toBe(true);
expect(Cause.hasInterruptsOnly(exit.cause)).toBe(false);
}
expect(events).toEqual(["clear"]);
}),
);
it.effect("stages and preflights before asking the launcher for an update ID", () =>
Effect.gen(function* () {
const { selfUpdate, order } = yield* makeHarness();
+124 -8
View File
@@ -4,15 +4,18 @@ import {
type ServerSelfUpdateInput,
type ServerSelfUpdateProgressStage,
type ServerSelfUpdateResult,
type ThreadId,
} from "@t3tools/contracts";
import { HostProcessExecutablePath } from "@t3tools/shared/hostProcess";
import * as Cause from "effect/Cause";
import * as Context from "effect/Context";
import * as Duration from "effect/Duration";
import * as Effect from "effect/Effect";
import * as HashSet from "effect/HashSet";
import * as Ref from "effect/Ref";
import * as FileSystem from "effect/FileSystem";
import * as Layer from "effect/Layer";
import * as Path from "effect/Path";
import * as Ref from "effect/Ref";
import * as ServerConfig from "../config.ts";
import * as DesktopAppUpdate from "../desktopUpdate/DesktopAppUpdate.ts";
@@ -41,14 +44,125 @@ export class ServerSelfUpdate extends Context.Service<
{
readonly update: (
input: ServerSelfUpdateInput,
reportProgress?: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,
reportProgress?: (
stage: ServerSelfUpdateProgressStage,
) => Effect.Effect<void, ServerSelfUpdateError>,
onHandoffAccepted?: () => Effect.Effect<void>,
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
readonly commitDesktopUpdate: (
requestId: string,
onHandoffAccepted?: () => Effect.Effect<void>,
) => Effect.Effect<never, ServerSelfUpdateError>;
}
>()("t3/cloud/selfUpdate/ServerSelfUpdate") {}
export const withRunningThreadContinuation = Effect.fn(
"cloud.server_self_update.withRunningThreadContinuation",
)(function* (input: {
readonly mode: ServerConfig.RuntimeMode;
readonly selfUpdate: ServerSelfUpdate["Service"];
readonly prepare: Effect.Effect<ReadonlyArray<ThreadId>, ServerSelfUpdateError>;
readonly clear: (
threadIds: ReadonlyArray<ThreadId>,
) => Effect.Effect<void, ServerSelfUpdateError>;
}) {
const desktopContinuationTokens = yield* Ref.make(HashSet.empty<string>());
const clearOnError = <A>(
effect: Effect.Effect<A, ServerSelfUpdateError>,
threadIds: () => ReadonlyArray<ThreadId>,
handoffAccepted: () => boolean,
): Effect.Effect<A, ServerSelfUpdateError> =>
effect.pipe(
Effect.catchCause((cause) =>
(handoffAccepted() && Cause.hasInterruptsOnly(cause)
? Effect.void
: input.clear(threadIds())
).pipe(Effect.andThen(Effect.failCause(cause))),
),
);
const update: ServerSelfUpdate["Service"]["update"] = (
request,
reportProgress = () => Effect.void,
) => {
let prepared = false;
let handoffAccepted = false;
let continuationThreadIds: ReadonlyArray<ThreadId> = [];
return clearOnError(
input.selfUpdate
.update(
request,
(stage) =>
(request.continueRunningThreads === true &&
input.mode !== "desktop" &&
stage === "installing" &&
!prepared
? input.prepare.pipe(
Effect.tap((threadIds) =>
Effect.sync(() => {
prepared = true;
continuationThreadIds = threadIds;
}),
),
Effect.asVoid,
)
: Effect.void
).pipe(Effect.andThen(reportProgress(stage))),
() =>
Effect.sync(() => {
handoffAccepted = true;
}),
)
.pipe(
Effect.tap((result) => {
if (
result.method === "desktop-app" &&
result.desktopUpdateToken !== undefined &&
request.continueRunningThreads === true
) {
return Ref.update(desktopContinuationTokens, HashSet.add(result.desktopUpdateToken));
}
return Effect.void;
}),
),
() => continuationThreadIds,
() => handoffAccepted,
);
};
return ServerSelfUpdate.of({
update,
commitDesktopUpdate: (requestId) =>
Effect.gen(function* () {
const shouldContinue = yield* Ref.modify(desktopContinuationTokens, (tokens) => [
HashSet.has(tokens, requestId),
HashSet.remove(tokens, requestId),
]);
let handoffAccepted = false;
let continuationThreadIds: ReadonlyArray<ThreadId> = [];
return yield* clearOnError(
Effect.gen(function* () {
continuationThreadIds = shouldContinue ? yield* input.prepare : [];
return yield* input.selfUpdate.commitDesktopUpdate(requestId, () =>
Effect.sync(() => {
handoffAccepted = true;
}),
);
}),
() => continuationThreadIds,
() => handoffAccepted,
).pipe(
Effect.catchCause((cause) =>
(shouldContinue && !handoffAccepted
? Ref.update(desktopContinuationTokens, HashSet.add(requestId))
: Effect.void
).pipe(Effect.andThen(Effect.failCause(cause))),
),
);
}),
});
});
export const make = Effect.fn("cloud.server_self_update.make")(function* () {
const serverConfig = yield* ServerConfig.ServerConfig;
const desktopAppUpdate = yield* DesktopAppUpdate.DesktopAppUpdate;
@@ -68,7 +182,7 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
const update: ServerSelfUpdate["Service"]["update"] = Effect.fn(
"cloud.server_self_update.update",
)(function* (input, reportProgress = () => Effect.void) {
)(function* (input, reportProgress = () => Effect.void, onHandoffAccepted = () => Effect.void) {
if (capability === "desktop-managed") {
// input.targetVersion is meaningless here: the desktop app's own
// update feed decides what it downloads, and the result carries what
@@ -180,9 +294,8 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
);
yield* reportProgress("installing");
const updateId = yield* launcher
.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath })
.pipe(
const updateId = yield* Effect.uninterruptible(
launcher.requestUpdate({ targetVersion, dbPath: serverConfig.dbPath }).pipe(
Effect.mapError((error) =>
failWith(
error._tag === "ServiceLauncherRejectedError"
@@ -191,7 +304,9 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
error,
),
),
);
Effect.tap(() => onHandoffAccepted()),
),
);
yield* Effect.logInfo("Server update prepared; handing off to the service launcher.", {
updateId,
@@ -204,7 +319,8 @@ export const make = Effect.fn("cloud.server_self_update.make")(function* () {
return ServerSelfUpdate.of({
update,
commitDesktopUpdate: (requestId) => desktopAppUpdate.commit(requestId),
commitDesktopUpdate: (requestId, onHandoffAccepted) =>
desktopAppUpdate.commit(requestId, onHandoffAccepted),
});
});
@@ -49,11 +49,16 @@ export class DesktopAppUpdate extends Context.Service<
/** Checks and downloads through the desktop app, then returns a token
while this server is still connected. `commit` starts installation. */
readonly run: (
reportProgress: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,
reportProgress: (
stage: ServerSelfUpdateProgressStage,
) => Effect.Effect<void, ServerSelfUpdateError>,
) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;
/** Starts the prepared install. Success stops this server, so this effect
returns only when installation fails or times out. */
readonly commit: (requestId: string) => Effect.Effect<never, ServerSelfUpdateError>;
readonly commit: (
requestId: string,
onHandoffAccepted?: () => Effect.Effect<void>,
) => Effect.Effect<never, ServerSelfUpdateError>;
}
>()("t3/desktopUpdate/DesktopAppUpdate") {}
@@ -72,11 +77,15 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
const consumeReports = (
requestId: string,
changes: Stream.Stream<DesktopUpdateStatusReport>,
reportProgress: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,
reportProgress: (
stage: ServerSelfUpdateProgressStage,
) => Effect.Effect<void, ServerSelfUpdateError>,
) =>
Effect.gen(function* () {
const lastStage = yield* Ref.make<ServerSelfUpdateProgressStage | null>(null);
const emitStage = (stage: ServerSelfUpdateProgressStage | null): Effect.Effect<void> =>
const emitStage = (
stage: ServerSelfUpdateProgressStage | null,
): Effect.Effect<void, ServerSelfUpdateError> =>
stage === null
? Effect.void
: Ref.get(lastStage).pipe(
@@ -90,7 +99,9 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
const terminal = yield* changes.pipe(
Stream.filter((report) => report.requestId === requestId),
Stream.mapEffect(
(report): Effect.Effect<Option.Option<DesktopUpdateStatusReport>> =>
(
report,
): Effect.Effect<Option.Option<DesktopUpdateStatusReport>, ServerSelfUpdateError> =>
report.outcome === undefined
? emitStage(desktopUpdateProgressStage(report.state)).pipe(
Effect.as(Option.none<DesktopUpdateStatusReport>()),
@@ -176,7 +187,7 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
const commit: DesktopAppUpdate["Service"]["commit"] = Effect.fn(
"desktopUpdate.desktopAppUpdate.commit",
)(function* (requestId) {
)(function* (requestId, onHandoffAccepted = () => Effect.void) {
if (!available) {
return yield* failWith("This server cannot commit a desktop app update.");
}
@@ -187,11 +198,12 @@ export const make = Effect.fn("desktopUpdate.desktopAppUpdate.make")(function* (
onNone: () => changes,
onSome: (report) => Stream.concat(Stream.make(report), changes),
});
yield* receiver
.commitDesktopUpdate(requestId)
.pipe(
yield* Effect.uninterruptible(
receiver.commitDesktopUpdate(requestId).pipe(
Effect.mapError((error) => failWith("Could not reach the T3 Code desktop app.", error)),
);
Effect.tap(() => onHandoffAccepted()),
),
);
return yield* reports.pipe(
Stream.filter((report) => report.requestId === requestId && report.outcome === "failed"),
Stream.runHead,
@@ -244,11 +244,13 @@ it.layer(NodeServices.layer)("ServerEnvironmentLive", (it) => {
expect(withFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
expect(withFd.capabilities.desktopAppUpdate).toBe(true);
expect(withFd.capabilities.serverSelfUpdateProgress).toBe(true);
expect(withFd.capabilities.serverUpdateThreadContinuation).toBe(true);
const withoutFd = yield* describeWith({ mode: "desktop" });
expect(withoutFd.capabilities.serverSelfUpdate).toBe("desktop-managed");
expect(withoutFd.capabilities.desktopAppUpdate).toBeUndefined();
expect(withoutFd.capabilities.serverSelfUpdateProgress).toBeUndefined();
expect(withoutFd.capabilities.serverUpdateThreadContinuation).toBeUndefined();
const web = yield* describeWith({ mode: "web", desktopTelemetryControlFd: 5 });
expect(web.capabilities.desktopAppUpdate).toBeUndefined();
@@ -224,7 +224,10 @@ export const make = Effect.gen(function* () {
threadPullRequestLinking: true,
...(serverSelfUpdate === null ? {} : { serverSelfUpdate }),
...(serverSelfUpdate === "boot-service" || desktopAppUpdate
? { serverSelfUpdateProgress: true }
? {
serverSelfUpdateProgress: true,
serverUpdateThreadContinuation: true,
}
: {}),
...(desktopAppUpdate ? { desktopAppUpdate: true } : {}),
},
@@ -2010,6 +2010,7 @@ export const makeCodexAdapter = Effect.fn("makeCodexAdapter")(function* (
provider: PROVIDER,
capabilities: {
sessionModelSwitch: "in-session",
promptlessTurnContinuation: true,
},
startSession,
sendTurn,
@@ -246,6 +246,7 @@ function makeFakeCodexAdapter(provider: ProviderDriverKind = CODEX_DRIVER) {
provider,
capabilities: {
sessionModelSwitch: "in-session",
...(provider === CODEX_DRIVER ? { promptlessTurnContinuation: true } : {}),
},
startSession,
sendTurn,
@@ -960,6 +961,56 @@ it.effect(
);
routing.layer("ProviderServiceLive routing", (it) => {
it.effect("allows promptless continuation only for capable providers", () =>
Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
const codexThreadId = asThreadId("thread-promptless-continuation");
yield* provider.startSession(codexThreadId, {
provider: CODEX_DRIVER,
providerInstanceId: codexInstanceId,
threadId: codexThreadId,
runtimeMode: "full-access",
});
yield* provider.sendTurn({ threadId: codexThreadId, continuation: true });
assert.deepEqual(routing.codex.sendTurn.mock.calls.at(-1)?.[0], {
threadId: codexThreadId,
continuation: true,
});
const claudeThreadId = asThreadId("thread-promptless-continuation-unsupported");
yield* provider.startSession(claudeThreadId, {
provider: CLAUDE_AGENT_DRIVER,
providerInstanceId: claudeAgentInstanceId,
threadId: claudeThreadId,
runtimeMode: "full-access",
});
const failure = yield* Effect.flip(
provider.sendTurn({ threadId: claudeThreadId, continuation: true }),
);
assert.instanceOf(failure, ProviderValidationError);
assert.include(failure.issue, "requires an explicit continuation prompt");
assert.equal(routing.claude.sendTurn.mock.calls.length, 0);
yield* provider.stopSession({ threadId: claudeThreadId });
routing.claude.startSession.mockClear();
const stoppedFailure = yield* Effect.flip(
provider.sendTurn({ threadId: claudeThreadId, continuation: true }),
);
assert.instanceOf(stoppedFailure, ProviderValidationError);
assert.include(stoppedFailure.issue, "requires an explicit continuation prompt");
assert.equal(routing.claude.startSession.mock.calls.length, 0);
yield* provider.stopSession({ threadId: codexThreadId });
routing.codex.startSession.mockClear();
routing.codex.sendTurn.mockClear();
routing.codex.stopSession.mockClear();
routing.claude.startSession.mockClear();
routing.claude.sendTurn.mockClear();
routing.claude.stopSession.mockClear();
}),
);
it.effect("routes provider operations and rollback conversation", () =>
Effect.gen(function* () {
const provider = yield* ProviderService.ProviderService;
@@ -723,7 +723,7 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
});
const attachments = parsed.attachments ?? [];
if (!parsed.input && attachments.length === 0) {
if (!parsed.input && attachments.length === 0 && parsed.continuation !== true) {
return yield* toValidationError(
"ProviderService.sendTurn",
"Either input text or at least one attachment is required",
@@ -777,11 +777,29 @@ const makeProviderService = Effect.fn("makeProviderService")(function* (
let metricProvider = "unknown";
let metricModel = input.modelSelection?.model;
return yield* Effect.gen(function* () {
const routed = yield* resolveRoutableSession({
let routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.sendTurn",
allowRecovery: true,
allowRecovery: false,
});
if (
input.continuation === true &&
!input.input &&
attachments.length === 0 &&
routed.adapter.capabilities.promptlessTurnContinuation !== true
) {
return yield* toValidationError(
"ProviderService.sendTurn",
`Provider '${routed.adapter.provider}' requires an explicit continuation prompt`,
);
}
if (!routed.isActive) {
routed = yield* resolveRoutableSession({
threadId: input.threadId,
operation: "ProviderService.sendTurn",
allowRecovery: true,
});
}
metricProvider = routed.adapter.provider;
metricModel = input.modelSelection?.model;
yield* Effect.annotateCurrentSpan({
@@ -32,6 +32,9 @@ export interface ProviderAdapterCapabilities {
* Declares whether changing the model on an existing session is supported.
*/
readonly sessionModelSwitch: ProviderSessionModelSwitchMode;
/** Starts a resumed turn with no synthetic user prompt. Omitted means the
adapter needs an explicit continuation instruction. */
readonly promptlessTurnContinuation?: boolean;
}
export interface ProviderThreadTurnSnapshot {
+2
View File
@@ -937,6 +937,8 @@ const buildAppUnderTest = (options?: {
Layer.mock(ServerRuntimeStartup.ServerRuntimeStartup)({
awaitCommandReady: Effect.void,
markHttpListening: Effect.void,
markRunningProviderSessionsForContinuation: Effect.succeed([]),
clearProviderSessionContinuationMarkers: () => Effect.void,
enqueueCommand: (effect) => effect,
...options?.layers?.serverRuntimeStartup,
}),
@@ -3,10 +3,12 @@ import {
type OrchestrationCommand,
ProviderDriverKind,
ProviderInstanceId,
type ProviderSendTurnInput,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import { assert, it } from "@effect/vitest";
import * as Deferred from "effect/Deferred";
import * as Effect from "effect/Effect";
import * as Option from "effect/Option";
import * as Stream from "effect/Stream";
@@ -27,10 +29,12 @@ const makeThread = (
status: "starting" | "running" | "ready" | "stopped" | "error",
activeTurnId: TurnId | null = null,
archivedAt: string | null = null,
deletedAt: string | null = null,
) => ({
id: ThreadId.make(id),
archivedAt,
deletedAt: null,
deletedAt,
interactionMode: "default" as const,
session: {
threadId: ThreadId.make(id),
status,
@@ -67,6 +71,7 @@ const queryWithThreads = (threads: ReadonlyArray<ReturnType<typeof makeThread>>)
const runReconciliation = (input: {
readonly threads: ReadonlyArray<ReturnType<typeof makeThread>>;
readonly liveThreadIds?: ReadonlyArray<ThreadId>;
readonly providerService?: ProviderService.ProviderService["Service"];
readonly directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"];
readonly dispatch: OrchestrationEngine.OrchestrationEngineService["Service"]["dispatch"];
}) =>
@@ -77,7 +82,7 @@ const runReconciliation = (input: {
),
Effect.provideService(
ProviderService.ProviderService,
makeProviderService(input.liveThreadIds),
input.providerService ?? makeProviderService(input.liveThreadIds),
),
Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, input.directory),
Effect.provideService(OrchestrationEngine.OrchestrationEngineService, {
@@ -90,6 +95,347 @@ const runReconciliation = (input: {
Effect.provide(NodeServices.layer),
);
it.effect("marks active running sessions that have persisted resume state", () => {
const active = makeThread("thread-mark-active", "running", TurnId.make("turn-mark-active"));
const archived = makeThread(
"thread-mark-archived",
"running",
TurnId.make("turn-mark-archived"),
updatedAt,
);
const ready = makeThread("thread-mark-ready", "ready");
const missingResumeState = makeThread(
"thread-mark-missing-resume-state",
"running",
TurnId.make("turn-mark-missing-resume-state"),
);
const bindingReads: ThreadId[] = [];
const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
return ServerRuntimeStartup.markRunningProviderSessionsForContinuation.pipe(
Effect.provideService(
ProjectionSnapshotQuery.ProjectionSnapshotQuery,
queryWithThreads([active, archived, ready, missingResumeState]),
),
Effect.provideService(ProviderSessionDirectory.ProviderSessionDirectory, {
getBinding: (threadId) =>
Effect.sync(() => bindingReads.push(threadId)).pipe(
Effect.as(
Option.some({
threadId,
provider: ProviderDriverKind.make("codex"),
providerInstanceId,
...(threadId === active.id ? { resumeCursor: { threadId } } : {}),
runtimePayload: { activeTurnId: "turn-mark-active" },
}),
),
),
upsert: (binding) => Effect.sync(() => upserts.push(binding)),
getProvider: () => Effect.die("unused"),
listThreadIds: () => Effect.die("unused"),
listBindings: () => Effect.die("unused"),
}),
Effect.tap((marked) =>
Effect.sync(() => {
assert.deepStrictEqual(bindingReads, [active.id, missingResumeState.id]);
assert.deepStrictEqual(marked, [active.id]);
assert.deepStrictEqual(upserts[0]?.runtimePayload, {
activeTurnId: "turn-mark-active",
continueAfterServerUpdate: active.session.activeTurnId,
});
}),
),
);
});
it.effect("continues marked sessions after activation with provider-specific input", () =>
Effect.gen(function* () {
const codex = makeThread(
"thread-continue-codex",
"running",
TurnId.make("turn-continue-codex"),
);
const fallback = makeThread("thread-continue-fallback", "starting");
const fallbackContinuationTurnId = TurnId.make("turn-continue-fallback");
const fallbackProviderInstanceId = ProviderInstanceId.make("claudeAgent");
const continuationSent = yield* Deferred.make<void>();
const continuationCleared = yield* Deferred.make<void>();
const sends: ProviderSendTurnInput[] = [];
const dispatched: OrchestrationCommand[] = [];
const upserts: ProviderSessionDirectory.ProviderRuntimeBinding[] = [];
const bindings = new Map<ThreadId, ProviderSessionDirectory.ProviderRuntimeBinding>(
[codex, fallback].map((thread) => [
thread.id,
{
threadId: thread.id,
provider:
thread.id === codex.id
? ProviderDriverKind.make("codex")
: ProviderDriverKind.make("claudeAgent"),
providerInstanceId:
thread.id === codex.id ? providerInstanceId : fallbackProviderInstanceId,
status: "running" as const,
runtimePayload: {
continueAfterServerUpdate:
thread.id === codex.id ? codex.session.activeTurnId : fallbackContinuationTurnId,
},
},
]),
);
const providerService: ProviderService.ProviderService["Service"] = {
...makeProviderService(),
getCapabilities: (instanceId) =>
Effect.succeed({
sessionModelSwitch: "in-session",
...(instanceId === providerInstanceId ? { promptlessTurnContinuation: true } : {}),
}),
sendTurn: (input) =>
Effect.gen(function* () {
sends.push(input);
if (sends.length === 2) {
yield* Deferred.succeed(continuationSent, undefined);
}
return {
threadId: input.threadId,
turnId: TurnId.make(`continued-${String(input.threadId)}`),
};
}),
};
yield* runReconciliation({
threads: [codex, fallback],
providerService,
directory: {
getBinding: (threadId) =>
Effect.sync(() => {
const binding = bindings.get(threadId);
return binding === undefined ? Option.none() : Option.some(binding);
}),
upsert: (binding) =>
Effect.sync(() => {
bindings.set(binding.threadId, binding);
upserts.push(binding);
const clearedCount = upserts.filter((candidate) => {
const payload = candidate.runtimePayload;
return (
payload !== null &&
typeof payload === "object" &&
!Array.isArray(payload) &&
"continueAfterServerUpdate" in payload &&
payload.continueAfterServerUpdate === null
);
}).length;
return clearedCount === 1;
}).pipe(
Effect.flatMap((firstMarkerCleared) =>
firstMarkerCleared ? Deferred.succeed(continuationCleared, undefined) : Effect.void,
),
),
getProvider: () => Effect.die("unused"),
listThreadIds: () => Effect.die("unused"),
listBindings: () => Effect.die("unused"),
},
dispatch: (command) =>
Effect.sync(() => dispatched.push(command)).pipe(
Effect.as({ sequence: dispatched.length }),
),
});
yield* Deferred.await(continuationSent);
yield* Deferred.await(continuationCleared);
assert.deepStrictEqual(
sends.toSorted((left, right) => String(left.threadId).localeCompare(String(right.threadId))),
[
{ threadId: codex.id, continuation: true, interactionMode: "default" },
{
threadId: fallback.id,
input: "Continue where you left off.",
interactionMode: "default",
},
],
);
assert.deepStrictEqual(
dispatched.map((command) =>
command.type === "thread.session.set"
? {
threadId: command.threadId,
status: command.session.status,
activeTurnId: command.session.activeTurnId,
}
: null,
),
[
{
threadId: codex.id,
status: "starting",
activeTurnId: null,
},
{
threadId: fallback.id,
status: "starting",
activeTurnId: fallback.session.activeTurnId,
},
],
);
for (const [thread, continuationTurnId] of [
[codex, codex.session.activeTurnId],
[fallback, fallbackContinuationTurnId],
] as const) {
assert.deepStrictEqual(
upserts
.filter((binding) => binding.threadId === thread.id)
.map((binding) => binding.runtimePayload)[0],
{
continueAfterServerUpdate: continuationTurnId,
activeTurnId: null,
},
);
}
assert.equal(
upserts.some((binding) => {
const payload = binding.runtimePayload;
return (
payload !== null &&
typeof payload === "object" &&
!Array.isArray(payload) &&
"continueAfterServerUpdate" in payload &&
payload.continueAfterServerUpdate === null
);
}),
true,
);
}),
);
it.effect("does not continue archived or deleted marked sessions", () => {
const archived = makeThread(
"thread-continue-archived",
"running",
TurnId.make("turn-continue-archived"),
updatedAt,
);
const deleted = makeThread(
"thread-continue-deleted",
"running",
TurnId.make("turn-continue-deleted"),
null,
updatedAt,
);
const sends: ProviderSendTurnInput[] = [];
const dispatched: OrchestrationCommand[] = [];
return runReconciliation({
threads: [archived, deleted],
providerService: {
...makeProviderService(),
sendTurn: (input) =>
Effect.sync(() => {
sends.push(input);
return {
threadId: input.threadId,
turnId: TurnId.make("unexpected-archived-turn"),
};
}),
},
directory: {
getBinding: (threadId) => {
const thread = threadId === archived.id ? archived : deleted;
return Effect.succeed(
Option.some({
threadId,
provider: ProviderDriverKind.make("codex"),
providerInstanceId,
status: "running" as const,
resumeCursor: { cursor: threadId },
runtimePayload: {
continueAfterServerUpdate: thread.session.activeTurnId,
},
}),
);
},
upsert: () => Effect.void,
getProvider: () => Effect.die("unused"),
listThreadIds: () => Effect.die("unused"),
listBindings: () => Effect.die("unused"),
},
dispatch: (command) =>
Effect.sync(() => dispatched.push(command)).pipe(Effect.as({ sequence: dispatched.length })),
}).pipe(
Effect.tap(() =>
Effect.sync(() => {
assert.deepStrictEqual(sends, []);
assert.deepStrictEqual(
dispatched.map((command) =>
command.type === "thread.session.set"
? { threadId: command.threadId, status: command.session.status }
: null,
),
[
{ threadId: archived.id, status: "error" },
{ threadId: deleted.id, status: "error" },
],
);
}),
),
);
});
it.effect("retries continuation preparation before settling a persistent failure", () => {
const thread = makeThread(
"thread-continuation-preparation-failure",
"running",
TurnId.make("turn-continuation-preparation-failure"),
);
const dispatched: OrchestrationCommand[] = [];
const failure = new OrchestrationCommandInvariantError({
commandType: "thread.session.set",
detail: "simulated continuation preparation failure",
});
return runReconciliation({
threads: [thread],
directory: {
getBinding: () =>
Effect.succeed(
Option.some({
threadId: thread.id,
provider: ProviderDriverKind.make("codex"),
providerInstanceId,
status: "running" as const,
resumeCursor: { cursor: thread.id },
runtimePayload: {
continueAfterServerUpdate: thread.session.activeTurnId,
},
}),
),
upsert: () => Effect.void,
getProvider: () => Effect.die("unused"),
listThreadIds: () => Effect.die("unused"),
listBindings: () => Effect.die("unused"),
},
dispatch: (command) => {
if (command.type !== "thread.session.set") {
return Effect.die("unexpected command");
}
dispatched.push(command);
return command.session.status === "starting"
? Effect.fail(failure)
: Effect.succeed({ sequence: dispatched.length });
},
}).pipe(
Effect.tap(() =>
Effect.sync(() =>
assert.deepStrictEqual(
dispatched.map(
(command) => command.type === "thread.session.set" && command.session.status,
),
["starting", "starting", "error"],
),
),
),
);
});
it.effect("reconciles multiple active and archived orphans but skips live sessions", () => {
const starting = makeThread("thread-starting", "starting");
const running = makeThread("thread-running", "running", TurnId.make("turn-running"));
@@ -123,7 +469,13 @@ it.effect("reconciles multiple active and archived orphans but skips live sessio
providerInstanceId,
status: "running" as const,
resumeCursor: { cursor: candidate },
runtimePayload: { activeTurnId: "stale", unrelated: candidate },
runtimePayload: {
activeTurnId: "stale",
unrelated: candidate,
...(candidate === staleActiveTurn.id
? { continueAfterServerUpdate: "turn-from-an-earlier-update" }
: {}),
},
}),
),
),
@@ -157,7 +509,16 @@ it.effect("reconciles multiple active and archived orphans but skips live sessio
assert.equal(upserts.length, orphanIds.length);
for (const binding of upserts) {
assert.equal(binding.status, "stopped");
assert.deepStrictEqual(binding.runtimePayload, { activeTurnId: null });
assert.deepStrictEqual(
binding.runtimePayload,
binding.threadId === staleActiveTurn.id
? {
activeTurnId: null,
unrelated: binding.threadId,
continueAfterServerUpdate: null,
}
: { activeTurnId: null, unrelated: binding.threadId },
);
assert.deepStrictEqual(binding.resumeCursor, { cursor: binding.threadId });
}
}),
+312 -40
View File
@@ -6,6 +6,7 @@ import {
ProjectId,
ProviderInstanceId,
ThreadId,
TurnId,
} from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Console from "effect/Console";
@@ -65,6 +66,13 @@ export class ServerRuntimeStartup extends Context.Service<
{
readonly awaitCommandReady: Effect.Effect<void, ServerRuntimeStartupError>;
readonly markHttpListening: Effect.Effect<void>;
readonly markRunningProviderSessionsForContinuation: Effect.Effect<
ReadonlyArray<ThreadId>,
ServerUpdateThreadContinuationError
>;
readonly clearProviderSessionContinuationMarkers: (
threadIds: ReadonlyArray<ThreadId>,
) => Effect.Effect<void, ServerUpdateThreadContinuationError>;
readonly enqueueCommand: <A, E>(
effect: Effect.Effect<A, E>,
) => Effect.Effect<A, E | ServerRuntimeStartupError>;
@@ -294,6 +302,138 @@ const runStartupPhase = <A, E, R>(phase: string, effect: Effect.Effect<A, E, R>)
const ORPHANED_PROVIDER_SESSION_ERROR =
"Provider session did not survive a server restart. Send a new message to continue.";
const SERVER_UPDATE_CONTINUATION_KEY = "continueAfterServerUpdate";
const SERVER_UPDATE_CONTINUATION_PROMPT = "Continue where you left off.";
class ProviderSessionContinuationError extends Schema.TaggedErrorClass<ProviderSessionContinuationError>()(
"ProviderSessionContinuationError",
{
threadId: ThreadId,
},
) {
override get message(): string {
return `Could not continue thread '${this.threadId}': the provider instance is missing.`;
}
}
export class ServerUpdateThreadContinuationError extends Schema.TaggedErrorClass<ServerUpdateThreadContinuationError>()(
"ServerUpdateThreadContinuationError",
{
cause: Schema.Defect(),
},
) {
override get message(): string {
return "Could not prepare running threads to continue after the update.";
}
}
function hasServerUpdateContinuationMarker(
runtimePayload: unknown,
): runtimePayload is Record<string, unknown> {
return (
runtimePayload !== null &&
typeof runtimePayload === "object" &&
!Array.isArray(runtimePayload) &&
SERVER_UPDATE_CONTINUATION_KEY in runtimePayload
);
}
function readRuntimePayload(runtimePayload: unknown): Record<string, unknown> {
return runtimePayload !== null &&
typeof runtimePayload === "object" &&
!Array.isArray(runtimePayload)
? (runtimePayload as Record<string, unknown>)
: {};
}
const isServerUpdateThreadContinuationError = Schema.is(ServerUpdateThreadContinuationError);
function readServerUpdateContinuationTurnId(runtimePayload: unknown): TurnId | null {
if (!hasServerUpdateContinuationMarker(runtimePayload)) {
return null;
}
const value = runtimePayload[SERVER_UPDATE_CONTINUATION_KEY];
return typeof value === "string" && value.length > 0 ? TurnId.make(value) : null;
}
const toServerUpdateThreadContinuationError = (cause: unknown) =>
isServerUpdateThreadContinuationError(cause)
? cause
: new ServerUpdateThreadContinuationError({ cause });
export const markRunningProviderSessionsForContinuation = Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const query = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const { threads } = yield* query.getCommandReadModel();
const running = threads.filter(
(thread) =>
thread.archivedAt === null &&
thread.deletedAt === null &&
thread.session?.status === "running" &&
thread.session.activeTurnId !== null,
);
const marked: ThreadId[] = [];
return yield* Effect.gen(function* () {
for (const thread of running) {
const activeTurnId = thread.session?.activeTurnId;
if (activeTurnId === null || activeTurnId === undefined) {
continue;
}
const binding = yield* directory.getBinding(thread.id);
if (Option.isNone(binding)) {
continue;
}
if (binding.value.resumeCursor === null || binding.value.resumeCursor === undefined) {
continue;
}
yield* directory.upsert({
...binding.value,
runtimePayload: {
...readRuntimePayload(binding.value.runtimePayload),
[SERVER_UPDATE_CONTINUATION_KEY]: activeTurnId,
},
});
marked.push(thread.id);
}
return marked;
}).pipe(
Effect.catchCause((cause) =>
clearProviderSessionContinuationMarkers(marked).pipe(Effect.andThen(Effect.failCause(cause))),
),
);
}).pipe(Effect.mapError(toServerUpdateThreadContinuationError));
const clearContinuationMarkers = (
directory: ProviderSessionDirectory.ProviderSessionDirectory["Service"],
threadIds: ReadonlyArray<ThreadId>,
) =>
Effect.forEach(
threadIds,
(threadId) =>
directory.getBinding(threadId).pipe(
Effect.flatMap(
Option.match({
onNone: () => Effect.void,
onSome: (binding) =>
directory.upsert({
...binding,
runtimePayload: {
...readRuntimePayload(binding.runtimePayload),
[SERVER_UPDATE_CONTINUATION_KEY]: null,
},
}),
}),
),
),
{ concurrency: "unbounded", discard: true },
);
export const clearProviderSessionContinuationMarkers = (threadIds: ReadonlyArray<ThreadId>) =>
Effect.gen(function* () {
const directory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
yield* clearContinuationMarkers(directory, threadIds);
}).pipe(Effect.mapError(toServerUpdateThreadContinuationError));
export const reconcileProviderSessions = Effect.gen(function* () {
const crypto = yield* Crypto.Crypto;
@@ -320,52 +460,165 @@ export const reconcileProviderSessions = Effect.gen(function* () {
if (session === null) {
continue;
}
yield* Effect.gen(function* () {
const binding = yield* directory.getBinding(thread.id);
if (Option.isSome(binding)) {
const binding = yield* directory.getBinding(thread.id).pipe(
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.failCause(cause)
: Effect.logWarning("failed to read orphaned provider session directory binding", {
threadId: thread.id,
cause,
}).pipe(Effect.as(Option.none())),
),
);
const continuationMarkerPresent =
Option.isSome(binding) && hasServerUpdateContinuationMarker(binding.value.runtimePayload);
const continuationTurnId = Option.isSome(binding)
? readServerUpdateContinuationTurnId(binding.value.runtimePayload)
: null;
const continuationMarked =
continuationTurnId !== null &&
(session.activeTurnId === null || continuationTurnId === session.activeTurnId);
const settleAsError = (lastError: string) =>
Effect.gen(function* () {
yield* Effect.gen(function* () {
if (Option.isSome(binding)) {
yield* directory.upsert({
...binding.value,
status: "stopped",
runtimePayload: {
...readRuntimePayload(binding.value.runtimePayload),
activeTurnId: null,
...(continuationMarkerPresent ? { [SERVER_UPDATE_CONTINUATION_KEY]: null } : {}),
},
});
}
}).pipe(
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.failCause(cause)
: Effect.logWarning(
"failed to reconcile orphaned provider session directory binding",
{ threadId: thread.id, cause },
),
),
);
yield* Effect.gen(function* () {
const reconciledAt = DateTime.formatIso(yield* DateTime.now);
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
threadId: thread.id,
session: {
...session,
status: "error",
activeTurnId: null,
lastError,
updatedAt: reconciledAt,
},
createdAt: reconciledAt,
});
}).pipe(
Effect.retry({ times: 1 }),
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.failCause(cause)
: Effect.logWarning("failed to settle orphaned provider session projection", {
threadId: thread.id,
cause,
}),
),
);
});
if (
Option.isSome(binding) &&
continuationMarked &&
thread.archivedAt === null &&
thread.deletedAt === null
) {
const prepared = yield* Effect.gen(function* () {
yield* directory.upsert({
...binding.value,
status: "stopped",
runtimePayload: { activeTurnId: null },
status: "starting",
runtimePayload: {
...readRuntimePayload(binding.value.runtimePayload),
activeTurnId: null,
},
});
const resumedAt = DateTime.formatIso(yield* DateTime.now);
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
threadId: thread.id,
session: {
...session,
status: "starting",
activeTurnId: null,
lastError: null,
updatedAt: resumedAt,
},
createdAt: resumedAt,
});
}).pipe(Effect.retry({ times: 1 }), Effect.exit);
if (Exit.isFailure(prepared)) {
if (Cause.hasInterrupts(prepared.cause)) {
return yield* Effect.failCause(prepared.cause);
}
yield* Effect.logWarning("failed to prepare provider session continuation", {
threadId: thread.id,
cause: prepared.cause,
});
yield* settleAsError(ORPHANED_PROVIDER_SESSION_ERROR);
continue;
}
}).pipe(
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.failCause(cause)
: Effect.logWarning("failed to reconcile orphaned provider session directory binding", {
threadId: thread.id,
cause,
}),
),
);
yield* Effect.gen(function* () {
const reconciledAt = DateTime.formatIso(yield* DateTime.now);
yield* orchestrationEngine.dispatch({
type: "thread.session.set",
commandId: CommandId.make(yield* crypto.randomUUIDv4),
threadId: thread.id,
session: {
...session,
status: "error",
activeTurnId: null,
lastError: ORPHANED_PROVIDER_SESSION_ERROR,
updatedAt: reconciledAt,
},
createdAt: reconciledAt,
});
}).pipe(
Effect.retry({ times: 1 }),
Effect.catchCause((cause) =>
Cause.hasInterrupts(cause)
? Effect.failCause(cause)
: Effect.logWarning("failed to settle orphaned provider session projection", {
yield* forkParked(
Effect.gen(function* () {
const continuation = Effect.gen(function* () {
const providerInstanceId = binding.value.providerInstanceId;
if (providerInstanceId === undefined) {
return yield* new ProviderSessionContinuationError({
threadId: thread.id,
});
}
const capabilities = yield* providerService.getCapabilities(providerInstanceId);
yield* providerService.sendTurn({
threadId: thread.id,
cause,
}),
),
);
...(capabilities.promptlessTurnContinuation === true
? { continuation: true }
: { input: SERVER_UPDATE_CONTINUATION_PROMPT }),
interactionMode: thread.interactionMode,
});
});
const continuationExit = yield* Effect.exit(continuation);
if (Exit.isSuccess(continuationExit) || Cause.hasInterrupts(continuationExit.cause)) {
if (Exit.isSuccess(continuationExit)) {
yield* clearContinuationMarkers(directory, [thread.id]).pipe(
Effect.uninterruptible,
Effect.catchCause((cause) =>
Effect.logWarning("failed to clear completed provider session continuation", {
threadId: thread.id,
cause,
}),
),
);
}
return;
}
yield* Effect.logWarning("failed to continue provider session after server update", {
threadId: thread.id,
cause: continuationExit.cause,
});
yield* settleAsError(
"Could not continue this thread after the server update. Send a new message to continue.",
).pipe(Effect.ignoreCause);
}),
);
continue;
}
yield* settleAsError(ORPHANED_PROVIDER_SESSION_ERROR);
}
}).pipe(
Effect.catchCause((cause) =>
@@ -390,6 +643,8 @@ export const make = (options?: StartupOptions) =>
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
const serverSettings = yield* ServerSettings.ServerSettingsService;
const serverEnvironment = yield* ServerEnvironment.ServerEnvironment;
const projectionSnapshotQuery = yield* ProjectionSnapshotQuery.ProjectionSnapshotQuery;
const providerSessionDirectory = yield* ProviderSessionDirectory.ProviderSessionDirectory;
const crypto = yield* Crypto.Crypto;
const launcher = yield* ServiceLauncherClient.ServiceLauncherClient;
@@ -577,6 +832,23 @@ export const make = (options?: StartupOptions) =>
return {
awaitCommandReady: commandGate.awaitCommandReady,
markHttpListening: Deferred.succeed(httpListening, undefined),
markRunningProviderSessionsForContinuation: markRunningProviderSessionsForContinuation.pipe(
Effect.provideService(
ProjectionSnapshotQuery.ProjectionSnapshotQuery,
projectionSnapshotQuery,
),
Effect.provideService(
ProviderSessionDirectory.ProviderSessionDirectory,
providerSessionDirectory,
),
),
clearProviderSessionContinuationMarkers: (threadIds) =>
clearProviderSessionContinuationMarkers(threadIds).pipe(
Effect.provideService(
ProviderSessionDirectory.ProviderSessionDirectory,
providerSessionDirectory,
),
),
enqueueCommand: commandGate.enqueueCommand,
} satisfies ServerRuntimeStartup["Service"];
});
+31 -6
View File
@@ -50,7 +50,7 @@ import {
ProviderUploadFeedbackError,
RelayClientInstallFailedError,
type RelayClientInstallProgressEvent,
type ServerSelfUpdateError,
ServerSelfUpdateError,
type ServerSelfUpdateProgressEvent,
type FilesystemBrowseFailure,
FilesystemBrowseError,
@@ -509,7 +509,7 @@ const makeWsRpcLayer = (
const providerRegistry = yield* ProviderRegistry.ProviderRegistry;
const providerService = yield* ProviderService.ProviderService;
const providerMaintenanceRunner = yield* ProviderMaintenanceRunner.ProviderMaintenanceRunner;
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
const serverUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
const config = yield* ServerConfig.ServerConfig;
const lifecycleEvents = yield* ServerLifecycleEvents.ServerLifecycleEvents;
const serverSettings = yield* ServerSettings.ServerSettingsService;
@@ -1700,14 +1700,14 @@ const makeWsRpcLayer = (
},
),
[WS_METHODS.serverUpdateServer]: (input) =>
observeRpcEffect(WS_METHODS.serverUpdateServer, serverSelfUpdate.update(input), {
observeRpcEffect(WS_METHODS.serverUpdateServer, serverUpdate.update(input), {
"rpc.aggregate": "server",
}),
[WS_METHODS.serverUpdateServerWithProgress]: (input) =>
observeRpcStream(
WS_METHODS.serverUpdateServerWithProgress,
Stream.callback<ServerSelfUpdateProgressEvent, ServerSelfUpdateError>((queue) =>
serverSelfUpdate
serverUpdate
.update(input, (stage) =>
Queue.offer(queue, {
type: "progress",
@@ -1733,7 +1733,7 @@ const makeWsRpcLayer = (
[WS_METHODS.serverCommitDesktopUpdate]: (input) =>
observeRpcEffect(
WS_METHODS.serverCommitDesktopUpdate,
serverSelfUpdate.commitDesktopUpdate(input.requestId),
serverUpdate.commitDesktopUpdate(input.requestId),
{ "rpc.aggregate": "server" },
),
[WS_METHODS.serverUpsertKeybinding]: (rule) =>
@@ -2578,7 +2578,32 @@ const makeWsRpcLayer = (
export const websocketRpcRouteLayer = Layer.unwrap(
Effect.gen(function* () {
const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;
const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
const baseServerSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;
const config = yield* ServerConfig.ServerConfig;
const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;
const serverSelfUpdate = yield* ServerSelfUpdate.withRunningThreadContinuation({
mode: config.mode,
selfUpdate: baseServerSelfUpdate,
prepare: startup.markRunningProviderSessionsForContinuation.pipe(
Effect.mapError(
(cause) =>
new ServerSelfUpdateError({
reason: "Could not prepare running threads to continue after the update.",
cause,
}),
),
),
clear: (threadIds) =>
startup.clearProviderSessionContinuationMarkers(threadIds).pipe(
Effect.mapError(
(cause) =>
new ServerSelfUpdateError({
reason: "Could not clear thread continuation markers after the update failed.",
cause,
}),
),
),
});
const pullRequests = yield* PullRequestService.PullRequestService;
return HttpRouter.add(
"GET",
+4
View File
@@ -428,6 +428,7 @@ import {
resolveServerSelfUpdateCapability,
serverUpdateGuidance,
supportsDesktopAppUpdate,
supportsServerUpdateThreadContinuation,
} from "../versionSkew";
import { useAssetUrls } from "../assets/assetUrls";
@@ -2221,6 +2222,7 @@ function ChatViewContent(props: ChatViewProps) {
const serverUpdateEnvironmentId = activeThread?.environmentId ?? null;
const versionMismatchSelfUpdate = resolveServerSelfUpdateCapability(serverConfig);
const versionMismatchDesktopAppUpdate = supportsDesktopAppUpdate(serverConfig);
const versionMismatchThreadContinuation = supportsServerUpdateThreadContinuation(serverConfig);
const serverUpdateState = useAtomValue(
serverEnvironment.updateStateAtom(serverUpdateEnvironmentId),
);
@@ -2356,6 +2358,7 @@ function ChatViewContent(props: ChatViewProps) {
serverLabel={versionMismatchServerLabel}
selfUpdate={versionMismatchSelfUpdate}
desktopAppUpdate={versionMismatchDesktopAppUpdate}
threadContinuation={versionMismatchThreadContinuation}
targetVersion={versionMismatch.clientVersion}
label={updateFailed ? "Retry" : "Update"}
variant="ghost"
@@ -2391,6 +2394,7 @@ function ChatViewContent(props: ChatViewProps) {
serverUpdateEnvironmentId,
versionMismatchSelfUpdate,
versionMismatchDesktopAppUpdate,
versionMismatchThreadContinuation,
versionMismatchServerLabel,
]);
const providerStatuses = serverConfig?.providers ?? EMPTY_PROVIDERS;
@@ -8,11 +8,17 @@ import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
const testState = vi.hoisted(() => ({
updateServer: vi.fn(),
toast: vi.fn(),
continueThreadsAfterServerUpdate: false,
}));
vi.mock("~/hooks/useCopyToClipboard", () => ({
useCopyToClipboard: () => ({ copyToClipboard: vi.fn() }),
}));
vi.mock("~/hooks/useSettings", () => ({
useClientSettings: (
selector: (settings: { continueThreadsAfterServerUpdate: boolean }) => unknown,
) => selector({ continueThreadsAfterServerUpdate: testState.continueThreadsAfterServerUpdate }),
}));
vi.mock("~/state/server", () => ({
serverEnvironment: { updateServer: Symbol("updateServer") },
}));
@@ -47,6 +53,7 @@ describe("ServerUpdateAction", () => {
beforeEach(() => {
testState.updateServer.mockReset();
testState.toast.mockReset();
testState.continueThreadsAfterServerUpdate = false;
});
it("reports success only after the shared update flow reconnects", async () => {
@@ -141,6 +148,49 @@ describe("ServerUpdateAction", () => {
description: "Desktop app relaunched on 0.0.34.",
});
});
it("leaves thread continuation off by default", async () => {
testState.updateServer.mockResolvedValue(
AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),
);
const action = ServerUpdateAction({
environmentId: "env-test" as EnvironmentId,
serverLabel: "Test server",
selfUpdate: "boot-service",
threadContinuation: true,
targetVersion: "0.0.31",
}) as ActionElement;
action.props.onClick?.();
await flushPromises();
expect(testState.updateServer).toHaveBeenCalledWith({
environmentId: "env-test",
input: { targetVersion: "0.0.31" },
});
});
it("applies the saved thread continuation preference automatically", async () => {
testState.updateServer.mockResolvedValue(
AsyncResult.success({ targetVersion: "0.0.31", method: "boot-service" as const }),
);
testState.continueThreadsAfterServerUpdate = true;
const action = ServerUpdateAction({
environmentId: "env-test" as EnvironmentId,
serverLabel: "Test server",
selfUpdate: "boot-service",
threadContinuation: true,
targetVersion: "0.0.31",
}) as ActionElement;
action.props.onClick?.();
await flushPromises();
expect(testState.updateServer).toHaveBeenCalledWith({
environmentId: "env-test",
input: { targetVersion: "0.0.31", continueRunningThreads: true },
});
});
});
describe("ServerUpdateProgress", () => {
+13 -1
View File
@@ -8,6 +8,7 @@ import type { ComponentProps } from "react";
import { requestConfirmDialog } from "~/confirmDialog";
import { useCopyToClipboard } from "~/hooks/useCopyToClipboard";
import { useClientSettings } from "~/hooks/useSettings";
import { serverEnvironment } from "~/state/server";
import { useAtomCommand } from "~/state/use-atom-command";
import { manualServerUpdateCommand } from "~/versionSkew";
@@ -78,6 +79,7 @@ export function ServerUpdateAction({
serverLabel,
selfUpdate,
desktopAppUpdate = false,
threadContinuation = false,
targetVersion,
label = "Update",
variant = "outline",
@@ -88,11 +90,16 @@ export function ServerUpdateAction({
/** The desktop app supervising this server accepts remote update
requests (capabilities.desktopAppUpdate). */
readonly desktopAppUpdate?: boolean;
/** The server can durably continue running provider turns after updating. */
readonly threadContinuation?: boolean;
readonly targetVersion: string;
readonly label?: string;
readonly variant?: ComponentProps<typeof Button>["variant"];
}) {
const isDesktopAppUpdate = selfUpdate === "desktop-managed";
const continueThreadsAfterServerUpdate = useClientSettings(
(settings) => settings.continueThreadsAfterServerUpdate,
);
const updateServer = useAtomCommand(serverEnvironment.updateServer, {
reportFailure: false,
});
@@ -137,7 +144,12 @@ export function ServerUpdateAction({
try {
const result = await updateServer({
environmentId,
input: { targetVersion },
input: {
targetVersion,
...(threadContinuation && continueThreadsAfterServerUpdate
? { continueRunningThreads: true }
: {}),
},
});
if (result._tag === "Failure") {
if (isAtomCommandInterrupted(result)) {
@@ -105,6 +105,7 @@ import {
resolveServerConfigVersionMismatch,
resolveServerSelfUpdateCapability,
supportsDesktopAppUpdate,
supportsServerUpdateThreadContinuation,
} from "~/versionSkew";
import { hasCloudPublicConfig } from "~/cloud/publicConfig";
import { useCloudLinkController } from "~/cloud/useCloudLinkController";
@@ -1487,6 +1488,7 @@ function SavedBackendListRow({
serverLabel={`${environment.label} server`}
selfUpdate={resolveServerSelfUpdateCapability(environment.serverConfig)}
desktopAppUpdate={supportsDesktopAppUpdate(environment.serverConfig)}
threadContinuation={supportsServerUpdateThreadContinuation(environment.serverConfig)}
targetVersion={versionMismatch.clientVersion}
label={serverUpdateState.status === "failed" ? "Retry" : "Update"}
/>
@@ -3064,6 +3066,9 @@ export function ConnectionsSettings() {
}
selfUpdate={resolveServerSelfUpdateCapability(primaryServerConfig)}
desktopAppUpdate={supportsDesktopAppUpdate(primaryServerConfig)}
threadContinuation={supportsServerUpdateThreadContinuation(
primaryServerConfig,
)}
targetVersion={primaryVersionMismatch.clientVersion}
label={primaryServerUpdateState.status === "failed" ? "Retry" : "Update"}
/>
@@ -533,6 +533,10 @@ export function useSettingsRestore(onRestored?: () => void) {
DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks
? ["Provider update checks"]
: []),
...(settings.continueThreadsAfterServerUpdate !==
DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate
? ["Continue threads after server updates"]
: []),
...(isBackgroundActivityDirty ? ["Background activity"] : []),
...(settings.defaultThreadEnvMode !== DEFAULT_UNIFIED_SETTINGS.defaultThreadEnvMode
? ["New thread mode"]
@@ -591,6 +595,7 @@ export function useSettingsRestore(onRestored?: () => void) {
settings.glassOpacity,
settings.enableLegacyTokenStreaming,
settings.enableProviderUpdateChecks,
settings.continueThreadsAfterServerUpdate,
settings.sidebarAutoSettleAfterDays,
settings.sidebarAutoSettleOnMerge,
settings.sidebarProjectGroupingMode,
@@ -681,6 +686,7 @@ export function useSettingsRestore(onRestored?: () => void) {
sidebarAutoSettleOnMerge: DEFAULT_UNIFIED_SETTINGS.sidebarAutoSettleOnMerge,
enableLegacyTokenStreaming: DEFAULT_UNIFIED_SETTINGS.enableLegacyTokenStreaming,
enableProviderUpdateChecks: DEFAULT_UNIFIED_SETTINGS.enableProviderUpdateChecks,
continueThreadsAfterServerUpdate: DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate,
backgroundActivity: DEFAULT_UNIFIED_SETTINGS.backgroundActivity,
backgroundActivityProfile: DEFAULT_UNIFIED_SETTINGS.backgroundActivityProfile,
automaticGitFetchInterval: DEFAULT_UNIFIED_SETTINGS.automaticGitFetchInterval,
@@ -2185,6 +2191,34 @@ export function GeneralSettingsPanel() {
}
/>
<SettingsRow
{...searchableSetting("continue-threads-after-server-update")}
description="Automatically resume active threads after a server update restarts the environment."
resetAction={
settings.continueThreadsAfterServerUpdate !==
DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate ? (
<SettingResetButton
label="continue threads after server updates"
onClick={() =>
updateSettings({
continueThreadsAfterServerUpdate:
DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate,
})
}
/>
) : null
}
control={
<Switch
checked={settings.continueThreadsAfterServerUpdate}
onCheckedChange={(checked) =>
updateSettings({ continueThreadsAfterServerUpdate: Boolean(checked) })
}
aria-label="Continue threads after server updates"
/>
}
/>
<SettingsRow
serverScoped
id={searchableSetting("background-activity").id}
@@ -191,6 +191,12 @@ export const SETTINGS_SEARCH_ITEMS = [
to: "/settings/general",
searchTerms: ["installed cli versions newer available codex claude cursor grok opencode"],
},
{
id: "continue-threads-after-server-update",
title: "Continue threads after server updates",
to: "/settings/general",
searchTerms: ["resume running active work restart desktop update automatically"],
},
{
id: "background-activity",
title: "Background activity",
+8
View File
@@ -106,6 +106,14 @@ export function supportsDesktopAppUpdate(
return serverConfig?.environment.capabilities.desktopAppUpdate === true;
}
/** True when the connected server can recover opted-in running turns after
its self-update restart. */
export function supportsServerUpdateThreadContinuation(
serverConfig: Pick<ServerConfig, "environment"> | null | undefined,
): boolean {
return serverConfig?.environment.capabilities.serverUpdateThreadContinuation === true;
}
/** The command to hand users whose server cannot update itself. */
export function manualServerUpdateCommand(targetVersion: string): string {
return `npx t3@${targetVersion}`;
+6 -2
View File
@@ -15,8 +15,12 @@ update the server, and the version difference remains visible in Connections.
## Before You Update
Let active agent work and terminal commands finish first. Updating restarts the server, so the
connection will disappear briefly and work that is still running may be interrupted.
Updating restarts the server, so the connection will disappear briefly. **Settings** → **General**
has a **Continue threads after server updates** preference. It is off by default. When enabled, the
update buttons automatically resume supported provider threads after the replacement server is
ready. Providers with native promptless continuation use it; other providers receive a short
instruction to continue where they left off. Terminal commands and other running work may still be
interrupted during the update.
The update does not remove saved threads, settings, or project files.
+3
View File
@@ -93,6 +93,9 @@ export const ExecutionEnvironmentCapabilities = Schema.Struct({
/** Server can stream self-update progress before acknowledging the
restart. Clients fall back to server.updateServer when absent. */
serverSelfUpdateProgress: Schema.optionalKey(Schema.Boolean),
/** Server can durably mark running provider turns before a self-update and
continue them after the replacement process starts. */
serverUpdateThreadContinuation: Schema.optionalKey(Schema.Boolean),
/** Agent-activity publishes (push notifications and Live Activities)
currently leave this environment: the publish opt-in is enabled and the
relay link credentials exist. Clients skip seeding a Live Activity when
+3
View File
@@ -67,6 +67,9 @@ export type ProviderSessionStartInput = typeof ProviderSessionStartInput.Type;
export const ProviderSendTurnInput = Schema.Struct({
threadId: ThreadId,
/** Internal recovery signal. Allows an empty turn only for adapters that
explicitly support promptless continuation. */
continuation: Schema.optional(Schema.Boolean),
input: Schema.optional(
TrimmedNonEmptyString.check(Schema.isMaxLength(PROVIDER_SEND_TURN_MAX_INPUT_CHARS)),
),
+4
View File
@@ -754,6 +754,10 @@ export const ServerSelfUpdateInput = Schema.Struct({
/** Exact npm version of the `t3` package to install (never a dist-tag, so
the server and the acknowledging client agree on what was requested). */
targetVersion: TrimmedNonEmptyString,
/** Opt-in recovery for provider turns that are running when the server
hands off to its replacement. Missing and false keep restart behavior
conservative under version skew. */
continueRunningThreads: Schema.optionalKey(Schema.Boolean),
});
export type ServerSelfUpdateInput = typeof ServerSelfUpdateInput.Type;
+4
View File
@@ -207,6 +207,9 @@ export const ClientSettingsSchema = Schema.Struct({
confirmThreadArchive: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
confirmThreadDelete: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(true))),
confirmThreadUnpin: Schema.Boolean.pipe(Schema.withDecodingDefault(Effect.succeed(false))),
continueThreadsAfterServerUpdate: Schema.Boolean.pipe(
Schema.withDecodingDefault(Effect.succeed(false)),
),
dismissedProviderUpdateNotificationKeys: Schema.Array(TrimmedNonEmptyString).pipe(
Schema.withDecodingDefault(Effect.succeed([])),
),
@@ -959,6 +962,7 @@ export const ClientSettingsPatch = Schema.Struct({
confirmThreadArchive: Schema.optionalKey(Schema.Boolean),
confirmThreadDelete: Schema.optionalKey(Schema.Boolean),
confirmThreadUnpin: Schema.optionalKey(Schema.Boolean),
continueThreadsAfterServerUpdate: Schema.optionalKey(Schema.Boolean),
diffIgnoreWhitespace: Schema.optionalKey(Schema.Boolean),
environmentIdentificationMode: Schema.optionalKey(EnvironmentIdentificationMode),
glassOpacity: Schema.optionalKey(GlassOpacity),