feat(updates): continue active threads across server restarts #9167
Mergedmaria-rcksmerged 8 commits into
main fromrefs/pull/9167/headmerged by maria-rcks View on GitHubgithub-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:L
- @@ -297,0 +310,21 @@310+ {311+ threadId: ThreadId,312+ reason: Schema.String,313+ },314+) {315+ override get message(): string {316+ return `Could not continue thread '${this.threadId}': ${this.reason}`;317+ }318+}319+320+export class ServerUpdateThreadContinuationError extends Schema.TaggedErrorClass<ServerUpdateThreadContinuationError>()(321+ "ServerUpdateThreadContinuationError",322+ {323+ reason: Schema.String,324+ cause: Schema.Defect(),325+ },326+) {327+ override get message(): string {328+ return this.reason;329+ }330+}
- @@ -297,0 +350,21 @@350+ thread.session?.status === "running" &&351+ thread.session.activeTurnId !== null,352+ );353+354+ const marked: ThreadId[] = [];355+ return yield* Effect.gen(function* () {356+ for (const thread of running) {357+ const binding = yield* directory.getBinding(thread.id);358+ if (Option.isNone(binding)) {359+ return yield* new ProviderSessionContinuationError({360+ threadId: thread.id,361+ reason: "No provider binding is persisted.",362+ });363+ }364+ if (binding.value.resumeCursor === null || binding.value.resumeCursor === undefined) {365+ return yield* new ProviderSessionContinuationError({366+ threadId: thread.id,367+ reason: "No provider resume state is persisted.",368+ });369+ }370+ yield* directory.upsert({apps/server/src/ws.ts line 521OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -518,3 +518,4 @@518518 const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;519519 const workspaceEntries = yield* WorkspaceEntries.WorkspaceEntries;520520 const workspaceFileSystem = yield* WorkspaceFileSystem.WorkspaceFileSystem;521+ const serverUpdate = ServerSelfUpdate.withRunningThreadContinuation({apps/server/src/serverRuntimeStartup.ts line 802OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -578,3 +783,20 @@578783 return {579784 awaitCommandReady: commandGate.awaitCommandReady,580785 markHttpListening: Deferred.succeed(httpListening, undefined),786+ markRunningProviderSessionsForContinuation: markRunningProviderSessionsForContinuation.pipe(787+ Effect.provideService(788+ ProjectionSnapshotQuery.ProjectionSnapshotQuery,789+ projectionSnapshotQuery,790+ ),791+ Effect.provideService(792+ ProviderSessionDirectory.ProviderSessionDirectory,793+ providerSessionDirectory,794+ ),795+ ),796+ clearProviderSessionContinuationMarkers: (threadIds) =>797+ clearProviderSessionContinuationMarkers(threadIds).pipe(798+ Effect.provideService(799+ ProviderSessionDirectory.ProviderSessionDirectory,800+ providerSessionDirectory,801+ ),802+ Effect.ignoreCause({ log: true }),
- apps/server/src/serverRuntimeStartup.ts lines 501 to 501OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -358,7 +487,15 @@487+ });488+ }).pipe(489+ Effect.retry({ times: 1 }),490+ Effect.catchCause((cause) =>491+ Cause.hasInterrupts(cause)492+ ? Effect.failCause(cause)493+ : Effect.logWarning("failed to settle orphaned provider session projection", {494+ threadId: thread.id,495+ cause,496+ }),497+ ),498+ );358499 });359- }).pipe(360- Effect.retry({ times: 1 }),361- Effect.catchCause((cause) =>362- Cause.hasInterrupts(cause)363- ? Effect.failCause(cause)364- : Effect.logWarning("failed to settle orphaned provider session projection", {500+501+ if (Option.isSome(binding) && continuationMarked) {docs/user/updating.md lines 18 to 22OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -15,5 +15,8 @@15151616 ## Before You Update171718-Let active agent work and terminal commands finish first. Updating restarts the server, so the19-connection will disappear briefly and work that is still running may be interrupted.18+Updating restarts the server, so the connection will disappear briefly. **Settings** → **General**19+has a **Continue threads after server updates** preference. It is off by default. When enabled, the20+update buttons automatically resume active work after the replacement server is ready. Providers21+with native promptless continuation use it; other providers receive a short instruction to continue22+where they left off.
- @@ -2168,0 +2175,21 @@2175+ <SettingResetButton2176+ label="continue threads after server updates"2177+ onClick={() =>2178+ updateSettings({2179+ continueThreadsAfterServerUpdate:2180+ DEFAULT_UNIFIED_SETTINGS.continueThreadsAfterServerUpdate,2181+ })2182+ }2183+ />2184+ ) : null2185+ }2186+ control={2187+ <Switch2188+ checked={settings.continueThreadsAfterServerUpdate}2189+ onCheckedChange={(checked) =>2190+ updateSettings({ continueThreadsAfterServerUpdate: Boolean(checked) })2191+ }2192+ aria-label="Continue threads after server updates"2193+ />2194+ }2195+ />
- apps/server/src/serverRuntimeStartup.ts lines 524 to 524OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -364,0 +504,21 @@504+ ...binding.value,505+ runtimePayload: {506+ [SERVER_UPDATE_CONTINUATION_KEY]: null,507+ activeTurnId: null,508+ },509+ });510+ const resumedAt = DateTime.formatIso(yield* DateTime.now);511+ yield* orchestrationEngine.dispatch({512+ type: "thread.session.set",513+ commandId: CommandId.make(yield* crypto.randomUUIDv4),514+ threadId: thread.id,515+ session: {516+ ...session,517+ status: "starting",518+ activeTurnId: null,519+ lastError: null,520+ updatedAt: resumedAt,521+ },522+ createdAt: resumedAt,523+ });524+ }).pipe(Effect.exit);apps/server/src/cloud/selfUpdate.ts lines 55 to 61OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -41,11 +42,20 @@4142 {4243 readonly update: (4344 input: ServerSelfUpdateInput,44- reportProgress?: (stage: ServerSelfUpdateProgressStage) => Effect.Effect<void>,45+ reportProgress?: (46+ stage: ServerSelfUpdateProgressStage,47+ ) => Effect.Effect<void, ServerSelfUpdateError>,4548 ) => Effect.Effect<ServerSelfUpdateResult, ServerSelfUpdateError>;4649 readonly commitDesktopUpdate: (4750 requestId: string,4851 ) => Effect.Effect<never, ServerSelfUpdateError>;4952 }5053 >()("t3/cloud/selfUpdate/ServerSelfUpdate") {}515455+export function withRunningThreadContinuation(input: {56+ readonly mode: ServerConfig.RuntimeMode;57+ readonly selfUpdate: ServerSelfUpdate["Service"];58+ readonly prepare: Effect.Effect<ReadonlyArray<ThreadId>, ServerSelfUpdateError>;59+ readonly clear: (threadIds: ReadonlyArray<ThreadId>) => Effect.Effect<void>;60+}): ServerSelfUpdate["Service"] {61+ const desktopContinuationTokens = new Set<string>();apps/server/src/serverRuntimeStartup.ts lines 319 to 328Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -297,0 +310,21 @@310+ {311+ threadId: ThreadId,312+ reason: Schema.String,313+ },314+) {315+ override get message(): string {316+ return `Could not continue thread '${this.threadId}': ${this.reason}`;317+ }318+}319+320+export class ServerUpdateThreadContinuationError extends Schema.TaggedErrorClass<ServerUpdateThreadContinuationError>()(321+ "ServerUpdateThreadContinuationError",322+ {323+ reason: Schema.String,324+ cause: Schema.Defect(),325+ },326+) {327+ override get message(): string {328+ return this.reason;329+ }330+}
- @@ -327,16 +437,12 @@327- yield* directory.upsert({328- ...binding.value,329- status: "stopped",330- runtimePayload: { activeTurnId: null },331- });332- }333- }).pipe(437+ const binding = yield* directory.getBinding(thread.id).pipe(334438 Effect.catchCause((cause) =>335439 Cause.hasInterrupts(cause)336440 ? Effect.failCause(cause)337- : Effect.logWarning("failed to reconcile orphaned provider session directory binding", {441+ : Effect.logWarning("failed to read orphaned provider session directory binding", {338442 threadId: thread.id,339443 cause,340- }),444+ }).pipe(Effect.as(Option.none())),341445 ),342446 );447+ const continuationMarked =448+ Option.isSome(binding) && hasServerUpdateContinuationMarker(binding.value.runtimePayload);@@ -297,0 +348,21 @@348+ thread.archivedAt === null &&349+ thread.deletedAt === null &&350+ thread.session?.status === "running" &&351+ thread.session.activeTurnId !== null,352+ );353+354+ const marked: ThreadId[] = [];355+ return yield* Effect.gen(function* () {356+ for (const thread of running) {357+ const binding = yield* directory.getBinding(thread.id);358+ if (Option.isNone(binding)) {359+ return yield* new ProviderSessionContinuationError({360+ threadId: thread.id,361+ reason: "No provider binding is persisted.",362+ });363+ }364+ if (binding.value.resumeCursor === null || binding.value.resumeCursor === undefined) {365+ return yield* new ProviderSessionContinuationError({366+ threadId: thread.id,367+ reason: "No provider resume state is persisted.",368+ });@@ -51,0 +91,21 @@91+ result.method === "desktop-app" &&92+ result.desktopUpdateToken !== undefined &&93+ request.continueRunningThreads === true94+ ) {95+ desktopContinuationTokens.add(result.desktopUpdateToken);96+ }97+ }),98+ ),99+ Effect.onError(() => input.clear(continuationThreadIds)),100+ );101+ };102+103+ return ServerSelfUpdate.of({104+ update,105+ commitDesktopUpdate: (requestId) =>106+ Effect.gen(function* () {107+ const shouldContinue = desktopContinuationTokens.delete(requestId);108+ const continuationThreadIds = shouldContinue ? yield* input.prepare : [];109+ return yield* input.selfUpdate110+ .commitDesktopUpdate(requestId)111+ .pipe(Effect.onError(() => input.clear(continuationThreadIds)));@@ -321,13 +434,4 @@321434 if (session === null) {322435 continue;323436 }324- yield* Effect.gen(function* () {325- const binding = yield* directory.getBinding(thread.id);326- if (Option.isSome(binding)) {327- yield* directory.upsert({328- ...binding.value,329- status: "stopped",330- runtimePayload: { activeTurnId: null },331- });332- }333- }).pipe(437+ const binding = yield* directory.getBinding(thread.id).pipe(
github-actions[bot](GitHub profile, opens in a new tab) removed labelssize:L
github-actions[bot](GitHub profile, opens in a new tab) added labelssize:XL
- apps/server/src/serverRuntimeStartup.ts lines 313 to 313OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -295,3 +303,11 @@295303296304 const ORPHANED_PROVIDER_SESSION_ERROR =297305 "Provider session did not survive a server restart. Send a new message to continue.";306+const SERVER_UPDATE_CONTINUATION_KEY = "continueAfterServerUpdate";307+const SERVER_UPDATE_CONTINUATION_PROMPT = "Continue where you left off.";308+309+class ProviderSessionContinuationError extends Schema.TaggedErrorClass<ProviderSessionContinuationError>()(310+ "ProviderSessionContinuationError",311+ {312+ threadId: ThreadId,313+ reason: Schema.String,apps/server/src/ws.ts lines 2571 to 2572OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -2565,4 +2565,8 @@25652565 export const websocketRpcRouteLayer = Layer.unwrap(25662566 Effect.gen(function* () {25672567 const previewAutomationBroker = yield* PreviewAutomationBroker.PreviewAutomationBroker;2568- const serverSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;2568+ const baseServerSelfUpdate = yield* ServerSelfUpdate.ServerSelfUpdate;2569+ const config = yield* ServerConfig.ServerConfig;2570+ const startup = yield* ServerRuntimeStartup.ServerRuntimeStartup;2571+ const toServerSelfUpdateError = (cause: Error) =>2572+ new ServerSelfUpdateError({ reason: cause.message, cause });
- apps/server/src/cloud/selfUpdate.ts line 76Resolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -48,4 +52,21 @@4852 ) => Effect.Effect<never, ServerSelfUpdateError>;4953 }5054 >()("t3/cloud/selfUpdate/ServerSelfUpdate") {}515556+export const withRunningThreadContinuation = Effect.fn(57+ "cloud.server_self_update.withRunningThreadContinuation",58+)(function* (input: {59+ readonly mode: ServerConfig.RuntimeMode;60+ readonly selfUpdate: ServerSelfUpdate["Service"];61+ readonly prepare: Effect.Effect<ReadonlyArray<ThreadId>, ServerSelfUpdateError>;62+ readonly clear: (63+ threadIds: ReadonlyArray<ThreadId>,64+ ) => Effect.Effect<void, ServerSelfUpdateError>;65+}) {66+ const desktopContinuationTokens = yield* Ref.make(HashSet.empty<string>());67+ const clearOnError = <A>(68+ effect: Effect.Effect<A, ServerSelfUpdateError>,69+ threadIds: () => ReadonlyArray<ThreadId>,70+ ): Effect.Effect<A, ServerSelfUpdateError> =>71+ effect.pipe(72+ Effect.catchCause((cause) =>apps/server/src/serverRuntimeStartup.ts line 539OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -358,7 +525,15 @@525+ );358526 });359- }).pipe(360- Effect.retry({ times: 1 }),361- Effect.catchCause((cause) =>362- Cause.hasInterrupts(cause)363- ? Effect.failCause(cause)364- : Effect.logWarning("failed to settle orphaned provider session projection", {527+528+ if (529+ Option.isSome(binding) &&530+ continuationMarked &&531+ thread.archivedAt === null &&532+ thread.deletedAt === null533+ ) {534+ const prepared = yield* Effect.gen(function* () {535+ yield* directory.upsert({536+ ...binding.value,537+ runtimePayload: {538+ ...readRuntimePayload(binding.value.runtimePayload),539+ [SERVER_UPDATE_CONTINUATION_KEY]: null,
- apps/server/src/cloud/selfUpdate.ts line 82Resolvedby cursor[bot](GitHub profile, opens in a new tab)@@ -51 +55,21 @@515556+export const withRunningThreadContinuation = Effect.fn(57+ "cloud.server_self_update.withRunningThreadContinuation",58+)(function* (input: {59+ readonly mode: ServerConfig.RuntimeMode;60+ readonly selfUpdate: ServerSelfUpdate["Service"];61+ readonly prepare: Effect.Effect<ReadonlyArray<ThreadId>, ServerSelfUpdateError>;62+ readonly clear: (63+ threadIds: ReadonlyArray<ThreadId>,64+ ) => Effect.Effect<void, ServerSelfUpdateError>;65+}) {66+ const desktopContinuationTokens = yield* Ref.make(HashSet.empty<string>());67+ const clearOnError = <A>(68+ effect: Effect.Effect<A, ServerSelfUpdateError>,69+ threadIds: () => ReadonlyArray<ThreadId>,70+ ): Effect.Effect<A, ServerSelfUpdateError> =>71+ effect.pipe(72+ Effect.catchCause((cause) =>73+ input.clear(threadIds()).pipe(Effect.andThen(Effect.failCause(cause))),74+ ),75+ );
- @@ -364,0 +536,21 @@536+ thread.archivedAt === null &&537+ thread.deletedAt === null538+ ) {539+ const prepared = yield* Effect.gen(function* () {540+ yield* directory.upsert({541+ ...binding.value,542+ status: "starting",543+ runtimePayload: {544+ ...readRuntimePayload(binding.value.runtimePayload),545+ activeTurnId: session.activeTurnId,546+ },547+ });548+ const resumedAt = DateTime.formatIso(yield* DateTime.now);549+ yield* orchestrationEngine.dispatch({550+ type: "thread.session.set",551+ commandId: CommandId.make(yield* crypto.randomUUIDv4),552+ threadId: thread.id,553+ session: {554+ ...session,555+ status: "starting",556+ activeTurnId: session.activeTurnId,@@ -51,0 +134,21 @@134+ Effect.gen(function* () {135+ const shouldContinue = yield* Ref.modify(desktopContinuationTokens, (tokens) => [136+ HashSet.has(tokens, requestId),137+ HashSet.remove(tokens, requestId),138+ ]);139+ let handoffAccepted = false;140+ let continuationThreadIds: ReadonlyArray<ThreadId> = [];141+ return yield* clearOnError(142+ Effect.gen(function* () {143+ continuationThreadIds = shouldContinue ? yield* input.prepare : [];144+ return yield* input.selfUpdate.commitDesktopUpdate(requestId, () =>145+ Effect.sync(() => {146+ handoffAccepted = true;147+ }),148+ );149+ }),150+ () => continuationThreadIds,151+ () => !handoffAccepted,152+ ).pipe(153+ Effect.catchCause((cause) =>154+ (shouldContinue && !handoffAccepted
- apps/server/src/cloud/selfUpdate.ts lines 77 to 77OutdatedResolvedby macroscopeapp[bot](GitHub profile, opens in a new tab)@@ -50,2 +57,21 @@5057 >()("t3/cloud/selfUpdate/ServerSelfUpdate") {}515859+export const withRunningThreadContinuation = Effect.fn(60+ "cloud.server_self_update.withRunningThreadContinuation",61+)(function* (input: {62+ readonly mode: ServerConfig.RuntimeMode;63+ readonly selfUpdate: ServerSelfUpdate["Service"];64+ readonly prepare: Effect.Effect<ReadonlyArray<ThreadId>, ServerSelfUpdateError>;65+ readonly clear: (66+ threadIds: ReadonlyArray<ThreadId>,67+ ) => Effect.Effect<void, ServerSelfUpdateError>;68+}) {69+ const desktopContinuationTokens = yield* Ref.make(HashSet.empty<string>());70+ const clearOnError = <A>(71+ effect: Effect.Effect<A, ServerSelfUpdateError>,72+ threadIds: () => ReadonlyArray<ThreadId>,73+ handoffAccepted: () => boolean,74+ ): Effect.Effect<A, ServerSelfUpdateError> =>75+ effect.pipe(76+ Effect.catchCause((cause) =>77+ (handoffAccepted() && Cause.hasInterrupts(cause)
maria-rcks merged this5b7d72a
maria-rcks closed this
Sign in to join this conversation.




macroscopeapp[bot](GitHub profile, opens in a new tab) reviewed