The best way to control Claude Code, Codex and more from any computer or phone
fix(server): end obsolete link cards after a matching retry succeeds (#26944)
Co-authored-by: maria-rcks <maria@kuuro.net> Co-authored-by: Julius Marminge <julius0216@outlook.com>
Stevan Borus committed
Nov 14, 2026 at 11:54 UTC
77ad2ebec500d331422e3c5093ad62fddeeb19e4
4 files changed
+531
-102
apps/server/src/orchestration-v2/Orchestrator.ts
+46
@@ -763,6 +763,18 @@ function cancelledAppOwnedTask(
763
};
764
}
765
766
+function askedForLinkedMachine(
767
+ card: Extract<OrchestrationV2TurnItem, { readonly type: "link_request" }>,
768
+ linked: Extract<OrchestrationV2InternalCommand, { readonly type: "link_request.record" }>,
769
+): boolean {
770
+ if (card.requestedAccess !== linked.requestedAccess) return false;
771
+ if (card.environmentId !== undefined) return card.environmentId === linked.linkedEnvironmentId;
772
+ if (card.url !== undefined) return linked.url !== undefined && card.url === linked.url;
773
+ const normalize = (text: string | undefined) => text?.trim().toLowerCase() ?? "";
774
+ const hint = normalize(card.hint);
775
+ return hint !== "" && hint === normalize(linked.hint) && hint === normalize(linked.linkedLabel);
776
+}
777
+
778
// A workspace change detaches the session, which can settle the calling run at once. Queuing its
779
// follow-up in a later command would let a delegated task report its result before that exists.
780
function metadataUpdateContinuation(
@@ -10448,6 +10460,7 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10460
type: _type,
10461
commandId: _commandId,
10462
turnItemId: _turnItemId,
10463
+ answeringTurnItemIds,
10464
wake,
10465
...fields
10466
} = command;
@@ -10507,6 +10520,39 @@ const makeOrchestrator = Effect.fn("orchestrationV2.Orchestrator.layer")(functio
10520
occurredAt: now,
10521
payload: turnItem,
10522
});
10523
+ // The link answers the older cards that asked for the same machine and
10524
+ // access. They end without waking anyone: the agent hears this link.
10525
+ // A card still being answered stays open for its own answer to end.
10526
+ if (!unchanged && command.linkStatus === "linked") {
10527
+ for (const item of projection.turnItems) {
10528
+ if (
10529
+ item.type !== "link_request" ||
10530
+ item.linkStatus !== "pending" ||
10531
+ item.ordinal >= turnItem.ordinal ||
10532
+ answeringTurnItemIds?.includes(item.id) === true ||
10533
+ !askedForLinkedMachine(item, command)
10534
+ ) {
10535
+ continue;
10536
+ }
10537
+ yield* emit(
10538
+ events,
10539
+ command,
10540
+ )({
10541
+ type: "turn-item.updated",
10542
+ threadId: command.threadId,
10543
+ ...(item.runId === null ? {} : { runId: item.runId }),
10544
+ ...(item.nodeId === null ? {} : { nodeId: item.nodeId }),
10545
+ occurredAt: now,
10546
+ payload: {
10547
+ ...item,
10548
+ status: "cancelled",
10549
+ linkStatus: "cancelled",
10550
+ completedAt: now,
10551
+ updatedAt: now,
10552
+ },
10553
+ });
10554
+ }
10555
+ }
10556
// The agent asked without waiting, so the answer reaches it as a
10557
// notification: it starts a turn, or follows the one running. Only the
10558
// answer that closes the card wakes it, and never a closed thread.
apps/server/src/peer/PeerLinkRequests.test.ts
+420
-66
@@ -7,6 +7,7 @@ import {
7
MessageId,
8
NodeId,
9
OrchestratorMcpFailure,
10
+ type PeerLinkCreateInput,
11
ProjectId,
12
ProviderDriverKind,
13
ProviderInstanceId,
@@ -125,74 +126,86 @@ const scope: McpInvocationContext.McpInvocationScope = {
126
issuedAt: 1,
127
};
128
128
-/** The laptop: a real orchestrator, its orchestrator toolkit, and its links. */
129
-const makeLaptop = Effect.gen(function* () {
130
- const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);
131
- // The orchestrator's own database, apart from the one links are kept in.
132
- const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);
133
- const layerDatabase = Layer.succeedContext(database);
134
- const layerOrchestrator = Layer.mergeAll(
135
- layerDatabase,
136
- ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
137
- ProviderReplayHarness.layerWithRegistry(
138
- { name: "peer-link-requests" },
139
- ProviderAdapterRegistry.layerFromAdapters([adapter]),
140
- { databaseLayer: layerDatabase, runEffectWorker: false },
141
- ),
142
- ).pipe(
143
- Layer.provide(
144
- Layer.succeed(ProviderContinuationRequests.ProviderContinuationRequests, {
145
- offer: () => Effect.void,
146
- take: Effect.never,
147
- }),
148
- ),
149
- );
150
- const layerThreads = ThreadManagement.layer.pipe(
151
- Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
152
- Layer.provideMerge(Layer.merge(layerOrchestrator, ServerSettings.layerTest())),
153
- );
154
- const layerHere = McpHttpServer.layerOrchestratorToolkit.pipe(
155
- Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
156
- Layer.provideMerge(PeerLinkRequests.layer),
157
- Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
158
- Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
159
- Layer.provide(Layer.succeedContext(linking)),
160
- Layer.provide(NodeCrypto.layer),
161
- Layer.provideMerge(layerThreads),
162
- Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
163
- Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
164
- Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
165
- Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
166
- Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
167
- Layer.provide(Layer.mock(ThreadLaunch.ThreadLaunchService)({})),
168
- Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
169
- Layer.provide(
170
- ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-requests-" }).pipe(
171
- Layer.provide(NodeServices.layer),
129
+/** A real orchestrator and links; the wrapper can hold a link in progress. */
130
+const makeLaptopWith = (
131
+ wrapLinks?: (links: PeerLinks.PeerLinks["Service"]) => PeerLinks.PeerLinks["Service"],
132
+) =>
133
+ Effect.gen(function* () {
134
+ const linking = yield* layerLinkingEnvironment(laptop).pipe(Layer.build);
135
+ const answering =
136
+ wrapLinks === undefined
137
+ ? linking
138
+ : Context.add(
139
+ linking,
140
+ PeerLinks.PeerLinks,
141
+ wrapLinks(Context.get(linking, PeerLinks.PeerLinks)),
142
+ );
143
+ // The orchestrator's own database, apart from the one links are kept in.
144
+ const database = yield* SqlitePersistence.layerMemory.pipe(Layer.build);
145
+ const layerDatabase = Layer.succeedContext(database);
146
+ const layerOrchestrator = Layer.mergeAll(
147
+ layerDatabase,
148
+ ProjectionStore.layer.pipe(Layer.provide(layerDatabase)),
149
+ ProviderReplayHarness.layerWithRegistry(
150
+ { name: "peer-link-requests" },
151
+ ProviderAdapterRegistry.layerFromAdapters([adapter]),
152
+ { databaseLayer: layerDatabase, runEffectWorker: false },
153
),
173
- ),
174
- Layer.provide(NodeServices.layer),
175
- Layer.fresh,
176
- );
177
- const here = yield* Layer.build(layerHere);
178
- const server = Context.get(here, McpServer.McpServer);
179
- return {
180
- links: Context.get(linking, PeerLinks.PeerLinks),
181
- linksSql: Context.get(linking, SqlClient.SqlClient),
182
- requests: Context.get(here, PeerLinkRequests.PeerLinkRequests),
183
- orchestrator: Context.get(here, Orchestrator.OrchestratorV2),
184
- sink: Context.get(here, EventSink.EventSinkV2),
185
- projections: Context.get(here, ProjectionStore.ProjectionStoreV2),
186
- sql: Context.get(database, SqlClient.SqlClient),
187
- call: (args: Record<string, unknown>, callScope = scope) =>
188
- server
189
- .callTool({ name: "t3_environment_link", arguments: args })
190
- .pipe(
191
- Effect.provideService(McpInvocationContext.McpInvocationContext, callScope),
192
- Effect.provideService(McpSchema.McpServerClient, mcpClient),
154
+ ).pipe(
155
+ Layer.provide(
156
+ Layer.succeed(ProviderContinuationRequests.ProviderContinuationRequests, {
157
+ offer: () => Effect.void,
158
+ take: Effect.never,
159
+ }),
160
+ ),
161
+ );
162
+ const layerThreads = ThreadManagement.layer.pipe(
163
+ Layer.provide(CommandReceiptStore.layer.pipe(Layer.provide(layerDatabase))),
164
+ Layer.provideMerge(Layer.merge(layerOrchestrator, ServerSettings.layerTest())),
165
+ );
166
+ const layerHere = McpHttpServer.layerOrchestratorToolkit.pipe(
167
+ Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
168
+ Layer.provideMerge(PeerLinkRequests.layer),
169
+ Layer.provide(Layer.mock(PeerForwarding.PeerForwarding)({})),
170
+ Layer.provide(Layer.mock(RemoteDelegation.RemoteDelegation)({})),
171
+ Layer.provide(Layer.succeedContext(answering)),
172
+ Layer.provide(NodeCrypto.layer),
173
+ Layer.provideMerge(layerThreads),
174
+ Layer.provide(Layer.mock(ProviderRegistry.ProviderRegistry)({})),
175
+ Layer.provide(Layer.mock(ProviderAdapterRegistry.ProviderAdapterRegistryV2)({})),
176
+ Layer.provide(Layer.mock(ScheduledTaskService.ScheduledTaskService)({})),
177
+ Layer.provide(Layer.mock(ProjectService.ProjectService)({})),
178
+ Layer.provide(Layer.mock(SecretRequests.SecretRequests)({})),
179
+ Layer.provide(Layer.mock(ThreadLaunch.ThreadLaunchService)({})),
180
+ Layer.provide(Layer.mock(GitVcsDriver.GitVcsDriver)({})),
181
+ Layer.provide(
182
+ ServerConfig.layerTest(process.cwd(), { prefix: "t3-peer-link-requests-" }).pipe(
183
+ Layer.provide(NodeServices.layer),
184
),
194
- };
195
-});
185
+ ),
186
+ Layer.provide(NodeServices.layer),
187
+ Layer.fresh,
188
+ );
189
+ const here = yield* Layer.build(layerHere);
190
+ const server = Context.get(here, McpServer.McpServer);
191
+ return {
192
+ links: Context.get(linking, PeerLinks.PeerLinks),
193
+ linksSql: Context.get(linking, SqlClient.SqlClient),
194
+ requests: Context.get(here, PeerLinkRequests.PeerLinkRequests),
195
+ orchestrator: Context.get(here, Orchestrator.OrchestratorV2),
196
+ sink: Context.get(here, EventSink.EventSinkV2),
197
+ projections: Context.get(here, ProjectionStore.ProjectionStoreV2),
198
+ sql: Context.get(database, SqlClient.SqlClient),
199
+ call: (args: Record<string, unknown>, callScope = scope) =>
200
+ server
201
+ .callTool({ name: "t3_environment_link", arguments: args })
202
+ .pipe(
203
+ Effect.provideService(McpInvocationContext.McpInvocationContext, callScope),
204
+ Effect.provideService(McpSchema.McpServerClient, mcpClient),
205
+ ),
206
+ };
207
+ });
208
+const makeLaptop = makeLaptopWith();
209
type Laptop = Effect.Success<typeof makeLaptop>;
210
211
/** The laptop's thread, mid-turn when its agent asks, in `runtimeMode`. */
@@ -1118,3 +1131,344 @@ it.live(
1131
}),
1132
),
1133
);
1134
+
1135
+const linkCards = (a: Laptop) =>
1136
+ a.orchestrator
1137
+ .getThreadProjection(threadId)
1138
+ .pipe(
1139
+ Effect.map((projection) =>
1140
+ projection.turnItems.flatMap((item) => (item.type === "link_request" ? [item] : [])),
1141
+ ),
1142
+ );
1143
+
1144
+const ask = (a: Laptop, args: Record<string, unknown>) =>
1145
+ Effect.gen(function* () {
1146
+ const asked = yield* a.call(args);
1147
+ const { turnItemId } = asked.structuredContent as { readonly turnItemId: TurnItemId };
1148
+ return (yield* linkCards(a)).find((card) => card.id === turnItemId)!;
1149
+ });
1150
+
1151
+const linkBox = (a: Laptop, b: ServedPeer, cardId: TurnItemId) =>
1152
+ Effect.gen(function* () {
1153
+ const pairing = yield* b.auth.issuePairingCredential();
1154
+ yield* a.requests.answer({
1155
+ threadId,
1156
+ turnItemId: cardId,
1157
+ answer: {
1158
+ type: "link",
1159
+ urls: [b.url],
1160
+ access: "full-access",
1161
+ pairingCode: pairing.credential,
1162
+ },
1163
+ });
1164
+ return pairing.credential;
1165
+ });
1166
+
1167
+const recordCard = (
1168
+ a: Laptop,
1169
+ key: string,
1170
+ fields: {
1171
+ readonly url?: string;
1172
+ readonly environmentId?: typeof box.environmentId;
1173
+ readonly hint?: string;
1174
+ readonly requestedAccess?: "read-only" | "full-access";
1175
+ },
1176
+) =>
1177
+ Effect.gen(function* () {
1178
+ const id = TurnItemId.make(`turn-item:link-request:${key}`);
1179
+ yield* a.orchestrator.dispatch({
1180
+ type: "link_request.record",
1181
+ commandId: CommandId.make(`command:pending:${key}`),
1182
+ threadId,
1183
+ runId,
1184
+ nodeId: rootNode,
1185
+ turnItemId: id,
1186
+ reason: "",
1187
+ linkStatus: "pending",
1188
+ ...fields,
1189
+ });
1190
+ return id;
1191
+ });
1192
+
1193
+it.live("a link ends older cards that asked for the same machine by hint, id or address", () =>
1194
+ withBoth((a, b) =>
1195
+ Effect.gen(function* () {
1196
+ yield* seedThread(a);
1197
+ // The agent first asks by the user's word, then again by the box's address.
1198
+ const older = yield* ask(a, {
1199
+ reason: "Delegate to the box.",
1200
+ hint: "Box",
1201
+ requestedAccess: "full-access",
1202
+ clientRequestId: "by-hint",
1203
+ });
1204
+ const byId = yield* ask(a, {
1205
+ environmentId: box.environmentId,
1206
+ requestedAccess: "full-access",
1207
+ clientRequestId: "by-id",
1208
+ });
1209
+ const byAddress = yield* recordCard(a, "by-address", {
1210
+ url: b.url,
1211
+ requestedAccess: "full-access",
1212
+ });
1213
+ const newer = yield* ask(a, {
1214
+ url: b.url,
1215
+ reason: "Delegate to the box.",
1216
+ hint: "Box",
1217
+ requestedAccess: "full-access",
1218
+ clientRequestId: "by-url",
1219
+ });
1220
+ const credential = yield* linkBox(a, b, newer.id);
1221
+
1222
+ const cards = yield* linkCards(a);
1223
+ expect(cards.find((card) => card.id === newer.id)).toMatchObject({
1224
+ status: "completed",
1225
+ linkStatus: "linked",
1226
+ linkedEnvironmentId: box.environmentId,
1227
+ });
1228
+ // The older card keeps what it asked and ends; it no longer asks the user.
1229
+ expect(cards.find((card) => card.id === older.id)).toMatchObject({
1230
+ status: "cancelled",
1231
+ linkStatus: "cancelled",
1232
+ hint: "Box",
1233
+ reason: "Delegate to the box.",
1234
+ requestedAccess: "full-access",
1235
+ });
1236
+ for (const id of [byId.id, byAddress]) {
1237
+ expect(cards.find((card) => card.id === id)).toMatchObject({ linkStatus: "cancelled" });
1238
+ }
1239
+ expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toBeNull();
1240
+ expect(
1241
+ ProjectionStore.threadShellFromProjection(
1242
+ yield* a.orchestrator.getThreadProjection(threadId),
1243
+ ).pendingRuntimeRequest,
1244
+ ).toBeNull();
1245
+ // The agent hears of the one link it made, and nothing about the card that link ended.
1246
+ expect((yield* outcomeMessages(a)).messages).toHaveLength(1);
1247
+ expect(yield* storedText(a)).not.toContain(credential);
1248
+ }),
1249
+ ),
1250
+);
1251
+
1252
+it.live("a link leaves open the cards that asked for something else, or asked later", () =>
1253
+ withBoth((a, b) =>
1254
+ Effect.gen(function* () {
1255
+ yield* seedThread(a);
1256
+ const other = descriptorOf("environment-other", "Other");
1257
+ const left = [
1258
+ // Another machine, and a word that names neither.
1259
+ yield* recordCard(a, "other-hint", { hint: "vps", requestedAccess: "full-access" }),
1260
+ yield* recordCard(a, "no-hint", { requestedAccess: "full-access" }),
1261
+ // The same word, but for less access than the link was asked with.
1262
+ yield* recordCard(a, "less-access", { hint: "Box", requestedAccess: "read-only" }),
1263
+ // The same word, on a card that named another machine.
1264
+ yield* recordCard(a, "other-id", {
1265
+ environmentId: other.environmentId,
1266
+ hint: "Box",
1267
+ requestedAccess: "full-access",
1268
+ }),
1269
+ yield* recordCard(a, "other-address", {
1270
+ url: "http://127.0.0.1:9",
1271
+ hint: "Box",
1272
+ requestedAccess: "full-access",
1273
+ }),
1274
+ // A word the label only contains.
1275
+ yield* recordCard(a, "partial-hint", { hint: "Bo", requestedAccess: "full-access" }),
1276
+ ];
1277
+ const linked = yield* ask(a, { url: b.url, hint: "Box", requestedAccess: "full-access" });
1278
+ const later = yield* recordCard(a, "later", { hint: "Box", requestedAccess: "full-access" });
1279
+ yield* linkBox(a, b, linked.id);
1280
+
1281
+ const cards = yield* linkCards(a);
1282
+ expect(cards.find((card) => card.id === linked.id)).toMatchObject({ linkStatus: "linked" });
1283
+ for (const id of [...left, later]) {
1284
+ expect(cards.find((card) => card.id === id)).toMatchObject({
1285
+ status: "waiting",
1286
+ linkStatus: "pending",
1287
+ });
1288
+ }
1289
+ }),
1290
+ ),
1291
+);
1292
+
1293
+it.live("a later card's failed link leaves the older card open", () =>
1294
+ withBoth((a, b) =>
1295
+ Effect.gen(function* () {
1296
+ yield* seedThread(a);
1297
+ const older = yield* ask(a, { hint: "Box", requestedAccess: "full-access" });
1298
+ const byAddress = yield* recordCard(a, "by-address", {
1299
+ url: b.url,
1300
+ requestedAccess: "full-access",
1301
+ });
1302
+ const newer = yield* ask(a, { url: b.url, hint: "Box", requestedAccess: "full-access" });
1303
+ yield* a.requests.answer({
1304
+ threadId,
1305
+ turnItemId: newer.id,
1306
+ answer: { type: "link", urls: [b.url], access: "full-access", pairingCode: "not-a-code" },
1307
+ });
1308
+
1309
+ const cards = yield* linkCards(a);
1310
+ expect(cards.find((card) => card.id === newer.id)).toMatchObject({ linkStatus: "failed" });
1311
+ for (const id of [older.id, byAddress]) {
1312
+ expect(cards.find((card) => card.id === id)).toMatchObject({
1313
+ status: "waiting",
1314
+ linkStatus: "pending",
1315
+ });
1316
+ }
1317
+ expect((yield* a.orchestrator.getThreadShell(threadId))?.pendingRuntimeRequest).toMatchObject(
1318
+ { kind: "user_input" },
1319
+ );
1320
+
1321
+ // The older card still takes its answer, and the failed one stays as it ended.
1322
+ yield* linkBox(a, b, older.id);
1323
+ const after = yield* linkCards(a);
1324
+ expect(after.find((card) => card.id === older.id)).toMatchObject({ linkStatus: "linked" });
1325
+ expect(after.find((card) => card.id === newer.id)).toMatchObject({ linkStatus: "failed" });
1326
+ }),
1327
+ ),
1328
+);
1329
+
1330
+const withHeldLinks = <A, E, R>(
1331
+ hold: (access: PeerLinkCreateInput["access"]) => Effect.Effect<void> | undefined,
1332
+ body: (a: Laptop, b: ServedPeer) => Effect.Effect<A, E, R>,
1333
+) =>
1334
+ Effect.scoped(
1335
+ Effect.gen(function* () {
1336
+ const b = yield* serveBox;
1337
+ const a = yield* makeLaptopWith((links) => ({
1338
+ ...links,
1339
+ link: (input) =>
1340
+ (hold(input.access) ?? Effect.void).pipe(Effect.andThen(links.link(input))),
1341
+ }));
1342
+ return yield* body(a, b);
1343
+ }),
1344
+ ).pipe(Effect.provide(NodeHttpServer.layerTest));
1345
+
1346
+it.live("an older card answered while a newer one links the same machine keeps its own link", () =>
1347
+ Effect.gen(function* () {
1348
+ const reached = yield* Deferred.make<void>();
1349
+ const release = yield* Deferred.make<void>();
1350
+ const fullAccessHeld = Deferred.succeed(reached, undefined).pipe(
1351
+ Effect.andThen(Deferred.await(release)),
1352
+ );
1353
+ yield* withHeldLinks(
1354
+ (access) => (access === "full-access" ? fullAccessHeld : undefined),
1355
+ (a, b) =>
1356
+ Effect.gen(function* () {
1357
+ yield* seedThread(a);
1358
+ // Both cards suggest the same machine and access.
1359
+ const older = yield* ask(a, {
1360
+ url: b.url,
1361
+ requestedAccess: "full-access",
1362
+ clientRequestId: "older",
1363
+ });
1364
+ const newer = yield* ask(a, {
1365
+ url: b.url,
1366
+ requestedAccess: "full-access",
1367
+ clientRequestId: "newer",
1368
+ });
1369
+ const olderCode = yield* b.auth.issuePairingCredential();
1370
+ const newerCode = yield* b.auth.issuePairingCredential();
1371
+
1372
+ // The user grants full access on the older card, which stalls while linking.
1373
+ const olderAnswer = yield* a.requests
1374
+ .answer({
1375
+ threadId,
1376
+ turnItemId: older.id,
1377
+ answer: {
1378
+ type: "link",
1379
+ urls: [b.url],
1380
+ access: "full-access",
1381
+ pairingCode: olderCode.credential,
1382
+ },
1383
+ })
1384
+ .pipe(Effect.forkChild);
1385
+ yield* Deferred.await(reached);
1386
+
1387
+ // Meanwhile the newer card links with read-only access and finishes.
1388
+ yield* a.requests.answer({
1389
+ threadId,
1390
+ turnItemId: newer.id,
1391
+ answer: {
1392
+ type: "link",
1393
+ urls: [b.url],
1394
+ access: "read-only",
1395
+ pairingCode: newerCode.credential,
1396
+ },
1397
+ });
1398
+ // The older card is still being answered, so the newer link leaves it open.
1399
+ expect((yield* linkCards(a)).find((card) => card.id === older.id)).toMatchObject({
1400
+ status: "waiting",
1401
+ linkStatus: "pending",
1402
+ });
1403
+
1404
+ yield* Deferred.succeed(release, undefined);
1405
+ yield* Fiber.join(olderAnswer);
1406
+
1407
+ const cards = yield* linkCards(a);
1408
+ const stored = Option.getOrThrow(yield* a.links.get(box.environmentId));
1409
+ expect(cards.find((card) => card.id === newer.id)).toMatchObject({
1410
+ status: "completed",
1411
+ linkStatus: "linked",
1412
+ linkedAccess: "read-only",
1413
+ });
1414
+ // The older card says what the link the box now has grants, and the agent hears it.
1415
+ expect(stored.access).toBe("full-access");
1416
+ expect(cards.find((card) => card.id === older.id)).toMatchObject({
1417
+ status: "completed",
1418
+ linkStatus: "linked",
1419
+ linkedEnvironmentId: stored.environmentId,
1420
+ linkedAccess: stored.access,
1421
+ });
1422
+ const { messages } = yield* outcomeMessages(a);
1423
+ expect(messages.map((message) => message.notification?.outcome)).toEqual([
1424
+ "completed",
1425
+ "completed",
1426
+ ]);
1427
+ }),
1428
+ );
1429
+ }),
1430
+);
1431
+
1432
+it.live("a card a newer link ended links nothing when answered after", () =>
1433
+ Effect.gen(function* () {
1434
+ let links = 0;
1435
+ yield* withHeldLinks(
1436
+ () => Effect.sync(() => void links++),
1437
+ (a, b) =>
1438
+ Effect.gen(function* () {
1439
+ yield* seedThread(a);
1440
+ const older = yield* ask(a, {
1441
+ url: b.url,
1442
+ requestedAccess: "full-access",
1443
+ clientRequestId: "older",
1444
+ });
1445
+ const newer = yield* ask(a, {
1446
+ url: b.url,
1447
+ requestedAccess: "full-access",
1448
+ clientRequestId: "newer",
1449
+ });
1450
+ yield* linkBox(a, b, newer.id);
1451
+ expect(links).toBe(1);
1452
+
1453
+ const pairing = yield* b.auth.issuePairingCredential();
1454
+ const late = yield* a.requests
1455
+ .answer({
1456
+ threadId,
1457
+ turnItemId: older.id,
1458
+ answer: {
1459
+ type: "link",
1460
+ urls: [b.url],
1461
+ access: "read-only",
1462
+ pairingCode: pairing.credential,
1463
+ },
1464
+ })
1465
+ .pipe(Effect.flip);
1466
+ expect(late.reason).toBe("already_answered");
1467
+ expect(links).toBe(1);
1468
+ expect(Option.getOrThrow(yield* a.links.get(box.environmentId)).access).toBe(
1469
+ "full-access",
1470
+ );
1471
+ }),
1472
+ );
1473
+ }),
1474
+);
apps/server/src/peer/PeerLinkRequests.ts
+60
-36
@@ -118,6 +118,7 @@ const make = Effect.gen(function* () {
118
outcome: LinkRequestOutcome,
119
commandId: CommandId,
120
wake?: LinkRequestWake,
121
+ answeringTurnItemIds?: ReadonlyArray<TurnItemId>,
122
) =>
123
threadManagement.dispatch({
124
type: "link_request.record",
@@ -133,6 +134,7 @@ const make = Effect.gen(function* () {
134
...(card.requestedAccess === undefined ? {} : { requestedAccess: card.requestedAccess }),
135
...outcome,
136
...(wake === undefined ? {} : { wake }),
137
+ ...(answeringTurnItemIds === undefined ? {} : { answeringTurnItemIds }),
138
});
139
140
const linkedOutcome = (linked: PeerLink): LinkRequestOutcome => ({
@@ -145,6 +147,11 @@ const make = Effect.gen(function* () {
147
// One answer per card at a time: two answers racing on one card must not
148
// both link. Other cards go on while a slow peer holds one.
149
const answerLocks = yield* KeyedLock.make<TurnItemId>();
150
+ // Per thread, held only to read a card before answering and to record the
151
+ // answer, never while linking. A link ends older cards for the same
152
+ // machine, but not one already being answered (its key is in answerLocks);
153
+ // an answer that starts after that reads the ended card and links nothing.
154
+ const lifecycleLocks = yield* KeyedLock.make<ThreadId>();
155
156
/**
157
* Closes a card still waiting when its agent retries naming a machine linked
@@ -153,22 +160,27 @@ const make = Effect.gen(function* () {
160
const closeAsLinked = (threadId: ThreadId, turnItemId: TurnItemId, linked: PeerLink) =>
161
answerLocks.withLock(
162
turnItemId,
156
- Effect.gen(function* () {
157
- const card = yield* readCard(threadId, turnItemId);
158
- if (
159
- card === undefined ||
160
- card.linkStatus !== "pending" ||
161
- card.runId === null ||
162
- card.nodeId === null
163
- ) {
164
- return;
165
- }
166
- yield* record(
167
- { ...card, runId: card.runId, nodeId: card.nodeId },
168
- linkedOutcome(linked),
169
- CommandId.make(`link-request:${card.id}:linked-on-retry`),
170
- );
171
- }),
163
+ lifecycleLocks.withLock(
164
+ threadId,
165
+ Effect.gen(function* () {
166
+ const card = yield* readCard(threadId, turnItemId);
167
+ if (
168
+ card === undefined ||
169
+ card.linkStatus !== "pending" ||
170
+ card.runId === null ||
171
+ card.nodeId === null
172
+ ) {
173
+ return;
174
+ }
175
+ yield* record(
176
+ { ...card, runId: card.runId, nodeId: card.nodeId },
177
+ linkedOutcome(linked),
178
+ CommandId.make(`link-request:${card.id}:linked-on-retry`),
179
+ undefined,
180
+ yield* answerLocks.activeKeys,
181
+ );
182
+ }),
183
+ ),
184
);
185
186
const request: PeerLinkRequests["Service"]["request"] = Effect.fn("PeerLinkRequests.request")(
@@ -340,17 +352,23 @@ const make = Effect.gen(function* () {
352
"orchestration_v2.thread_id": input.threadId,
353
"link_request.answer": input.answer.type,
354
});
343
- const card = yield* readCard(input.threadId, input.turnItemId).pipe(
344
- Effect.mapError((cause) => new PeerLinkRequestError({ reason: "load_failed", cause })),
355
+ const card = yield* lifecycleLocks.withLock(
356
+ input.threadId,
357
+ Effect.gen(function* () {
358
+ const card = yield* readCard(input.threadId, input.turnItemId).pipe(
359
+ Effect.mapError((cause) => new PeerLinkRequestError({ reason: "load_failed", cause })),
360
+ );
361
+ if (card === undefined || card.runId === null || card.nodeId === null) {
362
+ return yield* new PeerLinkRequestError({ reason: "not_found" });
363
+ }
364
+ // Any time while the card is open: the agent hears the answer as a
365
+ // notification, whether or not its run is still going.
366
+ if (card.linkStatus !== "pending") {
367
+ return yield* new PeerLinkRequestError({ reason: "already_answered" });
368
+ }
369
+ return { ...card, runId: card.runId, nodeId: card.nodeId };
370
+ }),
371
);
346
- if (card === undefined || card.runId === null || card.nodeId === null) {
347
- return yield* new PeerLinkRequestError({ reason: "not_found" });
348
- }
349
- // Any time while the card is open: the agent hears the answer as a
350
- // notification, whether or not its run is still going.
351
- if (card.linkStatus !== "pending") {
352
- return yield* new PeerLinkRequestError({ reason: "already_answered" });
353
- }
372
// An id beside an address is what answered there, recorded by an older
373
// server. Linking that machine could send its pairing code to the address.
374
const outcome: LinkRequestOutcome =
@@ -365,16 +383,22 @@ const make = Effect.gen(function* () {
383
: yield* answerOutcome(input.answer);
384
// If Stop closed the card while linking, the card keeps that; the link
385
// itself stands and Settings lists it.
368
- yield* record(
369
- { ...card, runId: card.runId, nodeId: card.nodeId },
370
- outcome,
371
- CommandId.make(`link-request:${card.id}:${outcome.linkStatus}`),
372
- {
373
- messageId: MessageId.make(`message:link-request:${card.id}`),
374
- ...outcomeNotice(card, outcome),
375
- },
376
- ).pipe(
377
- Effect.mapError((cause) => new PeerLinkRequestError({ reason: "record_failed", cause })),
386
+ yield* lifecycleLocks.withLock(
387
+ input.threadId,
388
+ Effect.flatMap(answerLocks.activeKeys, (answering) =>
389
+ record(
390
+ card,
391
+ outcome,
392
+ CommandId.make(`link-request:${card.id}:${outcome.linkStatus}`),
393
+ {
394
+ messageId: MessageId.make(`message:link-request:${card.id}`),
395
+ ...outcomeNotice(card, outcome),
396
+ },
397
+ answering,
398
+ ),
399
+ ).pipe(
400
+ Effect.mapError((cause) => new PeerLinkRequestError({ reason: "record_failed", cause })),
401
+ ),
402
);
403
},
404
(effect, input) =>
packages/contracts/src/orchestrationV2.ts
+5
@@ -3762,6 +3762,11 @@ const OrchestrationV2InternalCommand = Schema.Union([
3762
linkedLabel: Schema.optional(Schema.String),
3763
linkedAccess: Schema.optional(AuthMcpClientAccess),
3764
failure: Schema.optional(Schema.String),
3765
+ /**
3766
+ * Cards still being answered when this one linked. Their own answers end
3767
+ * them, so the link leaves them open; never stored on a card.
3768
+ */
3769
+ answeringTurnItemIds: Schema.optional(Schema.Array(TurnItemId)),
3770
/** Tells the agent how the card ended, in the same commit that closes it. */
3771
wake: Schema.optional(
3772
Schema.Struct({