From 67bd649bd365bbebaf55c7cc84af2f92d19416e8 Mon Sep 17 00:00:00 2001
From: Badcuban <108198679+badcuban@users.noreply.github.com>
Date: Wed, 18 Nov 2026 04:01:37 -0500
Subject: [PATCH 1/3] fix: thread moves across a link keep their parent, wake,
and refuse honestly
Fixes six review findings left in #985:
- A child that comes back before this computer heard its move landed now
lands under its parent: the sender names the thread it moved over from
(linkLineage.home.fromThreadId), and when that thread is still the
parent's child moving alone to that computer, the import adopts it and
completes that move in the same decision (adopt.completesMoveOf). A late
answer for a thread already back never records it as a remote child.
- A move waiting on another thread in its folder looks again on any event
of the threads it waits on, so an interrupted command run, or a workflow
or voice chat ending, wakes it.
- A parent's message to a child whose own move is stopping it is refused,
as for a frozen child, instead of deadlocking the move.
- A lone child's move to a computer that can't keep it its parent's ends
with that reason (checkMoveTarget reads aloneRefusal) instead of retrying
forever when the target came back on an older version.
- The move dialog hides the agent picker in "Move its whole family" mode
and says each thread uses the agent that computer suggests.
- A moved thread records whether its link pinned the computer it came from
(movedFrom.environmentPinned, taken from the link); while fenced, one
from an unpinned link moves nowhere.
---
apps/server/src/guide/topics.ts | 2 +-
apps/server/src/links/LinkMoves.test.ts | 50 ++++++
apps/server/src/links/LinkMoves.ts | 57 +++++--
apps/server/src/moves/MoveQueue.test.ts | 92 ++++++++++++
apps/server/src/moves/MoveQueue.ts | 17 ++-
apps/server/src/moves/ThreadMoves.test.ts | 91 ++++++++---
apps/server/src/moves/ThreadMoves.ts | 35 ++++-
apps/server/src/moves/familyMove.ts | 17 ++-
.../src/orchestration/childThreadDecisions.ts | 39 +++--
.../orchestration/decider.threadMoves.test.ts | 100 +++++++++++-
.../src/orchestration/threadMoveDecisions.ts | 142 ++++++++++++++++--
.../ChatView.move-thread.browser.tsx | 9 +-
.../components/ThreadMoveDialogContent.tsx | 37 +++--
packages/contracts/src/orchestration.ts | 19 ++-
packages/contracts/src/peerRpc.ts | 10 +-
15 files changed, 626 insertions(+), 91 deletions(-)
diff --git a/apps/server/src/guide/topics.ts b/apps/server/src/guide/topics.ts
index cdbe2de3f..f920537cd 100644
--- a/apps/server/src/guide/topics.ts
+++ b/apps/server/src/guide/topics.ts
@@ -156,7 +156,7 @@ Linking is two-way, with a permission for each direction: "'s agents can star
With a link allowed, an agent can start a thread on the other computer in that computer's copy of the project, read it and message it, and its reply comes back. A computer you only open from this app (Settings › Connections › Computers you use from here) is not a link: you see its threads here, but agents can't work across. This app's sign-in to it renews whenever they connect and ends after 90 days without one, or when that computer removes it. Fleet's All computers page and its own page then say the sign-in ended and offer to connect again with a new code; its threads stay on it.
-To carry on a thread on a linked computer, for example before shutting this one down, click its title at the top of the chat or right-click it in the sidebar (or use the command palette), and pick Move to another computer. The thread goes with its messages and its code changes, including files not yet committed; staged changes arrive unstaged. It lands in a new worktree of that computer's copy of the project; the dialog offers to set the project up there when it's missing. When that computer's permission for this one is Ask first, its user allows the move there. The copy left here stays, read-only, with a link to the new one. With Claude, Codex or Pi, and the same kind of agent picked on the other computer, the agent keeps its full memory: its own session moves too (up to 50 MB) and picks up where it was. Otherwise, or if that session can't be resumed there, the agent gets a summary of the conversation; the dialog and the moved thread's timeline say which. Turns from before the move can't be undone there. A working thread can move too: Move when it's done starts the move once its turn and background work finish, and Stop and move now stops its agent first. While it waits, a notice above the message box says what for, with Cancel, and the thread takes no new messages. An agent can move its own thread with thread_move; it goes when that turn ends. To clear a computer before shutting it down, Move threads (on a computer's page in Fleet, or in the command palette) moves several at once, and quitting the desktop app while threads work offers to move them first, quitting once each has gone. When the other computer asks first, it takes each move's files right away and holds them until its user allows them (all the moves from one computer together, or one at a time), so this computer counts them as sent and can shut down; a move that isn't allowed unfreezes here the next time the two connect. What a thread had going comes along when the other computer runs a current Threadlines, and runs there by itself: a goal that was working carries on, the agent is told its check-backs and sets them again, your queued messages are sent in order, its pull requests come along with auto-fix and auto-merge off (a notice there says what was on, with Turn on), and its plans come along, the waiting one with Implement. Until you send the moved thread a message there, its agent can't use other threads, rooms or schedules, and the thread can move only back to the computer it came from. A General Chats thread moves with every file in its folder, up to 100 MB. The dialog says what comes along and what won't work there; the "Moved here" line on the other computer says what arrived and what didn't. If a move doesn't happen, the thread gets back here what the move stopped: its goal and its check-backs, and its queued messages go. A room moves with its agents: the dialog has a row per agent with the matching agent on the other computer picked (same kind and model, else that kind's default), or Leave out. An agent with no match, or left out, arrives as having left, and both ends say which; each agent that comes keeps its own memory or gets the whole conversation once. Move when it's done waits for the agents' hand-offs and replies to finish, and Stop and move now ends them as Stop does. A thread that started other threads moves with them: the dialog lists its threads here, ticked, and one you untick stays here as its own thread, as does one that can't move (the dialog says why). On the other computer the threads that came are still its threads, and its "Moved here" line names the ones that stayed. Threads its agent started on another computer stay there, and the moved thread can't reach them. Moved to the computer one of them is on, its "Moved here" line names that thread, which stays separate. Move when it's done waits for the threads it started to report back, and Stop and move now ends that wait as Stop does. A thread another thread started can move on its own (Move just this thread) or with its whole family. On its own it stays that thread's thread on the other computer, which can still send to it, read it and stop it; there, like any thread another computer's agent started, its agent never gets other threads, rooms or schedules. A thread another computer's agent started can move only back to that computer, where it is that thread's thread again. A thread with a message queued by a scheduled task, an assistant or a thread outside its family can't move yet; the dialog says what to finish first.`,
+To carry on a thread on a linked computer, for example before shutting this one down, click its title at the top of the chat or right-click it in the sidebar (or use the command palette), and pick Move to another computer. The thread goes with its messages and its code changes, including files not yet committed; staged changes arrive unstaged. It lands in a new worktree of that computer's copy of the project; the dialog offers to set the project up there when it's missing. When that computer's permission for this one is Ask first, its user allows the move there. The copy left here stays, read-only, with a link to the new one. With Claude, Codex or Pi, and the same kind of agent picked on the other computer, the agent keeps its full memory: its own session moves too (up to 50 MB) and picks up where it was. Otherwise, or if that session can't be resumed there, the agent gets a summary of the conversation; the dialog and the moved thread's timeline say which. Turns from before the move can't be undone there. A working thread can move too: Move when it's done starts the move once its turn and background work finish, and Stop and move now stops its agent first. While it waits, a notice above the message box says what for, with Cancel, and the thread takes no new messages. An agent can move its own thread with thread_move; it goes when that turn ends. To clear a computer before shutting it down, Move threads (on a computer's page in Fleet, or in the command palette) moves several at once, and quitting the desktop app while threads work offers to move them first, quitting once each has gone. When the other computer asks first, it takes each move's files right away and holds them until its user allows them (all the moves from one computer together, or one at a time), so this computer counts them as sent and can shut down; a move that isn't allowed unfreezes here the next time the two connect. What a thread had going comes along when the other computer runs a current Threadlines, and runs there by itself: a goal that was working carries on, the agent is told its check-backs and sets them again, your queued messages are sent in order, its pull requests come along with auto-fix and auto-merge off (a notice there says what was on, with Turn on), and its plans come along, the waiting one with Implement. Until you send the moved thread a message there, its agent can't use other threads, rooms or schedules, and the thread can move only back to the computer it came from. If the link it came over can't confirm which computer sent it, it can't move at all until then. A General Chats thread moves with every file in its folder, up to 100 MB. The dialog says what comes along and what won't work there; the "Moved here" line on the other computer says what arrived and what didn't. If a move doesn't happen, the thread gets back here what the move stopped: its goal and its check-backs, and its queued messages go. A room moves with its agents: the dialog has a row per agent with the matching agent on the other computer picked (same kind and model, else that kind's default), or Leave out. An agent with no match, or left out, arrives as having left, and both ends say which; each agent that comes keeps its own memory or gets the whole conversation once. Move when it's done waits for the agents' hand-offs and replies to finish, and Stop and move now ends them as Stop does. A thread that started other threads moves with them: the dialog lists its threads here, ticked, and one you untick stays here as its own thread, as does one that can't move (the dialog says why). On the other computer the threads that came are still its threads, and its "Moved here" line names the ones that stayed. Threads its agent started on another computer stay there, and the moved thread can't reach them. Moved to the computer one of them is on, its "Moved here" line names that thread, which stays separate. Move when it's done waits for the threads it started to report back, and Stop and move now ends that wait as Stop does. A thread another thread started can move on its own (Move just this thread) or with its whole family. With its whole family, each thread moves with the agent the other computer suggests for it. On its own it stays that thread's thread on the other computer, which can still send to it, read it and stop it; there, like any thread another computer's agent started, its agent never gets other threads, rooms or schedules. A thread another computer's agent started can move only back to that computer, where it is that thread's thread again. A thread with a message queued by a scheduled task, an assistant or a thread outside its family can't move yet; the dialog says what to finish first.`,
},
{
id: "devices",
diff --git a/apps/server/src/links/LinkMoves.test.ts b/apps/server/src/links/LinkMoves.test.ts
index c3778f61e..d5fe59581 100644
--- a/apps/server/src/links/LinkMoves.test.ts
+++ b/apps/server/src/links/LinkMoves.test.ts
@@ -2048,6 +2048,7 @@ describe("a thread moving across its link (Part 3f, (h))", () => {
threadTitle: "Ship it",
});
assert.equal(imported.movedFrom.environmentId, WINDOWS);
+ assert.equal(imported.movedFrom.environmentPinned, true);
assert.isUndefined(imported.lineage);
assert.isUndefined(imported.adopt);
});
@@ -2063,6 +2064,8 @@ describe("a thread moving across its link (Part 3f, (h))", () => {
assert.equal(plain.status, "committed");
assert.isUndefined(plain.keptParent);
assert.isUndefined(importOf(first).remoteOrigin);
+ // Where it came from is only the move's word: its fence lets it go nowhere.
+ assert.isUndefined(importOf(first).movedFrom.environmentPinned);
assert.include(
importOf(first).arrival?.left ?? [],
"This computer can't confirm its link to Windows PC, so this is its own thread and 'Ship it' there can't reach it.",
@@ -2075,6 +2078,9 @@ describe("a thread moving across its link (Part 3f, (h))", () => {
assert.equal(lied.status, "committed");
assert.isUndefined(lied.keptParent);
assert.isUndefined(importOf(second).remoteOrigin);
+ // It came from the computer the link was made for, whatever the move says.
+ assert.equal(importOf(second).movedFrom.environmentId, WINDOWS);
+ assert.equal(importOf(second).movedFrom.environmentPinned, true);
});
});
@@ -2092,6 +2098,50 @@ describe("a thread moving across its link (Part 3f, (h))", () => {
});
});
+ it.live(
+ "comes home under its parent when its move here still waits for this computer's answer",
+ () => {
+ const LEFT = ThreadId.make("thread-left-here");
+ /** The parent's child here, frozen for its own move (alone) to `environmentId`. */
+ const leftHere = (environmentId: string, movedAway = false) => ({
+ threadId: LEFT,
+ projectId: ProjectId.make("project-b"),
+ deletedAt: null,
+ parentThreadId: PARENT_HERE,
+ attachedToParent: 1,
+ pendingMove: null,
+ move: {
+ transferId: "transfer-left",
+ target: { environmentId, label: "Windows PC" },
+ ...(movedAway
+ ? { movedAway: { threadId: "thread-a", movedAt: "2026-11-17T10:00:00.000Z" } }
+ : {}),
+ },
+ });
+ const back = { home: { parentThreadId: PARENT_HERE, fromThreadId: LEFT } };
+ const cases = [
+ { left: leftHere(WINDOWS), adopt: { parentThreadId: PARENT_HERE, completesMoveOf: LEFT } },
+ // Moving to another computer, or already heard to have landed: its own thread.
+ { left: leftHere("environment-mac"), adopt: undefined },
+ { left: leftHere(WINDOWS, true), adopt: undefined },
+ ];
+ return Effect.forEach(cases, ({ left, adopt }) => {
+ const repos = makeRepos();
+ const dispatched: OrchestrationCommand[] = [];
+ return moved(repos, dispatched, back, {
+ pinnedEnvironmentId: WINDOWS,
+ // The parent holds nothing there yet: this computer hasn't heard.
+ threadsHere: [parentHere(WINDOWS, "thread-other"), left],
+ }).pipe(
+ Effect.map((state) => {
+ assert.equal(state.status, "committed");
+ assert.deepEqual(importOf(dispatched).adopt, adopt);
+ }),
+ );
+ });
+ },
+ );
+
it.live("a home claim this computer's records don't back lands as its own thread", () => {
const cases = [
// The parent here never held that thread.
diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts
index ae43dd312..35b21be5c 100644
--- a/apps/server/src/links/LinkMoves.ts
+++ b/apps/server/src/links/LinkMoves.ts
@@ -111,6 +111,7 @@ import { generalChatThreadScratchCwd } from "../orchestration/generalChats.ts";
import { clampLaunchToCeiling } from "../orchestration/childThreadDecisions.ts";
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
+import { awaitsLoneMoveAnswer } from "../orchestration/threadMoveDecisions.ts";
import { ProjectionThreadRepository } from "../persistence/Services/ProjectionThreads.ts";
import { discardSessionFiles, releaseSessionFiles } from "../provider/nativeSession.ts";
import { ProviderService } from "../provider/Services/ProviderService.ts";
@@ -2322,7 +2323,11 @@ const make = Effect.gen(function* () {
* - A thread coming home (`home`) lands under the parent here only when
* that parent holds exactly this thread, on exactly the computer this
* link was made for, as its child: a linked computer can never put a
- * thread under one of this computer's own.
+ * thread under one of this computer's own. Or when it came back before
+ * this computer heard its move there landed: the thread it moved over
+ * from (`fromThreadId`) is still that parent's child here, moving alone
+ * to exactly that computer, so it lands under the parent and that move
+ * completes (`completesMoveOf`).
*
* Anything else lands as a thread of its own, with the "Moved here" words
* saying why (`left`).
@@ -2357,7 +2362,7 @@ const make = Effect.gen(function* () {
threadId: remoteParent.threadId,
threadTitle: remoteParent.title,
};
- return { remoteOrigin, environmentId: home };
+ return { remoteOrigin };
}
const parentThreadId = lineage.home?.parentThreadId;
if (parentThreadId === undefined) return {};
@@ -2373,17 +2378,44 @@ const make = Effect.gen(function* () {
),
);
const parent = Option.getOrUndefined(found);
- const holds =
+ const canAdopt =
parent !== undefined &&
parent.deletedAt === null &&
(parent.move ?? null) === null &&
(parent.pendingMove ?? null) === null &&
!((parent.parentThreadId ?? null) !== null && (parent.attachedToParent ?? 0) > 0) &&
- parent.projectId === projectId &&
- (parent.childRequests?.remoteChildren ?? []).some(
- (entry) => entry.environmentId === home && entry.threadId === source.threadId,
- );
- return holds ? { adopt: { parentThreadId }, environmentId: home } : own;
+ parent.projectId === projectId;
+ if (!canAdopt) return own;
+ const holds = (parent.childRequests?.remoteChildren ?? []).some(
+ (entry) => entry.environmentId === home && entry.threadId === source.threadId,
+ );
+ if (holds) return { adopt: { parentThreadId } };
+ // Back before this computer heard its move there landed: the parent's
+ // child here whose own move to that computer still waits for the answer.
+ const fromThreadId = lineage.home?.fromThreadId;
+ if (fromThreadId === undefined) return own;
+ const left = Option.getOrUndefined(
+ yield* threadRows
+ .getById({ threadId: fromThreadId })
+ .pipe(
+ Effect.mapError(
+ () => new ImportStop({ reason: `${ownLabel()} couldn't read its threads.` }),
+ ),
+ ),
+ );
+ return left !== undefined &&
+ awaitsLoneMoveAnswer(
+ {
+ deletedAt: left.deletedAt,
+ parentThreadId: left.parentThreadId ?? null,
+ attachedToParent: (left.attachedToParent ?? 0) > 0,
+ move: left.move ?? null,
+ },
+ parentThreadId,
+ home,
+ )
+ ? { adopt: { parentThreadId, completesMoveOf: fromThreadId } }
+ : own;
});
/**
@@ -2662,7 +2694,14 @@ const make = Effect.gen(function* () {
branch: scratch ? null : row.branch,
worktreePath: scratch ? null : row.worktreePath,
movedFrom: {
- environmentId: across.environmentId ?? row.manifest.source.environmentId,
+ // The computer this link was made for, when its invite pinned
+ // it; else only what the move says (Part 3f, (h)).
+ ...(authority.pinnedEnvironmentId !== null
+ ? {
+ environmentId: EnvironmentId.make(authority.pinnedEnvironmentId),
+ environmentPinned: true as const,
+ }
+ : { environmentId: row.manifest.source.environmentId }),
label: fromLabel,
threadId: row.manifest.source.threadId,
movedAt: now,
diff --git a/apps/server/src/moves/MoveQueue.test.ts b/apps/server/src/moves/MoveQueue.test.ts
index 317da0a1f..0ffde5657 100644
--- a/apps/server/src/moves/MoveQueue.test.ts
+++ b/apps/server/src/moves/MoveQueue.test.ts
@@ -1,5 +1,6 @@
import {
CommandId,
+ CommandRunId,
EnvironmentId,
MessageId,
ProjectId,
@@ -514,6 +515,97 @@ describe("MoveQueue", () => {
});
});
+describe("MoveQueue, another thread working in the same folder", () => {
+ const OTHER = ThreadId.make("thread-same-folder");
+ const RUN = CommandRunId.make("run-in-folder");
+
+ /** A second thread in the moving thread's folder, with a command still running in its terminal. */
+ async function sharingWithRunningCommand() {
+ let model = await seeded();
+ const decided = await Effect.runPromise(
+ decideOrchestrationCommand({
+ command: {
+ type: "thread.create",
+ commandId: nextCommandId(),
+ threadId: OTHER,
+ projectId: PROJECT,
+ title: "Update the docs",
+ modelSelection: agent,
+ runtimeMode: "auto",
+ interactionMode: "default",
+ branch: "fix/flaky",
+ worktreePath: "/worktrees/fix-flaky",
+ createdAt: now,
+ } as OrchestrationCommand,
+ readModel: model,
+ }),
+ );
+ for (const [index, planned] of (Array.isArray(decided) ? decided : [decided]).entries()) {
+ model = await Effect.runPromise(
+ projectEvent(model, { ...planned, sequence: 100 + index } as OrchestrationEvent),
+ );
+ }
+ return {
+ ...model,
+ threads: model.threads.map((thread) =>
+ thread.id === OTHER
+ ? {
+ ...thread,
+ commandRuns: [
+ {
+ runId: RUN,
+ terminalId: "terminal-docs",
+ mode: "run",
+ dialect: "posix",
+ command: "pnpm docs:build",
+ source: { kind: "message", messageId: MessageId.make("m-docs") },
+ turnId: TURN,
+ participantId: null,
+ cwd: "/worktrees/fix-flaky",
+ autoSend: false,
+ status: "running",
+ startedAt: now,
+ finishedAt: null,
+ exitCode: null,
+ error: null,
+ hasOutput: false,
+ heldReason: null,
+ outputSentAt: null,
+ outputMessageId: null,
+ createdAt: now,
+ updatedAt: now,
+ },
+ ],
+ }
+ : thread,
+ ),
+ } as OrchestrationReadModel;
+ }
+
+ it("moves once the other thread's command ends, even when nothing else happens there", async () => {
+ const h = await harness({ model: await sharingWithRunningCommand() });
+ await h.startReactor();
+ await h.queueMove();
+ await waitFor(
+ () => h.thread().pendingMove?.waitsFor?.some((w) => w.code === "shared_checkout") === true,
+ "the shared folder wait",
+ );
+ await settle();
+ expect(h.thread().move ?? null).toBeNull();
+
+ // Interrupted: no turn starts there, and no session changes, to wake the move.
+ await h.dispatch({
+ type: "thread.command-run.update",
+ commandId: nextCommandId(),
+ threadId: OTHER,
+ progress: { runId: RUN, status: "interrupted", finishedAt: now },
+ createdAt: now,
+ });
+ await waitFor(() => (h.thread().move ?? null) !== null, "the move to start");
+ await h.close();
+ });
+});
+
describe("MoveQueue, several threads at once", () => {
const OTHER = ThreadId.make("thread-2");
/** A second thread, in its own checkout, with pull request auto-fix on: it can't move. */
diff --git a/apps/server/src/moves/MoveQueue.ts b/apps/server/src/moves/MoveQueue.ts
index 8bb04017e..2f9d2d391 100644
--- a/apps/server/src/moves/MoveQueue.ts
+++ b/apps/server/src/moves/MoveQueue.ts
@@ -67,6 +67,7 @@ import {
PARENT_DIDNT_MOVE_WORDS,
restoreMessageText,
sameMoveStatus,
+ sharedCheckoutBusyThreads,
type ThreadMoveRefusalEntry,
threadMoveRefusals,
} from "../orchestration/threadMoveDecisions.ts";
@@ -315,6 +316,8 @@ interface TrackedMove {
quiescedAtMs: number;
/** The session the last quiesce saw (sessionMark). */
quiescedSession: string;
+ /** The other threads in its folder the last full look waited on (sharedCheckoutBusyThreads). */
+ waitsOnThreads: ReadonlySet;
}
export const makeMoveQueue = (
@@ -452,6 +455,7 @@ export const makeMoveQueue = (
existing.holds = 0;
existing.quiescedAtMs = 0;
existing.quiescedSession = "";
+ existing.waitsOnThreads = new Set();
return;
}
tracked.set(threadId, {
@@ -463,6 +467,7 @@ export const makeMoveQueue = (
holds: 0,
quiescedAtMs: 0,
quiescedSession: "",
+ waitsOnThreads: new Set(),
});
});
@@ -529,6 +534,9 @@ export const makeMoveQueue = (
context.thread,
context.thread.pendingMove?.targetTakes,
);
+ // Whatever those threads do next (a command run interrupted, a
+ // workflow or a voice chat ending) is a reason to look again.
+ entry.waitsOnThreads = new Set(sharedCheckoutBusyThreads(context.view, context.thread));
if (yield* settleRefusals(threadId, pending, refusals)) return;
// Before anything is stopped: whether the target takes what the thread
// carries (docs/design/fleet.md, Part 3e). One that doesn't ends the
@@ -1167,8 +1175,13 @@ export const makeMoveQueue = (
return yield* lookAtAll(settleDelay, false);
}
const threadId = "threadId" in event.payload ? event.payload.threadId : undefined;
- if (threadId !== undefined && tracked.has(threadId)) {
- yield* schedule(threadId, settleDelay);
+ if (threadId === undefined) return;
+ if (tracked.has(threadId)) yield* schedule(threadId, settleDelay);
+ // A move waiting on this thread's work in its folder looks again.
+ for (const [waiting, entry] of tracked) {
+ if (waiting !== threadId && entry.waitsOnThreads.has(threadId)) {
+ yield* schedule(waiting, settleDelay);
+ }
}
}),
),
diff --git a/apps/server/src/moves/ThreadMoves.test.ts b/apps/server/src/moves/ThreadMoves.test.ts
index f00e13746..1f6199510 100644
--- a/apps/server/src/moves/ThreadMoves.test.ts
+++ b/apps/server/src/moves/ThreadMoves.test.ts
@@ -9,6 +9,7 @@ import {
ProviderDriverKind,
ProviderInstanceId,
ThreadId,
+ ThreadMoveFamilyId,
type ThreadMovePreview,
TurnId,
} from "@threadlines/contracts";
@@ -70,20 +71,41 @@ const shown = (target: Partial): ThreadMov
describe("checkMoveTarget", () => {
it("takes the target's suggestion when the move names no agent, and a named one as named", () => {
- expect(checkMoveTarget(shown({ suggestedAgent: claude }), MAC_MINI, undefined)).toMatchObject({
+ expect(
+ checkMoveTarget(shown({ suggestedAgent: claude }), MAC_MINI, undefined, undefined),
+ ).toMatchObject({
agent: claude,
});
- expect(checkMoveTarget(shown({ suggestedAgent: claude }), MAC_MINI, codex)).toMatchObject({
+ expect(
+ checkMoveTarget(shown({ suggestedAgent: claude }), MAC_MINI, codex, undefined),
+ ).toMatchObject({
agent: codex,
});
});
it("can't go when the target suggests none and none is named", () => {
- expect(checkMoveTarget(shown({}), MAC_MINI, undefined)).toEqual({
+ expect(checkMoveTarget(shown({}), MAC_MINI, undefined, undefined)).toEqual({
refusal: "Mac mini has no agent ready.",
});
});
+ it("a child moving alone goes only where it stays its parent's; with its family it still goes", () => {
+ // A computer that was offline when the move was queued, back on an older Threadlines.
+ const older = shown({
+ suggestedAgent: claude,
+ aloneRefusal: "Update Threadlines on Mac mini to move it without the thread that started it.",
+ });
+ expect(checkMoveTarget(older, MAC_MINI, undefined, undefined)).toEqual({
+ refusal: "Update Threadlines on Mac mini to move it without the thread that started it.",
+ });
+ expect(
+ checkMoveTarget(older, MAC_MINI, undefined, {
+ id: ThreadMoveFamilyId.make("family-1"),
+ parentThreadId: ThreadId.make("thread-parent"),
+ }),
+ ).toMatchObject({ agent: claude });
+ });
+
it("a batch lists a computer once, and a thread its own refusals there", () => {
const peer = {
environmentId: MAC_MINI,
@@ -253,6 +275,7 @@ describe("checkMoveTarget", () => {
}),
MAC_MINI,
undefined,
+ undefined,
),
).toHaveProperty("unreachable");
});
@@ -443,36 +466,60 @@ describe("what a thread carries, as the dialog says it (Part 3e)", () => {
expect(linkLineageOf([thread], thread, MAC_MINI)).toEqual({
home: { parentThreadId: "thread-on-mac" },
});
- expect(
- linkLineageOf([thread], thread, EnvironmentId.make("environment-linux")),
- ).toBeUndefined();
- });
-
- it("a moved thread still fenced is offered only the computer it came from (Part 3f, (h))", () => {
- const thread = threadWith({
+ // A child that moved here alone names the thread it moved over from, so
+ // home can land it under its parent before it heard that move landed.
+ const movedHere = {
+ ...thread,
movedFrom: {
environmentId: MAC_MINI,
+ environmentPinned: true as const,
label: "Mac mini",
- threadId: ThreadId.make("thread-on-mac"),
+ threadId: ThreadId.make("thread-left-on-mac"),
movedAt: "2026-11-17T10:00:00.000Z",
- fenced: true,
},
+ };
+ expect(linkLineageOf([movedHere], movedHere, MAC_MINI)).toEqual({
+ home: { parentThreadId: "thread-on-mac", fromThreadId: "thread-left-on-mac" },
});
+ expect(
+ linkLineageOf([thread], thread, EnvironmentId.make("environment-linux")),
+ ).toBeUndefined();
+ });
+
+ it("a moved thread still fenced is offered only the computer it came from (Part 3f, (h))", () => {
+ const movedFrom = {
+ environmentId: MAC_MINI,
+ environmentPinned: true as const,
+ label: "Mac mini",
+ threadId: ThreadId.make("thread-on-mac"),
+ movedAt: "2026-11-17T10:00:00.000Z",
+ fenced: true as const,
+ };
+ const thread = threadWith({ movedFrom });
const carry = threadMoveCarry(view, thread);
const described = peer({ moveThreadState: true, moveLinkLineage: true });
- expect(
- targetPreviewOf(
- {
- environmentId: EnvironmentId.make("environment-linux"),
- label: "Linux box",
- described: Option.some(described),
- },
- { thread, place, carry },
- ).refusal,
- ).toBe(
+ const linux = {
+ environmentId: EnvironmentId.make("environment-linux"),
+ label: "Linux box",
+ described: Option.some(described),
+ };
+ expect(targetPreviewOf(linux, { thread, place, carry }).refusal).toBe(
"This thread moved here from Mac mini, and until you send it a message here it can only move back to Mac mini.",
);
expect(targetPreviewOf(target(described), { thread, place, carry }).refusal).toBeUndefined();
+ // Over a link that never proved its computer, "back" is only the sender's
+ // word: while fenced it goes nowhere.
+ const { environmentPinned: _, ...unproven } = movedFrom;
+ const unpinned = threadWith({ movedFrom: unproven });
+ const unpinnedCarry = threadMoveCarry(view, unpinned);
+ const unconfirmed =
+ "This thread moved here from Mac mini, and this computer's link can't confirm which computer that is, so it stays here until you send it a message.";
+ expect(
+ targetPreviewOf(target(described), { thread: unpinned, place, carry: unpinnedCarry }).refusal,
+ ).toBe(unconfirmed);
+ expect(targetPreviewOf(linux, { thread: unpinned, place, carry: unpinnedCarry }).refusal).toBe(
+ unconfirmed,
+ );
});
it("a child moves alone only to a computer that keeps it its parent's (Part 3f, (h))", () => {
diff --git a/apps/server/src/moves/ThreadMoves.ts b/apps/server/src/moves/ThreadMoves.ts
index 55013b439..f42a97ec5 100644
--- a/apps/server/src/moves/ThreadMoves.ts
+++ b/apps/server/src/moves/ThreadMoves.ts
@@ -679,12 +679,15 @@ export const offerUntilTaken = (deps: {
/**
* The target and agent a move names, checked against what the target said
* (`moves.preview`). No agent named: the one the target suggests for this
- * thread, as the dialog picks it; none there means the move can't go.
+ * thread, as the dialog picks it; none there means the move can't go. A
+ * child moving without its family (`family` absent) goes only to a computer
+ * that keeps it its parent's child (`aloneRefusal`, Part 3f, (h)).
*/
export function checkMoveTarget(
shown: ThreadMovePreview,
environmentId: EnvironmentId,
named: ModelSelection | undefined,
+ family: ThreadMoveFamily | undefined,
):
| { readonly ok: ThreadMoveTargetPreview; readonly agent: ModelSelection }
| { readonly unreachable: ThreadMoveTargetPreview }
@@ -693,6 +696,9 @@ export function checkMoveTarget(
if (target === undefined) return { refusal: "This computer isn't linked to that one." };
if (target.unreachable === true) return { unreachable: target };
if (target.refusal !== undefined) return { refusal: target.refusal };
+ if (family === undefined && target.aloneRefusal !== undefined) {
+ return { refusal: target.aloneRefusal };
+ }
const agent = named ?? target.suggestedAgent;
if (agent === undefined) return { refusal: `${target.label} has no agent ready.` };
const offered = target.agents.find((entry) => entry.instanceId === agent.instanceId);
@@ -1152,7 +1158,7 @@ const make = Effect.gen(function* () {
const shown = inspected.preview;
if (shown.refusal !== undefined) return yield* moveError(shown.refusal);
if (inspected.busy !== null) return yield* moveError(inspected.busy);
- const checked = checkMoveTarget(shown, input.targetEnvironmentId, input.agent);
+ const checked = checkMoveTarget(shown, input.targetEnvironmentId, input.agent, undefined);
if ("refusal" in checked) return yield* moveError(checked.refusal);
if ("unreachable" in checked) {
return yield* moveError(checked.unreachable.refusal ?? "That computer can't be reached.");
@@ -1185,7 +1191,7 @@ const make = Effect.gen(function* () {
});
const shown = inspected.preview;
if (shown.refusal !== undefined) return yield* moveError(shown.refusal);
- const checked = checkMoveTarget(shown, input.targetEnvironmentId, input.agent);
+ const checked = checkMoveTarget(shown, input.targetEnvironmentId, input.agent, input.family);
if ("refusal" in checked) return yield* moveError(checked.refusal);
// A pick the computer doesn't have is refused now; the rest is decided when it starts.
if ("ok" in checked) {
@@ -1234,7 +1240,12 @@ const make = Effect.gen(function* () {
}
const shown = inspected.success.preview;
if (shown.refusal !== undefined) return { kind: "blocked", words: shown.refusal } as const;
- const checked = checkMoveTarget(shown, input.targetEnvironmentId, input.agent);
+ const checked = checkMoveTarget(
+ shown,
+ input.targetEnvironmentId,
+ input.agent,
+ inspected.success.thread.pendingMove?.family,
+ );
if ("refusal" in checked) return { kind: "blocked", words: checked.refusal } as const;
if ("unreachable" in checked) {
return {
@@ -1817,13 +1828,23 @@ const make = Effect.gen(function* () {
* The thread was deleted while it moved: the other computer is asked
* once to drop the move (one that already arrived there stays), and the
* packed copy goes. Unreachable, its own expiry drops a move that never
- * finished arriving.
+ * finished arriving. A move already recorded as landed only loses its
+ * packed copy.
*/
const dropIfDeleted = Effect.gen(function* () {
const row = yield* threadRows.getById({ threadId });
- if (Option.isNone(row) || row.value.deletedAt === null) return;
+ if (Option.isNone(row)) return;
const move = row.value.move ?? null;
- if (move === null || move.transferId !== transferId || move.movedAway !== undefined) return;
+ if (move === null || move.transferId !== transferId) return;
+ // Completed by something other than this worker (the thread came back
+ // before it heard, Part 3f, (h)): only the packed copy is left to go.
+ if (move.movedAway !== undefined) {
+ yield* Effect.tryPromise(() =>
+ NodeFs.rm(moveDir(transferId), { recursive: true, force: true }),
+ ).pipe(Effect.ignore);
+ return;
+ }
+ if (row.value.deletedAt === null) return;
yield* client
.withPeer(move.target.environmentId, (peer) => peer["peer.move.abort"]({ transferId }))
.pipe(Effect.ignore);
diff --git a/apps/server/src/moves/familyMove.ts b/apps/server/src/moves/familyMove.ts
index c99fbd9e2..52d0cec3d 100644
--- a/apps/server/src/moves/familyMove.ts
+++ b/apps/server/src/moves/familyMove.ts
@@ -114,7 +114,9 @@ export const familyThreadIdsOf = (
* to `targetEnvironmentId` (docs/design/fleet.md, Part 3f, (h)), or nothing:
*
* - a thread another computer's agent started, going back to that computer:
- * `home`, naming the thread there that started it;
+ * `home`, naming the thread there that started it, and the thread there
+ * it moved over from, when it did (that computer may not have heard yet
+ * that its move landed);
* - a child moving without its parent: `remoteParent`, naming the parent,
* unless the parent is gone, frozen for its own move or moved away (then it
* lands as a thread of its own there). A parent whose move is only queued
@@ -129,9 +131,16 @@ export function linkLineageOf(
): PeerMoveLinkLineage | undefined {
const origin = thread.remoteOrigin ?? null;
if (origin !== null) {
- return origin.environmentId === targetEnvironmentId
- ? { home: { parentThreadId: origin.threadId } }
- : undefined;
+ if (origin.environmentId !== targetEnvironmentId) return undefined;
+ const from = thread.movedFrom ?? null;
+ return {
+ home: {
+ parentThreadId: origin.threadId,
+ ...(from !== null && from.environmentId === targetEnvironmentId
+ ? { fromThreadId: from.threadId }
+ : {}),
+ },
+ };
}
if (thread.parentThreadId === null || !thread.attachedToParent) return undefined;
if ((thread.move ?? thread.pendingMove)?.family !== undefined) return undefined;
diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts
index 495ed5cab..f320b7f82 100644
--- a/apps/server/src/orchestration/childThreadDecisions.ts
+++ b/apps/server/src/orchestration/childThreadDecisions.ts
@@ -571,8 +571,11 @@ export function decideChildSend(
return refuse(refusal?.detail ?? "That thread is gone.");
}
// A child frozen for its move takes nothing here (docs/design/fleet.md,
- // Part 3f, (h)): a message written now would never reach it.
- const childMove = child.move ?? null;
+ // Part 3f, (h)): a message written now would never reach it. Nor does one
+ // whose move is stopping it (`quiescing`): its queue no longer drains, so
+ // the move would wait on the message and the parent on its answer.
+ const childMove =
+ child.move ?? (child.pendingMove?.stage === "quiescing" ? child.pendingMove : null);
if (childMove !== null) {
return refuse(
`That thread is moving to ${childMove.target.label}. Send it the message once it's there.`,
@@ -1398,7 +1401,9 @@ export const MovedAloneActivityKind = "thread.moved-alone";
* settle as cancelled, with a note for its agent. When that computer kept it
* the parent's child across the link (`keptParent`, its answer over the
* link), the parent keeps it as a child there, as a thread it started there,
- * and reaches it over the link from now on.
+ * and reaches it over the link from now on. One that already came back here
+ * before this computer heard it landed (`returned`) is never kept there: it
+ * came back under the parent (`adopted`) or as a thread of its own (`own`).
*/
export function movedAloneEvents(
readModel: OrchestrationReadModel,
@@ -1408,16 +1413,26 @@ export function movedAloneEvents(
readonly target: { readonly environmentId: EnvironmentId; readonly label: string };
readonly threadId: ThreadId;
readonly keptParent: boolean;
+ readonly returned?: "adopted" | "own" | undefined;
},
at: string,
): ReadonlyArray {
if (child.parentThreadId === null || !child.attachedToParent) return [];
const parent = findThread(readModel, child.parentThreadId);
const label = moved.target.label;
- const kept = moved.keptParent && parent !== null && parent.deletedAt === null;
- const words = kept
- ? `It's still a thread of '${parent.title}', which reaches it on ${label}.`
- : `It's its own thread on ${label}, so the thread that started it can't reach it there.`;
+ const kept =
+ moved.returned === undefined &&
+ moved.keptParent &&
+ parent !== null &&
+ parent.deletedAt === null;
+ const words =
+ moved.returned === "adopted" && parent !== null
+ ? `It moved to ${label} and back, and is still a thread of '${parent.title}' here.`
+ : moved.returned !== undefined
+ ? `It moved to ${label} and back, as a thread of its own.`
+ : kept
+ ? `It's still a thread of '${parent.title}', which reaches it on ${label}.`
+ : `It's its own thread on ${label}, so the thread that started it can't reach it there.`;
return [
{
...baseFor(child.id),
@@ -1455,9 +1470,13 @@ export function movedAloneEvents(
"cancelled",
at,
(titles) =>
- kept
- ? `${quotedList(titles)} moved to ${label} before it answered. Send it the message again there.`
- : `${quotedList(titles)} moved to ${label} as its own thread, so its answer won't come back to you.`,
+ moved.returned === "adopted"
+ ? `${quotedList(titles)} moved to ${label} and back before it answered. Send it the message again.`
+ : moved.returned !== undefined
+ ? `${quotedList(titles)} moved to ${label} and back as its own thread, so its answer won't come back to you.`
+ : kept
+ ? `${quotedList(titles)} moved to ${label} before it answered. Send it the message again there.`
+ : `${quotedList(titles)} moved to ${label} as its own thread, so its answer won't come back to you.`,
)),
...(kept
? [
diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts
index be181a760..e05daf04d 100644
--- a/apps/server/src/orchestration/decider.threadMoves.test.ts
+++ b/apps/server/src/orchestration/decider.threadMoves.test.ts
@@ -1773,7 +1773,7 @@ describe("a moved thread that moves on, or edits its goal before its agent knows
interactionMode: "default",
branch: "fix/flaky",
worktreePath: "/worktrees/moved-3",
- movedFrom: { ...MAC_MINI, threadId: THREAD, movedAt: now },
+ movedFrom: { ...MAC_MINI, environmentPinned: true, threadId: THREAD, movedAt: now },
messages: [],
activities: [],
createdAt: now,
@@ -3016,6 +3016,23 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h))
});
});
+ it("a parent's message never lands on a child its own move is already stopping", async () => {
+ let model = await parentWorking(await withChild(await seeded()));
+ ({ model } = await apply(model, queueFor(CHILD)));
+ ({ model } = await apply(model, {
+ type: "thread.move.quiesce",
+ commandId: nextCommandId(),
+ threadId: CHILD,
+ requestId: CHILD_REQUEST,
+ createdAt: now,
+ }));
+ expect(threadOf(model, CHILD).pendingMove?.stage).toBe("quiescing");
+ // Its queue no longer drains: the move would wait on it, and the parent on the answer.
+ expect(
+ (await apply(model, sendTo(CHILD, ChildRequestId.make("r-stopping")))).refusal,
+ ).toContain("That thread is moving to Mac mini. Send it the message once it's there.");
+ });
+
it("a child that arrived as its own thread there leaves the family, and nothing records it there", async () => {
let model = await movedAlone(await withChild(await seeded()));
({ model } = await apply(model, complete(false)));
@@ -3309,7 +3326,7 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h))
interactionMode: "default",
branch: "fix/tests",
worktreePath: `/worktrees/${ARRIVED}`,
- movedFrom: { ...from, threadId: SOURCE, movedAt: now },
+ movedFrom: { ...from, environmentPinned: true, threadId: SOURCE, movedAt: now },
messages: [],
activities: [],
createdAt: now,
@@ -3501,5 +3518,84 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h))
),
).toEqual([]);
});
+
+ it("over a link that never proved its computer, a fenced thread moves nowhere, not even back", async () => {
+ const { model } = await apply(await seeded(), {
+ ...importFrom(MAC_MINI),
+ movedFrom: { ...MAC_MINI, threadId: SOURCE, movedAt: now },
+ } as OrchestrationCommand);
+ const unconfirmed =
+ "This thread moved here from Mac mini, and this computer's link can't confirm which computer that is, so it stays here until you send it a message.";
+ expect((await apply(model, queueFor(ARRIVED, TAKES))).refusal).toContain(unconfirmed);
+ expect((await apply(model, queueFor(ARRIVED, TAKES, THIRD))).refusal).toContain(unconfirmed);
+ // A person here takes it over: then it may go.
+ const taken = (await apply(model, personSends(ARRIVED))).model;
+ expect((await apply(taken, queueFor(ARRIVED, TAKES, THIRD))).refusal).toBeNull();
+ });
+
+ describe("back before this computer heard its move there landed", () => {
+ /** The child's own move to Mac mini, still waiting for the answer; it became THERE. */
+ const backFromThere = (extra: Record = {}) =>
+ ({
+ ...importFrom(MAC_MINI, extra),
+ movedFrom: { ...MAC_MINI, environmentPinned: true, threadId: THERE, movedAt: now },
+ }) as OrchestrationCommand;
+ const completesChild = { adopt: { parentThreadId: THREAD, completesMoveOf: CHILD } };
+
+ it("lands under its parent, and the move it left on completes then", async () => {
+ const moving = await movedAlone(await asked(await withChild(await seeded())));
+ let { model, refusal } = await apply(moving, backFromThere(completesChild));
+ expect(refusal).toBeNull();
+ expect(threadOf(model, ARRIVED)).toMatchObject({
+ parentThreadId: THREAD,
+ attachedToParent: true,
+ });
+ const left = threadOf(model, CHILD);
+ expect(left.move?.movedAway).toBeDefined();
+ expect(left.attachedToParent).toBe(false);
+ expect(left.activities.at(-1)?.summary).toBe(
+ "It moved to Mac mini and back, and is still a thread of 'Fix the flaky test' here.",
+ );
+ const parent = threadOf(model);
+ expect(parent.childRequests.remoteChildren ?? []).toEqual([]);
+ expect(parent.childRequests.open).toEqual([]);
+ expect(parent.childRequests.pendingNotes.at(-1)?.text).toContain(
+ "moved to Mac mini and back before it answered",
+ );
+ // The answer this computer was still waiting for comes late: nothing changes.
+ ({ model } = await apply(model, complete(true)));
+ expect(threadOf(model).childRequests.remoteChildren ?? []).toEqual([]);
+ expect(threadOf(model, ARRIVED).attachedToParent).toBe(true);
+ });
+
+ it("only for the parent's child moving alone to exactly that computer", async () => {
+ const moving = await movedAlone(await withChild(await seeded()));
+ // Over another computer's link.
+ expect(
+ (
+ await apply(moving, {
+ ...backFromThere(completesChild),
+ movedFrom: { ...THIRD, environmentPinned: true, threadId: THERE, movedAt: now },
+ } as OrchestrationCommand)
+ ).refusal,
+ ).toContain("doesn't hold this thread");
+ // Naming a thread that isn't moving there.
+ expect(
+ (await apply(await withChild(await seeded()), backFromThere(completesChild))).refusal,
+ ).toContain("doesn't hold this thread");
+ });
+
+ it("a late answer never makes a thread already back here the parent's child there", async () => {
+ const moving = await movedAlone(await withChild(await seeded()));
+ // An older computer there named no thread: it landed as its own thread.
+ let { model } = await apply(moving, backFromThere());
+ expect(threadOf(model, ARRIVED).parentThreadId).toBeNull();
+ ({ model } = await apply(model, complete(true)));
+ expect(threadOf(model).childRequests.remoteChildren ?? []).toEqual([]);
+ expect(threadOf(model, CHILD).activities.at(-1)?.summary).toBe(
+ "It moved to Mac mini and back, as a thread of its own.",
+ );
+ });
+ });
});
});
diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts
index 7f4cc350d..c21875ae5 100644
--- a/apps/server/src/orchestration/threadMoveDecisions.ts
+++ b/apps/server/src/orchestration/threadMoveDecisions.ts
@@ -412,22 +412,34 @@ export function threadMoveRefusals(
sendable: thread.queuedFollowUps ?? [],
}),
);
- // Another thread at work in the same checkout could change the files while
- // they are being packed. One frozen for its own move can't: its agent is
- // stopped, and nothing it holds (a plan, a queue) runs while it moves.
- const checkout = checkoutOf(readModel, thread);
- const sharedCheckoutBusy = readModel.threads.some(
- (candidate) =>
- candidate.id !== thread.id &&
- candidate.deletedAt === null &&
- (candidate.move ?? null) === null &&
- checkoutOf(readModel, candidate) === checkout &&
- busyInFolder(candidate),
- );
- if (sharedCheckoutBusy) found.push(wait("shared_checkout"));
+ if (sharedCheckoutBusyThreads(readModel, thread).length > 0) found.push(wait("shared_checkout"));
return found;
}
+/**
+ * The other threads at work in `thread`'s checkout (the `shared_checkout`
+ * wait): they could change the files while they are being packed. One
+ * frozen for its own move can't: its agent is stopped, and nothing it holds
+ * (a plan, a queue) runs while it moves. The move queue looks again when
+ * any of them changes.
+ */
+export function sharedCheckoutBusyThreads(
+ readModel: ThreadMoveView,
+ thread: OrchestrationThread,
+): ReadonlyArray {
+ const checkout = checkoutOf(readModel, thread);
+ return readModel.threads
+ .filter(
+ (candidate) =>
+ candidate.id !== thread.id &&
+ candidate.deletedAt === null &&
+ (candidate.move ?? null) === null &&
+ checkoutOf(readModel, candidate) === checkout &&
+ busyInFolder(candidate),
+ )
+ .map((candidate) => candidate.id);
+}
+
/**
* What `thread` is doing now that goes away on its own (docs/design/fleet.md,
* Parts 3b and 3f), as its move's waits: a turn and what it asks of the user,
@@ -556,8 +568,10 @@ export function remoteOriginMoveRefusal(
* Why a thread a move brought here, still behind the fence (`movedFrom.fenced`:
* no person here has sent it a message yet), can't move to `target`, or null
* (docs/design/fleet.md, Part 3f, (h)): it goes back to the computer it came
- * from, and nowhere else. Once a person here takes it over, the usual rules
- * hold. A null `target` asks about any computer: the dialog says per computer.
+ * from, and nowhere else. Over a link that never proved which computer that
+ * is (`environmentPinned`), where it came from is only the sender's word, so
+ * it goes nowhere. Once a person here takes it over, the usual rules hold. A
+ * null `target` asks about any computer: the dialog says per computer.
*/
export function fencedMoveRefusal(
thread: Pick,
@@ -565,6 +579,9 @@ export function fencedMoveRefusal(
): string | null {
const from = thread.movedFrom ?? null;
if (from === null || from.fenced !== true || target === null) return null;
+ if (from.environmentPinned !== true) {
+ return `This thread moved here from ${from.label}, and this computer's link can't confirm which computer that is, so it stays here until you send it a message.`;
+ }
return target.environmentId === from.environmentId ? null : fencedElsewhereWords(from.label);
}
@@ -1472,6 +1489,27 @@ export function decideMoveComplete(
const move = currentMove(thread, command.transferId);
if (move === null) return refuse("This thread isn't moving.");
if (move.movedAway !== undefined) return [];
+ return moveCompleteEvents(readModel, thread, move, command, baseFor);
+}
+
+/**
+ * decideMoveComplete's events for a move under way. Also what an import
+ * that proves a lone child's move landed records for it (`completesMoveOf`):
+ * the thread came back before this computer heard (`returned: "adopted"`).
+ * A lone child whose moved thread is already back here never becomes the
+ * parent's child on that computer, whichever came first.
+ */
+function moveCompleteEvents(
+ readModel: OrchestrationReadModel,
+ thread: OrchestrationThread,
+ move: OrchestrationThreadMove,
+ command: Pick<
+ CommandOf<"thread.move.complete">,
+ "transferId" | "movedThreadId" | "keptParent" | "createdAt"
+ >,
+ baseFor: EventBase,
+ returned?: "adopted",
+): PlannedEvent[] {
const familyId = move.family?.id;
const comesAlong = (child: OrchestrationThread) =>
familyId !== undefined &&
@@ -1510,6 +1548,11 @@ export function decideMoveComplete(
target: move.target,
threadId: command.movedThreadId,
keptParent: command.keptParent === true,
+ returned:
+ returned ??
+ (cameBackFrom(readModel, move.target.environmentId, command.movedThreadId)
+ ? "own"
+ : undefined),
},
command.createdAt,
)
@@ -1517,6 +1560,42 @@ export function decideMoveComplete(
];
}
+/** Whether the thread `threadId` on `environmentId` has since moved here. */
+const cameBackFrom = (
+ readModel: Pick,
+ environmentId: string,
+ threadId: string,
+) =>
+ readModel.threads.some(
+ (entry) =>
+ entry.deletedAt === null &&
+ entry.movedFrom?.environmentId === environmentId &&
+ entry.movedFrom.threadId === threadId,
+ );
+
+/**
+ * Whether `thread` is `parentThreadId`'s child here moving on its own
+ * (docs/design/fleet.md, Part 3f, (h)) to `environmentId`, with that
+ * computer's answer still to come: the move a thread coming back from there
+ * can complete (`thread.import`'s `adopt.completesMoveOf`).
+ */
+export function awaitsLoneMoveAnswer(
+ thread: Pick,
+ parentThreadId: ThreadId,
+ environmentId: string,
+): boolean {
+ const move = thread.move ?? null;
+ return (
+ thread.deletedAt === null &&
+ thread.parentThreadId === parentThreadId &&
+ thread.attachedToParent &&
+ move !== null &&
+ move.family === undefined &&
+ move.movedAway === undefined &&
+ move.target.environmentId === environmentId
+ );
+}
+
/**
* The read-only copy a moved thread leaves keeps nothing that acts for it
* (docs/design/fleet.md, Part 3e): its queued messages went with it, and its
@@ -1762,6 +1841,27 @@ export function decideThreadImport(
{ environmentId: command.movedFrom.environmentId, threadId: command.movedFrom.threadId },
command.createdAt,
);
+ // Its arrival proves the move it left on landed there: that move completes now.
+ const leftCopy =
+ adopt?.completesMoveOf === undefined
+ ? undefined
+ : readModel.threads.find((thread) => thread.id === adopt.completesMoveOf);
+ const leftMove = leftCopy?.move ?? null;
+ const completed =
+ leftCopy === undefined || leftMove === null
+ ? []
+ : moveCompleteEvents(
+ readModel,
+ leftCopy,
+ leftMove,
+ {
+ transferId: leftMove.transferId,
+ movedThreadId: command.movedFrom.threadId,
+ createdAt: command.createdAt,
+ },
+ baseFor,
+ "adopted",
+ );
return [
created,
...room,
@@ -1770,6 +1870,7 @@ export function decideThreadImport(
...importedState(command, base),
boundary,
...cameHome,
+ ...completed,
];
}
@@ -1821,6 +1922,17 @@ function importedLinkLineageRefusal(
if (parent.projectId !== command.projectId) {
return "The thread that started it is in another project.";
}
+ // Back before this computer heard its move there landed: the thread it
+ // moved over from is still the parent's child, moving alone to exactly
+ // that computer, and this import completes that move.
+ const completes = adopt.completesMoveOf;
+ if (completes !== undefined) {
+ const left = readModel.threads.find((entry) => entry.id === completes);
+ return left !== undefined &&
+ awaitsLoneMoveAnswer(left, parent.id, command.movedFrom.environmentId)
+ ? null
+ : "The thread that started it doesn't hold this thread.";
+ }
const held = (parent.childRequests.remoteChildren ?? []).some(
(entry) =>
entry.environmentId === command.movedFrom.environmentId &&
diff --git a/apps/web/src/components/ChatView.move-thread.browser.tsx b/apps/web/src/components/ChatView.move-thread.browser.tsx
index 7551edd5d..6a1f93230 100644
--- a/apps/web/src/components/ChatView.move-thread.browser.tsx
+++ b/apps/web/src/components/ChatView.move-thread.browser.tsx
@@ -1221,9 +1221,16 @@ describe("ChatView (full app): moving a thread to another computer", () => {
}),
);
- // The whole family: the parent is queued, with every thread it started.
+ // The whole family: the parent is queued, with every thread it started,
+ // each with the agent that computer suggests, so there's no agent to pick.
dialog = await openDialog();
+ await expect.element(dialog.getByTestId("thread-move-agent")).toBeInTheDocument();
await dialog.getByTestId("thread-move-child-family").click();
+ await expect.element(dialog.getByTestId("thread-move-agent")).not.toBeInTheDocument();
+ await expect.element(dialog.getByTestId("thread-move-session")).not.toBeInTheDocument();
+ await expect
+ .element(dialog.getByTestId("thread-move-family-agents"))
+ .toHaveTextContent("Each thread uses the agent Mac mini suggests for it.");
await dialog.getByTestId("thread-move-confirm").click();
await expect.element(page.getByTestId("thread-move-dialog")).not.toBeInTheDocument();
expect(queues.at(-1)).toEqual({
diff --git a/apps/web/src/components/ThreadMoveDialogContent.tsx b/apps/web/src/components/ThreadMoveDialogContent.tsx
index 82ce0f851..48d37ce4c 100644
--- a/apps/web/src/components/ThreadMoveDialogContent.tsx
+++ b/apps/web/src/components/ThreadMoveDialogContent.tsx
@@ -166,17 +166,6 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread
target !== null && agent !== null ? threadMoveAgentSelection(target, agent) : null;
// A General Chats thread: its folder goes, with no branch or staged changes.
const folder = preview?.folder;
- // What comes along, then what won't work there as it did, for the agent picked.
- const pickedInstanceId = unreachable ? null : (agentSelection?.instanceId ?? null);
- const brings = threadMoveNotesFor(preview?.brings, pickedInstanceId);
- const notes = threadMoveNotesFor(target?.notes, pickedInstanceId);
- // A room's other agents, each with the agent it moves as there or left out.
- // Out of reach: none sent, and each takes the suggestion when the move starts.
- const roomRows =
- preview?.room !== undefined && target !== null && !unreachable
- ? threadMoveRoomAgentRows(preview.room, target, roomPicks)
- : null;
- const roomAgents = roomRows?.map((row) => row.choice);
// A parent's family (Part 3f, (g)): the children ticked to come, each that can.
const family = preview?.family;
const coming = (family?.children ?? []).filter(
@@ -191,7 +180,25 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread
: target?.aloneRefusal !== undefined
? "family"
: pickedChildMove;
- const withFamily = parent !== undefined && childMove === "family";
+ const withFamily = queues && parent !== undefined && childMove === "family";
+ // With its whole family, every thread moves with the agent that computer
+ // suggests for it, as the parent's move queues them: nothing to pick here.
+ const suggestsAgents = unreachable || withFamily;
+ // What comes along, then what won't work there as it did, for the agent it gets.
+ const pickedInstanceId = unreachable
+ ? null
+ : withFamily
+ ? (target?.suggestedAgent?.instanceId ?? null)
+ : (agentSelection?.instanceId ?? null);
+ const brings = threadMoveNotesFor(preview?.brings, pickedInstanceId);
+ const notes = threadMoveNotesFor(target?.notes, pickedInstanceId);
+ // A room's other agents, each with the agent it moves as there or left out.
+ // Out of reach or with its family: none sent, and each takes the suggestion.
+ const roomRows =
+ preview?.room !== undefined && target !== null && !suggestsAgents
+ ? threadMoveRoomAgentRows(preview.room, target, roomPicks)
+ : null;
+ const roomAgents = roomRows?.map((row) => row.choice);
const canMove =
preview !== null &&
preview.refusal === undefined &&
@@ -207,7 +214,7 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread
try {
const client = requireThreadMovesClient(threadRef.environmentId, computerLabel);
const input = { threadId: threadRef.threadId, targetEnvironmentId: target.environmentId };
- if (queues && withFamily) {
+ if (withFamily) {
// The parent with every thread it started: the server's whole family,
// each with the agent that computer suggests.
await client.queue({
@@ -354,6 +361,10 @@ export function ThreadMoveDialogContent({ threadRef }: { threadRef: ScopedThread
{target.refusal} The move waits for it to connect, then uses the agent{" "}
{target.label} suggests.
+ ) : withFamily ? (
+
+ Each thread uses the agent {target.label} suggests for it.
+
) : (
<>
Date: Wed, 18 Nov 2026 04:19:10 -0500
Subject: [PATCH 2/3] fix(server): close the gaps review found in early-return
and folder-wait fixes
- An arriving thread reads the thread it moved over from before its
parent, and the decider takes `completesMoveOf` when the parent already
holds it, so an answer that lands mid-arrival never strands the return
or leaves the parent pointing at the read-only copy there.
- Only a thread that came back over a link that proved its computer stops
a late answer from recording the parent's child there.
- The move queue notes the last event per thread: a look that read a
waited-on thread before its event arrived looks again (a restart with the
shared folder wait already on record emits nothing else).
- A move worker stops waiting on an unreachable computer once the move
landed another way, and startup removes packed copies of moves already
recorded as landed.
---
apps/server/src/links/LinkMoves.ts | 52 +++++++++----------
apps/server/src/moves/MoveQueue.test.ts | 44 ++++++++++++++--
apps/server/src/moves/MoveQueue.ts | 17 ++++++
apps/server/src/moves/ThreadMoves.ts | 52 ++++++++++++++-----
.../orchestration/decider.threadMoves.test.ts | 31 +++++++++++
.../src/orchestration/threadMoveDecisions.ts | 38 ++++++++------
6 files changed, 176 insertions(+), 58 deletions(-)
diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts
index 35b21be5c..7fbff29d4 100644
--- a/apps/server/src/links/LinkMoves.ts
+++ b/apps/server/src/links/LinkMoves.ts
@@ -2370,14 +2370,31 @@ const make = Effect.gen(function* () {
left: "The thread that started it isn't on this computer anymore, so this is its own thread.",
};
if (home === null) return own;
- const found = yield* threadRows
- .getById({ threadId: parentThreadId })
- .pipe(
+ const read = (threadId: ThreadId) =>
+ threadRows.getById({ threadId }).pipe(
+ Effect.map(Option.getOrUndefined),
Effect.mapError(
() => new ImportStop({ reason: `${ownLabel()} couldn't read its threads.` }),
),
);
- const parent = Option.getOrUndefined(found);
+ // The thread it moved over from first, then the parent: its move's
+ // answer lands on both in one decision, so a parent read after a
+ // move that still waited either still waits or already holds it.
+ const fromThreadId = lineage.home?.fromThreadId;
+ const left = fromThreadId === undefined ? undefined : yield* read(fromThreadId);
+ const awaiting =
+ left !== undefined &&
+ awaitsLoneMoveAnswer(
+ {
+ deletedAt: left.deletedAt,
+ parentThreadId: left.parentThreadId ?? null,
+ attachedToParent: (left.attachedToParent ?? 0) > 0,
+ move: left.move ?? null,
+ },
+ parentThreadId,
+ home,
+ );
+ const parent = yield* read(parentThreadId);
const canAdopt =
parent !== undefined &&
parent.deletedAt === null &&
@@ -2391,29 +2408,10 @@ const make = Effect.gen(function* () {
);
if (holds) return { adopt: { parentThreadId } };
// Back before this computer heard its move there landed: the parent's
- // child here whose own move to that computer still waits for the answer.
- const fromThreadId = lineage.home?.fromThreadId;
- if (fromThreadId === undefined) return own;
- const left = Option.getOrUndefined(
- yield* threadRows
- .getById({ threadId: fromThreadId })
- .pipe(
- Effect.mapError(
- () => new ImportStop({ reason: `${ownLabel()} couldn't read its threads.` }),
- ),
- ),
- );
- return left !== undefined &&
- awaitsLoneMoveAnswer(
- {
- deletedAt: left.deletedAt,
- parentThreadId: left.parentThreadId ?? null,
- attachedToParent: (left.attachedToParent ?? 0) > 0,
- move: left.move ?? null,
- },
- parentThreadId,
- home,
- )
+ // child here whose own move to that computer still waits for the
+ // answer. Should the answer land before the import, the decider finds
+ // the parent holding it instead.
+ return awaiting && fromThreadId !== undefined
? { adopt: { parentThreadId, completesMoveOf: fromThreadId } }
: own;
});
diff --git a/apps/server/src/moves/MoveQueue.test.ts b/apps/server/src/moves/MoveQueue.test.ts
index 0ffde5657..1cf2a1b61 100644
--- a/apps/server/src/moves/MoveQueue.test.ts
+++ b/apps/server/src/moves/MoveQueue.test.ts
@@ -79,6 +79,8 @@ async function harness(options?: { readonly model?: OrchestrationReadModel }) {
carryChecks: 0,
/** How long checking a child that moves with its parent takes (a target that answers slowly). */
childCheckMs: 0,
+ /** Runs once after a look read the threads, before it gets them (something changed meanwhile). */
+ duringContextRead: null as null | (() => Effect.Effect),
};
const dispatch = (command: OrchestrationCommand): Effect.Effect =>
@@ -174,9 +176,17 @@ async function harness(options?: { readonly model?: OrchestrationReadModel }) {
readThread: (threadId) =>
Effect.sync(() => model.threads.find((entry) => entry.id === threadId) ?? null),
readContext: (threadId) =>
- Effect.sync(() => {
- const thread = model.threads.find((entry) => entry.id === threadId);
- return thread === undefined ? null : { thread, view: model };
+ Effect.gen(function* () {
+ const view = model;
+ const meanwhile = state.duringContextRead;
+ if (meanwhile !== null) {
+ state.duringContextRead = null;
+ yield* meanwhile().pipe(Effect.orDie);
+ // The reactor takes the event in before this look gets its read.
+ yield* Effect.sleep(Duration.millis(30));
+ }
+ const thread = view.threads.find((entry) => entry.id === threadId);
+ return thread === undefined ? null : { thread, view };
}),
pendingThreadIds: Effect.sync(() =>
model.threads.filter((thread) => (thread.pendingMove ?? null) !== null).map((t) => t.id),
@@ -604,6 +614,34 @@ describe("MoveQueue, another thread working in the same folder", () => {
await waitFor(() => (h.thread().move ?? null) !== null, "the move to start");
await h.close();
});
+
+ it("after a restart, an end that lands while a look reads the folder still wakes the move", async () => {
+ const first = await harness({ model: await sharingWithRunningCommand() });
+ await first.startReactor();
+ await first.queueMove();
+ await waitFor(
+ () =>
+ first.thread().pendingMove?.waitsFor?.some((w) => w.code === "shared_checkout") === true,
+ "the shared folder wait",
+ );
+ const left = first.model();
+ await first.close();
+
+ // The wait is already on record, so the look that finds it again reports nothing new.
+ const restarted = await harness({ model: left });
+ // The command ends after the look read the threads, before it knows whom it waits on.
+ restarted.state.duringContextRead = () =>
+ restarted.dispatchEffect({
+ type: "thread.command-run.update",
+ commandId: nextCommandId(),
+ threadId: OTHER,
+ progress: { runId: RUN, status: "interrupted", finishedAt: now },
+ createdAt: now,
+ });
+ await restarted.startReactor();
+ await waitFor(() => (restarted.thread().move ?? null) !== null, "the move to start");
+ await restarted.close();
+ });
});
describe("MoveQueue, several threads at once", () => {
diff --git a/apps/server/src/moves/MoveQueue.ts b/apps/server/src/moves/MoveQueue.ts
index 2f9d2d391..0eb8aca32 100644
--- a/apps/server/src/moves/MoveQueue.ts
+++ b/apps/server/src/moves/MoveQueue.ts
@@ -328,6 +328,12 @@ export const makeMoveQueue = (
const retryDelay = deps.retryDelay ?? defaultRetryDelay;
const settleDelay = deps.settleDelay ?? Duration.millis(250);
const tracked = new Map();
+ /**
+ * The last event the reactor saw, overall and per thread: a look that
+ * read another thread before one of its events arrived looks again.
+ */
+ let lastSequence = 0;
+ const lastSequenceOf = new Map();
const dispatchIgnoringRefusal = (command: OrchestrationCommand) =>
deps.dispatch(command).pipe(
@@ -527,6 +533,7 @@ export const makeMoveQueue = (
) {
return;
}
+ const readFrom = lastSequence;
const context = yield* deps.readContext(threadId);
if (context === null) return yield* forget(threadId);
const refusals = threadMoveRefusals(
@@ -537,6 +544,12 @@ export const makeMoveQueue = (
// Whatever those threads do next (a command run interrupted, a
// workflow or a voice chat ending) is a reason to look again.
entry.waitsOnThreads = new Set(sharedCheckoutBusyThreads(context.view, context.thread));
+ // One of them changed while this look read it: look again.
+ if (
+ [...entry.waitsOnThreads].some((other) => (lastSequenceOf.get(other) ?? 0) > readFrom)
+ ) {
+ entry.again = true;
+ }
if (yield* settleRefusals(threadId, pending, refusals)) return;
// Before anything is stopped: whether the target takes what the thread
// carries (docs/design/fleet.md, Part 3e). One that doesn't ends the
@@ -1140,6 +1153,10 @@ export const makeMoveQueue = (
yield* events.pipe(
Stream.runForEach((event) =>
Effect.gen(function* () {
+ lastSequence = Math.max(lastSequence, event.sequence);
+ if ("threadId" in event.payload) {
+ lastSequenceOf.set(event.payload.threadId, event.sequence);
+ }
if (event.type === "thread.move-queued") {
yield* track(event.payload.threadId, event.payload.pendingMove.requestId);
return yield* schedule(event.payload.threadId, Duration.zero);
diff --git a/apps/server/src/moves/ThreadMoves.ts b/apps/server/src/moves/ThreadMoves.ts
index f42a97ec5..28d045c6d 100644
--- a/apps/server/src/moves/ThreadMoves.ts
+++ b/apps/server/src/moves/ThreadMoves.ts
@@ -1404,13 +1404,16 @@ const make = Effect.gen(function* () {
/**
* Calls the other computer for a thread's move, waiting through outages
- * (every 15 seconds) for as long as the thread is here: a move never gives
- * up on its own, so the thread stays frozen until that computer answers.
- * Deleting the thread ends the wait. An answer that refuses the call
- * (PeerRpcError) is final and fails the call.
+ * (every 15 seconds) for as long as the thread is here and the move is
+ * still under way: a move never gives up on its own, so the thread stays
+ * frozen until that computer answers. Deleting the thread, or the move
+ * landing some other way (the thread came back, Part 3f, (h)), ends the
+ * wait. An answer that refuses the call (PeerRpcError) is final and fails
+ * the call.
*/
const peerCall = (
threadId: ThreadId,
+ transferId: ThreadMoveId,
environmentId: EnvironmentId,
call: (peer: PeerClient) => Effect.Effect,
) =>
@@ -1423,7 +1426,13 @@ const make = Effect.gen(function* () {
while: (error) =>
error._tag === "ComputerLinkUnavailableError"
? threadRows.getById({ threadId }).pipe(
- Effect.map((row) => Option.isSome(row) && row.value.deletedAt === null),
+ Effect.map(
+ (row) =>
+ Option.isSome(row) &&
+ row.value.deletedAt === null &&
+ row.value.move?.transferId === transferId &&
+ row.value.move.movedAway === undefined,
+ ),
Effect.orElseSucceed(() => true),
)
: Effect.succeed(false),
@@ -1459,11 +1468,11 @@ const make = Effect.gen(function* () {
continue;
}
if (move.cancelRequested) {
- return yield* peerCall(threadId, environmentId, (peer) =>
+ return yield* peerCall(threadId, transferId, environmentId, (peer) =>
peer["peer.move.abort"]({ transferId }),
);
}
- const state = yield* peerCall(threadId, environmentId, (peer) =>
+ const state = yield* peerCall(threadId, transferId, environmentId, (peer) =>
peer["peer.move.status"]({ transferId }),
);
if (state.status !== waitingWhile) return state;
@@ -1764,7 +1773,7 @@ const make = Effect.gen(function* () {
const move = yield* currentMove(threadId, transferId);
if (move === null) return null;
if (move.cancelRequested) {
- return yield* peerCall(threadId, environmentId, (peer) =>
+ return yield* peerCall(threadId, transferId, environmentId, (peer) =>
peer["peer.move.abort"]({ transferId }),
);
}
@@ -1782,7 +1791,7 @@ const make = Effect.gen(function* () {
},
catch: () => new ThreadMoveFailure({ reason: "The packed thread couldn't be read." }),
});
- const state = yield* peerCall(threadId, environmentId, (peer) =>
+ const state = yield* peerCall(threadId, transferId, environmentId, (peer) =>
peer["peer.move.chunk"]({ transferId, offset, data: bytes.toString("base64") }),
);
if (state.status !== "receiving") return state;
@@ -1798,7 +1807,7 @@ const make = Effect.gen(function* () {
});
}
}
- return yield* peerCall(threadId, environmentId, (peer) =>
+ return yield* peerCall(threadId, transferId, environmentId, (peer) =>
peer["peer.move.finish"]({ transferId }),
);
});
@@ -1817,7 +1826,9 @@ const make = Effect.gen(function* () {
* record yet is asked again until it is.
*/
const drop = (environmentId: EnvironmentId, reason: string) =>
- peerCall(threadId, environmentId, (peer) => peer["peer.move.abort"]({ transferId })).pipe(
+ peerCall(threadId, transferId, environmentId, (peer) =>
+ peer["peer.move.abort"]({ transferId }),
+ ).pipe(
Effect.retry({
schedule: Schedule.spaced(Duration.seconds(15)),
while: (error) => error._tag === "PeerRpcError",
@@ -1859,7 +1870,7 @@ const make = Effect.gen(function* () {
const label = move.target.label;
// Where the other computer stands, if it heard of this move at all: one
// it never heard of reads aborted with no reason.
- const known = yield* peerCall(threadId, environmentId, (peer) =>
+ const known = yield* peerCall(threadId, transferId, environmentId, (peer) =>
peer["peer.move.status"]({ transferId }),
);
let state: PeerMoveState | null = known;
@@ -1904,7 +1915,7 @@ const make = Effect.gen(function* () {
// allows it (an older one ignores that), and waited for while it is
// busy with other moves.
const offered = yield* offerUntilTaken({
- prepare: peerCall(threadId, environmentId, (peer) =>
+ prepare: peerCall(threadId, transferId, environmentId, (peer) =>
peer["peer.move.prepare"]({
transferId,
manifest: manifest.success,
@@ -2041,6 +2052,21 @@ const make = Effect.gen(function* () {
yield* runMove(thread.id, move.transferId).pipe(Effect.forkScoped);
}
}
+ // A packed copy left by a move that landed while no worker was there
+ // to tidy it (the thread came back first, then this computer stopped).
+ const packed = new Set(
+ yield* Effect.tryPromise(() =>
+ NodeFs.readdir(NodePath.join(config.stateDir, "moves")),
+ ).pipe(Effect.orElseSucceed((): ReadonlyArray => [])),
+ );
+ for (const thread of model.value.threads) {
+ const move = thread.move ?? null;
+ if (move !== null && move.movedAway !== undefined && packed.has(move.transferId)) {
+ yield* Effect.tryPromise(() =>
+ NodeFs.rm(moveDir(move.transferId), { recursive: true, force: true }),
+ ).pipe(Effect.ignore);
+ }
+ }
}
yield* events.pipe(
// A cancel wakes a move this process isn't running (it does
diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts
index e05daf04d..079f8f2de 100644
--- a/apps/server/src/orchestration/decider.threadMoves.test.ts
+++ b/apps/server/src/orchestration/decider.threadMoves.test.ts
@@ -3585,6 +3585,37 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h))
).toContain("doesn't hold this thread");
});
+ it("still lands under its parent when the answer beat it to the decision", async () => {
+ const moving = await movedAlone(await withChild(await seeded()));
+ // Read while the move still waited; the answer landed before the import did.
+ let { model } = await apply(moving, complete(true));
+ expect(threadOf(model).childRequests.remoteChildren).toHaveLength(1);
+ let refusal: string | null;
+ ({ model, refusal } = await apply(model, backFromThere(completesChild)));
+ expect(refusal).toBeNull();
+ expect(threadOf(model, ARRIVED)).toMatchObject({
+ parentThreadId: THREAD,
+ attachedToParent: true,
+ });
+ expect(threadOf(model).childRequests.remoteChildren ?? []).toEqual([]);
+ // The move it left on completed once, with that answer's words.
+ expect(threadOf(model, CHILD).activities.at(-1)?.summary).toBe(
+ "It's still a thread of 'Fix the flaky test', which reaches it on Mac mini.",
+ );
+ });
+
+ it("a claim over a link that never proved its computer doesn't cost the parent its child there", async () => {
+ const moving = await movedAlone(await withChild(await seeded()));
+ let { model } = await apply(moving, {
+ ...backFromThere(),
+ movedFrom: { ...MAC_MINI, threadId: THERE, movedAt: now },
+ } as OrchestrationCommand);
+ ({ model } = await apply(model, complete(true)));
+ expect(threadOf(model).childRequests.remoteChildren).toEqual([
+ expect.objectContaining({ environmentId: MAC_MINI.environmentId, threadId: THERE }),
+ ]);
+ });
+
it("a late answer never makes a thread already back here the parent's child there", async () => {
const moving = await movedAlone(await withChild(await seeded()));
// An older computer there named no thread: it landed as its own thread.
diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts
index c21875ae5..0b50e3b0c 100644
--- a/apps/server/src/orchestration/threadMoveDecisions.ts
+++ b/apps/server/src/orchestration/threadMoveDecisions.ts
@@ -1560,7 +1560,11 @@ function moveCompleteEvents(
];
}
-/** Whether the thread `threadId` on `environmentId` has since moved here. */
+/**
+ * Whether the thread `threadId` on `environmentId` has since moved here,
+ * over a link that proved that computer: the sender's word alone could
+ * otherwise cost a parent its child there.
+ */
const cameBackFrom = (
readModel: Pick,
environmentId: string,
@@ -1569,7 +1573,8 @@ const cameBackFrom = (
readModel.threads.some(
(entry) =>
entry.deletedAt === null &&
- entry.movedFrom?.environmentId === environmentId &&
+ entry.movedFrom?.environmentPinned === true &&
+ entry.movedFrom.environmentId === environmentId &&
entry.movedFrom.threadId === threadId,
);
@@ -1848,7 +1853,10 @@ export function decideThreadImport(
: readModel.threads.find((thread) => thread.id === adopt.completesMoveOf);
const leftMove = leftCopy?.move ?? null;
const completed =
- leftCopy === undefined || leftMove === null
+ leftCopy === undefined ||
+ leftMove === null ||
+ adoptedBy === undefined ||
+ !awaitsLoneMoveAnswer(leftCopy, adoptedBy.id, command.movedFrom.environmentId)
? []
: moveCompleteEvents(
readModel,
@@ -1922,23 +1930,23 @@ function importedLinkLineageRefusal(
if (parent.projectId !== command.projectId) {
return "The thread that started it is in another project.";
}
- // Back before this computer heard its move there landed: the thread it
- // moved over from is still the parent's child, moving alone to exactly
- // that computer, and this import completes that move.
- const completes = adopt.completesMoveOf;
- if (completes !== undefined) {
- const left = readModel.threads.find((entry) => entry.id === completes);
- return left !== undefined &&
- awaitsLoneMoveAnswer(left, parent.id, command.movedFrom.environmentId)
- ? null
- : "The thread that started it doesn't hold this thread.";
- }
const held = (parent.childRequests.remoteChildren ?? []).some(
(entry) =>
entry.environmentId === command.movedFrom.environmentId &&
entry.threadId === command.movedFrom.threadId,
);
- return held ? null : "The thread that started it doesn't hold this thread.";
+ if (held) return null;
+ // Back before this computer heard its move there landed: the thread it
+ // moved over from is still the parent's child, moving alone to exactly
+ // that computer, and this import completes that move. Had the answer
+ // landed first, the parent holds it (above).
+ const completes = adopt.completesMoveOf;
+ const left =
+ completes === undefined ? undefined : readModel.threads.find((entry) => entry.id === completes);
+ return left !== undefined &&
+ awaitsLoneMoveAnswer(left, parent.id, command.movedFrom.environmentId)
+ ? null
+ : "The thread that started it doesn't hold this thread.";
}
/**
From 0073f6ae046d16f0b6a419d62a053599181467dd Mon Sep 17 00:00:00 2001
From: Badcuban <108198679+badcuban@users.noreply.github.com>
Date: Wed, 18 Nov 2026 04:38:12 -0500
Subject: [PATCH 3/3] fix(server): an early return lands only as the copy its
move made
- A thread coming home completes its child's move only when it is the copy
that move made there: its id must be the one the transfer gives it there,
from this computer's device on that computer (linkMoveCopyThreadId). Both
the arrival and the decider check it, so a linked computer can't name the
real child and send back another thread.
- A parent on another computer can't queue a message for a child its own
move is already stopping (thread.remote-request.queue), and is told why.
- A returned thread deleted since still counts as back, so a late answer
never records the read-only copy there as the parent's child. Any
return counts again, proven link or not: the pinned-only check brought
back the original bug for honest returns over older links.
---
apps/server/src/links/LinkMoves.test.ts | 40 +++++++--
apps/server/src/links/LinkMoves.ts | 38 +++++---
apps/server/src/links/LinkRequests.ts | 8 +-
apps/server/src/moves/linkMoveIds.ts | 27 ++++++
.../src/orchestration/childThreadDecisions.ts | 32 ++++---
.../orchestration/decider.threadMoves.test.ts | 87 ++++++++++++++++---
.../src/orchestration/threadMoveDecisions.ts | 68 +++++++++------
packages/contracts/src/orchestration.ts | 19 ++--
8 files changed, 243 insertions(+), 76 deletions(-)
create mode 100644 apps/server/src/moves/linkMoveIds.ts
diff --git a/apps/server/src/links/LinkMoves.test.ts b/apps/server/src/links/LinkMoves.test.ts
index d5fe59581..51cb523c1 100644
--- a/apps/server/src/links/LinkMoves.test.ts
+++ b/apps/server/src/links/LinkMoves.test.ts
@@ -59,6 +59,8 @@ import {
import { RelayDeviceRepository } from "../relay/RelayDeviceRepository.ts";
import * as GitVcsDriver from "../vcs/GitVcsDriver.ts";
import * as VcsProcess from "../vcs/VcsProcess.ts";
+import { linkMoveCopyThreadId } from "../moves/linkMoveIds.ts";
+import { ComputerLinkRepository } from "./ComputerLinkRepository.ts";
import { LinkMoveRepository, LinkMoveRepositoryLive } from "./LinkMoveRepository.ts";
import {
binaryPatchBytes,
@@ -176,6 +178,8 @@ interface CarryRecord {
readonly shell?: () => OrchestrationThreadShell | undefined;
/** The computer the link was made for, when its invite pinned it. */
readonly pinnedEnvironmentId?: string;
+ /** This computer's device on that computer (its own link there), when it has one. */
+ readonly deviceThere?: string;
/** The link's name for that computer here (its device row). */
readonly linkLabel?: string;
/** Threads already here, as their rows read. */
@@ -195,6 +199,14 @@ function testLayer(
Layer.provideMerge(LinkMoveRepositoryLive),
Layer.provideMerge(
Layer.mergeAll(
+ Layer.mock(ComputerLinkRepository)({
+ getByEnvironment: () =>
+ Effect.succeed(
+ carry.deviceThere === undefined
+ ? Option.none()
+ : Option.some({ deviceId: carry.deviceThere } as never),
+ ),
+ }),
Layer.mock(LinkRequests)({
authority: () =>
Effect.succeed(
@@ -2008,12 +2020,17 @@ describe("a thread moving across its link (Part 3f, (h))", () => {
repos: ReturnType,
dispatched: OrchestrationCommand[],
lineage: MoveExportInput["linkLineage"],
- carry: Partial & { readonly sourceEnvironmentId?: EnvironmentId } = {},
+ carry: Partial & {
+ readonly sourceEnvironmentId?: EnvironmentId;
+ /** The thread it is on the computer it leaves. */
+ readonly sourceThreadId?: ThreadId;
+ } = {},
) =>
Effect.gen(function* () {
const packed = yield* pack(repos, null, undefined, {
linkLineage: lineage,
sourceEnvironmentId: carry.sourceEnvironmentId,
+ ...(carry.sourceThreadId !== undefined ? { threadId: carry.sourceThreadId } : {}),
// What the move says it is called never names anything here.
sourceLabel: "Not Windows",
});
@@ -2119,17 +2136,30 @@ describe("a thread moving across its link (Part 3f, (h))", () => {
},
});
const back = { home: { parentThreadId: PARENT_HERE, fromThreadId: LEFT } };
+ // This computer's device on Windows PC, which named the copy that move made there.
+ const DEVICE_THERE = "device-mac-on-windows";
+ const copy = linkMoveCopyThreadId(DEVICE_THERE, "transfer-left");
+ const completes = {
+ parentThreadId: PARENT_HERE,
+ completesMoveOf: { threadId: LEFT, deviceId: DEVICE_THERE },
+ };
const cases = [
- { left: leftHere(WINDOWS), adopt: { parentThreadId: PARENT_HERE, completesMoveOf: LEFT } },
+ { left: leftHere(WINDOWS), source: copy, adopt: completes },
+ // Another thread there, naming the child here: never under the parent.
+ { left: leftHere(WINDOWS), source: ThreadId.make("thread-a"), adopt: undefined },
+ // No link of this computer's own there to name the copy by.
+ { left: leftHere(WINDOWS), source: copy, deviceThere: null, adopt: undefined },
// Moving to another computer, or already heard to have landed: its own thread.
- { left: leftHere("environment-mac"), adopt: undefined },
- { left: leftHere(WINDOWS, true), adopt: undefined },
+ { left: leftHere("environment-mac"), source: copy, adopt: undefined },
+ { left: leftHere(WINDOWS, true), source: copy, adopt: undefined },
];
- return Effect.forEach(cases, ({ left, adopt }) => {
+ return Effect.forEach(cases, ({ left, source, adopt, ...rest }) => {
const repos = makeRepos();
const dispatched: OrchestrationCommand[] = [];
return moved(repos, dispatched, back, {
pinnedEnvironmentId: WINDOWS,
+ sourceThreadId: source,
+ ...("deviceThere" in rest ? {} : { deviceThere: DEVICE_THERE }),
// The parent holds nothing there yet: this computer hasn't heard.
threadsHere: [parentHere(WINDOWS, "thread-other"), left],
}).pipe(
diff --git a/apps/server/src/links/LinkMoves.ts b/apps/server/src/links/LinkMoves.ts
index 7fbff29d4..22d83825e 100644
--- a/apps/server/src/links/LinkMoves.ts
+++ b/apps/server/src/links/LinkMoves.ts
@@ -111,6 +111,8 @@ import { generalChatThreadScratchCwd } from "../orchestration/generalChats.ts";
import { clampLaunchToCeiling } from "../orchestration/childThreadDecisions.ts";
import { OrchestrationEngineService } from "../orchestration/Services/OrchestrationEngine.ts";
import { ProjectionSnapshotQuery } from "../orchestration/Services/ProjectionSnapshotQuery.ts";
+import { ComputerLinkRepository } from "./ComputerLinkRepository.ts";
+import { linkMoveCopyThreadId, linkMoveKey, linkMoveThreadId } from "../moves/linkMoveIds.ts";
import { awaitsLoneMoveAnswer } from "../orchestration/threadMoveDecisions.ts";
import { ProjectionThreadRepository } from "../persistence/Services/ProjectionThreads.ts";
import { discardSessionFiles, releaseSessionFiles } from "../provider/nativeSession.ts";
@@ -234,13 +236,7 @@ interface FamilyLanding {
const nowIso = Effect.map(DateTime.now, DateTime.formatIso);
-/** hash(link, transfer): every resource a move makes here is named from it. */
-export const linkMoveKey = (linkDeviceId: string, transferId: string) =>
- createHash("sha256").update(`${linkDeviceId}\u0000${transferId}`).digest("hex");
-
-/** The thread a move becomes here. */
-export const linkMoveThreadId = (transferKey: string) =>
- ThreadId.make(derivedUuid("link-move-thread", transferKey));
+export { linkMoveKey, linkMoveThreadId } from "../moves/linkMoveIds.ts";
/**
* hash(link, family id): a family's key here (docs/design/fleet.md, Part 3f,
@@ -600,6 +596,8 @@ const make = Effect.gen(function* () {
const engine = yield* OrchestrationEngineService;
const snapshots = yield* ProjectionSnapshotQuery;
const threadRows = yield* ProjectionThreadRepository;
+ // This computer's own links to others: its device on each (a copy's id there).
+ const outboundLinks = yield* ComputerLinkRepository;
const git = yield* GitVcsDriver;
const config = yield* ServerConfig;
const devices = yield* RelayDeviceRepository;
@@ -2409,10 +2407,28 @@ const make = Effect.gen(function* () {
if (holds) return { adopt: { parentThreadId } };
// Back before this computer heard its move there landed: the parent's
// child here whose own move to that computer still waits for the
- // answer. Should the answer land before the import, the decider finds
- // the parent holding it instead.
- return awaiting && fromThreadId !== undefined
- ? { adopt: { parentThreadId, completesMoveOf: fromThreadId } }
+ // answer, and this is the copy that move made there (its id is the
+ // transfer's, from this computer's device there). Should the answer
+ // land before the import, the decider finds the parent holding it.
+ const leftMove = left?.move ?? null;
+ if (!awaiting || fromThreadId === undefined || leftMove === null) return own;
+ const there = Option.getOrUndefined(
+ yield* outboundLinks
+ .getByEnvironment(home)
+ .pipe(
+ Effect.mapError(
+ () => new ImportStop({ reason: `${ownLabel()} couldn't read its links.` }),
+ ),
+ ),
+ );
+ return there !== undefined &&
+ linkMoveCopyThreadId(there.deviceId, leftMove.transferId) === source.threadId
+ ? {
+ adopt: {
+ parentThreadId,
+ completesMoveOf: { threadId: fromThreadId, deviceId: there.deviceId },
+ },
+ }
: own;
});
diff --git a/apps/server/src/links/LinkRequests.ts b/apps/server/src/links/LinkRequests.ts
index 492f0e754..62677c44d 100644
--- a/apps/server/src/links/LinkRequests.ts
+++ b/apps/server/src/links/LinkRequests.ts
@@ -81,7 +81,7 @@ import {
childAgentRefusal,
childReasoningRefusal,
} from "../orchestration/childThreadAgents.ts";
-import { clampLaunchToCeiling } from "../orchestration/childThreadDecisions.ts";
+import { clampLaunchToCeiling, movingChildRefusal } from "../orchestration/childThreadDecisions.ts";
import {
type ChildDelivery,
type ChildDeliveryRequest,
@@ -1076,6 +1076,12 @@ const make = Effect.gen(function* () {
yield* settleOrFail(row, "failed", reason, { error: reason });
return { status: "refused", reason } as const;
}
+ // Moving, or stopped for its move: it would never answer (decideRemoteRequestQueue).
+ const moving = movingChildRefusal(thread);
+ if (moving !== null) {
+ yield* settleOrFail(row, "failed", moving, { error: moving });
+ return { status: "refused", reason: moving } as const;
+ }
const sent = yield* dispatch(
{
type: "thread.remote-request.queue",
diff --git a/apps/server/src/moves/linkMoveIds.ts b/apps/server/src/moves/linkMoveIds.ts
new file mode 100644
index 000000000..bca40ca02
--- /dev/null
+++ b/apps/server/src/moves/linkMoveIds.ts
@@ -0,0 +1,27 @@
+/**
+ * The ids a move across a computer link is known by on the computer it
+ * arrives at (docs/design/fleet.md, Part 3c), derived from the link and the
+ * transfer, so every retry there lands on the same thread. The computer the
+ * thread left derives them too, from its own device on that computer: a
+ * thread coming back is the copy its move made there only when its id is
+ * this one (Part 3f, (h)).
+ */
+import { ThreadId } from "@threadlines/contracts";
+import { createHash } from "node:crypto";
+
+import { derivedUuid } from "../orchestration/childRequestIds.ts";
+
+/** hash(link, transfer): every resource a move makes there is named from it. */
+export const linkMoveKey = (linkDeviceId: string, transferId: string) =>
+ createHash("sha256").update(`${linkDeviceId}\u0000${transferId}`).digest("hex");
+
+/** The thread a move becomes there. */
+export const linkMoveThreadId = (transferKey: string) =>
+ ThreadId.make(derivedUuid("link-move-thread", transferKey));
+
+/**
+ * The copy the move `transferId` made on the computer where this computer's
+ * device is `deviceId` (a lone move: a family member's is named from its family).
+ */
+export const linkMoveCopyThreadId = (deviceId: string, transferId: string) =>
+ linkMoveThreadId(linkMoveKey(deviceId, transferId));
diff --git a/apps/server/src/orchestration/childThreadDecisions.ts b/apps/server/src/orchestration/childThreadDecisions.ts
index f320b7f82..29e1d9a29 100644
--- a/apps/server/src/orchestration/childThreadDecisions.ts
+++ b/apps/server/src/orchestration/childThreadDecisions.ts
@@ -541,6 +541,23 @@ export function decideChildRespond(
];
}
+/**
+ * Why a parent's message can't go to `child` now, or null: a child frozen
+ * for its move takes nothing here (docs/design/fleet.md, Part 3f, (h)), as a
+ * message written now would never reach it. Nor does one whose move is
+ * stopping it (`quiescing`): its queue no longer drains, so the move would
+ * wait on the message and the parent on its answer. For a parent here
+ * (`thread.child.send`) and on another computer (`thread.remote-request.queue`).
+ */
+export function movingChildRefusal(
+ child: Pick,
+): string | null {
+ const move = child.move ?? (child.pendingMove?.stage === "quiescing" ? child.pendingMove : null);
+ return move === null
+ ? null
+ : `That thread is moving to ${move.target.label}. Send it the message once it's there.`;
+}
+
/** A message from an agent to one of its children (`thread.child.send`). */
export function decideChildSend(
readModel: OrchestrationReadModel,
@@ -570,17 +587,8 @@ export function decideChildSend(
if (refusal !== null || child === null) {
return refuse(refusal?.detail ?? "That thread is gone.");
}
- // A child frozen for its move takes nothing here (docs/design/fleet.md,
- // Part 3f, (h)): a message written now would never reach it. Nor does one
- // whose move is stopping it (`quiescing`): its queue no longer drains, so
- // the move would wait on the message and the parent on its answer.
- const childMove =
- child.move ?? (child.pendingMove?.stage === "quiescing" ? child.pendingMove : null);
- if (childMove !== null) {
- return refuse(
- `That thread is moving to ${childMove.target.label}. Send it the message once it's there.`,
- );
- }
+ const moving = movingChildRefusal(child);
+ if (moving !== null) return refuse(moving);
if (
child.messages.some((message) => message.id === command.childMessageId) ||
parent.childRequests.open.some((request) => request.requestId === command.requestId)
@@ -1283,6 +1291,8 @@ export function decideRemoteRequestQueue(
if (thread.archivedAt !== null) {
return refuse("That thread is archived.");
}
+ const moving = movingChildRefusal(thread);
+ if (moving !== null) return refuse(moving);
if (thread.messages.some((message) => message.id === command.messageId)) {
return refuse("That message was already sent.");
}
diff --git a/apps/server/src/orchestration/decider.threadMoves.test.ts b/apps/server/src/orchestration/decider.threadMoves.test.ts
index 079f8f2de..1d4048fa2 100644
--- a/apps/server/src/orchestration/decider.threadMoves.test.ts
+++ b/apps/server/src/orchestration/decider.threadMoves.test.ts
@@ -34,6 +34,7 @@ import {
import * as Effect from "effect/Effect";
import { describe, expect, it } from "vite-plus/test";
+import { linkMoveCopyThreadId } from "../moves/linkMoveIds.ts";
import { decideOrchestrationCommand } from "./decider.ts";
import { createEmptyReadModel, projectEvent } from "./projector.ts";
import { isLinkFenced } from "./linkFence.ts";
@@ -2822,7 +2823,9 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h))
const CHILD = ThreadId.make("thread-lone-child");
const CHILD_REQUEST = ThreadMoveRequestId.make("request-lone-child");
const CHILD_TRANSFER = ThreadMoveId.make("transfer-lone-child");
- const THERE = ThreadId.make("thread-there");
+ /** This computer's device on Mac mini: the copy its move makes there is named from it. */
+ const DEVICE_THERE = "device-here-on-mac-mini";
+ const THERE = linkMoveCopyThreadId(DEVICE_THERE, CHILD_TRANSFER);
const TAKES: ThreadMoveTakes = { threadState: true, families: true, linkLineage: true };
const OLD_TAKES: ThreadMoveTakes = { threadState: true, families: true };
const THIRD = { environmentId: EnvironmentId.make("environment-third"), label: "Linux box" };
@@ -3281,6 +3284,37 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h))
} as OrchestrationCommand)
).model;
+ it("takes no message from its parent there once its move home is stopping it", async () => {
+ let model = await startedThere();
+ const fromParent = (messageId: string): OrchestrationCommand => ({
+ type: "thread.remote-request.queue",
+ commandId: nextCommandId(),
+ threadId: CHILD,
+ messageId: MessageId.make(messageId),
+ text: "Run the tests again",
+ fromThread: {
+ threadId: ThreadId.make("thread-on-mac"),
+ requestId: ChildRequestId.make(`request-${messageId}`),
+ kind: "request",
+ environmentId: MAC_MINI.environmentId,
+ },
+ createdAt: now,
+ });
+ ({ model } = await apply(model, queueFor(CHILD)));
+ // While it waits, a message still drains.
+ expect((await apply(model, fromParent("m-waiting"))).refusal).toBeNull();
+ ({ model } = await apply(model, {
+ type: "thread.move.quiesce",
+ commandId: nextCommandId(),
+ threadId: CHILD,
+ requestId: CHILD_REQUEST,
+ createdAt: now,
+ }));
+ expect((await apply(model, fromParent("m-stopping"))).refusal).toContain(
+ "That thread is moving to Mac mini. Send it the message once it's there.",
+ );
+ });
+
it("moves only back to that computer, over a link that proved it, never to a third", async () => {
const model = await startedThere();
expect((await apply(model, queueFor(CHILD, TAKES, THIRD))).refusal).toContain(
@@ -3540,7 +3574,12 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h))
...importFrom(MAC_MINI, extra),
movedFrom: { ...MAC_MINI, environmentPinned: true, threadId: THERE, movedAt: now },
}) as OrchestrationCommand;
- const completesChild = { adopt: { parentThreadId: THREAD, completesMoveOf: CHILD } };
+ const completesChild = {
+ adopt: {
+ parentThreadId: THREAD,
+ completesMoveOf: { threadId: CHILD, deviceId: DEVICE_THERE },
+ },
+ };
it("lands under its parent, and the move it left on completes then", async () => {
const moving = await movedAlone(await asked(await withChild(await seeded())));
@@ -3583,6 +3622,30 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h))
expect(
(await apply(await withChild(await seeded()), backFromThere(completesChild))).refusal,
).toContain("doesn't hold this thread");
+ // Another thread there, naming the child here: not the copy its move made.
+ const unrelated = await apply(moving, {
+ ...backFromThere(completesChild),
+ movedFrom: {
+ ...MAC_MINI,
+ environmentPinned: true,
+ threadId: ThreadId.make("thread-unrelated-on-mac"),
+ movedAt: now,
+ },
+ } as OrchestrationCommand);
+ expect(unrelated.refusal).toContain("doesn't hold this thread");
+ // Nor named from another device there.
+ const otherDevice = await apply(
+ moving,
+ backFromThere({
+ adopt: {
+ parentThreadId: THREAD,
+ completesMoveOf: { threadId: CHILD, deviceId: "device-someone-else" },
+ },
+ }),
+ );
+ expect(otherDevice.refusal).toContain("doesn't hold this thread");
+ // The child here is untouched, still on its way.
+ expect(threadOf(moving, CHILD).move?.movedAway).toBeUndefined();
});
it("still lands under its parent when the answer beat it to the decision", async () => {
@@ -3604,23 +3667,19 @@ describe("across the link: a child alone, and a thread going home (Part 3f, (h))
);
});
- it("a claim over a link that never proved its computer doesn't cost the parent its child there", async () => {
- const moving = await movedAlone(await withChild(await seeded()));
- let { model } = await apply(moving, {
- ...backFromThere(),
- movedFrom: { ...MAC_MINI, threadId: THERE, movedAt: now },
- } as OrchestrationCommand);
- ({ model } = await apply(model, complete(true)));
- expect(threadOf(model).childRequests.remoteChildren).toEqual([
- expect.objectContaining({ environmentId: MAC_MINI.environmentId, threadId: THERE }),
- ]);
- });
-
it("a late answer never makes a thread already back here the parent's child there", async () => {
const moving = await movedAlone(await withChild(await seeded()));
// An older computer there named no thread: it landed as its own thread.
let { model } = await apply(moving, backFromThere());
expect(threadOf(model, ARRIVED).parentThreadId).toBeNull();
+ // Deleted since: it still came back, and the copy there is read-only.
+ ({ model } = await apply(model, {
+ type: "thread.delete",
+ commandId: nextCommandId(),
+ threadId: ARRIVED,
+ createdAt: now,
+ } as OrchestrationCommand));
+ expect(threadOf(model, ARRIVED).deletedAt).not.toBeNull();
({ model } = await apply(model, complete(true)));
expect(threadOf(model).childRequests.remoteChildren ?? []).toEqual([]);
expect(threadOf(model, CHILD).activities.at(-1)?.summary).toBe(
diff --git a/apps/server/src/orchestration/threadMoveDecisions.ts b/apps/server/src/orchestration/threadMoveDecisions.ts
index 0b50e3b0c..1cc1bc4af 100644
--- a/apps/server/src/orchestration/threadMoveDecisions.ts
+++ b/apps/server/src/orchestration/threadMoveDecisions.ts
@@ -49,6 +49,7 @@ import { liveSideTurns } from "@threadlines/shared/sideTurns";
import { isValidParticipantId } from "@threadlines/shared/threadParticipants";
import { arrivalMessageText, resumedGoalMessageText } from "../moves/arrivalMessage.ts";
+import { linkMoveCopyThreadId } from "../moves/linkMoveIds.ts";
import { decideAgentChainStop } from "./agentRequestDecisions.ts";
import { derivedUuid } from "./childRequestIds.ts";
import { cameHomeEvents, leftBehindEvents, movedAloneEvents } from "./childThreadDecisions.ts";
@@ -1561,9 +1562,8 @@ function moveCompleteEvents(
}
/**
- * Whether the thread `threadId` on `environmentId` has since moved here,
- * over a link that proved that computer: the sender's word alone could
- * otherwise cost a parent its child there.
+ * Whether the thread `threadId` on `environmentId` has since moved here.
+ * One deleted since still came back: that computer's copy is read-only.
*/
const cameBackFrom = (
readModel: Pick,
@@ -1572,10 +1572,7 @@ const cameBackFrom = (
) =>
readModel.threads.some(
(entry) =>
- entry.deletedAt === null &&
- entry.movedFrom?.environmentPinned === true &&
- entry.movedFrom.environmentId === environmentId &&
- entry.movedFrom.threadId === threadId,
+ entry.movedFrom?.environmentId === environmentId && entry.movedFrom.threadId === threadId,
);
/**
@@ -1846,24 +1843,19 @@ export function decideThreadImport(
{ environmentId: command.movedFrom.environmentId, threadId: command.movedFrom.threadId },
command.createdAt,
);
- // Its arrival proves the move it left on landed there: that move completes now.
- const leftCopy =
- adopt?.completesMoveOf === undefined
- ? undefined
- : readModel.threads.find((thread) => thread.id === adopt.completesMoveOf);
- const leftMove = leftCopy?.move ?? null;
+ // Its arrival proves the move it left on landed there: that move completes
+ // now, unless its answer already did (the parent then held it, above).
+ const returned =
+ adoptedBy === undefined ? null : returnCompletes(readModel, command, adoptedBy.id);
const completed =
- leftCopy === undefined ||
- leftMove === null ||
- adoptedBy === undefined ||
- !awaitsLoneMoveAnswer(leftCopy, adoptedBy.id, command.movedFrom.environmentId)
+ returned === null
? []
: moveCompleteEvents(
readModel,
- leftCopy,
- leftMove,
+ returned.thread,
+ returned.move,
{
- transferId: leftMove.transferId,
+ transferId: returned.move.transferId,
movedThreadId: command.movedFrom.threadId,
createdAt: command.createdAt,
},
@@ -1936,19 +1928,39 @@ function importedLinkLineageRefusal(
entry.threadId === command.movedFrom.threadId,
);
if (held) return null;
- // Back before this computer heard its move there landed: the thread it
- // moved over from is still the parent's child, moving alone to exactly
- // that computer, and this import completes that move. Had the answer
+ // Back before this computer heard its move there landed. Had the answer
// landed first, the parent holds it (above).
- const completes = adopt.completesMoveOf;
- const left =
- completes === undefined ? undefined : readModel.threads.find((entry) => entry.id === completes);
- return left !== undefined &&
- awaitsLoneMoveAnswer(left, parent.id, command.movedFrom.environmentId)
+ return returnCompletes(readModel, command, parent.id) !== null
? null
: "The thread that started it doesn't hold this thread.";
}
+/**
+ * The move an import coming home completes (`adopt.completesMoveOf`), or
+ * null: the thread it moved over from is still `parentThreadId`'s child
+ * here, moving alone to exactly the computer it comes from with that
+ * computer's answer still to come, and the import is the very copy that
+ * move made there (its id is the one the transfer gives it there, from this
+ * computer's device on that computer). Anything else could put another
+ * thread under the parent, or end a move that never landed.
+ */
+function returnCompletes(
+ readModel: Pick,
+ command: CommandOf<"thread.import">,
+ parentThreadId: ThreadId,
+): { readonly thread: OrchestrationThread; readonly move: OrchestrationThreadMove } | null {
+ const completes = command.adopt?.completesMoveOf;
+ if (completes === undefined) return null;
+ const thread = readModel.threads.find((entry) => entry.id === completes.threadId);
+ const move = thread?.move ?? null;
+ return thread !== undefined &&
+ move !== null &&
+ awaitsLoneMoveAnswer(thread, parentThreadId, command.movedFrom.environmentId) &&
+ linkMoveCopyThreadId(completes.deviceId, move.transferId) === command.movedFrom.threadId
+ ? { thread, move }
+ : null;
+}
+
/**
* Why a moved room's agents can't be written as they are, or null: at most
* PEER_MOVE_ROOM_MAX_PARTICIPANTS, each with a UUID id of its own, no two
diff --git a/packages/contracts/src/orchestration.ts b/packages/contracts/src/orchestration.ts
index 7fbfd1067..0f3acb095 100644
--- a/packages/contracts/src/orchestration.ts
+++ b/packages/contracts/src/orchestration.ts
@@ -5629,14 +5629,21 @@ const ThreadImportCommand = Schema.Struct({
* (docs/design/fleet.md, Part 3f, (h)): it lands as `parentThreadId`'s
* child here, and that parent stops keeping it as a child on the computer
* it came from. Only when the parent here already holds exactly this
- * thread there (`movedFrom`) as its child, or (`completesMoveOf`) when it
- * is the parent's child here whose own move to that computer is still
- * waiting for that computer's answer: the thread came back before this
- * computer heard its move had landed, so that move completes in the same
- * decision.
+ * thread there (`movedFrom`) as its child, or (`completesMoveOf`) when the
+ * thread it moved over from is the parent's child here whose own move to
+ * that computer still waits for that computer's answer, and it is the
+ * very copy that move made there: its id is the one that move's transfer
+ * gives it there, from this computer's device on that computer
+ * (`deviceId`, linkMoveCopyThreadId). It came back before this computer
+ * heard its move had landed, so that move completes in the same decision.
*/
adopt: Schema.optional(
- Schema.Struct({ parentThreadId: ThreadId, completesMoveOf: Schema.optional(ThreadId) }),
+ Schema.Struct({
+ parentThreadId: ThreadId,
+ completesMoveOf: Schema.optional(
+ Schema.Struct({ threadId: ThreadId, deviceId: TrimmedNonEmptyString }),
+ ),
+ }),
),
/**
* What the "Moved here" line says came along (`brought`) and didn't