Commit Graph

4089 Commits

Author SHA1 Message Date
David Dudok de Wit c41ec9c588 refactor(desktop): scope gateway context to Sessions 2026-08-18 22:03:25 -07:00
David Dudok de Wit e999df46fa fix(desktop): keep gateway search shortcut local 2026-08-18 22:03:25 -07:00
David Dudok de Wit 6e9e12075c refactor(desktop): keep gateway details contextual 2026-08-18 22:03:25 -07:00
David Dudok de Wit 2c6dcf91c7 feat(desktop): keep large gateway registries searchable 2026-08-18 22:03:25 -07:00
David Dudok de Wit 0a36fa7fbd fix(desktop): keep remote bot identity visible 2026-08-18 22:03:25 -07:00
David Dudok de Wit 72fc5ab7ca fix(desktop): use gateway terminology in connection UI 2026-08-18 22:03:25 -07:00
David Dudok de Wit 3095ac54db docs(desktop): clarify connection settings copy 2026-08-18 22:03:25 -07:00
David Dudok de Wit 2228bc7d88 feat(desktop): remember the last used source 2026-08-18 22:03:25 -07:00
David Dudok de Wit ccd30f955c feat(desktop): distinguish sources from profiles 2026-08-18 22:03:25 -07:00
David Dudok de Wit 0ab0ed54ff feat(desktop): clarify active and default connections 2026-08-18 22:03:25 -07:00
David Dudok de Wit 4ea516b8d4 docs(desktop): explain multi-source session scoping 2026-08-18 22:03:25 -07:00
David Dudok de Wit fa73b45d34 fix(desktop): isolate state across source switches 2026-08-18 22:03:25 -07:00
David Dudok de Wit 0ca7443824 feat(desktop): switch sources from the Sessions rail 2026-08-18 22:03:25 -07:00
David Dudok de Wit 7245b022db feat(desktop): route REST through registered sources 2026-08-18 22:03:25 -07:00
amanning3390 8e5f55f83b feat(hermes-bots): add a collapsible group activity view
Bot Mode group rooms only showed a single "is thinking…" line while bots
ran, and nothing after a turn settled or failed — no way to see what the
room did without reading the whole transcript.

- Runtime-only, bounded activity feed per room (GROUP_ACTIVITY_LIMIT),
  recording truthful turn events: queued, working, replied, passed,
  timed-out, failed, cancelled, settled, delivered.
- Every event is tagged with the room epoch it belongs to; the view shows
  only the CURRENT run, so a superseding send (or a rename that re-keys
  the room) can never surface stale activity.
- Quiet disclosure in the room header: collapsed by default, the collapsed
  row shows the latest event summary; expanding lists the current run's
  events newest-first with per-state glyphs and tones.
- Never persisted and never hydrated — the transcript stays the only
  durable record, so activity cannot be replayed as history.

Tests: 8 new behavioral + source-contract cases in
tests/group-activity.test.mjs (settled arc, failed turn, supersede/cancel,
epoch filtering, bounded feed, runtime-only guarantee, labels, disclosure
a11y contract).
2026-08-18 22:03:02 -07:00
pierrenode 589bee99cf fix(bot-mode): never resubmit into a still-running stranded group member
runGroupChatRounds' responder selection had no awareness of the stranded/
harvest state the previous round's harvest pass just confirmed. A member
whose turn timed out (marked stranded) but is STILL genuinely running
could be re-selected as a responder in a later round of the same
invocation — resolveGroupResponders has no busy filter, and a member's
watermark is bumped past the stranded timeout regardless of outcome, so a
fresh delta re-qualifies them.

Re-selecting them fires another prompt.submit into their live session.
tui_gateway's _handle_busy_submit treats that as a normal busy mid-turn
prompt: by default it either redirects the live turn in place or, for
older agents, hard-interrupts it and queues the new text as the next
turn. Either way the member's original in-flight work — exactly what the
stranded/harvest mechanism exists to protect — gets abandoned or killed,
undermining the "never lost, just late" guarantee.

Filter responders against the room's current stranded map (freshly
confirmed by this round's own harvest pass) before selecting who speaks.
A member with a live stranded marker is skipped; the next harvest pass
picks their reply up once it actually lands.

