Skip to content

Commit 5c9a01b

Browse files
authored
fix(server): archiving or deleting a thread releases its devices (pingdotgg#34175)
1 parent 10128e5 commit 5c9a01b

5 files changed

Lines changed: 145 additions & 3 deletions

File tree

‎apps/server/src/guest/GuestShareService.test.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ const layerProviders = Layer.mock(ProviderRegistry.ProviderRegistry)({
9090
getProviders: Effect.succeed([]),
9191
});
9292
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.
9494
const layerCleanup = Layer.effect(
9595
ResourceCleanupService.ResourceCleanupService,
9696
Effect.gen(function* () {
@@ -100,6 +100,7 @@ const layerCleanup = Layer.effect(
100100
cleanupScheduledTasks: () => Effect.void,
101101
cleanupTerminals: () => Effect.void,
102102
cleanupPreviews: () => Effect.void,
103+
cleanupDevices: () => Effect.void,
103104
cleanupAttachments: (attachmentIds) =>
104105
Effect.forEach(
105106
attachmentIds,

‎apps/server/src/orchestration-v2/EffectWorker.ts‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -526,8 +526,19 @@ export const layerExecutor: Layer.Layer<
526526
}),
527527
),
528528
);
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.
529531
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+
),
531542
Effect.mapError(
532543
(cause) =>
533544
new OrchestrationEffectExecutionError({

‎apps/server/src/orchestration-v2/ResourceCleanupService.ts‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,14 +8,15 @@ import * as Schema from "effect/Schema";
88
import { resolveAttachmentRelativePath } from "../attachmentPaths.ts";
99
import { parseAttachmentFileExtension, resolveAttachmentPathById } from "../attachmentStore.ts";
1010
import * as ServerConfig from "../config.ts";
11+
import * as DeviceService from "../device/DeviceService.ts";
1112
import * as PreviewManager from "../preview/Manager.ts";
1213
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
1314
import * as TerminalManager from "../terminal/Manager.ts";
1415

1516
export class ResourceCleanupError extends Schema.TaggedError<ResourceCleanupError>()(
1617
"ResourceCleanupError",
1718
{
18-
operation: Schema.Literals(["terminal", "preview", "attachment", "scheduled-tasks"]),
19+
operation: Schema.Literals(["terminal", "preview", "device", "attachment", "scheduled-tasks"]),
1920
threadId: Schema.optional(Schema.String),
2021
attachmentId: Schema.optional(Schema.String),
2122
cause: Schema.Defect(),
@@ -26,6 +27,8 @@ export class ResourceCleanupService extends Context.Reference<{
2627
readonly cleanupScheduledTasks: (threadId: ThreadId) => Effect.Effect<void, ResourceCleanupError>;
2728
readonly cleanupTerminals: (threadId: string) => Effect.Effect<void, ResourceCleanupError>;
2829
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>;
2932
readonly cleanupAttachments: (
3033
attachmentIds: ReadonlyArray<string>,
3134
) => Effect.Effect<void, ResourceCleanupError>;
@@ -34,6 +37,7 @@ export class ResourceCleanupService extends Context.Reference<{
3437
cleanupScheduledTasks: () => Effect.void,
3538
cleanupTerminals: () => Effect.void,
3639
cleanupPreviews: () => Effect.void,
40+
cleanupDevices: () => Effect.void,
3741
cleanupAttachments: () => Effect.void,
3842
}),
3943
}) {}
@@ -43,6 +47,7 @@ export const layer = Layer.effect(
4347
Effect.gen(function* () {
4448
const terminals = yield* TerminalManager.TerminalManager;
4549
const previews = yield* PreviewManager.PreviewManager;
50+
const devices = yield* DeviceService.DeviceService;
4651
const fileSystem = yield* FileSystem.FileSystem;
4752
const config = yield* ServerConfig.ServerConfig;
4853
const scheduledTasks = yield* ScheduledTaskService.ScheduledTaskService;
@@ -81,6 +86,21 @@ export const layer = Layer.effect(
8186
),
8287
);
8388
}),
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+
}),
84104
cleanupAttachments: Effect.fn("ResourceCleanupService.cleanupAttachments")(function (
85105
attachmentIds: ReadonlyArray<string>,
86106
) {

‎apps/server/src/orchestration-v2/runtimeLayer.test.ts‎

Lines changed: 108 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,8 @@ import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts
8888
import * as ManagedPolicy from "../policy/ManagedPolicy.ts";
8989
import * as Scheduler from "../scheduling/Scheduler.ts";
9090
import * as SecretRequests from "../secrets/SecretRequests.ts";
91+
import * as DeviceHost from "../device/DeviceHost.ts";
92+
import * as DeviceService from "../device/DeviceService.ts";
9193
import * as PreviewManager from "../preview/Manager.ts";
9294
import * as TerminalManager from "../terminal/Manager.ts";
9395
import * as ResourceCleanupService from "./ResourceCleanupService.ts";
@@ -368,8 +370,59 @@ const layerScheduledTasksTest = ScheduledTaskService.layer.pipe(
368370
),
369371
),
370372
);
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+
});
371418
const layerResourceCleanupTest = ResourceCleanupService.layer.pipe(
372419
Layer.provideMerge(layerScheduledTasksTest),
420+
Layer.provideMerge(
421+
Layer.effect(
422+
DeviceService.DeviceService,
423+
DeviceService.makeWithHosts(new Map([[bootedSimulatorHost.id, bootedSimulatorHost]])),
424+
),
425+
),
373426
Layer.provide(
374427
Layer.mergeAll(
375428
Layer.mock(PreviewManager.PreviewManager)({ close: () => Effect.void }),
@@ -545,6 +598,61 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
545598
}),
546599
);
547600

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+
548656
it.effect("waits for an in-flight thread update before planning deletion", () =>
549657
Effect.gen(function* () {
550658
const projects = yield* ProjectService.ProjectService;

‎apps/server/src/provider/userInputAttachments.test.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import * as ServerConfig from "../config.ts";
1616
import * as DocumentText from "./DocumentText.ts";
1717
import { extractDocumentText } from "./documentTextWorker.ts";
1818
import * as Cleanup from "../orchestration-v2/ResourceCleanupService.ts";
19+
import * as DeviceService from "../device/DeviceService.ts";
1920
import * as TerminalManager from "../terminal/Manager.ts";
2021
import * as PreviewManager from "../preview/Manager.ts";
2122
import * as ScheduledTaskService from "../scheduledTasks/ScheduledTaskService.ts";
@@ -328,6 +329,7 @@ describe("question answer paths", () => {
328329
Layer.mergeAll(
329330
Layer.mock(TerminalManager.TerminalManager)({}),
330331
Layer.mock(PreviewManager.PreviewManager)({}),
332+
Layer.mock(DeviceService.DeviceService)({}),
331333
Layer.mock(ScheduledTaskService.ScheduledTaskService)({}),
332334
),
333335
),

0 commit comments

Comments
 (0)