From affd4bff0a361489a23bbe608a4d03fe15a14db8 Mon Sep 17 00:00:00 2001 From: Ben Davis <45952064+bmdavis419@users.noreply.github.com> Date: Tue, 28 Jul 2026 00:11:12 -0700 Subject: [PATCH] =?UTF-8?q?fix:=20final=20review-triage=20batch=20?= =?UTF-8?q?=E2=80=94=20five=20real=20findings,=20eight=20dispositioned?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fixed (all verified against current code, tests falsified where testable): - homeThreads.persistHomeThreadId: two racing creators each persisted their own id and returned different Home threads. Now a compare-and-set against the designation the caller read — not never-overwrite, because the self-healing path legitimately replaces a stale designation. - HermesGatewayBroker.createEnrollment: when the instance vanished mid-enrollment the skipped settings write still minted and returned a token whose `hermes t3 connect` could never authenticate. Committed settings are now inspected after the write (the renameInstance / removeInstance pattern) and enrollment fails instance-not-found. - HermesAdapter.stopAll: only ProviderAdapterRequestError was caught, so a session exiting mid-sweep aborted every remaining session's stop. SessionNotFound is now a no-op — an exited session needs no stop. - ProviderModelPicker: `modelPicker.toggle` on a Home thread armed the scroll-lock effect with no popover rendered, locking page scroll with nothing to dismiss. The static branch forces the menu closed. - mobile NewTaskDraftScreen: the picker-fallback guard read the filtered workspace list, so an agent-only environment sat on "Loading task" forever. It now reads the pre-filter list. Skipped with evidence (NOT-REAL unless noted): homeThreads empty-patch (caller re-reads; failing is worse), correlator sweep-vs-timeout (only per-request timeout is 6s ping vs 90s maxAge), duplicate requestId (UUIDv4/monotonic — no reachable collision), both ProviderService lifecycle overwrites (reconcile closes the old scope before building the replacement; adapter context guard drops stale frames), revokeInstance ordering (mooted by 3bc3f45bf per Macroscope itself), pendingApprovals optimistic delete and ingestion fallback attribution (documented deliberate designs; NOT-WORTH-IT). Co-Authored-By: Claude Fable 5 --- .../features/threads/NewTaskDraftScreen.tsx | 8 +- .../src/orchestration/homeThreads.test.ts | 82 +++++++++++++++++-- apps/server/src/orchestration/homeThreads.ts | 23 +++++- .../src/provider/Layers/HermesAdapter.test.ts | 66 ++++++++++++++- .../src/provider/Layers/HermesAdapter.ts | 5 ++ .../Layers/HermesGatewayBroker.test.ts | 29 +++++++ .../provider/Layers/HermesGatewayBroker.ts | 17 +++- .../components/chat/ProviderModelPicker.tsx | 6 +- 8 files changed, 225 insertions(+), 11 deletions(-) diff --git a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx index abebd95574..b4fbcb549b 100644 --- a/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx +++ b/apps/mobile/src/features/threads/NewTaskDraftScreen.tsx @@ -270,7 +270,12 @@ export function NewTaskDraftScreen(props: { return; } - if (projects.length > 0) { + // Guard on the *unfiltered* catalog. `projects` drops synthetic agent + // projects, so an agent-only environment is indistinguishable from a + // catalog that has not loaded yet — and a route pointing at an agent + // project then found no directProject, skipped this branch, and left the + // screen on "Loading task" with nothing left to resolve it. + if (allProjects.length > 0) { // Never fall through to the flow provider's temporary first-project // default. Return to the picker with the share id intact so the user // can choose an available destination. @@ -290,6 +295,7 @@ export function NewTaskDraftScreen(props: { navigation.dispatch(StackActions.replace("NewTask")); }, [ + allProjects, logicalProjects, projects, props.initialProjectRef, diff --git a/apps/server/src/orchestration/homeThreads.test.ts b/apps/server/src/orchestration/homeThreads.test.ts index 63335aa608..d7f6d30188 100644 --- a/apps/server/src/orchestration/homeThreads.test.ts +++ b/apps/server/src/orchestration/homeThreads.test.ts @@ -120,12 +120,21 @@ const makeQueryLayer = ( const makeEngineLayer = ( dispatched: Ref.Ref>, - options: { readonly fail?: boolean } = {}, + options: { + readonly fail?: boolean; + /** + * Runs after each command is recorded. The only hook that fires *inside* + * `getOrCreateHomeThread`, which is what lets a test land a competing + * settings write between this caller's read and its persist. + */ + readonly onDispatch?: (command: OrchestrationCommand) => Effect.Effect; + } = {}, ) => Layer.succeed(OrchestrationEngine.OrchestrationEngineService, { readEvents: () => Stream.empty, dispatch: (command: OrchestrationCommand) => Ref.update(dispatched, (calls) => [...calls, command]).pipe( + Effect.andThen(options.onDispatch ? options.onDispatch(command) : Effect.void), Effect.andThen( options.fail ? Effect.fail( @@ -150,6 +159,14 @@ const testLayer = (input: { readonly dispatched: Ref.Ref>; readonly providerInstances: Record; readonly failDispatch?: boolean; + /** Fires inside `getOrCreateHomeThread`, right after `thread.create`. */ + readonly onDispatch?: (command: OrchestrationCommand) => Effect.Effect; + /** + * Settings layer to use instead of a fresh one. A test that needs to write + * settings from `onDispatch` builds the layer itself so both sides share one + * store. + */ + readonly settingsLayer?: ReturnType; /** * Archive-state rows. Unlike the shell queue these ignore archive state, so * a test can model "archived, therefore invisible to the shell query but @@ -159,11 +176,15 @@ const testLayer = (input: { }) => Layer.mergeAll( makeQueryLayer(input.threads, input.archiveStates), - makeEngineLayer(input.dispatched, input.failDispatch ? { fail: true } : {}), + makeEngineLayer(input.dispatched, { + ...(input.failDispatch ? { fail: true } : {}), + ...(input.onDispatch ? { onDispatch: input.onDispatch } : {}), + }), configLayer, - ServerSettings.layerTest({ - providerInstances: input.providerInstances, - } as never), + input.settingsLayer ?? + ServerSettings.layerTest({ + providerInstances: input.providerInstances, + } as never), NodeServices.layer, ); @@ -311,6 +332,57 @@ it.effect("adopts a racing caller's designation when its own dispatch fails", () }), ); +it.effect("does not clobber a designation that landed while it was creating", () => + Effect.gen(function* () { + // Two handshakes race: both read "no designation", both create a thread. + // The one that persists *second* must stand down rather than overwrite — + // otherwise the first caller re-read the winner's id and returned it while + // this one overwrites with its own, so the two disagree about Home and + // concurrent proactive deliveries land in two different threads. + const threads = yield* Ref.make>>([ + Option.none(), + ]); + const dispatched = yield* Ref.make>([]); + const settingsLayer = ServerSettings.layerTest({ + providerInstances: { [INSTANCE_ID]: hermesInstance({}) }, + } as never); + + yield* Effect.gen(function* () { + const settings = yield* ServerSettings.ServerSettingsService; + + const resolved = yield* getOrCreateHomeThread({ + instanceId: INSTANCE_ID, + title: "Hermes Siva Local", + }).pipe( + Effect.provide( + testLayer({ + threads, + dispatched, + providerInstances: {}, + settingsLayer, + // The racing caller wins the settings write while this one is + // still between `thread.create` and its own persist. + onDispatch: () => + settings + .updateSettingsWith((latest) => ({ + providerInstances: { + ...latest.providerInstances, + [INSTANCE_ID]: hermesInstance({ homeThreadId: HOME_THREAD_ID }), + }, + })) + .pipe(Effect.ignore), + }), + ), + ); + + // Both callers agree on the winner's thread, and the loser's own thread + // stays an empty thread in the agent project rather than a second Home. + assert.equal(resolved, HOME_THREAD_ID); + assert.equal(yield* getDesignatedHomeThreadId(INSTANCE_ID), HOME_THREAD_ID); + }).pipe(Effect.provide(settingsLayer)); + }), +); + it.effect("recognizes any instance's home thread as undeletable", () => Effect.gen(function* () { const threads = yield* Ref.make>>([]); diff --git a/apps/server/src/orchestration/homeThreads.ts b/apps/server/src/orchestration/homeThreads.ts index eb3c5189c7..e4ac0b7cd4 100644 --- a/apps/server/src/orchestration/homeThreads.ts +++ b/apps/server/src/orchestration/homeThreads.ts @@ -116,10 +116,26 @@ const readHomeThreadRow = Effect.fn("readHomeThreadRow")(function* (threadId: Th return Option.getOrUndefined(row); }); -/** Persist a designation into the instance's Hermes config blob. */ +/** + * Persist a designation into the instance's Hermes config blob. + * + * A compare-and-set against `expected` — the designation this caller read + * before deciding to create — rather than a blind write. Two concurrent + * callers that both mint a thread would otherwise each persist their own id, + * and the one that wrote first re-reads before the other's overwrite lands, so + * the two return *different* threads and one is orphaned from the final + * designation. Standing down when the designation moved out from under us is + * what makes the caller's re-read below an actual tiebreaker. + * + * `expected` still has to be honoured rather than "never overwrite": the + * self-healing path arrives here with a stale designation pointing at a thread + * that is really gone, and replacing exactly that value is the whole point. + */ const persistHomeThreadId = (input: { readonly instanceId: ProviderInstanceId; readonly threadId: ThreadId; + /** Designation observed before creating, or `undefined` if there was none. */ + readonly expected: ThreadId | undefined; }) => Effect.gen(function* () { const settings = yield* ServerSettingsService; @@ -130,6 +146,9 @@ const persistHomeThreadId = (input: { // it. Returning an empty patch is the established no-op here. const existing = latest.providerInstances[input.instanceId]; if (!existing || existing.driver !== HERMES_DRIVER_KIND) return {}; + // Someone else designated (or re-designated) while we were creating. + // Adopt theirs; ours stays an empty thread in the agent project. + if (readHomeThreadId(existing) !== input.expected) return {}; const currentConfig = existing.config && typeof existing.config === "object" ? (existing.config as Record) @@ -231,7 +250,7 @@ export const getOrCreateHomeThread = Effect.fn("getOrCreateHomeThread")(function return yield* Effect.fail(dispatched.failure); } - yield* persistHomeThreadId({ instanceId: input.instanceId, threadId }); + yield* persistHomeThreadId({ instanceId: input.instanceId, threadId, expected: designated }); // Re-read rather than trusting our own write: if a racing caller persisted // first, both callers must agree on one thread, and settings is the diff --git a/apps/server/src/provider/Layers/HermesAdapter.test.ts b/apps/server/src/provider/Layers/HermesAdapter.test.ts index c44a03e53b..e6bd02f90f 100644 --- a/apps/server/src/provider/Layers/HermesAdapter.test.ts +++ b/apps/server/src/provider/Layers/HermesAdapter.test.ts @@ -456,6 +456,13 @@ const makeReconnectHarness = (options: { readonly instanceId: ProviderInstanceId; readonly threadId: ThreadId; readonly initialSessionId: HermesGatewaySessionId; + /** + * Runs before each one-way send is recorded, so a test can land a broker + * event in the middle of an adapter operation. + */ + readonly onSend?: ( + message: HermesGatewayT3ToPluginMessage, + ) => Effect.Effect; }) => Effect.gen(function* () { const sent: Array = []; @@ -520,7 +527,11 @@ const makeReconnectHarness = (options: { } return Effect.die(new Error(`unexpected request ${message.type}`)); }, - send: (_instanceId, message) => Effect.sync(() => sent.push(message)).pipe(Effect.asVoid), + send: (_instanceId, message) => + (options.onSend ? options.onSend(message) : Effect.void).pipe( + Effect.andThen(Effect.sync(() => sent.push(message))), + Effect.asVoid, + ), isConnected: () => Effect.sync(() => state.connected), stream: Stream.fromPubSub(brokerEvents), streamStatuses: Stream.fromPubSub(brokerStatuses), @@ -1153,6 +1164,59 @@ it.effect("keeps the session on an undeliverable stop so Hermes is not orphaned" }).pipe(Effect.scoped, Effect.provide(testEnvLayer)), ); +// `stopAll` snapshots `sessions.keys()` up front, and the broker event fiber +// deletes a session the moment `session.exited` lands — so a session can be +// gone by the time its own stop runs. That raises SessionNotFound, which the +// sweep used to let escape: every session after it in the snapshot was never +// stopped, and on shutdown the whole finalizer logged a failure. +it.effect("finishes the stopAll sweep when a session exits mid-sweep", () => + Effect.gen(function* () { + const instanceId = ProviderInstanceId.make("hermes_stop_all_race"); + const firstThreadId = ThreadId.make("thread-stop-all-first"); + const secondThreadId = ThreadId.make("thread-stop-all-second"); + const sessionId = HermesGatewaySessionId.make("session-stop-all"); + const events = yield* PubSub.unbounded(); + + const harness = yield* makeReconnectHarness({ + instanceId, + threadId: firstThreadId, + initialSessionId: sessionId, + // The second session exits while the first one's stop is being written. + onSend: (message) => + message.type === "session.stop" && message.threadId === firstThreadId + ? PubSub.publish(events, { + instanceId, + message: { + type: "session.exited", + protocolVersion: HERMES_GATEWAY_PROTOCOL_VERSION, + threadId: secondThreadId, + sessionId, + recoverable: false, + }, + }).pipe(Effect.andThen(drain)) + : Effect.void, + }); + // Route the harness's broker stream through our own pubsub so `onSend` can + // publish into the same stream the adapter is subscribed to. + yield* Stream.runForEach(Stream.fromPubSub(events), (envelope) => + PubSub.publish(harness.brokerEvents, envelope), + ).pipe(Effect.forkChild({ startImmediately: true })); + + for (const threadId of [firstThreadId, secondThreadId]) { + yield* harness.adapter.startSession({ + threadId, + providerInstanceId: instanceId, + runtimeMode: "full-access", + }); + } + + // The sweep must run to completion rather than dying on the vanished one. + yield* harness.adapter.stopAll(); + assert.isFalse(yield* harness.adapter.hasSession(firstThreadId)); + assert.isFalse(yield* harness.adapter.hasSession(secondThreadId)); + }).pipe(Effect.scoped, Effect.provide(testEnvLayer)), +); + it.effect("drops frames for a session it no longer tracks", () => Effect.gen(function* () { const instanceId = ProviderInstanceId.make("hermes_forgotten"); diff --git a/apps/server/src/provider/Layers/HermesAdapter.ts b/apps/server/src/provider/Layers/HermesAdapter.ts index 3408c45994..d6742854f1 100644 --- a/apps/server/src/provider/Layers/HermesAdapter.ts +++ b/apps/server/src/provider/Layers/HermesAdapter.ts @@ -1061,6 +1061,11 @@ export const makeHermesAdapter = Effect.fn("makeHermesAdapter")(function* (input threadId, detail: error.detail, }), + // The keys snapshot is taken before the first stop runs, and the + // broker event fiber deletes sessions on `session.exited` — so a + // session can disappear mid-sweep. That is the outcome this sweep + // wants anyway; aborting the remaining threads over it is not. + ProviderAdapterSessionNotFoundError: () => Effect.void, }), ), { discard: true }, diff --git a/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts b/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts index a8de518ed9..5a39fc86a4 100644 --- a/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts +++ b/apps/server/src/provider/Layers/HermesGatewayBroker.test.ts @@ -1064,6 +1064,35 @@ it.effect("preserves concurrent provider settings edits during rename and remova }).pipe(Effect.provide(testLayer)), ); +// `createEnrollment`'s settings callback no-ops when the instance is gone (or +// changed driver) between its read and its write. Continuing past that meant +// minting a token `registerConnection` can only ever reject — the user is +// handed a `hermes t3 connect …` command that fails with no explanation. +it.effect("fails rather than minting a token when the instance vanishes mid-enrollment", () => + Effect.gen(function* () { + const settings = yield* ServerSettings.ServerSettingsService; + const inner = makeSecretStore(); + // The credential invalidation sits exactly between the read and the write, + // so removing the instance from there lands the race deterministically. + const secrets: ServerSecretStore.ServerSecretStore["Service"] = { + ...inner, + remove: (name) => + settings + .updateSettingsWith((current) => { + const providerInstances = { ...current.providerInstances }; + delete providerInstances[instanceId]; + return { providerInstances }; + }) + .pipe(Effect.ignore, Effect.andThen(inner.remove(name))), + }; + const broker = yield* makeBrokerWith(secrets, settings); + + const error = yield* Effect.flip(enroll(broker, instanceId, "Vanishing Hermes")); + assert.equal(error.operation, "create-enrollment"); + assert.equal(error.code, "instance-not-found"); + }).pipe(Effect.provide(testLayer)), +); + it.effect("requires revocation before removing an enrolled instance", () => Effect.gen(function* () { const secrets = makeSecretStore(); diff --git a/apps/server/src/provider/Layers/HermesGatewayBroker.ts b/apps/server/src/provider/Layers/HermesGatewayBroker.ts index 2c0feffe92..f44e8a0fc6 100644 --- a/apps/server/src/provider/Layers/HermesGatewayBroker.ts +++ b/apps/server/src/provider/Layers/HermesGatewayBroker.ts @@ -448,7 +448,7 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ), ); - yield* settings + const committed = yield* settings .updateSettingsWith((latest) => { const latestConfigured = latest.providerInstances[input.instanceId]; if (!latestConfigured || latestConfigured.driver !== HERMES_DRIVER_KIND) return {}; @@ -474,6 +474,21 @@ export const makeHermesGatewayBroker = Effect.gen(function* () { ), ); + // Same committed-settings check `renameInstance` and `removeInstance` + // make, and for the sharper reason: the callback above no-ops when the + // instance vanished (or changed driver) between `readSettings` and the + // write, and continuing would mint a token `registerConnection` can + // only ever reject — handing the user a `hermes t3 connect` command + // that fails with no explanation. Failing here says so instead. + if (!recordFrom(input.instanceId, committed.providerInstances[input.instanceId])) { + return yield* managementError( + "create-enrollment", + "instance-not-found", + `Provider instance '${input.instanceId}' is no longer configured with the Hermes driver.`, + input.instanceId, + ); + } + // Any live connection is authenticating with the credential we just // invalidated, so it can no longer be trusted. const displaced = yield* connections.clearConnection(input.instanceId); diff --git a/apps/web/src/components/chat/ProviderModelPicker.tsx b/apps/web/src/components/chat/ProviderModelPicker.tsx index ad8329acb4..3c1f4d8176 100644 --- a/apps/web/src/components/chat/ProviderModelPicker.tsx +++ b/apps/web/src/components/chat/ProviderModelPicker.tsx @@ -54,7 +54,11 @@ export const ProviderModelPicker = memo(function ProviderModelPicker(props: { onInstanceModelChange: (instanceId: ProviderInstanceId, model: string) => void; }) { const [uncontrolledIsMenuOpen, setUncontrolledIsMenuOpen] = useState(false); - const isMenuOpen = props.open ?? uncontrolledIsMenuOpen; + // The static branch renders no Popover, so a truthy `open` would arm the + // scroll-lock effect below with nothing on screen to dismiss — the composer + // owns this state and `modelPicker.toggle` sets it without knowing which + // branch rendered. Forcing it closed keeps the page scrollable. + const isMenuOpen = props.staticLabel ? false : (props.open ?? uncontrolledIsMenuOpen); // Resolve the active instance entry by exact routing key. The composer // resolves fallbacks before rendering this component; if the selected