Added a regression test exercising runGroupChatRounds end-to-end with a
member confirmed still-busy: without the guard the round loop resubmits
into their session (asserted via prompt.submit call count); with the
guard it never does, and the marker survives untouched. Mutation-verified:
temporarily reverted the filter and confirmed the new test fails
(2 !== 0) fast, without a real wall-clock wait.

Full hermes-bots plugin suite: 246/246 pass (47 files). node --check
clean on both changed files.
2026-08-18 22:02:32 -07:00
Teknium d440891204 test(desktop): update canonical-chat-identity expectation for salvaged PR #89031 2026-08-18 21:52:41 -07:00
marketing2981 ed47d41dc9 fix(desktop): bot navigation no longer forces the all-profiles sidebar on
Every host.openSession call in the Bot Mode plugin omitted
keepAllProfilesScope, so the SDK applied its default and flipped
$showAllProfiles back on whenever the target session belonged to a
different profile than the live gateway (sdk/index.ts:
options.keepAllProfilesScope !== false => setShowAllProfiles(true)).

For anyone running more than one profile this silently undid the sidebar
profile filter: narrow Sessions to one profile, click any other bot, and
the unified all-profiles list came back.

Bot navigation is an explicit context switch into that bot's profile, so
pass keepAllProfilesScope: false at every openSession call site (4 on
current main after the plugin.js refactor consolidated the original 7).

Salvaged from PR #89031 onto current main; includes contributor mapping.
2026-08-18 21:52:41 -07:00
Teknium af3373f7c8 test: follow-up for salvaged PR #89020 — focused-highlight contract includes the !activeGroup guard 2026-08-18 21:52:11 -07:00
Shawn Wang 80f080b6ed fix(bot-mode): highlight selected group chat
Signed-off-by: Shawn Wang <32839114+enwaiax@users.noreply.github.com>
2026-08-18 21:52:11 -07:00
chelsealong 3809f740c6 fix(bot-mode): reseed $selectedBot on register so re-enabling never leaves it stale
nanostores' .listen() never replays the current value the way .subscribe()
does, so the $focusedBotProfile listener in register() only kept
$selectedBot current from the moment it was attached. A disable -> profile
switch -> re-enable cycle (Settings > Plugins) left $selectedBot pointed at
whichever bot was active before the plugin was disabled, so the roster
highlight fallback and Routines scoping could start from a stale bot.

Extract the sync into bindProfileSync(), which reseeds $selectedBot from
the profile store's current value before attaching the listener. This runs
on every register() call, so re-enabling the plugin always starts in sync.

Salvaged from PR #89637 (the pane-precedence portion was superseded on main
by the $focusedBotProfile design; this residual reseed gap remained).
Regression test mimics real nanostores get/listen semantics and fails
without the reseed.

Fixes-residual-of: #89625
2026-08-18 21:51:36 -07:00
David Dudok de Wit 00e9a32454 fix(desktop): keep Bot Mode routines docked 2026-08-18 21:50:56 -07:00
Jay 104ec97595 fix(bot-mode): group room preview shows the bot handle, not @default
`botHandle()` exists so that, per its own comment, "the word 'default'
never surfaces in the UI" — it presents the primary profile as `hermes`.
The roster rows, mention resolution and the group-chat prompt all route
through it. Two preview paths did not, and rendered the raw profile name:

- `GroupRow`'s room preview line built `@${last.from?.name}`, so a group
  room read `@default: …` while the bot answers to `@hermes`.
- `previewKind()` returned the raw captured name from the bot-to-bot
  delivery prefix, so the `🤖 @<name>` badge and its tooltip could show
  `@default` too.

The mismatch is presentation-only, but it reads as a routing bug: the
room says the message came from `@default` while `@default` is not a
handle the mention resolver accepts, so users reasonably conclude
bot-to-bot addressing is broken when it is working correctly.

Both paths now map through `botHandle()`. `GroupRow` passes the matching
member so a bot with a custom handle keeps it; `previewKind` maps the
lowercased sender name, which leaves every non-primary profile unchanged.

Tests: the primary profile resolves to `hermes` and a named profile keeps
its own handle (behavioural, in the existing previewKind suite), plus a
source-shape assertion for the render path matching that file's
convention. Both new assertions fail against the pre-fix source.

