The best way to control Claude Code, Codex and more from any computer or phone
fix(server): an MCP pin lands at the top of the Pinned section (#33978)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Xiao Wei Chen committed
Nov 15, 2026 at 02:37 UTC
f36c8351d82144413976b2482c745ace4a3f8f8b
7 files changed
+227
-68
apps/server/src/mcp/toolkits/core.test.ts
+77
@@ -19,9 +19,12 @@ import {
19
RuntimeRequestId,
20
ThreadId,
21
TurnItemId,
22
+ type OrchestrationV2ServerCommand,
23
type OrchestrationV2ProjectedTurnItem,
24
type OrchestrationV2ThreadShell,
25
} from "@t3tools/contracts";
26
+import { pinOrderKeyBetween } from "@t3tools/shared/pinOrderKey";
27
+import * as DateTime from "effect/DateTime";
28
import * as McpProviderSessions from "@t3tools/provider-core/server/McpProviderSessions";
29
import * as Deferred from "effect/Deferred";
30
import * as Effect from "effect/Effect";
@@ -447,6 +450,7 @@ it.effect("records only failed calls of tools that hand off no work", () => {
450
Effect.succeed(
451
McpToolAccessTestkit.idleThreadProjection(McpToolAccessTestkit.liveThreadShell(id)),
452
),
453
+ listActiveShellIndex: () => Effect.succeed([]),
454
dispatch: () => Effect.succeed({ sequence: 1 } as never),
455
}),
456
),
@@ -756,6 +760,7 @@ it.effect("a client caller targets any thread within its ceiling and cannot act
760
deletedAt: null,
761
},
762
} as never),
763
+ listActiveShellIndex: () => Effect.succeed([]),
764
dispatch: () => Effect.succeed({ sequence: 7, storedEvents: [] }),
765
}),
766
),
@@ -764,6 +769,78 @@ it.effect("a client caller targets any thread within its ceiling and cannot act
769
),
770
);
771
772
+it.effect("an MCP pin lands above every existing pin, as a client pin does", () => {
773
+ const dispatched: Array<OrchestrationV2ServerCommand> = [];
774
+ let targetPinnedAt: DateTime.Utc | null = null;
775
+ const pinnedAt = DateTime.makeUnsafe("2026-11-10T00:00:00.000Z");
776
+ const indexEntry = (id: string, pinned: boolean, pinOrderKey: string | null) => ({
777
+ ...McpToolAccessTestkit.liveThreadShell(ThreadId.make(id)),
778
+ pinnedAt: pinned ? pinnedAt : null,
779
+ pinOrderKey,
780
+ mayBeLive: false,
781
+ hasRemoteTasks: false,
782
+ });
783
+ return Effect.gen(function* () {
784
+ const server = yield* McpServer.McpServer;
785
+ const pin = server
786
+ .callTool({
787
+ name: "t3_thread_organize",
788
+ arguments: { action: "pin", threadId: "pin-target" },
789
+ })
790
+ .pipe(
791
+ Effect.provideService(McpInvocationContext.McpInvocationContext, clientScope("auto")),
792
+ Effect.provideService(McpSchema.McpServerClient, client),
793
+ );
794
+
795
+ const first = yield* pin;
796
+ expect(first.isError).toBe(false);
797
+ const orderKey = (dispatched[0] as { readonly orderKey?: string }).orderKey;
798
+ expect(dispatched[0]).toMatchObject({ type: "thread.pin", threadId: "pin-target" });
799
+ // The smallest key among pinned threads is "g"; the unpinned "b" and keyless pin are ignored.
800
+ expect(orderKey).toBe(pinOrderKeyBetween(null, "g"));
801
+
802
+ // A thread the handler last saw pinned still gets a key: an unpin can commit
803
+ // before this command, and the reducer ignores the key if the pin holds.
804
+ targetPinnedAt = pinnedAt;
805
+ const again = yield* pin;
806
+ expect(again.isError).toBe(false);
807
+ expect(dispatched[1]).toMatchObject({ type: "thread.pin", orderKey });
808
+ }).pipe(
809
+ Effect.provide(
810
+ layerThreadToolkit.pipe(
811
+ Layer.provideMerge(McpHttpServer.layerInProcessMcpServer),
812
+ Layer.provide(NodeCrypto.layer),
813
+ Layer.provide(
814
+ Layer.mock(ThreadManagement.ThreadManagementService)({
815
+ getThreadShell: (id) =>
816
+ Effect.succeed(McpToolAccessTestkit.liveThreadShell(id, { runtimeMode: "auto" })),
817
+ getProjectThreadRecords: ({ threadId: id }) => {
818
+ const projection = McpToolAccessTestkit.idleThreadProjection(
819
+ McpToolAccessTestkit.liveThreadShell(id, { runtimeMode: "auto" }),
820
+ );
821
+ return Effect.succeed({
822
+ ...projection,
823
+ thread: { ...projection.thread, pinnedAt: targetPinnedAt },
824
+ });
825
+ },
826
+ listActiveShellIndex: () =>
827
+ Effect.succeed([
828
+ indexEntry("pinned-late", true, "t"),
829
+ indexEntry("pinned-top", true, "g"),
830
+ indexEntry("pinned-keyless", true, null),
831
+ indexEntry("unpinned-stale-key", false, "b"),
832
+ ]),
833
+ dispatch: (command) => {
834
+ dispatched.push(command);
835
+ return Effect.succeed({ sequence: dispatched.length, storedEvents: [] });
836
+ },
837
+ }),
838
+ ),
839
+ ),
840
+ ),
841
+ );
842
+});
843
+
844
it.effect("search names the calling thread, so an agent can tell its own match apart", () =>
845
Effect.gen(function* () {
846
const server = yield* McpServer.McpServer;
apps/server/src/mcp/toolkits/thread/handlers.ts
+24
@@ -9,6 +9,7 @@ import {
9
} from "@t3tools/contracts";
10
import * as Effect from "effect/Effect";
11
import { modelSelectionCommandType } from "@t3tools/shared/model";
12
+import { topOfPinnedRunOrderKey } from "@t3tools/shared/pinOrderKey";
13
14
import * as McpInvocationContext from "../../McpInvocationContext.ts";
15
import * as McpToolAccess from "../../McpToolAccess.ts";
@@ -19,6 +20,7 @@ import {
20
readThread,
21
unavailable,
22
} from "../../threadAccess.ts";
23
+import type * as ThreadManagement from "../../../orchestration-v2/ThreadManagementService.ts";
24
import * as ThreadSearch from "../../../orchestration-v2/ThreadSearch.ts";
25
import * as ScheduledTasks from "../../../scheduledTasks/ScheduledTaskService.ts";
26
import { queuedRunsInDeliveryOrder } from "../../../orchestration-v2/QueuedRunOrder.ts";
@@ -50,6 +52,20 @@ const dispatch = Effect.fn("mcp.dispatchThreadCommand")(function* (
52
return { sequence: result.sequence };
53
});
54
55
+/**
56
+ * Places an agent pin at the top of the Pinned section, as a client pin is placed.
57
+ * Without a key the sidebar sorts the pin below every keyed pin. Ordering is
58
+ * best effort: if the index cannot be read, the pin still lands, keyless.
59
+ */
60
+const topOfPinnedRunKey = Effect.fn("mcp.topOfPinnedRunKey")(function* (
61
+ threads: Pick<ThreadManagement.ThreadManagementService["Service"], "listActiveShellIndex">,
62
+) {
63
+ const index = yield* threads.listActiveShellIndex().pipe(Effect.orElseSucceed(() => null));
64
+ if (index === null) return undefined;
65
+ const pinnedKeys = index.flatMap((entry) => (entry.pinnedAt == null ? [] : [entry.pinOrderKey]));
66
+ return topOfPinnedRunOrderKey(pinnedKeys) ?? undefined;
67
+});
68
+
69
const readQuestion = Effect.fn("mcp.readQuestion")(function* (input: {
70
threadId?: ThreadId | undefined;
71
requestId: RuntimeRequestId;
@@ -369,6 +385,14 @@ export const layer = McpToolAccess.toLayer(ThreadToolkit, {
385
case "mark_unread":
386
command = { ...common, type: "thread.mark-unread" };
387
break;
388
+ case "pin": {
389
+ // Always send a key, as the client does: the reducer ignores it for a
390
+ // thread that is already pinned, and a projection read before this
391
+ // command can be stale if an unpin commits in between.
392
+ const orderKey = yield* topOfPinnedRunKey(threads);
393
+ command = { ...common, type: "thread.pin", ...(orderKey ? { orderKey } : {}) };
394
+ break;
395
+ }
396
default:
397
command = { ...common, type: `thread.${input.action}` };
398
}
apps/server/src/orchestration-v2/ProjectionStore.test.ts
+25
-2
@@ -148,7 +148,14 @@ const assertShellIndexCoversShells = Effect.fnUntraced(function* () {
148
const trimmed = (
149
row: Pick<
150
ProjectionStore.ActiveShellIndexEntry,
151
- "id" | "projectId" | "lineage" | "settledOverride" | "settledAt" | "pinnedAt" | "snoozedUntil"
151
+ | "id"
152
+ | "projectId"
153
+ | "lineage"
154
+ | "settledOverride"
155
+ | "settledAt"
156
+ | "pinnedAt"
157
+ | "pinOrderKey"
158
+ | "snoozedUntil"
159
>,
160
) => ({
161
id: row.id,
@@ -157,6 +164,7 @@ const assertShellIndexCoversShells = Effect.fnUntraced(function* () {
164
settledOverride: row.settledOverride,
165
settledAt: iso(row.settledAt),
166
pinnedAt: iso(row.pinnedAt),
167
+ pinOrderKey: row.pinOrderKey ?? null,
168
snoozedUntil: iso(row.snoozedUntil),
169
});
170
assert.deepEqual(index.map(trimmed), shells.map(trimmed));
@@ -2499,13 +2507,28 @@ const backgroundThreadUpdatesKeepTimestamp = Effect.gen(function* () {
2507
assert.deepEqual(reordered.updatedAt, createdAt);
2508
assert.equal(reordered.thread.activeOrderKey, "a");
2509
2510
+ // MCP pins read the stored pin key from the active shell index.
2511
+ yield* store.apply({
2512
+ id: EventId.make("event:background-updates:pinned"),
2513
+ type: "thread.pinned",
2514
+ threadId,
2515
+ occurredAt: DateTime.add(createdAt, { minutes: 52 }),
2516
+ payload: {
2517
+ ...reordered.thread,
2518
+ pinnedAt: DateTime.add(createdAt, { minutes: 52 }),
2519
+ pinOrderKey: "m",
2520
+ },
2521
+ });
2522
+ const pinned = yield* readActivity;
2523
+ yield* assertShellIndexCoversShells();
2524
+
2525
// An already-unpinned thread keeps its activity time even when replay's envelope advances.
2526
yield* store.apply({
2527
id: EventId.make("event:background-updates:already-unpinned"),
2528
type: "thread.unpinned",
2529
threadId,
2530
occurredAt: DateTime.add(createdAt, { minutes: 55 }),
2508
- payload: { ...reordered.thread, pinnedAt: null, pinOrderKey: null },
2531
+ payload: { ...pinned.thread, pinnedAt: null, pinOrderKey: null },
2532
});
2533
yield* readActivity;
2534
});
apps/server/src/orchestration-v2/ProjectionStore.ts
+11
-1
@@ -465,7 +465,14 @@ export interface ShellSnapshotOptions {
465
/** What a shell subscriber's trims read from an active thread, without building its shell. */
466
export interface ActiveShellIndexEntry extends Pick<
467
OrchestrationV2ThreadShell,
468
- "id" | "projectId" | "lineage" | "settledOverride" | "settledAt" | "pinnedAt" | "snoozedUntil"
468
+ | "id"
469
+ | "projectId"
470
+ | "lineage"
471
+ | "settledOverride"
472
+ | "settledAt"
473
+ | "pinnedAt"
474
+ | "pinOrderKey"
475
+ | "snoozedUntil"
476
> {
477
/** False only when no run, request, work item, or watch can make the shell live. */
478
readonly mayBeLive: boolean;
@@ -8930,6 +8937,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
8937
readonly settled_override: string | null;
8938
readonly settled_at: string | null;
8939
readonly pinned_at: string | null;
8940
+ readonly pin_order_key: string | null;
8941
readonly snoozed_until: string | null;
8942
readonly may_be_live: number;
8943
readonly has_remote_tasks: number;
@@ -8944,6 +8952,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
8952
json_extract(t.payload_json, '$.settledOverride') AS settled_override,
8953
json_extract(t.payload_json, '$.settledAt') AS settled_at,
8954
json_extract(t.payload_json, '$.pinnedAt') AS pinned_at,
8955
+ json_extract(t.payload_json, '$.pinOrderKey') AS pin_order_key,
8956
json_extract(t.payload_json, '$.snoozedUntil') AS snoozed_until,
8957
-- A superset of isLiveSubagentShell: the sources of its run status, pending request,
8958
-- and pending background work.
@@ -9002,6 +9011,7 @@ export const layer: Layer.Layer<ProjectionStoreV2, never, SqlClient.SqlClient> =
9011
: null,
9012
settledAt: row.settled_at === null ? null : DateTime.makeUnsafe(row.settled_at),
9013
pinnedAt: row.pinned_at === null ? null : DateTime.makeUnsafe(row.pinned_at),
9014
+ pinOrderKey: row.pin_order_key,
9015
snoozedUntil: row.snoozed_until === null ? null : DateTime.makeUnsafe(row.snoozed_until),
9016
mayBeLive: row.may_be_live === 1,
9017
hasRemoteTasks: row.has_remote_tasks === 1,
packages/client-runtime/src/state/threadSort.ts
+3
-65
@@ -1,7 +1,10 @@
1
import type { ProjectId } from "@t3tools/contracts";
2
import type { SidebarProjectSortOrder, SidebarThreadSortOrder } from "@t3tools/contracts/settings";
3
+import { generateSpreadPinOrderKeys, pinOrderKeyBetween } from "@t3tools/shared/pinOrderKey";
4
import type { EnvironmentThreadShell } from "./models.ts";
5
6
+export { generateSpreadPinOrderKeys, pinOrderKeyBetween } from "@t3tools/shared/pinOrderKey";
7
+
8
export interface ThreadSortInput {
9
readonly createdAt: string;
10
readonly updatedAt: string;
@@ -180,71 +183,6 @@ export function getLatestThreadForProject<
183
return latest;
184
}
185
183
-const PIN_ORDER_DIGITS = "abcdefghijklmnopqrstuvwxyz";
184
-
185
-function isValidPinOrderKey(key: string): boolean {
186
- if (key.length === 0) return false;
187
- for (const char of key) {
188
- if (!PIN_ORDER_DIGITS.includes(char)) return false;
189
- }
190
- // A trailing minimum digit would leave no room to sort a key immediately
191
- // before this one; generators never produce it, so treat it as corrupt.
192
- return key.at(-1) !== PIN_ORDER_DIGITS[0];
193
-}
194
-
195
-/** Midpoint of two digit strings interpreted as fractions in (0, 1).
196
- "" stands for the open bound on either side. Requires a < b. */
197
-function pinOrderMidpoint(a: string, b: string): string {
198
- if (b !== "" && a >= b) throw new Error("pinOrderMidpoint: bounds out of order");
199
- if (b !== "") {
200
- let n = 0;
201
- while ((a.charAt(n) || PIN_ORDER_DIGITS[0]) === b.charAt(n)) n += 1;
202
- if (n > 0) return b.slice(0, n) + pinOrderMidpoint(a.slice(n), b.slice(n));
203
- }
204
- const digitA = a === "" ? 0 : PIN_ORDER_DIGITS.indexOf(a.charAt(0));
205
- const digitB = b === "" ? PIN_ORDER_DIGITS.length : PIN_ORDER_DIGITS.indexOf(b.charAt(0));
206
- if (digitB - digitA > 1) {
207
- return PIN_ORDER_DIGITS.charAt(Math.round((digitA + digitB) / 2));
208
- }
209
- if (b.length > 1) return b.charAt(0);
210
- return PIN_ORDER_DIGITS.charAt(digitA) + pinOrderMidpoint(a.slice(1), "");
211
-}
212
-
213
-/** Key that sorts strictly between two neighbors; null bounds mean "top of
214
- the pinned block" / "bottom of the keyed run". Returns null instead of
215
- throwing when existing keys are corrupt or out of order — callers fall
216
- back to rewriting the section. */
217
-export function pinOrderKeyBetween(before: string | null, after: string | null): string | null {
218
- const a = before ?? "";
219
- const b = after ?? "";
220
- if (a !== "" && !isValidPinOrderKey(a)) return null;
221
- if (b !== "" && !isValidPinOrderKey(b)) return null;
222
- if (b !== "" && a >= b) return null;
223
- return pinOrderMidpoint(a, b);
224
-}
225
-
226
-export function generateSpreadPinOrderKeys(count: number): string[] {
227
- let width = 2;
228
- let space = PIN_ORDER_DIGITS.length ** width;
229
- while (space <= (count + 1) * 2) {
230
- width += 1;
231
- space *= PIN_ORDER_DIGITS.length;
232
- }
233
- const step = space / (count + 1);
234
- const keys: string[] = [];
235
- for (let i = 0; i < count; i += 1) {
236
- let value = Math.round(step * (i + 1));
237
- if (value % PIN_ORDER_DIGITS.length === 0) value += 1;
238
- let key = "";
239
- for (let digit = 0; digit < width; digit += 1) {
240
- key = PIN_ORDER_DIGITS.charAt(value % PIN_ORDER_DIGITS.length) + key;
241
- value = Math.floor(value / PIN_ORDER_DIGITS.length);
242
- }
243
- keys.push(key);
244
- }
245
- return keys;
246
-}
247
-
186
export function planPinnedReorder(input: {
187
readonly orderedIds: readonly string[];
188
/** Include retained keys from hidden rows; only orderedIds receive writes. */
packages/shared/package.json
+4
@@ -578,6 +578,10 @@
578
"./speech": {
579
"types": "./src/speech.ts",
580
"import": "./src/speech.ts"
581
+ },
582
+ "./pinOrderKey": {
583
+ "types": "./src/pinOrderKey.ts",
584
+ "import": "./src/pinOrderKey.ts"
585
}
586
},
587
"scripts": {
packages/shared/src/pinOrderKey.ts
new
+83
@@ -0,0 +1,83 @@
1
+/**
2
+ * Fractional order keys for the sidebar's Pinned section. Keys are lowercase
3
+ * digit strings compared as plain strings; a smaller key sorts higher. Shared
4
+ * so the server places an agent-issued pin the same way a client pin is placed.
5
+ */
6
+const PIN_ORDER_DIGITS = "abcdefghijklmnopqrstuvwxyz";
7
+
8
+function isValidPinOrderKey(key: string): boolean {
9
+ if (key.length === 0) return false;
10
+ for (const char of key) {
11
+ if (!PIN_ORDER_DIGITS.includes(char)) return false;
12
+ }
13
+ // A trailing minimum digit would leave no room to sort a key immediately
14
+ // before this one; generators never produce it, so treat it as corrupt.
15
+ return key.at(-1) !== PIN_ORDER_DIGITS[0];
16
+}
17
+
18
+/** Midpoint of two digit strings interpreted as fractions in (0, 1).
19
+ "" stands for the open bound on either side. Requires a < b. */
20
+function pinOrderMidpoint(a: string, b: string): string {
21
+ if (b !== "" && a >= b) throw new Error("pinOrderMidpoint: bounds out of order");
22
+ if (b !== "") {
23
+ let n = 0;
24
+ while ((a.charAt(n) || PIN_ORDER_DIGITS[0]) === b.charAt(n)) n += 1;
25
+ if (n > 0) return b.slice(0, n) + pinOrderMidpoint(a.slice(n), b.slice(n));
26
+ }
27
+ const digitA = a === "" ? 0 : PIN_ORDER_DIGITS.indexOf(a.charAt(0));
28
+ const digitB = b === "" ? PIN_ORDER_DIGITS.length : PIN_ORDER_DIGITS.indexOf(b.charAt(0));
29
+ if (digitB - digitA > 1) {
30
+ return PIN_ORDER_DIGITS.charAt(Math.round((digitA + digitB) / 2));
31
+ }
32
+ if (b.length > 1) return b.charAt(0);
33
+ return PIN_ORDER_DIGITS.charAt(digitA) + pinOrderMidpoint(a.slice(1), "");
34
+}
35
+
36
+/** Key that sorts strictly between two neighbors; null bounds mean "top of
37
+ the pinned block" / "bottom of the keyed run". Returns null instead of
38
+ throwing when existing keys are corrupt or out of order — callers fall
39
+ back to rewriting the section. */
40
+export function pinOrderKeyBetween(before: string | null, after: string | null): string | null {
41
+ const a = before ?? "";
42
+ const b = after ?? "";
43
+ if (a !== "" && !isValidPinOrderKey(a)) return null;
44
+ if (b !== "" && !isValidPinOrderKey(b)) return null;
45
+ if (b !== "" && a >= b) return null;
46
+ return pinOrderMidpoint(a, b);
47
+}
48
+
49
+/** Key for a newly pinned thread at the top of the pinned run: before the
50
+ smallest existing key, or a fresh key when there is none. Null when the
51
+ smallest key is corrupt; callers then send no key. */
52
+export function topOfPinnedRunOrderKey(
53
+ existingKeys: Iterable<string | null | undefined>,
54
+): string | null {
55
+ let firstKey: string | null = null;
56
+ for (const key of existingKeys) {
57
+ if (key == null) continue;
58
+ if (firstKey === null || key < firstKey) firstKey = key;
59
+ }
60
+ return pinOrderKeyBetween(null, firstKey);
61
+}
62
+
63
+export function generateSpreadPinOrderKeys(count: number): string[] {
64
+ let width = 2;
65
+ let space = PIN_ORDER_DIGITS.length ** width;
66
+ while (space <= (count + 1) * 2) {
67
+ width += 1;
68
+ space *= PIN_ORDER_DIGITS.length;
69
+ }
70
+ const step = space / (count + 1);
71
+ const keys: string[] = [];
72
+ for (let i = 0; i < count; i += 1) {
73
+ let value = Math.round(step * (i + 1));
74
+ if (value % PIN_ORDER_DIGITS.length === 0) value += 1;
75
+ let key = "";
76
+ for (let digit = 0; digit < width; digit += 1) {
77
+ key = PIN_ORDER_DIGITS.charAt(value % PIN_ORDER_DIGITS.length) + key;
78
+ value = Math.floor(value / PIN_ORDER_DIGITS.length);
79
+ }
80
+ keys.push(key);
81
+ }
82
+ return keys;
83
+}