Commit Graph

483 Commits

Author SHA1 Message Date
Hongming Wang
c4d3c9a451 fix(memory): self-review on PR #2956 — drop speculative field, tighten 503 match
Two issues caught in five-axis self-review of #2956:

## 1. Drop speculative source_workspace_id rendering

The panel rendered a "from peer" badge based on
`propagation.source_workspace_id`, claiming it surfaced cross-
workspace propagation. But the OpenAPI spec at
docs/api-protocol/memory-plugin-v1.yaml documents `propagation` as
"Opaque metadata the plugin stores and returns. Reserved for future
cross-namespace propagation semantics" — and a grep across
workspace-server/internal/memory/ confirms NO writer in the codebase
populates that key. The badge would never render against real data.

Violates "don't design for hypothetical future requirements" from
the project conventions. Drop the field from MemoryV2, the row badge,
the test fixtures, and the JSDoc. When propagation gains a concrete
shape, re-add backed by an actual writer.

## 2. Tighten 503 detection — match the literal contract string

Pre-fix detection: `msg.includes('503') || msg.toLowerCase().includes('plugin is not configured')`
False-positives on any unrelated 503 + on any error mentioning
"plugin" + "configured" in any order.

Post-fix: `msg.includes('MEMORY_PLUGIN_URL')` — the env var name is a
hard-coded literal in workspace-server/internal/handlers/memories_v2.go's
available() error, so this is a pinned cross-layer contract. Drift
between the Go error message and the canvas detection now fails
loud (TestMemoriesV2_PluginUnwired_All503 asserts the env var name
in the response body; the canvas test asserts the same).

Extracted as a named export `isPluginUnavailableError` so the
detection is unit-testable and reusable. Added 4 direct tests:
contract-string match, generic-503 false-negative, 401 false-
negative, non-Error inputs.

## Test results

- 30 component tests pass (was 26; +4 for isPluginUnavailableError)
- Coverage on MemoryInspectorPanel.tsx: 100% lines, 100% functions
  (branch coverage up to 85.9% from 84.7% — speculative-field
  branches no longer count)
- Full canvas suite: 1277/1277 pass across 91 files
2026-05-05 16:11:13 -07:00
Hongming Wang
f0f4d0e761 feat(memory): redesign Memory tab for v2 plugin
Replaces the v1 LOCAL/TEAM/GLOBAL tab trio (mapped to the deprecated
shared_context model) with a v2 plugin-driven UI. Without this,
canvas Memory tab was reading the frozen agent_memories table while
all post-cutover agent writes went to the plugin's memory_records —
the tab silently displayed stale data.

## Backend (workspace-server)

New routes under wsAuth, all behind the existing per-tenant token:

  GET    /workspaces/:id/v2/namespaces      → readable + writable lists
  GET    /workspaces/:id/v2/memories        → plugin search proxy
  DELETE /workspaces/:id/v2/memories/:mid   → plugin forget proxy

memories_v2.go — slim handler:
  - Server-side ACL: every search request is intersected with the
    resolver's readable-namespaces set (canvas-supplied namespace
    that the workspace can't read returns [] not 403, matches v1
    existence-non-inferring shape).
  - Returns 503 with "set MEMORY_PLUGIN_URL" hint when plugin
    isn't wired (canvas surfaces a banner).
  - Maps plugin not_found → 404, other plugin errors → 502.
  - View shaping: NamespaceView.label rendered server-side
    ("Workspace (abc-1234)", "Team (t-99)", "Org (acme)", custom)
    so canvas doesn't parse namespace names. MemoryView surfaces
    pin/expires_at/score/source_workspace_id from Propagation.

memories_v2_test.go — 100% line + 100% function coverage:
  - 503 path on every endpoint when unwired
  - Namespaces success + readable/writable error paths
  - Search: empty intersection, full-path query/kind/limit
    propagation, namespace=/no-namespace branches, propagation
    map missing/wrong-type, intersect error, plugin error
  - Forget: success, plugin not_found→404, other plugin
    errors→502, missing memoryId→400
  - Helpers: namespaceLabel for all 4 kinds + truncation,
    parseLimit edge cases (default/0/negative/over-cap/non-num),
    memoryToView field round-trip, indexOfColon, shortID

## Frontend (canvas)