Fixes #89484
2026-08-18 21:50:31 -07:00
Teknium cb0fd836ac feat: Bot Mode blob avatars gain 4 new silhouettes via blobatar 2.0.0
blobatar 0.2.0 -> 2.0.0 (gen2). Ten silhouettes instead of six:
capsule, triangle, hexagon and droplet join round, organic, boxy,
nub, cloud and sun. BLOB_KIND_TRAIT repinned to gen2 band centers
(empirically verified against the published package: every pinned
value resolves to its named silhouette across seeds). The avatar
picker derives from BLOB_KINDS, so the new shapes appear there
automatically. Note: gen2 remaps most unpinned seed->face mappings
by design (upstream generation change).
2026-08-18 21:45:29 -07:00
hermes-seaeye[bot] 395c70d616 fmt(js): npm run fix on merge (#89703)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-08-19 04:05:24 +00:00
ethernet 0b879298a7 feat(desktop): browser-bar controls for the address and the page
The browser bar gets an open-in-external-browser glyph that opens
the tab's live address. The address field gets a copy control on its
right edge, with the same pre-faded inline appearance as the
code-block copy button. Copy always takes the address the field
shows: on a remote gateway, that is the reach-resolved address. The
page verbs (copy URL, open externally, console, DevTools) live here
and not in the guest context menu, which keeps the node-scoped
tools.
2026-08-18 23:53:07 -04:00
ethernet 1314a539c2 refactor(desktop): custom translated context menus across the app
One renderer coordinator owns every right-click and replaces the
native Electron menus. Menus are assembled from what the click
landed on:

- Links and images get open/copy/save sections; chat links add the
  reach-aware resolved-URL copy on remote gateways.
- Editables get spell-check suggestions (async-appended when
  Chromium's facts arrive from main), cut/copy/paste, and select
  all. Cut and copy need a selection; paste needs a non-empty
  clipboard; select all needs field content. The verbs show their
  accelerators instead of icons and dispatch a frame after the menu
  closes, so the radix focus trap cannot steal the target. Select
  all runs renderer-side, scoped to the field, because main's
  selectAll acts on the focused frame and could grab the transcript.
- Terminals answer through registered xterm handles; the read-only
  agent terminal hides paste.
- The in-app browser guest builds the same menus from the webview
  tag's context-menu event: Chromium's editFlags gate the edit
  verbs, spell-check rides the event, and Inspect element closes
  every menu. Coordinates arrive as window-relative device pixels,
  so the handler divides by the window zoom factor; guest edit
  commands focus the webview first, because they act on the focused
  webContents.
- Bare app chrome falls back to the window verbs.

Labels come from the locale files in all five languages. Main keeps
thin IPC verbs: edit commands, copy-image-at-gesture, spell-check
actions, and dictionary-add for guests (the tag has no session API).
The e2e spec exercises the real focus trap; it is blocked today by
the gateway-checking stall that also fails e2e/chat.spec.ts.
2026-08-18 23:53:07 -04:00
Teknium 51013e9ae0 fix(desktop): /goal clear removes the Goal paused card immediately
`/goal clear` (and pause/resume/status) can come back from the gateway as
a TYPED `{ type: "exec" }` command dispatch instead of the plain
`{ output }` slash.exec shape. The typed exec/plugin branch in
use-prompt-actions/slash.ts rendered the output ("✓ Goal cleared.") and
returned immediately — it never reached the goal-store sync that the
plain-output path runs (`applyGoalStatusText`). The composer status stack
therefore kept showing the stale "Goal paused" card, with the old goal
text, until the chat was left and reopened (which re-hydrates via
`refreshSessionGoal`).

Fix: in the typed exec/plugin dispatch branch, when the command is `goal`,
mirror the dispatch output into the goal store via
`applyGoalStatusText(sessionId, output)` before rendering — exactly what
the plain-output path already does. This covers the whole sibling class
(clear/pause/resume/status/done) since the store's text parser already
understands every /goal output shape; set (`send` dispatch notice) was
already handled.

Tests:
- use-prompt-actions/index.test.tsx: typed exec `✓ Goal cleared.` removes
  the session's goal entry immediately (#80348), and typed exec
  `▶ Goal resumed:` flips a paused card back to active.
- store/goals.test.ts: `✓ Goal cleared.` output clears a paused goal.

Fixes #80348
2026-08-18 19:51:41 -07:00
Teknium 23c1c9815f fix(desktop): Bots sidebar highlight and Cronjobs tile now follow the chat on screen
The Bots roster highlight and the Routines (Cronjobs) tile were keyed off
host.state.profile — the gateway socket's home. Tab/tile focus moves without
swapping the socket, so opening one bot's chat while the socket was homed on
another highlighted the wrong bot and showed the wrong bot's cronjobs
(community report: Newsanalyst chat open, Hermes highlighted).

- sdk: new host.state.focusedSessionProfile — owner profile of the focused
  chat, resolved from the focused stored session's row stamp via
  rememberedSessionProfile() (same ladder as remembered navigation and the
  HUD), with the gateway profile as the draft/uncached fallback.
- hermes-bots: $focusedBotProfile = focusedSessionProfile || profile
  (feature-detected; older desktops keep prior behavior). BotRow highlight,
  RoutinesPane scope, and the $selectedBot tracker use it. Turn-busy 'work'
  mood stays keyed to the socket-home profile (only it can be mid-turn).
- tests: SDK atom behavior (vitest) + plugin source-shape suite; prewarm
  harness stubs gain the new atom.
- docs: SDK page + hermes-agent skill reference list the new atom.
2026-08-18 19:51:13 -07:00
Brooklyn Nicholson 74f99af470 feat(desktop): agent-applied layout presets — apply_layout joins the desktop_ui toolset
The agent could reveal single panes (focus_pane) but had no way to arrange
the workspace as one act. apply_layout closes that gap: a desktop_ui tool
that emits layout.apply over the existing bridge, resolved in the renderer
against the layouts contribution registry — the same list the layout picker
reads — so core presets (default/focus/terminal-deck/quad), plugin presets,
and user-saved presets are all addressable by id. Active session only, same
as pane.reveal: a background turn never rearranges the user's desktop.
2026-08-18 21:06:18 -05:00
hermes-seaeye[bot] b7bed2419e fmt(js): npm run fix on merge (#89619)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-08-19 01:35:26 +00:00
ethernet 9a9015dfa8 test(desktop): batch clarify E2E spec and mock trigger
The mock server gains a batch clarify trigger that scripts a
two-question clarify turn. The scripted turn fires only while the
conversation has no tool result, so the answered batch falls through
to the canned reply instead of a repeat of the quiz.

The spec runs the real chain from composer to renderer and asserts
one batch card, the staged-answers confirm gate, and the settled
card. The local harness cannot boot the packaged app in this
environment (the pre-existing chat spec fails the same way), so the
proof for this spec is the CI run.
2026-08-18 21:28:53 -04:00
ethernet 25c6516607 feat(desktop): single confirm for the batch clarify card
The batch card previously locked each answer with its own Continue
press. Now picks and typed answers stage locally, and one Confirm and
continue button (enabled when every question has an answer) submits
the whole batch. Staged answers stay editable until that confirm.

The wire protocol is unchanged. The confirm sends the per-question
locks in sequence, because the last lock resolves the blocked tool and
each earlier lock must already be accepted when it lands. Replayed
locked answers from a reconnect pre-stage their questions so restored
progress stays visible. The TUI and CLI keep incremental per-question
locks, so a timeout there still returns partial answers.
2026-08-18 21:28:53 -04:00
ethernet 838c4692bc fix(desktop): merge duplicate batch clarify cards
A batch clarify rendered as two identical interactive cards. The
tool.start row carries the model tool_call_id and the clarify.request
row carries a gateway request_id. The hydration-race merge correlates
the two rows with the top-level question text. A batch payload has no
top-level question, so the rows never matched and the card mounted
twice.

The correlation key for a batch now comes from the joined per-question
texts. The NUL separator cannot occur in real question text, so a batch
key cannot collide with a single-question key.

New coverage: two hydration-race tests for the batch shape (tool.start
first and clarify.request first), a mock-server batch clarify trigger,
and an E2E spec that runs the full chain and asserts exactly one card,
the per-question locks, the Confirm and continue relabel, and the
settled card.
2026-08-18 21:28:53 -04:00
ethernet e0d8a2eb89 feat(desktop): multi-question clarify card with per-question locks
The clarify card renders every batch question at once. Answers stage
locally per question; the footer button locks the staged answer with a
clarify.respond keyed by question_id. Locked answers stay editable — a
new pick un-locks the row and a re-lock overwrites server-side. When
exactly one question is unanswered the button relabels to Confirm and
continue, and that final lock completes the batch. Skip cancels the
whole batch (no question_id). Reconnect replay seeds the locked map so
a reattached window restores its earlier state.

The settled card lists every question with its answer; blank answers
render as Skipped. Single-question cards are untouched.
2026-08-18 21:28:53 -04:00
hermes-seaeye[bot] 2163f7f8ca fmt(js): npm run fix on merge (#89580)
Co-authored-by: github-actions[bot] <github-actions[bot]@users.noreply.github.com>
2026-08-19 00:20:52 +00:00
Teknium 4ac938ddec feat(desktop): sessions/bots tabs are show/hide chrome — no close gestures, right-click + Cmd-K toggles
Builds on #89551 (@calvinnwq, cherry-picked): his showCloseButton flag
hid the hover X; this completes the model so standing chrome can never
be closed at all, only shown/hidden (#89546).

- hideOnly pane chrome (sessions + Bots): no hover X, no middle/meta
  click close, no Close verbs in the tab menu, excluded from
  close-others/right/all sweeps
- zone right-click menu gains Show/Hide rows for the strip's chrome
  tabs (Hide bots / Show sessions, localized in 6 locales)
- Cmd-K palette: auto-registered "Toggle <tab> tab" rows for every
  hideOnly pane, on-screen truth semantics, plugin panes included via
  registry subscription
- hides persist across launches (survive the enforced dock re-adopt);
  reveal intent and Layout reset clear them
- last-visible-tab guard: hiding the zone's last shown tab is refused
  with a toast, so the strip can never become an empty dead zone
2026-08-18 17:14:45 -07:00
Calvin Ng 34d1aed3f1 fix(desktop): hide close affordance on navigation tabs
Add a pane-level opt-out for the hover close button and apply it to the persistent Sessions and Bots navigation panes. Keep their existing close handlers and other tab behavior intact.\n\nFixes #89546
2026-08-18 17:14:45 -07:00
Teknium 97b41f8cf3 feat(bot-mode): group chats accept PDFs, files, and drag & drop
Completes group/1:1 attachment parity (#88983). PR #89486 covered images;
this adds the remaining half:

- The composer picker accepts any file type; kind (image/pdf/file) decides
  the staging RPC. Paste handlers accept non-image files too.
- Drag & drop anywhere on the room drops into the active composer (open
  reply box, else main), with a drop overlay naming the target.
- Member turns stage PDFs via pdf.attach (rendered per-page into vision
  tiles by the gateway) and other files via file.attach; each returned
  @file: ref is appended to that member's turn prompt so file tools can
  read the artifact. Failed attaches still degrade to text-only.
- Transcript markers distinguish [attached PDF: x] / [attached file: x] /
  [attached image: x]; room log renders non-image attachments as named
  chips, pending chips show type icons.

Tests: 3 new vm-harness tests (per-kind RPC routing across members,
@file: ref injection into turn prompts, transcript labels); 279 total pass.
2026-08-18 16:27:20 -07:00
Teknium a77ee88ce2 feat: Bot Mode avatars default to deterministic blob faces drawn from the agent's name
New agents now get a blobatar — a deterministic soft-body face generated
from the bot's name (same name, same face, forever) — as the default
shapes mode, with full manual control:

- Face follows the name live while typing in New Agent
- Randomize re-rolls the seed; Lock face pins the current one so a later
  rename can't change it (Unlock returns to name-following)
- Any of the six silhouettes (round/organic/boxy/nub/cloud/sun) can be
  pinned via frozen-per-major trait positions while the rest stays
  name-derived
- Classic geometric shapes remain one click away, and existing bots keep
  their stored looks untouched

Wiring: blobatar@0.2.0 (zero deps, ~3.7KB) exported through the plugin
SDK (blobatarSvg / Blobatar), feature-detected in plugin.js with a
legacy-shape fallback for older desktops. Blob shape strings are
'blobatar[:seed[:kind]]' inside the existing meta.shape field, so
persistence, cross-machine ui_meta sync, and the roster's PNG backfill
(data-bot-face tag preserved) all work unchanged.
2026-08-18 15:54:24 -07:00
Teknium f8767d1e71 perf(desktop): durable transcript-tail cache — bot wakes paint at ~0ms
Second layer of the "make hydration feel instant" work (on top of the
paint-first wait): persist a bounded tail (40 msgs / 256KB / 50-session
LRU) of every reconciled transcript in localStorage, keyed by durable
stored-session id.

- Cold resume paints the cached tail immediately — the wake is visually
  complete before any network I/O; the REST prefetch / runtime resume
  reconcile the authoritative transcript over it when they land.
- The cached paint is DISPLAY-ONLY: reconciliation treats the view as
  empty (viewMessagesForReconcile), so authoritative content replaces the
  provisional paint wholesale — no grafting onto stale rows. Failure
  latches also treat it as empty, so a cached paint can never mask a
  genuinely stranded resume; a resume that proves the session empty rolls
  the paint back and drops the poisoned entry.
- Saves happen only post-reconcile (cold path + warm activate path);
  deletes drop the entry; a gateway/mode re-home wipes the cache (another
  backend can recycle stored ids).

Sabotage-proven: disabling the cache load fails 5/7 cache tests; the
display-only contract is covered by the existing resume reconciliation
suite (663 tests green).
2026-08-18 15:52:39 -07:00
Teknium 5ce09b3c1e perf(desktop): Bot Mode wakes paint-first — transcript paint completes the
wake instead of the full runtime boot (#89206 class)

zero trust's third bundle (on ae6578af, both prior fixes present) showed the
remaining failure: cold profile backends on slower Windows machines take
47-120s to fully boot, while the wake path's fixed budgets (20s hydration,
~15s resume retries) raced the whole boot and lost — "errors waking up BOTS"
while the backend came up healthy moments later.

Rather than raising timeouts, make the wake cheap:

- waitForFocusedSessionHydration: a history-bearing chat is hydrated when
  the persisted transcript is PAINTED on the right session. The REST
  prefetch delivers that seconds after the backend's HTTP is up; the full
  runtime resume (agent build, MCP discovery, 114-skill load) keeps warming
  in the background and binds the composer when it lands. Only an
  expected-empty chat still waits for the runtime (nothing to paint).
- On hydration timeout, log a [bot-wake] phase breakdown (activation ms,
  hydration ms, which conditions were unmet) to the renderer console so the
  next support bundle pinpoints the slow phase directly.
- web_server: flush the headless "listening" line — block-buffered on the
  Desktop's piped stdout, it surfaced minutes late and made boots look far
  slower than they were in support bundles (the 120s "gap" in this bundle
  was partly this artifact).

Sabotage-proven: restoring the runtime-gated wait fails the new paint-first
test by timing out — the exact field shape.
2026-08-18 15:52:39 -07:00
Teknium b359db72ee feat(bot-mode): group chats accept image attachments every responding bot sees
Group rooms were text-only on the ingest side: the composer and
runGroupChatMemberTurn submitted prompt.submit {text} with no attach step,
so a user screenshot could never reach the members' models (community
report from Osiris). The gateway already ships the staging pipeline
(image.attach_bytes -> attached_images -> next prompt.submit) and the 1:1
canonical chat uses it — this wires the group surface to the same path.

- Composer + thread reply boxes: attach button, Ctrl/Cmd-V paste, pending
  chips with preview/remove, image-only sends allowed.
- Attachments are downscaled (long edge 1568px) and stored on the room-log
  entry, so reloads keep showing what members were shown.
- Turn drive stages the delta's images into EVERY responding member's own
  per-group session via image.attach_bytes before its prompt.submit —
  works cross-connection through requestForBot; a failed attach degrades
  that member to text-only rather than failing the turn. Watermarks
  guarantee an image is staged at most once per member.
- formatGroupChatLine names attachments ([attached image: name]) so the
  transcript delta and the staged pixels line up for every viewer.
- Room log renders attached images on user entries.

Tests: 6 new vm-harness tests (fan-out staging order, mention-scoped
attachment routing, image-only sends, no re-attach across turns,
transcript naming, invalid-attachment degradation); 276 total pass.
2026-08-18 15:05:15 -07:00
Jack Lau f0f4f29e27 docs(desktop): state one fallthrough contract at the agent seam
The comment above ensureGatewayAgent carried both the old and the new
contract on consecutive lines: "a local/null connectionId falls through
to the profile path verbatim", immediately contradicted by "only a null
connectionId falls through, explicit local is a registry identity".
Dropped the stale line.

Same wording above prepareGatewayForAgent in gateway.ts, tightened to
match what the code actually does: registryBackendScopeKey only collapses
to the bare profile key for a null or empty id, so an explicit local id
scopes to conn:local::<profile> and stays on the registry route.

Comments only, no behavior change. tsc --noEmit, eslint and the three
affected suites (43 passed) re-verified.

Refs #82140
2026-08-18 15:04:28 -07:00
Jack Lau 4e520f0850 fix(desktop): guard the profile publication on its activation result too
The agent path already declined to publish when applyActive() rejected its
activation, but the profile path discarded the same boolean and published
unconditionally. applyActive() returns false when its captured epoch has
been superseded, which happens whenever a newer switch or a teardown lands
while this preparation is still awaiting its route or socket.

The result was not a torn publication. batch() makes those writes
observer-atomic either way. It was something subtler: ONE complete,
internally inconsistent tuple, the CURRENT gateway paired with the stale
target's profile pointer and descriptor. Atomicity cannot make a rejected
activation correct, so the caller has to decline to publish at all.

prepareGatewayForProfile now returns Promise<() => boolean> like its agent
counterpart. The primary and shared-primary thunks return applyActive()
directly; the secondary thunk reports whether the prepared entry was still
current AND the epoch was accepted, keeping the descriptor publish
conditional on having a cached connection so an accepted activation with no
descriptor still moves the companions.

prepareGatewayForAgent's genuinely-local fallthrough now returns the profile
thunk unchanged instead of wrapping it to return an unconditional true,
which had been reporting a rejected activation to the agent caller as a
successful one.

Two regressions on the profile door: a superseded activation leaves all
three stores on the existing complete route with no subscriber notified at
all, and an accepted one still publishes, so a thunk that always reported
false could not pass. The mock thunks in profile.test.ts now return true,
since a bare vi.fn() returns undefined and would read as "superseded".
2026-08-18 15:04:28 -07:00
Jack Lau 162aa6d72a refactor(desktop): wrap the prepareGatewayForAgent signature at the project width 2026-08-18 15:04:28 -07:00
Jack Lau 053eb7aab0 fix(desktop): publish a gateway switch in one nanostores batch
The prepare/publish seam removed the *await* between activating the
gateway and setting the profile pointer and connection descriptor, but
not the *notification* gap. Nanostores drains a store's listeners
synchronously inside .set(), so three sequential sets still let a
$gateway listener run while $activeGatewayProfile and $connection named
the previous backend. That is the same mixed state the seam exists to
prevent, just narrowed from an async window to a synchronous one, and it
is worse to debug because it is invisible in an await-shaped reading of
the code.

batch() defers every notification to the end of the callback, so the
three become one observable transition on both the profile path and the
agent path.

Pinned with a test that attaches a real $gateway listener and asserts the
companions are already current in the first callback; the mock thunks now
publish distinct gateway identities so an out-of-order publication cannot
pass unnoticed, and three existing tests assert $gateway is still the
ORIGINAL object (by identity) on every path that must publish nothing.
2026-08-18 15:04:28 -07:00
Jack Lau 20ccf88acd fix(desktop): fail the agent switch closed when its descriptor lookup rejects
Review caught that the agent path fixed the pending-descriptor race but not
the failure path. `resolveConnectionForActiveAgent` caught a
`getConnectionFor` rejection and returned null, so `Promise.all` resolved as
`[null, activate]` and the switch published anyway: the activation thunk ran
and `$activeGatewayProfile` advanced, while only `setConnection` was skipped.

That is the same mixed state this PR exists to remove, except it does not
close on its own. The pending-descriptor window ends when the descriptor
arrives; a failed lookup never arrives, so `$gateway` named the new backend
while `$connection` described the old one until an unrelated reconnect or
switch happened to repair it. Anything branching on connection mode in
between (plugins, `MEDIA:`, `/api/fs/*`, `/api/media`, image attach) saw the
pair disagree.

Let the rejection propagate, matching `resolveConnectionForProfile`, whose
contract is already exactly this: null means "no desktop bridge" and nothing
else, and a bridge rejection aborts the whole switch before anything is
published. Both doors now fail closed identically, and the caller can retry.

The existing "leaves the prior connection intact when the descriptor fetch
fails" test asserted the old best-effort behaviour, so it pinned the defect
rather than a contract worth keeping. Replaced with a rejected-descriptor
test that asserts none of the three atoms moved and the activation thunk was
never called. The pending-descriptor case keeps its own separate test, so the
success and failure contracts are pinned independently.

Also reworded the publication comments: these are sequential atom writes with
no asynchronous gap between them, not a transaction, and describing them as
one "frame" overstated the guarantee.
2026-08-18 15:04:28 -07:00
Jack Lau d0e0951cf1 fix(desktop): publish the agent activation atomically too
`ensureGatewayAgent` is the (connectionId, profile) door the SDK's `ensureAgent`
goes through, and it landed on main after the profile path was made atomic. It
published in the order the profile path used to:

    await ensureGatewayForAgent(connection, target)   // $gateway flips here
    $activeGatewayProfile.set(target)
    await syncConnectionToActiveAgent(connection, target)   // $connection here

The trailing await is the same mixed-state window: $gateway and
$activeGatewayProfile already name the agent's backend while $connection still
describes the previous one, so any request or plugin mode-listener firing in
that window announces the wrong mode to the new backend.

Both doors now share one seam:

* `prepareGatewayForAgent` mirrors `prepareGatewayForProfile`: dial the socket,
  publish nothing, return the synchronous activation thunk. A local/null
  connection falls through to the profile seam, so the two paths cannot drift.
  `ensureGatewayForAgent` becomes `(await prepareGatewayForAgent(...))()`,
  exactly how `ensureGatewayForProfile` relates to its own prepare.
* `syncConnectionToActiveAgent` splits into `resolveConnectionForActiveAgent`,
  which resolves only. `ensureGatewayAgent` resolves the descriptor and dials
  the socket concurrently, then activates, moves the profile pointer and sets
  the descriptor with no awaits between them.

The best-effort contract on this path is unchanged on purpose: a descriptor
lookup that fails still leaves the previous `$connection` in place rather than
aborting the switch, which is what the profile path does instead. That
difference is deliberate and called out for review rather than quietly
harmonised.

Tests: `profile-agent-activation.test.ts` gains
`never publishes the agent gateway before its connection descriptor`, the mirror
of the profile-path test, asserting a pending `getConnectionFor` leaves all
three atoms on the old backend and that they flip together once it resolves. The
existing mutex and resync tests move onto the prepare/publish mocks, which also
repairs them: that file mocked `@/store/gateway` without `prepareGatewayForProfile`,
so its profile-path cases called an undefined mock after the rebase.
2026-08-18 15:04:28 -07:00
Jack Lau d57f94a330 fix(desktop): publish gateway, profile, and connection descriptor atomically on a profile switch
ensureGatewayProfile used to activate the target gateway and set
$activeGatewayProfile while the connection descriptor fetch was still
in flight, so during that window $gateway already targeted the new
backend while $connection still described the previous one, and any
request or plugin mode-listener firing then announced the wrong mode to
the new backend. A failed descriptor fetch made the mismatch permanent.

prepareGatewayForProfile (new gateway-store seam) opens the socket and
returns a synchronous activation thunk without publishing anything;
ensureGatewayForProfile now delegates to it. The switch resolves the
descriptor and opens the socket first, then flips the active gateway,
the profile atom, and $connection in one synchronous frame. A
descriptor failure aborts the switch as a unit: nothing is published and
every atom still consistently describes the previous profile.

The deferred-descriptor test holds the fetch open and asserts the public
atoms never disagree, then releases it and asserts all three flipped
together; the failure test asserts no partial publication.
2026-08-18 15:04:28 -07:00