@devries-cameron20 / t3code Mirror · read-only / commits / d2a894a247
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 12:15 UTC

fix(server): forks of forks keep their deleted source's files (#32255)

Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>

shivam committed Nov 15, 2026 at 10:32 UTC d2a894a247c041f5882e25a75450e20a593defc1
6 files changed +387 -142
apps/server/src/orchestration-v2/Orchestrator.ts
+20 -18
@@ -5674,9 +5674,9 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
5674 }),
5675 ),
5676 );
5677 - // Only side chat forks lock the source; validate the modes copied here, not an earlier read.
5677 + // Read under the source's lock; validate the modes copied here, not an earlier read.
5678 yield* refuseAboveDispatchModeLimit(command, command.sourceThreadId, sourceProjection.thread);
5679 - if (command.sideChat === true && sourceProjection.thread.deletedAt !== null) {
5679 + if (sourceProjection.thread.deletedAt !== null) {
5680 return yield* new OrchestratorDispatchError({
5681 commandId: command.commandId,
5682 commandType: command.type,
@@ -15662,28 +15662,30 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
15662 commandThreadId(command),
15663 dispatchWithReceiptEffect(command),
15664 );
15665 - // A parent's lock comes before its side chats' locks, so a delete cascade and a side chat
15666 - // fork or command never interleave. A fork from a side chat or onto an existing thread would
15667 - // invert that order; dispatch rejects both, so they skip the source lock.
15668 - if (
15669 - command.type === "thread.fork" &&
15670 - command.sideChat === true &&
15671 - command.sourceThreadId !== command.targetThreadId
15672 - ) {
15665 + // A fork holds its source's lock, so a source deletion and its fork never interleave. A
15666 + // parent's lock comes before its side chats' locks. A side chat fork from a side chat or a
15667 + // fork onto an existing thread would invert that order; dispatch rejects both, so they skip it.
15668 + if (command.type === "thread.fork" && command.sourceThreadId !== command.targetThreadId) {
15669 const source = yield* findThread(command.sourceThreadId);
15670 const target = yield* findThread(command.targetThreadId);
15675 - return yield* source === null || source.lineage.sideChat === true || target !== null
15671 + const skipsSourceLock =
15672 + source === null ||
15673 + target !== null ||
15674 + (command.sideChat === true && source.lineage.sideChat === true);
15675 + return yield* skipsSourceLock
15676 ? dispatch
15677 : threadDispatch.withLock(command.sourceThreadId, dispatch);
15678 }
15679 if (command.type === "thread.delete")
15680 - return yield* threadDispatch.withLock(
15681 - command.threadId,
15682 - liveSideChatIds(command.threadId).pipe(
15683 - Effect.flatMap((sideChatIds) =>
15684 - sideChatIds.reduce(
15685 - (locked, sideChatId) => threadDispatch.withLock(sideChatId, locked),
15686 - dispatchWithReceiptEffect(command, sideChatIds),
15680 + return yield* threadDispatch.withDeletionLock(
15681 + threadDispatch.withLock(
15682 + command.threadId,
15683 + liveSideChatIds(command.threadId).pipe(
15684 + Effect.flatMap((sideChatIds) =>
15685 + sideChatIds.reduce(
15686 + (locked, sideChatId) => threadDispatch.withLock(sideChatId, locked),
15687 + dispatchWithReceiptEffect(command, sideChatIds),
15688 + ),
15689 ),
15690 ),
15691 ),
apps/server/src/orchestration-v2/ProjectionStore.ts
+136 -58
@@ -6288,45 +6288,62 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6288 Effect.mapError(controlReadError(threadId)),
6289 );
6290
6291 - // A live run fork shows its source's history through the fork run without copying it.
6292 - const shownByLiveFork = (threadId: ThreadId, runIdColumn: string) => sql`
6293 - EXISTS (
6294 - SELECT 1
6295 - FROM orchestration_v2_projection_threads AS fork
6296 - JOIN orchestration_v2_projection_runs AS fork_run
6297 - ON fork_run.run_id = json_extract(fork.payload_json, '$.forkedFrom.runId')
6298 - LEFT JOIN orchestration_v2_projection_runs AS item_run
6299 - ON item_run.run_id = ${sql.literal(runIdColumn)}
6300 - WHERE fork_run.thread_id = ${threadId}
6301 - AND fork.deleted_at IS NULL
6302 - AND json_extract(fork.payload_json, '$.forkedFrom.type') = 'run'
6303 - AND json_extract(fork.payload_json, '$.forkedFrom.threadId') = ${threadId}
6304 - AND json_extract(fork.payload_json, '$.lineage.sideChat') IS NOT 1
6305 - AND (${sql.literal(runIdColumn)} IS NULL OR item_run.ordinal <= fork_run.ordinal)
6306 - )
6291 + // A run fork shows its source's history through the fork run without copying it, and every
6292 + // run fork below it shows that history too. Returns the last source run live forks show, with
6293 + // and without `leavingForkId`.
6294 + const lastRunsShownByLiveForks = (threadId: ThreadId, leavingForkId: ThreadId) =>
6295 + sql<{ with_fork: number | null; without_fork: number | null }>`
6296 + WITH RECURSIVE showing(thread_id, deleted_at, through) AS (
6297 + SELECT fork.thread_id, fork.deleted_at, fork_run.ordinal
6298 + FROM orchestration_v2_projection_context_transfers AS transfer
6299 + JOIN orchestration_v2_projection_threads AS fork
6300 + ON fork.thread_id = transfer.target_thread_id
6301 + JOIN orchestration_v2_projection_runs AS fork_run
6302 + ON fork_run.run_id = json_extract(fork.payload_json, '$.forkedFrom.runId')
6303 + WHERE transfer.source_thread_id = ${threadId}
6304 + AND transfer.type = 'fork'
6305 + AND fork_run.thread_id = ${threadId}
6306 + AND json_extract(fork.payload_json, '$.forkedFrom.type') = 'run'
6307 + AND json_extract(fork.payload_json, '$.forkedFrom.threadId') = ${threadId}
6308 + AND json_extract(fork.payload_json, '$.lineage.sideChat') IS NOT 1
6309 + UNION
6310 + SELECT child.thread_id, child.deleted_at, showing.through
6311 + FROM showing
6312 + JOIN orchestration_v2_projection_context_transfers AS transfer
6313 + ON transfer.source_thread_id = showing.thread_id AND transfer.type = 'fork'
6314 + JOIN orchestration_v2_projection_threads AS child
6315 + ON child.thread_id = transfer.target_thread_id
6316 + WHERE json_extract(child.payload_json, '$.forkedFrom.type') = 'run'
6317 + AND json_extract(child.payload_json, '$.forkedFrom.threadId') = showing.thread_id
6318 + AND json_extract(child.payload_json, '$.lineage.sideChat') IS NOT 1
6319 + )
6320 + SELECT
6321 + MAX(through) AS with_fork,
6322 + MAX(CASE WHEN thread_id <> ${leavingForkId} THEN through END) AS without_fork
6323 + FROM showing
6324 + WHERE deleted_at IS NULL
6325 + `.pipe(Effect.map((rows) => rows[0] ?? { with_fork: null, without_fork: null }));
6326 +
6327 + // A row with no run predates every run (-1), so any live fork shows it.
6328 + const runOrdinalBetween = (runIdColumn: string, from: number, through: number) => sql`
6329 + COALESCE((
6330 + SELECT run.ordinal FROM orchestration_v2_projection_runs AS run
6331 + WHERE run.run_id = ${sql.literal(runIdColumn)}
6332 + ), -1) BETWEEN ${from} AND ${through}
6333 `;
6334
6309 - // Thread deletion keeps what a live fork still shows; a reference check must count it.
6310 - const exceptShownByLiveFork = (
6335 + const runAttachmentIds = Effect.fn("ProjectionStore.runAttachmentIds")(function* (
6336 threadId: ThreadId,
6312 - runIdColumn: string,
6313 - options: { readonly includeShownByLiveFork?: boolean } | undefined,
6314 - ) =>
6315 - options?.includeShownByLiveFork === true
6316 - ? sql``
6317 - : sql`AND NOT ${shownByLiveFork(threadId, runIdColumn)}`;
6318 -
6319 - const getThreadAttachmentIds: ProjectionStoreV2Shape["getThreadAttachmentIds"] = (
6320 - threadId,
6321 - options,
6322 - ) =>
6323 - Effect.all([
6337 + from: number,
6338 + through: number,
6339 + ) {
6340 + const [messages, renders, answerFiles] = yield* Effect.all([
6341 sql<{ id: string }>`
6342 SELECT DISTINCT json_extract(attachment.value, '$.id') AS id
6343 FROM orchestration_v2_projection_messages AS message,
6344 json_each(message.payload_json, '$.attachments') AS attachment
6345 WHERE message.thread_id = ${threadId}
6329 - ${exceptShownByLiveFork(threadId, "message.run_id", options)}
6346 + AND ${runOrdinalBetween("message.run_id", from, through)}
6347 `,
6348 sql<{ payload_json: string }>`
6349 SELECT item.payload_json
@@ -6336,7 +6353,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6353 AND (item.payload_json LIKE '%htmlRender%'
6354 OR item.payload_json LIKE ${`%${MCP_APP_OUTPUT_KEY}%`}
6355 OR item.payload_json LIKE '%preview_recording_stop%')
6339 - ${exceptShownByLiveFork(threadId, "item.run_id", options)}
6356 + AND ${runOrdinalBetween("item.run_id", from, through)}
6357 `,
6358 sql<{ id: string }>`
6359 SELECT DISTINCT json_extract(attachment.value, '$.id') AS id
@@ -6345,37 +6362,98 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
6362 json_each(question.value) AS attachment
6363 WHERE item.thread_id = ${threadId}
6364 AND item.type = 'user_input_request'
6348 - ${exceptShownByLiveFork(threadId, "item.run_id", options)}
6365 + AND ${runOrdinalBetween("item.run_id", from, through)}
6366 `,
6367 + ]);
6368 + return [
6369 + ...messages.map((row) => row.id),
6370 + ...answerFiles.map((row) => row.id),
6371 + ...threadHtmlRenderAttachmentIds(
6372 + threadId,
6373 + renders.map((row) => {
6374 + const item = parseEncodedPayload(row.payload_json);
6375 + return {
6376 + toolName: typeof item.toolName === "string" ? item.toolName : null,
6377 + output: item.output,
6378 + };
6379 + }),
6380 + ),
6381 + ];
6382 + });
6383 +
6384 + const unshownRunAttachmentIds = Effect.fn("ProjectionStore.unshownRunAttachmentIds")(function* (
6385 + threadId: ThreadId,
6386 + from: number,
6387 + through: number,
6388 + ) {
6389 + const candidates = yield* runAttachmentIds(threadId, from, through);
6390 + if (from <= -1 || candidates.length === 0) return candidates;
6391 + const retained = new Set(yield* runAttachmentIds(threadId, -1, from - 1));
6392 + return candidates.filter((id) => !retained.has(id));
6393 + });
6394 +
6395 + // Deleting a fork also frees what its deleted sources kept only for it.
6396 + const getThreadAttachmentIds: ProjectionStoreV2Shape["getThreadAttachmentIds"] = Effect.fn(
6397 + "ProjectionStore.getThreadAttachmentIds",
6398 + )(
6399 + function* (threadId, options) {
6400 + const deletedSources = yield* sql<{ thread_id: ThreadId }>`
6401 + WITH RECURSIVE source(thread_id) AS (
6402 + SELECT json_extract(thread.payload_json, '$.forkedFrom.threadId')
6403 + FROM orchestration_v2_projection_threads AS thread
6404 + WHERE thread.thread_id = ${threadId}
6405 + AND json_extract(thread.payload_json, '$.forkedFrom.type') = 'run'
6406 + AND json_extract(thread.payload_json, '$.lineage.sideChat') IS NOT 1
6407 + UNION
6408 + SELECT json_extract(thread.payload_json, '$.forkedFrom.threadId')
6409 + FROM orchestration_v2_projection_threads AS thread
6410 + JOIN source USING (thread_id)
6411 + WHERE thread.deleted_at IS NOT NULL
6412 + AND json_extract(thread.payload_json, '$.forkedFrom.type') = 'run'
6413 + AND json_extract(thread.payload_json, '$.lineage.sideChat') IS NOT 1
6414 + )
6415 + SELECT thread.thread_id
6416 + FROM source
6417 + JOIN orchestration_v2_projection_threads AS thread USING (thread_id)
6418 + WHERE thread.deleted_at IS NOT NULL
6419 + `;
6420 + const afterRun = (ordinal: number | null) => (ordinal === null ? -1 : ordinal + 1);
6421 + const own = yield* lastRunsShownByLiveForks(threadId, threadId);
6422 + const released = yield* Effect.forEach(
6423 + options?.includeShownByLiveFork ? [] : deletedSources,
6424 + ({ thread_id: source }) =>
6425 + lastRunsShownByLiveForks(source, threadId).pipe(
6426 + Effect.flatMap((shown) =>
6427 + shown.with_fork === null
6428 + ? Effect.succeed([])
6429 + : unshownRunAttachmentIds(source, afterRun(shown.without_fork), shown.with_fork),
6430 + ),
6431 + ),
6432 + );
6433 // A guest's waiting files are pending uploads that no message row holds yet.
6351 - sql<{ id: string }>`
6352 - SELECT DISTINCT json_extract(attachment.value, '$.id') AS id
6353 - FROM orchestration_v2_projection_threads AS thread,
6354 - json_each(thread.payload_json, '$.guestShare.messages') AS message,
6355 - json_each(message.value, '$.attachments') AS attachment
6356 - WHERE thread.thread_id = ${threadId}
6357 - AND json_extract(message.value, '$.status') = 'pending'
6358 - `,
6359 - ]).pipe(
6360 - Effect.map(([messages, renders, answerFiles, guestFiles]) => [
6434 + const guestFiles = yield* sql<{ id: string }>`
6435 + SELECT DISTINCT json_extract(attachment.value, '$.id') AS id
6436 + FROM orchestration_v2_projection_threads AS thread,
6437 + json_each(thread.payload_json, '$.guestShare.messages') AS message,
6438 + json_each(message.value, '$.attachments') AS attachment
6439 + WHERE thread.thread_id = ${threadId}
6440 + AND json_extract(message.value, '$.status') = 'pending'
6441 + `;
6442 + return [
6443 ...new Set([
6362 - ...messages.map((row) => row.id),
6363 - ...guestFiles.map((row) => row.id),
6364 - ...answerFiles.map((row) => row.id),
6365 - ...threadHtmlRenderAttachmentIds(
6444 + ...(yield* unshownRunAttachmentIds(
6445 threadId,
6367 - renders.map((row) => {
6368 - const item = parseEncodedPayload(row.payload_json);
6369 - return {
6370 - toolName: typeof item.toolName === "string" ? item.toolName : null,
6371 - output: item.output,
6372 - };
6373 - }),
6374 - ),
6446 + options?.includeShownByLiveFork ? -1 : afterRun(own.with_fork),
6447 + Number.MAX_SAFE_INTEGER,
6448 + )),
6449 + ...guestFiles.map((row) => row.id),
6450 + ...released.flat(),
6451 ]),
6376 - ]),
6377 - Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause })),
6378 - );
6452 + ];
6453 + },
6454 + (effect, threadId) =>
6455 + effect.pipe(Effect.mapError((cause) => new ProjectionStoreReadError({ threadId, cause }))),
6456 + );
6457
6458 const getMessagesById = Effect.fn("ProjectionStore.getMessagesById")(
6459 function* (threadId: ThreadId, messageIds: ReadonlyArray<MessageId>) {
apps/server/src/orchestration-v2/ThreadCommandExecutor.ts
+22 -2
@@ -1,11 +1,31 @@
1 import type { ThreadId } from "@t3tools/contracts";
2 import * as KeyedLock from "@t3tools/shared/KeyedLock";
3 import * as Context from "effect/Context";
4 +import * as Effect from "effect/Effect";
5 import * as Layer from "effect/Layer";
6 +import * as Semaphore from "effect/Semaphore";
7
8 export class ThreadCommandExecutor extends Context.Service<
9 ThreadCommandExecutor,
8 - KeyedLock.KeyedLock<ThreadId>
10 + KeyedLock.KeyedLock<ThreadId> & {
11 + /**
12 + * One thread deletion plans and commits at a time: each decides what its deleted fork
13 + * sources keep for the forks still alive. Take it before any thread lock.
14 + */
15 + readonly withDeletionLock: <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
16 + }
17 >()("t3/orchestration-v2/ThreadCommandExecutor") {}
18
11 -export const layer = Layer.effect(ThreadCommandExecutor, KeyedLock.make<ThreadId>());
19 +export const make = Effect.gen(function* () {
20 + const deletion = yield* Semaphore.make(1);
21 + return ThreadCommandExecutor.of({
22 + ...(yield* KeyedLock.make<ThreadId>()),
23 + withDeletionLock: Effect.fn("ThreadCommandExecutor.withDeletionLock")(function* <A, E, R>(
24 + effect: Effect.Effect<A, E, R>,
25 + ) {
26 + return yield* deletion.withPermit(effect);
27 + }),
28 + });
29 +});
30 +
31 +export const layer = Layer.effect(ThreadCommandExecutor, make);
apps/server/src/orchestration-v2/runtimeLayer.test.ts
+205 -59
@@ -47,6 +47,7 @@ import * as Layer from "effect/Layer";
47 import * as Option from "effect/Option";
48 import * as Path from "effect/Path";
49 import * as Queue from "effect/Queue";
50 +import * as Ref from "effect/Ref";
51 import * as Stream from "effect/Stream";
52 import * as TestClock from "effect/testing/TestClock";
53 import * as SqlClient from "effect/sql/SqlClient";
@@ -462,6 +463,7 @@ const layerProjectDeletionTest = Layer.mergeAll(
463 RuntimeLayer.layer.pipe(Layer.provide(RuntimeLayer.layerProjectService)),
464 RuntimeLayer.layerProjectService,
465 RuntimeLayer.layerEventSink,
466 + ProjectionStore.layer,
467 ThreadCommandExecutor.layer,
468 ).pipe(
469 Layer.provide(
@@ -496,7 +498,7 @@ const layerProjectDeletionTest = Layer.mergeAll(
498 Layer.provide(ServerSettings.layerTest()),
499 Layer.provide(layerTestProviderInstanceRegistry),
500 Layer.provide(layerGitWorkflowTest),
499 - Layer.provide(layerPlatformTest),
501 + Layer.provideMerge(layerPlatformTest),
502 );
503
504 it.layer(layerProjectDeletionTest)("project deletion during thread commands", (it) => {
@@ -819,6 +821,41 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
821
822 assert.isFalse(yield* fileSystem.exists(filePath(dropped)));
823 assert.equal(yield* fileSystem.readFileString(filePath(shared)), "bytes");
824 +
825 + if (fork !== "no fork") {
826 + const laterRunId = yield* writeRun({
827 + name: "later",
828 + ordinal: 3,
829 + status: "completed",
830 + attachments: [shared],
831 + });
832 + const laterForkId = ThreadId.make(`${key}:later-fork`);
833 + yield* orchestrator.dispatch({
834 + type: "thread.fork",
835 + commandId: CommandId.make(`${key}:later-fork`),
836 + sourceThreadId: threadId,
837 + targetThreadId: laterForkId,
838 + sourcePoint: { type: "run", runId: laterRunId },
839 + createdBy: "user",
840 + creationSource: "web",
841 + });
842 + for (const id of [threadId, laterForkId]) {
843 + yield* orchestrator.dispatch({
844 + type: "thread.delete",
845 + commandId: CommandId.make(`${key}:delete:${id}`),
846 + threadId: id,
847 + });
848 + yield* worker.drain();
849 + assert.equal(yield* fileSystem.readFileString(filePath(shared)), "bytes");
850 + }
851 + yield* orchestrator.dispatch({
852 + type: "thread.delete",
853 + commandId: CommandId.make(`${key}:delete-first-fork`),
854 + threadId: ThreadId.make(`${key}:fork`),
855 + });
856 + yield* worker.drain();
857 + assert.isFalse(yield* fileSystem.exists(filePath(shared)));
858 + }
859 }).pipe(Effect.provide(NodeServices.layer)),
860 );
861
@@ -1137,6 +1174,167 @@ it.layer(layerProjectDeletionTest)("project deletion during thread commands", (i
1174 }).pipe(Effect.ensuring(Effect.sync(() => lockSpy.mockRestore())));
1175 }),
1176 );
1177 +
1178 + it.effect("deleted sources keep the html_render pages any live fork shows", () =>
1179 + Effect.gen(function* () {
1180 + const projects = yield* ProjectService.ProjectService;
1181 + const orchestrator = yield* Orchestrator.OrchestratorV2;
1182 + const projections = yield* ProjectionStore.ProjectionStoreV2;
1183 + const executor = yield* ThreadCommandExecutor.ThreadCommandExecutor;
1184 + const worker = yield* EffectWorker.OrchestrationEffectWorkerV2;
1185 + const fileSystem = yield* FileSystem.FileSystem;
1186 + const projectId = ProjectId.make("html-fork-project");
1187 + const sourceThreadId = ThreadId.make("html-fork-source");
1188 + const forkThreadId = ThreadId.make("html-fork-target");
1189 + yield* projects.create({
1190 + commandId: CommandId.make("html-fork-project"),
1191 + projectId,
1192 + title: "Page family",
1193 + workspaceRoot: "/work/html-fork",
1194 + });
1195 + yield* orchestrator.dispatch({
1196 + type: "thread.create",
1197 + commandId: CommandId.make("html-fork-create"),
1198 + threadId: sourceThreadId,
1199 + projectId,
1200 + title: "Page source",
1201 + modelSelection,
1202 + runtimeMode: "full-access",
1203 + interactionMode: "default",
1204 + branch: null,
1205 + worktreePath: null,
1206 + createdBy: "user",
1207 + creationSource: "web",
1208 + });
1209 + const inherited = yield* writeHtmlRenderRun({
1210 + threadId: sourceThreadId,
1211 + key: "inherited",
1212 + ordinal: 1,
1213 + });
1214 + const fork = (sourceThreadId: ThreadId, runId: RunId, targetThreadId: ThreadId) =>
1215 + orchestrator.dispatch({
1216 + type: "thread.fork",
1217 + commandId: CommandId.make(`html-fork:${targetThreadId}`),
1218 + sourceThreadId,
1219 + targetThreadId,
1220 + sourcePoint: { type: "run", runId },
1221 + createdBy: "user",
1222 + creationSource: "web",
1223 + });
1224 + yield* fork(sourceThreadId, inherited.runId, forkThreadId);
1225 + const forkPage = yield* writeHtmlRenderRun({
1226 + threadId: forkThreadId,
1227 + key: "fork",
1228 + ordinal: 1,
1229 + });
1230 + const [first, second] = [ThreadId.make("html-fork-first"), ThreadId.make("html-fork-second")];
1231 + yield* fork(forkThreadId, forkPage.runId, first);
1232 + // Project deletion goes newest first, so it reaches `second` before `first`.
1233 + yield* TestClock.adjust("1 second");
1234 + yield* fork(forkThreadId, forkPage.runId, second);
1235 + const firstRun = yield* writeHtmlRenderRun({ threadId: first, key: "first", ordinal: 1 });
1236 + const later = yield* writeHtmlRenderRun({
1237 + threadId: sourceThreadId,
1238 + key: "later",
1239 + ordinal: 2,
1240 + });
1241 + const deleteThread = (threadId: ThreadId) =>
1242 + orchestrator.dispatch({
1243 + type: "thread.delete",
1244 + commandId: CommandId.make(`html-fork-delete:${threadId}`),
1245 + threadId,
1246 + });
1247 + const pagesOnDisk = Effect.gen(function* () {
1248 + yield* worker.drain();
1249 + return yield* Effect.forEach([inherited, forkPage, later], (page) =>
1250 + fileSystem.exists(page.pagePath),
1251 + );
1252 + });
1253 + yield* deleteThread(forkThreadId);
1254 + yield* deleteThread(sourceThreadId);
1255 + assert.deepEqual(yield* pagesOnDisk, [true, true, false]);
1256 +
1257 + // `first`'s delete pauses after reading what to free. A fork of it and the project delete,
1258 + // which reaches `second`, must each wait on a lock it holds rather than decide on the same
1259 + // state; `blocked` hears each request for one.
1260 + const firstPlanned = yield* Deferred.make<void>();
1261 + const releaseFirst = yield* Deferred.make<void>();
1262 + const blocked = yield* Queue.unbounded<void>();
1263 + const readAttachmentIds = projections.getThreadAttachmentIds;
1264 + const attachmentSpy = vi
1265 + .spyOn(projections, "getThreadAttachmentIds")
1266 + .mockImplementation((threadId) =>
1267 + threadId === first
1268 + ? readAttachmentIds(threadId).pipe(
1269 + Effect.tap(() => Deferred.succeed(firstPlanned, undefined)),
1270 + Effect.tap(() => Deferred.await(releaseFirst)),
1271 + )
1272 + : readAttachmentIds(threadId),
1273 + );
1274 + const deletionHeld = yield* Ref.make(false);
1275 + const requestsHeld = (held: Effect.Effect<boolean>) =>
1276 + Effect.all([Deferred.isDone(firstPlanned), held]).pipe(
1277 + Effect.flatMap(([planned, isHeld]) =>
1278 + planned && isHeld ? Queue.offer(blocked, undefined) : Effect.void,
1279 + ),
1280 + );
1281 + const { withLock, withDeletionLock } = executor;
1282 + const observeLock: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withLock"] = (
1283 + key,
1284 + effect,
1285 + ) => requestsHeld(Effect.succeed(key === first)).pipe(Effect.andThen(withLock(key, effect)));
1286 + const observeDeletion: ThreadCommandExecutor.ThreadCommandExecutor["Service"]["withDeletionLock"] =
1287 + (effect) =>
1288 + requestsHeld(Ref.get(deletionHeld)).pipe(
1289 + Effect.andThen(
1290 + withDeletionLock(
1291 + Ref.set(deletionHeld, true).pipe(
1292 + Effect.andThen(effect),
1293 + Effect.ensuring(Ref.set(deletionHeld, false)),
1294 + ),
1295 + ),
1296 + ),
1297 + );
1298 + const lockSpy = vi.spyOn(executor, "withLock").mockImplementation(observeLock);
1299 + const deletionSpy = vi
1300 + .spyOn(executor, "withDeletionLock")
1301 + .mockImplementation(observeDeletion);
1302 + const forkOfDeleted = yield* Effect.gen(function* () {
1303 + const firstFiber = yield* deleteThread(first).pipe(
1304 + Effect.forkChild({ startImmediately: true }),
1305 + );
1306 + yield* Deferred.await(firstPlanned);
1307 + const forkFiber = yield* fork(first, firstRun.runId, ThreadId.make("html-fork-late")).pipe(
1308 + Effect.match({
1309 + onSuccess: () => "created",
1310 + onFailure: (error) => ("cause" in error ? String(error.cause) : error._tag),
1311 + }),
1312 + Effect.forkChild({ startImmediately: true }),
1313 + );
1314 + yield* Effect.raceFirst(Queue.take(blocked), Fiber.await(forkFiber));
1315 + const projectFiber = yield* projects
1316 + .delete({ commandId: CommandId.make("html-fork-project-delete"), projectId, force: true })
1317 + .pipe(Effect.forkChild({ startImmediately: true }));
1318 + yield* Effect.raceFirst(Queue.take(blocked), Fiber.await(projectFiber));
1319 + yield* Deferred.succeed(releaseFirst, undefined);
1320 + yield* Fiber.join(firstFiber);
1321 + yield* Fiber.join(projectFiber);
1322 + return yield* Fiber.join(forkFiber);
1323 + }).pipe(
1324 + Effect.ensuring(
1325 + Effect.sync(() => {
1326 + lockSpy.mockRestore();
1327 + deletionSpy.mockRestore();
1328 + attachmentSpy.mockRestore();
1329 + }),
1330 + ),
1331 + );
1332 + assert.deepEqual(
1333 + { afterLastForks: yield* pagesOnDisk, forkOfDeleted },
1334 + { afterLastForks: [false, false, false], forkOfDeleted: `Thread ${first} was deleted.` },
1335 + );
1336 + }),
1337 + );
1338 });
1339
1340 const layerSharedApplicationDataPlaneTest = Layer.mergeAll(
@@ -3016,6 +3214,11 @@ const writeHtmlRenderRun = Effect.fn("test.writeHtmlRenderRun")(function* (input
3214 const runId = RunId.make(`html-fork-run:${input.key}`);
3215 const messageId = MessageId.make(`html-fork-message:${input.key}`);
3216 const attachmentId = createAttachmentId(input.threadId, "html")!;
3217 + const fileSystem = yield* FileSystem.FileSystem;
3218 + const { attachmentsDir } = yield* ServerConfig.ServerConfig;
3219 + const pagePath = (yield* Path.Path).join(attachmentsDir, `${attachmentId}.html`);
3220 + yield* fileSystem.makeDirectory(attachmentsDir, { recursive: true });
3221 + yield* fileSystem.writeFileString(pagePath, "<p>Page</p>");
3222 yield* eventSink.write({
3223 events: [
3224 {
@@ -3097,67 +3300,10 @@ const writeHtmlRenderRun = Effect.fn("test.writeHtmlRenderRun")(function* (input
3300 },
3301 ],
3302 });
3100 - return { runId, attachmentId };
3303 + return { runId, pagePath };
3304 });
3305
3306 it.layer(layerTest)("OrchestrationV2LayerLive lifecycle", (it) => {
3104 - it.effect("deleting a source keeps the html_render page its live fork shows", () =>
3105 - Effect.gen(function* () {
3106 - const orchestrator = yield* Orchestrator.OrchestratorV2;
3107 - const outbox = yield* EffectOutbox.EffectOutboxV2;
3108 - const sourceThreadId = ThreadId.make("html-fork-source");
3109 - const forkThreadId = ThreadId.make("html-fork-target");
3110 - yield* orchestrator.dispatch({
3111 - type: "thread.create",
3112 - commandId: CommandId.make("html-fork-create"),
3113 - threadId: sourceThreadId,
3114 - projectId: ProjectId.make("html-fork-project"),
3115 - title: "Page source",
3116 - modelSelection,
3117 - runtimeMode: "full-access",
3118 - interactionMode: "default",
3119 - branch: null,
3120 - worktreePath: null,
3121 - createdBy: "user",
3122 - creationSource: "web",
3123 - });
3124 - const inherited = yield* writeHtmlRenderRun({
3125 - threadId: sourceThreadId,
3126 - key: "inherited",
3127 - ordinal: 1,
3128 - });
3129 - yield* orchestrator.dispatch({
3130 - type: "thread.fork",
3131 - commandId: CommandId.make("html-fork-fork"),
3132 - sourceThreadId,
3133 - targetThreadId: forkThreadId,
3134 - sourcePoint: { type: "run", runId: inherited.runId },
3135 - createdBy: "user",
3136 - creationSource: "web",
3137 - });
3138 - const later = yield* writeHtmlRenderRun({
3139 - threadId: sourceThreadId,
3140 - key: "later",
3141 - ordinal: 2,
3142 - });
3143 - const deleteCommandId = CommandId.make("html-fork-delete-source");
3144 - yield* orchestrator.dispatch({
3145 - type: "thread.delete",
3146 - commandId: deleteCommandId,
3147 - threadId: sourceThreadId,
3148 - });
3149 - const cleaned = (yield* outbox.listByCommandId(deleteCommandId)).flatMap((effect) =>
3150 - effect.request.type === "attachment.cleanup" ? effect.request.attachmentIds : [],
3151 - );
3152 - assert.include(cleaned, later.attachmentId);
3153 - assert.notInclude(
3154 - cleaned,
3155 - inherited.attachmentId,
3156 - "deleted a page its live fork still shows",
3157 - );
3158 - }),
3159 - );
3160 -
3307 it.effect("applies lifecycle commands idempotently and emits archive/removal shell deltas", () =>
3308 Effect.gen(function* () {
3309 const orchestrator = yield* Orchestrator.OrchestratorV2;
apps/server/src/project/AgentSessionImporter.test.ts
+3 -4
@@ -16,7 +16,6 @@ import {
16 type OrchestrationV2ProviderThread,
17 } from "@t3tools/contracts";
18 import * as IdAllocator from "@t3tools/provider-core/server/IdAllocator";
19 -import * as KeyedLock from "@t3tools/shared/KeyedLock";
19 import * as AcpRegistryRuntimeCoordinator from "@t3tools/provider-acp-registry/server/AcpRegistryRuntimeCoordinator";
20 import * as ProviderAdapter from "@t3tools/provider-core/server/ProviderAdapter";
21 import * as Context from "effect/Context";
@@ -188,7 +187,7 @@ const makeImporter = Effect.fn(function* (
187 candidates: ReadonlyArray<AgentSessionScanner.AgentSessionRecentThread>,
188 beforeTransaction: Effect.Effect<void> = Effect.void,
189 getAdapter?: ProviderAdapterRegistry.ProviderAdapterRegistryV2Shape["get"],
191 - threadCommands?: KeyedLock.KeyedLock<ThreadId>,
190 + threadCommands?: ThreadCommandExecutor.ThreadCommandExecutor["Service"],
191 settings: Layer.Layer<
192 ServerSettings.ServerSettingsService,
193 ServerSettingsError
@@ -271,7 +270,7 @@ const makeImporter = Effect.fn(function* (
270 ),
271 Layer.succeed(
272 ThreadCommandExecutor.ThreadCommandExecutor,
274 - threadCommands ?? (yield* KeyedLock.make<ThreadId>()),
273 + threadCommands ?? (yield* ThreadCommandExecutor.make),
274 ),
275 ),
276 ),
@@ -816,7 +815,7 @@ const importDuringCommand = Effect.fn(function* (
815 const projections = yield* ProjectionStore.ProjectionStoreV2;
816 const sink = yield* EventSink.EventSinkV2;
817 const threadId = yield* seedOwner(candidate(CODEX_MODEL_SELECTION, name));
819 - const lock = yield* KeyedLock.make<ThreadId>();
818 + const lock = yield* ThreadCommandExecutor.make;
819 const loaded = yield* Deferred.make<void>();
820 const importerCommitting = yield* Deferred.make<void>();
821 const commandWritten = yield* Deferred.make<void>();
apps/server/src/project/ProjectService.ts
+1 -1
@@ -538,7 +538,7 @@ export const make = Effect.gen(function* () {
538 projectThreads,
539 (thread) =>
540 threadCommands
541 - .withLock(thread.id, deleteChildThread(input, thread.id))
541 + .withDeletionLock(threadCommands.withLock(thread.id, deleteChildThread(input, thread.id)))
542 .pipe(
543 Effect.mapError(
544 (cause) =>