MemoryInspectorPanel rewritten for v2:
  - Drop LOCAL/TEAM/GLOBAL trio. Namespace dropdown driven by
    GET /v2/namespaces.readable, "All namespaces" default.
  - New per-row badges: kind (F/S/C), source (agent/runtime/user),
    pin (📌), TTL countdown (12h / "expired"), score% on
    semantic search, source-workspace ⇡ws-pee for propagated.
  - Drop Edit button — v2 plugin contract has no PATCH; the
    model is forget + recommit. Forget stays.
  - Plugin-unavailable banner with operator hint when /v2/*
    returns 503.
  - Bug fix surfaced by test: rollback-on-failed-delete order
    of operations (loadEntries() called setError(null) AFTER
    we set the failure message, wiping it). Reload first, then
    set the error.

MemoryEditorDialog deleted — Add was POST /memories which v2
doesn't support from canvas (writes go via MCP). The legacy
Edit-flow tests go with it.

## Test results

Backend: `go test ./internal/handlers/` — all pass
Backend coverage on memories_v2.go: 100% lines, 100% functions
Canvas: `vitest run` — 91 files, 1273 tests pass (26 new)
Canvas coverage on MemoryInspectorPanel.tsx: 100% lines,
  100% functions, 96.7% statements, 84.7% branches
  (uncovered branches are defensive `?? fallback` for
   contract-impossible kind/source values)

## Migration note

The legacy v1 GET/POST/PATCH/DELETE on /workspaces/:id/memories
remains in place for the back-compat MCP shim (mcp_tools_memory_v2's
legacy routing) and admin export/import. PR-9 (#283) drops
agent_memories along with the v1 endpoints once the cutover
verification window closes.
2026-05-05 15:53:28 -07:00
Hongming Wang
f3782662bd refactor(external-connect): embed help in agent paste, fix wrong docs hostname
Two related fixes to the Connect-External-Agent flow that the user
flagged: the "Need help?" disclosure block in the modal is for the
operator's eyes only — but the agent reading the pasted snippet has
no access to that context. And the docs URL was pointing at a
hostname that doesn't resolve.

User-visible problems:
1. The agent doesn't see the install link, docs link, or the common-
   error/check pairs that the human pasted. When the agent fails to
   register or hits ConnectionRefused, it can't self-diagnose because
   the troubleshooting context lives in a separate UI block.
2. https://docs.molecule.ai → DNS NXDOMAIN. Every "Documentation"
   link in the modal was a dead link.

## Fixes

### Move help INTO the snippet (not a separate human-only UI block)
Each of the 7 server-rendered templates in
`workspace-server/internal/handlers/external_connection.go` now
appends a `# Need help?` section with: install link, correct docs
link, and the top common errors as `# • symptom — check` pairs.

Templates updated: curl / channel (Claude Code) / mcp (Universal MCP) /
python / hermes / codex / openclaw. Agents reading the paste now have
the same diagnostic context the human did.

### Drop the duplicated UI block in the canvas modal
`canvas/src/components/ExternalConnectModal.tsx`:
- Removed the `TAB_HELP` per-tab metadata constant (152 lines).
- Removed the `HelpBlock` component (62 lines).
- Removed the `<HelpBlock help={TAB_HELP[tab]} />` render call.

The snippet is now the single source of truth for tab-level help.

### Fix the wrong docs hostname
The actual docs site is `doc.moleculesai.app` (singular `doc`,
`.app` not `.ai`), confirmed by:
- `package.json` description in `Molecule-AI/docs` repo →
  "Molecule AI documentation site — doc.moleculesai.app"
- HTTP HEAD on the new URL → 200 for both
  `/docs/guides/mcp-server-setup` and
  `/docs/guides/external-agent-registration`
- HTTP HEAD on old `docs.molecule.ai` → 000 (NXDOMAIN)

All template docs URLs now point at `doc.moleculesai.app`.

## Verification
- `go build ./...` clean
- `go test ./internal/handlers/... -count=1` green
- `pnpm test` → 1291/1291 pass (unchanged)
- `tsc --noEmit` clean
- 219 LOC removed (canvas duplicate UI), 69 LOC added (snippet help)
- Net `-150 LOC` while gaining the agent-readable help

## Out of scope (deferred, captured in followups)
- One blog post still has `canonical: "https://docs.molecule.ai/blog/..."`
  in `src/app/blog/2026-04-20-chrome-devtools-mcp/page.mdx` — separate
  blog-content fix.
- Comment in `theme-provider.tsx` references `docs.moleculesai.app`
  (with `s`) — comment-only, not a runtime URL.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 13:51:35 -07:00
Hongming Wang
9386f1d399
Merge pull request #2926 from Molecule-AI/fix/agent-comms-display-parity
fix(canvas): AgentCommsPanel display + initial-state parity with my-chat
2026-05-05 20:15:29 +00:00
Hongming Wang
5ad2669f88 fix(canvas): AgentCommsPanel display + initial-state parity with my-chat
User-visible problem: agent-comms panel opens mid-conversation on long
histories (the same chat-opens-in-middle bug PR #2903 fixed for
my-chat) and silently renders empty state when the history fetch fails
(no retry button, no diagnostic).

Three changes mirror the my-chat patterns from ChatTab:

1. Initial-mount instant scroll.
   Adds hasInitialScrollRef + switches the scroll hook from useEffect
   to useLayoutEffect. First arrival of messages → scrollIntoView
   `instant`; subsequent appends → `smooth` as before. useLayoutEffect
   runs before paint so the user never sees the panel jump for one
   frame on every append.

2. Error UI with Retry button.
   Adds `loadError` state. The history-load .catch now sets the
   error message; a new branch in the render renders a red alert
   with the failure text and a Retry button that re-invokes
   `loadInitial`. Same shape as ChatTab MyChatPanel's `loadError`
   handling — both surfaces should fail loud, not silent.

3. Extracted `loadInitial` callback.
   The history-load body becomes a useCallback so the retry button
   has a stable reference to call. Mirrors ChatTab's loadInitial.

Tests (4 new in AgentCommsPanel.render.test.tsx):
- Loading state renders the loading copy.
- Error state with Retry button renders on rejection; clicking
  Retry fires a second api.get.
- Empty state renders when load succeeds with zero rows.
- scrollIntoView is called with behavior=instant on first message
  arrival (pins the chat-opens-in-middle prevention).

Verification:
- pnpm test → 1284/1284 pass (1280 prior + 4 new)
- tsc --noEmit → clean
- 92 → 93 test files, no existing test broken

Closes the parity gap raised in chat. The two surfaces now share:
loading copy / error UI / empty-state placeholder / scroll behaviour /
useLayoutEffect timing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 13:09:36 -07:00
Hongming Wang
575f893f4e fix(canvas): consume CP logout_url to break the SSO re-auth loop
Follow-up to molecule-controlplane#485. The first half of #2913 wired
a Sign-out button + signOut() helper that POSTed /cp/auth/signout, but
clicking still left the user signed in: WorkOS's browser cookie
preserved the SSO session, /cp/auth/login auto-re-authed via SSO, and
the user landed back on /orgs.

CP PR #485 returns the AuthKit hosted logout URL in the signout
response. This change has signOut() navigate the browser there
instead of /cp/auth/login. AuthKit clears its cookie + redirects to
return_to (configured server-side from APP_URL) → next /cp/auth/login
hits a fresh AuthKit, no SSO session, login form actually shows.

Defensive parsing: malformed JSON, missing logout_url, or wrong-type
logout_url all fall through to the legacy /cp/auth/login fallback,
which works locally (DisabledProvider, dev) where there's no SSO to
escape.

Forward-compat: when CP doesn't have #485 deployed yet, signOut()
sees logout_url="" or missing → fallback fires. Order of merge
between this and #485 doesn't matter, but the bug isn't actually
fixed end-to-end until both ship.

Tests added (3 new, 15 total auth.test.ts):
- Hosted logout: navigates to logout_url when response includes one.
- DisabledProvider path: falls back to /cp/auth/login when "".
- Defensive: malformed JSON body → fallback (no crash).
- Defensive: non-string logout_url → fallback (no open redirect).

Verified:
- npx vitest run src/lib/__tests__/auth.test.ts — 15/15 pass
- tsc --noEmit clean

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 12:21:49 -07:00
Hongming Wang
4cac4e7710 fix(canvas): wire SaaS Sign-out button — POST /cp/auth/signout was unreachable from the UI
Reported externally on 2026-05-05: "SaaS app logout does not work."

Root cause: the control plane has had POST /cp/auth/signout (clears the
WorkOS session cookie + revokes at the provider) since auth shipped,
but no canvas code ever called it. grep across canvas/ for
`logout|signOut|signout|sign-out` returned zero results — no helper,
no button, no menu entry. Users had no path to log out short of
clearing cookies in DevTools.

This is a UI gap, not a backend bug. Adding the missing pieces:

1. `signOut()` helper in `canvas/src/lib/auth.ts`:
   - POST /cp/auth/signout with credentials:include (cross-origin
     cookie required for tenant subdomain → app subdomain)
   - Best-effort: a 5xx, 401-stale-cookie, or network failure still
     redirects the browser to /cp/auth/login. Leaving the user on an
     authed-looking page after they clicked Sign out is the worst
     possible UX — that's the precise "logout doesn't work" symptom
     the report described.
   - Lands on /cp/auth/login (not the current URL) so the user
     doesn't loop back into the org they just left via AuthGate's
     return_to.

2. `AccountBar` component on /orgs page Shell — renders the signed-in
   email + Sign-out button at the top. Click → signOut() →
   `Signing out…` → bounces to login. Disabled-while-pending so a
   double-click can't fire two requests.

3. Tests in `auth.test.ts` (4 new, total 12 pass):
   - POSTs to the right endpoint with credentials:include
   - Redirects to /cp/auth/login after success
   - Redirects EVEN ON network failure (the critical UX invariant)
   - Redirects on 401 (stale cookie path)

The auth-origin resolution (`getAuthOrigin`) is reused so a tenant
subdomain (acme.moleculesai.app) correctly POSTs to
app.moleculesai.app/cp/auth/signout — same chain that fetchSession
+ redirectToLogin already use.

Test plan:
- [x] `npx vitest run src/lib/__tests__/auth.test.ts` — 12/12 green
- [x] `tsc --noEmit` — clean
- [ ] Manual: navigate to /orgs, click Sign out, observe redirect +
      that the next /orgs visit bounces to login (cookie cleared)
- [ ] CI green

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 12:20:18 -07:00
Hongming Wang
a489ee1a7c fix(canvas/chat): instant-scroll to bottom on first mount
Reported: "right now when chat box opens it opens in the middle, but
it should be at the end of conversation."

Root cause: ChatTab.tsx:548 fires `bottomRef.scrollIntoView({ behavior:
"smooth" })` on every messages-update. On initial mount with N
messages already loaded, the smooth-scroll triggers a ~300ms animation
that any concurrent React re-render (agent push landing, theme
toggle, sidepanel resize) interrupts mid-flight, leaving the user
stuck somewhere in the middle of the conversation.

Fix: track first-mount via hasInitialScrollRef. Use behavior:"instant"
for the initial jump (deterministic, no animation interruption), then
smooth for subsequent appends (the new-message-landing visual stays).

Refs flipped on first messages.length > 0 transition, so:
- Initial open of chat tab: instant jump to bottom ✓
- New agent message arrives: smooth scroll into view ✓
- Workspace switch (ChatTab remounts): fresh hasInitialScrollRef, gets
  instant again ✓
- loadOlder prepend: anchor-restore path unchanged, still pins user's
  reading position ✓

Test plan:
- pnpm test --run ChatTab.lazyHistory.test.tsx → 8 pass (existing
  lazy-history tests untouched)
- npx tsc --noEmit clean
- Manual on hongming.moleculesai.app: open a busy chat (mac laptop,
  ~50 messages), confirm view lands at the latest bubble, not mid-
  scroll. Switch to another workspace + back → instant again.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 10:47:32 -07:00
Hongming Wang
7644e82f2f feat(saas): default new workspaces to T4 on SaaS, T3 self-hosted
User reported every SaaS workspace defaults to T2 (Standard). Three
sites quietly disagreed on the default:

- canvas CreateWorkspaceDialog (line 126): isSaaS ? 4 : 3   ← only correct one
- canvas EmptyState "Create blank":      tier: 2            ← hardcoded
- workspace.go POST /workspaces:         tier = 3           ← not SaaS-aware
- org_import.go createWorkspaceTree:     tier = 2 (fallback)← not SaaS-aware

So a user clicking "+ New Workspace" via the dialog got T4 on SaaS,
but a user clicking "Create blank" on the empty canvas got T2, and an
agent POSTing /workspaces directly got T3. Same tenant, three different
tiers depending on entry point.

Fix:

1. WorkspaceHandler.IsSaaS() and DefaultTier() helpers (workspace_dispatchers.go).
   IsSaaS() := h.cpProv != nil — single source of truth for "are we
   SaaS" across the file. DefaultTier() returns 4 on SaaS, 3 on
   self-hosted. SaaS rationale: each workspace runs on its own sibling
   EC2 so the per-workspace tier boundary is a Docker resource limit
   on the only container present — no neighbour to protect from. T4
   matches the boundary.

2. workspace.go now defaults tier via h.DefaultTier() instead of
   hardcoded T3.

3. org_import.go fallback (when neither ws.tier nor defaults.tier set)
   becomes SaaS-aware: T4 on SaaS, T2 on self-hosted (preserve the
   existing safe-shared-Docker-daemon default for self-hosted org
   imports).

4. canvas EmptyState "Create blank" stops sending tier:2 in the body
   and lets the backend pick — single source of truth in the backend.
   Eliminates the third disagreement.

Test plan:
- go vet ./... clean
- go test ./internal/handlers/ -count 1 — all green (4.3s)
- npx tsc --noEmit on canvas — clean
- Staging E2E (after deploy): create a fresh workspace via canvas
  empty-state on hongming.moleculesai.app, confirm tier=4 on the
  workspace details panel.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 10:30:22 -07:00
Hongming Wang
191ef3be91 fix(canvas/tests): pin Expand-to-Team absence with literal assertion
Multi-model review of #2862 caught a non-load-bearing assertion: the
test used \`expect(labels).not.toContain(expect.stringMatching(...))\`
to claim the "Expand to Team" right-click item is gone. But vitest's
toContain uses Object.is/===, so asymmetric matchers like
expect.stringMatching are plain objects that never === any string —
the assertion silently passed for ANY string array, including arrays
that DID contain "Expand to Team". The test would have green-lit the
unfixed code.

Switch to the literal substring shape the rest of this file already
uses (see lines 175/183/254 — labels.some((l) => l.includes(...))).

Verified the new assertion is load-bearing:

  1. Reintroduced \`{ label: "Expand to Team", ... }\` into the
     childless-workspace branch of ContextMenu.tsx
  2. Ran the test — failed at the new assertion line as expected
  3. Reverted the regression — test passes again

Net diff: replaces one broken expect with one correct expect + a
WHY-comment noting the toContain/asymmetric-matcher gotcha so the
next reader (or test writer) doesn't reintroduce the same shape.

Per memory feedback_assert_exact_not_substring.md: pin assertions
that fail on the old code path; this assertion never fired even on
the bug it was written to catch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 03:05:17 -07:00
Hongming Wang
a959feae84
Merge branch 'staging' into chore/remove-canvas-expand-button 2026-05-05 02:52:28 -07:00
Hongming Wang
49027af419 chore(canvas): remove Expand-to-Team right-click button (#2858)
Pairs with PR #2856 which removed the backend POST /workspaces/:id/expand
route. With the backend gone, the canvas right-click "Expand to Team"
button calls a 404. Remove the button and its callback.

ContextMenu.tsx:
  - Delete handleExpand callback (8 lines)
  - Drop the "Expand to Team" item from the childless-workspace menu
    array; childless workspaces now only show the regular actions
    (Extract from Team / Export Bundle / Duplicate / Pause / Restart /
    Delete).

Toolbar.tsx:
  - Drop "expand," from the right-click help-text shortcut.

ContextMenu.keyboard.test.tsx — two new pinning cases:
  - "'Expand to Team' menu item is gone (childless workspace)" —
    asserts the label literal is absent + the regular actions
    (Delete, Restart) are still present.
  - "'Collapse Team' is still present when the workspace HAS children" —
    sanity that the parent-with-children menu (Arrange Children /
    Collapse Team / Zoom to Team) didn't regress.

How users create children now: the existing + New Workspace dialog
(CreateWorkspaceDialog.tsx) already has a parent picker. No new UI
needed — every workspace can be a parent via the regular Create
flow with parent_id set.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-05 02:51:13 -07:00
Hongming Wang
d175d0c4c1
Merge branch 'staging' into feat/canvas-chat-lazy-load-history 2026-05-05 02:22:38 -07:00
Hongming Wang
b375252dc8 feat(external): credential rotation + re-show instruction modal (#319)
External workspaces (runtime=external) lose their workspace_auth_token
the moment the create modal closes — the token is unrecoverable from
any later DB read. Operators who lost their copy or want to respond to
a suspected leak had no recovery path short of recreating the workspace
(which also breaks cross-workspace delegation links + memory namespace).

This PR adds two endpoints + a Config-tab section that surfaces them:

  POST /workspaces/:id/external/rotate
    Revokes any prior live tokens, mints a fresh one, returns the same
    ExternalConnectionInfo payload Create returns. Old credentials stop
    working immediately — the previously-paired agent will fail auth on
    its next heartbeat (~20s).

  GET /workspaces/:id/external/connection
    Returns the connect block with auth_token="". For the operator who
    just needs to re-find PLATFORM_URL / WORKSPACE_ID / one of the
    snippets without invalidating the live agent.

Both reject runtime ≠ external with 400 + a hint pointing at /restart
for non-external runtimes (which mints AND injects into the container).

## Why a flag isn't needed

The endpoints are purely additive — Create's behavior is unchanged.
Existing external workspaces don't see anything different until an
operator clicks the new buttons.

## DRY refactor

Extracted BuildExternalConnectionPayload() in external_connection.go
as the single source of truth for the connect payload shape. Create,
Rotate, and GetExternalConnection all call it. Adds a snippet once →
all three endpoints emit it. Trims trailing slash on platform_url so
no double-slash sneaks into registry_endpoint.

## Canvas

ExternalConnectionSection mounts in ConfigTab when runtime=external.
Two buttons:
  - "Show connection info" (cosmetic) — fetches GET /external/connection
  - "Rotate credentials" (destructive) — confirm dialog explains the
    impact, then POST /external/rotate

Both reuse the existing ExternalConnectModal so operators don't learn
a second snippet UX.

## Coverage

10 Go tests:
  - Rotate happy path (revoke + mint order, payload shape, broadcast event)
  - Rotate refuses non-external runtimes (400 with restart hint)
  - Rotate 404 on unknown workspace + 400 on empty id
  - GetExternalConnection happy path (auth_token="", same payload shape)
  - GetExternalConnection refuses non-external + 404 on unknown
  - BuildExternalConnectionPayload — placeholder substitution + trailing
    slash trimming + blank-token contract

6 canvas tests:
  - both action buttons render
  - "Show" calls GET /external/connection and opens modal
  - "Rotate" opens confirm dialog before firing POST
  - Cancel dismisses without rotating
  - Confirm POSTs and opens modal with returned token
  - API failures surface as visible error chips

Migration: existing external workspaces gain new abilities; no data
migration. The DRY refactor preserves byte-identical Create response
shape (8 ConfigTab tests + all existing handler tests still pass).

Closes #319.
2026-05-05 01:55:27 -07:00
Hongming Wang
cbe48c2225 feat(canvas/memories): Add + Edit modal for MemoryInspectorPanel
The Memory tab was read-only — users could see and Delete entries but
the only path to write was leaving canvas. Adds a + Add button (toolbar,
next to Refresh) and an Edit button (per-entry, next to Delete) that
share one MemoryEditorDialog.

Add:  POST /workspaces/:id/memories with {content, scope, namespace}
Edit: PATCH /workspaces/:id/memories/:id (sibling endpoint #2838)
       with only fields that changed; no-op edits short-circuit
       client-side so we don't waste a redactSecrets + re-embed pass

Edit mode locks scope (cross-scope moves go through delete + recreate
to keep the GLOBAL audit-log + redact pipeline single-purpose).

Tests: 6 cases on the dialog covering POST shape, PATCH-only-diff,
no-op short-circuit, empty-content guard, save-error keeps modal open,
and namespace+content combined PATCH. Existing 27 MemoryInspectorPanel
tests still pass with the new prop wiring.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 21:16:35 -07:00
Hongming Wang
4c9309e801 fix(canvas/chat): tag scroll anchor + token-guard fetches (race fixes)
Multi-model review of #2826 found two issues my self-approval missed:

C1. Live agent-message append during loadOlder() yanked scroll AND
    swallowed the bottom-pin. The useLayoutEffect's "restore against
    saved distance-from-bottom" branch fired on ANY messages update
    while scrollAnchorRef was set — including appends from agent pushes
    that landed mid-fetch. User reading mid-history got thrown to a
    stale offset; the new agent message's normal scroll-to-bottom was
    silently swallowed.

    Fix: tag scrollAnchorRef with `expectFirstIdNotEqual` (the oldest
    message's id BEFORE the prepend). The layout effect only honors
    the anchor when messages[0].id has changed from that tag — i.e.,
    a real prepend happened, not an append.

R4. Workspace switch mid-fetch leaked the in-flight promise's result
    into the new workspace's state — user briefly saw someone else's
    history. Same shape for a fast-clicked Retry button or rapid
    scroll-flick triggering a second loadOlder.

    Fix: `fetchTokenRef` monotonic counter. loadInitial + loadOlder
    each capture their token at entry; the .then() bails if the
    token has moved. Both call sites bump the token at fetch start
    so any in-flight stale fetch loses identity.

C2 (loadOlder identity stability via refs) and R3 (inflightRef
synchronous double-entry guard) were already pushed in the previous
commit on this branch.

Build + 1258 tests pass.
2026-05-04 20:42:29 -07:00
Hongming Wang
20f76c4fdf fix(canvas/chat): stable IntersectionObserver + inflight guard for loadOlder
Self-review of the lazy-load PR caught three Important findings:

1. IO observer was re-armed on every messages change. The previous
   loadOlder useCallback depended on `messages`, so every live agent
   push recreated it → re-ran the IO useEffect → tore down + re-armed
   the observer. In a perf PR shipping to chat-heavy users, that's
   the wrong direction. Fix: refs for the captured state
   (oldestMessageRef, hasMoreRef), narrow loadOlder deps to
   [workspaceId], and gate the IO effect on `messages.length > 0`
   (boolean) instead of `messages` so it arms exactly once when data
   first lands and stays armed across appends.

2. loadingOlder setState race. Two IO callbacks dispatched in the
   same microtask (fast scroll, layout shift) could both pass the
   `if (loadingOlder)` guard before React committed setLoadingOlder.
   Fix: synchronous inflightRef set BEFORE any await, cleared in
   finally; loadingOlder state stays for the UI label only.

3. Retry-button onClick duplicated the mount-effect body. Single
   loadInitial() callback now serves both, eliminating the drift
   hazard.

Coverage:
- 4 new tests bring the file to 8/8 (was 4):
  - loadOlder fetches with limit=20 and before_ts=oldest.timestamp
  - inflight guard rejects three concurrent IO triggers while a
    deferred fetch is in flight (asserts call count stays at 2,
    not 5)
  - empty older response unmounts the sentinel (proxy for the
    anchor-clearing branch in loadOlder)
  - IO observer instance survives three subsequent prepends — same
    object reference both before and after, no churn
- Both behavioural tests verified to FAIL on the prior code
  (stashed ChatTab.tsx, ran them alone, confirmed both red), then
  PASS on this commit. Pinning real regressions, not tautologies.
- IntersectionObserver fake captures instances + exposes
  triggerIntersection() so the IO callback can be driven directly
  from jsdom (no real layout / scrolling needed).

Test: vitest run src/components/tabs/__tests__/ → 39 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 20:38:37 -07:00
Hongming Wang
ba63f76e10 feat(canvas/terminal): not-available banner for runtimes without a TTY
Pre-fix TerminalTab tried to open /ws/terminal/<id> for every workspace
including external ones (which have no shell endpoint on the
workspace-server). The server returned 404, status flipped to "error",
the user saw "Connection failed" with a Reconnect button — reading as
a bug when really the runtime intentionally has no TTY.

Now: when data.runtime is in RUNTIMES_WITHOUT_TERMINAL (currently just
"external"), TerminalTab renders a NotAvailablePanel with a big
terminal-off icon and a one-line explanation including the runtime
name. The xterm + WebSocket dance is skipped entirely — no spurious
404s, no scary error UI, no Reconnect that can't help.

The runtime is determined from the data prop now threaded by
SidePanel.tsx (existing pattern for ChatTab/ConfigTab/etc).

Tests: 4 new in TerminalTab.notAvailable.test.tsx pin: external
renders banner with runtime name, external doesn't open WS, claude-
code mounts normally (regression cover for the early-return scope),
data omitted falls through (back-compat).

Build clean. 1258 tests pass.
2026-05-04 20:33:13 -07:00
Hongming Wang
8152cfc81e feat(canvas/chat): lazy-load history — 10 newest on mount, 20 per scroll-up batch
Pre-fix ChatTab fetched the newest 50 messages on every mount and
scrolled to bottom, paying full DOM cost up-front even when the user
only wanted to read the last few bubbles. On a long-running workspace
this meant 50× message-bubble paint + DOM cost on every tab swap.

Now:
  - Initial fetch limit=10 (newest-first slice).
  - IntersectionObserver on a top sentinel (rootMargin 200px) fires
    loadOlder() the moment the user scrolls within 200px of the top.
  - loadOlder() uses the oldest loaded message's timestamp as
    `before_ts` (RFC3339 cursor the /activity endpoint already
    supports) and fetches OLDER_HISTORY_BATCH (20) more.
  - hasMore turns false when the server returns < limit rows; the
    sentinel unmounts and the IO observer disconnects — no spinner
    on a short conversation.
  - useLayoutEffect handles scroll behavior across messages updates:
    a prepend (loadOlder landed) restores the user's saved
    distance-from-bottom (captured via scrollAnchorRef before the
    fetch) so their reading position doesn't jump; an append /
    initial load pins to the latest bubble.

Tests: 4 new in ChatTab.lazyHistory.test.tsx pinning the limit=10
on initial fetch, hasMore=false on short-history, full-page rendering
on exactly-the-limit, and limit=10 on retry-after-failure. Doesn't
exercise the IO/scroll-anchor in jsdom — that's brittler than
trusting the synth-canary against a live tenant.

Build clean. Existing 1250 tests + 4 new = 1254 pass.
2026-05-04 20:12:01 -07:00
Hongming Wang
beab899501 feat(ConfigTab): drop Skills/Tools tag inputs, give Prompt Files its own section
User feedback (2026-05-04 conversation):
> "Skills and Tools are having their own tab as plugin, and Prompt
> Files are in the file system which can be directly edited. Am I
> missing something?"
> "Tools should be merged into plugin then, and for prompt files... it
> should be in another section than in skill& tools"

The "Skills & Tools" section in ConfigTab had three TagList inputs:
  - Skills:       managed via the dedicated SkillsTab (per-workspace
                  skill folders) — duplicate UI affordance
  - Tools:        managed via the Plugins tab (install a plugin → its
                  tools become available) — duplicate UI affordance
  - Prompt Files: load order for system-prompt files — semantically
                  unrelated to skills/tools

Drop the Skills + Tools inputs. Move Prompt Files into its own
section with explanatory copy that names the auto-loaded files
(system-prompt.md, CLAUDE.md, AGENTS.md) and points users at the
Files tab for actual editing.

Schema fields `config.skills` and `config.tools` are KEPT (load-bearing
for runtime skill loading + tool registry); only the inline editor goes
away. Operators who need to edit them can still use the Raw YAML toggle.

Tests:
- New ConfigTab.sections.test.tsx with 4 cases:
  1. "Skills & Tools" section title is gone
  2. Skills tag input is absent
  3. Tools tag input is absent
  4. Prompt Files section exists with explanatory copy

Sibling ConfigTab tests (hermes, provider) all still pass (20/20).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 20:02:05 -07:00
Hongming Wang
4ea6f437e9 feat(external-templates): codex tab now includes the bridge-daemon inbound path
The codex tab in the External Connect modal had a "outbound-tools-only
first cut" caveat — operators got the MCP wiring for codex calling
platform tools, but there was no documented inbound path. Canvas
messages couldn't wake an idle codex session.

That gap is now filled by codex-channel-molecule
(github.com/Molecule-AI/codex-channel-molecule), shipped today as the
codex counterpart to hermes-channel-molecule. The daemon long-polls
the platform inbox, runs `codex exec --resume <session>` per inbound
message, captures the assistant reply, routes it back via
send_message_to_user / delegate_task, and acks the inbox row.
Per-thread session continuity persisted to disk so daemon restarts
don't lose conversation context.

This commit:
- Updates externalCodexTemplate to include `pip install
  codex-channel-molecule` (step 1) and a foreground `nohup
  codex-channel-molecule` invocation (step 3) using the same env-var
  contract as the MCP server (WORKSPACE_ID + PLATFORM_URL +
  MOLECULE_WORKSPACE_TOKEN).
- Adds a "Canvas messages don't wake codex" common-issues entry to the
  TAB_HELP codex section pointing at the bridge daemon log.
- Updates the doc comment to record the upstream deprecation path:
  when openai/codex#17543 lands, the bridge becomes redundant and the
  wired MCP server delivers push natively.

Verified: TestExternalTemplates_NoMoleculeOrgIDPlaceholder still
passes (no MOLECULE_ORG_ID re-introduction); full handlers suite
green.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 18:28:35 -07:00
Hongming Wang
5559e96400 Merge branch 'temp-staging' into try-merge
# Conflicts:
#	tests/e2e/test_staging_full_saas.sh
2026-05-04 16:34:55 -07:00
Hongming Wang
2f7beb9bce feat: drop shared_context — use memory v2 team namespace instead
Parent → child knowledge sharing previously lived behind a `shared_context`
list in config.yaml: at boot, every child workspace HTTP-fetched its parent's
listed files via GET /workspaces/:id/shared-context and prepended them as
a "## Parent Context" block. That paid the full transfer cost on every
boot regardless of whether the agent needed it, single-parent SPOF, no team
or org scope, and broken if the parent was unreachable.

Replace with memory v2's team:<id> namespace: agents call recall_memory
on demand. For large blob-shaped artefacts see RFC #2789 (platform-owned
shared file storage).

Removed:
- workspace/coordinator.py: get_parent_context()
- workspace/prompt.py: parent_context arg + injection block
- workspace/adapter_base.py: import + call + arg pass
- workspace/config.py: shared_context field + parser entry
- workspace-server/internal/handlers/templates.go: SharedContext handler
- workspace-server/internal/router/router.go: GET /shared-context route
- canvas/src/components/tabs/ConfigTab.tsx: Shared Context tag input
- canvas/src/components/tabs/config/form-inputs.tsx: schema field + default
- canvas/src/components/tabs/config/yaml-utils.ts: serializer entry
- 6 tests pinning the removed behavior; 5 doc references

Added regression gates so any reintroduction is loud:
- workspace/tests/test_prompt.py: build_system_prompt must NOT emit
  "## Parent Context"
- workspace/tests/test_config.py: legacy YAML key loads cleanly but
  shared_context attr must NOT exist on WorkspaceConfig
- tests/e2e/test_staging_full_saas.sh §9d: GET /shared-context must NOT
  return 200 against a live tenant

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 16:30:26 -07:00
Hongming Wang
3a5544a9e6 feat(memory tab): add Edit affordance with optimistic-locking
Memory tab supported only Add+Delete. Correcting an entry meant
deleting and re-adding, losing the row's version counter and any
concurrent-write guard the agent depends on.

Now: per-row Edit button reveals an inline editor (value textarea +
TTL). Save POSTs to the existing /memory upsert endpoint with
if_match_version pinned to the entry's current version. On 409 the
UI surfaces a retry hint and reloads.

Tests:
- 11 vitest cases covering pre-fill (JSON vs string), payload shape
  (parsed JSON, fallback to plain text, TTL inclusion/omission),
  cancel, 409 retry path, generic error path, and the no-version
  back-compat case.
- E2E gate 9c in test_staging_full_saas.sh: seed → GET version →
  conditional update → assert new value → stale-version POST must
  409. Pins the optimistic-locking contract end-to-end on staging.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 16:18:08 -07:00
Hongming Wang
5c80b9c3d6 feat(canvas): render misconfigured workspaces with the configuration_status from agent_card
Closes molecule-controlplane#467 (issue filed against CP, but resolution
landed canvas-side because the workspace-server ALREADY returns the
agent_card JSONB blob with configuration_status / configuration_error
fields populated by molecule-core PR #2756). No CP-side change needed —
the gap was the canvas's blindness to those fields.

Before this PR, a workspace whose adapter.setup() failed (typically
missing/rotated LLM credential) appeared identical to a healthy one in
the canvas tile: green "Online" status, no error indication. The
operator had to dig into workspace logs to discover the env var to set.

This PR surfaces the state via the existing status-pill UX:

1. STATUS_CONFIG gains a "not_configured" entry — amber dot/glow,
   "Not configured" label. Distinct from "online" (emerald) and
   "failed" (red) — the workspace is reachable, it just needs config.

2. canvas-topology exposes getConfigurationStatus / getConfigurationError
   helpers — strict equality on the JSONB field so unknown values
   pass through as null instead of crashing the tile renderer.

3. WorkspaceNode derives an `effectiveStatus` that overrides
   data.status with "not_configured" when (status === "online" AND
   agent_card.configuration_status === "not_configured"). The override
   only applies on top of "online" — a genuinely offline / failed /
   provisioning workspace keeps its existing treatment.

4. The configuration_error string surfaces in two places: the tile's
   aria-label (screen reader access) + a truncated preview row at the
   bottom of the tile (same visual as the existing "degraded error
   preview" — mirrors the established pattern for in-tile error
   surfacing).

Test coverage: 11 new in canvas-topology-configuration-status.test.ts.
Each helper covered for the happy path, missing fields, defensive
ignores of unknown values, and an end-to-end "stale ready overrides
old error" guard.

Once this lands + canvas redeploys, operators see "Not configured:
Neither OPENAI_API_KEY nor MINIMAX_API_KEY is set" right on the
workspace tile instead of a confused-looking green "online" workspace
that silently 503s every JSON-RPC request.

Pairs with: molecule-core PR #2756 (decouple agent-card from setup),
            #2775 (boot_routes pin), #2778 (secret_redactor)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 15:14:40 -07:00
Hongming Wang
e1c99cd24c Pin the visibility gate behavior, not just cadence
Self-review on PR #2723 caught a coverage gap: the existing
"visibility gate" describe block actually tested cadence (10s/30s
timing), not the gate itself. If a refactor dropped the
`if (!visible) return` line, the cadence test would still pass
because the effect would still fire every 30s — the regression would
silently ship.

New test renders with comms-returning mock so the panel renders, clicks
the close button, advances 60s, asserts no further fetches occur.

Discipline-verified: removed `if (!visible) return` from the source,
test fails as expected. Restored, test passes.

Same failure mode as PR #434 (test asserted broken behavior) — pin
what you claim to fix, not the easy substring.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 03:18:42 -07:00
Hongming Wang
26b5b21238 Fix CommunicationOverlay rate-limit storm: cap fan-out + gate on visibility
User report 2026-05-04: 8+ workspace tenant (Design Director + 6 sub-agents
+ 3 standalones) saw sustained 429s in canvas console hitting
/workspaces/<id>/activity?limit=5. Server-side rate limit is 600 req/min/IP.

Three compounding issues in CommunicationOverlay:
1. Polled regardless of visibility — collapsed panel still hammered the API
2. 10s cadence — 6 req every 10s = 36 req/min from this overlay alone
3. Fan-out cap of 6 workspaces — scaled linearly with workspace count

Fix:
- Gate setInterval on `visible` (effect re-runs when collapsed/expanded)
- Cadence 10s → 30s
- Fan-out cap 6 → 3

Combined: ~36 req/min worst case → 6 req/min worst case (6x reduction),
0 req/min when collapsed.

Tests:
- Fan-out cap: 6 online nodes mounted → exactly 3 fetches (was 6)
- Offline gate: offline workspace never polled
- Cadence: timer at 10s = no new fetch; timer at 30s = next batch fires

Each test would fail if the corresponding dial regressed.

Follow-up (out of scope): structurally right fix is to consume the
WORKSPACE_ACTIVITY WS broadcast instead of polling per-workspace. Server
already publishes the events; canvas just isn't subscribing yet.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-04 03:18:42 -07:00
Hongming Wang
32fc77bad4 fix(canvas): A2ATopologyOverlay re-fetch storm hammering /activity → 429
Selector instability caused fetchAndUpdate to recreate on every Zustand
nodes[] mutation (status flips, position drags, peer-discovery writes,
heartbeats — typically ~5/sec). Each recreation invalidated the
useEffect deps so the 60s polling fan-out fired on every update,
hammering /workspaces/<id>/activity?type=delegation 5×N requests/sec
until the edge rate-limit returned 429. User-reported via browser
console showing infinite uE→ux→uE→ux render loop and 429s repeating
across every visible workspace ID.

Root cause:
  const nodes = useCanvasStore((s) => s.nodes);
  const visibleIds = useMemo(() => nodes.filter(...).map(...), [nodes]);
  // useMemo dep recreates on every store update, even when ID set unchanged

Fix: select a STABLE STRING KEY (sorted CSV of visible IDs) from
Zustand. The selector's shallow-equal short-circuit prevents re-renders
when the actual visible-ID set is unchanged, so visibleIds reference
stays stable, fetchAndUpdate keeps its identity, and the useEffect
only re-fires when the visible-ID-set genuinely changes.

Tests:
- New regression test "does not re-fetch when nodes[] reference
  changes but visible IDs are the same"
- Discipline-verified: pre-fix code emits 4 fetches (2 mount + 2
  re-fetch storm), post-fix emits exactly 2
- Companion test "re-fetches when the visible ID set actually changes"
  pins the desired behavior so future "stabilization" doesn't suppress
  legitimate updates

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 23:39:36 -07:00
Hongming Wang
b6ff280ca3 canvas/CreateWorkspaceDialog: hover sweep + semantic placeholders + focus rings
Sweep on the workspace-creation dialog — same patterns shipped on every
other surface.

- 2× bg-accent-strong hover:bg-accent (FAB + Create) hovered LIGHTER
  on white text → bg-accent hover:bg-accent-strong + focus-visible
  rings.
- Cancel: bg-surface-card hover:bg-surface-card no-op → surface-
  elevated + focus-visible ring.
- 4× placeholder-zinc-500/600 hardcoded → placeholder-ink-soft so
  placeholders flip with theme.
- FAB shadow tinting (shadow-blue-600/20 + shadow-blue-500/30) was
  hardcoded blue with no theme variant; switched to shadow-accent so
  the glow tint matches the brand mint accent in both modes.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 22:56:33 -07:00
Hongming Wang
ff20fe4f61 canvas/{OrgImportPreflightModal,SkillsTab}: hover sweep + custom-source focus ring
OrgImportPreflightModal:
- 3× bg-accent-strong hover:bg-accent (Import + 2 add-key buttons) —
  accent is the LIGHTER variant, drops below AA on white text →
  bg-accent hover:bg-accent-strong.
- Cancel: bg-surface-card hover:bg-surface-card no-op → surface-
  elevated + focus-visible ring.

SkillsTab:
- Custom-source input had focus:border-violet-600 but no
  focus-visible ring — keyboard users only got a 1px border swap.
  Added focus-visible:ring-violet-600/50 (kept the violet to match
  the surrounding "custom install" UI's brand).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 22:28:41 -07:00
Hongming Wang
16ad941a1e canvas/{Details,Config,Activity}Tab: button hover sweep across 6 buttons
Six button fixes — same trap patterns shipped on every other tab:

DetailsTab:
- Save button: bg-accent-strong hover:bg-accent (LIGHTER on white text,
  AA drop) → bg-accent hover:bg-accent-strong + focus-visible ring.
- Confirm Delete: bg-red-600 hover:bg-red-500 (LIGHTER on white text,
  AA drop) → bg-red-700 + focus-visible danger ring.
- Cancel: bg-surface-card hover:bg-surface-card (no-op) →
  surface-elevated.

ConfigTab:
- 2× Save buttons: same accent-LIGHTER trap → flipped + focus rings.
- Cancel: same no-op → surface-elevated.

ActivityTab:
- Refresh: same no-op → surface-elevated + focus-visible ring.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 22:01:18 -07:00
Hongming Wang
0e3e2559af canvas/{Schedule,Channels}Tab: fix accent-LIGHTER hover + Cancel no-op
Three button fixes — same AA-contrast-trap pattern shipped on
OnboardingWizard, MemoryTab, ConfirmDialog, ApprovalBanner.

ScheduleTab:
- Create/Update button: bg-accent-strong hover:bg-accent (accent is
  LIGHTER, drops below AA on white text) → bg-accent hover:bg-accent-
  strong + focus-visible ring.
- Cancel button: bg-surface-card hover:bg-surface-card no-op → hover
  surface-elevated + focus-visible ring.

ChannelsTab:
- Connect Channel button: same accent-LIGHTER trap → flipped + focus-
  visible ring.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 21:33:23 -07:00
Hongming Wang
7a30af5af0 canvas/MemoryTab: fix 9 hover bugs (4 light + 4 no-op + Delete no-op)
Three matched fixes — same patterns shipped on OnboardingWizard,
ConfirmDialog, ApprovalBanner.

1. 4× bg-accent-strong hover:bg-accent (Save, Add, two Show buttons)
   hovered LIGHTER on white text — accent is the lighter variant, so
   contrast dropped below AA on hover. Flipped: bg-accent
   hover:bg-accent-strong.

2. 4× bg-surface-card hover:bg-surface-card no-op hovers (Collapse,
   Open, Hide-Advanced, Refresh, Cancel). Lift to surface-elevated
   so the buttons visibly respond.

3. Delete row button: text-bad hover:text-bad was a no-op. Switched
   to a light hover bg + focus-visible danger ring so the destructive
   action visibly responds and keyboard users see focus.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 21:06:17 -07:00
Hongming Wang
38b1af3b84 canvas/FilesTab: fix Delete-LIGHTER + Cancel no-op + alertdialog role + focus rings
Three matched fixes for the inline Delete-All and Delete-File confirm
banners — same patterns shipped on ConfirmDialog/ApprovalBanner/
DeleteCascade:

1. Delete buttons hovered LIGHTER (bg-red-500 over bg-red-600). On
   white text drops below AA contrast. Flipped to bg-red-700.

2. Cancel buttons hover was a no-op (bg-surface-card on top of
   itself). Lift to surface-elevated, matching the Cancel pattern in
   ConfirmDialog.

3. None of the four buttons had focus-visible rings. Added danger
   ring on Delete, accent ring on Cancel, with ring-offset-surface
   so the offset color matches the inline banner backdrop.

4. Wrapped both confirm banners in role="alertdialog" + aria-
   labelledby pointing to the prompt text — SR users hear the
   destructive prompt immediately instead of as ambient text.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 20:39:29 -07:00
Hongming Wang
38e0fc8ea0 canvas/TracesTab: semantic status dots + aria-expanded on row expanders
Three small UIUX fixes for the workspace Traces tab — same pattern
shipped on EventsTab.

1. Status dots were hardcoded bg-red-400 / bg-emerald-400 — semantic-
   token misses. Switched to bg-bad / bg-good so they pin to the
   canvas-wide ramp instead of Tailwind raw tones.

2. Trace expander rows had no aria-expanded — SR users heard a
   generic "button" with no toggle indication. Added aria-expanded
   + aria-controls pointing to the detail panel id.

3. Refresh + each expander button now carry focus-visible:ring-accent
   so keyboard users see where focus lands. Both were hover-only
   before.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 20:12:21 -07:00
Hongming Wang
90b561add0 canvas/TerminalTab: semantic status colors + accent Reconnect button
Three small UIUX fixes for the workspace terminal status bar.

1. Status dots were hardcoded bg-green-500 / bg-yellow-500 /
   bg-red-500 / bg-zinc-500 — semantic-token misses. Switched to
   bg-good / bg-warm / bg-bad / bg-ink-soft so the colors flip with
   the canvas-wide ramp instead of pinning Tailwind raw values.

2. Reconnect button used hardcoded text-blue-400 / hover:text-blue-300
   with no focus ring. Switched to text-accent / hover:text-accent-strong
   for theme parity, and added focus-visible:ring-accent/60 so
   keyboard users see where focus lands on a recovery action.

3. Error banner used text-red-400 — switched to text-bad to match the
   semantic ramp.

Status-bar bg/border kept as zinc (terminal body stays dark
unconditionally per the Canvas v4 design rule); only the chrome's
foreground tokens needed semanticisation.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 19:45:24 -07:00
Hongming Wang
6cd650f48c canvas/EventsTab: theme-flip event colors + a11y for expander rows
Four UIUX fixes for the workspace Events tab.

1. Hardcoded text-yellow-400 (DEGRADED) and text-purple-400
   (AGENT_CARD_UPDATED) didn't theme-flip — read fine in dark mode,
   washed out in warm-paper light. Switched DEGRADED → text-warm
   (the semantic warm/amber token) and AGENT_CARD_UPDATED → text-
   accent (informational metadata, accent is the right semantic).

2. Refresh button hover was a no-op (bg-surface-card on top of itself).
   Lift to surface-elevated, matching the Cancel pattern from
   ConfirmDialog. Added focus-visible ring.

3. Event expander rows had no aria-expanded — screen readers heard a
   generic "button" with no indication it toggled. Added
   aria-expanded + aria-controls pointing to the payload panel id.

4. Added focus-visible ring on each expander button. Hover bg added
   too so the active row visibly responds.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 19:17:42 -07:00
Hongming Wang
4d747de218 canvas/OnboardingWizard: theme-flip colors + fix hover traps + focus rings
Five fixes for the first-time-user wizard. Every new user sees this,
so visual bugs here have outsized impact.

1. Action button hovered LIGHTER: bg-accent-strong/90 hover:bg-accent.
   accent is the LIGHTER variant — hovering to it on white text drops
   contrast below AA. Flipped the direction: bg-accent
   hover:bg-accent-strong, matching the same trap fixed in
   ConfirmDialog and ApprovalBanner.

2. "Next" button hover was a no-op (bg-surface-card on top of itself).
   Lift to surface-elevated, matching the Cancel pattern in
   ConfirmDialog.

3. Progress bar gradient was hardcoded from-blue-500 to-sky-400 —
   neither tone exists in the warm-paper light theme, so the bar lost
   brand color in light mode. Switched to the accent ramp so it stays
   brand-tinted in both.

4. Step indicator was hardcoded text-sky-400/80, same theme-flip
   issue. Switched to text-accent.

5. All three buttons (Skip / Action / Next) had no focus-visible
   rings. Added the accent ring pattern used across the rest of
   the canvas.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 18:49:19 -07:00
Hongming Wang
3e6c7075d0 canvas/TermsGate: stop hiding the dialog from screen readers + a11y polish
Five fixes for the terms-acceptance modal:

1. CRITICAL: aria-hidden="true" on the modal's wrapper hid the dialog
   AND its descendants from screen readers. The entire ToS-acceptance
   flow was invisible to AT users. Removed the false aria-hidden — the
   wrapper is just a backdrop, the dialog inside still has role=dialog
   aria-modal=true so AT recognises it correctly.

2. Added focus management: when the modal opens, focus moves to the
   "I agree" button (WCAG 2.4.3). Hard gate so no focus-trap loop or
   Esc-dismiss — the user must accept or close the page.

3. "I agree" button hovered LIGHTER (bg-emerald-500 over bg-emerald-600).
   On white text that drops below AA — same trap fixed in ApprovalBanner
   and ConfirmDialog. Flipped to bg-emerald-700.

4. Added focus-visible ring on the "I agree" button. Was relying on
   browser default outline only.

5. Privacy/Terms links: hardcoded text-sky-400 → text-accent (theme-
   aware) + hover:text-accent-strong (was hover:text-sky-400, no-op
   same color) + focus-visible ring. Added aria-describedby pointing
   to the body div so SR can read the description with the title.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 18:21:42 -07:00
Hongming Wang
390425afbc
Merge pull request #2664 from Molecule-AI/feat/canvas-agent-comms-waiting-bubble
canvas/AgentCommsPanel: per-peer waiting-for-reply bubble
2026-05-04 01:05:08 +00:00
Hongming Wang
663c5b7e70 canvas/AgentCommsPanel: add per-peer waiting-for-reply bubble
Mirrors the bouncing-dots indicator ChatTab already shows while waiting
for an agent reply. Before this, an operator delegating to one or more
external peers via Agent Comms saw their outbound bubble land and then
silence until the reply (or queued/failed status) arrived — no visual
"the system is working on this" cue.

Per-peer not global: when multiple delegations are in flight to
different peers (the fan-out case), one shared spinner under-reports —
the user can't tell whether ALL peers are still working or just the
visible ones. Per-peer matches Slack typing-indicator semantics and
keeps the signal honest.

Detection rule: walk visible messages, keep only the chronologically-
last bubble per peer. If that tail is `flow === "out"` AND status is
"pending" or "queued", emit a waiting bubble. Once an inbound reply
lands, the tail flips to "in" and the bubble disappears — even if the
backend hasn't mutated the original outbound row to "completed" yet.
This collapses both states into one rule.

Visual: matches the outgoing bubble (cyan-900/30 + cyan-700/20 border,
right-justified) with cyan-300/70 dots that respect prefers-reduced-
motion via `motion-safe:animate-bounce`. Queued case adds copy
explaining the peer is busy. role="status" + aria-label so SR users
also hear "Waiting for reply from <peer>".

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 18:02:30 -07:00
Hongming Wang
2f89a05f2f
Merge branch 'staging' into a11y/canvas-delete-cascade-buttons 2026-05-03 17:55:48 -07:00
Hongming Wang
71fb499dee canvas/DeleteCascadeConfirmDialog: fix Cancel no-op hover + Delete light hover + focus rings
Four fixes for the cascade-delete confirmation modal:

1. Cancel button hover was a no-op: bg-surface-card on top of the
   same base — clicking did something but the button looked dead.
   Lifted to surface-elevated, matching the ConfirmDialog Cancel
   pattern.

2. Delete button hovered LIGHTER (bg-red-500 over bg-red-600). On
   white text that drops contrast below AA — same trap fixed in
   ConfirmDialog and ApprovalBanner. Flipped to bg-red-700 so hover
   stays readable in both themes.

3. Checkbox ring-offset color was zinc-900 — but the dialog actually
   sits on bg-surface-sunken, so the offset showed the wrong color
   through the ring gap. Corrected to ring-offset-surface-sunken.
   Also moved focus → focus-visible so the ring only shows on
   keyboard nav, not mouse clicks.

4. Cancel + Delete had no focus-visible rings. Added accent ring
   on Cancel, danger ring on Delete, both with the correct
   ring-offset-surface-sunken.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 17:53:29 -07:00
Hongming Wang
e5c9656016
Merge pull request #2661 from Molecule-AI/feat/external-connect-modal-help-section
feat(external-connect): fix Claude Code channel snippet + add per-tab Help section to ExternalConnectModal
2026-05-04 00:50:10 +00:00
Hongming Wang
d5eb58af56 feat(external-connect): comprehensive setup — fix Claude Code channel snippet + add per-tab Help section
User report: handing the modal's Claude Code channel snippet to an
agent fails immediately with two errors that the snippet doesn't tell
the operator how to resolve:

  plugin:molecule@Molecule-AI/molecule-mcp-claude-channel · plugin not installed
  plugin:molecule@Molecule-AI/molecule-mcp-claude-channel · not on the approved channels allowlist

Root cause: the snippet's `claude --channels plugin:...` line assumes
the plugin is pre-installed AND that the channel is on Anthropic's
default allowlist. Both assumptions are wrong for a custom Molecule
plugin in a public repo.

Two changes:

1. Rewrite externalChannelTemplate (Go) with full setup chain:
   - Bun prereq check (channel plugins are Bun scripts)
   - `/plugin marketplace add Molecule-AI/molecule-mcp-claude-channel`
     + `/plugin install molecule@molecule-mcp-claude-channel` BEFORE the
     launch — otherwise "plugin not installed"
   - `--dangerously-load-development-channels` flag on launch — required
     for non-Anthropic-allowlisted channels, otherwise "not on approved
     channels allowlist"
   - Common-errors block at the bottom mapping each error string to
     which numbered step recovers it
   - Team/Enterprise managed-settings caveat (the dev-channels flag is
     blocked there; admin must use channelsEnabled + allowedChannelPlugins)

   Plugin install info verified by reading `Molecule-AI/molecule-mcp-claude-channel`
   plugin.json (`name: "molecule"`) and the Claude Code channels +
   plugin-discovery docs at code.claude.com/docs/en/{channels,discover-plugins}.

2. Add per-tab HelpBlock to the modal (canvas):
   - Collapsible <details> below each snippet, closed by default so the
     snippet stays the visual focus
   - "Where to install" link (PyPI for runtime, claude.com for Claude
     Code, github.com/openai/codex for Codex, NousResearch/hermes-agent
     for Hermes)
   - "Documentation" link (docs.molecule.ai/docs/guides/*; hostname
     confirmed by existing blog post canonical metadata; paths map
     1:1 to docs/guides/*.md files in this repo)
   - "Common errors" list with concrete recovery steps for each tab
     (e.g. Codex tab calls out the codex≥0.57 requirement and TOML
     duplicate-table parse error; OpenClaw calls out the :18789 port
     conflict check)

   URL discipline: every URL is either (a) verified against a file path
   in this repo's docs/, (b) the canonical repo of an existing snippet
   reference, or (c) a well-known third-party canonical URL. No guessed
   URLs — broken links would defeat the purpose of "more comprehensive
   instructions."

Verification:
- `go build ./...` clean in workspace-server
- `go test ./internal/handlers/...` passes (4.3s)
- Bash syntax check on test_staging_full_saas.sh (no edits there) clean
- TS brace/paren/bracket counts balanced; no full tsc run because the
  worktree's node_modules isn't installed — counterpart Canvas tabs E2E
  on the PR will exercise the full type-check + render path

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 17:46:55 -07:00
Hongming Wang
ec54942628 canvas/BundleDropZone: theme-flip drag overlay + announce import + reduced-motion
Three small UIUX fixes for the bundle drag-import surface.

1. Drag overlay was hardcoded blue-950/blue-400 — those tones don't
   exist in the warm-paper light theme, so the overlay washed out
   inconsistently. Switched to bg-accent/15 + border-accent/40 so
   the overlay flips with theme and matches the inner card's
   border-accent/50.

2. Importing spinner was visually obvious but invisible to screen
   readers — only the result toast had aria-live. Operators relying
   on AT had no way to know the import was in flight. Added
   role="status" + aria-live="polite" + aria-hidden on the spinner
   itself so the SR hears "Importing bundle..." once.

3. animate-spin → motion-safe:animate-spin so the spinner respects
   prefers-reduced-motion (Tailwind's built-in variant gates the
   animation on the user's OS setting). Layout doesn't change in
   either case — text alone communicates state.

Also dropped border-sky-400 → border-accent on the spinner so it
matches the rest of the canvas semantics.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 17:26:15 -07:00
Hongming Wang
10f2b9f01c canvas/ConsoleModal: fix no-op hovers + add Copy success feedback
Four UIUX fixes for the EC2 console modal:

1. Copy and Close buttons had hover:bg-surface-card on TOP of the
   same base bg-surface-card — silent no-op hover. Lifted to
   surface-elevated + line-soft border, matching ConfirmDialog's
   Cancel pattern. The button visibly responds now.

2. Copy button silently succeeded — no toast, no animation, no UI
   feedback. Operators clicking it had no idea whether anything
   landed in the clipboard. Now fires showToast on resolve/reject
   so the action is observable.

3. × close button was ~10x16px (well under WCAG 2.5.5's 24x24).
   Bumped to w-6 h-6 with focus-visible ring + hover bg.

4. Added focus-visible:ring-accent/60 + ring-offset-surface to
   all three buttons so keyboard users see focus. Matches the
   semantic ring pattern used across the canvas.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:58:31 -07:00
Hongming Wang
b1a1c8e4a9 canvas/BatchActionBar: wire Esc to clear selection (matches button title)
Two small fixes for the batch-action toolbar:

1. The deselect button's title says "Clear selection (Escape)" — but
   pressing Escape did NOTHING. The title has been lying since the bar
   shipped. Now wired: window keydown handler calls clearSelection
   when Esc fires. Skipped while the confirm dialog is open
   (`pending !== null`) so the dialog's own Esc-cancels takes
   precedence, and skipped during a busy in-flight action so the
   user can't strand a partial-failure mid-flight.

2. focus-visible:ring-zinc-500/70 → focus-visible:ring-accent/50
   on the deselect button. The hardcoded zinc broke the semantic-
   token pattern used by the other action buttons.

Tests: two new vitest cases — Esc clears with selection, Esc no-op
when empty (the bar isn't mounted at count===0 so the listener never
registers). Full suite: 1222/1222.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:31:23 -07:00
Hongming Wang
24d64677ab canvas/Legend: focus rings + 24x24 close-button touch target
Two small a11y fixes for the floating legend.

1. Both buttons (open pill + close ×) had no focus-visible ring —
   keyboard users couldn't tell where focus landed. Added the
   accent-ring pattern used across the rest of the canvas.

2. Close button was a ~10x16px hit area — well below WCAG 2.5.5's
   24x24 minimum. Bumped to w-6 h-6 with negative margin so the
   visible × stays in the same spot but the hit area + focus ring
   are larger. Hover bg added to make the hit area visible on hover.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 16:04:04 -07:00
Hongming Wang
652124284b canvas/CookieConsent: stop pretending to be a modal + fix link/button focus
Three fixes for the cookie banner:

1. role="dialog" aria-modal="true" → <section role="region">. The
   banner has no focus trap, doesn't block the page, and the user
   can keep using the canvas while it's up — none of which are modal
   semantics. Claiming aria-modal="true" without a trap actively
   harms screen-reader users: they're told the rest of the page is
   inert, jump into the banner, and then can't escape. Region
   semantics let AT navigate around it normally. (Forcing a modal
   cookie banner would also be a dark pattern under GDPR.)

2. Privacy-policy link: hover:text-accent → hover:text-accent-strong.
   The original was a no-op (same color). Also added focus-visible
   ring + underline-offset so the link is readable AND keyboard-
   distinguishable in both themes.

3. Both buttons: focus-visible:ring-2 + ring-offset-surface so
   keyboard users see where focus lands. Mouse clicks unchanged
   thanks to focus-visible.

Tests: swapped getByRole("dialog") → getByRole("region") in 8
existing tests, then tightened the role-assertion test into a
regression guard that explicitly asserts NO aria-modal and NO
dialog role exist. Full suite: 1220/1220.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-03 15:37:06 -07:00