@devries-cameron20 / t3code-1 / commits / 5c9a01b747
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(server): archiving or deleting a thread releases its devices (#34175)

Bin Jamshid committed Nov 12, 2026 at 03:19 UTC 5c9a01b747421f019487da13bc3b55f5b8746f52
5 files changed +145 -3
apps/server/src/guest/GuestShareService.test.ts
+2 -1
@@ -90,7 +90,7 @@ const layerProviders = Layer.mock(ProviderRegistry.ProviderRegistry)({
90 getProviders: Effect.succeed([]),
91 });
92 const layerConfig = ServerConfig.layerTest(process.cwd(), { prefix: "t3-guest-share-" });
93 -// The real cleanup also closes terminals and previews; these tests only need the files gone.
93 +// The real cleanup also closes terminals, previews and devices; these tests only need the files gone.
94 const layerCleanup = Layer.effect(
95 ResourceCleanupService.ResourceCleanupService,
96 Effect.gen(function* () {
@@ -100,6 +100,7 @@ const layerCleanup = Layer.effect(
100 cleanupScheduledTasks: () => Effect.void,
101 cleanupTerminals: () => Effect.void,
102 cleanupPreviews: () => Effect.void,
103 + cleanupDevices: () => Effect.void,
104 cleanupAttachments: (attachmentIds) =>
105 Effect.forEach(
106 attachmentIds,
apps/server/src/orchestration-v2/EffectWorker.ts
+12 -1
@@ -526,8 +526,19 @@ export const layerExecutor: Layer.Layer<
526 }),
527 ),
528 );
529 + // Archive and delete queue this one per-thread teardown, so it also releases the
530 + // thread's device claims; the devices stay booted for other threads.
531 case "terminal.cleanup":
530 - return resourceCleanup.cleanupTerminals(effect.threadId).pipe(
532 + return Effect.partition(
533 + [
534 + resourceCleanup.cleanupTerminals(effect.threadId),
535 + resourceCleanup.cleanupDevices(effect.threadId),
536 + ],
537 + (cleanup) => cleanup,
538 + ).pipe(
539 + Effect.flatMap(([, [failure]]) =>
540 + failure === undefined ? Effect.void : Effect.fail(failure),
541 + ),
542 Effect.mapError(
543 (cause) =>
544 new OrchestrationEffectExecutionError({
apps/server/src/orchestration-v2/ResourceCleanupService.ts
+21 -1
@@ -8,6 +8,7 @@ import * as Schema from "effect/Schema";
8 import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
9 import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
10 import * as ServerConfig from "../config.ts";
11 +import * as DeviceService from "../device/DeviceService.ts";
12 import * as PreviewManager from "../preview/Manager.ts";
13 import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
14 import * as TerminalManager from "../terminal/Manager.ts";
@@ -15,7 +16,7 @@ import * as TerminalManager from "../terminal/Manager.ts";
16 export class ResourceCleanupError extends Schema.TaggedError<ResourceCleanupError>()(
17 "ResourceCleanupError",
18 {
18 - operation: Schema.Literals(["terminal", "preview", "attachment", "scheduled-tasks"]),
19 + operation: Schema.Literals(["terminal", "preview", "device", "attachment", "scheduled-tasks"]),
20 threadId: Schema.optional(Schema.String),
21 attachmentId: Schema.optional(Schema.String),
22 cause: Schema.Defect(),
@@ -26,6 +27,8 @@ export class ResourceCleanupService extends Context.Reference<{
27 readonly cleanupScheduledTasks: (threadId: ThreadId) => Effect.Effect<void, ResourceCleanupError>;
28 readonly cleanupTerminals: (threadId: string) => Effect.Effect<void, ResourceCleanupError>;
29 readonly cleanupPreviews: (threadId: string) => Effect.Effect<void, ResourceCleanupError>;
30 + /** Releases the thread's device claims, as `device_close` does; the devices stay booted. */
31 + readonly cleanupDevices: (threadId: ThreadId) => Effect.Effect<void, ResourceCleanupError>;
32 readonly cleanupAttachments: (
33 attachmentIds: ReadonlyArray<string>,
34 ) => Effect.Effect<void, ResourceCleanupError>;
@@ -34,6 +37,7 @@ export class ResourceCleanupService extends Context.Reference<{
37 cleanupScheduledTasks: () => Effect.void,
38 cleanupTerminals: () => Effect.void,
39 cleanupPreviews: () => Effect.void,
40 + cleanupDevices: () => Effect.void,
41 cleanupAttachments: () => Effect.void,
42 }),
43 }) {}
@@ -43,6 +47,7 @@ export const layer = Layer.effect(
47 Effect.gen(function* () {
48 const terminals = yield* TerminalManager.TerminalManager;
49 const previews = yield* PreviewManager.PreviewManager;
50 + const devices = yield* DeviceService.DeviceService;
51 const fileSystem = yield* FileSystem.FileSystem;
52 const config = yield* ServerConfig.ServerConfig;
53 const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
@@ -81,6 +86,21 @@ export const layer = Layer.effect(
86 ),
87 );
88 }),
89 + cleanupDevices: Effect.fn("ResourceCleanupService.cleanupDevices")(function* (
90 + threadId: ThreadId,
91 + ) {
92 + // One close per session, so a reconnecting host does not keep the other hosts' claims.
93 + const sessions = yield* devices.sessionsForThread(threadId);
94 + const [, failures] = yield* Effect.partition(
95 + sessions,
96 + (session) =>
97 + devices.close({ threadId, hostId: session.hostId, deviceId: session.deviceId }),
98 + { concurrency: 1 },
99 + );
100 + const [failure] = failures;
101 + if (failure !== undefined)
102 + return yield* new ResourceCleanupError({ operation: "device", threadId, cause: failure });
103 + }),
104 cleanupAttachments: Effect.fn("ResourceCleanupService.cleanupAttachments")(function (
105 attachmentIds: ReadonlyArray<string>,
106 ) {
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+108
@@ -88,6 +88,8 @@ import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts
88 import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
89 import * as Scheduler from "../scheduling/Scheduler.ts";
90 import * as SecretRequests from "../secrets/SecretRequests.ts";
91 +import * as DeviceHost from "../device/DeviceHost.ts";
92 +import * as DeviceService from "../device/DeviceService.ts";
93 import * as PreviewManager from "../preview/Manager.ts";
94 import * as TerminalManager from "../terminal/Manager.ts";
95 import * as ResourceCleanupService from "./ResourceCleanupService.ts";
@@ -368,8 +370,59 @@ const layerScheduledTasksTest = ScheduledTaskService.layer.pipe(
370 ),
371 ),
372 );
373 +const bootedSimulatorReady: DeviceHost.DeviceHostAgentReady = {
374 + nodePath: process.execPath,
375 + hub: { origin: "http://device.test" },
376 + agentDevice: null,
377 + helpers: { serveSimAxSettings: null, serveSimCli: null },
378 + run: () => Effect.die("Thread cleanup must not run host commands"),
379 + releaseAgentSession: () => Effect.void,
380 + devices: {
381 + list: Effect.succeed({
382 + devices: [
383 + {
384 + id: "phone",
385 + name: "iPhone",
386 + platform: "ios",
387 + version: "26",
388 + booted: true,
389 + physical: false,
390 + },
391 + ],
392 + detail: undefined,
393 + }),
394 + boot: () => Effect.die("The simulator is already booted"),
395 + attach: () => Effect.void,
396 + shutdown: () => Effect.die("Thread cleanup must keep the simulator booted"),
397 + screenshot: () => Effect.die("unused screenshot"),
398 + },
399 +};
400 +const bootedSimulatorHost = DeviceHost.DeviceHost.of({
401 + id: "local",
402 + label: "Local",
403 + summary: Effect.succeed({
404 + id: "local",
405 + label: "Local",
406 + kind: "local",
407 + hubInstalled: true,
408 + agentDeviceInstalled: true,
409 + platforms: [{ platform: "ios", available: true }],
410 + }),
411 + platformAvailability: (platform) => Effect.succeed({ platform, available: true }),
412 + ensureReady: () => Effect.succeed(bootedSimulatorReady),
413 + ensureAgentReady: () => Effect.succeed(bootedSimulatorReady),
414 + current: Effect.succeed(bootedSimulatorReady),
415 + stopAgent: Effect.void,
416 + stop: Effect.void,
417 +});
418 const layerResourceCleanupTest = ResourceCleanupService.layer.pipe(
419 Layer.provideMerge(layerScheduledTasksTest),
420 + Layer.provideMerge(
421 + Layer.effect(
422 + DeviceService.DeviceService,
423 + DeviceService.makeWithHosts(new Map([[bootedSimulatorHost.id, bootedSimulatorHost]])),
424 + ),
425 + ),
426 Layer.provide(
427 Layer.mergeAll(
428 Layer.mock(PreviewManager.PreviewManager)({ close: () => Effect.void }),
@@ -545,6 +598,61 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
598 }),
599 );
600
601 + it.effect.each(["archive", "thread delete", "project delete"] as const)(
602 + "%s releases the thread's devices and keeps them booted",
603 + (lifecycle) =>
604 + Effect.gen(function* () {
605 + const projects = yield* ProjectService.ProjectService;
606 + const orchestrator = yield* Orchestrator.OrchestratorV2;
607 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
608 + const devices = yield* DeviceService.DeviceService;
609 + yield* devices.configure({ enabled: true, agentAccessEnabled: true });
610 + const projectId = ProjectId.make(`device-cleanup-project:${lifecycle}`);
611 + const threadId = ThreadId.make(`device-cleanup-thread:${lifecycle}`);
612 + const otherThreadId = ThreadId.make(`device-surviving-thread:${lifecycle}`);
613 + yield* projects.create({
614 + commandId: CommandId.make(`device-cleanup-create-project:${lifecycle}`),
615 + projectId,
616 + title: "Device cleanup",
617 + workspaceRoot: `/work/device-cleanup/${lifecycle}`,
618 + });
619 + for (const id of [threadId, otherThreadId]) {
620 + yield* orchestrator.dispatch({
621 + type: "thread.create",
622 + commandId: CommandId.make(`device-cleanup-create:${id}`),
623 + createdBy: "user",
624 + creationSource: "web",
625 + threadId: id,
626 + projectId: id === threadId ? projectId : ProjectId.make("device-cleanup-other-project"),
627 + title: "Device user",
628 + modelSelection,
629 + runtimeMode: "full-access",
630 + interactionMode: "default",
631 + branch: null,
632 + worktreePath: null,
633 + });
634 + yield* devices.open({ threadId: id, deviceId: "phone", platform: "ios" });
635 + }
636 + const otherSessions = yield* devices.sessionsForThread(otherThreadId);
637 +
638 + const commandId = CommandId.make(`device-cleanup:${lifecycle}`);
639 + if (lifecycle === "project delete") {
640 + yield* projects.delete({ commandId, projectId, force: true });
641 + } else {
642 + yield* orchestrator.dispatch({
643 + type: lifecycle === "archive" ? "thread.archive" : "thread.delete",
644 + commandId,
645 + threadId,
646 + });
647 + }
648 + yield* worker.drain();
649 +
650 + assert.deepEqual(yield* devices.sessionsForThread(threadId), []);
651 + assert.deepEqual(yield* devices.sessionsForThread(otherThreadId), otherSessions);
652 + assert.isTrue((yield* devices.state).devices[0]?.booted);
653 + }),
654 + );
655 +
656 it.effect("waits for an in-flight thread update before planning deletion", () =>
657 Effect.gen(function* () {
658 const projects = yield* ProjectService.ProjectService;
apps/server/src/provider/userInputAttachments.test.ts
+2
@@ -16,6 +16,7 @@ import * as ServerConfig from "../config.ts";
16 import * as DocumentText from "./DocumentText.ts";
17 import { extractDocumentText } from "./documentTextWorker.ts";
18 import * as Cleanup from "../orchestration-v2/ResourceCleanupService.ts";
19 +import * as DeviceService from "../device/DeviceService.ts";
20 import * as TerminalManager from "../terminal/Manager.ts";
21 import * as PreviewManager from "../preview/Manager.ts";
22 import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
@@ -328,6 +329,7 @@ describe("question answer paths", () => {
329 Layer.mergeAll(
330 Layer.mock(TerminalManager.TerminalManager)({}),
331 Layer.mock(PreviewManager.PreviewManager)({}),
332 + Layer.mock(DeviceService.DeviceService)({}),
333 Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
334 ),
335 ),