The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 11:00 UTC
fix(server): skills linked by a SessionStart hook appear in the $ picker in the same session (#37165)
Co-authored-by: Julius Marminge <julius0216@outlook.com>
Katya committed
Nov 15, 2026 at 13:23 UTC
dcaedc980034008cdf99fe18340cd3018869f154
11 files changed
+533
-33
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.test.ts
+76
@@ -3550,6 +3550,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3550
> &
3551
Partial<Pick<ClaudeAdapterV2.ClaudeAgentSdkQuerySession, "listPermissionRules">>;
3552
readonly environment?: NodeJS.ProcessEnv;
3553
+ readonly onSessionInit?: (cwd: string) => Effect.Effect<void>;
3554
readonly subagentLaunchToolUseId?: string;
3555
readonly subagentModel?: string;
3556
readonly nativeSessionId?: string;
@@ -3625,6 +3626,7 @@ describe("ClaudeAdapterV2 background wake turns", () => {
3626
path: yield* Path.Path,
3627
random: yield* SecureRandom.SecureRandom,
3628
idAllocator,
3629
+ ...(options?.onSessionInit ? { onSessionInit: options.onSessionInit } : {}),
3630
...(options?.routeModelCatalog ? { routeModelCatalog: options.routeModelCatalog } : {}),
3631
continuationRequests: {
3632
offer: (request) =>
@@ -4167,6 +4169,80 @@ describe("ClaudeAdapterV2 background wake turns", () => {
4169
),
4170
);
4171
4172
+ it.effect("reports the session cwd on each process's first init, not on repeated inits", () =>
4173
+ Effect.gen(function* () {
4174
+ const initCwds: Array<string> = [];
4175
+ const harness = yield* makeWakeHarnessWithOptions({
4176
+ freshQueueOnReopen: true,
4177
+ close: (queue) => Queue.shutdown(queue),
4178
+ onSessionInit: (cwd) =>
4179
+ Effect.sync(() => {
4180
+ initCwds.push(cwd);
4181
+ }),
4182
+ });
4183
+ // The CLI may report a resolved path, not the cwd clients key their snapshots on.
4184
+ const init = (uuid: string) =>
4185
+ claudeSdkFrame({
4186
+ type: "system",
4187
+ subtype: "init",
4188
+ cwd: "/private/workspace",
4189
+ session_id: WAKE_NATIVE_SESSION,
4190
+ uuid,
4191
+ });
4192
+ const latest = (): OrchestrationV2ProviderThread => {
4193
+ const event = harness.events.findLast(
4194
+ (candidate) => candidate.type === "provider_thread.updated",
4195
+ );
4196
+ return event?.type === "provider_thread.updated"
4197
+ ? event.providerThread
4198
+ : harness.providerThread;
4199
+ };
4200
+ const turn = (ordinal: number) =>
4201
+ makeClaudeTestTurnInput({
4202
+ threadId: harness.threadId,
4203
+ providerThread: latest(),
4204
+ now: DateTime.makeUnsafe(0),
4205
+ attemptId: RunAttemptId.make(`session-init-${ordinal}`),
4206
+ text: `Turn ${ordinal}`,
4207
+ attachments: [],
4208
+ providerTurnOrdinal: ordinal,
4209
+ });
4210
+ yield* harness.runtime.startTurn(turn(1));
4211
+ assert.deepEqual(initCwds, []);
4212
+ yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000701"));
4213
+ assert.deepEqual(initCwds, ["/workspace"]);
4214
+ yield* harness.offerAndWait(turnOneResult);
4215
+ yield* Queue.take(harness.terminalReceipts);
4216
+ // The CLI repeats init on every turn of one process; its startup hooks ran once.
4217
+ yield* harness.runtime.startTurn(turn(2));
4218
+ yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000702"));
4219
+ yield* harness.offerAndWait(
4220
+ makeResultFrame({ uuid: "00000000-0000-4000-8000-000000000703", result: "Two." }),
4221
+ );
4222
+ yield* Queue.take(harness.terminalReceipts);
4223
+ assert.deepEqual(initCwds, ["/workspace"]);
4224
+ yield* harness.runtime.interruptTurn({
4225
+ providerThread: latest(),
4226
+ providerTurnId: lastProviderTurn(harness.events).id,
4227
+ requestRuntimeRestart: true,
4228
+ });
4229
+ yield* harness.runtime.startTurn(turn(3));
4230
+ assert.equal(harness.processQueues.length, 2);
4231
+ yield* harness.offerAndWait(init("00000000-0000-4000-8000-000000000704"));
4232
+ assert.deepEqual(initCwds, ["/workspace", "/workspace"]);
4233
+ }).pipe(
4234
+ Effect.scoped,
4235
+ Effect.provide(
4236
+ Layer.mergeAll(
4237
+ IdAllocator.layer,
4238
+ McpProviderSessions.layer,
4239
+ NodeServices.layer,
4240
+ NodeCrypto.layer,
4241
+ ),
4242
+ ),
4243
+ ),
4244
+ );
4245
+
4246
it.effect("resumes the session a /clear selected after the Claude process is replaced", () =>
4247
Effect.gen(function* () {
4248
const harness = yield* makeWakeHarnessWithOptions({
apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts
+14
-2
@@ -5468,6 +5468,11 @@ export interface ClaudeAdapterV2Options {
5468
readonly queryRunner: ClaudeAgentSdkQueryRunnerShape;
5469
readonly scopedLimitNames?: Ref.Ref<ClaudeScopedLimitNames>;
5470
readonly onUsageLimits?: ManagedServerProvider["applyUsageLimits"];
5471
+ /**
5472
+ * Called with the requested cwd on a process's first init message, after its synchronous
5473
+ * SessionStart hooks have run, so cwd-keyed workspace scans can be refreshed.
5474
+ */
5475
+ readonly onSessionInit?: (cwd: string) => Effect.Effect<void>;
5476
/**
5477
* Applies Claude Code's reported model ids for a turn's cwd, so turns send ids its backend
5478
* accepts. Defaults to the catalog unchanged.
@@ -12812,11 +12817,13 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12817
Stream.runForEach((message) =>
12818
sdkMessageLock.withPermits(1)(
12819
Effect.suspend(() => {
12820
+ let firstInit = false;
12821
if (
12822
message.type === "system" &&
12823
message.subtype === "init" &&
12824
!context.receivedInit
12825
) {
12826
+ firstInit = true;
12827
context.openedPermissionMode =
12828
message.permissionMode ?? context.openedPermissionMode;
12829
context.receivedInit = true;
@@ -12855,7 +12862,12 @@ export const makeClaudeAdapterV2 = Effect.fn("makeClaudeAdapterV2")(function* (
12862
resultsReportingNewContextWindow.add(message);
12863
}
12864
}
12858
- return handleSdkMessage({ query: querySession, message });
12865
+ const handled = handleSdkMessage({ query: querySession, message });
12866
+ const reportedCwd = turnInput.runtimePolicy.cwd;
12867
+ if (!firstInit || reportedCwd === null || !adapterOptions.onSessionInit) {
12868
+ return handled;
12869
+ }
12870
+ return adapterOptions.onSessionInit(reportedCwd).pipe(Effect.andThen(handled));
12871
}),
12872
),
12873
),
@@ -14385,7 +14397,7 @@ export const createClaudeAdapterV2 = Effect.fn("ClaudeAdapterV2Driver.create")(
14397
input: ProviderAdapterDriverCreateInput<ClaudeSettings>,
14398
hooks: Pick<
14399
ClaudeAdapterV2Options,
14388
- "scopedLimitNames" | "onUsageLimits" | "modelCatalog" | "routeModelCatalog"
14400
+ "scopedLimitNames" | "onUsageLimits" | "onSessionInit" | "modelCatalog" | "routeModelCatalog"
14401
> = {},
14402
) {
14403
const { instanceId, environment, enabled, config } = input;
apps/server/src/provider/Drivers/ClaudeDriver.ts
+8
@@ -1,13 +1,16 @@
1
import { ClaudeSettings, ProviderDriverKind } from "@t3tools/contracts";
2
import * as Cache from "effect/Cache";
3
+import type * as Cause from "effect/Cause";
4
import * as Duration from "effect/Duration";
5
import * as SecureRandom from "effect/crypto/SecureRandom";
6
import * as Effect from "effect/Effect";
7
import * as Exit from "effect/Exit";
8
import * as FileSystem from "effect/FileSystem";
9
import * as Path from "effect/Path";
10
+import * as Queue from "effect/Queue";
11
import * as Ref from "effect/Ref";
12
import * as Schema from "effect/Schema";
13
+import * as Stream from "effect/Stream";
14
import { HttpClient } from "effect/http";
15
import { ChildProcessSpawner } from "effect/process";
16
@@ -167,6 +170,9 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
170
),
171
stateDir,
172
);
173
+ // Retain reports until the registry subscribes; end its listener on teardown.
174
+ const workspaceRescans = yield* Queue.unbounded<string, Cause.Done>();
175
+ yield* Effect.addFinalizer(() => Queue.end(workspaceRescans));
176
const orchestrationAdapter = yield* createClaudeAdapterV2(
177
{
178
instanceId,
@@ -179,6 +185,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
185
{
186
scopedLimitNames,
187
onUsageLimits: (update) => snapshot.applyUsageLimits(update),
188
+ onSessionInit: (cwd) => Queue.offer(workspaceRescans, cwd).pipe(Effect.asVoid),
189
modelCatalog,
190
routeModelCatalog: modelRoutes.route,
191
},
@@ -412,6 +419,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeSettings, ClaudeDriverEnv, Path.
419
enabled,
420
snapshot,
421
invalidateCaches: Cache.invalidateAll(capabilitiesProbeCache),
422
+ workspaceRescans: Stream.fromQueue(workspaceRescans),
423
snapshotForCwd: (cwd: string) =>
424
snapshot.getSnapshot.pipe(
425
Effect.flatMap((machineSnapshot) =>
apps/server/src/provider/ProviderRegistry.test.ts
+290
@@ -156,6 +156,135 @@ const layerBackgroundPolicyAlwaysRun = Layer.mock(BackgroundPolicy.BackgroundPol
156
shouldRunOpportunisticWork: Effect.succeed(true),
157
});
158
159
+const makeWorkspaceRescanHarness = Effect.gen(function* () {
160
+ const instanceId = ProviderInstanceId.make("claude");
161
+ const driver = ProviderDriverKind.make("claudeCode");
162
+ const provider = {
163
+ instanceId,
164
+ driver,
165
+ status: "ready",
166
+ enabled: true,
167
+ installed: true,
168
+ auth: { status: "authenticated" },
169
+ checkedAt: "1970-01-01T00:00:00.000Z",
170
+ version: "1.0.0",
171
+ models: [],
172
+ slashCommands: [],
173
+ skills: [],
174
+ } as const satisfies ServerProvider;
175
+ const scans = yield* Queue.unbounded<{
176
+ readonly cwd: string;
177
+ readonly result: Deferred.Deferred<ProviderWorkspaceSnapshot>;
178
+ }>();
179
+ const makeInstance = Effect.gen(function* () {
180
+ const rescans = yield* Queue.unbounded<string>();
181
+ const reports = yield* Queue.unbounded<string>();
182
+ const instance: ProviderInstance = {
183
+ instanceId,
184
+ driverKind: driver,
185
+ continuationIdentity: { driverKind: driver, continuationKey: "claude:rescan-test" },
186
+ displayName: undefined,
187
+ enabled: true,
188
+ snapshot: {
189
+ resolveMaintenance: () =>
190
+ Effect.succeed(
191
+ makeManualOnlyProviderMaintenanceCapabilities({
192
+ provider: driver,
193
+ packageName: null,
194
+ }),
195
+ ),
196
+ getSnapshot: Effect.succeed(provider),
197
+ refresh: Effect.succeed(provider),
198
+ streamChanges: Stream.empty,
199
+ applyUsageLimits: () => Effect.void,
200
+ },
201
+ // A pull-based stream pulls the next report only after the registry queued the last.
202
+ workspaceRescans: Stream.fromQueue(rescans).pipe(
203
+ Stream.tap((cwd) => Queue.offer(reports, cwd)),
204
+ ),
205
+ snapshotForCwd: (cwd) =>
206
+ Effect.gen(function* () {
207
+ const result = yield* Deferred.make<ProviderWorkspaceSnapshot>();
208
+ yield* Queue.offer(scans, { cwd, result });
209
+ return yield* Deferred.await(result);
210
+ }),
211
+ orchestrationAdapter: {} as ProviderInstance["orchestrationAdapter"],
212
+ textGeneration: {} as ProviderInstance["textGeneration"],
213
+ };
214
+ return { instance, rescans, reports };
215
+ });
216
+ const first = yield* makeInstance;
217
+ const instances = yield* Ref.make([first.instance]);
218
+ const changes = yield* PubSub.unbounded<void>();
219
+ const scope = yield* Scope.make();
220
+ yield* Effect.addFinalizer(() => Scope.close(scope, Exit.void));
221
+ const services = yield* Layer.build(
222
+ ProviderRegistry.layer.pipe(
223
+ Layer.provide(layerUnusedMutator),
224
+ Layer.provideMerge(
225
+ Layer.succeed(ProviderInstanceRegistry.ProviderInstanceRegistry, {
226
+ getInstance: (id) =>
227
+ Ref.get(instances).pipe(Effect.map((all) => all.find((i) => i.instanceId === id))),
228
+ listInstances: Ref.get(instances),
229
+ listUnavailable: Effect.succeed([]),
230
+ streamChanges: Stream.fromPubSub(changes),
231
+ subscribeChanges: PubSub.subscribe(changes),
232
+ }),
233
+ ),
234
+ Layer.provideMerge(ServerConfig.layerTest(process.cwd(), { prefix: "t3-workspace-rescan-" })),
235
+ Layer.provideMerge(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer)),
236
+ ),
237
+ ).pipe(Scope.provide(scope));
238
+ const registry = yield* ProviderRegistry.ProviderRegistry.pipe(Effect.provide(services));
239
+ const snapshot = (name: string): ProviderWorkspaceSnapshot => ({
240
+ ...provider,
241
+ skills: [{ name, path: `/workspace/${name}/SKILL.md`, enabled: true }],
242
+ });
243
+ const nextScan = Effect.fnUntraced(function* (cwd: string) {
244
+ const scan = yield* Queue.take(scans);
245
+ assert.equal(scan.cwd, cwd);
246
+ return (name: string) => Deferred.succeed(scan.result, snapshot(name));
247
+ });
248
+ const refresh = (cwd: string, fresh = false) =>
249
+ registry.refreshWorkspaceSnapshot({ instanceId, cwd, fresh });
250
+ const seed = Effect.fnUntraced(function* (cwd: string) {
251
+ const pending = yield* refresh(cwd).pipe(Effect.forkChild);
252
+ const complete = yield* nextScan(cwd);
253
+ yield* complete("initial");
254
+ yield* Fiber.join(pending);
255
+ });
256
+ // A later requested cwd reaching the serial consumer proves the previous rescan settled,
257
+ // including when that rescan correctly publishes no change. Seed "/barrier" first; it rescans
258
+ // to the skills it was seeded with, so it never stamps workspaceRescannedAt.
259
+ const drainRescans = Effect.gen(function* () {
260
+ yield* Queue.offer(first.rescans, "/barrier");
261
+ const complete = yield* nextScan("/barrier");
262
+ yield* complete("initial");
263
+ });
264
+ const skillsOf = (cwd: string) =>
265
+ Effect.map(registry.getProviders, (providers) =>
266
+ providers[0]?.workspaceSnapshots?.find((s) => s.cwd === cwd)?.skills?.map((s) => s.name),
267
+ );
268
+ const rescannedAtOf = Effect.map(
269
+ registry.getProviders,
270
+ (providers) => providers[0]?.workspaceRescannedAt,
271
+ );
272
+ return {
273
+ first,
274
+ makeInstance,
275
+ instances,
276
+ changes,
277
+ registry,
278
+ scans,
279
+ nextScan,
280
+ refresh,
281
+ seed,
282
+ drainRescans,
283
+ skillsOf,
284
+ rescannedAtOf,
285
+ };
286
+});
287
+
288
function selectDescriptor(
289
id: string,
290
label: string,
@@ -931,6 +1060,20 @@ it.layer(
1060
unchanged.workspaceSnapshots?.map((snapshot) => snapshot.cwd),
1061
["/project", "/plain"],
1062
);
1063
+ // A machine health refresh must not read as a rescan, nor erase the last one.
1064
+ const rescanned = { ...withCatalog, workspaceRescannedAt: "2026-03-25T00:01:00.000Z" };
1065
+ assert.equal(
1066
+ ProviderRegistry.mergeProviderSnapshot(rescanned, provider).workspaceRescannedAt,
1067
+ "2026-03-25T00:01:00.000Z",
1068
+ );
1069
+ assert.equal(
1070
+ ProviderRegistry.mergeProviderSnapshot(rescanned, {
1071
+ ...provider,
1072
+ workspaceRescannedAt: "2026-03-25T00:02:00.000Z",
1073
+ }).workspaceRescannedAt,
1074
+ "2026-03-25T00:02:00.000Z",
1075
+ );
1076
+ assert.equal(unchanged.workspaceRescannedAt, undefined);
1077
const changed = ProviderRegistry.mergeProviderSnapshot(withCatalog, {
1078
...provider,
1079
models: [machineModel, addedModel],
@@ -2285,6 +2428,153 @@ it.layer(
2428
}),
2429
);
2430
2431
+ it.effect("rescans a requested cwd whose snapshot is still current", () =>
2432
+ Effect.gen(function* () {
2433
+ const h = yield* makeWorkspaceRescanHarness;
2434
+ yield* h.seed("/barrier");
2435
+ yield* h.seed("/workspace");
2436
+ assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]);
2437
+ yield* Queue.offer(h.first.rescans, "/workspace");
2438
+ const complete = yield* h.nextScan("/workspace");
2439
+ yield* complete("hook");
2440
+ yield* h.drainRescans;
2441
+ assert.deepEqual(yield* h.skillsOf("/workspace"), ["hook"]);
2442
+ // Clients that fetched the old skills are told to fetch again.
2443
+ const scannedAt = (yield* h.registry.getProviders)[0]?.workspaceSnapshots?.find(
2444
+ (snapshot) => snapshot.cwd === "/workspace",
2445
+ )?.checkedAt;
2446
+ assert.isString(scannedAt);
2447
+ assert.equal(yield* h.rescannedAtOf, scannedAt);
2448
+ }),
2449
+ );
2450
+
2451
+ it.effect("stamps a rescan whose awaited scan already published the change", () =>
2452
+ Effect.gen(function* () {
2453
+ const h = yield* makeWorkspaceRescanHarness;
2454
+ yield* h.seed("/barrier");
2455
+ yield* h.seed("/workspace");
2456
+ const ordinary = yield* h.refresh("/workspace", true).pipe(Effect.forkChild);
2457
+ const completeOrdinary = yield* h.nextScan("/workspace");
2458
+ yield* Queue.offer(h.first.rescans, "/workspace");
2459
+ yield* Queue.take(h.first.reports);
2460
+ // Let the consumer reach its wait on the running scan.
2461
+ yield* TestClock.adjust(0);
2462
+ yield* completeOrdinary("hook");
2463
+ yield* Fiber.join(ordinary);
2464
+ const completeRescan = yield* h.nextScan("/workspace");
2465
+ yield* completeRescan("hook");
2466
+ yield* h.drainRescans;
2467
+ assert.isString(yield* h.rescannedAtOf);
2468
+ }),
2469
+ );
2470
+
2471
+ it.effect("leaves workspaceRescannedAt unset when a rescan changes nothing", () =>
2472
+ Effect.gen(function* () {
2473
+ const h = yield* makeWorkspaceRescanHarness;
2474
+ yield* h.seed("/barrier");
2475
+ yield* h.seed("/workspace");
2476
+ yield* Queue.offer(h.first.rescans, "/workspace");
2477
+ const complete = yield* h.nextScan("/workspace");
2478
+ yield* complete("initial");
2479
+ yield* h.drainRescans;
2480
+ assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]);
2481
+ assert.equal(yield* h.rescannedAtOf, undefined);
2482
+ }),
2483
+ );
2484
+
2485
+ it.effect("starts no scan for a reported cwd nobody requested", () =>
2486
+ Effect.gen(function* () {
2487
+ const h = yield* makeWorkspaceRescanHarness;
2488
+ yield* h.seed("/barrier");
2489
+ yield* Queue.offer(h.first.rescans, "/unrequested");
2490
+ // The next scan being the barrier's shows the report started none.
2491
+ yield* h.drainRescans;
2492
+ assert.deepEqual(yield* h.skillsOf("/unrequested"), undefined);
2493
+ }),
2494
+ );
2495
+
2496
+ it.effect("rescans after an initial scan in flight when the hook report arrives", () =>
2497
+ Effect.gen(function* () {
2498
+ const h = yield* makeWorkspaceRescanHarness;
2499
+ yield* h.seed("/barrier");
2500
+ const initial = yield* h.refresh("/workspace").pipe(Effect.forkChild);
2501
+ const completeInitial = yield* h.nextScan("/workspace");
2502
+ yield* Queue.offer(h.first.rescans, "/workspace");
2503
+ yield* Queue.take(h.first.reports);
2504
+ // Let the consumer reach its wait on the running scan.
2505
+ yield* TestClock.adjust(0);
2506
+ yield* completeInitial("initial");
2507
+ // The requesting client's reply is its only copy of the scan, so the rescan must not
2508
+ // supersede it.
2509
+ const reply = yield* Fiber.join(initial);
2510
+ assert.deepEqual(
2511
+ reply[0]?.workspaceSnapshots
2512
+ ?.find((s) => s.cwd === "/workspace")
2513
+ ?.skills?.map((s) => s.name),
2514
+ ["initial"],
2515
+ );
2516
+ const completeRescan = yield* h.nextScan("/workspace");
2517
+ yield* completeRescan("hook");
2518
+ yield* h.drainRescans;
2519
+ assert.deepEqual(yield* h.skillsOf("/workspace"), ["hook"]);
2520
+ }),
2521
+ );
2522
+
2523
+ it.effect("lets a fresh refresh started while a rescan waits keep its own result", () =>
2524
+ Effect.gen(function* () {
2525
+ const h = yield* makeWorkspaceRescanHarness;
2526
+ yield* h.seed("/barrier");
2527
+ const initial = yield* h.refresh("/workspace").pipe(Effect.forkChild);
2528
+ const completeInitial = yield* h.nextScan("/workspace");
2529
+ yield* Queue.offer(h.first.rescans, "/workspace");
2530
+ yield* Queue.take(h.first.reports);
2531
+ // Let the consumer reach its wait on the running scan.
2532
+ yield* TestClock.adjust(0);
2533
+ const fresh = yield* h.refresh("/workspace", true).pipe(Effect.forkChild);
2534
+ const completeFresh = yield* h.nextScan("/workspace");
2535
+ yield* completeInitial("initial");
2536
+ yield* completeFresh("fresh");
2537
+ yield* Fiber.join(initial);
2538
+ const reply = yield* Fiber.join(fresh);
2539
+ assert.deepEqual(
2540
+ reply[0]?.workspaceSnapshots
2541
+ ?.find((s) => s.cwd === "/workspace")
2542
+ ?.skills?.map((s) => s.name),
2543
+ ["fresh"],
2544
+ );
2545
+ // The rescan joins the fresh scan, so the next scan started is the barrier's.
2546
+ yield* h.drainRescans;
2547
+ assert.deepEqual(yield* h.skillsOf("/workspace"), ["fresh"]);
2548
+ }),
2549
+ );
2550
+
2551
+ it.effect("ignores a queued rescan from a replaced instance", () =>
2552
+ Effect.gen(function* () {
2553
+ const h = yield* makeWorkspaceRescanHarness;
2554
+ yield* h.seed("/workspace");
2555
+ const replacement = yield* h.makeInstance;
2556
+ const rebuilt = yield* h.registry.streamChanges.pipe(
2557
+ Stream.filter((providers) => providers[0]?.workspaceSnapshots === undefined),
2558
+ Stream.runHead,
2559
+ Effect.forkChild({ startImmediately: true }),
2560
+ );
2561
+ yield* Ref.set(h.instances, [replacement.instance]);
2562
+ yield* PubSub.publish(h.changes, undefined);
2563
+ yield* Fiber.join(rebuilt);
2564
+ yield* h.seed("/workspace");
2565
+ yield* h.seed("/barrier");
2566
+ // The forwarder pulls the second report only after queueing the first.
2567
+ yield* Queue.offerAll(h.first.rescans, ["/workspace", "/workspace"]);
2568
+ yield* Queue.take(h.first.reports);
2569
+ yield* Queue.take(h.first.reports);
2570
+ yield* Queue.offer(replacement.rescans, "/barrier");
2571
+ // A scan started for the stale report would come before the barrier's.
2572
+ const completeBarrier = yield* h.nextScan("/barrier");
2573
+ yield* completeBarrier("barrier");
2574
+ assert.deepEqual(yield* h.skillsOf("/workspace"), ["initial"]);
2575
+ }),
2576
+ );
2577
+
2578
it.effect("scans scanCwd and keys the workspace snapshot by cwd", () =>
2579
Effect.gen(function* () {
2580
const driver = ProviderDriverKind.make("codex");
apps/server/src/provider/ProviderRegistry.ts
+72
-15
@@ -20,6 +20,7 @@ import * as Layer from "effect/Layer";
20
import * as Option from "effect/Option";
21
import * as Path from "effect/Path";
22
import * as PubSub from "effect/PubSub";
23
+import * as Queue from "effect/Queue";
24
import * as Ref from "effect/Ref";
25
import * as Scope from "effect/Scope";
26
import * as Stream from "effect/Stream";
@@ -329,6 +330,10 @@ export const mergeProviderSnapshot = (
330
: previousWorkspaceSnapshots !== undefined
331
? { workspaceSnapshots: previousWorkspaceSnapshots }
332
: {}),
333
+ ...(nextProvider.workspaceRescannedAt === undefined &&
334
+ previousProvider.workspaceRescannedAt !== undefined
335
+ ? { workspaceRescannedAt: previousProvider.workspaceRescannedAt }
336
+ : {}),
337
...(shouldRetainMissingOpenCodeMetadata(nextProvider)
338
? {
339
slashCommands:
@@ -481,6 +486,10 @@ export const layer = Layer.effect(
486
const workspaceRefreshesRef = yield* Ref.make<
487
ReadonlyMap<ProviderInstance, ReadonlyMap<string, Deferred.Deferred<void>>>
488
>(new Map());
489
+ const workspaceRescans = yield* Queue.unbounded<{
490
+ readonly instance: ProviderInstance;
491
+ readonly cwd: string;
492
+ }>();
493
const maintenanceActionStatesRef = yield* Ref.make<
494
ReadonlyMap<
495
ProviderInstanceId,
@@ -501,7 +510,11 @@ export const layer = Layer.effect(
510
cacheDir: config.providerStatusCacheDir,
511
instanceId: key,
512
}).pipe(Effect.provideService(Path.Path, path));
504
- const { workspaceSnapshots: _workspaceSnapshots, ...machineProvider } = provider;
513
+ const {
514
+ workspaceSnapshots: _workspaceSnapshots,
515
+ workspaceRescannedAt: _workspaceRescannedAt,
516
+ ...machineProvider
517
+ } = provider;
518
yield* writeProviderStatusCache({ filePath, provider: machineProvider }).pipe(
519
Effect.provideService(FileSystem.FileSystem, fileSystem),
520
Effect.provideService(Path.Path, path),
@@ -927,6 +940,11 @@ export const layer = Layer.effect(
940
yield* Stream.runForEach(source.streamChanges, (provider) =>
941
correlateSnapshotWithSource(source, provider).pipe(Effect.flatMap(syncProvider)),
942
).pipe(Effect.forkScoped);
943
+ if (instance.workspaceRescans) {
944
+ yield* Stream.runForEach(instance.workspaceRescans, (cwd) =>
945
+ Queue.offer(workspaceRescans, { instance, cwd }),
946
+ ).pipe(Effect.forkScoped);
947
+ }
948
}
949
yield* Effect.yieldNow;
950
@@ -1043,7 +1061,25 @@ export const layer = Layer.effect(
1061
readonly cwd: string;
1062
readonly scanCwd?: string;
1063
readonly fresh?: boolean;
1064
+ // Set by an instance's own report that its workspace skills changed.
1065
+ readonly rescan?: ProviderInstance;
1066
}) {
1067
+ const workspaceSnapshotOf = (candidate: ServerProvider | undefined) =>
1068
+ candidate?.workspaceSnapshots?.find((s) => s.cwd === input.cwd);
1069
+ // What clients saw before the awaited scan, which may already have published the change.
1070
+ const heldBeforeWait = input.rescan
1071
+ ? workspaceSnapshotOf(
1072
+ (yield* Ref.get(providersRef)).find(
1073
+ (candidate) => candidate.instanceId === input.instanceId,
1074
+ ),
1075
+ )
1076
+ : undefined;
1077
+ // A rescan waits for a running scan, which may have read files before the hook linked them.
1078
+ // Claims are read before snapshots: a scan publishes before it releases its claim.
1079
+ const runningScan = input.rescan
1080
+ ? (yield* Ref.get(workspaceRefreshesRef)).get(input.rescan)?.get(input.cwd)
1081
+ : undefined;
1082
+ if (runningScan) yield* Deferred.await(runningScan);
1083
if (input.fresh) {
1084
yield* updateProviders((providers) =>
1085
providers.map((candidate) =>
@@ -1055,14 +1091,13 @@ export const layer = Layer.effect(
1091
}
1092
const providers = yield* Ref.get(providersRef);
1093
const provider = providers.find((candidate) => candidate.instanceId === input.instanceId);
1058
- const workspaceSnapshotOf = (candidate: ServerProvider | undefined) =>
1059
- candidate?.workspaceSnapshots?.find((s) => s.cwd === input.cwd);
1094
const scannedFrom = workspaceSnapshotOf(provider);
1095
const now = yield* DateTime.now;
1096
if (
1097
!provider ||
1098
!provider.enabled ||
1099
(!input.fresh &&
1100
+ !input.rescan &&
1101
scannedFrom &&
1102
!isProviderWorkspaceSnapshotPending(scannedFrom) &&
1103
isProviderWorkspaceSnapshotCurrent(scannedFrom, DateTime.toEpochMillis(now)))
@@ -1074,6 +1109,10 @@ export const layer = Layer.effect(
1109
const instance = yield* instanceRegistry.getInstance(input.instanceId);
1110
const snapshotForCwd = instance?.snapshotForCwd;
1111
if (!instance || !snapshotForCwd) return providers;
1112
+ // A report never enrolls a cwd nobody requested, nor outlives the instance that made it.
1113
+ if (input.rescan && (input.rescan !== instance || (!runningScan && !scannedFrom))) {
1114
+ return providers;
1115
+ }
1116
const token = yield* Deferred.make<void>();
1117
// A machine refresh can change this cwd's snapshot, so the scan publishes against the result.
1118
const refreshMachineSnapshot = input.fresh
@@ -1104,18 +1143,31 @@ export const layer = Layer.effect(
1143
if (Ref.getUnsafe(workspaceRefreshesRef).get(instance)?.get(input.cwd) !== token) {
1144
return currentProviders;
1145
}
1107
- return currentProviders.map((candidate) =>
1108
- candidate.instanceId === input.instanceId &&
1109
- Equal.equals(workspaceSnapshotOf(candidate), scanBase)
1110
- ? upsertProviderWorkspaceSnapshot(candidate, input.cwd, {
1111
- ...scopedSnapshot,
1112
- checkedAt: scannedAt,
1113
- // Without driver command discovery, retain previous commands after failed health checks and retry.
1114
- slashCommandsPending:
1115
- scopedSnapshot.slashCommandsPending ?? scopedSnapshot.status === "error",
1116
- })
1117
- : candidate,
1118
- );
1146
+ return currentProviders.map((candidate) => {
1147
+ if (
1148
+ candidate.instanceId !== input.instanceId ||
1149
+ !Equal.equals(workspaceSnapshotOf(candidate), scanBase)
1150
+ ) {
1151
+ return candidate;
1152
+ }
1153
+ const scanned = upsertProviderWorkspaceSnapshot(candidate, input.cwd, {
1154
+ ...scopedSnapshot,
1155
+ checkedAt: scannedAt,
1156
+ // Without driver command discovery, retain previous commands after failed health checks and retry.
1157
+ slashCommandsPending:
1158
+ scopedSnapshot.slashCommandsPending ?? scopedSnapshot.status === "error",
1159
+ });
1160
+ // Clients keep fetched snapshots, so a changed rescan must tell them to fetch again.
1161
+ const rescanned = workspaceSnapshotOf(scanned);
1162
+ const held = heldBeforeWait ?? scanBase;
1163
+ return input.rescan &&
1164
+ !(
1165
+ Equal.equals(rescanned?.skills, held?.skills) &&
1166
+ Equal.equals(rescanned?.slashCommands, held?.slashCommands)
1167
+ )
1168
+ ? { ...scanned, workspaceRescannedAt: scannedAt }
1169
+ : scanned;
1170
+ });
1171
});
1172
}),
1173
),
@@ -1158,6 +1210,11 @@ export const layer = Layer.effect(
1210
}
1211
return yield* Fiber.join(claim.scan);
1212
});
1213
+ yield* Stream.runForEach(Stream.fromQueue(workspaceRescans), ({ instance, cwd }) =>
1214
+ refreshWorkspaceSnapshot({ instanceId: instance.instanceId, cwd, rescan: instance }).pipe(
1215
+ Effect.ignoreCause({ log: true }),
1216
+ ),
1217
+ ).pipe(Effect.forkScoped);
1218
1219
const invalidateModelCaches = Effect.fn("ProviderRegistry.invalidateModelCaches")(function* (
1220
input: Parameters<ProviderRegistry["Service"]["invalidateModelCaches"]>[0],
packages/client-runtime/src/providerSkills.test.ts
+29
-6
@@ -176,16 +176,25 @@ describe("provider workspace snapshot refresh atom", () => {
176
| null
177
| Promise<ReadonlyArray<ServerProvider> | null>;
178
179
- function setup(initialProviders: ReadonlyArray<ServerProvider>, initialResponses?: Response[]) {
179
+ function setup(
180
+ initialProviders: ReadonlyArray<ServerProvider>,
181
+ initialResponses?: Response[],
182
+ // The client drops a reply whose provider changed while it was in flight.
183
+ options?: { readonly droppedReplies?: number },
184
+ ) {
185
+ let droppedReplies = options?.droppedReplies ?? 0;
186
const providersAtom = Atom.make<ReadonlyArray<ServerProvider> | null>(initialProviders);
187
const responses: Response[] = [...(initialResponses ?? [])];
188
const run = vi.fn(async () => {
189
const providers = await (responses.shift() ?? (() => null))();
184
- return providers === null
185
- ? AsyncResult.failure<{ providers: ReadonlyArray<ServerProvider> }, string>(
186
- Cause.fail("offline"),
187
- )
188
- : AsyncResult.success({ providers });
190
+ if (providers === null) {
191
+ return AsyncResult.failure<{ providers: ReadonlyArray<ServerProvider> }, string>(
192
+ Cause.fail("offline"),
193
+ );
194
+ }
195
+ if (droppedReplies > 0) droppedReplies -= 1;
196
+ else registry.set(providersAtom, providers);
197
+ return AsyncResult.success({ providers });
198
});
199
const family = createProviderWorkspaceSnapshotRefreshAtomFamily({
200
providers: () => providersAtom,
@@ -243,6 +252,20 @@ describe("provider workspace snapshot refresh atom", () => {
252
},
253
);
254
255
+ it("asks again at once when the client dropped a complete reply", async () => {
256
+ vi.useFakeTimers({ now: Date.parse("2026-01-01T00:00:00.000Z") });
257
+ const scanned = withSnapshot("2026-01-01T00:00:00.000Z");
258
+ const { registry, atom, run, unmount } = setup(noSnapshot, [() => scanned, () => scanned], {
259
+ droppedReplies: 1,
260
+ });
261
+ await vi.advanceTimersByTimeAsync(0);
262
+ expect(run).toHaveBeenCalledTimes(2);
263
+ expect(isProviderWorkspaceSnapshotScanning(registry.get(atom))).toBe(false);
264
+ registry.refresh(atom);
265
+ expect(run).toHaveBeenCalledTimes(2);
266
+ unmount();
267
+ });
268
+
269
it("keeps the TTL guard for a newly scanned catalog when the client clock is ahead", async () => {
270
vi.useFakeTimers({ now: Date.parse("2026-01-01T01:00:00.000Z") });
271
const { registry, atom, run, unmount } = setup(withSnapshot("2026-01-01T00:00:00.000Z"), [
packages/client-runtime/src/providerSkills.ts
+10
-4
@@ -235,6 +235,7 @@ function failProviderWorkspaceSnapshotRefresh(
235
state: ProviderWorkspaceSnapshotRefreshState,
236
requestedAt: number,
237
now: number,
238
+ cooldownMs = WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
239
): ProviderWorkspaceSnapshotRefreshState {
240
// A newer request, or a snapshot loss, already superseded this one.
241
if (state.requestedAt !== requestedAt) return state;
@@ -243,7 +244,7 @@ function failProviderWorkspaceSnapshotRefresh(
244
return {
245
...state,
246
requestedAt: null,
246
- retryNotBefore: now + WORKSPACE_SNAPSHOT_RETRY_COOLDOWN_MS,
247
+ retryNotBefore: cooldownMs === 0 ? null : now + cooldownMs,
248
failedAttempts,
249
};
250
}
@@ -335,14 +336,15 @@ export function createProviderWorkspaceSnapshotRefreshAtomFamily(input: {
336
// Outlives this build on purpose: a rebuild must not drop the retry.
337
// Once nothing subscribes, the retry state dies with the node; writing
338
// would recreate and rebuild it, which scans again with no subscriber.
338
- const retryLater = () => {
339
+ const retry = (cooldownMs?: number) => {
340
const node = registry.getNodes().get(refreshAtom);
341
if (node === undefined || node.canBeRemoved) return;
342
registry.set(refreshAtom, (state) =>
343
// @effect-diagnostics-next-line globalDate:off
343
- failProviderWorkspaceSnapshotRefresh(state, now, Date.now()),
344
+ failProviderWorkspaceSnapshotRefresh(state, now, Date.now(), cooldownMs),
345
);
346
};
347
+ const retryLater = () => retry();
348
void runAtomCommand(
349
registry,
350
input.refreshProviders,
@@ -361,7 +363,11 @@ export function createProviderWorkspaceSnapshotRefreshAtomFamily(input: {
363
(hasCurrentProviderWorkspaceSnapshot(refreshedProvider, cwd, completedAt) ||
364
snapshot?.checkedAt !==
365
(provider && resolveProviderWorkspaceSnapshot(provider, cwd))?.checkedAt);
364
- if (!refreshed) retryLater();
366
+ if (!refreshed) return retryLater();
367
+ // A reply is dropped when the provider changed while it was in flight, such as a
368
+ // SessionStart rescan; ask again at once for the snapshot that change produced.
369
+ const held = findProvider(registry.get(input.providers(environmentId)));
370
+ if (!hasCompleteProviderWorkspaceSnapshot(held, cwd)) retry(0);
371
}, retryLater);
372
return plan.state;
373
},
packages/client-runtime/src/state/server.test.ts
+10
@@ -1286,6 +1286,16 @@ describe("server state projection", () => {
1286
).providers[0]?.workspaceSnapshots,
1287
).toBeUndefined();
1288
1289
+ // A server rescan that changed the skills retires the snapshot fetched before it.
1290
+ expect(
1291
+ withFetchedWorkspaceSnapshots(
1292
+ configWith(true, [
1293
+ { ...provider(claude), workspaceRescannedAt: "2026-10-25T00:09:00.000Z" },
1294
+ ] as unknown as ServerConfig["providers"]),
1295
+ fetched,
1296
+ ).providers[0]?.workspaceSnapshots,
1297
+ ).toBeUndefined();
1298
+
1299
// A catalog digest stands for the lists: loading them keeps the snapshot, a new digest retires it.
1300
const digested = (catalogDigest: string, slashCommands: ReadonlyArray<{ name: string }> = []) =>
1301
({ ...provider(claude, undefined, slashCommands), catalogDigest }) as ReturnType<
packages/client-runtime/src/state/server.ts
+13
-6
@@ -747,8 +747,9 @@ export function resolveServerConfigValue(
747
}
748
749
/**
750
- * The provider-wide fields a workspace snapshot builds on. A live session, a sign-out, or a
751
- * /usage-limits change shows up here, so a snapshot fetched before it no longer applies.
750
+ * The provider-wide fields a workspace snapshot builds on. A live session, a sign-out, a
751
+ * /usage-limits change, or a server rescan that changed the skills shows up here, so a snapshot
752
+ * fetched before it no longer applies.
753
*/
754
const snapshotBasis = (provider: ServerProviderEntry | undefined) =>
755
provider && {
@@ -758,6 +759,9 @@ const snapshotBasis = (provider: ServerProviderEntry | undefined) =>
759
...(provider.catalogDigest === undefined
760
? { slashCommands: provider.slashCommands, skills: provider.skills }
761
: { catalogDigest: provider.catalogDigest }),
762
+ ...(provider.workspaceRescannedAt === undefined
763
+ ? {}
764
+ : { workspaceRescannedAt: provider.workspaceRescannedAt }),
765
};
766
767
interface FetchedWorkspaceSnapshot {
@@ -1582,6 +1586,11 @@ export function createServerEnvironmentAtoms<R, E>(
1586
refreshProviders: createEnvironmentRpcCommand(runtime, {
1587
label: "environment-data:server:refresh-providers",
1588
tag: WS_METHODS.serverRefreshProviders,
1589
+ // A rescan during the request must leave the stored basis behind the new stamp.
1590
+ onStart: ({ environmentId, input }, registry) =>
1591
+ registry
1592
+ .get(configValueAtom(environmentId))
1593
+ ?.providers.find((provider) => provider.instanceId === input.instanceId),
1594
execute: (input, registry, environmentId) => {
1595
const { instanceId, cwd } = input;
1596
const provider =
@@ -1603,7 +1612,7 @@ export function createServerEnvironmentAtoms<R, E>(
1612
: {}),
1613
});
1614
},
1606
- onSuccess: ({ environmentId, input }, registry, result) =>
1615
+ onSuccess: ({ environmentId, input }, registry, result, startedProvider) =>
1616
Effect.sync(() => {
1617
const { instanceId, cwd } = input;
1618
if (instanceId === undefined || cwd === undefined) return;
@@ -1625,9 +1634,7 @@ export function createServerEnvironmentAtoms<R, E>(
1634
current,
1635
{ instanceId, cwd, fresh: input.fresh === true },
1636
result.providers,
1628
- registry
1629
- .get(configValueAtom(environmentId))
1630
- ?.providers.find((provider) => provider.instanceId === instanceId),
1637
+ startedProvider,
1638
),
1639
);
1640
}),
packages/contracts/src/server.ts
+5
@@ -276,6 +276,11 @@ export const ServerProvider = Schema.Struct({
276
),
277
skills: Schema.Array(ServerProviderSkill).pipe(Schema.withDecodingDefault(Effect.succeed([]))),
278
workspaceSnapshots: Schema.optionalKey(Schema.Array(ServerProviderWorkspaceSnapshot)),
279
+ /**
280
+ * Set when the server rescanned a workspace after a session start and its skills or commands
281
+ * changed. Clients holding fetched workspace snapshots for this provider fetch them again.
282
+ */
283
+ workspaceRescannedAt: Schema.optionalKey(IsoDateTime),
284
usageLimits: Schema.optional(ServerProviderUsageLimits),
285
versionAdvisory: Schema.optionalKey(ServerProviderVersionAdvisory),
286
compatibilityAdvisory: Schema.optionalKey(ServerProviderCompatibilityAdvisory),
packages/provider-core/src/server/driver.ts
+6
@@ -14,6 +14,7 @@ import type {
14
import type * as Effect from "effect/Effect";
15
import type * as Schema from "effect/Schema";
16
import type * as Scope from "effect/Scope";
17
+import type * as Stream from "effect/Stream";
18
19
import type * as ProviderAdapter from "./ProviderAdapter.ts";
20
import type { ProviderAuthController } from "./auth.ts";
@@ -48,6 +49,11 @@ export interface ProviderInstance {
49
readonly snapshotForCwd?: (
50
cwd: string,
51
) => Effect.Effect<ProviderWorkspaceSnapshot, ProviderDriverError>;
52
+ /**
53
+ * Cwds whose workspace skills may have changed. The registry rescans only cwds already
54
+ * requested. The stream must end when the instance is torn down.
55
+ */
56
+ readonly workspaceRescans?: Stream.Stream<string>;
57
readonly refreshModels?: () => Effect.Effect<void, ProviderDriverError>;
58
readonly invalidateCaches?: Effect.Effect<void>;
59
/** Moves a long-lived service onto a newly updated binary before its version is read back. */