Compare commits

...
35 Commits
Author SHA1 Message Date
jason.woltje a9912983e6 fix(webui): sp7 re-check, a narrow pane wraps its header tools inside the pane, the project page's Review decision and request links keep the conversation's full view, Full view names its thread (#1873, lane sp7-polish) 2026-11-15 06:41:07 -06:00
jason.woltje 626321608f docs(webui): sp7, the Assistant's header comment names the links that keep the organization's own view (#1873, lane sp7-polish) 2026-11-15 06:28:40 -06:00
jason.woltje 5f965cdb30 fix(webui): sp7 review shots, a pane header keeps its title, Full view, Messages and close on one row with the organization and project below (#1873, lane sp7-polish) 2026-11-15 06:27:19 -06:00
jason.woltje 8296d33100 fix(webui): sp7 review round, each pane links its thread's full view in one plain click, a requirement's Open conversation keeps the organization's own view, the gated-pill assertion matches its text (#1873, lane sp7-polish) 2026-11-15 06:24:39 -06:00
jason.woltje 69ac78b97e fix(webui): sp7 shots round, a pane header keeps its close button on one line, and a thread that was not opened is said as a warning (#1873, lane sp7-polish)
- assistant.css: the pane title shrinks before the header tools wrap, so the close button stays on the title's line at 1440.
- assistant.js: paintNote draws the line under the lead; a refusal marks it data-refused and the line shows in the warning colour until the next change clears it.
- assistant-threads browser test: the refusal line carries data-refused, and closing a pane clears it.
2026-11-15 06:03:06 -06:00
jason.woltje a2a7df73df fix(webui): sp7 polish, a system page names itself once, thread links open as Assistant panes, each pane links its organization's messages, resume is a small control, Inbox class chips use words, a stopped organization's page has one restart (#1873, lane sp7-polish)
- A system page with nothing above it in the trail hides the trail that repeats its h1; drill-in trails stay.
- A project's thread link and each open-in-chat link add that thread as a pane on #/assistant. With three
  open, the first pane without an unsent message is replaced; when all three hold one, nothing is
  replaced and the page says why. Per-org chat addresses still work typed or pasted.
- "Messages in <org>" moves from the bar into each pane header as a link.
- The pane composer's Resume assistant is a small secondary control; behaviour unchanged.
- Inbox class chips read the one map of decision classes to words.
- Removes the unused pane, idPrefix and views params from projects.js and workspace.js; fixes the stale
  comment on the held-message status line.
- While an organization's bus is down, the header draws no bus control; the down banner's restart is the one.
2026-11-15 05:55:26 -06:00
jason.woltje 789e2bcdd4 fix(webui): sp6 third review round, a held message line stays steady between polls, only a pane's latest render decides the line, the held preview cuts on whole characters (#1873, lane sp6-threads) 2026-11-15 05:02:28 -06:00
jason.woltje 02df2a3a25 fix(webui): sp6 re-check notes, a held message is never overwritten or held out of sight, and a pane whose organization left the list does not promise it comes back (#1873, lane sp6-threads)
The held draft goes back only into an empty composer and is cleared only once it is in it. A thread
that reads without a composer shows the held message in the pane's line. Only a stopped or
unavailable bus says the message comes back when the pane reads again.
2026-11-15 04:57:37 -06:00
jason.woltje b982404963 fix(webui): sp6 review round, a stopped organization's pane stops reading and keeps its unsent message, an open pane picks up new replies on its own, a pasted thread id in any case shows its pane (#1873, lane sp6-threads)
A pane whose organization's bus is stopped or unavailable no longer polls or offers Refresh; it says
nothing is read until the bus starts again, holds any typed draft, and restores it untouched when the
bus returns. Unsent pane drafts now count for the organization-switch and Console-restart guards.
The Assistant sidebar item drops the Messages unread badge. "Start thread" is the primary action.
Tests cover the stopped pane's draft, a reply arriving with no refresh, and an uppercase show id.
2026-11-15 04:51:23 -06:00
jason.woltje 5dd940165d feat(webui): sp6, the Assistant page holds up to three threads from any organization side by side, with the open set in the address (#1873, lane sp6-threads)
The sidebar Assistant opens one system page, #/assistant. Each pane is the
chat thread view of its own organization: it reads, sends and updates
through that organization's routes, with a header carrying the title, the
organization chip, the project chip and a close control. "Open thread"
lists the threads of every answering organization, grouped by organization,
and starts a new thread in a chosen one. The open set and its order live in
the hash (open=org:id,...&show=org:id), validated on read. A stopped
organization is named at the top and in its own pane; the other panes keep
working. At 390 one pane shows with a tab strip.

Side by side is removed (panes.js, panes.css and its test); its old address
lands on the Assistant page.
2026-11-15 04:37:52 -06:00
jason.woltje ed4f45ed23 fix(webui): sp4 third review round, a move still writing never paints the board over the not-on-your-list page, an archived project keeps its filter while another filter matches none of its tasks (#1873, lane sp4) 2026-11-15 03:54:28 -06:00
jason.woltje 79df01f1de fix(webui): sp4 second review round, a project filter stays while its organization does not answer, a gone filter is cleaned only from the address its read started on, a read in flight never paints over the not-on-your-list page (#1873, lane sp4) 2026-11-15 03:54:28 -06:00
jason.woltje d7b98b4698 fix(webui): sp4, an organization's own task board with no filter on no longer says its tasks match the filters (#1873, lane sp4)
The scope's org= in the workspace read is where the board reads, not a filter, so the
count line and the empty state no longer treat it as one. Found in the retaken shots.
2026-11-15 03:54:28 -06:00
jason.woltje 0f29fe0d92 fix(webui): sp4 review round, one organization chip per card with its avatar, a filter that is gone leaves the address, an impossible organization address is not the system board (#1873, lane sp4)
- The card's organization chip carries the avatar in place of its dot; the bare avatar
  before it is gone (prototype shot 13).
- A filter naming an organization or project that is not on the list is dropped from the
  address after the render, and a dropped project reads again without its server filter.
- #/orgs/<id>/tasks with an id no organization can have says "This organization is not
  on your list." instead of showing every organization's tasks.
- The write check's comment and the test's fake say orgSetup is Console-wide today.
2026-11-15 03:54:28 -06:00
jason.woltje 32be3a01bc feat(webui): one task board for every organization, with organization and project filters in the address (#1873, lane sp4)
#/tasks is a system route that shows every organization's tasks on one board,
with the per-organization columns, organization and project chips on each card,
and the organization and project filters kept in the address. An organization
that did not answer is named first with its reason. A move or edit goes to the
row's own organization and is offered only where that organization's own config
takes task changes. #/orgs/<id>/tasks is the same board scoped to one
organization, and a card opened from the system board links to its task there.
A render replaced by a newer one now draws from that newer read instead of
throwing on an empty board.
2026-11-15 03:54:28 -06:00
jason.woltje f97e0d3aeb fix(webui): sp5 re-check notes, a late named Fire leaves a newer Fire's busy state alone, the picked agent row gets the left bar, tests for the picked agent with the state filter and a refused scope (#1873, lane sp5) 2026-11-15 03:32:32 -06:00
jason.woltje eebdb2f0ce fix(webui): sp5 review round, Open addresses the agent and the scoped page marks it, Fire words name the organization, a named Fire keeps its outcome, Cancel restores focus (#1873, lane sp5)
- Open on #/agents goes to #/orgs/<id>/agents?agent=<key>; the scoped table puts that agent first,
  marks it (aria-current) and draws no Open or Actions column (review F1, F2).
- Fire's aria-label, confirm group and receipt use the organization's label (F5).
- A Fire sent to a named organization keeps its receipt after the opened organization changes (F7).
- Cancel moves focus back to the row's Fire (F10).
- agentsPage refuses a scope that is not an organization id instead of listing every organization (F11).
2026-11-15 03:26:18 -06:00
jason.woltje 5373b110ac feat(webui): one Agents page for the whole system, with organization and state filters, Fire sent to the row's organization (#1873, lane sp5)
#/agents lists every organization's agents in one table: name, role, state,
what each works on, organization and project chips. Org and state filters
live in the hash query. A stopped organization is named at the top. A row
opens the agent in its organization; Fire is drawn only where that
organization's own config lets this Console decide, and posts to that
organization's hire route. #/orgs/<id>/agents leads with the same table
scoped to one organization, above the levels grid and held roles. A hired
agent reads as Hired (or Hired from pack X) with its org:hire id as
secondary text. The sidebar and dashboard Agents links open the system page.
2026-11-15 03:13:54 -06:00
jason.woltje 3885f4628b fix(webui): sp3 second review round, #/inbox keeps the system theme, hire links follow each organization's own decide (#1873, lane sp3) 2026-11-15 02:09:04 -06:00
jason.woltje ba9933309b fix(webui): sp3 review round, answers from the system Inbox read route_to and show who raised them, the hire form is linked, the sidebar count stays system-wide (#1873, lane sp3) 2026-11-15 01:10:13 -06:00
jason.woltje 0785af8129 feat(webui): one Inbox for the whole system, with organization filters and answers pinned to the row's organization (#1873, lane sp3)
#/inbox lists every answering organization's decisions from the one GET /api/workspace read, newest
first, each row with its organization chip and a project chip when it has one. Organization and
type filters live in the hash query. A stopped organization is named at the top with its reason.
An answer from the list reads and posts to the row's own organization (/api/orgs/<org>/...), never
the one opened last, and each item can be opened in its own organization. #/orgs/<id>/inbox is the
same list filtered to that organization. No server route was added.
2026-11-15 01:10:13 -06:00
jason.woltje d1b01329bc fix(webui): sp2 polish, an organization's bare address opens its page and the dashboard keeps the system theme (#1873, lane sp2)
- #/orgs/<id> with no page and no trailing slash now opens #/orgs/<id>/organization instead of the
  system dashboard.
- The system dashboard resolves its own appearance (this browser's choice made
  there, else the default) under mosaic-console-appearance-system; it no
  longer shows the theme of the organization opened last.
- A stopped organization's page shows one bus banner: the page's own down
  banner now carries the restart action, and the shell's "Bus unavailable"
  banner hides on that page (display.js paintBus and app.js busDown).
- The dashboard row for a stopped organization no longer repeats "the bus is
  not running" under "bus stopped"; the last start time still shows.
- Organizations table figures keep to one line (white-space, no font change).
- The Active agents status cell was class "st", which picked up the global
  .st::before "?" glyph; it is now ws-st.
- Tests: red-first browser tests for each item, plus the test sp1 lacked: a
  read still in flight at an organization switch keeps nothing.
- org-switch-browser: a stopped organization's page asserts one banner; the
  shell's "Bus unavailable" is checked on its tasks page instead.
2026-11-15 00:44:18 -06:00
jason.woltje c7aecbffa9 fix(webui): sp1 second review round, a read or file save in flight at a switch keeps nothing (#1873, lane sp1)
The second review found two paths the first fix round left open.

- The project-file save captures orgEpoch before its POST. When a switch
  happened meanwhile, it neither paints nor announces the old file's
  outcome on the new organization's page. An opaqueredirect still signs out.
- A live read (reader, get.api), the palette's inbox and tasks reads and
  the board poll keep their answer in `last` only while the organization
  they were sent for is still open. A later cached render on the new
  organization no longer draws the old one's rows.

single-pane test 11 holds acme's file save across a switch to beta and
asserts nothing is announced: red on the previous bus.js ("Saved as commit
cccccccccccc."), green now. The kept-read guard has no browser test.
2026-11-14 23:51:59 -06:00
jason.woltje bb2f79f3d9 fix(webui): sp1 review round, a switch carries nothing across and first run keeps its board (#1873, lane sp1)
- First run (no organization yet) keeps #/ as its board; the router no longer rewrites it to
  #/dashboard, which first run cannot draw.
- An organization switch stops the agents section's request poll and clears what it held. A
  route-change restart chain finishes on the organization it started in.
- A write in flight at a switch drops its answer: an org epoch in bus.js, checked after each
  await. The switch clears every busy flag, receipt and reply, and the doc drafts.
- The bus banner reads org state again only when the route crosses /dashboard, not on every
  hashchange inside one organization.
- The down banner does not repeat its heading as the reason.
- Tests: first run wordmark, poll stop on switch, restart pinned to its organization, settings
  save in flight at a switch, banner without a repeated reason. The org-switch test comment and
  wait match the in-place switch.
2026-11-14 23:19:05 -06:00
jason.woltje e24e7e93a2 feat(webui): one shell, a system dashboard, organization pages as drill-ins (#1873, lane sp1)
#/dashboard is the system landing route: one row per organization with its bus
state, agent count (organization files), project count and needs-you count,
each only when a read gave it, and active agents. Opening an organization from
the sidebar or a dashboard row is a route inside the same page: no reload, a
Dashboard / <organization> breadcrumb, and later /api reads scoped to it through
the existing fetch wrapper, whose organization is now a variable the router sets
(mosaic-org-switch event). #/orgs/<id>/... stays the address. An organization
whose bus is down says so on the dashboard and on its page, with the reason the
workspace read gives.
2026-11-14 22:35:00 -06:00
jason.woltje 387f73a7a4 fix(harness): r127 review round, only a shell's own not-found line names a program (#1873, lane r127)
Review P3-1: a "No such file or directory" line from another program
(cat, ls) no longer counts. Only bash's "line N:", dash's "N:" and env's
quoted form do.
P3-2: a name with a run of 16 letters and digits looks like a key, so it
stays in the run's private stderr instead of the reply.
P3-3: a 16 KiB stderr window that starts mid-file drops its partial first
line, so a cut name ("aude") isn't reported.
P3-4: CRLF lines read the same as LF lines.
P3-5: tests for the name check (tokens without spaces, key-shaped names),
for a cat line, and for the window boundary through the runner.
2026-11-14 21:19:02 -06:00
jason.woltje 61371adb10 fix(harness): an adapter exit 127 names the program that wasn't found (#1873, lane r127)
A claude-code turn on a Console started without MOSAIC_CLAUDE_BIN failed
with a bare "adapter exited 127". The sandbox binds /usr, so the wrapper
/usr/bin/claude is visible, but its exec target /opt/claude-code/bin/claude
isn't bound, and the shell exits 127.

On exit 127 the runner now reads the tail of the turn's stderr, finds the
shell's "not found" line (bash, dash, env) and adds the program's basename:
"adapter exited 127 (command not found: claude)". It never shows a host
path or anything that isn't a plain program name; a 127 without such a
line keeps the bare reason.

The deploy side (MOSAIC_CLAUDE_BIN on the Console unit) is a Lead-owned
script change, written up in the lane report.
2026-11-14 21:07:14 -06:00
jason.woltje b913f0f4c8 fix(bus,webui): pr2 review round, WebUI receipt carries routeFrom, design note, member and project tests (#1873, lane pr2)
The WebUI packs receipt passes routeFrom through on each hire line; the WebUI
README and TOOLS.md name it. The starter packs design doc gets a dated note
for the 2026-11-14 route ruling. New bus tests: a member pack hire on the
assistant route marks hired and awaiting-owner lines routeFrom assistant, and
a project pack with no chief route hires into the project on the assistant's
harness and model.
2026-11-14 18:37:28 -06:00
jason.woltje bfd2cc5e79 fix(bus,cli,webui): a pack hire falls back to the org assistant's harness and model (#1873, lane pr2)
pack.state gave a pack hire only the chief of staff's resolved route, so an
org whose chief has no model refused every hire pack-hire-route-missing. The
route is now the chief's (launch.by), else the org assistant's (the instance
whose definition is assistant; the one named assistant when there are several,
else the first in key order), else null. Both resolve through resolveInstance,
need harness and model, and carry thinking when set. pack.state adds routeFrom,
and each hired or awaiting-owner receipt line carries it. Refusal next step,
CLI hint, WebUI hire reason and the bus, CLI and TOOLS docs say the refusal now
means neither has a route.
2026-11-14 18:32:01 -06:00
jason.woltje 3e53af3941 fix(bus,webui): pd review round, supersede after apply, one pack hire loop per org, hireError, fromPack (#1873, lane pd)
Review pd-review.md (changes 6). Fixed:
- P2#2: the owner's pack hire withdraws a pack-raised inbox decision only
  after its replacement hire applied; a replacement that refuses (route
  missing, prepare refusal) leaves the old decision open in the inbox.
- P3#3: an apply whose hire loop throws after the apply committed still
  answers the apply receipt, with no hires and the code as hireError; the
  route passes a code through and the card says the hires did not run.
- P3#5: the packs read marks an awaiting-owner line this pack's own hire
  raised fromPack: true; the owner's card counts it in "Hire the N".
- P3#6: one pack hire loop per business; a second refuses
  organization-busy and raises nothing.
- P2#1 docs: TOOLS.md and the bus README say no member surface calls
  pack.hire.console yet (the member surface is a recorded follow-up).

Deferred: P3#4 project agents naming their pack (projectUnion is shared
with the runtime).
2026-11-14 16:09:46 -06:00
jason.woltje 359b3299b4 feat(bus,cli,organization,webui): applying a starter pack is the hire decision (#1873, lane pd)
Ruling 2026-11-14: a person's pack apply records one hire decision per
proposed hire and applies it in the same act, through the hire-decisions
path, with the evidence an inbox approval leaves.

- bus: pack.apply.console runs the pack hire loop; pack.hire.console hires
  an applied record's open proposals. The owner's apply approves flagged and
  credential lines; a member with org.hire gets the unflagged hires and the
  rest open as awaiting-owner decisions; an agent apply still refuses
  human-required. Project packs hire into projects.<p>.agents. Nothing is
  hired twice. Credential lines are approved, not bound. New refusal codes
  pack-not-applied and pack-hire-route-missing. The instances read names the
  pack each hire came from; the packs read lists hired agents and open
  proposals with reasons.
- organization: pack.hire.console maps to org.hire; instances carry
  hireDecision.
- cli: mosaic org pack hire ID PACK [--project P]; apply prints the hires.
- webui: pack card shows N agents hired, open proposals with reasons and
  "Hire the N proposed agents"; Agents and organization pages redraw on
  mosaic-org-changed; agent cards say "from pack X"; Fire (not on the chief
  or assistant) removes the card at once with a receipt.
- docs: design doc section 3 dated note, TOOLS.md, package READMEs.
2026-11-14 15:40:10 -06:00
jason.woltje 65f7288cea fix(webui): template save maps the new template-exists refusal to 409, not outcome-unknown (#1873)
f6c added template-exists for a save under a taken name. The template
route had no entry for it, so a duplicate save answered 503
outcome-unknown. Map it to 409 and move the SP8 pin.
2026-11-13 20:14:49 -06:00
jason.woltje 211b32ef1a fix(cli): f6c re-check, a failed released-marker write still removes the start lock; docs name the new warning and code (#1873) 2026-11-13 20:14:21 -06:00
jason.woltje 163972e08e fix(cli): f6c review round, released start locks, ENOENT and path cut (#1873)
P3-1: releasing a console start lock marks it released through its own
descriptor and removes the path only while it is still that file; a
released lock put back by a racing clear is cleared by the next start or
stop.
P3-2: org definitions reports unknown-organization only when the
organization file itself is missing; another missing file names the
operation.
P3-3: the path cut also covers a path after ':' or inside backticks.
2026-11-13 20:14:21 -06:00
jason.woltje 23e504f331 fix(cli,bus,organization): E2E6 lane f6c, refusal lines name the next step (#1873)
1. Stale bus host lock refusals from bus status, start, stop and restart
   name mosaic bus recover ORG.
2. org definitions: unknown org, unknown or malformed name and bad id give
   one refusal or usage line, no stack trace, no host path.
3. Pack, board and workflow refusals print their hint as template save does;
   tested with the real CliError transport shape.
4. console start and stop clear a console/start.lock whose named supervisor
   (pid and start time) is gone; a live or unnamed holder refuses.
5. Template save keeps free text verbatim and writes no placeholders; the
   preview lists each field that mentions an org-specific name.
6. A request the shim never sent (no socket, connect refused) exits 5 and
   the CLI reports bus-not-running with the start and recover line.
7. autonomy-precondition carries the check that failed, including on the
   hire paths.
8. Saving under an existing template name refuses template-exists with a
   next step; refusal table entry added, channel-proof pins moved.
2026-11-13 20:14:21 -06:00
89 changed files with 5440 additions and 1647 deletions

No files matched your search

+4
View File
@@ -346,8 +346,12 @@ For local development on a named instance only, `mosaic bus start BUSINESS --dev
The hire form and the autonomy panel from a terminal (E2, #1873, P1-3). `mosaic org role-templates|hire|fire|change ORG` and `mosaic org autonomy ORG [set|review]` send the page's own request to the running Console's org route (`/api/orgs/ORG/decisions/hire/templates|start`, `/api/orgs/ORG/autonomy[/review]`), as `org reload` does, so the Console applies the same owner, `--send`, origin, body and live-session checks and the same bus verbs run (`hire.templates.console`, `hire.start.console`, `autonomy.get.console`, `autonomy.set.console`, `autonomy.review.console`). `hire` and `change` read the templates first and send the chosen template's name and sha256, as the form does. `autonomy set` needs the 64-hex `--revision` from `mosaic org autonomy ORG` and sends every setting the panel sends, with only the named ones changed; a stale revision is refused `revision-conflict`; an empty `--authority-resolver ""` clears the resolver, as emptying the panel's field does. These verbs need a named instance (`MOSAIC_CONFIG` set to `~/.config/mosaic-NAME/config.json`) whose Console runs with `--dev-local-owner`; the default instance is refused with exit 3. A Console refusal exits 3 with the Console's code and message; `outcome-unknown` exits 1; an unknown template exits 2. Every one of these verbs, reads included, refuses inside an agent run. `mosaic tasks create|edit|archive` are the task board's three writes: the arguments pass the board's own check (`workspace-tasks.mjs parseTaskWrite`) and go to the bus as the person (`tasks.create|edit|archive`, human transport), so the bus runs its human, field, digest and archive checks. A stale `--expect` is refused `task-conflict`; read the digest with `mosaic tasks --json`.
Starter packs (#1873): `mosaic org pack list`, `mosaic org pack preview ID PACK [--project P]`, `mosaic org pack apply ID PACK --digest D [--project P]` and `mosaic org pack hire ID PACK [--project P]` call the bus as the organization's human (`packs`, `pack.preview`, `pack.apply`, `pack.hire`). Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): a person's apply is the hire decision. After the pack commits, the same act hires each proposed agent through the hire-decisions path and the receipt's `hires` lists `{name, state, decision | code}` per proposal (`hired`, `exists`, `open`, `awaiting-owner`, `refused`); a `hired` or `awaiting-owner` line adds `routeFrom: 'chief' | 'assistant'`. The owner's apply approves the flagged and credential lines; a credential line is approved but not bound, so the agent's launch refuses `credential-unbound` until its services are bound. The bus verb `pack.hire.console` also takes a member's console cap with `org.hire`: it hires only the proposals with no flagged or credential line, and the rest wait for the owner in the inbox. No member surface calls it yet: the WebUI packs routes and the CLI `pack` words are the owner's. An owner's pack hire also replaces and approves a hire this pack's own member hire left in the inbox; the old decision is withdrawn only after the new hire applies. Two pack hires on one organization at once: the second refuses `organization-busy`; an apply whose hire loop did not run still answers the apply's receipt with `hireError` and no hires. An agent's apply hires nothing. `pack hire` reruns the loop on a pack already applied and hires none twice; it refuses `pack-not-applied` when the pack has no packs entry, and a hire runs as the chief of staff's harness and model, else the organization assistant's (the instance whose definition is `assistant`), and a proposal refuses `pack-hire-route-missing` only when neither has both. All pack words refuse inside an agent run (exit 3). The WebUI pack card's "Hire the N proposed agents" is `POST /api/orgs/<id>/packs/hire`. Details: `packages/cli/README.md`, `packages/bus/README.md` and `packages/webui/README.md`, "Starter pack hires"; design: `docs/plans/2026-11-12_starter-packs-design.md` section 3.
The bus and Console lifecycle verbs refuse inside an agent run (agent-guard, #1873): `mosaic bus start`, `bus stop`, `bus restart` and `bus recover`, and `mosaic console start`, `console stop` and `console restart`, and `mosaic org archive` and `org delete`, which stop the organization's bus, and `mosaic org restore`, which starts it (`org restore --no-bus` starts nothing and is not refused), and `mosaic org role-templates`, `hire`, `fire`, `change` and `autonomy` (E2). Each exits 3 with `refused: this runs only from a human shell, outside any agent run (found MARKER in the environment)` before it reads anything. It checks the environment it is given and its own process environment, so a sanitized environment does not hide a marker. A usage error (a missing or extra argument, `--pm` with `--no-launch`, or a bad `--dev-insecure-bind`/`--dev-allow-host`) still comes first (exit 4). `mosaic bus status` and `mosaic console status` stay open to agents. The Console's Restart bus and Restart Console controls keep working: the Console starts its bus host with its own environment, which carries no marker, and Restart Console relaunches the Console under its supervisor without going through the CLI. The markers are the ones `packages/cli/src/transport.mjs` lists. The check is cooperative: a process that drops the markers from its environment is not stopped by it.
Refusal lines (E2E6, #1873). A refusal that has a next step prints it on a second line, `mosaic: next: ...`, after the unchanged message, so callers that match the message keep working. `mosaic bus status`, `start`, `stop` and `restart` on a stale bus host lock exit 3 with `mosaic: stale bus host lock ...` and `mosaic: next: if the bus host died, clear it with mosaic bus recover ORG; recover refuses while the host still runs`. A human-transport verb whose bus is not running (no socket, or the connect refused before anything was sent) exits 3 with `bus-not-running: the bus for ORG is not running, so the request was not sent` and a next line naming `mosaic bus start ORG` and `mosaic bus recover ORG`; `outcome-unknown` (exit 1) stays for a request that left and got no answer. `mosaic org definitions` with an unknown organization, an unknown or malformed name, or a bad id prints one refusal line (exit 3; `unknown-organization` only when the organization file itself is missing, `definitions-unreadable` when `templates` cannot read the roles directory) or, for a bad id, the usage (exit 4), with no stack trace and no host path. Pack, board and workflow refusals carry their next step as `template save` does. `mosaic console start` and `console stop` clear a `console/start.lock` whose named supervisor (pid and start time) is gone, once, with a `cleared a console start lock left by process PID, which is gone` warning; a lock whose holder still runs, or that names no holder, refuses and stays. A start or stop releasing its lock marks it released through its own descriptor and removes the path only while it is still that file, so a lock put back after its release is cleared the same way, with a `cleared a console start lock its holder had released` warning. An `autonomy-precondition` refusal from the bus carries the check that failed (owner notices off, no tested reverse, a resolver without the right, no `review.verdict` holder, no enforced budget, out of the loop only from near the loop, the trail review or near-loop decision missing); the human-transport child writes only the code, so a terminal `org autonomy set` shows the Console's message. `mosaic org template save` writes free text verbatim: it never rewrites prose, and the preview lists every field that mentions the organization id, a project id, an agent name or the owner's account, with the names it mentions, for the owner to edit before sharing. Saving under a name already saved for the account refuses `template-exists` (exit 2, nothing written) with a next line to save under another name or list the saved ones with `mosaic org template list ORG`.
The instance processing switch is separate from per-business launches off/on.
`mosaic halt` durably stops managed processing across every business in the
selected configuration's data root. The bus stays up for reads and human
@@ -374,6 +374,48 @@ exactly as if a person had made them by hand. The steps:
`projects.<p>.agents`; those entries refuse instance credential material
(`BOUND_KEYS`, `agent-levels.mjs:21`).
**2026-11-14 change (#1873, lane pd).** Jason's ruling: "Damnit. If I
choose a starter pack and apply it, that is a decision!" This replaces
"Apply never hires" above for a person's apply. The `packs` entry and the
proposals stay as written; what changes is who acts on them:
- A person's apply (`pack.apply.console` from the WebUI, `pack.apply` from
the CLI) is the hire decision. In the same act, after the pack's commit,
the broker raises one hire decision per proposal through the
hire-decisions path and resolves it, leaving the evidence an inbox
approval leaves: the decision row, its resolved event, `human.input`,
`hire.consume`, the `hire.apply` event and `action.allowed pack.hire`.
The hired entry carries `hireDecision`.
- Invariant 7 still decides each line. The owner's apply approves the
flagged and credential lines. A member with `org.hire` hires only the
proposals with neither a flagged nor a credential line; each of the
others is raised as an open decision that waits for the owner in the
inbox (`awaiting-owner`). The owner's later pack hire withdraws such a
decision and hires the agent itself. An
agent apply hires nothing: the hire stays a proposal for the chief, and
a hire verb from an agent is refused `human-required`.
- Credentials take the smallest rule. The hire writes the entry with no
credential material, so its services show `unbound` and a launch is
refused `credential-unbound` until someone binds them. The owner's
approval covers the credential lines; it binds nothing and reads no
secret.
- The route is the chief of staff's resolved harness and model. With
none, that proposal is refused `pack-hire-route-missing` and stays open.
Note 2026-11-14 (lead ruling, lane pr2): the route is the chief's, else
the organization assistant's (the instance whose definition is
`assistant`; the one named `assistant` when there are several, else the
first in key order), and the refusal applies only when neither resolves
a harness and a model. Hire lines carry `routeFrom`.
- `pack.hire` / `pack.hire.console` (`mosaic org pack hire ID PACK
[--project P]`, `POST /api/orgs/<id>/packs/hire`) runs the same loop on
a pack already applied, refused `pack-not-applied` otherwise. A proposal
whose instance exists is `exists`, and one with an open decision is
`open` or `awaiting-owner`, so neither a re-apply nor `pack hire` ever
hires twice. A project pack hires into `projects.<p>.agents`.
- Each hire line in the receipt is `{name, state, decision | code}` with
state `hired`, `exists`, `open`, `awaiting-owner` or `refused`. The
packs read adds `hired` and `open` (with each proposal's reason) to each
applied entry, and the instances read names the pack an agent came from.
### The surface
| Layer | Name |
+37
View File
@@ -1135,3 +1135,40 @@ Each write records `human.input`. A task read returns a `digest` that can be sup
`task-conflict`. Existing assignees may remain after a role is removed, but new assignees
must be current roles. Automatic tail placement and an explicitly occupied position refuse
`task-position-full` when there is no room; no task row is written.
## Starter pack hires (ruling 2026-11-14, #1873)
"If I choose a starter pack and apply it, that is a decision!" A person's
`pack.apply` (the organization's human, outside any run) or `pack.apply.console`
hires the proposals of the packs entry it wrote, once the apply has committed.
An agent's `pack.apply` hires nothing. `pack.hire` (the owner's human session)
and `pack.hire.console` (the owner's or a member's console cap, needing
`org.hire`) run the same loop on a pack already applied; with no packs entry they
refuse `pack-not-applied`.
Each proposal goes through `#raiseHire` and `hire.resolve.console`, the path an
inbox approval takes: the decision row, its resolved event, `human.input`,
`hire.consume`, the hire's commit and `hire.apply` event, plus
`action.allowed {operation: 'pack.hire', pack, version, origin, project, hire,
decision}`. The route is the chief of staff's resolved harness and model (the
`launch.by` instance), else the organization assistant's: the instance whose
definition is `assistant`, the one named `assistant` when there are several,
else the first in key order. Thinking is carried when set. With neither the
proposal refuses `pack-hire-route-missing`. A `hired` or `awaiting-owner` line
carries `routeFrom: 'chief' | 'assistant'`. The entry is written with
no credential material, so a credential line leaves its services `unbound`.
A proposal whose instance exists is `exists`; one an open hire decision names is
`open`, so nothing is hired twice. The owner approves every line, and replaces
an open decision an earlier hire of the same pack left for the owner: the new
hire is raised and applied first, and the old decision is withdrawn only once it
has applied, so a replacement that refuses leaves the old one in the inbox. A member's flagged or credentialed hires are raised after
the others, left open for the owner's inbox (`awaiting-owner`). A hire that
refuses records `action.allowed {operation: 'pack.hire.refused', code}` and the
loop goes on. The `packs` read adds `hired` and `open` to each applied entry,
and the `instances` read adds `pack: {id, origin, project}` to each instance a
pack hire created. An `awaiting-owner` line this pack's own hire raised carries
`fromPack: true` (the owner's pack hire would replace it). One pack hire loop
runs per business at a time; a second refuses `organization-busy`. An apply
whose hire loop throws after the apply committed still answers the apply's
receipt, with no hires and the loop's code as `hireError`. No member surface
calls `pack.hire.console` yet; the Console's packs routes are the owner's.
+240 -54
View File
@@ -178,7 +178,7 @@ export const USER_VERBS = Object.freeze(['project.list', 'thread.create', 'threa
'thread.share', 'thread.unshare', 'thread.shares']);
// Row 252 (#1753, design sections 2-3): the only verbs a Console owner cap reaches. Every other verb
// refuses it human-required before its own checks, and these refuse every other cap.
export const CONSOLE_VERBS = Object.freeze(['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
export const CONSOLE_VERBS = Object.freeze(['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'pack.hire.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
// Task 3 (#1839): and the owner's intake controls. The reads and writes are the same lifecycle methods the PM's
// unsuffixed verbs reach, with the owner's verified (provider, iss, sub) as the only caller; the PM-only
// request.question and the PM's own reads keep their unsuffixed names and refuse a console cap.
@@ -233,7 +233,7 @@ const TEMPLATE_KEYS = Object.freeze({
export const TEMPLATE_BUS_KEYS = Object.freeze(Object.fromEntries(Object.entries(TEMPLATE_KEYS).flatMap(([verb, k]) => [[verb, k], [`${verb}.console`, k]])));
// The codes a template refusal keeps, each with its reason: a field path or a checked name, never a
// value from the organization file and never a host path.
const TEMPLATE_CODES = Object.freeze(['template-secret-suspected', 'invalid-request', 'human-required', 'not-configured', 'pack-plan-stale', 'starter-pack-invalid', 'starter-pack-template-changed']);
const TEMPLATE_CODES = Object.freeze(['template-secret-suspected', 'template-exists', 'invalid-request', 'human-required', 'not-configured', 'pack-plan-stale', 'starter-pack-invalid', 'starter-pack-template-changed']);
// Row 175: the organization verbs a tester may call. Its writes run every check the human's do
// and log actor `tester`; row 176 adds routes reads; limits.set, organization.set and organization.revision refuse it.
export const TESTER_ORGANIZATION_VERBS = Object.freeze(['limits', 'plugins', 'instances', 'plugins.set', 'instances.set', 'routes.set', 'routes']);
@@ -289,9 +289,12 @@ export class BusError extends Error {
if (reason !== undefined) this.reason = reason;
}
}
const fail = (code) => {
throw new BusError(code);
// E2E6 fix 7: a refusal may carry a reason, static text that names which check failed; it never
// quotes an argument or file bytes.
const fail = (code, reason) => {
throw new BusError(code, reason);
};
const BUDGET_UNCOVERED = 'no enforced budget covers new agents; authority away from the loop needs one';
const object = (x) => x !== null && typeof x === 'object' && !Array.isArray(x);
// #1873 CB5: a copy binding proposal leaves the bus only as its copy and its change. The copy id,
// incarnation, definition pin, services, grant ids and slots stay in the raise event, which the
@@ -636,6 +639,9 @@ export class Broker {
#builtinBinding;
#organization;
#hires;
// Businesses with a pack hire loop running: a second loop on the same business refuses
// organization-busy rather than raising a second decision for the same agent.
#packHiring = new Set();
#autonomyHost;
#pluginService;
#credentialVerbs;
@@ -6262,16 +6268,16 @@ export class Broker {
if (CREDENTIAL_VERBS.includes(request.verb)) return this.#requestCredential(s, request.verb, structuredClone(args));
if(['autonomy.get.console','autonomy.set.console','autonomy.review.console','decision.reverse.console'].includes(request.verb)) {
this.#autonomyOwner(s);
return this.#autonomyConsole(s,request.verb,structuredClone(args)).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown'),request);});
return this.#autonomyConsole(s,request.verb,structuredClone(args)).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
}
if (s.hireMembership && !['hire.preview.console','hire.resolve.console','hire.start.console','hire.templates.console'].includes(request.verb)) fail('human-required');
if (s.hireMembership && !['hire.preview.console','hire.resolve.console','hire.start.console','hire.templates.console','pack.hire.console'].includes(request.verb)) fail('human-required');
if(request.verb==='decision.resolve' && !s.human) {
if(s.tester)fail('tester-refused');
keys(args,['id','choice','note'],['id','choice']);identifier(args.id);
}
if(request.verb==='decision.resolve' && !s.human && ['role.hire','role.fire','role.change'].includes(this.#decision(s,args.id).action)) {
const d=this.#decision(s,args.id);
if(d.route_to!=='human')return this.#resolveAuthority(s,args).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown'),request);});
if(d.route_to!=='human')return this.#resolveAuthority(s,args).catch(e=>{throw this.#refused(s,e instanceof BusError?e:new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
}
if(request.verb==='hire.templates.console') {
keys(args,[]);const caller=this.#hireCaller(s);
@@ -6285,14 +6291,32 @@ export class Broker {
const input=request.verb==='decision.raise' ? (()=>{ keys(args,['action','hire'],['action','hire']); if(args.action!==`role.${args.hire?.op}`)fail('invalid-request'); return args.hire; })() : args;
// #1873 SP5: a raise from a pack's recorded proposal; the pin, not the caller, names the role.
if(request.verb==='hire.raise' && object(args) && Object.hasOwn(args,'proposal'))
return Promise.resolve().then(()=>this.#raiseHire(s,this.#proposalHire(s,args),false)).catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request'),request);});
return this.#raiseHire(s,input,request.verb==='hire.start.console').catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request'),request);});
return Promise.resolve().then(()=>{const r=this.#proposalHire(s,args);return this.#raiseHire(s,r.input,false,{pack:r.pack});}).catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request',e instanceof BusError?e.reason:undefined),request);});
return this.#raiseHire(s,input,request.verb==='hire.start.console').catch(e=>{throw this.#refused(s,new BusError(e.code??'invalid-request',e instanceof BusError?e.reason:undefined),request);});
}
if(request.verb==='decision.preview.console' && ['role.hire','role.fire','role.change'].includes(this.#decision(s,args.id).action))return this.#hireConsole(s,'hire.preview.console',args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown'),request);});
if(request.verb==='decision.preview.console' && ['role.hire','role.fire','role.change'].includes(this.#decision(s,args.id).action))return this.#hireConsole(s,'hire.preview.console',args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
if (['hire.preview.console','hire.resolve.console'].includes(request.verb))
return this.#hireConsole(s,request.verb,args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown'),request);});
return this.#hireConsole(s,request.verb,args).catch(e=>{throw this.#refused(s,new BusError(e.code??'outcome-unknown',e instanceof BusError?e.reason:undefined),request);});
if (request.verb === 'grants.scope' || request.verb === 'grants.scope.set')
return this.#grantScopeVerb(s, request.verb, structuredClone(args));
// Ruling 2026-11-14: hire a pack's proposed agents after the apply that recorded them, through
// the same loop a person's apply runs. pack.hire is the owner's CLI human cap; pack.hire.console
// the owner's or a member's console cap. An agent and the tester never get here.
if (request.verb === 'pack.hire' || request.verb === 'pack.hire.console') {
if (s.tester) fail('tester-refused');
if ((request.verb === 'pack.hire.console') !== !!s.console) fail('human-required');
keys(args, ['pack', 'project'], ['pack']);
if (typeof args.pack !== 'string' || !/^(saved:)?[a-z0-9][a-z0-9._-]{0,63}$/.test(args.pack)) fail('invalid-request');
if (Object.hasOwn(args, 'project') && (typeof args.project !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(args.project))) fail('invalid-request');
const callerOf = () => this.#packHireCaller(s);
if (!callerOf().rights.includes('org.hire')) fail('right-required');
return Promise.resolve().then(async () => {
const state = this.#organization ? this.#organization(s.business, 'pack.state', { pack: args.pack, project: args.project ?? null }, s.human, {}) : null;
if (!state?.entry) fail('pack-not-applied');
const out = await this.#packHires(s, callerOf, { pack: args.pack, project: args.project ?? null });
this.#secretCheck(out); return { pack: state.entry.id, ...out };
}).catch(e => { if (e instanceof BusError) throw this.#refused(s, e, request); this.#packFail(e); });
}
// #1873 SP4: the owner's starter packs, board and workflows. Only the organization's owner calls
// them: the human cap from the CLI, or the owner's console cap (a hire member's cap is refused
// above). The tester is refused before any argument check. A preview and an apply raise no
@@ -6337,6 +6361,20 @@ export class Broker {
if (spends && wrote) this.#store.transaction(() => this.#consumeAuthority(s, 'organization.change'));
this.#secretCheck(value); return value;
};
// Ruling 2026-11-14: a person's apply is the hire decision. Once the apply has committed, the
// same call hires the proposals (#packHires); an agent's apply never hires.
// The apply has committed by then, so a hire loop that throws (organization-busy, a store error)
// still returns the apply's receipt, with no hires and the loop's code as hireError.
if (verb === 'pack.apply' && !agent) {
const hired = async (value) => {
let out;
try { out = await this.#packHires(s, () => this.#packHireCaller(s), { pack: args.pack, project: args.project ?? null }); }
catch (e) { out = { hires: [], hireError: e instanceof BusError && typeof e.code === 'string' ? e.code : 'outcome-unknown' }; }
return done({ ...value, ...out });
};
return Promise.resolve(result).then(value => value, packFail).then(hired);
}
if (verb === 'packs') return Promise.resolve(result).then(value => done(this.#packsEnrich(s.business, value)), packFail);
return result?.then ? result.then(done, packFail) : done(result);
}
// #1873 SP8: saving a template. Only the organization's owner: the human cap from the CLI or the
@@ -6458,6 +6496,12 @@ export class Broker {
entry.running = this.#running(s.business, name);
entry.alive = this.#aliveAfterFire(s.business, name);
}
// Ruling 2026-11-14: each instance a pack hire created names the pack, from its pack.hire event.
if (request.verb === "instances" && result?.instances && typeof result.instances === "object") {
const from = this.#packHireOrigins(s.business);
for (const entry of Object.values(result.instances))
if (typeof entry.hireDecision === 'string' && from.has(entry.hireDecision)) entry.pack = from.get(entry.hireDecision);
}
// #1873 A3: the copies this bus booted with, and each one's running runs. The file's own
// instances above carry no copy; a copy carries its state, missing service names or reason.
if (request.verb === "instances" && result?.instances && typeof result.instances === "object" && this.#business(s.business).copies)
@@ -6628,7 +6672,7 @@ export class Broker {
if(!this.#autonomyHost?.get || !this.#autonomyHost?.set)fail('not-configured');
const old=await this.#autonomyHost.get(s.business),b=this.#business(s.business);
if(a.revision!==old.revision)fail('revision-conflict');
if(AUTONOMY_CLASSES.some(cls=>decisionAutonomy(cls,a.autonomy)==='near the loop') && a.autonomy.notices!==true)fail('autonomy-precondition');
if(AUTONOMY_CLASSES.some(cls=>decisionAutonomy(cls,a.autonomy)==='near the loop') && a.autonomy.notices!==true)fail('autonomy-precondition','owner notices are off; a class near the loop needs them on');
for(const cls of AUTONOMY_CLASSES) {
const before=decisionAutonomy(cls,old.autonomy),after=decisionAutonomy(cls,a.autonomy);
// Pulling back is unconditional. Only a move away from the loop has prerequisites.
@@ -6637,22 +6681,24 @@ export class Broker {
if(cls==='policy')continue;
if(cls==='authority' && after==='out of the loop' && before!==after)fail('authority-limits-unavailable');
if(['in the loop','near the loop','out of the loop'].indexOf(after)<=['in the loop','near the loop','out of the loop'].indexOf(before))continue;
if(a.autonomy.notices!==true || !this.#autonomyHost.reversible?.(cls,b))fail('autonomy-precondition');
if(a.autonomy.notices!==true)fail('autonomy-precondition',`owner notices are off; moving ${cls} away from the loop needs them on`);
if(!this.#autonomyHost.reversible?.(cls,b))fail('autonomy-precondition',`${cls} has no tested reverse in this organization, so it stays in the loop`);
const resolvers=cls==='authority'?[a.autonomy.authorityResolver]:cls==='merge'?[b.arbiters.technical]:cls==='policy'?[b.arbiters.delivery]:Object.values(b.arbiters);
for(const name of resolvers) {
const role=b.roles[name],right=cls==='authority'?'decision.resolve.authority':`decision.resolve.${cls==='merge'?'technical':cls==='policy'?'delivery':name===b.arbiters.technical?'technical':'delivery'}`;
if(!role?.authority?.withinRole.includes(right) || (cls==='authority' && name===b.launch?.by))fail('autonomy-precondition');
if(!role?.authority?.withinRole.includes(right))fail('autonomy-precondition',cls==='authority'?'the authority resolver is not a role with decision.resolve.authority':`the ${cls} resolver is not a role with ${right}`);
if(cls==='authority' && name===b.launch?.by)fail('autonomy-precondition','the authority resolver is the role that launches agents; name a separate resolver');
}
if(['merge','policy'].includes(cls) && !Object.values(b.roles).some(r=>r.authority?.withinRole.includes('review.verdict')))fail('autonomy-precondition');
if(cls==='authority' && !this.#budgetCovered(b))fail('autonomy-precondition');
if(['merge','policy'].includes(cls) && !Object.values(b.roles).some(r=>r.authority?.withinRole.includes('review.verdict')))fail('autonomy-precondition',`no role holds review.verdict, which ${cls} away from the loop needs`);
if(cls==='authority' && !this.#budgetCovered(b))fail('autonomy-precondition',BUDGET_UNCOVERED);
if(after==='out of the loop') {
if(before!=='near the loop')fail('autonomy-precondition');
if(before!=='near the loop')fail('autonomy-precondition',`${cls} moves out of the loop only from near the loop`);
const review=this.#store.get("SELECT seq,body FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation')='autonomy.review' AND json_extract(body,'$.decisionClass')=? ORDER BY seq DESC LIMIT 1",s.business,cls);
const latest=this.#store.get("SELECT seq FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation')='autonomy.set' ORDER BY seq DESC LIMIT 1",s.business);
if(!review || JSON.parse(review.body).settingSeq!==latest?.seq)fail('autonomy-precondition');
if(!review || JSON.parse(review.body).settingSeq!==latest?.seq)fail('autonomy-precondition',`${cls} needs your review of its trail since the last autonomy change`);
const notice=this.#store.get("SELECT seq FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation')='autonomy.notice' AND json_extract(body,'$.decisionClass')=? AND seq>? ORDER BY seq DESC LIMIT 1",s.business,cls,latest?.seq??0);
const reversal=this.#store.get("SELECT max(e.seq) seq FROM events e WHERE e.business=? AND e.kind='action.allowed' AND json_extract(e.body,'$.operation') LIKE 'autonomy.reverse%' AND EXISTS(SELECT 1 FROM events n WHERE n.business=e.business AND n.kind='action.allowed' AND json_extract(n.body,'$.operation')='autonomy.notice' AND json_extract(n.body,'$.decisionClass')=? AND json_extract(n.body,'$.decision')=json_extract(e.body,'$.decision'))",s.business,cls);
if(!notice || review.seq<=Math.max(notice.seq,reversal?.seq??0))fail('autonomy-precondition');
if(!notice || review.seq<=Math.max(notice.seq,reversal?.seq??0))fail('autonomy-precondition',`${cls} needs a near-loop decision since the last autonomy change, and your trail review after it`);
}
}
this.#store.transaction(()=>this.#event(s,'action.allowed',{operation:'autonomy.set.requested',autonomy:a.autonomy,subject:s.console},null));
@@ -6736,28 +6782,159 @@ export class Broker {
.at(-1);
if (!entry) fail('invalid-request');
const hire = entry.proposedHires.find(h => h.name === proposal.hire);
const pin = hire.pin;
if (!object(pin)) fail('invalid-request');
let role;
if (Object.hasOwn(pin, 'inline')) {
if (!object(hire.entry) || typeof pin.sha256 !== 'string') fail('invalid-request');
// The broker's sandbox import closure is fixed, so the digest and the composition are local
// copies: canonical is organization util.mjs canonicalJson, built as a string so integer-like
// keys keep the sorted order (an object would put them first), and the composition is
// definitions.mjs compositionOf.
const canonical = v => Array.isArray(v) ? `[${v.map(canonical).join(',')}]` : object(v)
? `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}` : JSON.stringify(v);
if (sha256(canonical(hire.entry)) !== pin.sha256) fail('starter-pack-proposal-stale');
const from = hire.entry.from?.template;
if (from !== undefined && (b.launch?.noHire ?? []).includes(from)) fail('definition-not-hireable');
if (!object(hire.entry.role) || typeof hire.entry.instructions !== 'string') fail('invalid-request');
role = { inline: { ...hire.entry.role, instructions: hire.entry.instructions, ...(hire.entry.personality !== undefined ? { personality: hire.entry.personality } : {}) } };
} else role = structuredClone(pin);
const role = this.#pinRole(b.launch?.noHire ?? [], hire);
const reason = Object.hasOwn(args, 'reason') ? args.reason : hire.reason;
return { op: 'hire', level: project === null ? 'org' : 'project', ...(project === null ? {} : { project }), name: hire.name, role, route: structuredClone(args.route), reason };
return { input: { op: 'hire', level: project === null ? 'org' : 'project', ...(project === null ? {} : { project }), name: hire.name, role, route: structuredClone(args.route), reason },
pack: { pack: entry.id, version: entry.version ?? null, origin: entry.origin ?? null, project } };
}
async #raiseHire(s, input, immediate) {
// A recorded proposal's pin as a hire request's role (SP5's chief raise and a person's pack hire).
#pinRole(noHire, hire) {
const pin = hire?.pin;
if (!object(pin)) fail('invalid-request');
if (!Object.hasOwn(pin, 'inline')) return structuredClone(pin);
if (!object(hire.entry) || typeof pin.sha256 !== 'string') fail('invalid-request');
// The broker's sandbox import closure is fixed, so the digest and the composition are local
// copies: canonical is organization util.mjs canonicalJson, built as a string so integer-like
// keys keep the sorted order (an object would put them first), and the composition is
// definitions.mjs compositionOf.
const canonical = v => Array.isArray(v) ? `[${v.map(canonical).join(',')}]` : object(v)
? `{${Object.keys(v).sort().map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}` : JSON.stringify(v);
if (sha256(canonical(hire.entry)) !== pin.sha256) fail('starter-pack-proposal-stale');
const from = hire.entry.from?.template;
if (from !== undefined && noHire.includes(from)) fail('definition-not-hireable');
if (!object(hire.entry.role) || typeof hire.entry.instructions !== 'string') fail('invalid-request');
return { inline: { ...hire.entry.role, instructions: hire.entry.instructions, ...(hire.entry.personality !== undefined ? { personality: hire.entry.personality } : {}) } };
}
// Ruling 2026-11-14: a person's pack apply is the hire decision. The person who may hire from a
// pack: the owner's console cap, the owner's CLI human cap (outside any run), or a member's console
// cap with org.hire. Anyone else is refused human-required; the tester tester-refused.
#packHireCaller(s) {
if (s.tester) fail('tester-refused');
if (s.console) return this.#hireCaller(s);
this.#human(s);
if (s.human !== this.#business(s.business).human) fail('human-required');
return { actor: s.human, agent: false, rights: ['org.hire'], owner: true, instanceOwner: false, subject: null, via: 'cli' };
}
#openHireDecisions(business) {
return this.#store.all(`SELECT d.id FROM decisions d WHERE d.business=? AND d.action='role.hire' AND NOT EXISTS(SELECT 1 FROM decision_events x WHERE x.decision=d.id AND x.op IN ${CLOSED}) ORDER BY d.at, d.id`, business)
.map(({ id }) => ({ id, hire: this.#raised(business, id)?.hire })).filter(x => object(x.hire));
}
// decision id -> {id, origin, project} of the pack whose hire raised it.
#packHireOrigins(business) {
return new Map(this.#packHireEvents(business).filter(e => e.operation === 'pack.hire' && typeof e.decision === 'string')
.map(e => [e.decision, { id: e.pack, origin: e.origin ?? null, project: e.project ?? null }]));
}
// Ruling 2026-11-14: the packs read gains, per applied entry, the agents its hires created
// (launched, for the organization level) and each proposal still open: awaiting-owner with its
// decision, refused with the last refusal code, or proposed. Each carries the pack's reason.
#packsEnrich(business, value) {
if (!Array.isArray(value?.applied)) return value;
const events = this.#packHireEvents(business), agents = value.agents ?? { org: {}, projects: {} };
const open = new Map(this.#openHireDecisions(business).map(x => [JSON.stringify([x.hire.name, x.hire.project ?? null]), x.id]));
const raisedBy = new Map(events.filter(e => e.operation === 'pack.hire').map(e => [e.decision, e]));
for (const a of value.applied) {
const level = a.project === null ? agents.org ?? {} : agents.projects?.[a.project] ?? {};
const mine = e => e.pack === a.id && (e.origin ?? null) === (a.origin ?? null) && (e.project ?? null) === (a.project ?? null);
// Hired: every live instance at the entry's level a hire of this pack created, whichever entry
// proposed it (a re-apply records an entry that proposes nothing new).
a.hired = Object.entries(level).filter(([, inst]) => inst.launched && inst.hireDecision && raisedBy.has(inst.hireDecision) && mine(raisedBy.get(inst.hireDecision))).map(([name]) => name);
a.open = [];
for (const h of a.proposedHires) {
if (Object.hasOwn(level, h.name)) continue;
const decision = open.get(JSON.stringify([h.name, a.project ?? null]));
// fromPack: this pack's own hire raised it, so the owner's pack hire replaces and approves it.
if (decision) { a.open.push({ name: h.name, reason: h.reason, state: 'awaiting-owner', decision, ...(raisedBy.has(decision) && mine(raisedBy.get(decision)) ? { fromPack: true } : {}) }); continue; }
const last = events.filter(e => mine(e) && e.hire === h.name).at(-1);
if (last?.operation === 'pack.hire.refused') a.open.push({ name: h.name, reason: h.reason, state: 'refused', code: last.code });
else a.open.push({ name: h.name, reason: h.reason, state: 'proposed' });
}
}
return value;
}
#packHireEvents(business) {
return this.#store.all(`SELECT body FROM events WHERE business=? AND kind='action.allowed' AND json_extract(body,'$.operation') IN ('pack.hire','pack.hire.refused') ORDER BY seq`, business)
.map(r => JSON.parse(r.body));
}
// One pass over the latest packs entry of `pack` (and project): each proposed hire is raised and
// approved in the same act through #raiseHire and #hireConsole, the path an inbox approval takes, so
// each agent leaves the same decision record. A hire whose instance exists, or that an open hire
// decision already names, is skipped, so a re-apply hires nothing twice. The owner approves every
// line. A member approves only the unflagged hires; each flagged or credentialed one is recorded
// after them, pinned to the final revision, as an open decision for the owner's inbox. A hire that
// refuses records action.allowed pack.hire.refused with its code, and the loop goes on.
async #packHires(s, callerOf, { pack, project = null }) {
if (!this.#organization || !this.#hires) fail('not-configured');
if (this.#packHiring.has(s.business)) fail('organization-busy');
this.#packHiring.add(s.business);
try { return await this.#packHireLoop(s, callerOf, { pack, project }); }
finally { this.#packHiring.delete(s.business); }
}
async #packHireLoop(s, callerOf, { pack, project }) {
const caller = callerOf();
const read = () => this.#organization(s.business, 'pack.state', { pack, project }, caller.actor, {});
const state = read();
if (!state?.entry) return { hires: [] };
const entry = state.entry, provenance = { pack: entry.id, version: entry.version ?? null, origin: entry.origin ?? null, project };
const out = [], deferred = [];
const refused = (name, e) => {
const code = e?.code ?? 'outcome-unknown';
this.#store.transaction(() => this.#event(s, 'action.allowed', { operation: 'pack.hire.refused', pack: entry.id, origin: entry.origin ?? null, project, hire: name, code }, null));
out.push({ name, state: 'refused', code });
};
const open = new Map(this.#openHireDecisions(s.business).map(x => [JSON.stringify([x.hire.name, x.hire.project ?? null]), x.id]));
const raisedBy = new Map(this.#packHireEvents(s.business).filter(e => e.operation === 'pack.hire').map(e => [e.decision, e]));
for (const hire of (Array.isArray(entry.proposedHires) ? entry.proposedHires : []).filter(object)) {
const name = hire.name;
if (state.names.includes(name)) { out.push({ name, state: 'exists' }); continue; }
const openId = open.get(JSON.stringify([name, project]));
// The owner's pack hire approves every line, so an open decision an earlier pack hire of this
// same pack left for the owner is replaced by one approved now (its pin may be stale after the
// hires approved since). The old one is withdrawn only once the new hire has applied: a
// replacement that refuses leaves it open in the owner's inbox. Any other open decision is left alone.
let supersedes = null;
if (openId) {
const by = raisedBy.get(openId);
if (caller.owner !== true || !by || by.pack !== entry.id || (by.origin ?? null) !== (entry.origin ?? null) || (by.project ?? null) !== project) { out.push({ name, state: 'open', decision: openId }); continue; }
supersedes = openId;
}
let input;
try {
if (!state.route) fail('pack-hire-route-missing');
input = { op: 'hire', level: project === null ? 'org' : 'project', ...(project === null ? {} : { project }), name, role: this.#pinRole(state.noHire, hire), route: structuredClone(state.route),
reason: typeof hire.reason === 'string' && hire.reason.trim() ? hire.reason : `Proposed by starter pack ${entry.id}.` };
} catch (e) { refused(name, e); continue; }
let r;
try {
r = await this.#raiseHire(s, input, true, { caller: callerOf, pack: provenance, defer: caller.owner !== true });
} catch (e) { refused(name, e); continue; }
if (r?.deferred) { deferred.push(input); continue; }
if (supersedes) this.#store.transaction(() => {
if (this.#closed(supersedes)) return;
const seq = Number(this.#store.run('INSERT INTO decision_events(decision,at,op,by,choice,note,via) VALUES(?,?,?,?,?,?,?)',
supersedes, this.#now(), 'withdrawn', caller.actor, null, null, caller.via ?? 'console').lastInsertRowid);
this.#event(s, 'human.input', { kind: 'answer', decision: supersedes, op: 'withdrawn', choice: null, via: caller.via ?? 'console', subject: caller.via === 'cli' ? null : s.console, decisionSeq: seq }, supersedes);
});
out.push({ name, state: 'hired', decision: r.id, routeFrom: state.routeFrom, ...(supersedes ? { supersedes } : {}) });
}
for (const input of deferred) {
try {
const r = await this.#raiseHire(s, input, false, { caller: callerOf, pack: provenance, record: true });
out.push({ name: input.name, state: 'awaiting-owner', decision: r.id, routeFrom: state.routeFrom });
} catch (e) { refused(input.name, e); }
}
return { hires: out };
}
// opts (ruling 2026-11-14, a person's pack apply is the hire decision):
// caller: () => the person's hire caller, read again after prepare. Default #hireCaller(s).
// pack: {pack, version, origin, project}; the raise also records action.allowed pack.hire.
// defer: a flagged or credentialed hire a non-owner may not approve returns {deferred: true}
// instead of refusing hire-owner-required, and records nothing.
// record: the person's raise is left open for the owner's inbox (route human, not resolved).
async #raiseHire(s, input, immediate, opts = {}) {
const b=this.#business(s.business);
const human=immediate || opts.record===true;
const callerOf=()=>opts.caller ? opts.caller() : this.#hireCaller(s);
// Change is a replacement composition and uses the existing role.hire grant.
const chiefAllowed=()=>{
this.#agent(s);
@@ -6767,36 +6944,44 @@ export class Broker {
};
// #1873 CB1: a copy credential binding is owner-only. A person raising one in one step must be
// the organization's owner; a member with org.hire is not.
if(immediate) { const c=this.#hireCaller(s); if(!c.rights.includes('org.hire'))fail('right-required'); if(input?.binding!==undefined && c.owner!==true)fail('human-required'); }
if(human) { const c=callerOf(); if(!c.rights.includes('org.hire'))fail('right-required'); if(input?.binding!==undefined && c.owner!==true)fail('human-required'); }
else chiefAllowed();
if(!this.#hires)fail('not-configured');
const did=randomUUID(), at=this.#now(), expiresAt=new Date(Date.parse(at)+7*86400000).toISOString();
const p=await this.#hires.prepare(s.business,structuredClone(input),{id:did,expiresAt});
// Recheck the chief after asynchronous preparation; a released run cannot raise.
if(!immediate)chiefAllowed();
let caller=null;
if(!human)chiefAllowed();
else {
const caller=this.#hireCaller(s);
caller=callerOf();
if(p.binding && caller.owner!==true)fail('human-required');
if(!p.binding && (((p.flagged.length || p.credentialLines.length) && !caller.owner) || (p.level==='root' && !caller.instanceOwner)))fail('hire-owner-required');
const ownerOnly=!p.binding && (((p.flagged.length || p.credentialLines.length) && !caller.owner) || (p.level==='root' && !caller.instanceOwner));
if(ownerOnly && opts.defer===true)return {deferred:true,name:p.name,flagged:p.flagged,credentialLines:p.credentialLines};
if(ownerOnly && opts.record!==true)fail('hire-owner-required');
}
const action=`role.${p.op}`;
const level=decisionAutonomy('authority',b.autonomy);
let route='human';
// A binding always goes to the owner; no autonomy level moves it (design section 4).
if(!immediate && !p.binding && level!=='in the loop' && p.level!=='root' && !p.flagged.length && !p.credentialLines.length) {
if(!human && !p.binding && level!=='in the loop' && p.level!=='root' && !p.flagged.length && !p.credentialLines.length) {
if(level==='out of the loop')fail('authority-limits-unavailable');
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition');
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition',BUDGET_UNCOVERED);
route=b.autonomy?.authorityResolver;
if(!b.roles[route]?.authority?.withinRole.includes('decision.resolve.authority'))fail('autonomy-precondition');
if(!b.roles[route]?.authority?.withinRole.includes('decision.resolve.authority'))fail('autonomy-precondition','the authority resolver is not a role with decision.resolve.authority');
if(route===s.role || resolverSubject(b,route,p.name))route='human';
}
this.#store.transaction(()=>{
const raiser=immediate?'human':s.role;
const raiser=human?'human':s.role;
const run=human?(caller?.via==='cli'?'human-cli':'human-console'):s.run;
this.#store.run('INSERT INTO decisions(id,at,business,project,raised_by_role,raised_by_run,class,action,route_to,question,options,recommendation,blocking) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)',
did,at,s.business,p.project??null,raiser,immediate?'human-console':s.run,'gated',action,route,p.binding?`${p.binding.after===null?'unbind':'bind'} credentials for copy ${p.binding.instance}?`:`${p.op} ${p.name} at ${p.level} level?`,JSON.stringify([{key:'yes',text:'Approve'},{key:'no',text:'Deny'}]),'no',0);
did,at,s.business,p.project??null,raiser,run,'gated',action,route,p.binding?`${p.binding.after===null?'unbind':'bind'} credentials for copy ${p.binding.instance}?`:`${p.op} ${p.name} at ${p.level} level?`,JSON.stringify([{key:'yes',text:'Approve'},{key:'no',text:'Deny'}]),'no',0);
this.#event(s,'action.allowed',{operation:'decision.raise',decision:did,action,approvalChoice:'yes',target:p.name,hire:p,autonomyLevel:level},did);
// The pack this hire came from, for the Agents page and the pack card. No target key: the
// decision.raise above is the record the decision readers key on.
if(opts.pack)this.#event(s,'action.allowed',{operation:'pack.hire',pack:opts.pack.pack,version:opts.pack.version??null,origin:opts.pack.origin??null,project:opts.pack.project??null,hire:p.name,decision:did},did);
});
if(immediate) return this.#hireConsole(s,'hire.resolve.console',{id:did,choice:'yes',digest:p.digest});
if(immediate) return this.#hireConsole(s,'hire.resolve.console',{id:did,choice:'yes',digest:p.digest},opts.caller ?? null);
if(human) return {id:did,op:'raised',name:p.name,flagged:p.flagged,credentialLines:p.credentialLines};
return {...this.#decisionView(this.#decision(s,did)),hire:bindingSummary(p)};
}
// The harness fact comes from the host's loaded modules; no host, no account coverage.
@@ -6818,7 +7003,7 @@ export class Broker {
if(this.#expireHire(s,d,p))fail('decision-expired');
if(this.#autonomyLevel(d)==='in the loop')fail('hire-resolution-required');
if(this.#autonomyLevel(d)==='out of the loop')fail('authority-limits-unavailable');
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition');
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition',BUDGET_UNCOVERED);
if(!this.#business(s.business).roles[s.role]?.authority?.withinRole.includes('decision.resolve.authority'))fail('not-resolver');
};
validate();
@@ -6838,7 +7023,7 @@ export class Broker {
const recheck=()=>{
this.#agent(s);
if(this.#autonomyLevel(d)==='out of the loop')fail('authority-limits-unavailable');
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition');
if(!this.#budgetCovered(this.#business(s.business)))fail('autonomy-precondition',BUDGET_UNCOVERED);
if(this.#autonomyLevel(d)==='in the loop' || !this.#business(s.business).roles[s.role]?.authority?.withinRole.includes('decision.resolve.authority') || resolverSubject(this.#business(s.business),s.role,p.name))fail('not-resolver');
};
recheck();
@@ -6853,8 +7038,8 @@ export class Broker {
this.#store.transaction(()=>this.#event(s,'action.allowed',{operation:'hire.failed',decision:d.id,code:error.code??'outcome-unknown'},d.id));throw error;
}
}
async #hireConsole(s,verb,a) {
const caller={...this.#hireCaller(s),now:()=>Math.max(Date.now(),this.#clock)};
async #hireConsole(s,verb,a,callerOf=null) {
const caller={...(callerOf ? callerOf() : this.#hireCaller(s)),now:()=>Math.max(Date.now(),this.#clock)};
keys(a,verb==='hire.preview.console'?['id','adjust']:['id','choice','digest','adjust'],verb==='hire.preview.console'?['id']:['id','choice','digest']);
identifier(a.id);
const d=this.#decision(s,a.id), raise=this.#raised(s.business,d.id);
@@ -6877,8 +7062,9 @@ export class Broker {
// A durable close/consume precedes the external file effect. A crash never replays an approval.
this.#store.transaction(()=>{
if(this.#closed(d.id))fail('decision-closed');
this.#store.run('INSERT INTO decision_events(decision,at,op,by,choice,via) VALUES(?,?,?,?,?,?)',d.id,this.#now(),'resolved',caller.actor,a.choice,'console');
this.#event(s,'human.input',{kind:'answer',decision:d.id,op:'resolved',choice:a.choice,via:'console',subject:s.console},d.id);
const via=caller.via ?? 'console';
this.#store.run('INSERT INTO decision_events(decision,at,op,by,choice,via) VALUES(?,?,?,?,?,?)',d.id,this.#now(),'resolved',caller.actor,a.choice,via);
this.#event(s,'human.input',{kind:'answer',decision:d.id,op:'resolved',choice:a.choice,via,subject:callerOf ? caller.subject ?? null : s.console},d.id);
if(a.choice==='yes')this.#event(s,'action.allowed',{operation:'hire.consume',decision:d.id,digest:p.digest,hire:p},d.id);
});
if(a.choice==='no')return {id:d.id,op:'resolved',choice:a.choice};
+14 -3
View File
@@ -1,5 +1,11 @@
import { connect } from 'node:net';
import { BusError, PROJECT_SAVE_VERB, PROJECT_SAVE_REQUEST_MAX } from './broker.mjs';
// E2E6 fix 6: a connect that fails with one of these never sent the request. The code stays
// outcome-unknown for every caller that reads it (the harness, the Console), and the error is marked
// notSent so the human and tester shims can exit with NOT_SENT_EXIT and `mosaic` can say the bus is
// not running.
const NOT_SENT = new Set(['ENOENT', 'ECONNREFUSED', 'ENOTDIR', 'ENOTSOCK']);
export const NOT_SENT_EXIT = 5;
export class Client {
constructor({ path, cap, human, tester, user, console: owner, timeout = 5000 }) {
this.path = path;
@@ -22,7 +28,8 @@ export class Client {
return new Promise((resolve, reject) => {
const socket = connect(this.path);
let input = Buffer.alloc(0),
settled = false;
settled = false,
connected = false;
const end = (error, value) => {
if (settled) return;
settled = true;
@@ -30,8 +37,12 @@ export class Client {
error ? reject(error) : resolve(value);
};
socket.setTimeout(['processing.halt', 'processing.resume'].includes(verb) ? Math.max(this.timeout, 20000) : this.timeout, () => end(new BusError('outcome-unknown')));
socket.on('connect', () => socket.write(request));
socket.on('error', () => end(new BusError('outcome-unknown')));
socket.on('connect', () => { connected = true; socket.write(request); });
socket.on('error', (error) => {
const unknown = new BusError('outcome-unknown');
if (!connected && NOT_SENT.has(error?.code)) unknown.notSent = true;
end(unknown);
});
socket.on('end', () => end(new BusError('outcome-unknown')));
socket.on('data', (b) => {
input = Buffer.concat([input, b]);
+4 -2
View File
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto';
import { spawnSync } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { readFileSync } from 'node:fs';
import { Client } from './client.mjs';
import { Client, NOT_SENT_EXIT } from './client.mjs';
import { readProcess } from './human.mjs';
const file = fileURLToPath(import.meta.url);
if (!process.env.MOSAIC_BUS_CLI_NONCE) {
@@ -39,5 +39,7 @@ try {
process.stdout.write(JSON.stringify(result) + '\n');
} catch (e) {
process.stderr.write((/^[a-z-]{1,64}$/.test(e.code ?? '') ? e.code : 'invalid-request') + '\n');
process.exitCode = 2;
// E2E6 fix 6: a request that never left (no socket, or the connect refused) keeps its code and
// exits NOT_SENT_EXIT, so `mosaic` can say the bus is not running. Every other failure exits 2.
process.exitCode = e?.notSent === true ? NOT_SENT_EXIT : 2;
}
+19
View File
@@ -218,6 +218,19 @@ group(
"R8: a hire raised from a pack proposal matches its recorded pin",
"The role entry stored with this proposal no longer matches the hash it was recorded with. Preview and apply the pack again for a fresh proposal, then raise the hire from that one."
);
// Ruling 2026-11-14: a person's pack apply is the hire decision. The hire action works from the packs
// entry an apply recorded, and each hire runs as the chief's harness and model, else the org
// assistant's (lane pr2).
group(
"pack-not-applied",
"R8: a pack hire works from the packs entry an apply recorded",
"Preview and apply the pack first; its proposed hires come from the packs entry that apply records."
);
group(
"pack-hire-route-missing",
"R3/R8: a hire runs as a harness and model the organization names",
"Neither the chief of staff nor the organization's assistant resolves a harness and a model. Give the chief of staff or the assistant both in its vars, or set them at the organization or system level, then use the pack's hire action again."
);
// #1873 SP8: a saved template carries no credential the bus holds. Save checks every kept string and
// key against the credential store; a hit names the field, never the text.
group(
@@ -225,6 +238,12 @@ group(
"R1/R10: a saved template carries no credential value the bus holds",
"A field the template would keep holds a credential value. Remove it from the named definition, board or workflow text, then preview and save again."
);
// E2E6 fix 8: save never replaces a template already saved under the name.
group(
"template-exists",
"R10: a saved template is never replaced",
"A template of this name is already saved for your account. Save under another name, or list your saved templates to pick a free one."
);
group(
"not-resolver",
"Role resolve right and decision route",
+61 -3
View File
@@ -300,7 +300,7 @@ const COPY_SWEEP_MS = 60000;
const PACK_AS = /^(definitions|workflows)\.([a-z0-9][a-z0-9._-]{0,63})=([a-z0-9][a-z0-9._-]{0,63})$/;
const SAVED_PREFIX = 'saved:';
// Each op, and whether it writes.
const PACK_OPS = Object.freeze({ packs: false, 'pack.preview': false, 'pack.apply': true, 'board.set': true, 'workflow.set': true });
const PACK_OPS = Object.freeze({ packs: false, 'pack.preview': false, 'pack.state': false, 'pack.apply': true, 'board.set': true, 'workflow.set': true });
const EMPTY_CHIEF = Object.freeze({ tools: [], network: 'none', authority: { withinRole: [], crossRole: [] }, credentials: [] });
function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean, configDir }) {
const bad = () => { throw new BusError('invalid-request'); };
@@ -501,9 +501,67 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
return `projects.${args.project}.${key}`;
};
const revisionOf = args => { if (typeof args.revision !== 'string' || !/^[0-9a-f]{64}$/.test(args.revision)) bad(); return args.revision; };
// Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): the
// organization facts the broker's pack hire loop and the packs read need, as the file stands.
// `pack` names a packs entry the way apply names the pack: saved:NAME is the owner's saved
// template, any other name the latest shipped or installed entry of that id. The route is a
// resolved harness, model and thinking (system, organization and agent vars): the chief's (the
// launch.by instance), else the org assistant's (lane pr2, lead ruling 2026-11-14), else null.
// routeFrom names which one gave it.
const latestEntries = doc => {
const latest = new Map();
for (const e of doc.packs ?? []) if (isObject(e) && typeof e.id === 'string') latest.set(canonicalJson([e.id, e.origin ?? null, e.project ?? null]), e);
return [...latest.values()];
};
const agentsOf = doc => {
const launched = doc.launch?.instances ?? [];
const one = (entry, isLaunched) => ({ hireDecision: typeof entry?.hireDecision === 'string' ? entry.hireDecision : null, launched: isLaunched });
return {
org: Object.fromEntries(Object.entries(doc.roles ?? {}).map(([name, e]) => [name, one(e, launched.includes(name))])),
projects: Object.fromEntries(Object.entries(doc.projects ?? {}).filter(([, p]) => isObject(p) && p.kind !== 'library')
.map(([project, p]) => [project, Object.fromEntries(Object.entries(p.agents ?? {}).map(([name, e]) => [name, one(e, true)]))])),
};
};
// The org assistant is the instance whose definition is `assistant` (broker.mjs continuationEffect);
// with several, the one named `assistant`, else the first in key order.
const packRoute = (doc, id) => {
const roles = doc.roles ?? {};
let loaded = null;
const routeOf = instance => {
loaded ??= validateBusinessDocument(doc, `${id}.json`, { rolesDir, dataRoot });
const { vars } = resolveInstance({ system, business: loaded, instance });
const pick = k => (typeof vars?.[k] === 'string' && vars[k] ? vars[k] : null);
if (!pick('harness') || !pick('model')) return null;
return { harness: pick('harness'), model: pick('model'), ...(pick('thinking') ? { thinking: pick('thinking') } : {}) };
};
const by = doc.launch?.by;
const chief = typeof by === 'string' && Object.hasOwn(roles, by) ? routeOf(by) : null;
if (chief) return { route: chief, routeFrom: 'chief' };
const assistants = Object.keys(roles).filter(name => isObject(roles[name]) && roles[name].definition === 'assistant');
const assistant = assistants.includes('assistant') ? 'assistant' : assistants[0];
const route = assistant === undefined ? null : routeOf(assistant);
return route ? { route, routeFrom: 'assistant' } : { route: null, routeFrom: null };
};
const applied = doc => latestEntries(doc).map(e => ({ id: e.id, origin: e.origin ?? null, project: e.project ?? null, version: e.version ?? null,
proposedHires: (Array.isArray(e.proposedHires) ? e.proposedHires : []).filter(isObject).map(h => ({ name: h.name, reason: h.reason ?? null })) }));
return {
// Shipped and installed packs only: a saved template is its owner's, read by name.
packs: async () => ({ packs: (await installed()).map(({ id, origin, pack }) => ({ id, origin, pack })) }),
// Shipped and installed packs only: a saved template is its owner's, read by name. `applied` is
// the latest packs entry of each id, origin and project, and `agents` each instance's hire record.
packs: async (id) => {
const doc = writer.read(id).document;
return { packs: (await installed()).map(({ id: pid, origin, pack }) => ({ id: pid, origin, pack })), applied: applied(doc), agents: agentsOf(doc) };
},
'pack.state': (id, args) => {
if (typeof args.pack !== 'string' || !args.pack) bad();
const project = args.project ?? null;
if (project !== null && (typeof project !== 'string' || !/^[a-z0-9][a-z0-9._-]{0,63}$/.test(project))) bad();
const { document: doc, revision } = writer.read(id);
const saved = args.pack.startsWith(SAVED_PREFIX);
const packId = saved ? args.pack.slice(SAVED_PREFIX.length) : args.pack;
const entry = (doc.packs ?? []).filter(e => isObject(e) && e.id === packId && (e.project ?? null) === project && (saved ? e.origin === 'saved' : e.origin !== 'saved')).at(-1) ?? null;
const scope = project === null ? doc.roles ?? {} : doc.projects?.[project]?.agents ?? {};
return { revision, entry: entry ? structuredClone(entry) : null, ...packRoute(doc, id), names: Object.keys(scope), noHire: [...(doc.launch?.noHire ?? [])] };
},
'pack.preview': (id, args, actor, context) => build(id, args, actor, context),
'pack.apply': async (id, args, actor, context) => {
if (typeof args.digest !== 'string') bad();
+3 -2
View File
@@ -15,7 +15,7 @@ if (!process.env.MOSAIC_BUS_TESTER_NONCE) {
// P19 #876: only the re-executed child, whose initial environment holds the nonce, talks to the
// bus. Loading the client (and the broker module graph behind it) here instead of at the top
// keeps the re-exec parent to a bare node start.
const { Client } = await import('./client.mjs');
const { Client, NOT_SENT_EXIT } = await import('./client.mjs');
const { readProcess } = await import('./human.mjs');
try {
const request = JSON.parse(readFileSync(0, 'utf8'));
@@ -39,5 +39,6 @@ try {
process.stdout.write(JSON.stringify(result) + '\n');
} catch (e) {
process.stderr.write((/^[a-z-]{1,64}$/.test(e.code ?? '') ? e.code : 'invalid-request') + '\n');
process.exitCode = 2;
// E2E6 fix 6: as human-cli.mjs, a request that never left exits NOT_SENT_EXIT.
process.exitCode = e?.notSent === true ? NOT_SENT_EXIT : 2;
}
@@ -64,7 +64,7 @@ test('AU authority reverse crossing deadline in prepared IO never publishes',asy
});
test('AU authority resolver rechecks budget removal after a proposal was raised',async t=>{
const f=world(t),d=await f.raise(),b=structuredClone(f.loaded());b.plugins['limit-check']=[];f.broker.reloadBusiness('demo',b);
const before=f.writer.read('demo').revision;await assert.rejects(f.call('judge','decision.resolve',{id:d.id,choice:'yes'}),{code:'autonomy-precondition'});
const before=f.writer.read('demo').revision;await assert.rejects(f.call('judge','decision.resolve',{id:d.id,choice:'yes'}),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
assert.equal(f.writer.read('demo').revision,before);assert.equal(f.store.get('SELECT count(*) n FROM decision_events WHERE decision=?',d.id).n,0);
});
@@ -113,7 +113,7 @@ test('AU an account-quota authority raise routes to the resolver only when the h
const covered=world(t,{account:true,countsAccount:name=>name==='pi'}),d=await covered.raise();assert.equal(d.route_to,'judge');
for(const countsAccount of [undefined,()=>false,()=>null]){
const f=world(t,{account:true,countsAccount});
await assert.rejects(f.raise(),{code:'autonomy-precondition'});
await assert.rejects(f.raise(),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
assert.equal(f.store.get("SELECT count(*) n FROM decisions").n,0);
}
});
+12 -4
View File
@@ -137,11 +137,11 @@ test('AU authority near requires an enforced organization budget covering every
const f=await settingsFixture(t);
for(const tokens of [{},{instances:{coder:tokenCap}},{providers:{unrelated:tokenCap}}]){
f.business.launch.limits.tokens=tokens;f.broker.reloadBusiness('demo',f.business);
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition'});
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
}
f.business.launch.limits.tokens={providers:{anthropic:{...tokenCap,limit:0}}};
f.business.plugins={'limit-check':[]};f.broker.reloadBusiness('demo',f.business);
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition'});
await assert.rejects(f.set(authorityNear),{code:'autonomy-precondition',reason:'no enforced budget covers new agents; authority away from the loop needs one'});
f.business.plugins={'limit-check':['token-limit']};f.broker.reloadBusiness('demo',f.business);
await f.set(authorityNear);assert.equal(f.writes(),1);
});
@@ -153,12 +153,20 @@ test('AU authority out refuses until per-definition agent limits exist, even wit
await assert.rejects(f.set({...authorityNear,authority:'out of the loop'}),e=>e.code==='authority-limits-unavailable' && /near the loop/.test(e.nextStep));
assert.equal(f.writes(),1);
});
test('AU a class moves out of the loop only from near the loop, and the refusal says so (E2E6 fix 7)',async t=>{
const f=await settingsFixture(t);await f.set({'cross-role':'in the loop'});
await assert.rejects(f.set({'cross-role':'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'cross-role moves out of the loop only from near the loop'});
assert.equal(f.writes(),1);
});
test('AU moving out requires an actual near resolution and a later owner review',async t=>{
const f=await settingsFixture(t);await f.set({merge:'in the loop'});await f.set({merge:'near the loop',notices:true});
// E2E6 fix 7: each refusal names the check that failed.
await assert.rejects(f.set({merge:'near the loop'}),{code:'autonomy-precondition',reason:'owner notices are off; a class near the loop needs them on'});
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'merge needs your review of its trail since the last autonomy change'});
f.call(f.owner,'autonomy.review.console',{decisionClass:'merge'});
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition'});
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'merge needs a near-loop decision since the last autonomy change, and your trail review after it'});
const d=f.raise({action:'git.merge.protected'});f.call(f.chief,'decision.resolve',{id:d.id,choice:'yes'});
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition'});
await assert.rejects(f.set({merge:'out of the loop',notices:true}),{code:'autonomy-precondition',reason:'merge needs a near-loop decision since the last autonomy change, and your trail review after it'});
f.call(f.owner,'autonomy.review.console',{decisionClass:'merge'});
await f.set({merge:'out of the loop',notices:true});
});
+5 -2
View File
@@ -11,6 +11,8 @@
// which shares humanCall's spawn as transport(). The human proof and its spawn are unchanged.
// Row 225 (C2-10b) re-pins webui bus.mjs for one STATUS entry, library-revert-not-agent: 409; no proof
// or transport change.
// E2E6 fix 6 re-pins human-cli.mjs, which exits 5 when its connect failed before the request was
// written, and cli transport.mjs, which reads that exit as bus-not-running. The proof is unchanged.
import test from "node:test";
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
@@ -21,9 +23,10 @@ import { Client } from "../src/client.mjs";
const baselines = {
"packages/bus/src/human.mjs": "bb13c146717cdc46d75d157177e400edac4d3e10f14fe511027a25fd44cec885",
"packages/bus/src/human-cli.mjs": "271b9781d73cf31cc562a56180e3ebcd725b5fde148a83347a201fdef2fc28af",
"packages/bus/src/human-cli.mjs": "410892787cc70440b0ba4c45d6f24861d12ee5e70cba678cfeb1ed86b796c149",
// Row 239 (#1745): EXIT outcome-unknown-revoked 1; no proof or transport change.
"packages/cli/src/transport.mjs": "662642a8ce739fcb6c188ad07125a94e008c8a305eced127c8041d472c56e55b",
// E2E6 fix 6: shim exit 5 with outcome-unknown becomes bus-not-running (exit 3, start and recover next).
"packages/cli/src/transport.mjs": "101870f7ffb47a9cbd54ebd8c1901734cc9f442d6770cb2a0d059afd4d14b160",
// Row 165 (#1662): seven STATUS entries for the role instance routes (organization-instance-exists,
// organization-unknown-instance, organization-credentials-out-of-scope, organization-launch-not-configured,
// organization-no-change, organization-project-mismatch, organization-unresolvable-instance), no proof or
+1 -1
View File
@@ -89,7 +89,7 @@ function setup(t) {
// #797 / #1839 adds the owner-only artifact read to the existing decision and request controls;
// no unsuffixed verb is ever a console verb.
test('N4: owner Console verbs have an explicit immutable whitelist and exclude decision.resolve', () => {
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'pack.hire.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.console',
// Starter packs SP4 (#1873): the owner's pack list and preview, and the three pack writes.
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console',
+367
View File
@@ -0,0 +1,367 @@
// Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): a person's
// apply records one hire decision per proposed hire in the same act and applies it, so the agents
// exist when the call returns. The owner approves every line; a member with org.hire gets the
// unflagged hires and the rest wait in the owner's inbox; an agent's apply never hires.
import test from 'node:test';
import assert from 'node:assert/strict';
import { chmodSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { DatabaseSync } from 'node:sqlite';
import { pluginHash } from '../../plugins/src/pinned.mjs';
import { installPlugin } from '../../plugins/src/install.mjs';
import { starterPack as codingPack } from '../../plugins/starter-pack/coding/index.mjs';
import { templateHash } from '../../organization/src/definitions.mjs';
const SUBJECT = { provider: 'test', iss: 'test', sub: 'owner' };
const ROUTE = { harness: 'pi', model: 'claude-opus-5-5' };
const ASSISTANT_ROUTE = { harness: 'pi', model: 'glm-5.3-flash', thinking: 'low' };
// assistant: false, no assistant instance; {} an assistant with no vars; any other object the
// assistant's vars. Lane pr2: a pack hire falls back to the org assistant's route.
async function harness(t, { route = true, assistant = false, mutate = () => {} } = {}) {
const { startBroker } = await import('../src/runtime.mjs');
const { businessDoc, rolesCopy, systemFor, writeJson } = await import('../../organization/tests/helpers.mjs');
const root = mkdtempSync(join(tmpdir(), 'packhire-'));
const rolesDir = rolesCopy(root);
const doc = businessDoc(root, 'demo');
doc.plugins = { harness: ['pi'] };
if (route) doc.roles.chief.vars = { ...ROUTE };
if (assistant) doc.roles.assistant = { definition: 'assistant', ...(Object.keys(assistant).length ? { vars: { ...assistant } } : {}) };
mutate(doc);
writeJson(join(root, 'businesses/demo.json'), doc);
const data = join(root, 'data');
mkdirSync(data, { mode: 0o700 });
const roles = { chief: { definition: 'chief-of-staff', authority: { withinRole: ['decision.resolve.technical', 'decision.resolve.delivery', 'organization.change'], crossRole: [] } },
coder: { definition: 'coder', authority: { withinRole: ['message.send'], crossRole: [] } } };
const businesses = { demo: { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles } };
const bus = await startBroker({ dataRoot: data, businesses, organization: { dir: root, rolesDir, system: systemFor(root) } });
const thaw = (p) => { const st = lstatSync(p); if (st.isSymbolicLink()) return; if (st.isDirectory()) { chmodSync(p, 0o700); for (const e of readdirSync(p)) thaw(join(p, e)); } };
t.after(async () => { await bus.close(); thaw(root); rmSync(root, { recursive: true, force: true }); });
const b = bus.broker;
const consoleOwner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
const human = b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
const member = b.bindHireConsole({ business: 'demo', actor: 'alice', subject: { provider: 'test', iss: 'test', sub: 'alice' }, rights: ['org.hire', 'board.read'] });
const call = async (verb, args = {}, cap = consoleOwner) => b.request(cap, { verb, args });
const path = join(root, 'businesses/demo.json');
const file = () => JSON.parse(readFileSync(path, 'utf8'));
const decisions = list => b.request(human, { verb: 'decisions', args: { list } });
// The broker's own database, read-only.
const db = (sql, ...a) => { const d = new DatabaseSync(join(data, 'bus/bus.sqlite'), { readOnly: true }); try { return d.prepare(sql).all(...a); } finally { d.close(); } };
const store = { all: db, get: (sql, ...a) => db(sql, ...a)[0] };
const events = () => store.all("SELECT kind, body FROM events WHERE business='demo' ORDER BY seq").map(r => ({ kind: r.kind, body: JSON.parse(r.body) }));
let n = 0;
const install = (pack) => {
const src = join(root, `src-${n++}`);
mkdirSync(join(src, 'starter-pack'), { recursive: true });
writeFileSync(join(src, 'starter-pack', 'index.mjs'), `export const interfaceVersion = 1;\nexport function starterPack() { return ${JSON.stringify(pack)}; }\n`);
const manifest = { name: pack.id, version: '1.0.0', kinds: ['starter-pack'], interfaceVersions: { 'starter-pack': 1 }, sha256: '0'.repeat(64),
source: { path: 'fixture', version: '1.0.0' }, signature: null, tools: [], actions: [], services: [], roleTemplates: [] };
writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
manifest.sha256 = pluginHash(src);
writeFileSync(join(src, 'plugin.json'), JSON.stringify(manifest));
installPlugin({ dataRoot: data, source: src, expectedHash: manifest.sha256 });
};
const op = (name) => events().filter(e => e.kind === 'action.allowed' && e.body.operation === name).map(e => e.body);
return { bus, b, root, rolesDir, path, consoleOwner, human, member, call, file, decisions, events, op, store, install };
}
const apply = async (call, args = { pack: 'coding' }, cap) => {
const preview = await call('pack.preview.console', args, cap);
return { preview, out: await call('pack.apply.console', { ...args, digest: preview.digest }, cap) };
};
// The evidence an inbox-approved hire leaves: a decision.raise naming the hire, a console
// resolution yes, a hire.consume and a hire.apply, and the instance's hireDecision.
function assertHireRecord(h, name, decision) {
const raise = h.op('decision.raise').find(r => r.decision === decision);
assert.ok(raise, `decision.raise for ${name}`);
assert.equal(raise.hire.name, name);
assert.equal(raise.action, 'role.hire');
assert.ok(h.op('hire.consume').some(r => r.decision === decision), `hire.consume for ${name}`);
assert.ok(h.op('hire.apply').some(r => r.decision === decision), `hire.apply for ${name}`);
const resolved = h.store.all('SELECT op, choice, via, by FROM decision_events WHERE decision=?', decision);
assert.deepEqual(resolved.map(r => [r.op, r.choice]), [['resolved', 'yes']]);
assert.equal(h.file().roles[name].hireDecision, decision);
}
test('PD the owner applies a pack with flagged hires on a fresh org; the agents exist on return, each with its decision record', async t => {
const h = await harness(t);
const { preview, out } = await apply(h.call);
// The preview lists the flagged and credential lines the owner's apply approves.
assert.ok(preview.hires.some(x => x.flagged.length || x.credentialLines.length), JSON.stringify(preview.hires));
assert.deepEqual(out.hires.map(x => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
const doc = h.file();
for (const x of out.hires) {
assert.ok(Object.hasOwn(doc.roles, x.name), `${x.name} exists`);
assert.ok(doc.launch.instances.includes(x.name), `${x.name} is launched`);
assertHireRecord(h, x.name, x.decision);
}
// The coder's credential lines are approved, not bound: the instance is written with no credential.
assert.equal(doc.roles['coder-1'].credentials, undefined);
// Each hire names its pack.
assert.deepEqual(h.op('pack.hire').map(e => [e.hire, e.pack, e.origin, e.project]), out.hires.map(x => [x.name, 'coding', 'shipped', null]));
// The instances read carries the pack each agent came from.
const inst = await h.call('instances', {}, h.human);
assert.deepEqual(inst.instances['coder-1'].pack, { id: 'coding', origin: 'shipped', project: null });
assert.equal(inst.instances.pm.pack, undefined);
// The packs read counts the hires and lists nothing open.
const packs = await h.call('packs.console');
const applied = packs.applied.find(a => a.id === 'coding');
assert.deepEqual(applied.hired.sort(), ['coder-1', 'pm-1', 'reviewer-1']);
assert.deepEqual(applied.open, []);
});
test('PD a re-apply hires nothing twice', async t => {
const h = await harness(t);
await apply(h.call);
const raised = h.op('decision.raise').length;
const again = await apply(h.call);
// The second apply proposes nothing: each proposal's instance exists.
assert.deepEqual(again.out.hires, []);
assert.deepEqual((await h.call('packs.console')).applied.find(a => a.id === 'coding').hired.sort(), ['coder-1', 'pm-1', 'reviewer-1']);
// The pack action on the same entry skips each instance that exists.
const hired = await h.call('pack.hire.console', { pack: 'coding' });
assert.equal(h.op('decision.raise').length, raised);
assert.ok(hired.hires.every(x => x.state === 'exists'), JSON.stringify(hired));
});
test('PD the owner CLI apply hires through the same path, resolved via cli', async t => {
const h = await harness(t);
const preview = await h.call('pack.preview', { pack: 'coding' }, h.human);
const out = await h.call('pack.apply', { pack: 'coding', digest: preview.digest }, h.human);
assert.deepEqual(out.hires.map(x => x.state), ['hired', 'hired', 'hired']);
for (const x of out.hires) {
assertHireRecord(h, x.name, x.decision);
assert.equal(h.store.get('SELECT via FROM decision_events WHERE decision=?', x.decision).via, 'cli');
assert.equal(h.store.get('SELECT raised_by_run FROM decisions WHERE id=?', x.decision).raised_by_run, 'human-cli');
}
});
test('PD with no chief route the apply records the pack, hires nothing and says why; the hire action on the existing record hires once a route exists', async t => {
const h = await harness(t, { route: false });
const { out } = await apply(h.call);
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.code]), [['pm-1', 'refused', 'pack-hire-route-missing'], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
assert.equal(h.op('decision.raise').length, 0);
const packs = await h.call('packs.console');
assert.deepEqual(packs.applied.find(a => a.id === 'coding').open.map(o => [o.name, o.state, o.code, typeof o.reason]),
[['pm-1', 'refused', 'pack-hire-route-missing', 'string'], ['coder-1', 'refused', 'pack-hire-route-missing', 'string'], ['reviewer-1', 'refused', 'pack-hire-route-missing', 'string']]);
// The owner gives the chief a route; the pack action hires from the packs entry already recorded.
const doc = h.file();
doc.roles.chief.vars = { ...ROUTE };
writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
const hired = await h.call('pack.hire.console', { pack: 'coding' });
assert.deepEqual(hired.hires.map(x => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
for (const x of hired.hires) assertHireRecord(h, x.name, x.decision);
assert.deepEqual((await h.call('packs.console')).applied.find(a => a.id === 'coding').open, []);
// The CLI's pack hire is the same action; nothing is left to hire.
const cli = await h.call('pack.hire', { pack: 'coding' }, h.human);
assert.ok(cli.hires.every(x => x.state === 'exists'));
await assert.rejects(h.call('pack.hire.console', { pack: 'nosuch' }), /pack-not-applied/);
});
// A pack with one hire inside the chief's own grants and two above them.
// An installed pack's own definition narrows a template; the scout keeps only read.
const mixkit = (rolesDir) => {
const SCOUT = { from: { template: 'coder', sha256: templateHash(rolesDir, 'coder') }, role: { tools: ['read'], network: 'none', authority: { withinRole: [], crossRole: [] }, credentials: [] }, instructions: 'Read and report.' };
const p = structuredClone(codingPack());
p.id = 'mixkit';
p.definitions = { scout: SCOUT, coder: p.definitions.coder, reviewer: p.definitions.reviewer };
p.hires = [{ name: 'scout-1', definition: 'scout', reason: 'reads and reports' }, { name: 'coder-1', definition: 'coder', reason: 'implements each change' }, { name: 'reviewer-1', definition: 'reviewer', reason: 'reviews each change' }];
p.workflows = { change: { description: 'One change.', steps: [{ id: 'build', title: 'Build it', roles: ['coder'], state: 'in-progress' }, { id: 'review', title: 'Review it', roles: ['reviewer'], state: 'in-review' }] } };
return p;
};
test('PD a member with org.hire gets the unflagged hires; the flagged ones become open decisions in the owner inbox', async t => {
const h = await harness(t, { route: false });
h.install(mixkit(h.rolesDir));
await apply(h.call, { pack: 'mixkit' });
const doc = h.file();
doc.roles.chief.vars = { ...ROUTE };
writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
const out = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
assert.deepEqual(out.hires.map(x => [x.name, x.state]), [['scout-1', 'hired'], ['coder-1', 'awaiting-owner'], ['reviewer-1', 'awaiting-owner']]);
const after = h.file();
assert.ok(after.launch.instances.includes('scout-1'));
assert.equal(Object.hasOwn(after.roles, 'coder-1'), false);
assert.equal(Object.hasOwn(after.roles, 'reviewer-1'), false);
assertHireRecord(h, 'scout-1', out.hires[0].decision);
assert.equal(h.store.get('SELECT via FROM decision_events WHERE decision=?', out.hires[0].decision).via, 'console');
// Each flagged hire is an open decision routed to the human, raised by the member's act.
const waiting = out.hires.filter(x => x.state === 'awaiting-owner');
for (const x of waiting) {
const d = h.store.get('SELECT route_to, raised_by_role, action FROM decisions WHERE id=?', x.decision);
assert.deepEqual([d.route_to, d.raised_by_role, d.action], ['human', 'human', 'role.hire']);
assert.equal(h.store.all('SELECT 1 FROM decision_events WHERE decision=?', x.decision).length, 0);
}
// The packs read lists both as open, awaiting the owner, each with the pack's reason.
const applied = (await h.call('packs.console')).applied.find(a => a.id === 'mixkit');
assert.deepEqual(applied.hired, ['scout-1']);
assert.deepEqual(applied.open.map(o => [o.name, o.state, o.reason, o.decision]), [['coder-1', 'awaiting-owner', 'implements each change', waiting[0].decision], ['reviewer-1', 'awaiting-owner', 'reviews each change', waiting[1].decision]]);
// The member's pack action never re-raises a hire an open decision names.
const again = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
assert.deepEqual(again.hires.map(x => [x.name, x.state, x.decision ?? null]), [['scout-1', 'exists', null], ['coder-1', 'open', waiting[0].decision], ['reviewer-1', 'open', waiting[1].decision]]);
// The member cannot approve a flagged hire; the owner can, from the inbox, and the agent exists.
const view = await h.call('hire.preview.console', { id: waiting[0].decision });
await assert.rejects(h.call('hire.resolve.console', { id: waiting[0].decision, choice: 'yes', digest: view.digest }, h.member), /hire-owner-required|human-required/);
await h.call('hire.resolve.console', { id: waiting[0].decision, choice: 'yes', digest: view.digest });
assert.ok(h.file().launch.instances.includes('coder-1'));
// The owner's pack action approves the rest: the open pack decision is withdrawn by the owner and
// replaced by one approved in the same act.
const owner = await h.call('pack.hire.console', { pack: 'mixkit' });
assert.deepEqual(owner.hires.map(x => [x.name, x.state, x.supersedes ?? null]), [['scout-1', 'exists', null], ['coder-1', 'exists', null], ['reviewer-1', 'hired', waiting[1].decision]]);
assert.deepEqual(h.store.all('SELECT op, by FROM decision_events WHERE decision=?', waiting[1].decision).map(r => [r.op, r.by]), [['withdrawn', 'jason']]);
assertHireRecord(h, 'reviewer-1', owner.hires[2].decision);
const done = (await h.call('packs.console')).applied.find(a => a.id === 'mixkit');
assert.deepEqual(done.hired.sort(), ['coder-1', 'reviewer-1', 'scout-1']);
assert.deepEqual(done.open, []);
});
test('PD an agent apply still refuses human-required and hires nothing; the tester and a cli cap on the console name refuse', async t => {
const h = await harness(t);
const agent = h.b.bindLaunch({ business: 'demo', role: 'coder', run: 'coder-run', harness: 'pi', address: 'coder-run' });
h.b.request(agent, { verb: 'role.claim' });
assert.throws(() => h.b.request(agent, { verb: 'pack.apply.console', args: { pack: 'coding', digest: 'a'.repeat(64) } }), /human-required/);
await assert.rejects(Promise.resolve().then(() => h.b.request(agent, { verb: 'pack.hire', args: { pack: 'coding' } })), /human-required/);
await assert.rejects(Promise.resolve().then(() => h.b.request(agent, { verb: 'pack.hire.console', args: { pack: 'coding' } })), /human-required/);
await assert.rejects(Promise.resolve().then(() => h.b.request(h.human, { verb: 'pack.hire.console', args: { pack: 'coding' } })), /human-required/);
await assert.rejects(h.call('pack.hire', { pack: 'coding' }), /human-required/);
for (const args of [{}, { pack: 7 }, { pack: 'coding', extra: 1 }, { pack: 'coding', project: 'Bad Name' }])
await assert.rejects(h.call('pack.hire.console', args), /invalid-request/);
assert.equal(h.op('decision.raise').length, 0);
});
test('PD a project pack hires into projects.<p>.agents', async t => {
const h = await harness(t);
const pack = structuredClone(codingPack());
pack.id = 'projkit'; pack.scope = 'project';
h.install(pack);
const { out } = await apply(h.call, { pack: 'projkit', project: 'stack' });
assert.deepEqual(out.hires.map(x => x.state), ['hired', 'hired', 'hired']);
const agents = h.file().projects.stack.agents;
for (const x of out.hires) { assert.equal(agents[x.name].hireDecision, x.decision); assert.equal(agents[x.name].credentials, undefined); }
assert.equal(Object.hasOwn(h.file().roles, 'coder-1'), false);
assert.deepEqual(h.op('pack.hire').map(e => e.project), ['stack', 'stack', 'stack']);
const applied = (await h.call('packs.console')).applied.find(a => a.id === 'projkit');
assert.deepEqual(applied.hired.sort(), ['coder-1', 'pm-1', 'reviewer-1']);
const again = await h.call('pack.hire.console', { pack: 'projkit', project: 'stack' });
assert.ok(again.hires.every(x => x.state === 'exists'));
});
test('PD the new codes are in the refusal table with a rail and a next step that names no path', async () => {
const { REFUSALS } = await import('../src/refusals.mjs');
for (const c of ['pack-not-applied', 'pack-hire-route-missing', 'hire-owner-required', 'no-chief-of-staff']) {
assert.ok(Object.hasOwn(REFUSALS, c), c);
assert.ok(REFUSALS[c].rail?.length > 5);
assert.ok(REFUSALS[c].nextStep?.length > 20);
assert.ok(!/(^|[\s("'`])(\/|~\/)/.test(REFUSALS[c].nextStep));
}
});
test('PD the owner supersede withdraws an inbox decision only after its replacement hires; a refused replacement leaves it open', async t => {
const h = await harness(t, { route: false });
h.install(mixkit(h.rolesDir));
await apply(h.call, { pack: 'mixkit' });
const setRoute = (vars) => { const doc = h.file(); if (vars) doc.roles.chief.vars = { ...vars }; else delete doc.roles.chief.vars; writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n'); };
setRoute(ROUTE);
const out = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
const waiting = out.hires.filter(x => x.state === 'awaiting-owner');
assert.equal(waiting.length, 2);
// The packs read marks each member-raised line as raised by a pack hire.
const open = (await h.call('packs.console')).applied.find(a => a.id === 'mixkit').open;
assert.deepEqual(open.map(o => [o.name, o.state, o.fromPack]), [['coder-1', 'awaiting-owner', true], ['reviewer-1', 'awaiting-owner', true]]);
// The chief loses its route; the owner's pack hire cannot build a replacement.
setRoute(null);
const owner = await h.call('pack.hire.console', { pack: 'mixkit' });
assert.deepEqual(owner.hires.map(x => [x.name, x.state, x.code ?? null]), [['scout-1', 'exists', null], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
// Both inbox decisions are still open: nothing withdrew them.
for (const x of waiting) assert.deepEqual(h.store.all('SELECT op FROM decision_events WHERE decision=?', x.decision), []);
// With the route back, the owner's pack hire replaces them, withdrawing each only once its replacement applied.
setRoute(ROUTE);
const done = await h.call('pack.hire.console', { pack: 'mixkit' });
assert.deepEqual(done.hires.map(x => [x.name, x.state, x.supersedes ?? null]), [['scout-1', 'exists', null], ['coder-1', 'hired', waiting[0].decision], ['reviewer-1', 'hired', waiting[1].decision]]);
for (const x of waiting) assert.deepEqual(h.store.all('SELECT op, by FROM decision_events WHERE decision=?', x.decision).map(r => [r.op, r.by]), [['withdrawn', 'jason']]);
});
test('PD a second pack hire on the same organization while one runs refuses organization-busy and raises nothing', async t => {
const h = await harness(t, { route: false });
await apply(h.call);
const doc = h.file();
doc.roles.chief.vars = { ...ROUTE };
writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
const first = h.call('pack.hire.console', { pack: 'coding' });
const second = h.call('pack.hire.console', { pack: 'coding' });
await assert.rejects(second, /organization-busy/);
const hired = await first;
assert.deepEqual(hired.hires.map(x => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
// One decision per hire: the refused call raised nothing.
assert.equal(h.op('decision.raise').length, 3);
// Once the loop ends the latch is free again: the next pack hire runs and finds nothing to hire.
const later = await h.call('pack.hire.console', { pack: 'coding' });
assert.ok(later.hires.every(x => x.state === 'exists'), JSON.stringify(later));
});
// Lane pr2 (lead ruling 2026-11-14): a pack hire takes the chief of staff's harness and model, else
// the org assistant's, else refuses pack-hire-route-missing.
test('PR2 with no chief route the apply hires every proposal with the org assistant harness and model', async t => {
const h = await harness(t, { route: false, assistant: ASSISTANT_ROUTE });
const { out } = await apply(h.call);
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.routeFrom]), [['pm-1', 'hired', 'assistant'], ['coder-1', 'hired', 'assistant'], ['reviewer-1', 'hired', 'assistant']]);
const doc = h.file();
for (const x of out.hires) {
assertHireRecord(h, x.name, x.decision);
assert.deepEqual(doc.roles[x.name].vars, ASSISTANT_ROUTE);
assert.deepEqual(h.op('decision.raise').find(r => r.decision === x.decision).hire.route, ASSISTANT_ROUTE);
}
});
test('PR2 a chief route wins over a different assistant route', async t => {
const h = await harness(t, { assistant: ASSISTANT_ROUTE });
const { out } = await apply(h.call);
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.routeFrom]), [['pm-1', 'hired', 'chief'], ['coder-1', 'hired', 'chief'], ['reviewer-1', 'hired', 'chief']]);
for (const x of out.hires) assert.deepEqual(h.file().roles[x.name].vars, ROUTE);
});
test('PR2 an assistant with no harness and model gives no route: the apply refuses as before', async t => {
for (const assistant of [{}, { harness: 'pi' }]) {
const h = await harness(t, { route: false, assistant });
const { out } = await apply(h.call);
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.code]), [['pm-1', 'refused', 'pack-hire-route-missing'], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
assert.equal(h.op('decision.raise').length, 0);
}
});
test('PR2 with several assistants the one named assistant gives the route, else the first in key order', async t => {
const OTHER = { harness: 'pi', model: 'claude-sonnet-5-5' };
const named = await harness(t, { route: false, assistant: ASSISTANT_ROUTE, mutate: doc => { doc.roles = { aide: { definition: 'assistant', vars: { ...OTHER } }, ...doc.roles }; } });
const a = await apply(named.call);
for (const x of a.out.hires) assert.deepEqual(named.file().roles[x.name].vars, ASSISTANT_ROUTE);
const first = await harness(t, { route: false, mutate: doc => { doc.roles.aide = { definition: 'assistant', vars: { ...OTHER } }; doc.roles.zed = { definition: 'assistant', vars: { ...ASSISTANT_ROUTE } }; } });
const b = await apply(first.call);
assert.deepEqual(b.out.hires.map(x => [x.state, x.routeFrom]), [['hired', 'assistant'], ['hired', 'assistant'], ['hired', 'assistant']]);
for (const x of b.out.hires) assert.deepEqual(first.file().roles[x.name].vars, OTHER);
});
test('PR2 a member pack hire on the assistant route marks hired and awaiting-owner lines routeFrom assistant', async t => {
const h = await harness(t, { route: false, assistant: ASSISTANT_ROUTE });
h.install(mixkit(h.rolesDir));
// The member's apply would not run; the owner's apply would hire everything. Record the pack first
// with the assistant route absent, then give it back and let the member hire.
const doc0 = h.file(); delete doc0.roles.assistant.vars; writeFileSync(h.path, JSON.stringify(doc0, null, 2) + '\n');
await apply(h.call, { pack: 'mixkit' });
const doc = h.file(); doc.roles.assistant.vars = { ...ASSISTANT_ROUTE }; writeFileSync(h.path, JSON.stringify(doc, null, 2) + '\n');
const out = await h.call('pack.hire.console', { pack: 'mixkit' }, h.member);
assert.deepEqual(out.hires.map(x => [x.name, x.state, x.routeFrom]), [['scout-1', 'hired', 'assistant'], ['coder-1', 'awaiting-owner', 'assistant'], ['reviewer-1', 'awaiting-owner', 'assistant']]);
assert.deepEqual(h.file().roles['scout-1'].vars, ASSISTANT_ROUTE);
});
test('PR2 a project pack with no chief route hires into the project on the assistant route', async t => {
const h = await harness(t, { route: false, assistant: ASSISTANT_ROUTE });
const pack = structuredClone(codingPack());
pack.id = 'projkit'; pack.scope = 'project';
h.install(pack);
const { out } = await apply(h.call, { pack: 'projkit', project: 'stack' });
assert.deepEqual(out.hires.map(x => [x.state, x.routeFrom]), [['hired', 'assistant'], ['hired', 'assistant'], ['hired', 'assistant']]);
const agents = h.file().projects.stack.agents;
for (const x of out.hires) { assert.equal(agents[x.name].hireDecision, x.decision); assert.deepEqual(h.op('decision.raise').find(r => r.decision === x.decision).hire.route, ASSISTANT_ROUTE); }
});
+1 -1
View File
@@ -90,7 +90,7 @@ const ask = (x, state, extra = {}) => x.call('pm', 'request.question', { request
options: [{ key: 'web', text: 'Web' }, { key: 'cli', text: 'CLI' }], ...extra });
test('the console verb list includes the artifact read and existing owner controls', () => {
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
assert.deepEqual([...CONSOLE_VERBS], ['project.remote.get.console', 'project.remote.set.console', 'autonomy.get.console', 'autonomy.set.console', 'autonomy.review.console', 'decision.confirm.console', 'decision.reverse.console', 'request.workspace.console', 'request.artifact.console', 'decision.preview.console', 'decision.resolve.console', 'hire.preview.console', 'hire.resolve.console', 'hire.start.console', 'hire.templates.console', 'pack.hire.console', 'prd.revoke.console', 'request.mode.console', 'request.draft.console',
'request.get.console', 'request.projects.console', 'request.answer.console', 'request.attach.console', 'request.cancel.console',
// Starter packs SP4 (#1873): the owner's pack list and preview, and the three pack writes.
'packs.console', 'pack.preview.console', 'pack.apply.console', 'board.set.console', 'workflow.set.console',
+1 -1
View File
@@ -154,7 +154,7 @@ test('SP8 argument checks: a second save, a .. name, an unknown key, preview wit
const { call, saved } = await harness(t);
const { preview } = await save(call, 'demo-shape');
const first = readFileSync(saved('demo-shape'));
await assert.rejects(call('template.save.console', { name: 'demo-shape', digest: preview.digest }), (e) => e.code === 'invalid-request' && e.reason === 'a template of this name is already saved');
await assert.rejects(call('template.save.console', { name: 'demo-shape', digest: preview.digest }), (e) => e.code === 'template-exists' && e.reason === 'a template of this name is already saved; save under another name');
assert.deepEqual(readFileSync(saved('demo-shape')), first);
for (const name of ['..', '../x', 'a/b']) await assert.rejects(call('template.save.console', { name, preview: true }), { code: 'invalid-request' });
for (const args of [{ name: 'x', preview: true, account: 'alex' }, { name: 'x', preview: true, digest: preview.digest }, { name: 'x' }, { preview: true }, { name: 'x', preview: false }])
+21
View File
@@ -121,3 +121,24 @@ test('committed mutation followed by dropped reply reports unknown and is never
assert.equal(calls, 1);
assert.equal(store.get('SELECT count(*) n FROM messages').n, 1);
});
// E2E6 fix 6: a connect that fails before the request is written is marked notSent; the code stays
// outcome-unknown for every caller. A request that left and got no answer is not marked.
test('E2E6 a failed connect is outcome-unknown marked notSent; a dropped answer is not marked', async (t) => {
const { createServer } = await import('node:net');
const { writeFileSync } = await import('node:fs');
const { NOT_SENT_EXIT } = await import('../src/client.mjs');
assert.equal(NOT_SENT_EXIT, 5);
const dir = mkdtempSync(join(tmpdir(), 'e2e6-'));
t.after(() => rmSync(dir, { recursive: true, force: true }));
const plain = join(dir, 'plain');
writeFileSync(plain, '');
for (const path of [join(dir, 'missing.sock'), plain, join(plain, 'below')]) {
await assert.rejects(new Client({ path, cap: 'x' }).call('inbox', {}), (e) => e.code === 'outcome-unknown' && e.notSent === true, path);
}
const sock = join(dir, 'drop.sock');
const server = createServer((c) => c.once('data', () => c.destroy()));
await new Promise((r) => server.listen(sock, r));
t.after(() => server.close());
await assert.rejects(new Client({ path: sock, cap: 'x' }).call('inbox', {}), (e) => e.code === 'outcome-unknown' && e.notSent === undefined);
});
+17
View File
@@ -1363,6 +1363,23 @@ message, an answer that never came exits 1, an unknown template exits 2. All of
these verbs, reads included, refuse inside an agent run (exit 3) after their
usage checks (exit 4) and before any config is read.
Starter pack hires (ruling 2026-11-14, #1873): `mosaic org pack apply ID PACK
--digest D [--project P]` is the owner's hire decision. After the pack commits,
the same command hires each proposed agent through the bus's hire-decisions
path (`pack.apply` as the organization's human) and the receipt adds `hires`,
one `{name, state, decision | code}` per proposal: `hired`, `exists` (an
instance by that name is there), `open` (a hire decision already names it),
`awaiting-owner` or `refused` with the hire's code. The owner's apply approves
the flagged and credential lines; a credential line is approved, not bound, so
the agent's launch is refused `credential-unbound` until its services are
bound. `mosaic org pack hire ID PACK [--project P]` (`pack.hire`) runs the same
loop on a pack already applied, for the proposals an earlier apply left open,
and hires none twice; a pack with no packs entry is refused `pack-not-applied`
with the hint to preview and apply it first. A proposal is refused
`pack-hire-route-missing` when neither the chief of staff nor the
organization's assistant has a harness and model to give it; the chief's route
wins when both have one. Like the other pack words, both refuse inside an agent run (exit 3).
`mosaic tasks create|edit|archive` are the task board's three writes. The
arguments pass the board's own check, then go to the bus as the person
(`tasks.create`, `tasks.edit`, `tasks.archive`), so the bus runs its human,
+1
View File
@@ -845,6 +845,7 @@ export async function run(argv, io = { env: process.env, stdin: process.stdin, s
if (!(error instanceof CliError)) throw error;
io.stderr.write(`mosaic: ${error.message}\n`);
if (OTHER_TREE_CODES.has(error.code)) io.stderr.write(`mosaic: ${OTHER_TREE}\n`);
if (typeof error.next === "string" && error.next !== "") io.stderr.write(`mosaic: next: ${error.next}\n`);
return error.exitCode;
}
}
+5 -1
View File
@@ -3,11 +3,15 @@
// input, a decision or option that doesn't exist); 3 refused (system or
// business config problem, the broker or notifier refused, the human proof
// refused, a host already running); 4 usage.
//
// E2E6: `next` is an optional next-step line. run() prints it after the message as
// `mosaic: next: ...`; the message itself stays as callers (the Console among them) match it.
export class CliError extends Error {
constructor(message, exitCode = 2) {
constructor(message, exitCode = 2, { next } = {}) {
super(message);
this.name = "CliError";
this.exitCode = exitCode;
if (typeof next === "string" && next !== "") this.next = next;
}
}
+7 -1
View File
@@ -76,6 +76,11 @@ const same = (a, b) => a?.pid === b?.pid && a?.startTime === b?.startTime && a?.
// tried again, like one that goes before the check. `found` runs once the
// lock is found and before it is read, `between` after the stale lock is
// read; both are for the tests. Exported for the tests.
// E2E6 fix 1: every stale-lock refusal names the verb that clears a host that died.
export const recoverNext = (business) =>
typeof business === "string" && /^[a-z0-9][a-z0-9._-]{0,63}$/.test(business)
? `if the bus host died, clear it with mosaic bus recover ${business}; recover refuses while the host still runs`
: "if the bus host died, clear it with mosaic bus recover <org>; recover refuses while the host still runs";
export function claimHostLock(dataRoot, state, { found = () => {}, between = () => {}, refuseStale = false } = {}) {
mkdirSync(hostDir(dataRoot), { recursive: true, mode: 0o700 });
const file = hostLock(dataRoot);
@@ -94,7 +99,8 @@ export function claimHostLock(dataRoot, state, { found = () => {}, between = ()
const prior = readState(file, found);
if (!prior) continue;
if (prior.live) throw new CliError(`a bus host already runs for ${prior.business} (pid ${prior.pid})`, 3);
if (refuseStale) throw new CliError("stale bus host lock", 3);
// E2E6 fix 1: the message stays (the Console matches it); the next line names the clearing verb.
if (refuseStale) throw new CliError("stale bus host lock", 3, { next: recoverNext(prior.business) });
between();
try {
renameSync(file, aside);
+11 -9
View File
@@ -8,7 +8,7 @@ import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { resolveOrg, withOrgLifecycle } from '../../organization/src/org-registry.mjs';
import { orgPaths } from './config.mjs';
import { cmdlineOf, hostFile, hostLock, hostStatus, readHostState, startTimeOf, stopHost } from './host.mjs';
import { cmdlineOf, hostFile, hostLock, hostStatus, readHostState, recoverNext, startTimeOf, stopHost } from './host.mjs';
import { CliError } from './errors.mjs';
import { readBootStatus } from './boot-status.mjs';
@@ -27,20 +27,22 @@ async function target(ctx, id, allowDeleting = false) {
return { ...org, paths: orgPaths(org.root) };
}
function checkedState(org) {
// E2E6 fix 1: each refusal keeps its message and adds the recover line as its next step.
const stale = message => { throw new CliError(message, 3, { next: recoverNext(org.id) }); };
const s = hostStatus(org.root);
let lock = null;
try { lock = JSON.parse(readFileSync(hostLock(org.root), 'utf8')); }
catch (e) { if (e.code !== 'ENOENT') fail('bus host lock is unreadable'); }
if (lock && (!Number.isSafeInteger(lock.pid) || typeof lock.startTime !== 'string' || startTimeOf(lock.pid) !== lock.startTime)) fail('stale bus host lock');
if (s.host && (!s.host.live || s.host.business !== org.id)) fail('stale or mismatched bus host state');
catch (e) { if (e.code !== 'ENOENT') stale('bus host lock is unreadable'); }
if (lock && (!Number.isSafeInteger(lock.pid) || typeof lock.startTime !== 'string' || startTimeOf(lock.pid) !== lock.startTime)) stale('stale bus host lock');
if (s.host && (!s.host.live || s.host.business !== org.id)) stale('stale or mismatched bus host state');
if (s.host) {
const args = cmdlineOf(s.host.pid) ?? [], i = args.indexOf(CLI);
if (i < 0 || args[i + 1] !== 'bus' || args[i + 2] !== 'start' || args[i + 3] !== org.id) fail('bus host identity mismatch');
if (i < 0 || args[i + 1] !== 'bus' || args[i + 2] !== 'start' || args[i + 3] !== org.id) stale('bus host identity mismatch');
}
if (lock && (!s.host || lock.pid !== s.host.pid || lock.business !== org.id)) fail('bus host lock does not match host state');
if (s.writerLock && !s.writerLock.live) fail('stale bus writer lock');
if (!s.host && s.writerLock) fail('bus writer lock has no matching host');
if (s.host && !lock) fail('bus host lock is missing');
if (lock && (!s.host || lock.pid !== s.host.pid || lock.business !== org.id)) stale('bus host lock does not match host state');
if (s.writerLock && !s.writerLock.live) stale('stale bus writer lock');
if (!s.host && s.writerLock) stale('bus writer lock has no matching host');
if (s.host && !lock) stale('bus host lock is missing');
return s;
}
export function probeBusSocket(path, { signal, deadline } = {}) {
+72 -7
View File
@@ -3,7 +3,7 @@ import { randomBytes } from 'node:crypto';
import { processState } from '../../seat/src/process-state.mjs';
import { spawn } from 'node:child_process';
import { request as httpRequest } from 'node:http';
import { constants, closeSync, fstatSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, renameSync, writeFileSync, writeSync } from 'node:fs';
import { constants, closeSync, fstatSync, ftruncateSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, renameSync, writeFileSync, writeSync } from 'node:fs';
import { basename, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { listOrgs, resolveOrg } from '../../organization/src/org-registry.mjs';
@@ -60,14 +60,79 @@ function removeStale(ctx, s, warn) {
warn(`mosaic: stale console state moved to ${aside}\n`);
return true;
}
function takeLock(ctx) {
// E2E6 fix 4: what a start.lock that already exists names. Null when it names no holder: unreadable,
// empty (a holder between its open and its write), not a regular file of this user, or a bad pid or
// start time. Such a lock is never cleared. A lock its holder marked released ({"released":true},
// written through the holder's own descriptor) names no live holder and is cleared (f6c review P3-1).
function lockHolder(path) {
let fd;
try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
catch { return null; }
try {
const st = fstatSync(fd);
if (!st.isFile() || st.uid !== process.getuid() || st.nlink !== 1 || st.size > 4096) return null;
const data = JSON.parse(readFileSync(fd, 'utf8'));
if (data?.released === true && Object.keys(data).length === 1) return { released: true, dev: st.dev, ino: st.ino };
if (!Number.isSafeInteger(data?.pid) || data.pid <= 0 || typeof data.startTime !== 'string' || !/^\d+$/.test(data.startTime)) return null;
return { pid: data.pid, startTime: data.startTime, dev: st.dev, ino: st.ino };
} catch { return null; } finally { closeSync(fd); }
}
// True when the process the lock names (pid and start time) is gone. A /proc read that cannot settle
// it counts as live, so an uncertain holder is never cleared.
function holderGone(holder) {
if (holder.released) return true;
let p;
try { p = processState(holder.pid); } catch { return false; }
return !p.alive || p.startTime !== holder.startTime;
}
// Moves aside and removes the lock the holder check read, and only that file: a lock another start
// took in between is put back and the clear refuses.
function clearLock(path, holder) {
const aside = `${path}.dead-${randomBytes(4).toString('hex')}`;
try { renameSync(path, aside); } catch { fail('console start lock changed while it was being cleared; run the command again'); }
const st = lstatSync(aside);
if (st.dev !== holder.dev || st.ino !== holder.ino) {
// Put back without replacing: if a third start took the path meanwhile, the aside stays for a human.
let restored = false;
try { linkSync(aside, path); restored = true; } catch { /* left aside */ }
if (restored) rmSync(aside, { force: true });
fail('console start lock changed while it was being cleared; run the command again');
}
rmSync(aside, { force: true });
}
function takeLock(ctx, warn = () => {}) {
checkDir(ctx);
const path = join(directory(ctx), 'start.lock');
let fd; try { fd = openSync(path, 'wx', 0o600); } catch { fail('console start lock exists'); }
let fd;
for (let cleared = false; fd === undefined;) {
try { fd = openSync(path, 'wx', 0o600); }
catch (e) {
if (e?.code !== 'EEXIST' || cleared) fail('console start lock exists');
// E2E6 fix 4: a lock whose named holder (pid and start time) is gone is cleared once, and the
// take tried again. A live holder, or a lock that names none, refuses and stays.
const holder = lockHolder(path);
if (!holder) fail('console start lock exists and names no holder; remove console/start.lock under the data root once no console start or stop runs');
if (!holderGone(holder)) fail(`console start lock is held by process ${holder.pid}, which still runs; wait for its start or stop to finish`);
clearLock(path, holder);
warn(holder.released ? 'mosaic: cleared a console start lock its holder had released\n' : `mosaic: cleared a console start lock left by process ${holder.pid}, which is gone\n`);
cleared = true;
}
}
// D1: the lock names its holder, so a detached start that timed out can clear the lock of the
// supervisor it killed (clearDeadLock) and no other.
// supervisor it killed (clearDeadLock), and a later start or stop can clear it once that holder is gone.
try { writeSync(fd, JSON.stringify({ pid: process.pid, startTime: startTimeOf(process.pid) })); } catch { /* an unnamed lock is only never cleared */ }
return () => { closeSync(fd); rmSync(path, { force: true }); };
// f6c review P3-1: the release marks its own file released, through its own descriptor, and removes
// the path only while the path is still that file. A clear that moved the lock aside and puts it back
// after this release puts back a released lock, which the next start or stop clears; and the release
// never removes a lock another start took meanwhile.
// A failed marker write (disk full) still removes the path: an empty lock would refuse forever.
return () => {
try {
try { ftruncateSync(fd, 0); writeSync(fd, JSON.stringify({ released: true }), 0); } catch { /* the matched unlink below still runs */ }
const own = fstatSync(fd), now = lstatSync(path);
if (own.dev === now.dev && own.ino === now.ino) rmSync(path, { force: true });
} catch { /* gone already, or moved aside by a clear */ } finally { closeSync(fd); }
};
}
// Removes start.lock only when it names this exact process (pid and start time) and that process
// is gone. A lock that is unreadable, unnamed or another holder's stays.
@@ -242,7 +307,7 @@ export async function consoleStart(ctx, { devLocalOwner = false, detach = false,
// re-check P1). A Restart Console relaunch goes through relaunch(), not here.
refuseInsideAgent(process.env); if (ctx.env) refuseInsideAgent(ctx.env);
if (detach && devLocalOwner) return detachedSupervisor(ctx, { port, bind, allowHosts, warn });
const release = takeLock(ctx);
const release = takeLock(ctx, warn);
let run, args;
try {
const prior = state(ctx);
@@ -266,7 +331,7 @@ export async function consoleStart(ctx, { devLocalOwner = false, detach = false,
return result;
}
export async function consoleStop(ctx, { warn = s => process.stderr.write(s) } = {}) {
const release = takeLock(ctx);
const release = takeLock(ctx, warn);
try {
const s = state(ctx);
if (!s || removeStale(ctx, s, warn)) return { stopped: false };
+34
View File
@@ -4,10 +4,12 @@
// credential store, whose held-secret check every definition write needs (R1), and no other process
// holds the tokens it looks for. Each write prints its receipt.
import { readFile } from 'node:fs/promises';
import { basename } from 'node:path';
import { configDir } from '../../organization/src/organization-config.mjs';
import { organizationWriter } from '../../organization/src/organization.mjs';
import { definitionVerbs } from '../../organization/src/definition-verbs.mjs';
import { checkDefinition } from '../../organization/src/definitions.mjs';
import { ID_PATTERN } from '../../organization/src/vocabulary.mjs';
import { rolesDir } from './config.mjs';
import { CliError } from './errors.mjs';
import { busExit, refuseInsideAgent } from './transport.mjs';
@@ -59,6 +61,33 @@ function refusal(code, verb, name, rev, read) {
return error;
}
// E2E6 fix 2: a read or a write's file check that fails says so in one line: an unknown
// organization, a missing definition or a bad file, by code. No stack trace, and no host path: a raw
// filesystem error is named by its operation and code, and any absolute path left in a message is cut.
const NAME_SHOWN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
function missing(id, name) { return `${NAME_SHOWN.test(name ?? '') ? `definitions declares no ${name}` : 'definitions declares no definition by that name'}; list them with mosaic org definitions ${id} list`; }
// f6c review P3-3: a path after ':' or a backtick is cut too.
function pathFree(message) { return String(message).replace(/(^|[\s'"(=:`])\/[^\s'"),`]*/g, '$1<path>'); }
export function definitionsFailure(e, id, name) {
if (e instanceof CliError) return e;
const coded = (code, text, exit = 3) => Object.assign(new CliError(`${code}: ${text}`, exit), { code });
if (typeof e?.syscall === 'string' && typeof e.code === 'string' && /^E[A-Z0-9]+$/.test(e.code)) {
// f6c review P3-2: only a missing organization file means no organization; another missing file
// (the roles directory for `templates`, a role template) says which operation failed.
if (e.code === 'ENOENT' && (typeof e.path !== 'string' || basename(e.path) === `${id}.json`)) return coded('unknown-organization', `this instance has no organization ${id}; list them with mosaic org list`);
if (id === 'templates' || id === undefined) return coded('definitions-unreadable', `cannot ${e.syscall} a file the definitions command reads (${e.code})`);
return coded('organization-unreadable', `cannot ${e.syscall} the file of organization ${id} (${e.code})`);
}
const message = typeof e?.message === 'string' ? e.message : '';
if (/^definitions declares no /.test(message)) return coded('definition-missing', missing(id, name));
if (typeof e?.code === 'string' && /^[a-z][a-z-]{0,63}$/.test(e.code)) {
const text = e.code === 'definition-missing' ? missing(id, name) : pathFree(message);
return coded(e.code, text);
}
if (e?.name === 'OrganizationConfigError' || e?.name === 'BusinessError') return coded('organization-invalid', pathFree(message));
return coded('definitions-failed', 'the definitions command failed', 1);
}
// deps.callFor(parsed) returns the human's call(verb, args) for the organization parsed names (cli.mjs
// passes its callFor). Without one, a write refuses: it never runs without the bus's secret check.
export async function definitionsCommand(args, io, deps = {}) {
@@ -68,6 +97,10 @@ export async function definitionsCommand(args, io, deps = {}) {
const ifRev = () => { const r = need('--if-rev'); if (!/^[1-9][0-9]*$/.test(r)) throw new CliError('invalid --if-rev', 4); return Number(r); };
const [id, verb, name] = pos;
if (WRITES.includes(verb)) refuseInsideAgent(io.env);
if (id !== 'templates' && id !== undefined && !ID_PATTERN.test(id)) throw new CliError(`invalid organization id: an id is 1 to 64 of a-z, 0-9, '.', '_' and '-', starting with a letter or digit\n${DEFINITIONS_USAGE}`, 4);
try { await run(); }
catch (e) { throw definitionsFailure(e, id, name); }
async function run() {
const writer = deps.writer ?? organizationWriter({ dir: configDir(io.env), rolesDir: rolesDir(io.env) });
const verbs = definitionVerbs({ writer, rolesDir: rolesDir(io.env) });
let result;
@@ -93,4 +126,5 @@ export async function definitionsCommand(args, io, deps = {}) {
}
} else throw new CliError(DEFINITIONS_USAGE, 4);
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
}
}
+21 -2
View File
@@ -100,6 +100,15 @@ export function autonomyDocument(current, changes) {
return out;
}
// E2E6 fix 7: the autonomy-precondition check the CLI can see from the read and the document it sent:
// owner notices off while a class sits near the loop, or moves away from the loop.
const ORDER = ['in the loop', 'near the loop', 'out of the loop'];
export function preconditionSeen(current, doc) {
if (doc?.notices === true) return undefined;
const moved = CLASSES.filter(c => ORDER.indexOf(doc?.[c]) > ORDER.indexOf(current?.levels?.[c] ?? 'in the loop'));
if (CLASSES.some(c => doc?.[c] === 'near the loop') || moved.length) return 'owner notices are off; a class near the loop, or one moving away from it, needs them on (--notices on)';
return undefined;
}
// Autonomy codes carry no message from the route; these are the panel's own words (autonomy.js).
const AUTONOMY_GUIDANCE = {
'revision-conflict': 'the organization changed; read it again with mosaic org autonomy ID',
@@ -117,6 +126,10 @@ function refused(answer, what, unknown, guidance = {}) {
const code = typeof raw === 'string' && /^[a-z-]{1,64}$/.test(raw) ? raw : `http ${answer.status}`;
if (code === 'outcome-unknown' || (answer.status >= 500 && !raw)) return new CliError(`outcome unknown: ${unknown}`, 1);
const said = typeof answer.body?.message === 'string' ? answer.body.message.slice(0, 500) : guidance[code];
// E2E6 fix 7: a route that forwards the bus's reason (which check failed) has it said first; the
// general guidance becomes the next line. A reason is one printable line, never a control byte.
const reason = typeof answer.body?.reason === 'string' && /^[\x20-\x7e]{1,300}$/.test(answer.body.reason) ? answer.body.reason : undefined;
if (reason) return new CliError(`${what} refused (${code}): ${reason}`, 3, { next: said });
return new CliError(`${what} refused (${code})${said ? `: ${said}` : ''}`, 3);
}
@@ -173,8 +186,14 @@ export async function orgOwnerCommand(args, io, deps = {}) {
const read = await consoleOrgRequest(ctx, id, { path: 'autonomy' });
if (!ok(read)) throw refused(read, 'autonomy set', 'the autonomy read did not finish; nothing was changed', AUTONOMY_GUIDANCE);
const unknown = `the setting may have been saved; check mosaic org autonomy ${id} before trying again`;
const answer = await consoleOrgRequest(ctx, id, { method: 'POST', path: 'autonomy', body: { revision, autonomy: autonomyDocument(read.body, changes) }, unknown });
if (!ok(answer)) throw refused(answer, 'autonomy set', unknown, AUTONOMY_GUIDANCE);
const doc = autonomyDocument(read.body, changes);
const answer = await consoleOrgRequest(ctx, id, { method: 'POST', path: 'autonomy', body: { revision, autonomy: doc }, unknown });
if (!ok(answer)) {
// E2E6 fix 7: a route that forwards no reason still gets the one check this side can see.
const local = answer.body?.error === 'autonomy-precondition' && answer.body?.reason === undefined ? preconditionSeen(read.body, doc) : undefined;
if (local) throw new CliError(`autonomy set refused (autonomy-precondition): ${local}`, 3, { next: AUTONOMY_GUIDANCE['autonomy-precondition'] });
throw refused(answer, 'autonomy set', unknown, AUTONOMY_GUIDANCE);
}
return { value: answer.body, text: b => `saved autonomy for ${id}: revision ${b.revision ?? 'unknown'}${b.transaction ? `, receipt ${b.transaction}` : ''}\n` };
};
} else if (step === 'review') {
+30 -15
View File
@@ -15,7 +15,7 @@ import { busExit, humanTransport, refuseInsideAgent } from './transport.mjs';
import { definitionsCommand, DEFINITIONS_USAGE } from './org-definitions.mjs';
import { orgOwnerCommand, ORG_OWNER_USAGE, ORG_OWNER_VERBS } from './org-owner.mjs';
// Starter packs SP4 (design section 8): the owner's pack, board and workflow words.
export const PACKS_USAGE = 'mosaic org pack list | pack preview ID PACK [--project P] [--as KIND.NAME=NEW]... | pack apply ID PACK --digest D [--project P] [--as KIND.NAME=NEW]... | board set ID FILE [--project P] | workflow set ID NAME FILE [--project P] | workflow remove ID NAME [--project P]';
export const PACKS_USAGE = 'mosaic org pack list | pack preview ID PACK [--project P] [--as KIND.NAME=NEW]... | pack apply ID PACK --digest D [--project P] [--as KIND.NAME=NEW]... | pack hire ID PACK [--project P] | board set ID FILE [--project P] | workflow set ID NAME FILE [--project P] | workflow remove ID NAME [--project P]';
// #1873 SP8: saving the organization, or one project, as a template; the owner's alone.
export const TEMPLATE_USAGE = 'mosaic org template save ID NAME [--project P] (--preview | --digest D) | template list ID';
export const ORG_USAGE = 'mosaic org lock show|clear ID | reload ID | archive ID --if-revision N [--json] | restore ID --if-revision N [--no-bus] [--json] | delete ID --confirm ID [--if-revision N] [--json] | template render ID [--fixture local] --output FILE | validate FILE | create ID --from FILE | show ID [--json] | list [--json] | update ID --from FILE --if-revision N | queue init ID (--local-only --accept-local-loss-risk | --remote URL) | queue show ID [--json] | project repo init ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) | project repo show ID PROJECT [--json] | project repo set ID PROJECT (--local-only --accept-local-loss-risk | --remote URL) --if-revision N [--json] | ' + DEFINITIONS_USAGE.slice('mosaic org '.length) + ' | ' + ORG_OWNER_USAGE.slice('mosaic org '.length) + ' | ' + PACKS_USAGE.slice('mosaic org '.length) + ' | ' + TEMPLATE_USAGE.slice('mosaic org '.length) + ' | config validate ID | config resolve ID INSTANCE [--project ID]';
@@ -63,7 +63,27 @@ const PACK_REFUSALS = {
'invalid-request': 'the bus refused the request: a bad argument, a project that is not a code project, or a pack that fails the composition check',
'human-required': 'only the organization\'s owner, from a human shell, may do this',
'starter-pack-not-found': 'no installed, shipped or saved pack has that name',
'starter-pack-invalid': 'the pack fails its own checks or the composition check; nothing was written',
'starter-pack-template-changed': 'a template the pack names changed since it was loaded; preview again',
'not-configured': 'this organization\'s bus has no organization writer configured',
// Ruling 2026-11-14: apply and pack hire hire the pack's proposals. These come back as a hire's code.
'pack-not-applied': 'that pack has no packs entry in this organization or project; preview and apply it first',
'pack-hire-route-missing': 'neither the chief of staff nor the assistant has a harness and model to give a hire; set both in either one\'s vars, then run pack hire',
'no-chief-of-staff': 'the organization has no chief of staff to raise its hires',
'right-required': 'hiring needs the org.hire right',
};
// E2E6 fix 3: humanTransport throws a CliError whose message and .code are the bus code alone. A code
// a table knows gains its hint, as template save's do; a next line it carried is kept. Any other
// CliError (bus-not-running with its own next line, a usage error) passes unchanged, and a bare coded
// error (a test's call) becomes a CliError named by its code.
function hinted(e, ...tables) {
const code = typeof e?.code === 'string' ? e.code : '';
const table = tables.find(t => Object.hasOwn(t, code));
if (!table && (code === '' || e instanceof CliError)) return e;
const error = new CliError(table ? `${code}: ${table[code]}` : code, busExit(code), { next: e.next });
error.code = code;
return error;
}
async function packsCommand(args, io, deps) {
const pos = [], values = {}, as = [];
for (let i = 0; i < args.length; i++) {
@@ -86,6 +106,9 @@ async function packsCommand(args, io, deps) {
if (sub === 'apply' && !values['--digest']) throw new CliError('--digest is required: apply the digest a preview printed', 4);
verb = `pack.${sub}`;
request = { pack: name, ...project, ...(as.length ? { as } : {}), ...(sub === 'apply' ? { digest: values['--digest'] } : {}) };
} else if (word === 'pack' && sub === 'hire' && pos.length === 4) {
// Ruling 2026-11-14: hire the proposals of a pack already applied, the same loop apply runs.
allowed('--project'); verb = 'pack.hire'; request = { pack: name, ...project };
} else if (word === 'board' && sub === 'set' && pos.length === 4) { allowed('--project'); verb = 'board.set'; revised = true; request = { board: await packFile(name), ...project }; }
else if (word === 'workflow' && sub === 'set' && pos.length === 5) { allowed('--project'); verb = 'workflow.set'; revised = true; request = { name, workflow: await packFile(file), ...project }; }
else if (word === 'workflow' && sub === 'remove' && pos.length === 4) { allowed('--project'); verb = 'workflow.set'; revised = true; request = { name, workflow: null, ...project }; }
@@ -105,13 +128,7 @@ async function packsCommand(args, io, deps) {
}
let result;
try { result = await call(verb, request); }
catch (e) {
if (typeof e?.code !== 'string' || e.code === '' || e instanceof CliError) throw e;
const why = PACK_REFUSALS[e.code];
const error = new CliError(why ? `${e.code}: ${why}` : e.code, busExit(e.code));
error.code = e.code;
throw error;
}
catch (e) { throw hinted(e, PACK_REFUSALS); }
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
}
// #1873 SP8: template save previews (--preview) or writes the previewed JSON (--digest); template
@@ -120,7 +137,8 @@ async function packsCommand(args, io, deps) {
const TEMPLATE_REFUSALS = {
'template-secret-suspected': 'a field the template would keep holds a credential the organization\'s bus holds; remove it and preview again (nothing was written)',
'pack-plan-stale': 'the organization or a template changed since the preview; preview again and save its digest',
'invalid-request': 'the bus refused the request: a bad name, a name already saved, an unknown project, or an organization the template cannot hold',
'template-exists': 'a template of this name is already saved for your account; nothing was written',
'invalid-request': 'the bus refused the request: a bad name, an unknown project, or an organization the template cannot hold',
'human-required': 'only the organization\'s owner, from a human shell, may do this',
'not-configured': 'the templates directory is missing or not private to this instance\'s user',
'starter-pack-invalid': 'the template would not be a valid pack: more than 8 hires, or a definition wider than its template',
@@ -147,12 +165,9 @@ async function templateCommand(args, io, deps) {
let result;
try { result = await packCall(id, io, deps)(verb, request); }
catch (e) {
// humanTransport throws a CliError named by the bus code alone: a known code gains its hint.
const why = typeof e?.code !== 'string' ? undefined
: Object.hasOwn(TEMPLATE_REFUSALS, e.code) ? TEMPLATE_REFUSALS[e.code] : Object.hasOwn(PACK_REFUSALS, e.code) ? PACK_REFUSALS[e.code] : undefined;
if (!why) throw e;
const error = new CliError(`${e.code}: ${why}`, busExit(e.code));
error.code = e.code;
const error = hinted(e, TEMPLATE_REFUSALS, PACK_REFUSALS);
// E2E6 fix 8: a taken name says what to do next.
if (error.code === 'template-exists' && error.next === undefined) error.next = `preview and save under another name, or see the saved names with mosaic org template list ${id}`;
throw error;
}
io.stdout.write(JSON.stringify(result, null, 2) + '\n');
+13
View File
@@ -41,6 +41,7 @@ const EXIT = {
"tester-required": 3,
"tester-off": 3,
"tester-refused": 3,
"bus-not-running": 3,
"outcome-unknown": 1,
"outcome-unknown-revoked": 1,
"response-too-large": 1,
@@ -51,6 +52,17 @@ export function busExit(code) {
return EXIT[code] ?? 2;
}
// E2E6 fix 6: the shim exits 5 (packages/bus/src/client.mjs NOT_SENT_EXIT) when its connect failed
// before the request was written: no socket, or the connect refused. That is a stopped bus, and
// nothing happened; outcome-unknown stays for a request that left and got no answer.
const NOT_SENT_EXIT = 5;
export function busNotRunning(business) {
const error = new CliError(`bus-not-running: the bus for ${business} is not running, so the request was not sent`, 3);
error.code = "bus-not-running";
error.next = `start it with mosaic bus start ${business}, or clear a host that died with mosaic bus recover ${business}`;
return error;
}
// Returns a call(verb, args) for one business. `cli` and `spawn` exist for
// the tests; the command line never sets them.
export function humanTransport({ socket, business, env = process.env, cli = HUMAN_CLI, spawn = spawnSync, timeoutMs = 30000 }) {
@@ -65,6 +77,7 @@ export function humanTransport({ socket, business, env = process.env, cli = HUMA
if (proc.error || proc.status === null) throw new CliError("outcome-unknown: the bus transport did not finish", 1);
if (proc.status !== 0) {
const code = String(proc.stderr ?? "").trim().split("\n").reverse().find((l) => /^[a-z-]{1,64}$/.test(l)) ?? "invalid-response";
if (proc.status === NOT_SENT_EXIT && code === "outcome-unknown") throw busNotRunning(business);
const error = new CliError(code, busExit(code));
error.code = code;
throw error;
+17
View File
@@ -89,6 +89,8 @@ function organizations({ send = true } = {}) {
calls.push({ verb, args, opts });
if (verb === 'autonomy.review.console') return { reviewed: args.decisionClass };
if (args.revision !== state.revision) throw new BusReadError('revision-conflict');
// E2E6 fix 7: the bus refuses policy out of the loop here; the route forwards the code alone.
if (args.autonomy.policy === 'out of the loop') throw new BusReadError('autonomy-precondition');
const { notices, reverseWindowHours, authorityResolver, ...levels } = args.autonomy;
state = { revision: REV(parseInt(state.revision, 16) + 1), levels, autonomy: { notices, reverseWindowHours, ...(authorityResolver ? { authorityResolver } : {}) } };
return { revision: state.revision, transaction: `tx-${parseInt(state.revision, 16)}` };
@@ -259,6 +261,21 @@ test('autonomy reads, saves with the panel\'s revision check and records a revie
assert.equal((await page(c.port, 'GET', '/api/orgs/alpha/autonomy')).body.revision, REV(5));
c.calls.splice(0);
// E2E6 fix 7: an autonomy-precondition the route sends without a reason still names the one check the
// terminal can see from its read and the document it sent (notices off while a class moves away),
// and the general guidance becomes the next line.
r = await mosaic(env, ['org', 'autonomy', 'alpha', 'set', '--revision', REV(5), '--policy', 'out']);
assert.equal(r.status, 3, r.stderr);
assert.match(r.stderr, /^mosaic: autonomy set refused \(autonomy-precondition\): owner notices are off; a class near the loop, or one moving away from it, needs them on \(--notices on\)$/m);
assert.match(r.stderr, /^mosaic: next: this move needs a separate resolver/m);
const { preconditionSeen } = await import('../src/org-owner.mjs');
const shown = { levels: { ...LOOP, merge: 'near the loop' } };
assert.equal(preconditionSeen(shown, { ...LOOP, merge: 'near the loop', notices: true }), undefined);
assert.equal(preconditionSeen(shown, { ...LOOP, notices: false }), undefined, 'moving back toward the loop needs no notices');
assert.match(preconditionSeen(shown, { ...LOOP, merge: 'near the loop', notices: false }), /^owner notices are off/);
assert.match(preconditionSeen({ levels: LOOP }, { ...LOOP, authority: 'out of the loop', notices: false }), /^owner notices are off/);
c.calls.splice(0);
r = await mosaic(env, ['org', 'autonomy', 'alpha', 'review', 'merge']);
assert.equal(r.status, 0, r.stderr);
assert.equal(r.stdout, 'recorded your trail review for merge on alpha\n');
+9
View File
@@ -67,6 +67,15 @@ test('two organization buses are isolated and refusals never select a sibling',
writeFileSync(join(alpha.root, 'bus-host/host.json'), JSON.stringify(staleHost), { mode: 0o600 });
writeFileSync(join(alpha.root, 'bus-host/host.lock'), JSON.stringify(staleHost), { mode: 0o600 });
writeFileSync(join(alpha.root, 'bus/writer.lock'), JSON.stringify({ pid: 2147483647, at: '2026-01-01T00:00:00Z' }), { mode: 0o600 });
// E2E6 fix 1: status, start, stop and restart refuse a dead host's lock with the message unchanged and a
// next line naming the verb that clears it.
for (const args of [['status', 'alpha', '--json'], ['start', 'alpha', '--no-launch', '--detach'], ['stop', 'alpha'], ['restart', 'alpha']]) {
const r = spawnSync(join(REPO, 'scripts/mosaic'), ['bus', ...args], { env, encoding: 'utf8', timeout: 30000 });
assert.equal(r.status, 3, `${args[0]}: ${r.stderr}`);
assert.match(r.stderr, /^mosaic: stale bus host lock$/m, args[0]);
assert.match(r.stderr, /^mosaic: next: if the bus host died, clear it with mosaic bus recover alpha; recover refuses while the host still runs$/m, args[0]);
}
await assert.rejects(busStatus(ctx, 'alpha'), e => e.message === 'stale bus host lock' && e.exitCode === 3 && /mosaic bus recover alpha/.test(e.next));
const recovery = spawnSync(join(REPO, 'scripts/mosaic'), ['bus', 'recover', 'alpha'], { env, encoding: 'utf8' });
assert.equal(recovery.status, 0, recovery.stderr);
const restarted = await busStart(ctx, 'alpha', { detach: true, noLaunch: true });
+57
View File
@@ -417,3 +417,60 @@ test('a detached console without the dev owner has no supervisor, so it refuses
assert.equal(start.stderr, '');
assert.equal((await consoleStop(ctx)).stopped, true);
});
// E2E6 fix 4: console start and stop clear a start.lock whose named supervisor (pid and start time) is
// gone, and never one whose holder still runs or that names no holder.
test('E2E6 a start.lock whose holder is gone is cleared by stop and by start; a live or unnamed one refuses and stays', { timeout: 60000 }, async t => {
const { startTimeOf } = await import('../src/host.mjs');
const { ctx } = await instance(t);
const dir = join(ctx.dataRoot, 'console'), lock = join(dir, 'start.lock');
mkdirSync(dir, { recursive: true, mode: 0o700 });
// A process this test starts and lets end: its pid and start time name a supervisor that is gone.
const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 30000)'], { stdio: 'ignore' });
await new Promise(r => child.once('spawn', r));
const deadHolder = { pid: child.pid, startTime: startTimeOf(child.pid) };
assert.match(deadHolder.startTime, /^\d+$/);
child.kill('SIGKILL');
await new Promise(r => child.once('exit', r));
const warnings = [];
writeFileSync(lock, JSON.stringify(deadHolder), { mode: 0o600 });
assert.deepEqual(await consoleStop(ctx, { warn: s => warnings.push(s) }), { stopped: false });
assert.deepEqual(warnings, [`mosaic: cleared a console start lock left by process ${child.pid}, which is gone\n`]);
assert.equal(existsSync(lock), false);
assert.deepEqual(readdirSync(dir).filter(x => x.startsWith('start.lock')), []);
// A live pid with another start time is a reused pid: its holder is gone too.
writeFileSync(lock, JSON.stringify({ pid: process.pid, startTime: '1' }), { mode: 0o600 });
warnings.length = 0;
const result = await consoleStart(ctx, { detach: true, port: 'auto', warn: s => warnings.push(s) });
assert.deepEqual(warnings, [`mosaic: cleared a console start lock left by process ${process.pid}, which is gone\n`]);
assert.equal(existsSync(lock), false, 'the start released its own lock');
assert.equal((await consoleStop(ctx)).stopped, true);
assert.ok(Number.isSafeInteger(result.pid));
// A live holder refuses on start and stop, and the lock stays as it was.
const live = JSON.stringify({ pid: process.pid, startTime: startTimeOf(process.pid) });
writeFileSync(lock, live, { mode: 0o600 });
await assert.rejects(consoleStop(ctx), e => e.message === `console start lock is held by process ${process.pid}, which still runs; wait for its start or stop to finish`);
await assert.rejects(consoleStart(ctx, { detach: true, port: 'auto' }), /which still runs/);
assert.equal(readFileSync(lock, 'utf8'), live);
// A lock that names no holder (empty: a holder between its open and its write; or bad JSON) stays too.
for (const body of ['', '{"pid":', JSON.stringify({ pid: 0, startTime: '1' }), JSON.stringify({ pid: child.pid, startTime: 7 })]) {
writeFileSync(lock, body, { mode: 0o600 });
await assert.rejects(consoleStop(ctx), /console start lock exists and names no holder/);
assert.equal(readFileSync(lock, 'utf8'), body);
}
// f6c review P3-1: a lock its holder marked released (a clear put it back after the release) is
// cleared; a released marker with anything else in it names no holder and stays.
writeFileSync(lock, JSON.stringify({ released: true }), { mode: 0o600 });
warnings.length = 0;
assert.deepEqual(await consoleStop(ctx, { warn: s => warnings.push(s) }), { stopped: false });
assert.deepEqual(warnings, ['mosaic: cleared a console start lock its holder had released\n']);
assert.equal(existsSync(lock), false);
const odd = JSON.stringify({ released: true, pid: 1 });
writeFileSync(lock, odd, { mode: 0o600 });
await assert.rejects(consoleStop(ctx), /console start lock exists and names no holder/);
assert.equal(readFileSync(lock, 'utf8'), odd);
rmSync(lock);
});
@@ -136,3 +136,55 @@ test('T1 mosaic org definitions: writes go through the bus and its secret check,
await assert.rejects(orgCommand(['definitions', 'acme', 'remove', 'copy', '--if-rev', '1'], x), (e) => e.exitCode === 3 && /organization bus/.test(e.message));
assert.deepEqual(readFileSync(file), before);
});
// E2E6 fix 2: an unknown definition, an unknown organization, a bad id and a bad name each end in
// one usage or refusal line: no stack trace and no host path.
test('E2E6 mosaic org definitions: unknown names, an unknown org and a bad id give one line, no stack and no path', async (t) => {
const root = tmp(t);
const f = fixture(root, 'acme');
const { run } = await import('../src/cli.mjs');
const cases = [
[['acme', 'show', 'ghost'], 3, 'mosaic: definition-missing: definitions declares no ghost; list them with mosaic org definitions acme list'],
[['acme', 'diff', 'ghost'], 3, 'mosaic: definition-missing: definitions declares no ghost; list them with mosaic org definitions acme list'],
[['acme', 'show', 'Bad Name'], 3, 'mosaic: definition-missing: definitions declares no definition by that name; list them with mosaic org definitions acme list'],
[['nosuch', 'list'], 3, 'mosaic: unknown-organization: this instance has no organization nosuch; list them with mosaic org list'],
[['nosuch', 'show', 'x'], 3, 'mosaic: unknown-organization: this instance has no organization nosuch; list them with mosaic org list'],
];
for (const [args, exit, line] of cases) {
const x = io(f.env);
assert.equal(await run(['org', 'definitions', ...args], x, {}), exit, args.join(' '));
assert.equal(x.err.text, `${line}\n`, args.join(' '));
assert.ok(!x.err.text.includes(root) && !/\n\s+at /.test(x.err.text), args.join(' '));
}
for (const args of [['Bad/Id', 'list'], ['../x', 'show', 'y']]) {
const x = io(f.env);
assert.equal(await run(['org', 'definitions', ...args], x, {}), 4, args.join(' '));
assert.match(x.err.text, /^mosaic: invalid organization id: an id is 1 to 64 of a-z/);
assert.match(x.err.text, /\nmosaic org definitions templates \| definitions ID list/);
assert.ok(!x.err.text.includes(root) && !/\n\s+at /.test(x.err.text));
}
});
test('E2E6 definitionsFailure: a raw filesystem error is named by its operation and code, a message path is cut, an unknown error says only that it failed', async () => {
const { definitionsFailure } = await import('../src/org-definitions.mjs');
const fsError = (code, syscall) => Object.assign(new Error(`${code}: no such file, open '/home/someone/.config/x/acme.json'`), { code, syscall, path: '/home/someone/.config/x/acme.json' });
let e = definitionsFailure(fsError('EACCES', 'open'), 'acme');
assert.deepEqual([e.code, e.exitCode, e.message], ['organization-unreadable', 3, 'organization-unreadable: cannot open the file of organization acme (EACCES)']);
e = definitionsFailure(Object.assign(new Error("organization file /srv/x/acme.json is not valid"), { code: 'organization-invalid' }), 'acme');
assert.equal(e.message, 'organization-invalid: organization file <path> is not valid');
e = definitionsFailure(new TypeError('Cannot read properties of undefined'), 'acme');
assert.deepEqual([e.code, e.exitCode, e.message], ['definitions-failed', 1, 'definitions-failed: the definitions command failed']);
// f6c review P3-2: only the organization file missing means no organization.
e = definitionsFailure(fsError('ENOENT', 'open'), 'acme');
assert.deepEqual([e.code, e.message], ['unknown-organization', 'unknown-organization: this instance has no organization acme; list them with mosaic org list']);
const rolesGone = Object.assign(new Error("ENOENT: no such file or directory, scandir '/home/someone/roles'"), { code: 'ENOENT', syscall: 'scandir', path: '/home/someone/roles' });
e = definitionsFailure(rolesGone, 'templates');
assert.deepEqual([e.code, e.exitCode, e.message], ['definitions-unreadable', 3, 'definitions-unreadable: cannot scandir a file the definitions command reads (ENOENT)']);
e = definitionsFailure(rolesGone, 'acme');
assert.equal(e.code, 'organization-unreadable');
// f6c review P3-3: a path after ':' or inside backticks is cut.
e = definitionsFailure(Object.assign(new Error('organization file:/srv/x/acme.json is not valid'), { code: 'organization-invalid' }), 'acme');
assert.equal(e.message, 'organization-invalid: organization file:<path> is not valid');
e = definitionsFailure(Object.assign(new Error('bad role at `/srv/roles/x.json`'), { code: 'organization-invalid' }), 'acme');
assert.equal(e.message, 'organization-invalid: bad role at `<path>`');
});
+52
View File
@@ -97,3 +97,55 @@ test('SP4 an agent shell refuses every pack, board and workflow word, pack list
assert.deepEqual(s.calls, []);
assert.deepEqual(readFileSync(s.file), before);
});
// E2E6 fix 3: the real transport shape. humanTransport throws a CliError whose message and .code are
// the bus code alone (packages/cli/src/transport.mjs); pack, board and workflow refusals must still
// gain their hint, as template save's do, and a CliError with its own next line passes unchanged.
test('E2E6 pack, board and workflow refusals from a CliError-shaped transport print the hint', async (t) => {
const { CliError } = await import('../src/errors.mjs');
const { busExit, busNotRunning } = await import('../src/transport.mjs');
const root = tmp(t);
const f = fixture(root, 'acme');
const boot = bootConfig({ system: loadSystem({ env: f.env }), businessId: 'acme', env: f.env });
const b = await startBroker({ dataRoot: f.dataRoot, businesses: boot.businesses, organization: boot.organization });
t.after(() => b.close());
const human = b.broker.bindHuman({ business: 'acme', human: f.doc.human, via: 'cli', outsideAgent: true });
let down = false;
const deps = { system: { dataRoot: f.dataRoot }, transport: () => async (verb, args = {}) => {
if (down) throw busNotRunning('acme');
try { return structuredClone(await b.broker.request(human, { verb, args })); }
catch (e) { if (!(e instanceof BusError)) throw e; throw Object.assign(new CliError(e.code, busExit(e.code)), { code: e.code }); }
} };
const run = async (args) => { const x = io(f.env); await main(['org', ...args], x, deps); return JSON.parse(x.out.text); };
const hinted = (e) => typeof e.code === 'string' && e instanceof CliError && e.message.startsWith(`${e.code}: `) && e.message.length > e.code.length + 10;
await assert.rejects(run(['pack', 'preview', 'acme', 'no-such-pack']), (e) => e.code === 'starter-pack-not-found' && e.message === 'starter-pack-not-found: no installed, shipped or saved pack has that name');
const spec = join(root, 'board.json');
writeFileSync(spec, JSON.stringify({ columns: [{ state: 'todo', label: 'Backlog' }], layout: 'kanban' }));
await assert.rejects(run(['board', 'set', 'acme', spec]), (e) => hinted(e) && e.exitCode === busExit(e.code));
await assert.rejects(run(['workflow', 'remove', 'acme', 'ghost']), (e) => hinted(e) && e.exitCode === busExit(e.code));
// A stopped bus keeps its own message and next line.
down = true;
await assert.rejects(run(['pack', 'preview', 'acme', 'no-such-pack']), (e) => e.code === 'bus-not-running' && e.exitCode === 3
&& e.message === 'bus-not-running: the bus for acme is not running, so the request was not sent' && /mosaic bus start acme/.test(e.next) && /mosaic bus recover acme/.test(e.next));
});
// Ruling 2026-11-14: "If I choose a starter pack and apply it, that is a decision!" The owner's apply
// hires the proposals in the same act; pack hire runs the same loop on the packs entry and hires none twice.
test('PD mosaic org pack apply hires the proposals; pack hire on the same record hires nothing twice', async (t) => {
const s = await setup(t);
assert.ok(PACKS_USAGE.includes('pack hire ID PACK [--project P]'));
const preview = await s.run(['pack', 'preview', 'acme', 'coding']);
const applied = await s.run(['pack', 'apply', 'acme', 'coding', '--digest', preview.digest]);
assert.deepEqual(applied.hires.map((x) => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
for (const x of applied.hires) assert.match(String(x.decision), /^[0-9a-f-]{36}$/);
const doc = s.doc();
for (const x of applied.hires) { assert.equal(doc.roles[x.name].hireDecision, x.decision); assert.ok(doc.launch.instances.includes(x.name), x.name); }
const again = await s.run(['pack', 'hire', 'acme', 'coding']);
assert.deepEqual(again.hires.map((x) => [x.name, x.state]), [['pm-1', 'exists'], ['coder-1', 'exists'], ['reviewer-1', 'exists']]);
assert.deepEqual(s.calls.at(-1), ['pack.hire', ['pack']]);
await assert.rejects(s.run(['pack', 'hire', 'acme', 'ghost-pack']), (e) => e.code === 'pack-not-applied' && /apply it first/.test(e.message));
await assert.rejects(s.run(['pack', 'hire', 'acme']), (e) => e.exitCode === 4 && e.message === PACKS_USAGE);
});
+6 -1
View File
@@ -37,8 +37,13 @@ test('organization host claim refuses a stale lock without removing it', t => {
const stale = { pid: 99999999, startTime: '0', business: 'alpha', startedAt: 'old' };
writeFileSync(hostLock(root), JSON.stringify(stale), { mode: 0o600 });
const mine = { pid: process.pid, startTime: startTimeOf(process.pid), business: 'alpha', startedAt: 'now' };
assert.throws(() => claimHostLock(root, mine, { refuseStale: true }), /stale.*lock/i);
// E2E6 fix 1: the message stays; the next line names the verb that clears the dead host.
assert.throws(() => claimHostLock(root, mine, { refuseStale: true }), e => e.message === 'stale bus host lock' && e.exitCode === 3
&& e.next === 'if the bus host died, clear it with mosaic bus recover alpha; recover refuses while the host still runs');
assert.deepEqual(JSON.parse(readFileSync(hostLock(root), 'utf8')), stale);
// A lock naming no valid organization id still names the verb, with a placeholder.
writeFileSync(hostLock(root), JSON.stringify({ ...stale, business: '../x\nsecret' }), { mode: 0o600 });
assert.throws(() => claimHostLock(root, mine, { refuseStale: true }), e => e.next === 'if the bus host died, clear it with mosaic bus recover <org>; recover refuses while the host still runs');
});
import { busStatus } from '../src/org-bus.mjs';
+4 -2
View File
@@ -40,7 +40,7 @@ test('SP8 mosaic org template save: --preview writes nothing, --digest writes th
const before = readFileSync(s.file);
const preview = await s.run(['template', 'save', 'acme', 'acme-shape', '--preview']);
assert.match(preview.digest, /^[0-9a-f]{64}$/);
assert.ok(Array.isArray(preview.freeText) && Array.isArray(preview.replacements));
assert.ok(Array.isArray(preview.freeText) && Array.isArray(preview.mentions) && !('replacements' in preview));
assert.ok(!existsSync(s.saved('acme-shape')), 'preview writes no file');
const out = await s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]);
@@ -49,7 +49,9 @@ test('SP8 mosaic org template save: --preview writes nothing, --digest writes th
assert.equal(lstatSync(s.saved('acme-shape')).mode & 0o777, 0o600);
assert.deepEqual(readFileSync(s.file), before, 'save writes nothing to the organization file');
await assert.rejects(s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]), (e) => e.code === 'invalid-request' && /already saved/.test(e.message));
await assert.rejects(s.run(['template', 'save', 'acme', 'acme-shape', '--digest', preview.digest]), (e) => e.code === 'template-exists' && e.exitCode === 2
&& e.message === 'template-exists: a template of this name is already saved for your account; nothing was written'
&& /under another name/.test(e.next) && /mosaic org template list acme/.test(e.next));
await assert.rejects(s.run(['template', 'save', 'acme', 'other', '--digest', preview.digest]), (e) => e.code === 'pack-plan-stale' && /preview again/.test(e.message));
const listed = await s.run(['template', 'list', 'acme']);
assert.deepEqual(listed.templates.map((x) => x.name), ['acme-shape']);
+29 -2
View File
@@ -1,8 +1,8 @@
import { test } from "node:test";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { readFileSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { busExit, humanTransport, refuseInsideAgent } from "../src/transport.mjs";
import { busExit, humanTransport, refuseInsideAgent, HUMAN_CLI } from "../src/transport.mjs";
import { fakeCli, humanEnv, tmp } from "./helpers.mjs";
// The fake records argv and stdin, then answers per verb. The real
@@ -15,6 +15,8 @@ const { verb } = JSON.parse(input);
if (verb === "inbox") process.stdout.write(JSON.stringify([{ id: "d1" }]) + "\\n");
else if (verb === "garbage") process.stdout.write("not json");
else if (verb === "hang") setTimeout(() => {}, 60000);
else if (verb === "not-sent") { process.stderr.write("outcome-unknown\\n"); process.exit(5); }
else if (verb === "not-sent-other") { process.stderr.write("human-required\\n"); process.exit(5); }
else { process.stderr.write("some noise\\n" + verb + "\\n"); process.exit(2); }
`;
@@ -50,3 +52,28 @@ test("busExit and refuseInsideAgent", () => {
assert.doesNotThrow(() => refuseInsideAgent(humanEnv()));
assert.throws(() => refuseInsideAgent({ PI_AGENT_DIR: "/x" }), (e) => e.exitCode === 3 && /PI_AGENT_DIR/.test(e.message));
});
// E2E6 fix 6: the shim exits 5 when its connect failed before the request was written. That is a stopped
// bus: mosaic says so with the start and recover line. outcome-unknown stays for a request that left.
test("E2E6 exit 5 with outcome-unknown is bus-not-running; exit 2 with outcome-unknown is unchanged", async (t) => {
const s = setup(t);
await assert.rejects(s.call("not-sent"), (e) => e.code === "bus-not-running" && e.exitCode === 3
&& e.message === "bus-not-running: the bus for acme is not running, so the request was not sent"
&& e.next === "start it with mosaic bus start acme, or clear a host that died with mosaic bus recover acme");
await assert.rejects(s.call("outcome-unknown"), (e) => e.code === "outcome-unknown" && e.exitCode === 1 && e.message === "outcome-unknown" && e.next === undefined);
// Exit 5 says only that nothing was sent; any other code it carries keeps its own meaning.
await assert.rejects(s.call("not-sent-other"), (e) => e.code === "human-required" && e.exitCode === 3);
assert.equal(busExit("bus-not-running"), 3);
});
// The real shim, with no bus behind the path: nothing reaches a broker, so no proof runs. A missing socket
// and a path that is not a listening socket are both a bus that is not running.
test("E2E6 the real human shim against a missing socket or a plain file says the bus is not running", async (t) => {
const root = tmp(t);
const plain = join(root, "plain.sock");
writeFileSync(plain, "");
for (const socket of [join(root, "missing.sock"), plain]) {
const call = humanTransport({ socket, business: "acme", env: humanEnv(), cli: HUMAN_CLI, timeoutMs: 20000 });
await assert.rejects(call("inbox"), (e) => e.code === "bus-not-running" && e.exitCode === 3, socket);
}
});
+50 -3
View File
@@ -36,9 +36,9 @@
import { refusalGuidance } from "../../bus/src/refusals.mjs";
import { spawn } from "node:child_process";
import { setTimeout as delay } from "node:timers/promises";
import { chmodSync, existsSync, mkdirSync, openSync, readFileSync, rmSync, closeSync } from "node:fs";
import { chmodSync, existsSync, fstatSync, mkdirSync, openSync, readFileSync, readSync, rmSync, closeSync } from "node:fs";
import { createServer, connect } from "node:net";
import { join } from "node:path";
import { basename, join } from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { Client } from "../../bus/src/client.mjs";
import { LENGTH_FAILURE_NOTICE_PREFIX } from "./failure-notice.mjs";
@@ -384,13 +384,56 @@ export function toolServer({ path, tools, client, local }) {
});
}
// #1873 r127: exit 127 is the shell's "command not found". The turn's stderr then holds the
// shell's own line for it, the last one nearest the exit:
// bash X: line N: [exec: ]CMD: No such file or directory | [command ]not found
// dash X: N: [exec: ]CMD: not found
// env [/usr/bin/]env: 'CMD': No such file or directory
// Only those shapes count, so another program's missing file (cat: F: No such file…) doesn't.
// The answer is CMD's basename, which the person reads in the failure; never its host path, and
// nothing that isn't a plain program name. A run of 16 letters and digits looks like a key, not a
// program, so it stays in the run's private stderr.
const NOT_FOUND = [
/(?:^|: )line \d+: (?:exec: )?([^\s:]+): (?:(?:command )?not found|No such file or directory)$/,
/: \d+: (?:exec: )?([^\s:]+): not found$/,
/^(?:\S*\/)?env: ['\u2018]([^\s:'\u2019]+)['\u2019]: No such file or directory$/,
];
export function missingCommand(text) {
let name = null;
for (const line of String(text).split(/\r?\n/)) {
const m = NOT_FOUND.map((re) => re.exec(line)).find(Boolean);
if (m) name = basename(m[1]);
}
return name && /^[A-Za-z0-9._+-]{1,64}$/.test(name) && !/[A-Za-z0-9]{16}/.test(name) ? name : null;
}
// The last 16 KiB of a turn's stderr file from a line start, or "" when it can't be read.
const TAIL = 16384;
function stderrTail(path) {
let fd;
try {
fd = openSync(path, "r");
const size = fstatSync(fd).size, length = Math.min(size, TAIL);
const buf = Buffer.alloc(length);
readSync(fd, buf, 0, length, size - length);
const text = buf.toString("utf8");
// A window that starts mid-file starts mid-line; that partial line is dropped.
return size > TAIL ? text.slice(text.indexOf("\n") + 1) : text;
} catch {
return "";
} finally {
if (fd !== undefined) closeSync(fd);
}
}
// Run one turn. Resolves { ok, text, reason }.
function runTurn({ session, request, n, env, onChild }) {
const marker = session.turnMarker;
rmSync(marker, { force: true });
const turns = join(session.runDir, "turns");
mkdirSync(turns, { recursive: true, mode: 0o700 });
const errFd = openSync(join(turns, `${String(n).padStart(4, "0")}.stderr`), "wx", 0o600);
const errPath = join(turns, `${String(n).padStart(4, "0")}.stderr`);
const errFd = openSync(errPath, "wx", 0o600);
// Adapters are 0644 in the repository (the image sets the mode), so the
// host runs them through sh.
const child = spawn("/bin/sh", [session.adapter], {
@@ -461,6 +504,10 @@ function runTurn({ session, request, n, env, onChild }) {
if (status?.stopReason === "length" && status.hasText === false && status.hasToolCall === false)
return resolve({ ok: false, emptyLength: true, reason: "output limit reached while thinking before any answer or tool call" });
}
if (code === 127) {
const missing = missingCommand(stderrTail(errPath));
return resolve({ ok: false, reason: `adapter exited 127${missing ? ` (command not found: ${missing})` : ""}` });
}
if (code !== 0) return resolve({ ok: false, reason: signal ? `adapter killed by ${signal}` : `adapter exited ${code}` });
// A "marker" harness (row 65: the module's turnEnd()) writes the marker when its turn ends.
if (session.turnEnd === "marker" && !existsSync(marker)) return resolve({ ok: false, reason: `${session.harness} exited before the turn ended (no turn marker)` });
+83 -1
View File
@@ -13,7 +13,7 @@ import { join } from "node:path";
import { Store } from "../../bus/src/store.mjs";
import { Broker, BusError } from "../../bus/src/broker.mjs";
import { serve } from "../../bus/src/server.mjs";
import { EXIT, founderCheck, landingRequest, stateBlock, turnRequest, unslopCounts, unslopLog, unslopNotes } from "../src/runner.mjs";
import { EXIT, founderCheck, landingRequest, missingCommand, stateBlock, turnRequest, unslopCounts, unslopLog, unslopNotes } from "../src/runner.mjs";
import { typedTools } from "../src/tools.mjs";
import { resolvedFor, scratch } from "./helpers.mjs";
@@ -298,6 +298,88 @@ test("SIGKILL of the model child keeps base failure receipts through the real ad
assert.equal(records[1].body, records[0].body);
});
// #1873 r127: on the dev instance /usr/bin/claude is a wrapper that execs a binary outside /usr.
// The sandbox binds /usr only, so the wrapper starts and its target is missing: the shell exits
// 127 and the person read only "adapter exited 127". The reason now names the missing program.
test("r127 an adapter exit 127 names the program that wasn't found, through the real claude adapter", async t => {
const ctx = await setup(t, {session:{harness:"claude-code", turnEnd:"exit", adapter:new URL("../../../adapters/claude/adapter.sh", import.meta.url).pathname}});
const sessionFile = join(ctx.runDir, "session.json");
const session = JSON.parse(readFileSync(sessionFile, "utf8"));
const wrapper = join(ctx.dir, "bin", "claude");
mkdirSync(join(ctx.dir, "bin"));
writeFileSync(wrapper, `#!/bin/sh\nexport DISABLE_UPDATES=1\nexec ${join(ctx.dir, "not-mounted", "claude-code", "bin", "claude")} "$@"\n`, {mode:0o755});
session.harnessEnv = {MOSAIC_CLAUDE_BIN:wrapper, MOSAIC_THINKING:"low", MOSAIC_CLAUDE_SETTINGS:session.bundle.policy, MOSAIC_CLAUDE_MCP_CONFIG:session.bundle.tools};
writeFileSync(sessionFile, JSON.stringify(session));
ctx.inbox = [];
const r = startRunner(ctx.runDir, ctx.cap);
t.after(() => r.child.kill("SIGKILL"));
const sent = ctx.call(ctx.pm, "message.send", {to:"coder", body:"hello", class:"REQUEST"});
const [reply] = await until(replies(ctx));
await until(() => ctx.store.get("SELECT 1 FROM deliveries WHERE message=? AND op='read'", sent.id));
assert.equal(reply.body, "The turn failed: adapter exited 127 (command not found: claude)");
assert.doesNotMatch(reply.body, /not-mounted|\/bin\//, "the reason names the program, never its host path");
assert.match(r.stderr(), /failed: adapter exited 127 \(command not found: claude\)/);
r.child.kill("SIGTERM"); await r.exited;
});
test("r127 an adapter whose own command is missing names it; a 127 with no such line keeps the bare reason", async t => {
const ctx = await setup(t);
const adapter = join(ctx.dir, "adapter.sh");
writeFileSync(adapter, `case "$MOSAIC_REQUEST" in *QUIET*) echo "nothing useful" >&2; exit 127 ;; esac\nexec mosaic-r127-no-such-harness -p "$MOSAIC_REQUEST"\n`);
ctx.inbox = [];
const r = startRunner(ctx.runDir, ctx.cap);
t.after(() => r.child.kill("SIGKILL"));
ctx.call(ctx.pm, "message.send", {to:"coder", body:"one"});
ctx.call(ctx.pm, "message.send", {to:"coder", body:"QUIET"});
await until(() => replies(ctx)() && ctx.inbox.length >= 2);
assert.deepEqual(ctx.inbox.map(m => m.body), [
"The turn failed: adapter exited 127 (command not found: mosaic-r127-no-such-harness)",
"The turn failed: adapter exited 127",
]);
r.child.kill("SIGTERM"); await r.exited;
});
test("r127 missingCommand reads the shells' not-found lines and gives a safe basename only", () => {
assert.equal(missingCommand("/usr/bin/claude: line 4: /opt/claude-code/bin/claude: No such file or directory\nclaude adapter: invalid or incomplete model stream\n"), "claude");
assert.equal(missingCommand("/usr/bin/claude: 4: exec: /opt/claude-code/bin/claude: not found\n"), "claude");
assert.equal(missingCommand("/x/adapters/pi/adapter.sh: 140: exec: pi: not found\n"), "pi");
assert.equal(missingCommand("/x/adapter.sh: line 9: exec: pi: not found\n"), "pi");
assert.equal(missingCommand("sh: line 1: pi: command not found\n"), "pi");
assert.equal(missingCommand("/usr/bin/env: 'node': No such file or directory\n"), "node");
assert.equal(missingCommand("/usr/bin/env: ‘node’: No such file or directory\n"), "node");
// The last such line is the one nearest the exit.
assert.equal(missingCommand("a: 1: exec: first: not found\nb: 2: exec: second: not found\n"), "second");
assert.equal(missingCommand(""), null);
assert.equal(missingCommand("error: model refused\n"), null);
// A name that isn't a plain program name is left out, never echoed.
assert.equal(missingCommand("a: 1: exec: $(rm -rf x): not found\n"), null);
assert.equal(missingCommand(`a: 1: exec: ${"x".repeat(80)}: not found\n`), null);
// Review r127 P3-5: tokens without spaces reach the name check, and it refuses them.
assert.equal(missingCommand("a: 1: exec: $(id): not found\n"), null);
assert.equal(missingCommand("a: line 2: x;id: command not found\n"), null);
assert.equal(missingCommand("a: line 2: `id`: command not found\n"), null);
// P3-2: a long run of letters and digits looks like a key, not a program; it stays in stderr.
assert.equal(missingCommand("adapter.sh: line 3: sk-proj-abcDEF1234567890xyz: command not found\n"), null);
assert.equal(missingCommand("adapter.sh: line 3: 0123456789abcdef0123: command not found\n"), null);
// P3-1: only a shell's or env's own line counts; other programs' missing files don't.
assert.equal(missingCommand("cat: /nope/file: No such file or directory\n"), null);
assert.equal(missingCommand("w.sh: line 1: /opt/x/claude: No such file or directory\ncat: /run/state.json: No such file or directory\n"), "claude");
// P3-4: CRLF lines read the same.
assert.equal(missingCommand("sh: line 1: pi: command not found\r\n"), "pi");
});
test("r127 a not-found line cut by the 16 KiB stderr window is not read as a name", async t => {
const ctx = await setup(t, { session: { harness: 'pi', turnEnd: 'exit' } });
ctx.inbox = [];
// 52 + 16351 + 1 bytes: the 16 KiB window starts inside "claude", at "aude: No such file…".
writeFileSync(join(ctx.dir, 'adapter.sh'),
`printf 'x: line 1: /opt/x/claude: No such file or directory\\n' >&2\nhead -c 16351 /dev/zero | tr '\\0' 'z' >&2\nprintf '\\n' >&2\nexit 127\n`);
const r = startRunner(ctx.runDir, ctx.cap);
t.after(async () => { r.child.kill('SIGTERM'); await r.exited; });
const reply = await ask(ctx);
assert.equal(reply.body, "The turn failed: adapter exited 127");
});
// Claude's private stream reader owns model activity; final result stdout alone
// (even a synthetic success) must not cancel the model watchdog. Other adapters
// still need the stdout fallback when no streaming producer is installed.
+8
View File
@@ -684,3 +684,11 @@ After the pinned window, use an ordinary new decision.
Policy has no effect executor. Per the Lead ruling, its in and existing out
levels work, while near refuses `policy-reverse-unavailable` and directs the
owner to choose in or out. Policy near and its reverse wait for that executor.
### Pack hires and rights (ruling 2026-11-14, #1873)
`src/org-rights.mjs` maps `pack.hire.console` to `org.hire`: hiring a starter
pack's proposed agents is a hire, so a member with that right hires the
unflagged proposals and the rest wait for the owner (invariant 7). The read
`instanceSettings` returns each instance's `hireDecision`, which the bus's
`instances` read uses to name the pack an agent came from.
@@ -183,6 +183,8 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null, r
protected: closed(entry.definition),
kept: (launch?.keep ?? []).includes(name),
endProtected: protectedRefusal(document, name, actor) !== null,
// Ruling 2026-11-14: a hired instance names its hire decision; the bus adds the pack it came from.
...(typeof entry.hireDecision === 'string' ? { hireDecision: entry.hireDecision } : {}),
}]));
// Row 194 (D1): the human's forbid lists and the retired names. The bus adds running runs.
return {
+3
View File
@@ -94,6 +94,9 @@ export const VERB_RIGHTS = record({
'packs.console': 'board.read',
'pack.preview.console': null,
'pack.apply.console': null,
// Ruling 2026-11-14: hiring a pack's proposed agents is a hire; a member with org.hire gets the
// unflagged ones and the rest wait for the owner (invariant 7).
'pack.hire.console': 'org.hire',
'board.set.console': null,
'workflow.set.console': null,
// #1873 SP8: saving a template, and listing the saved ones, are the owner's alone: a template is a
+72 -56
View File
@@ -10,10 +10,13 @@
// (instance credentials, copyBindings, copyId, orgIncarnation, generation), launch, plugins, vars,
// project roots and git state, definition revs and hire decisions, and everything on the bus.
//
// Free text is kept, with the organization id, its project ids, its agent names, the owner's
// account and the project roots replaced by {org}, {project}, {agent}, {owner} and {root}. The
// preview lists each replacement and every kept free-text field by path, and the exact JSON save
// writes; save takes that JSON's digest. Every string and key is passed to the credential store's
// Free text is kept verbatim: save never rewrites prose (E2E6 fix 5, Lead ruling). A placeholder
// could stand only where a field's whole value is an organization identifier, and a pack carries no
// such field (hire names are <role>-<n>, step roles name definitions or templates), so save writes
// none and apply has none to resolve. The preview lists every kept free-text field by path, each
// one that mentions the organization id, a project id, an agent name, the owner's account or a
// project root (so the owner can edit it before saving), and the exact JSON save writes; save takes
// that JSON's digest. Every string and key is passed to the credential store's
// assertClean; a hit refuses template-secret-suspected naming the path, never the text.
//
// A refusal is a TemplateError: a bus code and a reason that names a path or a checked name only,
@@ -49,8 +52,8 @@ export const DEFAULT_BOARD = Object.freeze({
layout: "kanban",
});
const HIRE_REASON = "The organization this template was saved from ran this agent.";
// A word boundary for placeholder replacement: an identifier character on either side means the
// literal is part of a longer name, which stays as it is.
// A word boundary for a mention: an identifier character on either side means the literal is part of
// a longer name, which is not a mention.
const WORD = "A-Za-z0-9_-";
export class TemplateError extends Error {
@@ -100,63 +103,63 @@ function templateOrNull(rolesDir, name, cache) {
return cache.get(name);
}
// ---- Placeholders ----
// ---- Mentions ----
// The literals section 5 replaces, longest first so a root path is replaced before the ids inside
// it. A name that is also a template or a definition name is a role's name, not a person's or a
// client's, and stays: replacing "coder" would rewrite every role text that says coder.
function literals(document, { rolesDir, cache }) {
// The organization-specific names the preview looks for in kept text, longest first so a root path
// is found before the ids inside it. A name that is also a template or a definition name is a role's
// name, not a person's or a client's, and is not a mention: role text says "coder" on purpose. A
// mention is labelled by kind and name; a project root is labelled by kind alone, so the preview
// names no host path beyond the text it already shows.
function orgNames(document, { rolesDir, cache }) {
const out = [];
const add = (text, placeholder) => {
if (typeof text === "string" && text.length > 0 && !out.some((l) => l.text === text)) out.push({ text, placeholder });
const add = (text, label) => {
if (typeof text === "string" && text.length > 0 && !out.some((l) => l.text === text)) out.push({ text, label });
};
for (const project of Object.values(document.projects ?? {})) {
add(project?.root, "{root}");
add(project?.repo, "{root}");
add(project?.root, "project root");
add(project?.repo, "project root");
}
add(document.id, "{org}");
for (const id of Object.keys(document.projects ?? {})) add(id, "{project}");
add(document.human, "{owner}");
if (typeof document.id === "string") add(document.id, `organization ${document.id}`);
for (const id of Object.keys(document.projects ?? {})) add(id, `project ${id}`);
if (typeof document.human === "string") add(document.human, `owner ${document.human}`);
const role = (name) => Object.hasOwn(document.definitions ?? {}, name) || templateOrNull(rolesDir, name, cache) !== null;
const agents = new Set([...Object.keys(document.roles ?? {}), ...(Array.isArray(document.retired) ? document.retired : [])]);
for (const project of Object.values(document.projects ?? {})) for (const name of Object.keys(project?.agents ?? {})) agents.add(name);
for (const name of agents) if (!role(name)) add(name, "{agent}");
for (const name of agents) if (!role(name)) add(name, `agent ${name}`);
out.sort((a, b) => b.text.length - a.text.length);
return out;
}
// Returns the text with every literal replaced, and counts each placeholder used. One pass over the
// text with one alternation, longest literal first: a placeholder written in never matches a later
// literal, so an instance named "root" or "agent" cannot rewrite {root} or {agent}.
// The labels of every name the text mentions, in first-mention order, each once. One pass with one
// alternation, longest name first, so a root path is one mention and not the ids inside it.
const combined = new WeakMap();
function replace(text, list, counts) {
if (list.length === 0) return text;
function mentions(text, list) {
if (list.length === 0) return [];
let entry = combined.get(list);
if (!entry) {
const by = new Map(list.map((l) => [l.text, l.placeholder]));
const by = new Map(list.map((l) => [l.text, l.label]));
entry = { by, pattern: new RegExp(`(?<![${WORD}])(?:${list.map((l) => escape(l.text)).join("|")})(?![${WORD}])`, "g") };
combined.set(list, entry);
}
return text.replace(entry.pattern, (match) => {
const placeholder = entry.by.get(match);
counts[placeholder] = (counts[placeholder] ?? 0) + 1;
return placeholder;
});
const found = [];
for (const match of text.matchAll(entry.pattern)) {
const label = entry.by.get(match[0]);
if (!found.includes(label)) found.push(label);
}
return found;
}
// ---- Capture ----
// Builds the template document. With list null, free text is kept as it is (the scan's second
// copy); otherwise each replacement and each kept free-text field is recorded by path.
// Builds the template document. Free text is copied verbatim; each kept free-text field, and each
// one that mentions an organization-specific name, is recorded by path.
function capture(document, { name, project, rolesDir, list, record }) {
const cache = new Map();
const text = (value, path) => {
if (list === null) return value;
const counts = {};
const out = replace(value, list, counts);
for (const [placeholder, count] of Object.entries(counts)) record.replacements.push({ path, placeholder, count });
record.freeText.push({ path, text: out });
return out;
record.freeText.push({ path, text: value });
const names = mentions(value, list);
if (names.length > 0) record.mentions.push({ path, names });
return value;
};
const orgDefinitions = plain(document.definitions) ? document.definitions : {};
const scope = project === undefined ? "org" : "project";
@@ -233,7 +236,7 @@ function capture(document, { name, project, rolesDir, list, record }) {
if (!template) refuse("starter-pack-invalid", `${at}.from names a template that is not a version 2 role`);
// A template that changed since the definition copied it: the saved from names its current
// hash, and the role must still narrow the current template. The preview lists the re-pin.
if (template.sha256 !== entry.from.sha256 && list !== null) record.repinned.push(`${at}.from`);
if (template.sha256 !== entry.from.sha256) record.repinned.push(`${at}.from`);
out.from = { template: template.name, sha256: template.sha256 };
let composition;
try {
@@ -323,11 +326,12 @@ function capture(document, { name, project, rolesDir, list, record }) {
seen.add(k);
packs.push({ id: entry.id, version: entry.version });
}
if (list !== null) record.packsDropped = Math.max(0, packs.length - PACK_BOUNDS.packs);
record.packsDropped = Math.max(0, packs.length - PACK_BOUNDS.packs);
const keptPacks = packs.slice(Math.max(0, packs.length - PACK_BOUNDS.packs));
const label = name.slice(0, PACK_BOUNDS.label);
const descriptionText = scope === "org" ? "Saved from {org}." : "Saved from {project} in {org}.";
// No placeholder: apply copies the description as it stands, so a "{org}" here would stay literal.
const descriptionText = scope === "org" ? "Saved from an organization." : "Saved from one project of an organization.";
return {
packVersion: PACK_VERSION, id: name, version: "1.0.0", label, description: descriptionText, scope,
definitions, hires, board, workflows, skills, packs: keptPacks,
@@ -356,20 +360,16 @@ function scan(value, path, assertClean) {
}
}
// The preview: the exact JSON save writes, its digest, each replacement and each kept free-text
// field by path. Refuses before returning when any string or key holds a held credential value.
// The preview: the exact JSON save writes, its digest, each kept free-text field by path, each such
// field that mentions an organization-specific name, with the names it mentions, and each re-pin.
// Refuses before returning when any string or key holds a held credential value.
export function templatePreview({ document, name, project, rolesDir, assertClean }) {
checkTemplateName(name);
if (project !== undefined && (typeof project !== "string" || !ID_PATTERN.test(project))) refuse("invalid-request", "the project id is invalid");
if (typeof assertClean !== "function") throw new TypeError("templatePreview needs the credential store's assertClean");
if (!plain(document)) refuse("invalid-request", "the organization file is not readable");
const scope = { name, project, rolesDir };
// The scan reads both copies: the kept text before replacement (a held value a placeholder would
// break up still refuses) and the document save writes.
const raw = capture(document, { ...scope, list: null, record: null });
scan(raw, "", assertClean);
const record = { replacements: [], freeText: [], repinned: [], packsDropped: 0 };
const template = capture(document, { ...scope, list: literals(document, { rolesDir, cache: new Map() }), record });
const record = { freeText: [], mentions: [], repinned: [], packsDropped: 0 };
const template = capture(document, { name, project, rolesDir, list: orgNames(document, { rolesDir, cache: new Map() }), record });
scan(template, "", assertClean);
let checked;
try {
@@ -386,13 +386,27 @@ export function templatePreview({ document, name, project, rolesDir, assertClean
return {
name, scope: checked.scope, ...(project === undefined ? {} : { project }),
template: checked, json, digest: sha256(json),
replacements: record.replacements.sort(byPath), freeText: record.freeText.sort(byPath),
freeText: record.freeText.sort(byPath), mentions: record.mentions.sort(byPath),
repinned: record.repinned.sort(), packsDropped: record.packsDropped,
};
}
// ---- The file ----
const TEMPLATE_EXISTS = "a template of this name is already saved; save under another name";
// Whether a file (or anything, a symlink included) already holds the name. It looks only through a
// templates and an account directory that are real directories, so a link is never followed to say
// what lies elsewhere; any other case is left to the directory checks and the exclusive create.
function taken(templates, home, file) {
try {
if (!lstatSync(templates).isDirectory() || !lstatSync(home).isDirectory()) return false;
lstatSync(file);
return true;
} catch {
return false;
}
}
// A directory save writes under: real, the uid's own, writable by nobody else. The account's own
// directory is private (0700 or narrower), as readSavedTemplate requires.
function directory(path, uid, { private: closed }) {
@@ -413,23 +427,25 @@ function directory(path, uid, { private: closed }) {
}
// Save: the preview again, its digest compared, then the file created exclusively (wx, 0600). A
// name already saved refuses; nothing is replaced.
// name already saved refuses template-exists; nothing is replaced. The name is checked before the
// digest, so a save under a taken name says so even when the preview is stale.
export function templateSave({ document, name, project, digest, rolesDir, assertClean, configDir, account, uid = process.getuid() }) {
checkAccount(account);
checkTemplateName(name);
if (typeof digest !== "string" || !/^[0-9a-f]{64}$/.test(digest)) refuse("invalid-request", "save takes the preview's digest");
const preview = templatePreview({ document, name, project, rolesDir, assertClean });
if (preview.digest !== digest) refuse("pack-plan-stale", "the organization or a template changed since the preview");
const templates = join(configDir, "templates");
const home = join(templates, account);
const file = join(home, `${name}.json`);
if (taken(templates, home, file)) refuse("template-exists", TEMPLATE_EXISTS);
const preview = templatePreview({ document, name, project, rolesDir, assertClean });
if (preview.digest !== digest) refuse("pack-plan-stale", "the organization or a template changed since the preview");
directory(templates, uid, { private: false });
directory(home, uid, { private: true });
const file = join(home, `${name}.json`);
let fd;
try {
fd = openSync(file, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
} catch (error) {
if (error?.code === "EEXIST") refuse("invalid-request", "a template of this name is already saved");
if (error?.code === "EEXIST") refuse("template-exists", TEMPLATE_EXISTS);
refuse("not-configured", "the template file cannot be created");
}
try {
@@ -86,6 +86,7 @@ const VERBS = {
'packs.console': 'board.read',
'pack.preview.console': null,
'pack.apply.console': null,
'pack.hire.console': 'org.hire',
'board.set.console': null,
'workflow.set.console': null,
// Starter packs SP8 (#1873): saving a template and listing the saved ones are the owner's alone.
@@ -1,6 +1,7 @@
// Starter packs SP8 (#1873): saving an organization or one of its projects as a template. The saved
// file carries no credential material and no member, keeps each role's credential request lines,
// replaces the organization's own names with placeholders, and reads back as an origin-saved pack.
// keeps free text verbatim (E2E6 fix 5) while the preview lists the fields that mention the
// organization's own names, and reads back as an origin-saved pack.
import test from "node:test";
import assert from "node:assert/strict";
import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
@@ -94,34 +95,56 @@ test("SP8 the saved file keeps each role's credential request lines", (t) => {
assert.ok(template.definitions.writer.role.credentials.length > 0);
});
test("SP8 placeholders replace the org and project ids, the owner, agent names and project roots, in free text only", (t) => {
// E2E6 fix 5, red before: the old save rewrote prose word by word, so a project named "work" turned
// "hand finished work to review" into "hand finished {project} to review", and apply never resolves
// a placeholder. Save now keeps every free-text field as it stands.
test("E2E6 red before: save never rewrites prose; a project named work leaves \"hand finished work to review\" as it is", (t) => {
const { doc, rolesDir } = fixture(t);
doc.projects.work = { ...structuredClone(doc.projects.stack), root: join(doc.projects.stack.root, "..", "work-root") };
doc.workflows.change.steps[1].title = "hand finished work to review";
const preview = templatePreview({ document: doc, name: "team-shape", rolesDir, assertClean });
assert.equal(preview.template.workflows.change.steps[1].title, "hand finished work to review");
assert.ok(!preview.json.includes("{project}"));
// The owner sees the mention and may edit the text before saving.
assert.deepEqual(preview.mentions.find((m) => m.path === "workflows.change.steps[1].title"), { path: "workflows.change.steps[1].title", names: ["project work"] });
});
test("E2E6 free text is kept verbatim, no placeholder is written, and the preview lists each field that mentions an org-specific name", (t) => {
const { doc, rolesDir } = fixture(t);
const preview = templatePreview({ document: doc, name: "team-shape", rolesDir, assertClean });
const { template } = preview;
assert.equal(template.definitions.writer.instructions, "Write code for {org} in {root}/src. Ask {owner}; pair with {agent} on {project}.");
assert.equal(template.definitions.writer.personality.summary, "Careful {org} engineer.");
assert.deepEqual(template.definitions.writer.personality.traits, ["works with {agent}", "plain"]);
assert.equal(template.board.columns[0].label, "{org} backlog");
assert.equal(template.workflows.change.description, "Change for {project}");
assert.equal(template.workflows.change.steps[0].title, "{agent} writes it");
// Agent names that are role names (pm, coder) stay; role text says "coder" on purpose.
const all = JSON.stringify(template);
for (const literal of ["acme", "jason", "ana", doc.projects.stack.root]) assert.ok(!all.includes(literal), literal);
assert.equal(template.description, "Saved from {org}.");
// Each replacement is listed by path.
const at = (path) => preview.replacements.filter((r) => r.path === path).map((r) => r.placeholder).sort();
assert.deepEqual(at("definitions.writer.instructions"), ["{agent}", "{org}", "{owner}", "{project}", "{root}"]);
assert.equal(template.definitions.writer.instructions, doc.definitions.writer.instructions);
assert.equal(template.definitions.writer.personality.summary, "Careful acme engineer.");
assert.deepEqual(template.definitions.writer.personality.traits, ["works with ana", "plain"]);
assert.equal(template.board.columns[0].label, "acme backlog");
assert.equal(template.workflows.change.description, "Change for stack");
assert.equal(template.workflows.change.steps[0].title, "ana writes it");
for (const placeholder of ["{org}", "{project}", "{agent}", "{owner}", "{root}"]) assert.ok(!preview.json.includes(placeholder), placeholder);
assert.equal(template.description, "Saved from an organization.");
assert.ok(!Object.hasOwn(preview, "replacements"));
const at = (path) => preview.mentions.find((m) => m.path === path)?.names;
// A root path is one mention, labelled by kind alone, not the ids inside it.
assert.deepEqual(at("definitions.writer.instructions"), ["organization acme", "project root", "owner jason", "agent ana", "project stack"]);
assert.deepEqual(at("definitions.writer.personality.traits[1]"), undefined);
assert.deepEqual(at("board.columns[0].label"), ["organization acme"]);
// Role names (writer, coder) are not mentions; a longer word holding a name is not one either.
assert.equal(at("board.columns[1].label"), undefined);
doc.board.columns[1].label = "acmes and anas";
assert.equal(templatePreview({ document: doc, name: "team-shape", rolesDir, assertClean }).mentions.find((m) => m.path === "board.columns[1].label"), undefined);
// Every mention is a kept free-text field, in path order.
const paths = preview.mentions.map((m) => m.path);
assert.deepEqual(paths, [...paths].sort());
for (const p of paths) assert.ok(preview.freeText.some((f) => f.path === p), p);
});
test("SP8 an instance named root, org or agent never rewrites a placeholder already written in", (t) => {
test("E2E6 text that looks like a placeholder, or an instance named root, org or agent, stays verbatim", (t) => {
const { doc, rolesDir } = fixture(t);
doc.roles.root = { definition: "org:writer" };
doc.roles.org = { definition: "org:writer" };
doc.definitions.writer.instructions = "Work for acme with root on stack. Ask org, then jason.";
doc.definitions.writer.instructions = "Work for acme with root on stack. Ask org, then jason. Keep {org} and {agent} literal.";
const preview = templatePreview({ document: doc, name: "team-shape", rolesDir, assertClean });
assert.equal(preview.template.definitions.writer.instructions, "Work for {org} with {agent} on {project}. Ask {agent}, then {owner}.");
const at = preview.replacements.filter((r) => r.path === "definitions.writer.instructions").map((r) => r.placeholder).sort();
assert.deepEqual(at, ["{agent}", "{org}", "{owner}", "{project}"]);
assert.equal(preview.template.definitions.writer.instructions, doc.definitions.writer.instructions);
assert.deepEqual(preview.mentions.find((m) => m.path === "definitions.writer.instructions").names, ["organization acme", "agent root", "project stack", "agent org", "owner jason"]);
});
test("SP8 the preview lists every kept free-text field with its saved text", (t) => {
@@ -151,7 +174,7 @@ test("SP8 a held credential in kept text refuses template-secret-suspected namin
doc.definitions.writer.personality.voice = `short, key ${TOKEN}`;
refused(() => templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean }), "template-secret-suspected", "definitions.writer.personality.voice");
try { templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean }); } catch (e) { assert.ok(!e.message.includes(TOKEN)); }
// A held value a placeholder would split still refuses: the scan reads the text before replacement.
// A held value inside other text still refuses: the scan reads the text save keeps.
const second = fixture(t);
second.doc.workflows.change.steps[1].title = `acme${TOKEN}`;
refused(() => templatePreview({ document: second.doc, name: "acme-shape", rolesDir: second.rolesDir, assertClean }), "template-secret-suspected", "workflows.change.steps[1].title");
@@ -170,7 +193,9 @@ test("SP8 a second save to the same name refuses and leaves the first file", (t)
const first = readFileSync(file);
doc.definitions.writer.instructions = "Changed.";
const next = templatePreview({ document: doc, name: "acme-shape", rolesDir, assertClean });
refused(() => templateSave({ document: doc, name: "acme-shape", digest: next.digest, rolesDir, assertClean, configDir, account: "jason" }), "invalid-request", "a template of this name is already saved");
refused(() => templateSave({ document: doc, name: "acme-shape", digest: next.digest, rolesDir, assertClean, configDir, account: "jason" }), "template-exists", "a template of this name is already saved; save under another name");
// E2E6 fix 8: the name is checked first, so a stale or malformed-but-valid digest still says the name is taken.
refused(() => templateSave({ document: doc, name: "acme-shape", digest: "0".repeat(64), rolesDir, assertClean, configDir, account: "jason" }), "template-exists");
assert.deepEqual(readFileSync(file), first);
assert.equal(lstatSync(file).mode & 0o777, 0o600);
assert.equal(lstatSync(join(configDir, "templates", "jason")).mode & 0o777, 0o700);
@@ -246,7 +271,7 @@ test("SP8 a project template carries the project's agents, the definitions it na
assert.deepEqual(Object.keys(template.definitions).sort(), ["reviewer", "writer"]);
assert.deepEqual(template.board, JSON.parse(JSON.stringify(DEFAULT_BOARD)));
assert.deepEqual(template.workflows, {});
assert.equal(template.description, "Saved from {project} in {org}.");
assert.equal(template.description, "Saved from one project of an organization.");
refused(() => templatePreview({ document: doc, name: "x", project: "nope", rolesDir, assertClean }), "invalid-request");
});
+33
View File
@@ -25,6 +25,7 @@ baseline CLI.
| Restart the Console | Stop and run `mosaic console start` again | Enabled (F3) when `mosaic console start` runs it in the foreground, or with `--dev-local-owner --detach` under a detached supervisor (D1): Settings > Console; the owner only; trailed. Other Consoles answer `not-supervised` |
| Save, review, confirm or reverse an organization's autonomy | Read, save and review: `mosaic org autonomy ORG`, `mosaic org autonomy ORG set --revision REV [--cross-role|--merge|--policy|--authority in|near|out] [--notices on|off] [--reverse-window-hours 1-168] [--authority-resolver NAME|""]`, `mosaic org autonomy ORG review CLASS` (E2, through this route and its revision check); confirm and reverse act on inbox decisions and have no verb yet | Enabled (D1) on a `--dev-local-owner` Console: the owner only, on the selected organization's bus, behind a fence that passes only the four console verbs `autonomy.set.console`, `autonomy.review.console`, `decision.confirm.console` and `decision.reverse.console` |
| Hire, fire or change an agent; read role templates | `mosaic org role-templates ORG`; `mosaic org hire|change ORG --name NAME --template TEMPLATE --harness H --model M [--thinking T] [--level org|project|root] [--project P] --reason TEXT`; `mosaic org fire ORG --name NAME [--level ...] --reason TEXT` (E2, through this route) | Enabled (D4) for the owner on a selected organization's bus: one decision raised and approved through `hire.start.console`, with the bus's hire checks |
| Apply a starter pack; hire its proposed agents; fire an agent from its card | `mosaic org pack preview|apply ID PACK [--digest D] [--project P]`; `mosaic org pack hire ID PACK [--project P]`; `mosaic org fire ORG --name NAME --reason TEXT` | Enabled for the owner (ruling 2026-11-14): applying is the hire decision; see "Starter pack hires" |
| Create, edit or archive a board task | `mosaic tasks create --title T --requirement REQ [--project P] [--state S] [--assignees R,...] [--priority 0-5] [--due ISO|none]`; `mosaic tasks edit task:N --expect DIGEST ...`; `mosaic tasks archive task:N --expect DIGEST` (E2: the board's own check, then the person's `tasks.create|edit|archive` on the bus) | Enabled for the owner on an organization with the built-in task store |
| Create chat project linked to a configured repository | `mosaic project create <name> --repo <project> --org <id>` | Enabled |
| Create a thread | `mosaic thread create <project> <name> --org <id>` | Planned enabled |
@@ -70,6 +71,38 @@ as the owner's page can. The startup warning says so. Use a dev instance for UI
testing only. The real boundary is sign-in (`--sso`); a refusal for local agent
peers in dev mode is a recorded follow-up.
### Starter pack hires (ruling 2026-11-14, #1873)
"Damnit. If I choose a starter pack and apply it, that is a decision!"
`POST /api/orgs/<id>/packs/apply` (`pack.apply.console`) hires the pack's
proposed agents in the same act, and its receipt is `{revision, added, pack,
hires}`; when the apply committed but its hire loop did not run, `hires` is
empty and `hireError` names the code, and the card says the hires did not run.
`POST /api/orgs/<id>/packs/hire` with `{pack, project?}`
(`pack.hire.console`) runs the same loop on a pack already applied and answers
`{pack, hires}`; `pack-not-applied` is 404 and `right-required` 403. Each hire
line is `{name, state, decision | code}`, and a `hired` or `awaiting-owner`
line adds `routeFrom: 'chief' | 'assistant'`, whose harness and model the hire
got (the chief of staff's, else the organization assistant's). `GET /api/orgs/<id>/packs` adds, to
each applied entry, `hired` (the agents its hires created) and `open` (each
proposal not hired, with its reason, its state and its decision or code, and
`fromPack: true` on an `awaiting-owner` line this pack's own hire raised). The
packs routes stay the owner's: a member's pack hire is the bus verb's
(`pack.hire.console` needs `org.hire`, and the flagged hires wait for the
owner), but no member page calls it yet.
The pack card says what applying does before the click ("applying is the hire
decision, and approves the flagged and credential lines below"), shows "N
agents hired" and the open proposals with their reasons after it, and offers
"Hire the N proposed agents" for proposals not waiting for the owner, and for
the owner's own `fromPack` lines, which the owner's hire replaces and approves. Apply,
hire and fire dispatch `mosaic-org-changed`, so the Agents page and the
organization page redraw in the same cycle instead of at the next 10-second
poll. Each agent card a pack hire made says "from pack X". The owner's Agents
page offers Fire on each agent but the chief of staff and the assistant, with a confirm step;
Fire sends `{op: 'fire'}` through `/api/decisions/hire/start`, removes the
card at once and leaves a receipt naming the decision.
### Route registration
A module may export `registerRoutes(table)` and be included with one entry in
+29 -12
View File
@@ -2,10 +2,14 @@
// selected organization. Owner Console transports only; no caller-supplied business, actor, subject
// or origin reaches the bus.
//
// GET /api/orgs/<id>/packs {packs, writable}: packs.console, the shipped and installed
// packs (never a saved template). /api/packs on a root Console.
// GET /api/orgs/<id>/packs {packs, applied, writable}: packs.console, the shipped and installed
// packs (never a saved template), and each applied entry with the
// agents its hires created and its open proposals. /api/packs on a root Console.
// POST /api/orgs/<id>/packs/preview {pack, project?, as?}: pack.preview.console. Writes nothing.
// POST /api/orgs/<id>/packs/apply {pack, digest, project?, as?}: pack.apply.console
// POST /api/orgs/<id>/packs/apply {pack, digest, project?, as?}: pack.apply.console. Ruling 2026-11-14:
// the owner's apply is the hire decision; the receipt carries `hires`
// POST /api/orgs/<id>/packs/hire {pack, project?}: pack.hire.console, the proposals of a pack already
// applied, hired through the same loop. {pack, hires}
// POST /api/orgs/<id>/board {revision, board, project?}: board.set.console (board null removes it)
// POST /api/orgs/<id>/workflows/<name> {revision, workflow, project?}: workflow.set.console
// DELETE /api/orgs/<id>/workflows/<name> {revision, project?}: workflow.set.console with workflow null
@@ -15,17 +19,17 @@
// file revision a workflow write sends back
//
// `read` is the owner's Console call (consoleCall), used for the two verbs that write nothing. `write`
// is the owner's Console call fenced to the three write verbs (packsCaller), present only for the
// is the owner's Console call fenced to the four write verbs (packsCaller), present only for the
// owner's own session under --send. The broker answers every .console verb to the business human's
// console cap alone, and runs the merge, the digest and the held-credential check itself. `workflows`
// (SP6) is the owner's read of the organization file as the writer reads it ({document, revision,
// templates}), the same read `mosaic org workflow set` takes its revision from; no bus verb answers it.
export const PACKS_ROUTE = /^\/api\/(?:packs(?:\/(preview|apply))?|board|workflows(?:\/([^/]+))?)$/;
export const PACKS_ROUTE = /^\/api\/(?:packs(?:\/(preview|apply|hire))?|board|workflows(?:\/([^/]+))?)$/;
// Which requests the pack route answers. GET and HEAD /api/board stay the Board read (the Console's own task
// board through its upstream); every other method on /api/board is this route's (POST writes, the rest 405).
// serve.mjs dispatches on this, so the HEAD pin in packs-http.test.mjs tests the predicate it uses.
export const packsServes = (path, method) => PACKS_ROUTE.test(path) && !(path === '/api/board' && (method === 'GET' || method === 'HEAD'));
export const PACK_WRITE_VERBS = Object.freeze(['pack.apply.console', 'board.set.console', 'workflow.set.console']);
export const PACK_WRITE_VERBS = Object.freeze(['pack.apply.console', 'pack.hire.console', 'board.set.console', 'workflow.set.console']);
export const packsCaller = call => async (verb, args, options) => {
if (!PACK_WRITE_VERBS.includes(verb)) throw new Error(`the pack writer does not call ${verb}`);
return call(verb, args, options);
@@ -38,9 +42,9 @@ const REVISION = /^[a-f0-9]{64}$/;
const LIMIT = 65536;
const codes = {
'invalid-request': 400, 'credential-leak': 400, 'starter-pack-invalid': 400, 'definition-invalid': 400,
'starter-pack-not-found': 404, 'project-not-found': 404,
'starter-pack-not-found': 404, 'project-not-found': 404, 'pack-not-applied': 404,
'pack-plan-stale': 409, 'revision-conflict': 409, 'organization-busy': 409,
'human-required': 403, 'read-only': 403,
'human-required': 403, 'read-only': 403, 'right-required': 403,
'not-configured': 503, 'no-bus-host': 503,
};
const one = (req, key) => req.headersDistinct[key]?.length === 1 ? req.headersDistinct[key][0] : null;
@@ -89,7 +93,7 @@ export async function packsHTTP(req, res, { path, owner, read, write, workflows
let verb, args = {};
if (list) verb = 'packs.console';
else if (step !== null) {
const value = await body(req, step === 'apply' ? ['pack', 'digest'] : ['pack'], ['project', 'as']);
const value = await body(req, step === 'apply' ? ['pack', 'digest'] : ['pack'], step === 'hire' ? ['project'] : ['project', 'as']);
if (value === 'too-large') return refuse(413, 'invalid-request');
if (!value || typeof value.pack !== 'string' || !(NAME.test(value.pack) || SAVED.test(value.pack))
|| (step === 'apply' && (typeof value.digest !== 'string' || !REVISION.test(value.digest)))
@@ -124,16 +128,29 @@ export async function packsHTTP(req, res, { path, owner, read, write, workflows
if (!plain(result)) return refuse(503, 'outcome-unknown');
if (list) {
if (!Array.isArray(result.packs)) return refuse(503, 'outcome-unknown');
return json(res, 200, { packs: result.packs, writable: Boolean(write) });
const applied = Array.isArray(result.applied) ? result.applied.filter(plain).map(a => ({ id: a.id, origin: a.origin ?? null, project: a.project ?? null,
hired: Array.isArray(a.hired) ? a.hired.filter(n => typeof n === 'string') : [],
open: Array.isArray(a.open) ? a.open.filter(plain).map(o => ({ name: o.name, reason: typeof o.reason === 'string' ? o.reason : '', state: o.state, ...(typeof o.code === 'string' ? { code: o.code } : {}), ...(typeof o.decision === 'string' ? { decision: o.decision } : {}), ...(o.fromPack === true ? { fromPack: true } : {}) })) : [] })) : [];
return json(res, 200, { packs: result.packs, applied, writable: Boolean(write) });
}
if (step === 'preview') {
if (!REVISION.test(result.digest ?? '')) return refuse(503, 'outcome-unknown');
return json(res, 200, result);
}
// A write admitted may already have committed: its receipt is returned even if the session ended
// meanwhile, never reported as not done.
// meanwhile, never reported as not done. Each hire line is its name, state and decision or code,
// and for a raised hire routeFrom, whose harness and model it got (lane pr2).
const hires = Array.isArray(result.hires) ? result.hires.filter(plain).map(h => ({ name: h.name, state: h.state,
...(typeof h.decision === 'string' ? { decision: h.decision } : {}), ...(typeof h.code === 'string' ? { code: h.code } : {}),
...(['chief', 'assistant'].includes(h.routeFrom) ? { routeFrom: h.routeFrom } : {}) })) : null;
if (step === 'hire') {
if (!hires) return refuse(503, 'outcome-unknown');
return json(res, 200, { pack: result.pack, hires });
}
if (!REVISION.test(result.revision ?? '')) return refuse(503, 'outcome-unknown');
return json(res, 200, { revision: result.revision, added: Array.isArray(result.added) ? result.added : [], ...(step === 'apply' ? { pack: result.pack } : {}) });
// hireError: the apply committed but its hire loop did not run (organization-busy, outcome-unknown).
const hireError = step === 'apply' && typeof result.hireError === 'string' && /^[a-z0-9-]{1,64}$/.test(result.hireError) ? { hireError: result.hireError } : {};
return json(res, 200, { revision: result.revision, added: Array.isArray(result.added) ? result.added : [], ...(step === 'apply' ? { pack: result.pack, hires: hires ?? [], ...hireError } : {}) });
}
// SP6: the workflow list and editor's read. Only workflows, the names a step role may resolve to and the
+34 -15
View File
@@ -76,8 +76,11 @@
if (!usable() || busy || pending || !view) return;
const [url, payload] = plan(action, name);
busy = true; confirming = null; receipt = ''; redraw();
const gen = generation;
let answer;
try { answer = await post(url, payload); } catch { answer = { ok: false, result: { sent: 'unknown' } }; }
// #1873 SP1: an organization switch while this was in flight drops the answer; the switch already cleared busy.
if (gen !== generation) return;
busy = false;
if (answer === null) return;
const { ok, result } = answer;
@@ -122,8 +125,10 @@
const instance = create.instance.trim(), definition = create.definition;
if (!instance || !definition) { receipt = 'Name the instance and choose a definition.'; redraw(); return; }
busy = true; receipt = ''; redraw();
const gen = generation;
let answer;
try { answer = await post('/api/instances', { revision: view.revision, instance, op: 'add', definition }); } catch { answer = { ok: false, result: { sent: 'unknown' } }; }
if (gen !== generation) return;
busy = false;
if (answer === null) return;
if (answer.ok && /^[a-f0-9]{64}$/.test(answer.result?.revision ?? '')) { create = { instance: '', definition: '' }; receipt = `Created ${instance}. ${answer.result.restart ? restartText() : NO_RESTART_TEXT}`; reread(); }
@@ -154,19 +159,31 @@
document.addEventListener('submit', e => { if (e.target?.id !== 'agent-create-form') return; e.preventDefault(); createAgent(); });
// A sign-out stops any poll; nothing that was asked is retried.
document.addEventListener('mosaic-signed-out', () => { generation++; pending = null; confirming = null; });
// #1873 SP1: opening another organization stops any poll and clears what this section held for the
// old one. A request already sent finishes on the old organization's bus; its page reads it again there.
document.addEventListener('mosaic-org-switch', () => {
generation++; pending = null; receipt = ''; editing = null; confirming = null; busy = false;
create = { instance: '', definition: '' };
for (const k of Object.keys(reasons)) delete reasons[k];
});
// F3: restart an agent so a route change reaches it now, offered by the Routing receipt. One
// terminate; then reads of the instances until the run has left (up to the 60 s regenerate
// allows); then one launch. A thread definition is not launched: its next message starts it.
// A refusal, a sign-out or an unknown outcome stops the chain and says so; nothing is retried.
const restarts = Object.create(null);
let restarts = Object.create(null);
// #1873 SP1: the chain's reads and writes go to the organization it started in, which the fetch
// wrapper passes through unchanged. A switch clears what the new page shows; the old chain keeps
// its own entry and stops painting.
const pin = (org, path) => org ? `/api/orgs/${encodeURIComponent(org)}/${path.slice('/api/'.length)}` : path;
document.addEventListener('mosaic-org-switch', () => { restarts = Object.create(null); });
const RESTART_WAIT = 30;
function restartMarkup(name, thread = false) {
const r = restarts[name];
return `<span class="agent-restart"><button type="button" class="btn" data-agent-restart="${esc(name)}" data-agent-thread="${thread ? 'yes' : 'no'}"${r?.busy ? ' disabled' : ''}>${r?.busy ? 'Restarting…' : `Restart ${esc(name)} now`}</button> <span role="status" data-agent-restart-status="${esc(name)}">${esc(r?.text ?? '')}</span></span>`;
}
const esc = s => String(s).replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
const paintRestart = name => document.querySelectorAll('.agent-restart').forEach(el => {
const paintRestart = (name, org = window.MosaicOrg?.id ?? null) => (window.MosaicOrg?.id ?? null) !== org ? undefined : document.querySelectorAll('.agent-restart').forEach(el => {
const b = el.querySelector('[data-agent-restart]');
if (b?.dataset.agentRestart === name) el.outerHTML = restartMarkup(name, b.dataset.agentThread === 'yes');
});
@@ -179,45 +196,47 @@
return { ok: res.ok, result };
}
// The request's closing read, or a reason the chain stops.
async function closing(request) {
async function closing(request, org) {
for (let tries = 0; tries < POLL_LIMIT; tries++) {
await new Promise(r => setTimeout(r, POLL_MS));
let res, r = null;
try { res = await fetch(`/api/agent/request?id=${encodeURIComponent(request)}`, { cache: 'no-store', redirect: 'manual' }); } catch { continue; }
try { res = await fetch(pin(org, `/api/agent/request?id=${encodeURIComponent(request)}`), { cache: 'no-store', redirect: 'manual' }); } catch { continue; }
if (res.type === 'opaqueredirect') return { stop: 'Sign in again, then read the agents.' };
try { r = await res.json(); } catch { continue; }
if (res.ok && r?.request === request && r.state === 'closed') return { done: r };
}
return { stop: `Request ${request} is still open. Read the agents again later.` };
}
async function runs(name) {
async function runs(name, org) {
try {
const res = await fetch('/api/bus/instances', { cache: 'no-store', redirect: 'manual' });
const res = await fetch(pin(org, '/api/bus/instances'), { cache: 'no-store', redirect: 'manual' });
if (!res.ok || res.type === 'opaqueredirect') return null;
const e = (await res.json())?.rows?.[0]?.instances?.[name];
return e ? (Array.isArray(e.running) ? e.running.length : 0) : 0;
} catch { return null; }
}
async function restartAgent(name, thread) {
const org = window.MosaicOrg?.id ?? null;
const r = restarts[name] = { busy: true, text: `Terminating ${name}…` };
const stop = text => { r.busy = false; r.text = text; paintRestart(name); };
paintRestart(name);
const asked = await send('/api/agent/terminate', { instance: name, reason: 'route change' });
const paint = () => paintRestart(name, org);
const stop = text => { r.busy = false; r.text = text; paint(); };
paint();
const asked = await send(pin(org, '/api/agent/terminate'), { instance: name, reason: 'route change' });
if (asked.signedOut) return stop('Sign in again, then retry.');
if (asked.unknown || !asked.ok || !REQUEST_ID.test(asked.result?.request ?? '')) return stop(asked.ok || asked.unknown ? UNKNOWN : refused(asked.result));
const ended = await closing(asked.result.request);
const ended = await closing(asked.result.request, org);
if (ended.stop) return stop(ended.stop);
if (ended.done.reason) return stop(`${name}: ${ended.done.reason}. It was not restarted.`);
r.text = `Terminated ${name}. Waiting for its session to end…`; paintRestart(name);
r.text = `Terminated ${name}. Waiting for its session to end…`; paint();
let left = false;
for (let i = 0; i < RESTART_WAIT && !left; i++) { await new Promise(res => setTimeout(res, POLL_MS)); left = (await runs(name)) === 0; }
for (let i = 0; i < RESTART_WAIT && !left; i++) { await new Promise(res => setTimeout(res, POLL_MS)); left = (await runs(name, org)) === 0; }
if (!left) return stop(`${name} was asked to end but its session is still running. Launch it from Agents once it has ended.`);
if (thread) return stop(`Terminated ${name} at ${new Date().toLocaleTimeString()}. Its next message starts it on the new route.`);
r.text = `Launching ${name}…`; paintRestart(name);
const launch = await send('/api/agent/launch', { instance: name });
r.text = `Launching ${name}…`; paint();
const launch = await send(pin(org, '/api/agent/launch'), { instance: name });
if (launch.signedOut) return stop('Sign in again. It was terminated and not launched.');
if (launch.unknown || !launch.ok || !REQUEST_ID.test(launch.result?.request ?? '')) return stop(launch.ok || launch.unknown ? `${UNKNOWN} It was terminated.` : `${refused(launch.result)} It was terminated and not launched.`);
const started = await closing(launch.result.request);
const started = await closing(launch.result.request, org);
if (started.stop) return stop(started.stop);
if (started.done.reason) return stop(`${name}: ${started.done.reason}. It was terminated and not launched.`);
return stop(`Restarted ${name} on the new route${started.done.done?.run ? ` (run ${started.done.done.run})` : ''}.`);
+64 -18
View File
@@ -11,8 +11,10 @@
// Show machine sessions (#1589): off by default, kept with the page's settings. While it is off the
// page doesn't read /api/board at all; the held roles above come from the bus (bus.js).
let machine = false;
const boardKey = window.MosaicOrg ? `mosaic-console-board:${window.MosaicOrg.id}` : 'mosaic-console-board';
try { machine = JSON.parse(localStorage.getItem(boardKey))?.machine === true; } catch {}
// #1873 SP1: kept per organization, read again when the open organization changes.
const boardKey = () => window.MosaicOrg?.id ? `mosaic-console-board:${window.MosaicOrg.id}` : 'mosaic-console-board';
const readMachine = () => { try { return JSON.parse(localStorage.getItem(boardKey()))?.machine === true; } catch { return false; } };
machine = readMachine();
// Signed out (#1589): a Console fetch answered with a redirect, so the sign-in proxy turned it away.
// The first one sets body.signed-out (the listener below); after that no Console fetch is made.
const out = () => document.body.classList.contains('signed-out');
@@ -58,6 +60,11 @@
const darkPreference = window.matchMedia('(prefers-color-scheme: dark)');
const APPEARANCE_KEY = 'mosaic-console-appearance', LAST_KEY = 'mosaic-console-appearance-last';
const orgKey = id => `${APPEARANCE_KEY}:${id}`;
// #1873 SP2: the system dashboard is no organization's page. It shows the system theme: this browser's
// own choice made there, else the default, never the theme of the organization opened last.
const SYSTEM_KEY = 'mosaic-console-appearance-system';
// SP3: display.js owns which addresses are system pages (the dashboard and #/inbox); the bare address is one before it normalizes.
const onSystem = () => !!window.MosaicOrg && ((!/^#\/orgs\//.test(location.hash) && ['', '/'].includes(location.hash.replace(/^#/, '').split('?')[0])) || window.MosaicOrg.system?.() === true);
const store = {
read(k) { try { const v = JSON.parse(localStorage.getItem(k)); return v && typeof v === 'object' && !Array.isArray(v) ? v : null; } catch { return null; } },
write(k, v) { try { localStorage.setItem(k, JSON.stringify(v)); return true; } catch { return false; } },
@@ -66,7 +73,10 @@
const orgId = v => typeof v === 'string' && v.length > 0 && v.length <= 64;
// org: null until the Console knows which organization it shows. Then the override lives under that organization's own key;
// before that, and for a Console with no organization, it is the browser-wide record this page has always kept.
let org = null, override = null, themes = null, themesUnavailable = false, current = null, applied = [];
let org = null, override = null, themes = null, themesUnavailable = false, current = null, applied = [], system = false;
const shown = () => (system ? null : org);
// Kept in memory too: a choice storage refused still shows until reload, as an organization's does.
let systemOverride = Brand.appearanceOf(store.read(SYSTEM_KEY));
const readOverride = () => {
if (org) return Brand.appearanceOf(store.read(orgKey(org.id)));
const v = store.read(APPEARANCE_KEY);
@@ -78,7 +88,7 @@
$('theme-switch').setAttribute('aria-checked', String(dark));
}
function paintNotices() {
const w = current.warning, banner = $('theme-warning'), cue = $('org-cue'), label = org?.label;
const w = current.warning, banner = $('theme-warning'), cue = $('org-cue'), label = shown()?.label;
banner.hidden = !w;
if (w) {
const asked = String(w.theme).slice(0, 64), kept = w.source === 'browser' ? 'The choice is kept.' : 'The saved value is unchanged.';
@@ -91,11 +101,12 @@
$('theme-clear').textContent = label ? `Use ${label}’s theme` : 'Use the default theme';
}
// Colour is never the only cue to which organization this is: whenever the theme is not the built-in one, the name is written out.
cue.hidden = !(org && (current.theme !== Brand.DEFAULT_THEME || w));
cue.hidden = !(shown() && (current.theme !== Brand.DEFAULT_THEME || w));
if (!cue.hidden) cue.textContent = w ? `${label} · Harbor shown instead of “${String(w.theme).slice(0, 64)}”` : `${label} · ${nameOf(current.theme)} theme · ${current.themeSource === 'browser' ? 'your choice in this browser' : 'set by the organization'}`;
}
function paint() {
current = Brand.resolveAppearance({ themes, unavailable: themesUnavailable, saved: org?.saved ?? null, override });
system = onSystem();
current = Brand.resolveAppearance({ themes, unavailable: themesUnavailable, saved: shown()?.saved ?? null, override: system ? systemOverride : override });
const root = document.documentElement;
root.dataset.palette = current.theme;
if (current.mode === 'system') delete root.dataset.mode; else root.dataset.mode = current.mode;
@@ -126,15 +137,16 @@
ready: null,
// The installed, valid themes as the server listed them, or null until /api/themes has answered.
themes: () => themes && themes.map(t => ({ id: t.id, displayName: t.displayName, tokens: t.tokens })),
state: () => ({ theme: current.theme, mode: current.mode, requested: current.requested, themeSource: current.themeSource, modeSource: current.modeSource, warning: current.warning, provisional: current.provisional, organization: org && { id: org.id, label: org.label }, saved: org?.saved ?? null, override: override && { ...override } }),
state: () => { const o = shown(), v = system ? systemOverride : override; return { theme: current.theme, mode: current.mode, requested: current.requested, themeSource: current.themeSource, modeSource: current.modeSource, warning: current.warning, provisional: current.provisional, organization: o && { id: o.id, label: o.label }, saved: o?.saved ?? null, override: v && { ...v } }; },
// Writes this browser's override for the organization (a theme, a mode, or both). false when storage refused it; the page still shows it until reload.
set(patch) {
if (onSystem()) { const next = Brand.appearanceOf({ ...(systemOverride || {}), ...patch }), ok = next ? store.write(SYSTEM_KEY, next) : true; systemOverride = next; showAppearance(ok); return ok; }
const next = Brand.appearanceOf({ ...(override || {}), ...patch });
const ok = next ? (org ? store.write(orgKey(org.id), next) : store.write(APPEARANCE_KEY, next)) : true;
override = next; showAppearance(ok); return ok;
},
// Removes the override: the organization's saved value, or else the default, shows again.
clear() { const ok = org ? store.remove(orgKey(org.id)) : store.remove(APPEARANCE_KEY); override = null; showAppearance(ok); return ok; },
clear() { if (onSystem()) { const ok = store.remove(SYSTEM_KEY); systemOverride = null; showAppearance(ok); return ok; } const ok = org ? store.remove(orgKey(org.id)) : store.remove(APPEARANCE_KEY); override = null; showAppearance(ok); return ok; },
// The seam for the organization switcher (stream S5): call it with the organization now shown and its saved appearance.
organization(id, saved, label) {
if (!orgId(id)) return;
@@ -151,6 +163,20 @@
override = readOverride();
paint();
document.dispatchEvent(new CustomEvent('mosaic-theme-change', {detail: {palette: current.theme, mode: current.mode, stored: true, warning: null, picked: current.theme}}));
// The open organization's saved appearance, read again when another organization opens (#1873 SP1).
const readBusiness = async () => {
try {
const { ok, body } = await getJSON('/api/business');
if (ok && orgId(body?.business?.id)) return window.MosaicAppearance.organization(body.business.id, body.business.appearance, body.business.id);
} catch (err) { if (err?.signedOut) return; }
// No fresh answer: keep the organization this browser last showed for its own override, but not its stale saved value.
if (org && !org.confirmed) { org.saved = null; showAppearance(); }
};
document.addEventListener('mosaic-org-switch', () => { readBusiness(); });
// The dashboard and an organization page share the shell: moving between them repaints the theme.
const repaintScope = () => { if (onSystem() !== system) showAppearance(); };
window.addEventListener('hashchange', repaintScope);
window.MosaicOrg?.ready?.then(repaintScope);
window.MosaicAppearance.ready = (async () => {
await Promise.allSettled([
(async () => {
@@ -161,14 +187,7 @@
} catch (err) { if (err?.signedOut) return; themes = []; themesUnavailable = true; }
showAppearance();
})(),
(async () => {
try {
const { ok, body } = await getJSON('/api/business');
if (ok && orgId(body?.business?.id)) return window.MosaicAppearance.organization(body.business.id, body.business.appearance, body.business.id);
} catch (err) { if (err?.signedOut) return; }
// No fresh answer: keep the organization this browser last showed for its own override, but not its stale saved value.
if (org && !org.confirmed) { org.saved = null; showAppearance(); }
})(),
readBusiness(),
]);
})();
$('palette').onchange = e => window.MosaicAppearance.set({ theme: e.target.value });
@@ -488,12 +507,22 @@
const box = $('bus-down');
// E2E5 review P2: the organization list is read first and on its own, so a failed bus-status read
// (likely when the bus is down) still refreshes the list, its banner and the Settings Start control.
// #1873 SP1: the dashboard lists every organization's bus on its own rows; this banner is an organization page's.
if (window.MosaicOrg && window.MosaicOrg.route().split('?')[0] === '/dashboard') { box.hidden = true; return; }
// An answer about an organization that is no longer open is dropped: the new one's read draws the banner.
// So is one drawn for a page left while it was read (#1873 SP2: the organization page draws none).
const where = () => window.MosaicOrg?.route().split('?')[0] === '/organization';
const asked = window.MosaicOrg?.id ?? null, onPage = where(), stale = () => (window.MosaicOrg?.id ?? null) !== asked || where() !== onPage;
if (window.MosaicOrg) {
const org = (await window.MosaicOrg.readList()).find(row => row.id === window.MosaicOrg.id);
const org = (await window.MosaicOrg.readList()).find(row => row.id === asked);
if (stale()) return;
// #1873 SP2: the organization's own page says it in its down banner, with the restart action: one banner, not two.
if (org?.busHealthy === false && onPage) { box.hidden = true; return; }
if (org?.busHealthy === false) { box.textContent = 'Bus unavailable'; box.hidden = false; window.MosaicConsole?.attachBus(box, 'Restart the bus'); return; }
}
try {
const s = await api('/api/bus-status');
if (stale()) return;
if (!s.down) { box.hidden = true; return; }
const b = s.boot;
box.replaceChildren(node('b', '', 'Bus down: organization file invalid. '), node('span', '', `${b.reason} `), node('span', 'small muted', `File ${b.file}. Refused at ${b.at}. Last good load: ${b.lastGood ?? 'none'}. Fix the file, then restart the bus.`));
@@ -528,11 +557,28 @@
function showMachine() { $('show-machine').checked = machine; document.body.classList.toggle('machine-off', !machine); }
$('show-machine').onchange = e => {
machine = e.target.checked; showMachine();
try { localStorage.setItem(boardKey, JSON.stringify({ machine })); } catch {}
try { localStorage.setItem(boardKey(), JSON.stringify({ machine })); } catch {}
if (machine) { $('status').textContent = 'Loading board…'; fresh(); refresh(); } else hideMachine();
};
showMachine();
if (!machine) hideMachine();
// #1873 SP1: another organization opened in place. Its board setting and bus state are its own.
const onOrgSwitch = () => {
machine = readMachine(); showMachine();
if (machine) { fresh(); refresh(); } else { hideMachine(); busDown(); }
};
document.addEventListener('mosaic-org-switch', onOrgSwitch);
// An address with no organization picks one after the first list read; its own setting applies then.
window.MosaicOrg?.ready?.then(() => { if (readMachine() !== machine) onOrgSwitch(); });
// The banner hides on the system dashboard, gives way to the organization page's own down banner,
// and shows on the organization's other pages, so a move across those lines redraws it. Other moves
// inside one organization read nothing (the switch path reads its own).
let busPlace = null;
window.addEventListener('hashchange', () => {
if (!window.MosaicOrg) return;
const path = window.MosaicOrg.route().split('?')[0], now = ['/dashboard', '/organization'].includes(path) ? path : 'page';
if (now !== busPlace) { busPlace = now; busDown(); }
});
$('refresh').onclick = refresh;
$('mobile-pause').onclick = () => $('pause').click();
$('pause').onclick = () => { paused = !paused; $('pause').querySelector('span').textContent = paused ? 'Resume' : 'Pause'; $('pause').setAttribute('aria-label', paused ? 'Resume' : 'Pause'); $('pause').title = paused ? 'Resume' : 'Pause'; $('mobile-pause').textContent = paused ? 'Resume' : 'Pause'; $('pause').setAttribute('aria-pressed', String(paused)); schedule(); if (data) render(); };
+88
View File
@@ -0,0 +1,88 @@
/* #1873 SP6: the Assistant page (r2-13). A bar with the page heading and "Open thread", then up to
three thread panes as cards side by side, each with its own header (title, organization and
project chips, close), its own scroll and its own composer. One pane and a tab strip on a phone.
Loaded after shell.css and chat.css; every rule is scoped to the Assistant page. */
html[data-organizations] .assist{display:flex;flex-direction:column;gap:10px;min-width:0}
html[data-organizations] .assist-bar{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap}
html[data-organizations] .assist-vh{flex:1 1 320px;min-width:0}
html[data-organizations] .assist-vh h1{margin:0}
html[data-organizations] .assist-vh h1:focus{outline:none}
html[data-organizations] .assist-vh .sub{margin:4px 0 0;color:var(--muted);font-size:14px}
html[data-organizations] .assist-tools{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
html[data-organizations] .assist-open{min-width:220px;max-width:100%;font:500 14px/1.4 var(--font);color:var(--text);background:var(--surface);border:1px solid var(--line);border-radius:var(--r);padding:6px 8px}
html[data-organizations] .assist-open:disabled{color:var(--muted);cursor:not-allowed}
html[data-organizations] .assist [data-assist-unread]:empty,html[data-organizations] .assist [data-assist-note]:empty{display:none}
html[data-organizations] .assist [data-assist-unread] .note{margin:0}
html[data-organizations] .assist [data-assist-note]{margin:0;font-size:13px;color:var(--muted)}
html[data-organizations] .assist [data-assist-note][data-refused]{color:var(--warning);font-weight:600}
html[data-organizations] .assist-new{border:1px solid var(--line);border-radius:var(--r);background:var(--surface);padding:12px 14px;display:grid;gap:10px}
html[data-organizations] .assist-new[hidden]{display:none}
html[data-organizations] .assist-new h2{margin:0;font-size:16px}
html[data-organizations] .assist-new h2:focus{outline:none}
html[data-organizations] .assist-new-fields{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:10px}
html[data-organizations] .assist-new-fields label{display:grid;gap:4px;font-size:13px;color:var(--muted);min-width:0}
html[data-organizations] .assist-new-fields select,html[data-organizations] .assist-new-fields input{font:500 14px/1.4 var(--font);color:var(--text);background:var(--canvas);border:1px solid var(--line);border-radius:var(--r);padding:6px 8px;min-width:0}
html[data-organizations] .assist-new-actions{display:flex;gap:8px;flex-wrap:wrap}
html[data-organizations] .assist-new .ws-btn.primary{background:var(--action);color:var(--onAction);border-color:var(--action)}
html[data-organizations] .assist-new .ws-btn.primary:hover:not(:disabled){background:color-mix(in srgb,var(--action) 88%,var(--strong))}
html[data-organizations] .assist-new [data-assist-new-status]{margin:0;font-size:13px}
html[data-organizations] .assist-new [data-assist-new-status]:empty{display:none}
html[data-organizations] .assist-tabs{display:none;margin-left:0;max-width:100%;flex-wrap:wrap}
html[data-organizations] .assist-tabs>button{max-width:60vw;overflow:hidden;text-overflow:ellipsis;min-height:32px;padding:2px 10px}
html[data-organizations] .assist-panes{display:grid;grid-template-columns:repeat(var(--assist-n,1),minmax(0,1fr));gap:12px;min-height:0}
html[data-organizations] .assist-panes[hidden]{display:none}
html[data-organizations] .assist-pane{display:flex;flex-direction:column;min-width:0;min-height:0;border:1px solid var(--line);border-radius:var(--r);background:var(--surface);overflow:hidden}
html[data-organizations] .assist-pane-h{display:flex;align-items:center;gap:8px;padding:10px 12px;border-bottom:1px solid var(--line);box-shadow:inset 0 3px 0 var(--org,var(--line));min-width:0;flex-wrap:wrap}
html[data-organizations] .assist-pane-h h2{margin:0;font-size:15px;font-weight:700;color:var(--strong,var(--text));overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:5em;flex:1 1 0}
html[data-organizations] .assist-pane-h h2:focus{outline:none}
html[data-organizations] .assist-chips{display:inline-flex;gap:6px;flex-wrap:wrap;min-width:0;order:1;flex:1 0 100%}
html[data-organizations] .assist-chips:empty{display:none}
/* SP7: a pane's tools (Full view, Messages, close) stay together on the title's row; the chips take the row under it.
A pane too narrow for them wraps the tools, never pushes one past the pane's edge. */
html[data-organizations] .assist-pane-tools{display:inline-flex;align-items:center;justify-content:flex-end;gap:2px;flex:0 1 auto;flex-wrap:wrap;max-width:100%;margin-left:auto}
html[data-organizations] .assist-chips .ws-chip{max-width:100%;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
html[data-organizations] .assist .pane-tool{display:inline-grid;place-items:center;width:28px;height:28px;border-radius:var(--r);color:var(--muted);border:0;background:none;padding:0;min-height:0;cursor:pointer;flex:none}
html[data-organizations] .assist .pane-tool:hover{background:var(--raised);color:var(--text)}
/* SP7: each pane's own organization's Messages page, a text link among the pane's tools. */
html[data-organizations] .assist .pane-tool.assist-msgs{width:auto;padding:0 8px;font-size:12px;font-weight:600;text-decoration:none}
/* SP7: "Resume assistant" under a pane's composer is a small secondary control, not a second primary button. */
html[data-organizations] .assist-body .btn.pane-resume{align-self:flex-start;min-height:0;padding:2px 8px;margin-top:4px;font-size:12px;font-weight:500;background:none;border-color:transparent;color:var(--muted)}
html[data-organizations] .assist-body .btn.pane-resume:hover:not(:disabled){background:var(--raised);color:var(--text)}
html[data-organizations] .assist .pane-tool svg.i{width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
html[data-organizations] .assist-line{margin:0;padding:6px 12px;border-bottom:1px solid var(--line);font-size:13px;color:var(--text);background:color-mix(in srgb,var(--warn,#b7791f) 12%,var(--surface))}
html[data-organizations] .assist-line[hidden]{display:none}
html[data-organizations] .assist-body{flex:1;min-height:0;overflow:auto;padding:12px;display:flex;flex-direction:column}
/* The chat thread view in a pane: the log scrolls, the composer stays at the foot of the card.
Messages read as the project conversation's bubbles (projects.css scopes those to .project-chat,
whose page-level layout a pane must not take), sized for a third of the screen. */
html[data-organizations] .assist-body .chat-log{flex:1 1 0;min-height:120px;max-height:none;overflow:auto;margin:8px 0 0;padding:0;border:0}
html[data-organizations] .assist-body .chat-log>li{border:0;display:flex;flex-direction:column;align-items:flex-start;gap:4px;padding-block:6px}
html[data-organizations] .assist-body .chat-log>li.chat-message-human{align-items:flex-end}
html[data-organizations] .assist-body .chat-log>li>.chat-body{background:var(--raised);border:1px solid var(--line);border-radius:12px;padding:8px 12px;max-width:100%;box-sizing:border-box;overflow-wrap:anywhere}
html[data-organizations] .assist-body .chat-log>li.chat-message-human>.chat-body{background:var(--accent-fill);color:var(--on-accent);border-color:transparent}
html[data-organizations] .assist-body .chat-message-meta{display:flex;align-items:center;gap:6px;opacity:1;font-size:12px;color:var(--muted)}
html[data-organizations] .assist-body .chat-message-meta strong{color:var(--text);font-weight:600}
html[data-organizations] .assist-body .chat-avatar{display:grid;place-items:center;flex:none;width:24px;height:24px;border-radius:50%;background:var(--raised);color:var(--action);font-weight:700;font-size:12px}
html[data-organizations] .assist-body .chat-message-human .chat-avatar{background:var(--accent-fill);color:var(--on-accent)}
html[data-organizations] .assist-body>.chat-area{max-width:none;margin:0;flex:1 1 auto;min-height:0;display:flex;flex-direction:column}
html[data-organizations] .assist-body .chat-conversation{flex:1 1 auto;min-height:0;display:flex;flex-direction:column}
html[data-organizations] .assist-body .chat-conversation>p.small{margin:0;font-size:12px}
html[data-organizations] .assist-body form{margin-top:auto;padding-top:10px}
html[data-organizations] .assist-body .chat-conversation>button,html[data-organizations] .assist-body form>button{align-self:flex-start;justify-self:start;width:auto}
html[data-organizations] .assist-body textarea{width:100%;box-sizing:border-box;min-height:56px;height:56px}
html[data-organizations] .assist-empty{margin:24px 0;color:var(--muted)}
html[data-organizations] .assist-empty[hidden]{display:none}
@media (max-width:760px){
html[data-organizations] .assist-tabs:not([hidden]){display:inline-flex}
html[data-organizations] .assist-panes{grid-template-columns:minmax(0,1fr);height:auto}
html[data-organizations] .assist-pane.alt{display:none}
html[data-organizations] .assist-body{overflow:visible}
html[data-organizations] .assist-body .chat-log{flex:none;min-height:0;overflow:visible}
html[data-organizations] .assist-open{flex:1 1 100%;min-width:0}
html[data-organizations] .assist-tools{flex:1 1 100%}
html[data-organizations] .assist-new-fields{grid-template-columns:minmax(0,1fr)}
}
+517
View File
@@ -0,0 +1,517 @@
// #1873 SP6: the Assistant page (#/assistant), one system page with no organization prefix. Up to
// three chat threads, from any organization on the list, open next to each other. Each pane is the
// chat thread view (chat.js) in its own instance pinned to the pane's organization, so its reads and
// its sends name that organization in the address whichever organization the page opened last.
// A phone shows one pane at a time with a tab strip.
//
// The open set, its order and the phone's shown pane live in the address
// (#/assistant?open=<org>:<thread>,…&show=<org>:<thread>), checked before use and rewritten with
// replaceState. A bare #/assistant opens the set this browser had last.
//
// SP7: a plain click on a thread link anywhere in the Console (a project's conversation rows, the
// sidebar's thread links) opens that thread as a pane here, added to the open set; #/assistant?add=<org>:<thread>
// carries it across the page change. A link marked data-full-view (a pane's Full view, a requirement's
// "Open conversation") and a per-organization chat address typed or pasted open that organization's own chat view.
(() => {
'use strict';
if (!document.documentElement.hasAttribute('data-organizations')) return;
const data = window.MosaicWorkspaceData, ws = () => window.MosaicWorkspace;
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const enc = encodeURIComponent;
const MAX = 3, POLL = 10000, LIST_TTL = 3000, INFO_TTL = 30000, STORE = 'mosaic-assistant-open-v1';
const ORG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const paused = () => document.getElementById('pause')?.getAttribute('aria-pressed') === 'true';
const load = () => { try { return localStorage.getItem(STORE); } catch { return null; } };
const save = value => { try { localStorage.setItem(STORE, value); } catch {} };
const svg = d => `<svg class="i sm" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${d}</svg>`;
const CLOSE = svg('<path d="M6 6l12 12M18 6 6 18"/>');
const setHtml = (el, html) => { if (el && el.innerHTML !== html) el.innerHTML = html; };
const setText = (el, text) => { if (el && el.textContent !== text) el.textContent = text; };
const rowsOf = body => (Array.isArray(body?.rows) ? body.rows : null);
// "<org>:<thread>,…" from the address: valid selectors only, each once, at most three.
function parse(query) {
const q = new URLSearchParams(query || ''), keys = [];
for (const part of (q.get('open') || '').split(',')) {
const cut = part.indexOf(':');
if (cut < 1) continue;
const org = part.slice(0, cut), id = part.slice(cut + 1).toLowerCase();
if (!ORG.test(org) || !UUID.test(id)) continue;
const key = `${org}:${id}`;
if (!keys.includes(key) && keys.length < MAX) keys.push(key);
}
const want = q.get('show') || '', at = want.indexOf(':');
const show = at > 0 ? `${want.slice(0, at)}:${want.slice(at + 1).toLowerCase()}` : null;
return { keys, show: keys.includes(show) ? show : null, named: q.has('open') };
}
const split = key => { const cut = key.indexOf(':'); return { org: key.slice(0, cut), id: key.slice(cut + 1) }; };
// ---------- reads ----------
// The organization list, and per organization its threads, projects and whether this Console may
// send there (its config's chatSend). An organization whose bus is down is not read.
let listAt = 0, listPromise = null;
const infos = new Map();
function orgList(fresh = false) {
if (!listPromise || fresh || Date.now() - listAt > LIST_TTL) {
listAt = Date.now();
listPromise = Promise.all([data.organizations(), ws()?.themes?.()]).then(([rows]) => (Array.isArray(rows) ? rows : null)).catch(() => null);
}
return listPromise;
}
const readConfig = org => fetch(`/api/orgs/${enc(org)}/config`, { cache: 'no-store', redirect: 'manual' })
.then(r => (r.ok ? r.json() : null)).then(c => c?.chatSend === true).catch(() => false);
function info(org, fresh = false) {
if (!org || org.invalid || org.busHealthy === false) return Promise.resolve({ threads: null, projects: null, chatSend: false, read: false });
const hit = infos.get(org.id);
if (hit && !fresh && Date.now() - hit.at < INFO_TTL) return hit.promise;
const promise = Promise.all([
data.threads(org.id).then(rowsOf).catch(() => null),
data.projects(org.id).then(rowsOf).catch(() => null),
readConfig(org.id),
]).then(([threads, projects, chatSend]) => ({
threads: threads && threads.filter(t => t && !t.shared && typeof t.id === 'string' && UUID.test(t.id)),
projects: projects && projects.filter(p => p && typeof p.id === 'string'),
chatSend, read: true,
}));
infos.set(org.id, { at: Date.now(), promise });
return promise;
}
// The rows ws().orgsOf reads: an organization not ok is named at the top of the page.
function orgRows(list, got) {
return list.map(o => {
const why = o.invalid ? ['invalid', o.reason || ''] : o.busHealthy === false ? ['down', ws().state(o)[2]] : got.get(o.id)?.threads === null ? ['timeout', 'the thread list did not answer'] : ['ok', ''];
return { org: o.id, label: o.label, theme: o.theme, state: why[0], reason: why[1] };
});
}
// ---------- state ----------
let mounted = null; // { root, panes: [pane], show, turn, timer, list, got, o, form }
let mountGen = 0, paneSeq = 0;
function writeUrl() {
if (!mounted) return;
const keys = mounted.panes.map(p => p.key);
const qs = keys.length ? `open=${keys.join(',')}${mounted.show && mounted.show !== keys[0] ? `&show=${mounted.show}` : ''}` : '';
save(keys.join(','));
const next = qs ? `#/assistant?${qs}` : '#/assistant';
if (location.hash !== next) history.replaceState(null, '', next);
}
// ---------- markup ----------
function frame() {
return `<section class="assist" data-assistant aria-labelledby="assist-title">
<div class="assist-bar">
<div class="assist-vh"><h1 id="assist-title" tabindex="-1">Assistant</h1>
<p class="sub">Threads from any organization, side by side. Each pane reads and sends through its own organization.</p></div>
<div class="assist-tools">
<label class="ws-sr" for="assist-open">Open thread</label>
<select id="assist-open" class="assist-open" data-assist-open><option value="">Open thread…</option></select>
</div>
</div>
<div data-assist-unread></div>
<p class="note" data-assist-note role="status"></p>
<form class="assist-new" data-assist-new hidden aria-labelledby="assist-new-title">
<h2 id="assist-new-title" tabindex="-1">New thread in <span data-assist-new-org></span></h2>
<div class="assist-new-fields">
<label><span>Project</span><select name="project" required></select></label>
<label><span>Agent</span><select name="instance" required></select></label>
<label><span>Name</span><input name="name" required maxlength="200" autocomplete="off"></label>
</div>
<div class="assist-new-actions"><button class="ws-btn primary" type="submit">Start thread</button><button class="ws-btn" type="button" data-assist-new-cancel>Cancel</button></div>
<p class="note" data-assist-new-status role="status"></p>
</form>
<div class="ws-seg assist-tabs" role="group" aria-label="Shown thread" data-assist-tabs></div>
<div class="assist-panes" data-assist-panes></div>
<p class="assist-empty" data-assist-empty hidden>No thread is open. Choose one under Open thread.</p>
</section>`;
}
function paneShell(p) {
const n = p.n;
return `<section class="assist-pane ws-o" data-assist-pane="${esc(p.key)}" id="assist-p${n}" aria-labelledby="assist-p${n}-title">
<div class="assist-pane-h">
<h2 id="assist-p${n}-title" data-assist-title>Reading…</h2>
<span class="assist-chips" data-assist-chips></span>
<span class="assist-pane-tools">
<a class="pane-tool assist-msgs" data-assist-pane-full data-full-view href="#/orgs/${enc(p.org)}/projects/threads/${enc(p.id)}">Full view</a>
<a class="pane-tool assist-msgs" data-assist-pane-messages href="#/orgs/${enc(p.org)}/messages" aria-label="Messages in ${esc(p.org)}">Messages</a>
<button type="button" class="pane-tool" data-assist-close aria-label="Close thread">${CLOSE}</button>
</span>
</div>
<p class="assist-line" data-assist-line role="status" hidden></p>
<div class="assist-body" data-assist-body></div>
</section>`;
}
const els = p => ({
title: p.el.querySelector('[data-assist-title]'), chips: p.el.querySelector('[data-assist-chips]'),
close: p.el.querySelector('[data-assist-close]'), full: p.el.querySelector('[data-assist-pane-full]'), messages: p.el.querySelector('[data-assist-pane-messages]'), line: p.el.querySelector('[data-assist-line]'), body: p.el.querySelector('[data-assist-body]'),
});
// The picker: every organization on the list, its threads, and "New thread in …" where this
// Console may send. A stopped, invalid or silent organization is named and offers nothing.
function pickerHtml(list, got) {
const open = new Set(mounted.panes.map(p => p.key));
const groups = (list || []).filter(o => o && typeof o.id === 'string' && ORG.test(o.id)).map(o => {
const name = ws().label(o), i = got.get(o.id);
if (o.invalid) return `<optgroup label="${esc(name)} · invalid"><option disabled value="">Organization invalid</option></optgroup>`;
if (o.busHealthy === false) return `<optgroup label="${esc(name)} · ${esc(ws().state(o)[2])}"><option disabled value="">No threads while its bus is down</option></optgroup>`;
if (!i?.threads) return `<optgroup label="${esc(name)} · not answering"><option disabled value="">Threads unavailable</option></optgroup>`;
const project = id => i.projects?.find(p => p.id === id)?.name;
const rows = i.threads.map(t => {
const key = `${o.id}:${t.id.toLowerCase()}`, where = project(t.project);
return `<option value="${esc(key)}"${open.has(key) ? ' disabled' : ''}>${esc(t.name || t.id)}${where ? ` · ${esc(where)}` : ''}${open.has(key) ? ' (open)' : ''}</option>`;
}).join('');
const fresh = i.chatSend ? `<option value="new:${esc(o.id)}">New thread in ${esc(name)}…</option>` : '';
return `<optgroup label="${esc(name)}">${rows || (fresh ? '' : '<option disabled value="">No threads</option>')}${fresh}</optgroup>`;
});
return `<option value="">Open thread…</option>${groups.join('')}`;
}
// ---------- drawing ----------
async function draw({ fresh = false, navigated = false } = {}) {
if (!mounted) return;
const gen = mountGen, turn = ++mounted.turn;
const live = () => mounted && gen === mountGen && turn === mounted.turn;
clearTimeout(mounted.timer);
const list = await orgList(fresh);
if (!live()) return;
const openOrgs = new Set(mounted.panes.map(p => p.org));
const valid = (list || []).filter(o => o && typeof o.id === 'string' && ORG.test(o.id));
const got = new Map(await Promise.all(valid.map(async o => [o.id, await info(o, fresh || (!navigated && openOrgs.has(o.id)))])));
if (!live()) return;
mounted.list = list; mounted.got = got;
mounted.o = ws().orgsOf({ orgs: orgRows(valid, got) });
paintTop();
for (const p of mounted.panes) drawPane(p);
paintTabs(); layout();
mounted.timer = setTimeout(tick, POLL);
}
function tick() {
if (!mounted) return;
if (paused()) { mounted.timer = setTimeout(tick, POLL); return; }
void draw();
}
// The line under the lead: how many panes are open, or why a thread was not opened (drawn as a warning).
function paintNote() {
const el = mounted.root.querySelector('[data-assist-note]');
setText(el, mounted.notice || (mounted.panes.length ? `${mounted.panes.length} open, up to ${MAX}` : ''));
el?.toggleAttribute('data-refused', !!mounted.notice);
}
function paintTop() {
const { root, list, o, panes } = mounted;
setHtml(root.querySelector('[data-assist-unread]'), list ? ws().unreadNote(o, [], 'assistant') : '<p class="note ws-unread-note">The organization list could not be read. Open panes only read.</p>');
paintNote();
const pick = root.querySelector('[data-assist-open]');
if (document.activeElement !== pick) { setHtml(pick, pickerHtml(list, mounted.got)); pick.value = ''; }
const full = panes.length >= MAX;
pick.disabled = full;
pick.title = full ? `${MAX} threads are open. Close one to open another.` : '';
root.querySelector('[data-assist-empty]').hidden = panes.length > 0;
}
function drawPane(p) {
if (!mounted || !p.el.isConnected) return;
const { list, got, o } = mounted, e = els(p);
const org = list?.find(x => x?.id === p.org) || null, i = got.get(p.org);
const name = org ? ws().label(org) : p.org;
const thread = i?.threads?.find(t => t.id.toLowerCase() === p.id) || null;
const title = thread?.name || `Thread ${p.id.slice(0, 8)}`;
p.title = title;
setText(e.title, title);
e.close.setAttribute('aria-label', `Close ${title}, ${name}`);
e.full.setAttribute('aria-label', `Full view of ${title}, ${name}`);
e.messages.setAttribute('aria-label', `Messages in ${name}`);
if (org) p.el.setAttribute('style', ws().colours(org)); else p.el.removeAttribute('style');
const project = thread && i.projects?.find(x => x.id === thread.project)?.name;
setHtml(e.chips, `${ws().orgChip(o, p.org)}${ws().projChip(project || '')}`);
let line = '', readable = true, why = 'Nothing is read for this thread.', back = false;
if (!list) line = 'The organization list could not be read, so sending is off here until it reads again.';
else if (!org) { line = `${p.org} is not on your organization list.`; readable = false; }
else if (org.invalid) { line = `${name}: organization invalid. Fix its file under Settings, Organizations.`; readable = false; }
else if (org.busHealthy === false) {
const how = org.busStopped ? 'stopped' : 'unavailable';
line = `${name}: bus is ${how}. This pane cannot read or send until it starts again; the other panes are not affected.`;
why = `Nothing is read for this thread while ${name}'s bus is ${how}.`; readable = false; back = true;
}
else if (i?.threads && !thread) line = `This thread is not in ${name}'s thread list.`;
// A held message the last render had no composer for stays in the line between polls, so the
// status line neither flickers nor is announced again on every read.
const withHeld = () => {
const cps = [...p.draft.replace(/\s+/g, ' ').trim()];
return `${line ? `${line} ` : ''}Your unsent message is kept until this thread can send: “${cps.length > 200 ? `${cps.slice(0, 200).join('')}…` : cps.join('')}”`;
};
const shown = readable && p.held && p.draft ? withHeld() : line;
setText(e.line, shown); e.line.hidden = !shown;
if (!readable) {
p.held = false;
// An unsent message outlives the chat view: it is held on the pane and put back when the
// thread reads again.
const typed = p.chat && e.body.querySelector('form textarea')?.value;
if (typed?.trim()) p.draft = typed;
p.chat?.dispose(); p.chat = null;
const kept = !p.draft ? '' : back ? ' Your unsent message is kept and comes back here when it reads again.' : ' Your unsent message is kept while this pane stays open.';
setHtml(e.body, `<p class="ws-line">${esc(why)}${kept}</p>`);
return;
}
if (!p.chat) { p.chat = window.MosaicChat.pane(p.org); p.first = true; }
const first = p.first, chat = p.chat, seq = ++p.seq; p.first = false;
void chat.render({ path: `/chat/threads/${p.id}`, container: e.body, canSend: !!list && i?.chatSend === true, navigated: first }).then(() => {
// Only the latest render of this pane decides: an earlier one that a newer render cut short
// has no composer yet and must not claim the thread cannot send.
if (seq !== p.seq || p.chat !== chat || !p.el.isConnected) return;
const field = p.draft ? e.body.querySelector('form textarea') : null;
if (p.draft && !field) {
// The thread reads but this render drew no composer (it cannot send now): the held message is
// quoted in the pane's status line until a composer is back to take it.
p.held = true; const text = withHeld(); setText(e.line, text); e.line.hidden = false;
return;
}
// Put the held message back only into an empty composer; text typed meanwhile is never overwritten.
if (field && !field.value) { field.value = p.draft; field.dispatchEvent(new Event('input', { bubbles: true })); }
if (field && field.value === p.draft) p.draft = '';
if (p.held && (field || !p.draft)) { p.held = false; setText(e.line, line); e.line.hidden = !line; }
}, () => {});
}
function paintTabs() {
const { root, panes, show } = mounted;
const tabs = root.querySelector('[data-assist-tabs]');
const focused = tabs.contains(document.activeElement) ? document.activeElement.dataset.assistShow : null;
const html = panes.map(p => `<button type="button" data-assist-show="${esc(p.key)}" aria-pressed="${show === p.key}" aria-controls="assist-p${p.n}">${esc(p.title || 'Reading…')}</button>`).join('');
if (tabs.innerHTML !== html) { tabs.innerHTML = html; if (focused) tabs.querySelector(`[data-assist-show="${CSS.escape(focused)}"]`)?.focus({ preventScroll: true }); }
tabs.hidden = panes.length < 2;
}
function layout() {
const { root, panes, show } = mounted;
const box = root.querySelector('[data-assist-panes]');
box.style.setProperty('--assist-n', String(Math.max(1, panes.length)));
box.hidden = !panes.length;
for (const p of panes) p.el.classList.toggle('alt', show !== p.key);
fit();
}
// Wide screens: the panes fill the window below the bar and each scrolls on its own.
const wide = window.matchMedia('(min-width: 761px)');
function fit() {
if (!mounted) return;
const box = mounted.root.querySelector('[data-assist-panes]');
if (!wide.matches) { box.style.height = ''; return; }
const foot = document.querySelector('body > .foot, .foot')?.getBoundingClientRect().height || 0;
const top = box.getBoundingClientRect().top;
box.style.height = `${Math.max(360, Math.floor(window.innerHeight - Math.max(top, 0) - foot - 16))}px`;
}
// ---------- panes ----------
function makePane(key) {
const { org, id } = split(key);
const p = { key, org, id, n: ++paneSeq, el: null, chat: null, first: true, title: null, draft: '', held: false, seq: 0 };
const box = mounted.root.querySelector('[data-assist-panes]');
box.insertAdjacentHTML('beforeend', paneShell(p));
p.el = box.lastElementChild;
return p;
}
function addPane(key, { focus = false } = {}) {
if (!mounted) return;
const had = mounted.panes.find(p => p.key === key);
if (had) { mounted.show = key; paintTabs(); layout(); writeUrl(); return; }
if (mounted.panes.length >= MAX) return;
const p = makePane(key);
mounted.panes.push(p); mounted.show = key;
writeUrl();
if (mounted.got) { paintTop(); drawPane(p); paintTabs(); layout(); }
if (focus) els(p).title.setAttribute('tabindex', '-1'), els(p).title.focus({ preventScroll: true });
}
// SP7: a thread opened from a link takes a free slot or, with all three taken, the place of the
// first pane that holds no unsent message. When every pane holds one, nothing is replaced.
const holds = p => !!p.draft.trim() || !!p.chat?.hasDraft();
function place(key) {
const had = mounted.panes.find(p => p.key === key);
if (had) return had;
if (mounted.panes.length < MAX) { const p = makePane(key); mounted.panes.push(p); return p; }
const old = mounted.panes.find(p => !holds(p));
if (!old) return null;
const p = makePane(key);
old.chat?.dispose(); old.chat = null; old.el.replaceWith(p.el);
mounted.panes[mounted.panes.indexOf(old)] = p;
return p;
}
const REFUSED = `That thread was not opened: all ${MAX} panes hold an unsent message. Send or clear one, or close a pane, then open the thread again.`;
function add(key) {
if (!mounted) return false;
const p = place(key);
if (!p) { mounted.notice = REFUSED; paintNote(); return false; }
mounted.notice = ''; mounted.show = key;
writeUrl();
if (mounted.got) { paintTop(); drawPane(p); paintTabs(); layout(); }
els(p).title.setAttribute('tabindex', '-1'); els(p).title.focus({ preventScroll: true });
return true;
}
const addOf = query => { const v = new URLSearchParams(query || '').get('add'); return v ? parse(new URLSearchParams({ open: v }).toString()).keys[0] || null : null; };
const THREAD_LINK = /^#\/(?:orgs\/([^/?#]+)\/)?(?:projects|chat)\/threads\/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})$/i;
document.addEventListener('click', e => {
if (e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const a = e.target.closest?.('a[href]');
// A link marked data-full-view (a pane's Full view, a requirement's "Open conversation") goes to the
// organization's own thread view, which has Request details, sessions and sharing.
if (!a || a.hasAttribute('download') || a.hasAttribute('data-full-view') || (a.target && a.target !== '_self')) return;
const m = THREAD_LINK.exec(a.getAttribute('href') || '');
const org = m && (m[1] || window.MosaicOrg?.id);
if (!m || !org || !ORG.test(org)) return;
e.preventDefault();
const key = `${org}:${m[2].toLowerCase()}`;
if (mounted && /^#\/assistant(?:\?|$)/.test(location.hash)) add(key);
else location.hash = `#/assistant?add=${key}`;
});
function closePane(p) {
if (!mounted || !p) return;
const at = mounted.panes.indexOf(p);
if (at < 0) return;
mounted.notice = '';
p.chat?.dispose(); p.chat = null; p.el.remove();
mounted.panes.splice(at, 1);
const next = mounted.panes[Math.min(at, mounted.panes.length - 1)];
if (mounted.show === p.key) mounted.show = next?.key ?? null;
writeUrl(); paintTop(); paintTabs(); layout();
// The close button just left the page: focus the next pane's close control, or the picker.
(next ? els(next).close : mounted.root.querySelector('[data-assist-open]')).focus({ preventScroll: true });
}
// ---------- a new thread ----------
async function openForm(orgId) {
if (!mounted) return;
const org = mounted.list?.find(o => o?.id === orgId);
if (!org || org.busHealthy === false || mounted.got.get(orgId)?.chatSend !== true) return;
const f = mounted.root.querySelector('[data-assist-new]'), formTurn = ++mounted.formTurn;
mounted.form = { org: orgId, busy: false };
f.hidden = false; f.reset();
setText(f.querySelector('[data-assist-new-org]'), ws().label(org));
setText(f.querySelector('[data-assist-new-status]'), 'Reading projects and agents…');
const project = f.elements.project, instance = f.elements.instance;
project.innerHTML = ''; instance.innerHTML = ''; project.disabled = true; instance.disabled = true;
f.querySelector('h2').focus({ preventScroll: true });
const [i, agents] = await Promise.all([
info(org, true),
fetch(`/api/orgs/${enc(orgId)}/chat/instances`, { cache: 'no-store', redirect: 'manual' }).then(r => (r.ok ? r.json() : null)).then(rowsOf).catch(() => null),
]);
if (!mounted || mounted.formTurn !== formTurn || f.hidden) return;
const projects = (i.projects || []).filter(p => !p.archived);
project.innerHTML = projects.map(p => `<option value="${esc(p.id)}">${esc(p.name || p.id)}</option>`).join('');
instance.innerHTML = (agents || []).filter(a => a && typeof a.instance === 'string').map(a => `<option value="${esc(a.instance)}">${esc(a.name || a.instance)}</option>`).join('');
project.disabled = !projects.length; instance.disabled = !agents?.length;
const missing = [i.projects === null ? 'Projects could not be read.' : !projects.length ? 'This organization has no open project.' : '', agents === null ? 'Agents could not be read.' : !agents.length ? 'No agent takes threads here.' : ''].filter(Boolean).join(' ');
setText(f.querySelector('[data-assist-new-status]'), missing);
}
function closeForm() {
if (!mounted) return;
mounted.form = null; mounted.formTurn++;
mounted.root.querySelector('[data-assist-new]').hidden = true;
}
async function submitForm(f) {
const form = mounted?.form;
if (!form || form.busy) return;
const status = f.querySelector('[data-assist-new-status]');
const body = { project: f.elements.project.value, name: f.elements.name.value.trim(), instance: f.elements.instance.value };
if (!body.project || !body.instance || !body.name) { setText(status, 'Choose a project and an agent, and name the thread.'); return; }
form.busy = true;
const submit = f.querySelector('[type=submit]'); submit.disabled = true;
setText(status, 'Starting the thread…');
let result = null, why = '';
try {
const r = await fetch(`/api/orgs/${enc(form.org)}/chat/threads`, { method: 'POST', cache: 'no-store', redirect: 'manual', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
const v = await r.json().catch(() => null);
if (r.ok && typeof v?.id === 'string' && UUID.test(v.id)) result = v.id.toLowerCase();
else why = r.type === 'opaqueredirect' || r.status === 401 ? 'You are signed out. Reload the page to sign in again.' : `The thread was not started${typeof v?.error === 'string' ? ` (${v.error})` : ''}.`;
} catch { why = 'Outcome unknown. Look under Open thread before trying again.'; }
if (mounted?.form !== form) return;
form.busy = false; submit.disabled = false;
if (!result) { setText(status, why); return; }
infos.delete(form.org);
const key = `${form.org}:${result}`;
if (mounted.panes.length >= MAX && !mounted.panes.some(p => p.key === key)) { setText(status, `Started. ${MAX} threads are open; close one to open it.`); return; }
closeForm();
addPane(key, { focus: true });
void draw({ fresh: false });
}
// ---------- events (bound once to the mount root) ----------
function bind(root) {
root.addEventListener('change', e => {
const pick = e.target.closest?.('[data-assist-open]');
if (!pick || !mounted) return;
const value = pick.value;
pick.value = '';
if (value.startsWith('new:')) { void openForm(value.slice(4)); return; }
const want = parse(`open=${value}`).keys[0];
if (want) { mounted.notice = ''; addPane(want); }
});
root.addEventListener('click', e => {
if (!mounted) return;
const show = e.target.closest?.('[data-assist-show]');
if (show) { const p = mounted.panes.find(x => x.key === show.dataset.assistShow); if (p) { mounted.show = p.key; paintTabs(); layout(); writeUrl(); } return; }
const close = e.target.closest?.('[data-assist-close]');
if (close) { closePane(mounted.panes.find(x => x.el.contains(close))); return; }
if (e.target.closest?.('[data-assist-new-cancel]')) { closeForm(); root.querySelector('[data-assist-open]').focus({ preventScroll: true }); }
});
root.addEventListener('submit', e => {
const f = e.target.closest?.('[data-assist-new]');
if (!f) return;
e.preventDefault();
void submitForm(f);
});
}
// ---------- public ----------
async function mount(container, query, { navigated = false } = {}) {
unmount();
++mountGen;
container.innerHTML = frame();
const root = container.querySelector('[data-assistant]');
mounted = { root, panes: [], show: null, turn: 0, timer: null, list: null, got: null, o: null, form: null, formTurn: 0, notice: '' };
bind(root);
window.addEventListener('resize', fit);
document.title = 'Assistant · Mosaic Console';
let want = parse(query);
if (!want.named) want = parse(`open=${load() || ''}`);
for (const key of want.keys) mounted.panes.push(makePane(key));
mounted.show = want.show || want.keys[0] || null;
// A thread link followed from another page: a fresh set holds no unsent message, so it always lands.
const extra = addOf(query), added = extra && place(extra);
if (added) mounted.show = extra;
if (added) { els(added).title.setAttribute('tabindex', '-1'); els(added).title.focus({ preventScroll: true }); }
else if (navigated) root.querySelector('h1').focus({ preventScroll: true });
writeUrl(); paintTabs(); layout();
root.querySelector('[data-assist-empty]').hidden = mounted.panes.length > 0;
await draw({ navigated: true });
}
function unmount() {
if (!mounted) return;
clearTimeout(mounted.timer);
for (const p of mounted.panes) p.chat?.dispose();
window.removeEventListener('resize', fit);
mounted = null; mountGen++;
}
// The Console's Refresh, and a redraw of the same page: every pane reads again now. A query that
// names a different open set (an address edited in place) opens that set.
function refresh(query) {
if (!mounted) return;
if (typeof query === 'string') {
const want = parse(query);
if (want.named && want.keys.join(',') !== mounted.panes.map(p => p.key).join(',')) {
for (const p of [...mounted.panes]) if (!want.keys.includes(p.key)) { p.chat?.dispose(); p.el.remove(); }
const kept = new Map(mounted.panes.map(p => [p.key, p]));
mounted.panes = want.keys.map(k => kept.get(k) || makePane(k));
const box = mounted.root.querySelector('[data-assist-panes]');
for (const p of mounted.panes) box.append(p.el);
mounted.show = want.show || want.keys[0] || null;
writeUrl();
}
const extra = addOf(query);
if (extra) add(extra);
}
infos.clear();
void draw({ fresh: true });
}
const hasDraft = () => !!mounted && mounted.panes.some(p => !!p.draft.trim() || !!p.chat?.hasDraft());
// A write that changed an organization reads it again.
document.addEventListener('mosaic-org-changed', e => { if (mounted && mounted.panes.some(p => p.org === e.detail?.org)) { infos.delete(e.detail.org); void draw(); } });
window.MosaicAssistant = Object.freeze({ mount, unmount, refresh, hasDraft, add });
})();
+19 -3
View File
@@ -181,11 +181,27 @@
menu.addEventListener('click', e => { if (e.target.closest('a')) close(); });
document.addEventListener('click', e => { if (!e.target.closest('.avatar-wrap')) close(); });
function breadcrumbs() {
const path = location.hash.slice(2).split('?')[0], parts = path.split('/').filter(Boolean), box = $('breadcrumbs');
draw();
// SP1: every page inside an organization says which one, after the dashboard: Dashboard / Acme / ...
const box = $('breadcrumbs'), org = /^#\/orgs\/[^/?]+/.test(location.hash) ? window.MosaicOrg : null;
if (box && org?.id && !box.querySelector('[data-crumb-org]') && !/^#\/orgs\/[^/?]+\/organization(?:[/?]|$)/.test(location.hash)) box.insertAdjacentHTML('afterbegin', `<a href="#/dashboard">Dashboard</a><span aria-hidden="true">/</span><a href="#/orgs/${encodeURIComponent(org.id)}/organization" data-crumb-org>${escape(org.label)}</a><span aria-hidden="true">/</span>`);
// SP7: a trail with nothing above the page only repeats the page's heading, so the heading names it once.
if (!box) return;
const heading = [...$('main').querySelectorAll('h1')].find(h => h.getClientRects().length)?.textContent.trim();
const echo = !box.querySelector('a') && !!heading && box.textContent.trim() === heading;
if (box.hidden !== echo) box.hidden = echo;
}
window.MosaicBreadcrumbs = breadcrumbs;
function draw() {
// SP1: an organization's pages are routes under #/orgs/<id>; the crumb reads the route inside it.
const path = location.hash.replace(/^#\/orgs\/[^/?]+/, '#').slice(2).split('?')[0], parts = path.split('/').filter(Boolean), box = $('breadcrumbs');
if (!box || !$('bus-view')) return;
if (window.MosaicProjects?.breadcrumb?.(box, $('bus-view'))) return;
if (!parts.length || parts[0] === 'board') { box.innerHTML = '<span aria-current="page">Dashboard</span>'; return; }
const names = {projects:'Projects',chat:'Projects',inbox:'Inbox',messages:'Messages',tasks:'Tasks',agents:'Agents',queue:'Queue',business:'Business',docs:'Docs',settings:'Settings'};
// Inside an organization the board is its control board; the system dashboard is the crumb before it.
if (parts[0] === 'board' && /^#\/orgs\//.test(location.hash)) { box.innerHTML = '<span aria-current="page">Control board</span>'; return; }
if (!parts.length || parts[0] === 'board' || parts[0] === 'dashboard') { box.innerHTML = '<span aria-current="page">Dashboard</span>'; return; }
if (parts[0] === 'organization') { const h = $('bus-view').querySelector('[data-org-dashboard] h1')?.textContent?.trim(); box.innerHTML = `<a href="#/dashboard">Dashboard</a>${h ? `<span aria-hidden="true">/</span><span aria-current="page">${escape(h)}</span>` : ''}`; return; }
const names = {projects:'Projects',chat:'Projects',inbox:'Inbox',messages:'Messages',assistant:'Assistant',tasks:'Tasks',agents:'Agents',queue:'Queue',business:'Business',docs:'Docs',settings:'Settings'};
if (parts[0] === 'settings' && parts[1] === 'business' && $('bus-view').querySelector('#settings-page-title')?.textContent.trim() === 'Business') { box.innerHTML = '<a href="#/settings">Settings</a><span aria-hidden="true">/</span><span aria-current="page">Business</span>'; return; }
const name = names[parts[0]] || 'Dashboard', heading = $('bus-view').querySelector('h1')?.textContent?.trim();
const project = $('bus-view').querySelector('.chat-conversation > p:first-child a, .chat-room > p:first-child a');
+258 -54
View File
@@ -75,13 +75,17 @@
window.MosaicIcons.succeeded();
return body;
}
// #1873 SP1: bumped by each in-place organization switch. A write, or a read that keeps its answer,
// captures it before its await and drops the answer when it changed, so nothing the old organization
// answered lands on the new page or in its kept answers.
let orgEpoch = 0;
// A reader for one render. `live` asks the server; otherwise only kept answers are used.
function reader(live) {
const used = [];
const get = async (verb, subject) => {
const k = subject === undefined ? verb : `${verb}:${subject}`;
let r;
if (live) { r = await fetchRead(verb, subject); last.set(k, r); }
if (live) { const epoch = orgEpoch; r = await fetchRead(verb, subject); if (epoch === orgEpoch) last.set(k, r); }
else if (!(r = last.get(k))) throw new ReadError('not-read', 'not read before');
used.push(r.at);
if (verb === 'messages') { messageCount = r.unread; return r; }
@@ -90,7 +94,7 @@
get.api = async path => {
const k = `api:${path}`;
let r;
if (live) { r = await fetchApi(path); last.set(k, r); }
if (live) { const epoch = orgEpoch; r = await fetchApi(path); if (epoch === orgEpoch) last.set(k, r); }
else if (!(r = last.get(k))) throw new ReadError('not-read', 'not read before');
used.push(r.at);
return r;
@@ -264,8 +268,8 @@
// ---------------------------------------------------------------- views
let inboxCount = null, messageCount = null;
// Organization mode (sample 01): Dashboard, Inbox, Tasks, Projects, Side by side, Agents and
// Assistant, with Settings pinned to the foot of the sidebar. Queue opens from the organization
// Organization mode (sample 01): Dashboard, Inbox, Tasks, Projects, Agents and Assistant (SP6:
// `#/assistant`, threads of any organization side by side), with Settings pinned to the foot of the sidebar. Queue opens from the organization
// dashboard and Docs from its Docs row, so neither is a sidebar item here.
function orgSections(route) {
const nav = $('console-nav');
@@ -275,9 +279,10 @@
const focused = $('sections').contains(active) || foot.contains(active) ? active.getAttribute('href') : null;
const icon = id => window.MosaicWorkspace?.icon?.(id) ?? `<svg class="i" aria-hidden="true"><use href="/icons.svg#i-${id}"/></svg>`;
const n = (count, what) => count > 0 ? `<span class="ws-n hot" aria-label="${count} ${what}">${count}</span>` : '';
const items = [['/', 'Dashboard', '', 'board'], ['/inbox', 'Inbox', n(inboxCount?.open, 'open for you'), 'inbox'], ['/tasks', 'Tasks', '', 'tasks'], ['/projects', 'Projects', '', 'folder'], ['/side-by-side', 'Side by side', '', 'columns'], ['/agents', 'Agents', '', 'agents'], ['/messages', 'Assistant', n(messageCount, 'unread messages'), 'talk']];
const items = [['/dashboard', 'Dashboard', '', 'board'], ['/inbox', 'Inbox', n(inboxCount?.open, 'open for you'), 'inbox'], ['/tasks', 'Tasks', '', 'tasks'], ['/projects', 'Projects', '', 'folder'], ['/agents', 'Agents', '', 'agents'], ['/assistant', 'Assistant', '', 'talk']];
const link = ([h, l, extra, id]) => {
const cur = h === '/' ? (route === '/' || route === '/board') : route.startsWith(h) || (h === '/projects' && route.startsWith('/chat')) || (h === '/tasks' && route.startsWith('/trail/task')) || (h === '/inbox' && (route.startsWith('/trail/decision') || route.startsWith('/trail/message')));
// #1873 SP1: the Dashboard item is the system dashboard, `#/dashboard`, outside any organization.
const cur = h === '/dashboard' ? (route === '/dashboard' || route === '/' || route === '/board') : route.startsWith(h) || (h === '/projects' && route.startsWith('/chat')) || (h === '/tasks' && route.startsWith('/trail/task')) || (h === '/inbox' && (route.startsWith('/trail/decision') || route.startsWith('/trail/message')));
return `<a href="#${h}" class="s1-section ws-nav"${cur ? ' aria-current="page"' : ''}>${icon(id)}<span class="t">${l}</span>${extra}</a>`;
};
// No project tree under Projects here: the sidebar's Projects group lists every organization's
@@ -342,6 +347,8 @@
});
let configRead = Promise.resolve();
// #1873 SP1: the config read an organization switch started, until the next render has waited for it.
let switchRead = null;
let canSend = false, canMessage = false, chatSend = false, sendRoles = null, sending = false, receipt = null, replies = [];
const REPLIES = 50; // the broker's cap
function repliesHtml() {
@@ -462,14 +469,86 @@
if(!templatesOnly && d.op!=='fire' && !template){hireStatus='Read and choose a role template first.';hireCode='';paintHireStart();return;}
const thinking=d.thinking?.trim(),hire={op:d.op,level:d.level,name:d.name,reason:d.reason,...(d.level==='project'?{project:d.project}:{}),...(d.op==='fire'?{}:{role:{template:template?.name,sha256:template?.sha256},route:{harness:d.harness,model:d.model,...(thinking?{thinking}:{})}})};
hireBusy=true;hireStatus='';hireCode='';paintHireStart();
const epoch=orgEpoch;
const {res,json}=await decidePost(`/api/decisions/hire/${templatesOnly?'templates':'start'}`,{business:hireOrg() ?? d.business,...(templatesOnly?{}:{hire})});
if(epoch!==orgEpoch){if(res?.type==='opaqueredirect')signOut();return;}
hireBusy=false;
if(res?.type==='opaqueredirect'){signOut();return;}
if(res?.ok && templatesOnly && Array.isArray(json?.templates)){hireTemplates=json.templates;hireStatus=hireTemplates.length?'Templates read.':'No templates available.';}
else if(res?.ok && !templatesOnly && json?.op==='resolved'){hireStatus=`Recorded decision ${json.id}.`;}
else {const r=decideRefusal(res,json,templatesOnly?'confirmation-unavailable':'outcome-unknown');hireStatus=r.message;hireCode=r.code;}
paintHireStart();
// A hire, fire or change applied: the Agents page and any pane showing this organization draw it now.
if(res?.ok && !templatesOnly && json?.op==='resolved' && hireOrg())document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org:hireOrg()}}));
}
// Fire from an agent card on the Agents page (ruling 2026-11-14, visibility): the same hire decision the
// form above raises with op fire, after an inline confirmation. On success the card goes at once, a
// receipt names the decision, and the page reads the organization again. The confirmation and the
// receipt live here so a redraw keeps them; workspace.js draws them from MosaicDecide.
const FIRE_REASON='Fired from the Agents page.';
let fireAsk=null,fireBusy=false,fireReceipt=null;
const fireKey=(org,name)=>`${org}\u0000${name}`;
// #1873 SP5: the system Agents page lists every organization's agents, so its controls carry their
// organization (data-agent-fire-org) and post to that organization's own bus, never to the one
// opened last. Its receipt box is `data-agents-receipt="*"` and shows a receipt from any of them.
// The agent cards keep the old shape: no attribute, the opened organization, canDecide.
function fireNote(scope=hireOrg()){const r=fireReceipt&&(scope==='*'?fireReceipt.system:fireReceipt.org===scope)?fireReceipt:null;
return r?`<p class="receipt${r.failed?' failed':''}" data-agents-receipt-text>${txt(r.text)}${r.code?` (<code>${txt(r.code)}</code>)`:''}</p>`:'';}
function paintFireNote(){for(const e of document.querySelectorAll('[data-agents-receipt]'))e.innerHTML=fireNote(e.dataset.agentsReceipt||hireOrg());}
const fireSel=(attr,name,org)=>`[${attr}="${CSS.escape(name)}"]${org?`[data-agent-fire-org="${CSS.escape(org)}"]`:':not([data-agent-fire-org])'}`;
async function fireAgent(name,named=null,orgName=named){
const org=named??hireOrg();
// A named organization was checked against its own config when the control was drawn (decidesIn).
if(fireBusy||!org||out()||(!named&&!canDecide)||isTester)return;
fireBusy=true;
for(const b of document.querySelectorAll('[data-agent-fire-yes],[data-agent-fire-no]'))b.disabled=true;
const epoch=orgEpoch;
const {res,json}=await decidePost(`${decideBase({ org: named })}/decisions/hire/start`,{business:org,hire:{op:'fire',level:'org',name,reason:FIRE_REASON}});
// SP5 review F7: a named organization's Fire went to that organization, so its outcome still
// stands after the opened organization changes.
// After a switch, busy and confirm state belong to whatever Fire started since; leave them alone.
const stale=epoch!==orgEpoch;
if(stale&&!named){if(res?.type==='opaqueredirect')signOut();return;}
if(!stale){fireBusy=false;fireAsk=null;}
if(res?.type==='opaqueredirect'){signOut();return;}
const where=named?` in ${orgName}`:'';
if(res?.ok && json?.op==='resolved'){
for(const c of document.querySelectorAll(`[data-org="${CSS.escape(org)}"] [data-agent-card="${CSS.escape(name)}"]`))c.remove();
for(const r of document.querySelectorAll(`[data-agents-org="${CSS.escape(org)}"] tr[data-agent="${CSS.escape(name)}"]`))r.remove();
for(const r of document.querySelectorAll(`[data-ws-agent="${CSS.escape(`${org}:${name}`)}"]`))r.remove();
fireReceipt={org,system:!!named,text:`Fired ${name}${where}. Recorded decision ${json.id}.`};
paintFireNote();announce(fireReceipt.text);
document.dispatchEvent(new CustomEvent('mosaic-org-changed',{detail:{org}}));
} else {
const r=decideRefusal(res,json,'outcome-unknown');
fireReceipt={org,system:!!named,failed:true,text:`${name}${where} was not fired: ${r.message}`,code:r.code};
paintFireNote();
for(const c of document.querySelectorAll(fireSel('data-agent-fire-confirm',name,named)))c.outerHTML=fireButton(name,named,orgName);
}
}
const fireOrgAttr=org=>org?` data-agent-fire-org="${esc(org)}"`:'';
const fireFocus=(kind,name,org)=>esc(org?`${kind}:${org}:${name}`:`${kind}:${name}`);
// SP5 review F5: the words name the organization by its label (`orgName`); its id addresses the control.
const fireNameAttr=(org,orgName)=>org&&orgName&&orgName!==org?` data-agent-fire-name="${esc(orgName)}"`:'';
const fireButton=(name,org=null,orgName=org)=>`<button type="button" class="btn small" data-agent-fire="${esc(name)}"${fireOrgAttr(org)}${fireNameAttr(org,orgName)} data-focus-key="${fireFocus('fire',name,org)}" aria-label="Fire ${esc(name)}${org?` in ${esc(orgName)}`:''}">Fire</button>`;
const fireConfirm=(name,org=null,orgName=org)=>`<span class="ws-fire-confirm" role="group" aria-label="Fire ${esc(name)}${org?` in ${esc(orgName)}`:''}?" data-agent-fire-confirm="${esc(name)}"${fireOrgAttr(org)}${fireNameAttr(org,orgName)}>Fire ${txt(name)}? <button type="button" class="btn small primary" data-agent-fire-yes="${esc(name)}"${fireOrgAttr(org)} data-focus-key="${fireFocus('fire-yes',name,org)}"${fireBusy?' disabled':''}>Confirm fire</button><button type="button" class="btn small" data-agent-fire-no="${esc(name)}"${fireOrgAttr(org)}${fireBusy?' disabled':''}>Cancel</button></span>`;
// What the agent card shows for one agent: nothing without the decide right or outside the page's own
// organization. SP5: `allowed` given means the caller read that organization's own config (decidesIn);
// the control is then drawn for that organization, whichever one was opened last.
function fireControl(org,name,allowed,orgName=org){
const named=typeof allowed==='boolean';
if(isTester||(named?!allowed:(!canDecide||org!==hireOrg())))return '';
return fireAsk===fireKey(org,name)?fireConfirm(name,named?org:null,named?orgName:null):fireButton(name,named?org:null,named?orgName:null);
}
document.addEventListener('click',e=>{
const t=e.target.closest?.('[data-agent-fire],[data-agent-fire-yes],[data-agent-fire-no]');
if(!t)return;
const named=t.dataset.agentFireOrg??null,org=named??hireOrg(),orgName=t.closest('[data-agent-fire-name]')?.dataset.agentFireName??named;
if(t.hasAttribute('data-agent-fire')){const name=t.dataset.agentFire;fireAsk=fireKey(org,name);t.outerHTML=fireConfirm(name,named,orgName);document.querySelector(fireSel('data-agent-fire-yes',name,named))?.focus();}
else if(t.hasAttribute('data-agent-fire-no')){const name=t.dataset.agentFireNo;fireAsk=null;t.closest('[data-agent-fire-confirm]').outerHTML=fireButton(name,named,orgName);document.querySelector(fireSel('data-agent-fire',name,named))?.focus();announce('Cancelled. Nothing was fired.');}
else void fireAgent(t.dataset.agentFireYes,named,orgName);
});
window.MosaicDecide=Object.freeze({fireControl,fireNote});
document.addEventListener('click',e=>{if(e.target.closest?.('[data-hire-load]'))hireSubmit(true);});
document.addEventListener('submit',e=>{if(e.target.id==='hire-start-form'){e.preventDefault();hireSubmit();}});
const answerChoices = c => ['decision','hire'].includes(c.kind)
@@ -523,6 +602,9 @@
};
const decideRefusal = (res, json, fallback) => res && !res.ok && res.status !== 408 && typeof json?.error === 'string' && typeof json?.message === 'string'
? { code: json.error, message: json.message } : { code: fallback, message: DECIDE_FALLBACK[fallback] };
// SP3: an answer started from the system Inbox names its organization and goes there, whichever
// organization was opened last. One started on a decision page keeps the page's own scope.
const decideBase = a => a.org ? `/api/orgs/${enc(a.org)}` : '/api';
async function decide(step) {
const a = answer;
if (!a || a.pending || a.result) return;
@@ -533,7 +615,7 @@
const choice = selected.key, ordinary = ['decision','hire'].includes(a.console.kind);
const adjust=choice==='yes'?collectHireAdjustment(a.console):undefined;
a.pending = step; a.error = null; a.confirm = null; paintDecide();
const { res, json } = await decidePost(`/api/decisions/${enc(a.id)}/confirmation`, { choice,...(adjust===undefined?{}:{adjust}) });
const { res, json } = await decidePost(`${decideBase(a)}/decisions/${enc(a.id)}/confirmation`, { choice,...(adjust===undefined?{}:{adjust}) });
a.pending = null;
// The page moved to another decision meanwhile: its confirmation is dropped, never shown.
if (answer !== a) { if (res?.type === 'opaqueredirect') signOut(); return; }
@@ -547,7 +629,7 @@
if (step !== 'confirm' || !a.confirm) return;
const c = a.confirm;
a.pending = 'confirm'; a.error = null; paintDecide();
const { res, json } = await decidePost(`/api/decisions/${enc(a.id)}/resolve`, { choice: c.choice, confirmation: c.confirmation });
const { res, json } = await decidePost(`${decideBase(a)}/decisions/${enc(a.id)}/resolve`, { choice: c.choice, confirmation: c.confirmation });
// One use, whatever came back.
a.pending = null; a.confirm = null;
if (answer !== a) { if (res?.type === 'opaqueredirect') signOut(); else render(false); return; }
@@ -557,6 +639,53 @@
paintDecide('#decide-status'); announce(['decision','hire'].includes(c.kind) ? 'Recorded' : c.action === 'approve' ? 'Approved' : 'Denied'); render(false);
} else { a.error = decideRefusal(res, json, 'outcome-unknown'); paintDecide('#decide-status'); announce(`Not answered: ${a.error.message}`); }
}
// Whether this Console decides in one organization, from that organization's own config: the system
// Inbox's hire links must not follow the organization opened last, whose bus may be the stopped one.
const orgConfig = id => (isTester ? Promise.resolve(null) : fetch(`/api/orgs/${enc(id)}/config`, { cache: 'no-store', redirect: 'manual' })
.then(r => (r.ok ? r.json() : null)).catch(() => null));
const decidesIn = id => orgConfig(id).then(c => c?.decide === true && c?.tester !== true);
// SP4: whether this Console takes task changes in one organization, from that organization's own
// config (orgSetup, as the per-organization board read it), so the system task board offers a move
// only where the row's organization takes it.
const tasksIn = id => orgConfig(id).then(c => c?.orgSetup === true && c?.tester !== true);
// SP3: the answer panel for the row selected in the Inbox, in that row's organization. That
// organization's config says whether this Console answers decisions there, and its bus inbox says
// whether this decision is eligible (its `console` field), so neither comes from the organization
// opened last. The state follows the same keep rules as the decision page's. `current` is the
// render's own check: a read that returns after the page moved on changes nothing.
async function inboxAnswer(d, current) {
if (!d || isTester || !d.console || typeof d.org !== 'string') return inboxKeep(d);
const base = `/api/orgs/${enc(d.org)}`;
let eligible = null, failed = false, seen = null;
try {
const [c, i] = await Promise.all([`${base}/config`, `${base}/bus/inbox`].map(u => fetch(u, { cache: 'no-store', redirect: 'manual' })));
if (c.type === 'opaqueredirect' || i.type === 'opaqueredirect') { if (current()) signOut(); return ''; }
if (!c.ok || !i.ok) throw new Error('not read');
const [cfg, box] = await Promise.all([c.json(), i.json()]);
const row = (Array.isArray(box?.rows) ? box.rows : []).find(r => r?.id === d.id);
// The broker's inbox row is the decisions row (`route_to`) plus `authorization`; the confirm
// step shows who raised it and what it affects from it, as the decision page does from the trail.
eligible = cfg?.decide === true && cfg?.tester !== true && row?.route_to === 'human' && row.console && typeof row.console === 'object' ? row.console : null;
if (eligible) seen = { at: row.at, raisedBy: { role: row.raised_by_role, run: row.raised_by_run }, routeTo: row.route_to, authorization: row.authorization ?? null };
} catch { failed = true; }
if (!current()) return '';
const same = answer?.org === d.org && answer.id === d.id;
if (!same) answer = eligible ? { id: d.id, org: d.org, console: eligible, pending: null, confirm: null, error: null, result: null } : null;
else if (eligible && !answer.pending) {
if (answer.console.digest !== eligible.digest) answer.confirm = null;
answer.console = eligible;
}
else if (!eligible && !failed && !answer.pending && !answer.result) answer = null;
if (answer?.org === d.org && answer.id === d.id) { if (seen) answer.decision = seen; return decideHtml(); }
return failed ? '<p class="note" data-ws-answer-why>Whether this Console can answer it here was not read: the organization did not answer. Open it in its organization, or use a terminal.</p>' : '';
}
// A row this Console cannot answer drops any answer held for another row, unless one is in flight.
function inboxKeep(d) {
if (answer?.org && !answer.pending && !(d && answer.org === d.org && answer.id === d.id && answer.result)) answer = null;
return answer?.org && d && answer.org === d.org && answer.id === d.id ? decideHtml() : '';
}
// The receipt stays on screen after the answered row leaves the list.
const inboxAnswered = key => answer?.org && answer.result && `${answer.org}:${answer.id}` === key ? decideHtml() : '';
async function inboxView(get) {
await configRead;
if(!hireDraft.business && window.MosaicOrg?.id)hireDraft.business=window.MosaicOrg.id;
@@ -771,12 +900,15 @@
return `<section aria-labelledby="b-thread-claims">${title}<div class="banner err" role="alert"><p>${why(err)}</p>${retry}</div></section>`;
}
}
async function agentsView(get) {
// SP5: an organization's scoped page leads with its rows of the system Agents table (which owns the
// heading), then the levels grid under its own h2, then held roles and threads.
const scopedTop = async (q, org, note) => `${await window.MosaicWorkspace.agentsPage(q, { scope: org })}${await window.MosaicWorkspace.agentGrid(note, undefined, { under: true })}`;
async function agentsView(get, q = new URLSearchParams(), org = null) {
let claims;
try { claims = await get('agents'); } catch (err) {
if (!window.MosaicOrg || err.code === 'signed-out') throw err;
if (refusal(err)) forget();
return `${await window.MosaicWorkspace.agentGrid()}<div class="banner err" role="alert">The selected organization's held roles could not be read. ${why(err)}</div>`;
return `${org ? await scopedTop(q, org) : await window.MosaicWorkspace.agentGrid()}<div class="banner err" role="alert">The selected organization's held roles could not be read. ${why(err)}</div>`;
}
let instances = null, threads = [];
if (!isTester) {
@@ -793,7 +925,7 @@
const threadSection = await threadClaimsSection(get, holders, threads, !!instances, running);
const rows = claims.map(c => `<tr><th scope="row">${txt(c.role)}</th><td>${stateMark(c.state)}${c.working ? `<span class="source">${esc(plural(c.working.messages, 'message'))} since ${when(c.working.since)}</span>` : ''}</td><td>${attention(c)}</td><td>${txt(holders.get(c.holder_run) || c.role)}<span class="source">run ${txt(c.holder_run)}${!instances ? ', running status unavailable' : running.has(c.holder_run) ? '' : ', not running'}</span></td><td>${txt(c.harness)}${c.address ? `<span class="source">${txt(c.address)}</span>` : ''}</td><td>${when(c.at)}</td></tr>`).join('');
// Organization mode (sample 08): the levels grid carries the page heading; held roles follow.
const top = window.MosaicOrg ? await window.MosaicWorkspace.agentGrid(readNote(get)) : head('Agents', readNote(get));
const top = !window.MosaicOrg ? head('Agents', readNote(get)) : org ? await scopedTop(q, org, readNote(get)) : await window.MosaicWorkspace.agentGrid(readNote(get));
return `${top}
<section aria-labelledby="b-claims"><h2 id="b-claims">Held roles <span class="count">${claims.length}</span></h2><p class="small muted">The current holder of each claimed role. A role nobody holds does not appear. Working: the holder has messages it received and hasn't answered yet. Waiting: a decision the role raised is open in your inbox. Otherwise idle.</p>
${claims.length ? `<div class="table-wrap" tabindex="0" role="region" aria-label="Held roles, scroll for all columns"><table class="s1-table s1-agents"><thead><tr>${['Role', 'State', 'Attention', 'Holder', 'Harness', 'Held since'].map(h => `<th scope="col">${h}</th>`).join('')}</tr></thead><tbody>${rows}</tbody></table></div>` : empty('No role is held right now.', 'A role shows here while a run holds its claim on the bus.')}</section>
@@ -989,9 +1121,9 @@
document.addEventListener('change',e=>{const form=e.target.closest?.('#launch-settings-form');if(form){settingsInputs=settingDraft(form);markSettingsDraft('limits',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=$('launch-settings-reload');if(discard)discard.hidden=false;}});
document.addEventListener('click',e=>{if(e.target.id!=='launch-settings-reload')return;settingsInputs=null;settingsSnapshot=null;settingsReceipt='';last.delete('api:settings');render(true);});
document.addEventListener('submit',async e=>{
if(e.target.id!=='launch-settings-form')return;e.preventDefault();if(!canSend||out()||settingsSaving)return;settingsInputs=settingDraft(e.target);let payload;try{payload=settingPayload();}catch(err){settingsReceipt=err.message+' Draft kept.';render(false);return;}settingsSaving=true;settingsReceipt='';render(false);
try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){settingsReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsInputs=null;settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});settingsReceipt='Launch settings saved.';}else settingsReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again. Draft kept.':`${result?.message||'Settings refused.'} Draft kept.`;}}
catch{settingsReceipt='Outcome unknown. Read current settings before trying again. Draft kept.';}finally{settingsSaving=false;if(!out())render(false);}
if(e.target.id!=='launch-settings-form')return;e.preventDefault();if(!canSend||out()||settingsSaving)return;settingsInputs=settingDraft(e.target);let payload;try{payload=settingPayload();}catch(err){settingsReceipt=err.message+' Draft kept.';render(false);return;}settingsSaving=true;settingsReceipt='';render(false);const epoch=orgEpoch;
try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){settingsReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsInputs=null;settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});settingsReceipt='Launch settings saved.';}else settingsReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again. Draft kept.':`${result?.message||'Settings refused.'} Draft kept.`;}}
catch{if(epoch!==orgEpoch)return;settingsReceipt='Outcome unknown. Read current settings before trying again. Draft kept.';}finally{if(epoch===orgEpoch){settingsSaving=false;if(!out())render(false);}}
});
// Row 125 (#1619, REQ-LIMIT-3, REQ-LIMIT-4): each token limit as the bus's checks report it. A
// limit no switched-on check counts reads "not enforced". Reset counts it again from now. Row 126
@@ -1012,9 +1144,9 @@
document.addEventListener('click',async e=>{
const path=e.target.dataset?.limitReset;if(path===undefined||!canSend||out()||settingsSaving)return;
const revision=settingsSnapshot?.revision;if(!/^[a-f0-9]{64}$/.test(revision??''))return;
settingsSaving=true;resetReceipt='';render(false);let reread=false;
try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision,reset:[JSON.parse(path)]}),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){resetReceipt='Sign in again.';signOut();}else{const result=await response.json();if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});reread=true;resetReceipt='Limit reset.';}else resetReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again.':`${result?.message||'Reset refused.'}`;}}
catch{resetReceipt='Outcome unknown. Read current settings before trying again.';}finally{settingsSaving=false;if(!out())render(reread);}
settingsSaving=true;resetReceipt='';render(false);let reread=false;const epoch=orgEpoch;
try{const response=await fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision,reset:[JSON.parse(path)]}),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){resetReceipt='Sign in again.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;if(response.ok&&/^[a-f0-9]{64}$/.test(result?.revision??'')){settingsSnapshot=result;const prior=last.get('api:settings');if(prior)last.set('api:settings',{...prior,launch:result});reread=true;resetReceipt='Limit reset.';}else resetReceipt=result?.sent==='unknown'?'Outcome unknown. Read current settings before trying again.':`${result?.message||'Reset refused.'}`;}}
catch{if(epoch!==orgEpoch)return;resetReceipt='Outcome unknown. Read current settings before trying again.';}finally{if(epoch===orgEpoch){settingsSaving=false;if(!out())render(reread);}}
});
function tokenUsage(value) {
if (!value?.total) return '<section class="panel" aria-labelledby="token-usage-title"><h2 id="token-usage-title">Token usage</h2><p>Usage unavailable. No count was read.</p></section>';
@@ -1069,9 +1201,9 @@
}
const unknownAssistant='Outcome unknown. Read current settings before trying again. Draft kept.';
async function assistantPost(url,payload,instance,ok,kind='tester'){
if(kind==='tester')assistantBusy=true;else assistantFormsBusy.add(assistantKey(instance,kind));assistantReceiptKinds[instance]=kind;assistantReceipts[instance]='';if(kind!=='tester')assistantCardReceipts[assistantKey(instance,kind)]='';render(false);
try{const response=await fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){assistantReceipts[instance]='Sign in again. Draft kept.';signOut();}else{const result=await response.json();assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=response.ok?ok(result):result?.sent==='unknown'?unknownAssistant:`${result?.message||'Refused.'} Draft kept.`;}}
catch{assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=unknownAssistant;}finally{if(kind==='tester')assistantBusy=false;else{assistantCardReceipts[assistantKey(instance,kind)]=assistantReceipts[instance];assistantFormsBusy.delete(assistantKey(instance,kind));}if(!out())render(false);}
if(kind==='tester')assistantBusy=true;else assistantFormsBusy.add(assistantKey(instance,kind));assistantReceiptKinds[instance]=kind;assistantReceipts[instance]='';if(kind!=='tester')assistantCardReceipts[assistantKey(instance,kind)]='';render(false);const epoch=orgEpoch;
try{const response=await fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){assistantReceipts[instance]='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=response.ok?ok(result):result?.sent==='unknown'?unknownAssistant:`${result?.message||'Refused.'} Draft kept.`;}}
catch{if(epoch!==orgEpoch)return;assistantReceiptKinds[instance]=kind;assistantReceipts[instance]=unknownAssistant;}finally{if(epoch===orgEpoch){if(kind==='tester')assistantBusy=false;else{assistantCardReceipts[assistantKey(instance,kind)]=assistantReceipts[instance];assistantFormsBusy.delete(assistantKey(instance,kind));}if(!out())render(false);}}
}
const assistantForm=el=>el?.closest?.('.assistant-form');
for(const kind of ['input','change'])document.addEventListener(kind,e=>{const form=assistantForm(e.target);if(!form)return;const instance=form.dataset.instance,field=e.target.dataset.assistantField;if(field==='name')nameDrafts[instance]=e.target.value;else if(field)assistantDrafts[instance]={...Object.fromEntries(['definition','vars','tracker'].map(f=>[f,form.querySelector(`[data-assistant-field="${f}"]`).value]))};if(field){markSettingsDraft('assistant',true);form.querySelector('.settings-actions')?.classList.add('has-draft');const discard=form.querySelector('[data-assistant-discard]');if(discard)discard.hidden=false;}});
@@ -1136,11 +1268,11 @@
const form=e.target?.closest?.('.instance-form');if(!form||e.target!==form)return;e.preventDefault();if(!(canSend || isTester)||out()||!instanceView)return;
const op=form.dataset.op;if(instanceBusyOps.has(op))return;instanceReceiptOp=op;instanceDrafts[op]=instanceFields(form);let payload;
try{payload=instancePayload(op,instanceDrafts[op]);}catch(err){instanceReceipt=err.message;instanceReceipts[op]=instanceReceipt;render(false);return;}
instanceBusyOps.add(op);instanceReceipt='';instanceReceipts[op]='';render(false);
try{const response=await fetch('/api/instances',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){instanceReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();
instanceBusyOps.add(op);instanceReceipt='';instanceReceipts[op]='';render(false);const epoch=orgEpoch;
try{const response=await fetch('/api/instances',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){instanceReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;
if(response.ok&&instanceAnswer(result)){instanceDrafts[op]=null;instanceView=result;const prior=last.get('instances');if(prior)last.set('instances',{...prior,rows:[result]});instanceReceipt=`${op==='add'?'Added':'Changed'} ${payload.instance}. ${result.restart?restartText():NO_RESTART_TEXT}`;}
else instanceReceipt=response.ok||result?.sent==='unknown'?unknownInstance:`${result?.message||'Refused.'} Draft kept.`;}}
catch{instanceReceipt=unknownInstance;}finally{instanceBusyOps.delete(op);instanceReceiptOp=op;instanceReceipts[op]=instanceReceipt;if(!out())render(false);}
catch{if(epoch!==orgEpoch)return;instanceReceipt=unknownInstance;}finally{if(epoch===orgEpoch){instanceBusyOps.delete(op);instanceReceiptOp=op;instanceReceipts[op]=instanceReceipt;if(!out())render(false);}}
});
// Row 65 (mos-0840): the routing table. One row per instance: harness, model and thinking, and
// the fallback's three. Each cell offers the switched-on harnesses, the model table's keys and the
@@ -1166,8 +1298,8 @@
const routesApplyMarkup=()=>routesApply?.length?`<ul class="routes-apply" aria-label="How the change reaches each agent">${routesApply.map(a=>`<li><b>${txt(a.name)}</b>: ${txt(a.text)}${a.restart&&canSend&&!isTester?` ${window.MosaicAgents?.restartMarkup(a.name,a.thread)??''}`:''}</li>`).join('')}</ul>`:'';
let harnessSettings=null, harnessDraft=null, harnessLoading=false, harnessReceipt='', harnessBusy=false;
function readHarnesses(){
if(harnessLoading || harnessSettings !== null || !canSend || isTester)return; harnessLoading=true;
fetch('/api/proxy/plugins',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(!r.ok || !/^[a-f0-9]{64}$/.test(v.revision??'') || !Array.isArray(v.available?.harness) || !v.available.harness.every(n=>typeof n==='string') || !Array.isArray(v.plugins?.harness??[]))throw Error();harnessSettings=v;}).catch(()=>{harnessSettings=false;harnessReceipt='Harnesses could not be read.';}).finally(()=>{harnessLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);});
if(harnessLoading || harnessSettings !== null || !canSend || isTester)return; harnessLoading=true;const epoch=orgEpoch;
fetch('/api/proxy/plugins',{cache:'no-store',redirect:'manual'}).then(async r=>{const v=await r.json();if(epoch!==orgEpoch)return;if(!r.ok || !/^[a-f0-9]{64}$/.test(v.revision??'') || !Array.isArray(v.available?.harness) || !v.available.harness.every(n=>typeof n==='string') || !Array.isArray(v.plugins?.harness??[]))throw Error();harnessSettings=v;}).catch(()=>{if(epoch!==orgEpoch)return;harnessSettings=false;harnessReceipt='Harnesses could not be read.';}).finally(()=>{if(epoch!==orgEpoch)return;harnessLoading=false;if(routeOf().split('?')[0]==='/settings/routing')render(false);});
}
const ROUTE_CELLS=[['harness','Harness'],['model','Model'],['thinking','Thinking'],['fallback.harness','Fallback harness'],['fallback.model','Fallback model'],['fallback.thinking','Fallback thinking']];
const routeCells=r=>({harness:r.harness??'',model:r.model??'',thinking:r.thinking??'','fallback.harness':r.fallback?.harness??'','fallback.model':r.fallback?.model??'','fallback.thinking':r.fallback?.thinking??''});
@@ -1244,32 +1376,32 @@
if(harnessSettings.revision!==routesView?.revision){harnessReceipt='The business changed. Reload this page before saving harnesses.';render(false);return;}
const used=old.filter(n=>!selected.includes(n) && Object.values(routesView.instances).some(r=>r.harness===n || r.fallback?.harness===n));
if(used.length){harnessReceipt=`A saved route uses ${used.join(', ')}. Change the route before switching it off.`;render(false);return;}
harnessBusy=true;const button=e.target;button.disabled=true;harnessReceipt='';
try{const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:harnessSettings.revision,plugins:{harness:selected}}),cache:'no-store',redirect:'manual'});const result=await response.json();if(!response.ok){harnessReceipt=result.message||result.error||'Harness setting was refused.';return;}harnessSettings={...result,available:harnessSettings.available};harnessDraft=null;harnessReceipt='Harnesses saved. The next launch uses the new settings.';routesView=null;last.delete('routes');}
catch{harnessReceipt='Outcome unknown. Read the harnesses again before trying.';harnessSettings=false;}
finally{harnessBusy=false;if(!out())render(false);}
harnessBusy=true;const button=e.target;button.disabled=true;harnessReceipt='';const epoch=orgEpoch;
try{const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:harnessSettings.revision,plugins:{harness:selected}}),cache:'no-store',redirect:'manual'});const result=await response.json();if(epoch!==orgEpoch)return;if(!response.ok){harnessReceipt=result.message||result.error||'Harness setting was refused.';return;}harnessSettings={...result,available:harnessSettings.available};harnessDraft=null;harnessReceipt='Harnesses saved. The next launch uses the new settings.';routesView=null;last.delete('routes');}
catch{if(epoch!==orgEpoch)return;harnessReceipt='Outcome unknown. Read the harnesses again before trying.';harnessSettings=false;}
finally{if(epoch===orgEpoch){harnessBusy=false;if(!out())render(false);}}
});
document.addEventListener('click',async e=>{if(e.target.id!=='provider-switch'||!canSend||isTester)return;
const button=e.target,status=$('provider-switch-status');if(routesDraft){status.textContent='Save or discard the route draft first.';return;}button.disabled=true;
try {const read=await fetch('/api/proxy/plugins',{cache:'no-store'});const settings=await read.json();if(!read.ok||!/^[a-f0-9]{64}$/.test(settings.revision??''))throw Error('Could not read provider settings.');
const button=e.target,status=$('provider-switch-status');if(routesDraft){status.textContent='Save or discard the route draft first.';return;}button.disabled=true;const epoch=orgEpoch;
try {const read=await fetch('/api/proxy/plugins',{cache:'no-store'});const settings=await read.json();if(epoch!==orgEpoch)return;if(!read.ok||!/^[a-f0-9]{64}$/.test(settings.revision??''))throw Error('Could not read provider settings.');
const names=Array.isArray(settings.plugins?.['model-provider'])?settings.plugins['model-provider']:[];
// The fresh read decides: a stale label never turns the proxy module on when it meant off.
const on=names.includes('cliproxy');if(String(on)!==button.dataset.enabled){button.dataset.enabled=String(on);button.textContent=`${on?'Disable':'Enable'} model proxy catalogue`;button.disabled=false;status.textContent='The switch now shows the current setting. Press it again to change it.';return;}
const next=on?names.filter(n=>n!=='cliproxy'):[...names,'cliproxy'];
const response=await fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:settings.revision,plugins:{'model-provider':next}}),cache:'no-store',redirect:'manual'});
if(!response.ok)throw Error('Provider setting was refused.');harnessSettings=null;routesView=null;last.delete('routes');render(true);
}catch(error){status.textContent=error.message;button.disabled=false;}
if(epoch!==orgEpoch)return;if(!response.ok)throw Error('Provider setting was refused.');harnessSettings=null;routesView=null;last.delete('routes');render(true);
}catch(error){if(epoch!==orgEpoch)return;status.textContent=error.message;button.disabled=false;}
});
document.addEventListener('click',e=>{if(e.target.matches?.('.fallback-toggle'))e.target.closest('tr')?.classList.add('fallback-open');});
document.addEventListener('click',e=>{if(e.target.id!=='routes-reload')return;routesDraft=null;routesView=null;routesReceipt='';routesApply=null;last.delete('routes');render(true);});
document.addEventListener('submit',async e=>{
if(e.target.id!=='routes-form')return;e.preventDefault();if(!(canSend || isTester)||out()||routesBusy||!routesView)return;
routesDraft=routesFields(e.target);let payload;try{payload=routesPayload(routesDraft);}catch(err){routesReceipt=err.message;render(false);return;}
routesBusy=true;routesReceipt='';routesApply=null;render(false);
try{const response=await fetch('/api/routes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(response.type==='opaqueredirect'){routesReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();
if(response.ok&&routesAnswer(result)){routesDraft=null;routesView=result;harnessSettings=null;const prior=last.get('routes');if(prior)last.set('routes',{...prior,rows:[result]});routesReceipt=`Routes saved for ${Object.keys(payload.routes).join(', ')}. The next launch of each uses the new route.`;routesApply=await routesApplyRead(Object.keys(payload.routes));}
routesBusy=true;routesReceipt='';routesApply=null;render(false);const epoch=orgEpoch;
try{const response=await fetch('/api/routes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});if(epoch!==orgEpoch){if(response.type==='opaqueredirect')signOut();return;}if(response.type==='opaqueredirect'){routesReceipt='Sign in again. Draft kept.';signOut();}else{const result=await response.json();if(epoch!==orgEpoch)return;
if(response.ok&&routesAnswer(result)){routesDraft=null;routesView=result;harnessSettings=null;const prior=last.get('routes');if(prior)last.set('routes',{...prior,rows:[result]});routesReceipt=`Routes saved for ${Object.keys(payload.routes).join(', ')}. The next launch of each uses the new route.`;const applied=await routesApplyRead(Object.keys(payload.routes));if(epoch!==orgEpoch)return;routesApply=applied;}
else routesReceipt=response.ok||result?.sent==='unknown'?unknownRoutes:`${result?.message||'Refused.'}${catalogueStep(result?.error,payload.routes)} Draft kept.`;}}
catch{routesReceipt=unknownRoutes;}finally{routesBusy=false;if(!out())render(false);}
catch{if(epoch!==orgEpoch)return;routesReceipt=unknownRoutes;}finally{if(epoch===orgEpoch){routesBusy=false;if(!out())render(false);}}
});
// Row 194 (#1692, D7): the Agents section lives in agents.js (window.MosaicAgents) and draws from
// the same instances read. A refresh drops that read so the next render asks the bus again.
@@ -1480,6 +1612,7 @@
if (!s || !saveable(s)) return;
const sent = { project: s.project, path: s.path, base: s.commit, content: s.text }, unknown = 'Outcome unknown: the save may have gone through. Copy your text, then reload the file to check before saving again. Draft kept.';
s.saving = true; s.status = '';
const epoch = orgEpoch;
let res = null, body = null;
try {
paintDoc();
@@ -1491,13 +1624,16 @@
} else if (body?.sent === false) s.status = `${typeof body.message === 'string' && body.message ? body.message : 'Not saved.'} Draft kept.`;
else s.status = unknown;
} finally { s.saving = false; } // a throw above must not leave Save off and Reload refused
// #1873 SP1: a switch while this was in flight cleared the drafts; the old file's outcome is not
// painted or announced on the new organization's page.
if (epoch !== orgEpoch) { if (res?.type === 'opaqueredirect') signOut(); return; }
paintDoc();
announce(s.status);
if (res?.type === 'opaqueredirect') signOut();
});
// Not found and states
function notFound(why) { return `${head('Not found')}<div class="empty nf"><b>${why || 'No page at this address.'}</b><p>Nothing is at <code>${txt(location.hash || '#/')}</code>. <a href="#/">Go to the ${window.MosaicOrg ? 'Dashboard' : 'Board'}</a> or press <kbd>Ctrl K</kbd> to search.</p></div>`; }
function notFound(why) { return `${head('Not found')}<div class="empty nf"><b>${why || 'No page at this address.'}</b><p>Nothing is at <code>${txt(location.hash || '#/')}</code>. <a href="${window.MosaicOrg ? '#/dashboard' : '#/'}">Go to the ${window.MosaicOrg ? 'Dashboard' : 'Board'}</a> or press <kbd>Ctrl K</kbd> to search.</p></div>`; }
const loadingView = (source = null) => `${head('Reading…')}<div class="skel-rows" aria-busy="true"><span class="sr-only">${source ? `Reading the ${esc(source.toLowerCase())}.` : 'Reading from the bus.'}</span><span class="skel"></span><span class="skel"></span><span class="skel"></span><span class="skel"></span></div>`;
const retry = '<div class="actions"><button type="button" class="btn" data-retry>Read again</button></div>';
// Why a read failed, in words, with the bus code as given. Never a path or a guess.
@@ -1552,16 +1688,34 @@
const parts = path.split('/').filter(Boolean).map(p => { try { return decodeURIComponent(p); } catch { return null; } });
if (parts.includes(null)) return notFound();
const [a, b, c] = parts, n = parts.length;
if (n === 0 && window.MosaicOrg) return window.MosaicWorkspace.home();
// #1873 SP1: `#/dashboard` is the system dashboard, every organization on one page.
if ((n === 0 || (a === 'dashboard' && n === 1)) && window.MosaicOrg) return window.MosaicWorkspace.home();
if (a === 'projects' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.projectsPage(q);
if (a === 'organization' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.dashboard();
if (a === 'inbox' && n === 1 && window.MosaicOrg) return configRead.then(() => window.MosaicWorkspace.inboxPage(q, { hire: hireStartHtml }));
if (a === 'tasks' && n === 1 && window.MosaicOrg) return window.MosaicTasksBoard.view();
// SP3: #/inbox is every organization's items; #/orgs/<id>/inbox is that list for one, with its hire form.
if (a === 'inbox' && n === 1 && window.MosaicOrg) {
const scope = /^#\/orgs\/([^/?]+)/.exec(location.hash)?.[1];
let org = null; try { org = scope ? decodeURIComponent(scope) : null; } catch { return notFound(); }
return configRead.then(() => window.MosaicWorkspace.inboxPage(q, { scope: org, hire: org ? hireStartHtml : null, hireIn: org ? null : decidesIn, answer: d => inboxAnswer(d, current), answered: inboxAnswered }));
}
// SP4: #/tasks is every organization's tasks on one board; #/orgs/<id>/tasks is that board for one.
if (a === 'tasks' && n === 1 && window.MosaicOrg) {
const scope = /^#\/orgs\/([^/?]+)/.exec(location.hash)?.[1];
let org = null; try { org = scope ? decodeURIComponent(scope) : null; } catch { return notFound(); }
return configRead.then(() => window.MosaicTasksBoard.view(q, { scope: org, writesIn: tasksIn }));
}
if (a === 'inbox' && n === 1) return inboxView(get);
if (a === 'inbox' && n === 2) return SAFE.test(b) ? decisionView(get, b, current) : notFound(`${txt(b)} is not a decision id.`);
if (a === 'messages' && n === 1) return messagesView(get, q);
if (a === 'tasks' && n === 1) return tasksView(get);
if (a === 'tasks' && n === 2) return TASK.test(b) ? taskView(get, b) : notFound(`${txt(b)} is not a task reference.`);
// SP5: #/agents is every organization's agents; #/orgs/<id>/agents is that table for one, above its levels grid and held roles.
if (a === 'agents' && n === 1 && window.MosaicOrg) {
const scope = /^#\/orgs\/([^/?]+)/.exec(location.hash)?.[1];
let org = null; try { org = scope ? decodeURIComponent(scope) : null; } catch { return notFound(); }
if (!org) return configRead.then(() => window.MosaicWorkspace.agentsPage(q, { scope: null, fireIn: decidesIn }));
return agentsView(get, q, org);
}
if (a === 'agents' && n === 1) return agentsView(get);
if (a === 'queue' && n === 1) return queueView(get, q);
if (a === 'queue' && n === 2) return /^[1-9]\d{0,5}$/.test(b) ? queueRowView(get, b) : notFound(`${txt(b)} is not a queue row id.`);
@@ -1577,7 +1731,7 @@
const paused = () => $('pause')?.getAttribute('aria-pressed') === 'true';
// A file open in the editor is never refreshed from under its draft; Reload is the person's to press.
// The cross-organization pages (U3) poll at the workspace read's pollMs.
const wsPage = path => !!window.MosaicOrg && (path === '/' || path === '' || path === '/projects' || path === '/inbox');
const wsPage = path => !!window.MosaicOrg && (path === '/' || path === '' || path === '/dashboard' || path === '/projects' || path === '/inbox' || path === '/agents' || path === '/tasks');
function schedule() { clearTimeout(timer); if (!paused() && !out() && !routeOf().startsWith('/docs/')) timer = setTimeout(() => render(false), wsPage(routeOf().split('?')[0]) ? window.MosaicWorkspace?.pollMs || 10000 : 10000); }
// Keep focus, open <details> and the copy status across a refresh of the same page.
// In the send form, the focused field and its caret too (its values come from `draft`).
@@ -1627,6 +1781,14 @@
// A refresh due while this render reads would replace it: a navigation would lose its heading focus.
clearTimeout(timer);
if (out()) return;
// #1873 SP1: an address with no organization waits for the first list read to pick one, and a
// page drawn right after a switch waits for the new organization's config.
if ((window.MosaicOrg && !window.MosaicOrg.id) || switchRead) {
const g0 = ++gen, waiting = switchRead;
await window.MosaicOrg?.ready; await waiting;
if (waiting && switchRead === waiting) switchRead = null;
if (g0 !== gen || out()) return;
}
const route = routeOf(), [path, query = ''] = route.split('?'), board = window.MosaicOrg ? path === '/board' : path === '/' || path === '' || path === '/board';
// On the cross-organization pages a filter or selection changes only the query: that is a
// repaint of the same page, not a navigation (no loading view, focus and scroll kept).
@@ -1634,7 +1796,7 @@
if (path !== '/settings/model-proxy' && proxyCleanup) {proxyCleanup();proxyCleanup=null;}
if ((navigated || path !== '/settings/organizations') && orgCleanup) {orgCleanup();orgCleanup=null;}
// Leaving a decision discards its confirmation immediately, including a preview in flight.
if (answer && (navigated || path !== `/inbox/${answer.id}`)) answer = null;
if (answer && (navigated || path !== (answer.org ? '/inbox' : `/inbox/${answer.id}`))) answer = null;
const g = ++gen, routeVersion = routesEditVersion;
const current = () => g === gen && route === routeOf() && !out();
// In organization mode #/ is the cross-organization dashboard; the processing controls stay on the board.
@@ -1647,13 +1809,17 @@
window.MosaicChat?.leave(chatPath);
if (path === '/business') { location.replace('#/settings/business'); return; }
if (path === '/settings/display') { location.replace('#/settings/appearance'); return; }
// U5: Side by side draws its own two panes (panes.js); every other page stops their polling.
if (path !== '/side-by-side') window.MosaicPanes?.unmount();
else if (window.MosaicOrg && window.MosaicPanes) {
// #1873 SP6: the Assistant page draws its own thread panes (assistant.js); every other page
// stops their polling. It is a system page: an organization's address for it, and the old
// Side by side address, land on `#/assistant`.
if (window.MosaicOrg && window.MosaicAssistant && path === '/side-by-side') { location.replace('#/assistant'); return; }
if (path !== '/assistant') window.MosaicAssistant?.unmount();
else if (window.MosaicOrg && window.MosaicAssistant) {
if (!window.MosaicOrg.system()) { location.replace(`#/assistant${query ? `?${query}` : ''}`); return; }
const fresh = navigated || shown !== path;
shown = path;
if (fresh) { unmountEditor(); await window.MosaicPanes.mount($('bus-view'), query, { navigated }); }
else window.MosaicPanes.refresh();
if (fresh) { unmountEditor(); await window.MosaicAssistant.mount($('bus-view'), query, { navigated }); }
else window.MosaicAssistant.refresh(query);
return;
}
if (chatPath === '/chat' || chatPath.startsWith('/chat/') || /^\/projects\/[0-9a-f-]+\/(?:settings|conversations|tasks|requirements|files)$/i.test(chatPath)) {
@@ -1688,19 +1854,25 @@
// The board page keeps its own title; the Inbox count still follows the bus.
if (shown !== null) { shown = null; unmountEditor(); $('bus-view').innerHTML = ''; document.title = 'Dashboard · Mosaic Console'; if (navigated) $('main').focus(); }
// The held roles (row 95) are read with it. A refusal of either forgets both, as on the bus pages.
const epoch = orgEpoch;
const [inbox, agents, messages, tasks, queue, business, projects] = await Promise.allSettled([
fetchRead('inbox'), fetchRead('agents'), fetchRead('messages'), fetchRead('tasks'), fetchApi('queue'), fetchApi('business'),
fetch('/api/chat/projects', { cache: 'no-store', redirect: 'manual' }).then(async r => { if (r.type === 'opaqueredirect') { signOut(); throw signedOut(); } const body = await r.json(); if (signInRequired(r, body)) { signOutSso(); throw signedOut(); } if (!r.ok || !Array.isArray(body.rows)) throw new ReadError(body?.error, body?.message, r.status); return body; })
]);
const failed = [inbox, agents, messages, tasks].filter(s => s.status === 'rejected').map(s => s.reason);
if (failed.some(err => err.code === 'signed-out')) return;
// #1873 SP1: an answer read for an organization that is no longer open is not kept.
if (epoch !== orgEpoch) return;
if (inbox.status === 'fulfilled') last.set('inbox', inbox.value);
if (agents.status === 'fulfilled') last.set('agents', agents.value);
if (messages.status === 'fulfilled') last.set('messages', messages.value);
const refused = failed.find(refusal);
if (refused) forget();
if (g !== gen) return;
if (inbox.status === 'fulfilled' && !refused) countInbox(inbox.value.rows);
// SP3 (#1873): with organizations the sidebar count is every organization's, from the same
// workspace read as #/inbox, never this one organization's inbox.
if (window.MosaicOrg) window.MosaicWorkspace?.inboxCount?.();
else if (inbox.status === 'fulfilled' && !refused) countInbox(inbox.value.rows);
if (messages.status === 'fulfilled' && !refused) messageCount = messages.value.unread;
const good = result => !refused && result.status === 'fulfilled' ? result.value : null;
const taskRows = good(tasks)?.rows, queueRows = good(queue)?.rows, projectRows = good(projects)?.rows;
@@ -1812,7 +1984,7 @@
// Ctrl+K opens it. It lists the views, and the decisions and tasks from the last inbox and
// tasks reads (opening it reads both again, GET only). Enter goes; Esc closes and puts focus
// back where it was. It only navigates.
const VIEWS = [['#/', 'Dashboard'], ['#/projects', 'Projects'], ['#/inbox', 'Inbox'], ['#/messages', 'Assistant'], ['#/tasks', 'Tasks'], ['#/agents', 'Agents'], ['#/queue', 'Queue'], ['#/settings/business', 'Business'], ['#/docs', 'Docs'], ['#/settings', 'Settings'], ['#/settings/display', 'Sidebar display']];
const VIEWS = [['#/', 'Dashboard'], ['#/projects', 'Projects'], ['#/inbox', 'Inbox'], ...(window.MosaicAssistant ? [['#/assistant', 'Assistant'], ['#/messages', 'Messages']] : [['#/messages', 'Assistant']]), ['#/tasks', 'Tasks'], ['#/agents', 'Agents'], ['#/queue', 'Queue'], ['#/settings/business', 'Business'], ['#/docs', 'Docs'], ['#/settings', 'Settings'], ['#/settings/display', 'Sidebar display']];
let pkAll = [], pkShown = [], pkAt = 0, pkBack = null;
function pkItems() {
const decisions = (last.get('inbox')?.rows || []).map(d => ({ href: `#/inbox/${enc(d.id)}`, label: first(d.question), group: `decision ${short(d.id)}` }));
@@ -1834,7 +2006,9 @@
if (d.open) return;
pkBack = document.activeElement; pkAt = 0; $('cmdk-input').value = '';
pkItems(); pkFill(); d.showModal(); $('cmdk-input').focus();
Promise.allSettled(['inbox', 'tasks'].map(async v => last.set(v, await fetchRead(v)))).then(rs => {
const epoch = orgEpoch;
Promise.allSettled(['inbox', 'tasks'].map(async v => { const r = await fetchRead(v); if (epoch === orgEpoch) last.set(v, r); })).then(rs => {
if (epoch !== orgEpoch) return;
if (rs.some(r => r.status === 'rejected' && refusal(r.reason))) { forget(); sections(routeOf().split('?')[0]); }
if (d.open) { pkItems(); pkFill(); }
});
@@ -1874,11 +2048,13 @@
if (out()) { receipt = { kind: 'refused', to: to || 'no role', code: 'sign-in', message: 'signed out; reload the page to sign in again' }; paintSend(); announce('Not sent: ' + receipt.message); return; }
if (!to || !text.trim()) { receipt = { kind: 'refused', to: to || 'no role', code: 'invalid-request', message: to ? 'the message is empty' : 'choose a role first' }; paintSend(); announce('Not sent: ' + receipt.message); return; }
sending = true; receipt = null; paintSend();
const epoch = orgEpoch;
let res = null, body = null;
try {
res = await fetch('/api/bus/message', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ to, body: text }), cache: 'no-store', redirect: 'manual' });
try { body = await res.json(); } catch { body = null; }
} catch { res = null; }
if (epoch !== orgEpoch) { if (res?.type === 'opaqueredirect') signOut(); return; }
// Sent: an id came back. Not sent: a 4xx (refused before the bus wrote), the server's
// sent:false, or a redirect, which only the sign-in proxy gives (an expired session), so the
// request never reached the Console. Anything else, no answer included, may have been sent,
@@ -1909,7 +2085,7 @@
// F3: `settingsSend` lets the owner of an organization Console save Settings on the selected
// organization's bus; messaging a role still follows `send` (canMessage) and `chatSend`.
// A bus restart reads the config again and sends it here as a mosaic-config event.
const applyConfig = c => {
const applyConfig = (c, opts = {}) => {
isTester = c?.tester === true;
canEdit = !isTester && c?.edit === true;
canSend = !isTester && (c?.send === true || c?.settingsSend === true);
@@ -1926,7 +2102,7 @@
banner.setAttribute('role', 'status'); banner.textContent = 'Tester Console. Changes are recorded as tester, never as the human.';
$('main').prepend(banner);
}
if (!canSend && !isTester && !ssoOn) return;
if (opts.quiet || (!canSend && !isTester && !ssoOn)) return;
const path = routeOf().split('?')[0];
if (path.startsWith('/chat')||path.startsWith('/projects')||path.startsWith('/inbox')||path.startsWith('/settings')||path.startsWith('/docs/')||wsPage(path)) render(false); else if (window.MosaicOrg ? path === '/board' : path === '/' || path === '') paintHeld(heldErr);
};
@@ -1934,7 +2110,35 @@
// E1 (P1-5): after Restart bus the organization dashboard draws its bus line now, not at the next poll.
// E2E6 P2-2: a write on the organization page that changes other sections (a pack apply) asks for a
// fresh read of the page; editors in progress are kept by holdLive.
document.addEventListener('mosaic-org-changed', e => { if (window.MosaicOrg && e.detail?.org === window.MosaicOrg.id && routeOf().split('?')[0] === '/organization') render(false); });
// Ruling 2026-11-14: an apply, hire or fire redraws the Agents page in the same response cycle, not at the next poll.
// SP5: the system Agents page shows every organization, so a change in any of them redraws it.
document.addEventListener('mosaic-org-changed', e => { if (!window.MosaicOrg) return; const path = routeOf().split('?')[0]; if ((path === '/agents' && window.MosaicOrg.system()) || (e.detail?.org === window.MosaicOrg.id && ['/organization', '/agents'].includes(path))) render(false); });
// #1873 SP1: another organization opened in place (display.js, before this file's hashchange
// render). Nothing read, drafted or confirmed for the old one carries over; the new one's config
// is read before the next page draws. A write already sent finishes against the old organization,
// and its answer is not drawn on the new one.
document.addEventListener('mosaic-org-switch', () => {
// Writes still in flight keep going to the old organization; their answers are dropped (orgEpoch)
// and every busy flag and receipt starts clean here.
orgEpoch++;
sending = false; receipt = null; replies = [];
hireBusy = false; fireBusy = false; settingsSaving = false; resetReceipt = '';
assistantBusy = false; assistantFormsBusy.clear(); instanceBusyOps = new Set();
routesBusy = false; routesApply = null; harnessBusy = false; harnessLoading = false;
forget(); clearTimeout(timer);
answer = null; heldErr = null; heldHtml = null; readAt = null; shown = null; projectContext = null;
draft.to = ''; draft.body = '';
hireDraft = { op: 'hire', level: 'org' }; hireTemplates = []; hireStatus = ''; hireCode = '';
fireAsk = null; fireReceipt = null;
settingsSnapshot = null; settingsInputs = null; settingsReceipt = ''; settingInvalidKey = null;
assistantDrafts = Object.create(null); nameDrafts = Object.create(null); assistantReceipts = Object.create(null); assistantReceiptKinds = Object.create(null); assistantCardReceipts = Object.create(null);
instanceView = null; instanceDrafts = { add: null, change: null }; instanceReceipt = ''; instanceReceiptOp = null; instanceReceipts = Object.create(null);
routesView = null; routesDraft = null; routesReceipt = ''; routesEditVersion++;
harnessSettings = null; harnessDraft = null; harnessReceipt = '';
// A file draft is keyed by project and path only; the page reload that used to drop it is gone.
docKey = null; docStates.clear(); pkAll = []; pkShown = []; pkAt = 0;
configRead = switchRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(c => applyConfig(c, { quiet: true })).catch(() => {});
});
document.addEventListener('mosaic-config', e => { if (e.detail && typeof e.detail === 'object') { applyConfig(e.detail); if (window.MosaicOrg && routeOf().split('?')[0] === '/organization') render(false); } });
// The cross-organization pages ask for a repaint after a filter, sort or selection change,
// and report the inbox count across organizations for the sidebar.
+105 -63
View File
@@ -1,6 +1,11 @@
/* Row 129: business chat, isolated from the Board's seat conversations and role composer. */
(() => {
'use strict';
// #1873 SP6: one chat view, more than one instance. The page's own instance (no env) is the chat
// as it always was. An Assistant pane makes its own instance with env.org: its reads and writes
// name that organization in the address, so a send always reaches the pane's own organization,
// whichever organization the page last opened, and its listeners answer only inside its container.
function chatInstance(env = {}) {
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
// crypto.randomUUID exists only in a secure context; a dev owner Console opened by LAN name
// (http://NAME:PORT/) is not one, so build the same v4 form from getRandomValues there.
@@ -18,6 +23,14 @@
// E2E6 P2-15: a message's `inline code` spans show as code, not as raw backticks. The text is escaped
// first; a pair of single backticks on one line then wraps its already-escaped contents in <code>.
const prose = value => txt(value).replace(/`([^`\n]+)`/g, '<code>$1</code>');
const pane = typeof env.org === 'string', life = new AbortController();
const on = (type, fn, capture = false) => document.addEventListener(type, fn, { capture, signal: life.signal });
// A pane prefixes its element ids so two panes never share one; handlers read them back unprefixed.
const idOf = el => { const id = typeof el?.id === 'string' ? el.id : ''; return pane && id.startsWith(env.prefix) ? 'chat-' + id.slice(env.prefix.length) : id; };
// A pane's ids carry its prefix; byId takes the page's own 'chat-…' name.
const byId = id => document.getElementById(pane && id.startsWith('chat-') ? env.prefix + id.slice(5) : id);
const pid = id => (pane && id.startsWith('chat-') ? env.prefix + id.slice(5) : id);
const mine = target => pane ? !!current?.container.contains(target) : !target?.closest?.('[data-assist-pane]');
const states = new Map(), forms = new Map(), knownRequests = new Map();
const pinnedScrolls = new WeakMap(), settlingPins = new WeakMap();
const pageFlow = log => log.closest('.project-chat') && matchMedia('(max-width: 319px), (max-height: 540px)').matches;
@@ -27,7 +40,7 @@
? (pageTailTarget(log)?.getBoundingClientRect().bottom ?? 0) - innerHeight < 40 || messageEnd && Math.abs((log.lastElementChild?.getBoundingClientRect().bottom ?? 0) - innerHeight) < 40
: log.scrollHeight - log.scrollTop - log.clientHeight < 40;
const pageTailTarget = log => {
const form = log.closest('.project-chat')?.querySelector('#chat-send-form, #chat-room-send-form');
const form = log.closest('.project-chat')?.querySelector(`#${pid('chat-send-form')}, #${pid('chat-room-send-form')}`);
const field = form?.querySelector('textarea');
const usable = current && (!field?.disabled && !current.channelDisabled || state(current.key ?? current.id).pending);
return form && field && usable && form.getClientRects().length ? form : log.lastElementChild;
@@ -69,8 +82,7 @@
const channelMessage = 'The chat channel is disabled for this business. Ask the person who manages it to enable WebUI chat, then refresh.';
function forget() {
generation++; controller?.abort(); states.clear(); forms.clear(); knownRequests.clear(); libraries.clear(); reverts.clear();
window.MosaicRequests?.forget();
window.MosaicProjectArchive?.forget();
if (!pane) { window.MosaicRequests?.forget(); window.MosaicProjectArchive?.forget(); }
if (current) current.container.replaceChildren();
current = null;
}
@@ -82,7 +94,7 @@
if (out()) throw new ChatError('signed-out');
let res;
try {
res = await fetch('/api/chat/' + path, {
res = await fetch((pane ? `/api/orgs/${encodeURIComponent(env.org)}/chat/` : '/api/chat/') + path, {
cache: 'no-store', redirect: 'manual', signal,
...(value === undefined ? {} : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(value) }),
});
@@ -104,12 +116,14 @@
}
// In organization mode #/projects is the cross-organization page, so the organization's own
// project list lives at #/chat. That list keeps the project surface and its #/projects links.
const legacyRoute = () => { const r = window.MosaicOrg?.route() ?? location.hash.slice(1); return r.startsWith('/chat') && !(window.MosaicOrg && r.split('?')[0] === '/chat'); };
const projectPath = id => legacyRoute() ? `#/chat/projects/${id}` : `#/projects/${id}`;
const threadPath = id => legacyRoute() ? `#/chat/threads/${id}` : `#/projects/threads/${id}`;
const roomPath = id => legacyRoute() ? `#/chat/rooms/${id}` : `#/projects/rooms/${id}`;
const orgBase = pane ? '#/orgs/' + encodeURIComponent(env.org) : '#';
const legacyRoute = () => { if (pane) return false; const r = window.MosaicOrg?.route() ?? location.hash.slice(1); return r.startsWith('/chat') && !(window.MosaicOrg && r.split('?')[0] === '/chat'); };
const projectPath = id => legacyRoute() ? `#/chat/projects/${id}` : `${orgBase}/projects/${id}`;
const threadPath = id => legacyRoute() ? `#/chat/threads/${id}` : `${orgBase}/projects/threads/${id}`;
const roomPath = id => legacyRoute() ? `#/chat/rooms/${id}` : `${orgBase}/projects/rooms/${id}`;
const link = (type, id, label) => UUID.test(id) ? `<a href="${type === 'projects' ? projectPath(id) : threadPath(id)}">${txt(label)}</a>` : txt(label);
const heading = text => `<h1 tabindex="-1">${txt(text)}</h1>`;
// A pane's title is its own header; the page keeps its one h1.
const heading = text => pane ? `<p class="chat-pane-state"><strong>${txt(text)}</strong></p>` : `<h1 tabindex="-1">${txt(text)}</h1>`;
const selectedInactive = () => { const s = current?.sessions?.find(r => r.id === current.session); return !!s?.state && s.state !== 'active'; };
const disabledSession = pending => disabled(pending || selectedInactive());
const disabled = pending => !current.canSend || current.orgArchived || out() || pending ? ' disabled' : '';
@@ -199,7 +213,8 @@
return `<div class="chat-library"><p role="status">${parts.join(' · ')}</p>${list}</div>`;
}
async function loadLibrary(project, g, signal) {
if (project === null) return;
// The library routes read the page's organization, not a pane's: a pane shows no library line.
if (project === null || pane) return;
let entry;
try {
const res = await fetch('/api/library/status?project=' + encodeURIComponent(project), { cache: 'no-store', redirect: 'manual', signal });
@@ -241,6 +256,8 @@
const REQUEST_ROWS = 3;
// The request panel, Files and summary each read independently. Share only confirmed
// request-not-found responses while a thread is open, without changing other fetch paths.
// Panes mount no request panels, so only the page's instance wraps fetch.
if (!pane) {
const fetchPage = window.fetch.bind(window);
window.fetch = async (url, init) => {
const path = typeof url === 'string' && /^\/api\/requests\/([A-Za-z0-9][A-Za-z0-9._-]{0,159})(?:\/workspace)?$/.exec(url);
@@ -260,11 +277,12 @@
}
return response;
};
}
// A request read elsewhere on this page (any requests.js panel) proves the id now exists, so
// every open thread forgets that miss and the next refresh reads it again. The id's own
// generation also advances, so a 404 still in flight from before this observation cannot
// record the miss after it. Only that id moves; other ids' slow misses still settle.
document.addEventListener('mosaic-request-state', event => {
on('mosaic-request-state', event => {
const id = event.detail?.state?.request;
if (typeof id !== 'string' || out()) return;
for (const s of states.values()) {
@@ -274,7 +292,7 @@
});
function requestRows(rows) {
const ids = new Set();
if (!window.MosaicRequests || !roomOwner()) return ids;
if (pane || !window.MosaicRequests || !roomOwner()) return ids;
for (let i = rows.length - 1; i >= 0 && ids.size < REQUEST_ROWS; i--) {
const m = rows[i];
if (m.from_role === 'human' && typeof m.request === 'string' && REQUEST_ID.test(m.request)) ids.add(m.id);
@@ -286,7 +304,7 @@
const withRequest = requestRows(s.rows);
const receipt = s.receipt;
const project = current.projects.find(p => p.id === t.project);
const redesigned = project && roomOwner() && window.MosaicProjects && (!legacyRoute() || current.path?.startsWith('/projects'));
const redesigned = !pane && project && roomOwner() && window.MosaicProjects && (!legacyRoute() || current.path?.startsWith('/projects'));
// Keep each request tied to its originating message while placing its card after the first reply.
const mountsAfter = new Map();
if (redesigned) s.rows.forEach((m, i) => {
@@ -297,9 +315,11 @@
});
const mount = m => `<div class="request-mount" data-request="${esc(m.request)}" data-origin-message="${esc(m.id)}"></div>`;
const messages = s.rows.map((m, i) => `<li class="${m.from_role === 'human' ? 'chat-message-human' : 'chat-message-agent'}" data-message="${esc(m.id)}"><div class="chat-message-meta"><span class="chat-avatar" aria-hidden="true">${txt(String(m.from_role || '?').slice(0, 1).toUpperCase())}</span><strong>${txt(m.from_role === 'human' ? 'You' : m.from_role)}</strong> ${stamp(m.at)}</div>${messageBody(m)}${!redesigned && withRequest.has(m.id) ? mount(m) : ''}</li>${redesigned ? (mountsAfter.get(i) || []).map(origin => `<li class="project-request-item">${mount(origin)}</li>`).join('') : ''}`).join('');
const frame = redesigned ? window.MosaicProjects.header(project, 'conversations', current.threads, t.name, true) : heading(t.name);
const details = redesigned ? `<dialog class="chat-details project-dialog" id="project-conversation-dialog" aria-labelledby="project-conversation-title"><h2 id="project-conversation-title" tabindex="-1">Conversation details</h2><button class="btn" type="button" data-dialog-close>Close</button>${sessionControls(t)}${sharing(t)}<p>Reading never wakes the assistant. An accepted message is not an answer.</p>${threadWrites() ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : ''}</dialog>` : `<details class="chat-details"><summary id="chat-details-toggle">Conversation details</summary>${sessionControls(t)}${sharing(t)}</details><p class="muted">Reading never wakes the assistant. An accepted message is not an answer.</p>${threadWrites() ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : ''}`;
return `<section class="chat-conversation${redesigned ? ' project-chat' : ''}" data-project="${esc(t.project)}" data-thread="${esc(t.id)}" data-session="${esc(current.session)}"><p>${link('projects', t.project, current.projects.find(p => p.id === t.project)?.name ?? 'Project')} / ${txt(t.instance)}</p>${frame}${libraryLine(libraryOf(current, t))}${details}${redesigned ? '<p class="small muted" data-conversation-request-status></p>' : ''}<ol class="chat-log" tabindex="0" aria-label="Thread conversation">${messages || (current.readFailed ? '<li class="muted">Messages unavailable.</li>' : '<li class="muted">No messages yet.</li>')}</ol><div class="chat-paging">${current.readFailed ? '<button type="button" class="btn" data-chat-retry>Read again</button>' : s.more ? '<p>Showing earlier history. Read forward to reach the current conversation.</p><button class="btn" type="button" id="chat-next">Read next messages</button>' : '<p class="muted">Caught up to the last read.</p>'}<button class="btn" type="button" id="chat-new"${s.follow ? ' hidden' : ''}>New messages — go to end</button></div>${threadWrites() ? `<form id="chat-send-form"><label for="chat-body">Message ${txt(t.instance)}</label><textarea id="chat-body" rows="4" placeholder="${redesigned ? `Message ${esc(t.instance)}` : 'Write a message…'}"${disabledSession(s.pending)}>${esc(s.draft)}</textarea><p class="chat-audience">To: ${redesigned ? `<span class="room-chip" aria-label="Recipient ${esc(t.instance)}">${txt(t.instance)}</span>` : `${txt(t.instance)} · Private conversation`}</p>${redesigned ? '<p class="project-composer-hint">Enter adds a new line.</p>' : ''}<button class="btn primary" type="submit"${disabledSession(s.pending || current.channelDisabled)}>Send</button></form>` : ''}<p id="chat-receipt" role="status">${txt(receipt)}</p>${redesigned ? '' : '<section class="chat-files"><h2>Files</h2><div data-chat-files>Files unavailable.</div></section><div data-chat-summary></div>'}</section>`;
const frame = pane ? '' : redesigned ? window.MosaicProjects.header(project, 'conversations', current.threads, t.name, true) : heading(t.name);
// A pane leaves out the details: sessions and sharing are unavailable on an organization Console.
const resume = threadWrites() ? `<button class="btn${pane ? ' pane-resume' : ''}" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : '';
const details = pane ? `<p class="muted small">Reading never wakes the assistant. An accepted message is not an answer.</p>` : redesigned ? `<dialog class="chat-details project-dialog" id="project-conversation-dialog" aria-labelledby="project-conversation-title"><h2 id="project-conversation-title" tabindex="-1">Conversation details</h2><button class="btn" type="button" data-dialog-close>Close</button>${sessionControls(t)}${sharing(t)}<p>Reading never wakes the assistant. An accepted message is not an answer.</p>${threadWrites() ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : ''}</dialog>` : `<details class="chat-details"><summary id="chat-details-toggle">Conversation details</summary>${sessionControls(t)}${sharing(t)}</details><p class="muted">Reading never wakes the assistant. An accepted message is not an answer.</p>${threadWrites() ? `<button class="btn" type="button" id="chat-resume"${disabledSession(s.pending || current.channelDisabled)}>Resume assistant</button>` : ''}`;
return `<section class="chat-conversation${redesigned ? ' project-chat' : ''}" data-project="${esc(t.project)}" data-thread="${esc(t.id)}" data-session="${esc(current.session)}">${pane ? '' : `<p>${link('projects', t.project, current.projects.find(p => p.id === t.project)?.name ?? 'Project')} / ${txt(t.instance)}</p>`}${frame}${libraryLine(libraryOf(current, t))}${details}${redesigned ? '<p class="small muted" data-conversation-request-status></p>' : ''}<ol class="chat-log" tabindex="0" aria-label="Thread conversation">${messages || (current.readFailed ? '<li class="muted">Messages unavailable.</li>' : '<li class="muted">No messages yet.</li>')}</ol><div class="chat-paging">${current.readFailed ? '<button type="button" class="btn" data-chat-retry>Read again</button>' : s.more ? '<p>Showing earlier history. Read forward to reach the current conversation.</p><button class="btn" type="button" id="chat-next">Read next messages</button>' : '<p class="muted">Caught up to the last read.</p>'}<button class="btn" type="button" id="chat-new"${s.follow ? ' hidden' : ''}>New messages — go to end</button></div>${threadWrites() ? `<form id="chat-send-form"><label for="chat-body">Message ${txt(t.instance)}</label><textarea id="chat-body" rows="4" placeholder="${redesigned ? `Message ${esc(t.instance)}` : 'Write a message…'}"${disabledSession(s.pending)}>${esc(s.draft)}</textarea><p class="chat-audience">To: ${redesigned ? `<span class="room-chip" aria-label="Recipient ${esc(t.instance)}">${txt(t.instance)}</span>` : `${txt(t.instance)} · Private conversation`}</p>${redesigned ? '<p class="project-composer-hint">Enter adds a new line.</p>' : ''}<button class="btn primary" type="submit"${disabledSession(s.pending || current.channelDisabled)}>Send</button></form>` : ''}<p id="chat-receipt" role="status">${txt(receipt)}</p>${pane ? resume : ''}${redesigned || pane ? '' : '<section class="chat-files"><h2>Files</h2><div data-chat-files>Files unavailable.</div></section><div data-chat-summary></div>'}</section>`;
}
// C2-10c: rooms reuse the same state, renderer and generation fences as threads.
const ROOM_LINES = Object.freeze({
@@ -475,19 +495,20 @@
if (err.code === 'channel-disabled' && current?.key === c.key) current.channelDisabled = true;
} finally { s.pending = false; if (current?.key === c.key && !out()) paint(); }
}
document.addEventListener('keydown', event => {
if (current?.kind !== 'room' || event.target.id !== 'chat-room-body' || !current.completion?.items.length) return;
on('keydown', event => {
if (!mine(event.target)) return;
if (current?.kind !== 'room' || idOf(event.target) !== 'chat-room-body' || !current.completion?.items.length) return;
const c = current.completion;
if (['ArrowDown', 'ArrowUp'].includes(event.key)) { event.preventDefault(); c.index = (c.index + (event.key === 'ArrowDown' ? 1 : c.items.length - 1)) % c.items.length; drawRoomCompletion(); }
if (['Enter', 'Tab'].includes(event.key)) { event.preventDefault(); completeRoom(c.items[c.index].instance); }
if (event.key === 'Escape') { event.preventDefault(); current.completion = null; drawRoomCompletion(); }
});
document.addEventListener('mousedown', event => { if (event.target.closest?.('[data-room-complete]')) event.preventDefault(); });
on('mousedown', event => { if (event.target.closest?.('[data-room-complete]')) event.preventDefault(); });
function capture() {
if (!current) return null;
const active = document.activeElement, log = current.container.querySelector('.chat-log');
const field = active?.id?.startsWith('chat-') ? { id: active.id, start: active.selectionStart, end: active.selectionEnd } : null;
const field = idOf(active).startsWith('chat-') && current.container.contains(active) ? { id: active.id, start: active.selectionStart, end: active.selectionEnd } : null;
const dialog = current.container.querySelector('dialog.project-dialog[open]');
const dialogValues = dialog ? [...dialog.querySelectorAll('input[id],select[id],textarea[id]')].map(e=>({id:e.id,value:e.value,checked:e.checked})) : [];
const dialogFocus = dialog?.contains(active) ? { id:active.id, index:[...dialog.querySelectorAll('button,a,input,select,textarea,[tabindex]')].indexOf(active), value:'value' in active ? active.value : null, start:active.selectionStart, end:active.selectionEnd } : null;
@@ -512,7 +533,7 @@
// Refreshes often read exactly the same view. Remember the generated presentation,
// not the mutable DOM (which also contains independently mounted request controls).
function refreshProjectData(c, redesigned, restore) {
if (c.user || c.tester || !window.MosaicProjects) return;
if (pane || c.user || c.tester || !window.MosaicProjects) return;
const project = c.projects.find(p => p.id === c.id);
const projectContent = c.container.querySelector('[data-project-content]');
if (redesigned && (c.kind === 'project' || c.kind === 'thread' || c.kind === 'room')) {
@@ -526,6 +547,7 @@
// visible view is unchanged: a request's phase moves without a new message. A quiet reread
// keeps the present content until a changed result arrives.
function refreshRequestData(c, quiet) {
if (pane) return;
window.MosaicRequests?.mount?.(c.container, { archiveUnknown: !!c.archiveUnknown, projectArchived: !!c.projectArchived });
const t = c.kind === 'thread' ? c.thread : null;
const repo = c.kind === 'project' ? c.projects.find(p => p.id === c.id)?.repo : libraryOf(c, t);
@@ -562,7 +584,7 @@
});
for (let i = 0; i < desired.length; i++) if (liveLog.children[i] !== desired[i]) liveLog.insertBefore(desired[i], liveLog.children[i] || null);
while (liveLog.children.length > desired.length) liveLog.lastElementChild.remove();
window.MosaicRequests?.mount?.(c.container, { archiveUnknown: !!c.archiveUnknown, projectArchived: !!c.projectArchived });
if (!pane) window.MosaicRequests?.mount?.(c.container, { archiveUnknown: !!c.archiveUnknown, projectArchived: !!c.projectArchived });
const s = state(c.key ?? c.id);
if (s.tailRequested || s.follow && ((keep?.tail ?? true) || keep?.settlingPin)) pinTranscript(liveLog);
else if (keep?.top !== undefined) { if (pageFlow(liveLog)) window.scrollTo(0, keep.top); else liveLog.scrollTop = keep.top; }
@@ -604,8 +626,8 @@
function paint(navigated = false, read = false) {
if (!current || out()) return;
const keep = capture(), c = current;
const redesigned = (!legacyRoute() || c.path?.startsWith('/projects')) && !!window.MosaicProjects && !c.user && !c.tester;
let html = '<div class="chat-area"><p><a href="#/projects">Projects</a></p>';
const redesigned = !pane && (!legacyRoute() || c.path?.startsWith('/projects')) && !!window.MosaicProjects && !c.user && !c.tester;
let html = pane ? '<div class="chat-area">' : '<div class="chat-area"><p><a href="#/projects">Projects</a></p>';
if (c.orgArchived) html += `<p role="status">${c.orgArchived === 'room-not-open' ? 'This room is not open.' : 'This organization is archived.'} Sending is unavailable; your draft is kept.</p>`;
if (c.error && !(c.kind === 'room' && c.error === ROOM_LINES['room-not-open'] && redesigned)) html += `<p class="chat-error banner err" role="alert">${txt(c.error)}</p>`;
if (c.archiveUnknown && !c.loading) html += '<p role="status" data-archive-notice>Archive status unavailable. Some changes are unavailable; sending may be refused; refresh to check.</p>';
@@ -635,8 +657,10 @@
} else {
html += heading('Projects') + '<p>Projects and their conversations.</p><div class="chat-projects">' + c.projects.map(p => `<section class="panel"><h2>${link('projects', p.id, p.name)}</h2>${p.repo ? `<p class="muted">Repository: ${txt(p.repo)}</p>` : ''}${threads(c.threads.filter(t => t.project === p.id && !t.shared))}</section>`).join('') + (c.projects.length ? '' : c.readFailed ? '<p>Projects unavailable.</p>' : '<p>No projects yet.</p>') + '</div><h2>Shared with me</h2>' + threads(c.threads.filter(t => t.shared)) + creation('project', 'projects');
}
if (!c.canSend) html += window.MosaicOrgBusStopped ? '<p class="muted">The bus is stopped. Use Start the bus on Settings → Organizations to send messages.</p>' : '<p class="muted">Creating and sending require signed-in send mode. This Console only reads.</p>';
if (!c.canSend && pane) html += '<p class="muted">Sending is unavailable in this organization. This thread only reads.</p>';
else if (!c.canSend) html += window.MosaicOrgBusStopped ? '<p class="muted">The bus is stopped. Use Start the bus on Settings → Organizations to send messages.</p>' : '<p class="muted">Creating and sending require signed-in send mode. This Console only reads.</p>';
html += '</div>';
if (pane) html = html.replace(/\b(id|for|aria-controls|aria-describedby|aria-labelledby)="chat-/g, `$1="${env.prefix}`);
// Drafts already live in the focused textarea; their changing text is not a
// reason for a background read to replace the control.
const fingerprint = visualKey(html);
@@ -690,13 +714,13 @@
// which names the project as the organization file does: the chat project's repo key.
if (remote && roomOwner() && window.MosaicOrg && typeof window.MosaicProjectRepo?.mount === 'function') window.MosaicProjectRepo.mount({ container: remote, project: project?.repo ?? null, archived: !!c.projectArchived });
else if (remote && roomOwner() && typeof window.MosaicProjectRemote?.mount === 'function') { remote.replaceChildren(); window.MosaicProjectRemote.mount({ container: remote, projectId: c.id, repositoryKey: project?.repo ?? null, projectArchived: !!c.projectArchived, preserve: true }); }
if (!window.MosaicOrg && (!redesigned || c.kind !== 'project' || c.settings || c.projectArchived)) window.MosaicProjectArchive?.mount(c.container, c);
if (!pane && !window.MosaicOrg && (!redesigned || c.kind !== 'project' || c.settings || c.projectArchived)) window.MosaicProjectArchive?.mount(c.container, c);
if (redesigned && c.kind === 'project' && c.projectArchived && !c.settings) {
const controls = c.container.querySelector('.project-archive-control');
if (controls) c.container.querySelector('.project-tabs')?.insertAdjacentElement('afterend', controls);
}
refreshProjectData(c, redesigned, !navigated ? keep : null);
document.title = `${c.container.querySelector('h1')?.textContent ?? 'Chat'} · Mosaic Console`;
if (!pane) document.title = `${c.container.querySelector('h1')?.textContent ?? 'Chat'} · Mosaic Console`;
if (!navigated && keep?.toggles) [...c.container.querySelectorAll('.project-new-conversation,.project-create')].forEach((e,i)=>{e.open=!!keep.toggles[i];});
const details = c.container.querySelector('.chat-details');
if (details && keep?.detailsOpen && details.tagName === 'DETAILS') details.open = true;
@@ -736,7 +760,7 @@
f.focus({ preventScroll: true });
if (keep.field.start != null && typeof f.setSelectionRange === 'function') f.setSelectionRange(keep.field.start, keep.field.end);
}
} else if (navigated) c.container.querySelector('h1')?.focus({ preventScroll: true });
} else if (navigated && !pane) c.container.querySelector('h1')?.focus({ preventScroll: true });
updateRoomCompletion();
}
function readError(err) {
@@ -773,8 +797,8 @@
// server paths lack archive guards, and the request panel's writes.
const withdraw = () => {
lastPaint = null;
for (const el of container.querySelectorAll('#chat-session-form input, #chat-session-form button, #chat-share-form input, #chat-share-form button, [data-unshare], #chat-cancel, [data-revert]')) el.disabled = true;
window.MosaicRequests?.mount?.(container, { archiveUnknown: !!current.archiveUnknown, projectArchived: !!current.projectArchived });
for (const el of container.querySelectorAll(['chat-session-form input', 'chat-session-form button', 'chat-share-form input', 'chat-share-form button', 'chat-cancel'].map(x => '#' + pid(x)).concat('[data-unshare]', '[data-revert]').join(', '))) el.disabled = true;
if (!pane) window.MosaicRequests?.mount?.(container, { archiveUnknown: !!current.archiveUnknown, projectArchived: !!current.projectArchived });
if (!current.archiveUnknown) return;
if (container.querySelector('[data-archive-notice]')) return;
const notice = document.createElement('p');
@@ -815,7 +839,8 @@
current.thread = current.threads.find(t => t.id === id);
current.shared = current.thread?.shared === true;
const projectId = kind === 'project' ? id : current.thread?.project;
if (projectId && !current.projects.some(p => p.id === projectId) && !user && !tester) {
// A pane leaves an unlisted project's archive state unknown: the archive lookup reads the page's organization.
if (projectId && !current.projects.some(p => p.id === projectId) && !user && !tester && !pane) {
try {
if (typeof window.MosaicProjectArchive?.resolve !== 'function') throw Error('archive-unavailable');
const resolved = await window.MosaicProjectArchive.resolve(projectId, signal);
@@ -830,7 +855,7 @@
current.archiveUnknown = true;
}
}
else if (projectId) current.archiveUnknown = false;
else if (projectId && (!pane || current.projects.some(p => p.id === projectId))) current.archiveUnknown = false;
current.projectArchived = current.projects.some(p => p.id === projectId && p.archived);
// A same-thread refresh kept the controls of the last resolved (live) state. If this
// lookup now finds the project archived or unknown, withdraw them before the slower
@@ -958,7 +983,7 @@
for (const row of state(current.key).rows) if (row.from_role === 'human' && typeof row.request === 'string' && REQUEST_ID.test(row.request)) ids.add(row.request);
knownRequests.set(projectId, { repo: project.repo, ids });
}
if (project) document.dispatchEvent(new CustomEvent('mosaic-project-context', { detail: { projectId, repositoryKey: project.repo ?? null, thread: kind === 'thread' ? id : null, session: kind === 'thread' ? current.session : null } }));
if (project && !pane) document.dispatchEvent(new CustomEvent('mosaic-project-context', { detail: { projectId, repositoryKey: project.repo ?? null, thread: kind === 'thread' ? id : null, session: kind === 'thread' ? current.session : null } }));
}
paint(navigated, true);
const t = kind === 'thread' ? current.threads.find(t => t.id === id) : null;
@@ -988,17 +1013,17 @@
}
}
function refresh(next = false) {
if (current) return render({ ...current, path: (window.MosaicOrg?.route() ?? location.hash.slice(1)).split('?')[0], next });
if (current) return render({ ...current, path: pane ? current.path : (window.MosaicOrg?.route() ?? location.hash.slice(1)).split('?')[0], next });
}
function leave(path) {
if (!path.startsWith('/chat') && !path.startsWith('/projects')) { generation++; controller?.abort(); current = null; }
}
document.addEventListener('input', event => {
if (!current || out()) return;
if (event.target.id === 'chat-room-body') { state(current.key).draft = event.target.value; updateRoomCompletion(); return; }
if (event.target.id === 'chat-operation') { const f = form('clear:' + current.key); if (f.pending) return; f.op = event.target.value; f.record = null; const button = document.getElementById('chat-cancel'); if (button) button.disabled = !current.canSend || current.archiveUnknown || current.projectArchived || f.pending || !f.op; }
if (event.target.id === 'chat-share-target') form('share:' + current.id).to = event.target.value;
if (event.target.id === 'chat-body') state(current.key ?? current.id).draft = event.target.value;
on('input', event => {
if (!current || out() || !mine(event.target)) return;
if (idOf(event.target) === 'chat-room-body') { state(current.key).draft = event.target.value; updateRoomCompletion(); return; }
if (idOf(event.target) === 'chat-operation') { const f = form('clear:' + current.key); if (f.pending) return; f.op = event.target.value; f.record = null; const button = byId('chat-cancel'); if (button) button.disabled = !current.canSend || current.archiveUnknown || current.projectArchived || f.pending || !f.op; }
if (idOf(event.target) === 'chat-share-target') form('share:' + current.id).to = event.target.value;
if (idOf(event.target) === 'chat-body') state(current.key ?? current.id).draft = event.target.value;
const f = event.target.closest('.chat-create');
if (f && event.target.dataset.chatField) {
const draft = form(f.dataset.key), field = event.target.dataset.chatField;
@@ -1010,7 +1035,7 @@
// User input cancels a pending page pin, including scrollbar dragging.
// Tab counts from any target: it moves focus and can scroll the document.
const readerInput = event => {
if (!['thread', 'room'].includes(current?.kind)) return;
if (!['thread', 'room'].includes(current?.kind) || !mine(event.target)) return;
if (event.type === 'keydown' && event.key !== 'Tab' && (!['ArrowUp', 'ArrowDown', 'PageUp', 'PageDown', 'Home', 'End', ' '].includes(event.key) || event.target.closest?.('input, textarea, select, button, a, [contenteditable=true]'))) return;
if (event.type === 'pointerdown' && event.target !== document.documentElement && event.target !== document.body && !event.target.matches?.('.chat-log')) return;
const log = current.container.querySelector('.chat-log');
@@ -1024,8 +1049,8 @@
}
else if (event.key === 'Tab' || event.target === log || log.contains(event.target)) { pinnedScrolls.delete(log); settlingPins.delete(log); }
};
for (const type of ['wheel', 'touchstart', 'pointerdown', 'keydown']) document.addEventListener(type, readerInput, true);
document.addEventListener('scroll', event => {
for (const type of ['wheel', 'touchstart', 'pointerdown', 'keydown']) on(type, readerInput, true);
on('scroll', event => {
if (!['thread', 'room'].includes(current?.kind)) return;
const log = current.container.querySelector('.chat-log');
if (!log) return;
@@ -1110,25 +1135,25 @@
if (!out() && current && (isThread ? (current.key ?? current.id) === key : (action === 'createSession' ? current.id === targetThread : key === 'projects' ? current.kind === 'list' : current.id === key))) paint();
}
}
document.addEventListener('submit', event => {
if (!current || !event.target.id.startsWith('chat-')) return;
on('submit', event => {
if (!current || !mine(event.target) || !idOf(event.target).startsWith('chat-')) return;
event.preventDefault();
if (event.target.id === 'chat-room-send-form') {
if (idOf(event.target) === 'chat-room-send-form') {
void sendRoom();
} else if (event.target.id === 'chat-share-form') {
} else if (idOf(event.target) === 'chat-share-form') {
void changeShare('share', form('share:' + current.id).to ?? '');
} else if (event.target.id === 'chat-send-form') {
} else if (idOf(event.target) === 'chat-send-form') {
const id = current.id, session = current.session, key = current.key;
void write('send', key, { body: state(key).draft, ...(session ? { session } : {}) }, `threads/${id}/messages`);
} else if (event.target.id === 'chat-session-form') {
} else if (idOf(event.target) === 'chat-session-form') {
const key = 'session:' + current.id, f = form(key);
// Keep an ambiguous create's key and payload; editing requires a deliberate new attempt.
f.op ??= opId();
f.payload ??= { name: f.name, op: f.op };
void write('createSession', key, f.payload, `threads/${current.id}/sessions`);
} else if (event.target.id === 'chat-operation-form') {
} else if (idOf(event.target) === 'chat-operation-form') {
const clear = form('clear:' + current.key);
clear.op = document.getElementById('chat-operation').value;
clear.op = byId('chat-operation').value;
void checkClear(current.id, current.key, clear);
} else if (event.target.classList.contains('chat-create')) {
const key = event.target.dataset.key, f = form(key), project = key === 'projects';
@@ -1137,9 +1162,9 @@
void write(project ? 'createProject' : 'createThread', key, value, project ? 'projects' : 'threads');
}
});
document.addEventListener('click', event => {
if (!current || out()) return;
if (event.target.id === 'chat-room-open' || event.target.closest?.('[data-room-open-inline]')) void openRoom();
on('click', event => {
if (!current || out() || !mine(event.target)) return;
if (idOf(event.target) === 'chat-room-open' || event.target.closest?.('[data-room-open-inline]')) void openRoom();
const projectRoomOpen=event.target.closest?.('[data-project-room-open]'); if(projectRoomOpen && UUID.test(projectRoomOpen.dataset.projectRoomOpen)) void openRoom(projectRoomOpen.dataset.projectRoomOpen);
const chip = event.target.closest?.('[data-room-chip]');
if (chip) { const name = chip.dataset.roomChip; document.querySelector(`[data-room-member="${CSS.escape(name)}"]`)?.click(); document.querySelector(`[data-room-chip="${CSS.escape(name)}"]`)?.focus(); }
@@ -1154,16 +1179,17 @@
const option = event.target.closest?.('[data-room-complete]');
if (option) completeRoom(option.dataset.roomComplete);
if (event.target.dataset.unshare) void changeShare('unshare', event.target.dataset.unshare);
if (event.target.id === 'chat-resume') void write('open', current.key, current.session ? { session: current.session } : {}, `threads/${current.id}/open`);
if (event.target.id === 'chat-cancel') void cancelClear();
if (event.target.id === 'chat-clear') void clearContext();
if (event.target.id === 'chat-next') void refresh(true);
if (idOf(event.target) === 'chat-resume') void write('open', current.key, current.session ? { session: current.session } : {}, `threads/${current.id}/open`);
if (idOf(event.target) === 'chat-cancel') void cancelClear();
if (idOf(event.target) === 'chat-clear') void clearContext();
if (idOf(event.target) === 'chat-next') void refresh(true);
if (event.target.closest?.('[data-chat-retry]')) void refresh();
const revertButton = event.target.closest?.('[data-revert]');
if (revertButton) void revert(revertButton.dataset.revert);
if (event.target.id === 'chat-new') { state(current.key ?? current.id).tailRequested = true; state(current.key ?? current.id).follow = true; paint(); }
if (idOf(event.target) === 'chat-new') { state(current.key ?? current.id).tailRequested = true; state(current.key ?? current.id).follow = true; paint(); }
});
document.addEventListener('change', event => {
on('change', event => {
if (!mine(event.target)) return;
if (event.target.matches?.('[data-room-member]') && current?.kind === 'room') {
const field = document.getElementById('chat-room-body'), s = state(current.key);
const parsed = roomAddress(field.value);
@@ -1175,7 +1201,7 @@
s.draft = chosen.map(name => '@' + name).join(' ') + (parsed.body ? ' ' + parsed.body : ' ');
s.receipt = ''; paint(); return;
}
if (event.target.id === 'chat-session' && current && UUID.test(event.target.value)) {
if (idOf(event.target) === 'chat-session' && current && UUID.test(event.target.value)) {
location.hash = sessionPath(current.id, event.target.value);
}
});
@@ -1246,7 +1272,23 @@
if (!out() && current?.key === key) { await refresh(); paint(); }
}
}
document.addEventListener('mosaic-signed-out', () => { signedOut = true; forget(); });
on('mosaic-signed-out', () => { signedOut = true; forget(); });
const hasDraft = () => [...states.values()].some(s => Boolean(s.draft?.trim())) || [...forms.values()].some(f => Boolean(f.name?.trim() || f.repo || f.instanceChosen));
window.MosaicChat = Object.freeze({ render, leave, forget, projectPath, hasDraft });
// Ends a pane instance: its listeners, reads and observers stop and its container is left as is.
function dispose() {
life.abort(); generation++; controller?.abort(); transcriptObserver?.disconnect(); transcriptResize?.disconnect();
current = null; lastPaint = null;
}
return { render, leave, forget, refresh, projectPath, hasDraft, dispose };
}
const main = chatInstance();
const ORG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
let panes = 0;
// An Assistant pane: one thread of one organization, read and sent through that organization's own routes.
function pane(org) {
if (typeof org !== 'string' || !ORG.test(org)) throw new TypeError('pane needs an organization id');
const chat = chatInstance({ org, prefix: `chat-p${++panes}-` });
return Object.freeze({ render: chat.render, refresh: chat.refresh, dispose: chat.dispose, hasDraft: chat.hasDraft });
}
window.MosaicChat = Object.freeze({ render: main.render, leave: main.leave, forget: main.forget, projectPath: main.projectPath, hasDraft: main.hasDraft, pane });
})();
+1 -1
View File
@@ -21,7 +21,7 @@
.then(r => (r.type === 'opaqueredirect' ? null : r.ok ? r.json() : null));
const ready = readConfig().then(c => { config = c; boot = typeof c?.boot === 'string' ? c.boot : null; return c; }).catch(() => null);
const dirty = () => !!(window.MosaicChat?.hasDraft?.() || window.MosaicOrgCreate?.hasDraft?.()
const dirty = () => !!(window.MosaicChat?.hasDraft?.() || window.MosaicAssistant?.hasDraft?.() || window.MosaicOrgCreate?.hasDraft?.()
|| document.querySelector('.settings-dot')
|| [...document.querySelectorAll('#reply, #conv-reply, #doc-source, #send-body')].some(el => !!el.value?.trim()));
+137 -66
View File
@@ -1,60 +1,72 @@
window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(value).toLocaleString() : 'unknown';
// An organization switch reloads the page, which drops every per-page cache and
// subscription. Requests already sent keep the organization captured here.
// #1873 SP1: one shell for the whole system. `#/dashboard` is the system landing route and
// `#/orgs/<id>/...` is a route inside the same page, not a mode: opening another organization
// changes the scope of later /api reads and fires `mosaic-org-switch`. Nothing reloads.
// Requests already sent keep the organization they were sent with.
(() => {
const nativeFetch = window.fetch.bind(window);
const match = /^#\/orgs\/([^/]+)(\/.*)?$/.exec(location.hash);
const id = match?.[1] ?? null;
if (!id) {
if (!document.documentElement.hasAttribute('data-organizations')) return;
const readInitialOrganizations = () => nativeFetch('/api/orgs', { cache: 'no-store', redirect: 'manual' }).then(async r => {
if (r.ok) { window.MosaicOrganizationError = null; return r.json(); }
const body = await r.json().catch(() => ({}));
window.MosaicOrganizationError = body.message || 'Organization registry could not be read';
return null;
}).catch(() => { window.MosaicOrganizationError = 'Organization registry could not be read'; return null; });
const refreshInitial = () => {
const initialOrganizations = window.MosaicInitialOrganizations = readInitialOrganizations();
initialOrganizations.then(async rows => {
if (!Array.isArray(rows) || !rows.length || location.hash.startsWith('#/orgs/')) return;
rows = rows.filter(row => !row.invalid);
if (!rows.length) return;
let preferred;
try { preferred = (await (await nativeFetch('/api/config', { cache: 'no-store', redirect: 'manual' })).json()).preselect; } catch { /* first authorized organization */ }
const selected = rows.find(row => row.id === preferred) ?? rows[0];
const tail = location.hash.startsWith('#/') ? location.hash.slice(1) : '/';
history.replaceState(null, '', `#/orgs/${encodeURIComponent(selected.id)}${tail}`);
location.reload();
}).catch(() => {});
return initialOrganizations;
};
window.MosaicRefreshOrganizations = refreshInitial;
refreshInitial();
return;
}
const route = () => location.hash.replace(/^#\/orgs\/[^/]+/, '') || '/';
const orgOf = hash => /^#\/orgs\/([^/]+)/.exec(hash)?.[1] ?? null;
const atLoad = orgOf(location.hash);
if (!atLoad && !document.documentElement.hasAttribute('data-organizations')) return;
// current: the scoping organization as its hash segment. settled: false only while the first
// list read picks one for an address that names none. With no valid organization at all the
// page stays in its first-run mode (window.MosaicOrg reads undefined), as before.
let current = atLoad, settled = !!atLoad, markReady;
const ready = new Promise(resolve => { markReady = resolve; });
const settle = seg => { current = seg; settled = true; markReady(seg ? decodeURIComponent(seg) : null); };
// An address that names its organization is settled at load: anything waiting on ready goes on.
if (atLoad) markReady(decodeURIComponent(atLoad));
const tail = hash => { const m = /^#\/orgs\/[^/]+(.*)$/.exec(hash); return m ? (m[1] || '/') : hash.startsWith('#/') ? hash.slice(1) : '/'; };
const route = () => tail(location.hash);
// The bare address and the old per-organization dashboard address are the system dashboard;
// an organization page without the prefix gets the current organization's. #1873 SP2: an
// organization's own bare address (#/orgs/<id>, no trailing slash) is that organization's page;
// #/orgs/<id>/ stays the old dashboard address. SP3: `#/inbox` is a system route too (every
// organization's items); `#/orgs/<id>/inbox` is that list, filtered. SP5: `#/agents` is every
// organization's agents; `#/orgs/<id>/agents` is that table for one organization. SP4: `#/tasks` is
// one task board for every organization; `#/orgs/<id>/tasks` is that board, scoped to one.
// SP6: `#/assistant` is the Assistant page, threads of any organization side by side.
const system = hash => { const bare = tail(hash).split('?')[0]; return bare === '/dashboard' || (!orgOf(hash) && (bare === '/inbox' || bare === '/agents' || bare === '/tasks' || bare === '/assistant')); };
const normalize = (hash, seg = current) => {
const path = tail(hash), bare = path.split('?')[0], named = /^#\/orgs\/([^/?]+)$/.exec(hash.split('?')[0])?.[1];
if (named) return `#/orgs/${named}/organization${hash.slice(hash.split('?')[0].length)}`;
if (bare === '/' || bare === '/dashboard') return `#/dashboard${path.slice(bare.length)}`;
return orgOf(hash) || !seg || system(hash) ? hash : `#/orgs/${seg}${path}`;
};
// /api/workspace reads and writes across organizations (U1, U4b), so it keeps its own path.
const unscoped = /^\/api\/(?:workspace(?:\/|\?|$)|orgs(?:\/|$)|themes(?:\?|$)|org-template(?:\?|$)|org-presets(?:\?|$)|org-admin(?:\?|$)|org-validate(?:\?|$)|agents\/(?:levels|root)(?:\?|$))/;
window.fetch = (input, init) => {
if (typeof input === 'string' && input.startsWith('/api/') && !/^\/api\/(?:workspace(?:\/|\?|$)|orgs(?:\/|$)|themes(?:\?|$)|org-template(?:\?|$)|org-presets(?:\?|$)|org-admin(?:\?|$)|org-validate(?:\?|$)|agents\/(?:levels|root)(?:\?|$))/.test(input))
input = `/api/orgs/${id}/${input.slice('/api/'.length)}`;
return nativeFetch(input, init);
if (typeof input !== 'string' || !input.startsWith('/api/') || unscoped.test(input)) return nativeFetch(input, init);
const send = () => nativeFetch(current ? `/api/orgs/${current}/${input.slice('/api/'.length)}` : input, init);
return settled ? send() : ready.then(send);
};
// A failed read keeps its reason, so the header can say why the list is empty.
let listError = null;
const readList = () => nativeFetch('/api/orgs', { cache: 'no-store', redirect: 'manual' }).then(async r => {
let listError = null, rowsSeen = [];
const readRows = () => nativeFetch('/api/orgs', { cache: 'no-store', redirect: 'manual' }).then(async r => {
if (r.ok) {
const body = await r.json(); listError = null;
const body = await r.json(); listError = null; window.MosaicOrganizationError = null;
const rows = Array.isArray(body) ? body : [];
// E2E5 review P2: an open panel (Settings > Organizations) follows every fresh list read, not only its own.
document.dispatchEvent(new CustomEvent('mosaic-org-list', { detail: { rows } }));
return rows;
}
const body = await r.json().catch(() => ({}));
listError = typeof body.message === 'string' && body.message ? body.message : 'Organization registry could not be read';
return [];
}).catch(() => { listError = 'Organization registry could not be read'; return []; });
// Idempotent: each read replaces the banner and the wordmark name, and removes them on recovery.
listError = window.MosaicOrganizationError = typeof body.message === 'string' && body.message ? body.message : 'Organization registry could not be read';
return null;
}).catch(() => { listError = window.MosaicOrganizationError = 'Organization registry could not be read'; return null; });
const readList = () => readRows().then(rows => rows ?? []);
// The bus banner belongs to an organization page; the dashboard and the Inbox name every bus themselves.
// #1873 SP2: the organization's own page draws its down banner with the restart action, so this one hides there.
const paintBus = () => {
const banner = document.getElementById('bus-down');
if (!banner) return;
const org = rowsSeen.find(row => current && row.id === decodeURIComponent(current) && !row.invalid), path = route().split('?')[0];
if (system(location.hash) || (path === '/organization' && org?.busHealthy === false) || (banner.dataset.orgBus && org?.busHealthy !== false)) { banner.hidden = true; delete banner.dataset.orgBus; return; }
if (org?.busHealthy === false) { banner.textContent = 'Bus unavailable'; banner.hidden = false; banner.dataset.orgBus = '1'; window.MosaicConsole?.attachBus(banner, 'Restart the bus'); }
};
// Idempotent: each read replaces the banner, and removes it on recovery.
const paintHeader = rows => {
rowsSeen = rows;
document.getElementById('org-list-banner')?.remove();
const lines = [...(listError ? [listError] : []), ...rows.filter(row => row.invalid).map(row => `${row.id}: invalid — ${row.reason}`)];
if (lines.length) {
@@ -62,58 +74,117 @@ window.MosaicLocalTime = value => Number.isFinite(Date.parse(value)) ? new Date(
banner.textContent = lines.join('; ');
document.body.prepend(banner);
}
// The shell no longer names one organization in its wordmark: the breadcrumb does.
document.getElementById('current-organization')?.remove();
const org = rows.find(row => row.id === decodeURIComponent(id) && !row.invalid);
const mark = document.querySelector('.wordmark');
if (mark && org) { const name = document.createElement('span'); name.id = 'current-organization'; name.textContent = ` · ${org.label || org.id}`; mark.append(name); }
if (org?.busHealthy === false) { const banner = document.getElementById('bus-down'); if (banner) { banner.textContent = 'Bus unavailable'; banner.hidden = false; window.MosaicConsole?.attachBus(banner, 'Restart the bus'); } }
paintBus();
window.MosaicBreadcrumbs?.();
return rows;
};
let list = readList().then(paintHeader);
let list;
const refreshList = () => (list = readList().then(paintHeader));
window.MosaicRefreshOrganizations = refreshList;
let previous = location.hash;
const dirty = () => window.MosaicChat?.hasDraft?.() || window.MosaicOrgCreate?.hasDraft?.() || [...document.querySelectorAll('#reply, #conv-reply, #doc-source')].some(el => !!el.value?.trim());
function change(next) {
history.replaceState(null, '', next);
location.reload();
if (atLoad) {
const first = normalize(location.hash);
if (first !== location.hash) history.replaceState(null, '', first);
refreshList();
} else {
const initial = window.MosaicInitialOrganizations = readRows();
list = initial.then(rows => paintHeader(rows ?? []));
initial.then(async rows => {
const valid = Array.isArray(rows) ? rows.filter(row => !row.invalid) : [];
if (!valid.length) return null;
let preferred;
try { preferred = (await (await nativeFetch('/api/config', { cache: 'no-store', redirect: 'manual' })).json()).preselect; } catch { /* first authorized organization */ }
return encodeURIComponent((valid.find(row => row.id === preferred) ?? valid[0]).id);
}).catch(() => null).then(seg => {
settle(orgOf(location.hash) ?? seg);
if (!current) return;
const next = normalize(location.hash);
if (next !== location.hash) history.replaceState(null, '', next);
previous = location.hash; paintBus();
});
}
// From the first-run page (no organization yet) the first one changes the page's mode, which
// still takes one reload. Once an organization is open, a list refresh repaints in place.
window.MosaicRefreshOrganizations = () => {
if (current || !settled) return refreshList();
const read = window.MosaicInitialOrganizations = readRows();
list = read.then(rows => paintHeader(rows ?? []));
read.then(rows => {
const valid = Array.isArray(rows) ? rows.filter(row => !row.invalid) : [];
if (!valid.length || orgOf(location.hash)) return;
history.replaceState(null, '', `#/orgs/${encodeURIComponent(valid[0].id)}${tail(location.hash) === '/' ? '/organization' : tail(location.hash)}`);
location.reload();
});
return read;
};
let previous = location.hash, skipGuard = false;
const dirty = () => window.MosaicChat?.hasDraft?.() || window.MosaicAssistant?.hasDraft?.() || window.MosaicOrgCreate?.hasDraft?.() || [...document.querySelectorAll('#reply, #conv-reply, #doc-source')].some(el => !!el.value?.trim());
// A switch scopes later reads to the new organization; listeners drop what they held for the old one.
function rescope(seg) {
const from = current;
current = seg;
document.dispatchEvent(new CustomEvent('mosaic-org-switch', { detail: { from: from ? decodeURIComponent(from) : null, to: decodeURIComponent(seg) } }));
}
function discard() {
window.MosaicChat?.forget?.();
for (const el of document.querySelectorAll('#reply, #conv-reply, #doc-source')) el.value = '';
}
function confirmSwitch(next) {
const dialog = document.createElement('dialog');
dialog.setAttribute('aria-label', 'Unsaved draft');
dialog.innerHTML = '<p>You have an unsaved draft. Stay here or discard it and continue.</p><button type="button" data-stay>Stay</button> <button type="button" data-discard>Discard</button>';
document.body.append(dialog);
const stay = () => { const picker = document.getElementById('org-picker'); if (picker) picker.value = decodeURIComponent(id); dialog.close(); dialog.remove(); };
const close = () => { dialog.close(); dialog.remove(); };
const stay = () => { const picker = document.getElementById('org-picker'); if (picker && current) picker.value = decodeURIComponent(current); close(); };
dialog.querySelector('[data-stay]').onclick = stay;
dialog.querySelector('[data-discard]').onclick = () => change(next);
dialog.querySelector('[data-discard]').onclick = () => { close(); discard(); skipGuard = true; location.hash = next; };
dialog.addEventListener('cancel', e => { e.preventDefault(); stay(); });
dialog.showModal(); dialog.querySelector('[data-stay]').focus();
}
// Capture phase: this runs before bus.js renders, so a switch is scoped before the page reads.
window.addEventListener('hashchange', event => {
const oldHash = event.oldURL ? new URL(event.oldURL).hash : previous;
let next = location.hash;
if (!next.startsWith('#/orgs/')) { next = `#/orgs/${id}${next.startsWith('#/') ? next.slice(1) : '/'}`; history.replaceState(null, '', next); }
const nextId = /^#\/orgs\/([^/]+)/.exec(next)?.[1];
if ((nextId && nextId !== id) || (next !== oldHash && window.MosaicOrgCreate?.hasDraft?.())) {
const raw = location.hash;
// First run (no organization yet) keeps its own addresses: #/ is its board, not #/dashboard.
// Before the first list read settles, the settle step normalizes whatever address it finds.
if (!settled || !current) { previous = raw; return; }
const seg = orgOf(raw) ?? current, next = normalize(raw, seg);
if (next !== raw) history.replaceState(null, '', next);
const switching = seg !== current;
if (!skipGuard && next !== oldHash && (switching || window.MosaicOrgCreate?.hasDraft?.()) && dirty()) {
event.stopImmediatePropagation();
if (dirty()) { history.replaceState(null, '', oldHash); confirmSwitch(next); } else change(next);
history.replaceState(null, '', oldHash); confirmSwitch(next);
return;
}
previous = next;
skipGuard = false; previous = next;
if (switching) rescope(seg);
paintBus();
}, true);
window.MosaicOrg = Object.freeze({ id: decodeURIComponent(id), route, get list() { return list; }, readList, refreshList, switchTo: next => { location.hash = `#/orgs/${encodeURIComponent(next)}${route()}`; } });
const api = Object.freeze({
get id() { return current ? decodeURIComponent(current) : null; },
// The open organization's name as the last list read gave it, for the breadcrumb.
get label() { const id = current ? decodeURIComponent(current) : null, row = id && rowsSeen.find(r => r.id === id); return id ? (typeof row?.label === 'string' && row.label ? row.label : id) : null; },
ready, route, get list() { return list; }, readList, refreshList,
// SP3: whether this address is a system page (no organization's), for the shell's theme scope.
system: () => system(location.hash),
switchTo: next => { const path = route().split('?')[0]; location.hash = `#/orgs/${encodeURIComponent(next)}${path === '/dashboard' || path === '/' ? '/organization' : route()}`; },
});
Object.defineProperty(window, 'MosaicOrg', { configurable: true, enumerable: true, get: () => (current || !settled ? api : undefined) });
})();
if (document.documentElement.hasAttribute('data-settings-proxy-document') && !location.hash) location.hash = '#/settings/model-proxy';
/* Browser-local sidebar density. No authority or project data is stored here. */
(() => {
const key=window.MosaicOrg ? `mosaic-sidebar-display-v1:${window.MosaicOrg.id}` : 'mosaic-sidebar-display-v1';
// #1873 SP1: the key follows the open organization, read again when it changes.
const key=()=>window.MosaicOrg?.id ? `mosaic-sidebar-display-v1:${window.MosaicOrg.id}` : 'mosaic-sidebar-display-v1';
const defaults=()=>({version:1,density:'comfortable',order:'title-first'});
const valid=x=>x&&x.version===1&&['comfortable','compact'].includes(x.density)&&['title-first','contact-first'].includes(x.order)&&Object.keys(x).sort().join(',')==='density,order,version';
let saved=defaults();
try {const value=JSON.parse(localStorage.getItem(key));if(valid(value))saved=value;} catch {}
const load=()=>{saved=defaults();try {const value=JSON.parse(localStorage.getItem(key()));if(valid(value))saved=value;} catch {}};
const apply=()=>{document.documentElement.dataset.sidebarDensity=saved.density;document.documentElement.dataset.sidebarOrder=saved.order;document.dispatchEvent(new CustomEvent('mosaic-display-change',{detail:{...saved}}));};
apply();
window.MosaicDisplay={get:()=>({...saved}),setDensity(density){if(!['comfortable','compact'].includes(density))return false;saved={...saved,density};apply();try{localStorage.setItem(key,JSON.stringify(saved));return true;}catch{return false;}}};
load();apply();
window.MosaicOrg?.ready?.then(()=>{load();apply();});
document.addEventListener('mosaic-org-switch',()=>{load();apply();});
window.MosaicDisplay={get:()=>({...saved}),setDensity(density){if(!['comfortable','compact'].includes(density))return false;saved={...saved,density};apply();try{localStorage.setItem(key(),JSON.stringify(saved));return true;}catch{return false;}}};
})();
// P4 page: credentials and OAuth state exist only during the current operation.
+2 -2
View File
@@ -6,8 +6,8 @@
<link rel="stylesheet" href="/project-archive.css"><link rel="stylesheet" href="/projects.css">
<link rel="stylesheet" href="/processing.css"><script src="/processing.js" defer></script>
<link rel="stylesheet" href="/org-create.css"><script src="/org-create.js" defer></script>
<link rel="stylesheet" href="/onboarding.css"><script src="/onboarding.js" defer></script><link rel="stylesheet" href="/panes.css">
<script src="/workspace-data.js" defer></script><script src="/workspace.js" defer></script><script src="/tasks-board.js" defer></script><script src="/console-restart.js" defer></script><script src="/display.js" defer></script><script src="/inbox.js" defer></script><script src="/files.js" defer></script><script src="/project-remote.js" defer></script><link rel="stylesheet" href="/autonomy.css"><script src="/autonomy.js" defer></script><link rel="stylesheet" href="/packs.css"><script src="/packs.js" defer></script><script src="/workflows.js" defer></script><script src="/federation.js" defer></script><script src="/brand.js" defer></script><script src="/app.js" defer></script><script src="/markdown-preview.js" defer></script><script src="/projects.js" defer></script><script src="/chat.js" defer></script><script src="/project-archive.js" defer></script><script src="/agents.js" defer></script><script src="/panes.js" defer></script><script src="/bus.js" defer></script><script src="/requests.js" defer></script></head>
<link rel="stylesheet" href="/onboarding.css"><script src="/onboarding.js" defer></script><link rel="stylesheet" href="/assistant.css">
<script src="/workspace-data.js" defer></script><script src="/workspace.js" defer></script><script src="/tasks-board.js" defer></script><script src="/console-restart.js" defer></script><script src="/display.js" defer></script><script src="/inbox.js" defer></script><script src="/files.js" defer></script><script src="/project-remote.js" defer></script><link rel="stylesheet" href="/autonomy.css"><script src="/autonomy.js" defer></script><link rel="stylesheet" href="/packs.css"><script src="/packs.js" defer></script><script src="/workflows.js" defer></script><script src="/federation.js" defer></script><script src="/brand.js" defer></script><script src="/app.js" defer></script><script src="/markdown-preview.js" defer></script><script src="/projects.js" defer></script><script src="/chat.js" defer></script><script src="/project-archive.js" defer></script><script src="/agents.js" defer></script><script src="/assistant.js" defer></script><script src="/bus.js" defer></script><script src="/requests.js" defer></script></head>
<body>
<div hidden aria-hidden="true"><select id="palette"></select><select id="mode"><option value="system">system</option><option value="light">light</option><option value="dim">dim</option><option value="dark">dark</option></select></div>
<a class="skip" href="#main">Skip to content</a>
+4
View File
@@ -17,3 +17,7 @@
:is([data-packs],[data-workflows]) .btn{min-height:44px;margin:4px 8px 4px 0}
:is([data-packs],[data-workflows]) :is(button,select,input,textarea):focus-visible{outline:2px solid var(--focus);outline-offset:2px}
:is([data-packs],[data-workflows]) [role=status]{overflow-wrap:anywhere}
.pack-applied{border-left:3px solid var(--border);padding:4px 0 4px 12px;margin:8px 0}
.pack-applied p{margin:0 0 6px}
.pack-open{list-style:none;margin:6px 0 8px;padding:0}
.pack-open li{padding:4px 0;overflow-wrap:anywhere}
+70 -7
View File
@@ -3,6 +3,10 @@
// pack.preview (POST .../packs/preview, writes nothing) and applies the previewed plan by its digest
// (POST .../packs/apply). The bus builds the plan, the marks, the flagged and credential lines and the
// noHire marks; this page only shows them. Every pack- or organization-supplied string goes through esc.
// Ruling 2026-11-14 ("If I choose a starter pack and apply it, that is a decision!"): the owner's apply
// hires the proposals in the same act. Each pack card says how many agents it hired and lists the
// proposals still open with their reasons; "Hire the N proposed agents" (POST .../packs/hire) runs the
// same hire loop on the recorded entry.
(() => {
'use strict';
const esc = x => String(x ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
@@ -25,7 +29,23 @@
'not-configured': 'This Console has no bus connection for packs.',
'no-bus-host': 'The organization bus is not running.',
'invalid-request': 'The bus refused the request as malformed.',
'pack-not-applied': 'Apply this pack first; its hires come from the applied entry.',
'right-required': 'Hiring needs the org.hire right.',
};
// Why a hire did not happen, by the code the bus recorded. An unknown code is shown as itself.
const HIRE_WHY = {
'pack-hire-route-missing': 'neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Routing',
'no-chief-of-staff': 'the organization has no chief of staff',
'hire-owner-required': 'it has flagged or credential lines only the owner approves',
'definition-not-hireable': 'its role is on the no-hire list',
'starter-pack-proposal-stale': 'the pack changed since it was applied; apply it again',
'human-required': 'only a person can hire',
'organization-busy': 'another pack hire on this organization was running',
'outcome-unknown': 'the bus did not say why',
};
const whyText = code => HIRE_WHY[code] ?? code;
const OPEN_STATE = { 'awaiting-owner': 'waiting for the owner in the inbox', proposed: 'proposed, not hired yet' };
const plainObj = x => x !== null && typeof x === 'object' && !Array.isArray(x);
const MARKS = {
add: 'will be added',
same: 'already the same',
@@ -43,10 +63,11 @@
// pack and the last receipt. A kept preview applies by its digest, so a stale one is refused by the bus.
async function load(org) {
const prev = states.get(org);
const s = { packs: null, writable: false, error: null, projects: null, preview: prev?.preview ?? null, status: prev?.status ?? '', picks: prev?.picks ?? {} };
const s = { packs: null, applied: [], writable: false, error: null, projects: null, preview: prev?.preview ?? null, status: prev?.status ?? '', picks: prev?.picks ?? {} };
try {
const value = await call(`${base(org)}/packs`);
s.packs = Array.isArray(value?.packs) ? value.packs.filter(p => p && typeof p === 'object' && p.pack && typeof p.pack === 'object') : [];
s.applied = Array.isArray(value?.applied) ? value.applied.filter(a => plainObj(a) && typeof a.id === 'string' && Array.isArray(a.hired) && Array.isArray(a.open)) : [];
s.writable = value?.writable === true;
} catch (error) { s.error = error.message; }
// A project pack needs a code project. The workflow read lists them; when it fails, a project pack
@@ -72,7 +93,11 @@
const creds = Array.isArray(h.credentialLines) && h.credentialLines.length
? `<p>Credential lines:</p><ul data-pack-credentials>${h.credentialLines.map(l => `<li><code>${esc(l?.service)}</code>${l?.scope === undefined ? '' : ` ${esc(l.scope)}`}</li>`).join('')}</ul>`
: '<p class="note">No credential lines.</p>';
const mark = h.mark === 'dropped' ? 'Not proposed: an agent or open hire decision already has this name.' : 'Recorded on apply for the chief to raise as a hire decision.';
const hasCreds = Array.isArray(h.credentialLines) && h.credentialLines.length > 0;
const owner = (Array.isArray(h.flagged) && h.flagged.length) || h.flagged === null || hasCreds;
// The binding sentence only where the hire has a credential line to bind.
const mark = h.mark === 'dropped' ? 'Not proposed: an agent or open hire decision already has this name.'
: `Hired when you apply: applying is the hire decision${owner ? ', and approves the flagged and credential lines below' : ''}.${hasCreds ? ' A credential line is approved, not bound: the agent waits for a binding before it launches.' : ''}`;
const noHire = h.noHire ? '<p class="pack-nohire" data-pack-nohire>On this organization\'s no-hire list: the decision will say so.</p>' : '';
return `<li class="pack-hire" data-pack-hire="${esc(h.name)}"><strong>${esc(h.name)}</strong> <span class="muted">role ${esc(h.definition)}</span><p>${esc(mark)}</p>${noHire}${flagged}${creds}</li>`;
}
@@ -87,6 +112,23 @@
const apply = s.writable ? `<button class="btn" type="button" data-pack-apply data-focus-key="pack-apply">Apply this plan</button>` : '<p class="note">This Console was started without send. Packs can be previewed, not applied.</p>';
return `<div class="pack-preview" data-pack-preview="${esc(p.pack)}"><h4>Preview: ${esc(v.pack?.label ?? p.pack)}${v.project ? ` <span class="muted">for project ${esc(v.project)}</span>` : ''}</h4>${items}${hires}${skills}${chief}${apply}</div>`;
}
// The pack's applied entries (one per project for a project pack): the agents it hired and its open proposals.
function appliedBlock(org, s, entry) {
const mine = s.applied.filter(a => a.id === entry.id && (a.origin ?? null) === (entry.origin ?? null));
if (!mine.length) return '';
return mine.map(a => {
const where = a.project ? ` <span class="muted">in project ${esc(a.project)}</span>` : '';
const n = a.hired.length;
const hired = `<p data-pack-hired="${esc(a.project ?? '')}"><strong>${n === 0 ? 'No agents hired yet' : `${n} ${n === 1 ? 'agent' : 'agents'} hired`}</strong>${where}${n ? `: ${a.hired.map(x => `<code>${esc(x)}</code>`).join(', ')}` : ''}</p>`;
const open = a.open.filter(plainObj);
const lines = open.length ? `<ul class="pack-open" data-pack-open>${open.map(o => `<li data-pack-open-hire="${esc(o.name)}" data-pack-open-state="${esc(o.state)}"><code>${esc(o.name)}</code>: ${esc(o.reason || 'No reason given.')} <span class="muted">${esc(o.state === 'refused' ? `not hired: ${whyText(o.code)}` : OPEN_STATE[o.state] ?? o.state)}</span></li>`).join('')}</ul>` : '';
// The page is the owner's, and the owner's pack hire also approves a line this pack's own hire
// left in the inbox (fromPack). A decision raised some other way stays the inbox's.
const hireable = open.filter(o => o.state !== 'awaiting-owner' || o.fromPack === true).length;
const button = hireable && s.writable ? `<button class="btn" type="button" data-pack-hire-button data-pack-hire-project="${esc(a.project ?? '')}" data-focus-key="${esc(`pack-hire:${org}:${entry.id}:${a.project ?? ''}`)}">Hire the ${hireable} proposed ${hireable === 1 ? 'agent' : 'agents'}</button>` : '';
return `<div class="pack-applied">${hired}${lines}${button}</div>`;
}).join('');
}
function packRow(org, s, entry) {
const pack = entry.pack;
const project = pack.scope === 'project'
@@ -96,13 +138,13 @@
: '';
const canPreview = pack.scope !== 'project' || (s.projects && s.projects.length);
return `<li class="pack-row" data-pack="${esc(entry.id)}"><strong>${esc(pack.label ?? entry.id)}</strong> <span class="muted"><code>${esc(entry.id)}</code> ${esc(pack.version)} · ${esc(entry.origin)} · ${pack.scope === 'project' ? 'project pack' : 'organization pack'}</span>
<p>${esc(pack.description)}</p>${project}${canPreview ? `<button class="btn" type="button" data-pack-preview-button data-focus-key="${esc(`pack-preview:${org}:${entry.id}`)}">Preview</button>` : ''}</li>`;
<p>${esc(pack.description)}</p>${appliedBlock(org, s, entry)}${project}${canPreview ? `<button class="btn" type="button" data-pack-preview-button data-focus-key="${esc(`pack-preview:${org}:${entry.id}`)}">Preview</button>` : ''}</li>`;
}
function section(org) {
const s = states.get(org);
if (!s || s.error) return `<section class="panel" data-packs data-packs-org="${esc(org)}" data-live-key="${esc(`packs:${org}`)}"><h3>Starter packs</h3><p>${esc(s?.error ?? 'Starter packs could not be read.')}</p></section>`;
const list = s.packs.length ? `<ul class="pack-list">${s.packs.map(e => packRow(org, s, e)).join('')}</ul>` : '<p class="note">No starter packs are installed.</p>';
return `<section class="panel" data-packs data-packs-org="${esc(org)}" data-live-key="${esc(`packs:${org}`)}"><h3>Starter packs</h3><p>A pack adds roles, a board and workflows to the organization. Preview shows what it would change; apply adds only what is missing, and a hire it proposes is only raised by the chief, as a decision.</p>${list}${previewBlock(s)}<p role="status" data-packs-status>${esc(s.status)}</p></section>`;
return `<section class="panel" data-packs data-packs-org="${esc(org)}" data-live-key="${esc(`packs:${org}`)}"><h3>Starter packs</h3><p>A pack adds roles, a board and workflows to the organization. Preview shows what it would change; apply adds only what is missing and hires the agents it proposes. Applying is the hire decision.</p>${list}${previewBlock(s)}<p role="status" data-packs-status>${esc(s.status)}</p></section>`;
}
function redraw(org) {
const el = [...document.querySelectorAll('[data-packs-org]')].find(n => n.dataset.packsOrg === org);
@@ -114,14 +156,19 @@
if (s) s.picks[select.closest('[data-pack]').dataset.pack] = select.value;
});
document.addEventListener('click', async e => {
const button = e.target.closest('[data-pack-preview-button],[data-pack-apply]');
const button = e.target.closest('[data-pack-preview-button],[data-pack-apply],[data-pack-hire-button]');
if (!button) return;
const root = button.closest('[data-packs-org]'), org = root?.dataset.packsOrg, s = states.get(org);
if (!s) return;
button.disabled = true;
let applied = false;
try {
if (button.hasAttribute('data-pack-preview-button')) {
if (button.hasAttribute('data-pack-hire-button')) {
const pack = button.closest('[data-pack]').dataset.pack, project = button.dataset.packHireProject;
const r = await call(`${base(org)}/packs/hire`, { pack, ...(project ? { project } : {}) });
s.status = hireSummary(r.hires);
applied = true;
} else if (button.hasAttribute('data-pack-preview-button')) {
const row = button.closest('[data-pack]'), pack = row.dataset.pack, project = row.querySelector('[data-pack-project]')?.value;
const body = { pack, ...(project ? { project } : {}) };
s.preview = { pack, project: project ?? null, value: await call(`${base(org)}/packs/preview`, body) };
@@ -131,15 +178,31 @@
const r = await call(`${base(org)}/packs/apply`, { pack: p.pack, digest: p.value.digest, ...(p.project ? { project: p.project } : {}) });
const added = Array.isArray(r.added) && r.added.length ? r.added.join(', ') : 'nothing new';
s.preview = null;
s.status = `Applied. Added ${added}. Proposed hires are recorded for the chief to raise as decisions.`;
s.status = `Applied. Added ${added}. ${typeof r.hireError === 'string' ? `The hires did not run: ${whyText(r.hireError)}. Use Hire on the pack card to run them.` : hireSummary(r.hires)}`;
applied = true;
}
} catch (error) { s.status = error.message; }
// An apply or a hire reads the packs again, so the card's hired count and open proposals are the bus's now.
if (applied) await load(org);
// A preview the page cannot draw says so, instead of leaving the button disabled with nothing shown.
try { redraw(org); } catch { s.preview = null; s.status = 'The preview could not be shown.'; redraw(org); }
// An apply changes the workflows, the board and the roles too: the page and any pane showing this
// organization read every section again. The receipt above is kept in state, so it survives that read.
if (applied) document.dispatchEvent(new CustomEvent('mosaic-org-changed', { detail: { org } }));
});
// One line for the hires an apply or a hire made, from the bus's answer.
function hireSummary(hires) {
const list = Array.isArray(hires) ? hires.filter(plainObj) : [];
if (!list.length) return 'The pack proposes no hires.';
const names = state => list.filter(h => h.state === state).map(h => h.name);
const parts = [];
const hired = names('hired'), waiting = names('awaiting-owner'), exists = names('exists'), open = names('open');
if (hired.length) parts.push(`Hired ${hired.join(', ')}.`);
if (waiting.length) parts.push(`Sent to the owner's inbox: ${waiting.join(', ')}.`);
if (open.length) parts.push(`Already waiting as a decision: ${open.join(', ')}.`);
if (exists.length) parts.push(`Already hired: ${exists.join(', ')}.`);
for (const h of list.filter(h => h.state === 'refused')) parts.push(`Not hired: ${h.name}, ${whyText(h.code)}.`);
return parts.join(' ');
}
window.MosaicPacks = { load, section };
})();
-93
View File
@@ -1,93 +0,0 @@
/* Side by side (U5, sample 07 "EXT 8"): a bar, then two panes with a divider between them. Each pane
has its own header with the organization's mark and edge, and its own scroll. One pane and a
shown-pane switch on a phone. Loaded after shell.css; every rule is scoped to the side-by-side page. */
html[data-organizations] .content:has(> #bus-view > .sbs){padding:0}
html[data-organizations] .sbs{margin:0;display:flex;flex-direction:column;min-height:0;height:calc(100vh - var(--bar-h,53px) - var(--foot-h,33px))}
html[data-organizations] .sbs .panebar{display:flex;align-items:center;gap:10px;padding:8px 14px;border-bottom:1px solid var(--line);background:var(--canvas);flex-wrap:wrap}
html[data-organizations] .sbs .panebar h1{font-size:16px;font-weight:700;margin:0;line-height:1.4}
html[data-organizations] .sbs .panebar h1:focus{outline:none}
html[data-organizations] .sbs .panebar .note{font-size:13px;color:var(--muted)}
html[data-organizations] .sbs .panebar [data-pane-add]{margin-left:auto}
html[data-organizations] .sbs .ws-seg.pane-tabs{display:none;margin-left:0}
html[data-organizations] .sbs .pane-tabs>button{gap:5px;max-width:44vw}
html[data-organizations] .sbs .pane-tabs>button>span:last-child{overflow:hidden;text-overflow:ellipsis}
html[data-organizations] .panes{--sbs-a:1fr;--sbs-b:1fr;display:grid;grid-template-columns:minmax(0,1fr);flex:1;min-height:0}
html[data-organizations] .panes.two{grid-template-columns:minmax(0,var(--sbs-a)) 1px minmax(0,var(--sbs-b))}
html[data-organizations] .pane{display:flex;flex-direction:column;min-width:0;min-height:0}
html[data-organizations] .pane[hidden]{display:none}
html[data-organizations] .pane-h{display:flex;align-items:center;gap:8px;padding:8px 14px;border-bottom:1px solid var(--line);background:var(--surface);box-shadow:inset 0 3px 0 var(--org,var(--line));min-width:0}
html[data-organizations] .pane-h .ttl{font-weight:700;color:var(--strong,var(--text));overflow:hidden;text-overflow:ellipsis;white-space:nowrap;min-width:0;flex:0 1 auto}
html[data-organizations] .pane-h .ttl small{font-weight:500;color:var(--muted);margin-left:6px;font-size:inherit}
html[data-organizations] .pane-h [data-pane-state]:empty{display:none}
html[data-organizations] .pane-pick{flex:0 1 180px;min-width:0;max-width:220px;margin-left:auto;font:500 12px/1.4 var(--font);color:var(--text);background:var(--canvas);border:1px solid var(--line);border-radius:var(--r);padding:3px 6px;min-height:0}
html[data-organizations] .pane-h .tools{display:flex;gap:2px;flex:none}
html[data-organizations] .pane-tool{display:inline-grid;place-items:center;width:26px;height:26px;border-radius:var(--r);color:var(--muted);border:0;background:none;padding:0;min-height:0;cursor:pointer}
html[data-organizations] .pane-tool:hover{background:var(--raised);color:var(--text)}
html[data-organizations] .pane-tool[hidden]{display:none}
html[data-organizations] .pane-tool svg.i{width:15px;height:15px;fill:none;stroke:currentColor;stroke-width:1.8;stroke-linecap:round;stroke-linejoin:round}
html[data-organizations] .pane-line{margin:0;padding:6px 14px;border-bottom:1px solid var(--line);font-size:13px;color:var(--text);background:color-mix(in srgb,var(--warn,#b7791f) 12%,var(--surface))}
html[data-organizations] .pane-line[hidden]{display:none}
html[data-organizations] .pane-body{overflow:auto;padding:14px;min-height:0;flex:1}
html[data-organizations] .pane-body:focus{outline:none}
html[data-organizations] .pane-body:focus-visible{outline:2px solid var(--focus,var(--action));outline-offset:-2px}
/* A page inside a pane is a section of the side-by-side page: smaller headings, no page chrome. */
html[data-organizations] .pane-body .ws h1{font-size:20px}
html[data-organizations] .pane-body .chat-area.pane-project{display:block;height:auto;min-height:0;overflow:visible;padding:0}
/* A project in a pane is compact (sample 07): the pane header already names the project and its
organization, so the page heading stays only for assistive technology and focus, the full-page
actions give way (North star and PRD are on the Requirements tab, Settings in the full view), and
the tabs, measures and current work come first. Project pages size some parts from the window
(projects.css); in a pane they size from the pane. */
html[data-organizations] .pane-body{container-type:inline-size}
html[data-organizations] .pane-body .project-header{display:block;width:auto;max-width:100%;margin:0 0 6px;padding:0}
html[data-organizations] .pane-body .project-header .project-heading,html[data-organizations] .pane-body .project-header .project-heading>div{display:block}
html[data-organizations] .pane-body .project-header-icon,html[data-organizations] .pane-body .project-actions{display:none}
html[data-organizations] .pane-body .project-header h1{position:absolute;width:1px;height:1px;margin:-1px;padding:0;border:0;overflow:hidden;clip-path:inset(50%);white-space:nowrap}
html[data-organizations] .pane-body:has(.project-header h1:focus-visible){outline:2px solid var(--focus,var(--action));outline-offset:-2px}
html[data-organizations] .pane-body .project-header .project-heading p{margin:0;font-size:13px;color:var(--muted)}
html[data-organizations] .pane-body .project-tabs a{min-height:40px;padding:0 12px;font-size:14px}
html[data-organizations] .pane-body .project-metrics{grid-template-columns:repeat(2,minmax(0,1fr));margin-top:10px;padding:6px 0}
html[data-organizations] .pane-body .project-metrics a{padding:4px 12px;border-right:0;border-bottom:0;line-height:1.3}
html[data-organizations] .pane-body .project-metrics a span,html[data-organizations] .pane-body .project-metrics small{font-size:12px;overflow-wrap:anywhere}
html[data-organizations] .pane-body .project-metrics strong{font-size:20px}
html[data-organizations] .pane-body .project-metrics p{margin:6px 12px 0;padding-top:6px}
html[data-organizations] .pane-body .project-columns{grid-template-columns:minmax(0,1fr);gap:14px;margin-top:12px}
html[data-organizations] .pane-body .project-columns h2{font-size:16px;margin:12px 0 8px}
html[data-organizations] .pane-body .project-columns h3{font-size:14px}
html[data-organizations] .pane-body .project-columns .project-section-title h2,html[data-organizations] .pane-body .project-columns aside>h2:first-child{margin-top:0}
@container (min-width:560px){
html[data-organizations] .pane-body .project-metrics{grid-template-columns:repeat(4,minmax(0,1fr))}
html[data-organizations] .pane-body .project-metrics a:not(:nth-child(4)){border-right:1px solid var(--line)}
}
/* E2E6 P2-9: a dashboard in a pane sizes from the pane, not the window. Half a 1440 window left the
Settings column too narrow for its values (clipped to 1-2 characters): the split stacks below 900px
of pane, and a narrow Settings list puts each value on its own line, as at phone width. */
@container (max-width:899px){
html[data-organizations] .pane-body .ws-split{grid-template-columns:minmax(0,1fr)}
}
@container (max-width:559px){
html[data-organizations] .pane-body .ws-cfg li{grid-template-columns:18px minmax(0,1fr) auto auto}
html[data-organizations] .pane-body .ws-cfg .v{grid-column:2/-1;grid-row:2}
}
/* The side-by-side page has its own bar; the page breadcrumb would name only one pane. */
body:has(#bus-view > .sbs) #breadcrumbs{display:none}
html[data-organizations] .content:has(> #bus-view > .sbs) > .org-cue{margin:8px 14px}
html[data-organizations] .pane-div{position:relative;background:var(--line);cursor:col-resize;touch-action:none;outline:none}
html[data-organizations] .pane-div::before{content:"";position:absolute;inset:0 -4px;z-index:1}
html[data-organizations] .pane-div:hover,html[data-organizations] .pane-div.dragging{background:var(--action)}
html[data-organizations] .pane-div:focus-visible{background:var(--action);box-shadow:0 0 0 2px var(--action)}
html[data-organizations] .pane-div[hidden]{display:none}
@media (max-width:760px){
html[data-organizations] .content:has(> #bus-view > .sbs){padding:0}
html[data-organizations] .sbs{height:auto}
html[data-organizations] .sbs .ws-seg.pane-tabs{display:inline-flex}
html[data-organizations] .sbs .hide-m{display:none}
html[data-organizations] .panes,html[data-organizations] .panes.two{grid-template-columns:minmax(0,1fr)}
html[data-organizations] .pane.alt,html[data-organizations] .pane-div{display:none}
html[data-organizations] .pane-body{overflow:visible}
html[data-organizations] .pane-h{flex-wrap:wrap}
html[data-organizations] .pane-pick{flex:1 1 100%;max-width:none;order:5;margin-left:0}
}
-484
View File
@@ -1,484 +0,0 @@
// Side by side (U5, sample 07): two panes, each showing one page of any organization. A pane holds
// the organization dashboard, the Agents levels or a project page (overview, conversations, tasks,
// requirements, files), drawn by the same modules as the full view (workspace.js, projects.js) into
// the pane instead of #bus-view. Every read names the pane's organization, so the panes never share
// state. Pages that keep one global form, dialog or editor (a conversation, the room, settings, the
// queue, docs, the inbox) are not offered in a pane; their links open the full view.
//
// The panes' routes, the divider and the phone's shown pane live in the URL
// (#/orgs/<page>/side-by-side?a=<org>/<route>&b=<org>/<route>&w=<percent>&show=a|b), updated with
// replaceState so nothing reloads, and the last layout is remembered in this browser.
(() => {
'use strict';
if (!document.documentElement.hasAttribute('data-organizations')) return;
const data = window.MosaicWorkspaceData, ws = () => window.MosaicWorkspace;
const esc = value => String(value ?? '').replace(/[&<>"']/g, c => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
const enc = encodeURIComponent;
const STORE = 'mosaic-side-by-side-v1', POLL = 10000, LIST_TTL = 3000, PROJECTS_TTL = 30000;
const MIN = 25, MAX = 75, STEP = 5;
const ORG = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
const PROJECT = /^\/projects\/([A-Za-z0-9][A-Za-z0-9._-]{0,159})(?:\/(conversations|tasks|requirements|files))?$/;
const SECTIONS = { overview: 'Overview', conversations: 'Conversations', tasks: 'Tasks', requirements: 'Requirements', files: 'Files' };
const FOCUSABLE = 'a[href],button:not([disabled]),select,textarea,input,summary,[tabindex]:not([tabindex="-1"])';
const NAMES = { a: 'left', b: 'right' };
const load = () => { try { return localStorage.getItem(STORE); } catch { return null; } };
const save = value => { try { localStorage.setItem(STORE, value); } catch {} };
const paused = () => document.getElementById('pause')?.getAttribute('aria-pressed') === 'true';
const svg = d => `<svg class="i sm" viewBox="0 0 24 24" aria-hidden="true" focusable="false">${d}</svg>`;
const FULL = svg('<rect x="3.5" y="4.5" width="17" height="15" rx="1.5"/><path d="M12 4.5v15"/>');
const CLOSE = svg('<path d="M6 6l12 12M18 6 6 18"/>');
const PLUS = svg('<path d="M12 5v14M5 12h14"/>');
// A pane's page: the routes a pane can draw. Anything else is not pane-safe.
function page(route) {
if (route === '/organization') return { kind: 'dashboard' };
if (route === '/agents') return { kind: 'agents' };
const m = PROJECT.exec(route);
if (m && m[1] !== 'threads' && m[1] !== 'rooms') return { kind: 'project', id: m[1], section: m[2] || 'overview' };
return null;
}
// "<org>/<route>" from the URL; null when either part is not one a pane draws.
function parsePane(value) {
if (typeof value !== 'string') return null;
const cut = value.indexOf('/');
if (cut < 1) return null;
const org = value.slice(0, cut), route = value.slice(cut);
return ORG.test(org) && page(route) ? { org, route } : null;
}
const paneValue = p => `${p.org}${p.route}`;
const clampW = n => Math.min(MAX, Math.max(MIN, Math.round(n)));
// ---------- shared reads (one organization list and project lists for both panes) ----------
let listAt = 0, listPromise = null, projectReads = new Map();
function orgList(fresh = false) {
if (!listPromise || fresh || Date.now() - listAt > LIST_TTL) {
listAt = Date.now();
listPromise = Promise.all([data.organizations(), ws()?.themes?.()]).then(([rows]) => (Array.isArray(rows) ? rows : null)).catch(() => null);
}
return listPromise;
}
function projectsOf(org, fresh = false) {
const hit = projectReads.get(org);
if (hit && !fresh && Date.now() - hit.at < PROJECTS_TTL) return hit.promise;
const promise = data.projects(org).then(b => (Array.isArray(b?.rows) ? b.rows.filter(p => p && typeof p.id === 'string') : null)).catch(() => null);
projectReads.set(org, { at: Date.now(), promise });
return promise;
}
// ---------- state ----------
let mounted = null; // { root, panes: [pane], w, show, gen }
let mountGen = 0;
let listCache = null; // the last organization list read, for the shown-pane tabs
function readQuery(query) {
const q = new URLSearchParams(query || '');
return { a: parsePane(q.get('a')), b: parsePane(q.get('b')), w: Number(q.get('w')), show: q.get('show'), named: q.has('a') || q.has('b') };
}
function queryOf(state) {
const q = new URLSearchParams();
state.panes.forEach((p, i) => q.set(i ? 'b' : 'a', paneValue(p)));
q.set('w', String(state.w));
q.set('show', state.show);
return q.toString().replace(/%2F/g, '/');
}
function writeUrl() {
if (!mounted) return;
const qs = queryOf(mounted);
save(qs);
const next = `#/orgs/${enc(window.MosaicOrg.id)}/side-by-side?${qs}`;
if (location.hash !== next) history.replaceState(null, '', next);
}
// The first pane is this page's organization; the second is the next organization on the list,
// or this one's Agents when there is no other.
async function defaults() {
const here = window.MosaicOrg.id, list = await orgList();
const other = (list || []).find(o => o && !o.invalid && o.id !== here && ORG.test(o.id));
return [{ org: here, route: '/organization' }, other ? { org: other.id, route: '/organization' } : { org: here, route: '/agents' }];
}
// ---------- markup ----------
function paneShell(key) {
const name = NAMES[key];
return `<section class="pane" id="pane-${key}" data-pane="${key}" aria-label="${name[0].toUpperCase()}${name.slice(1)} pane">
<div class="pane-h ws-o" data-pane-head>
<span data-pane-av></span><span class="ttl" data-pane-ttl></span><span data-pane-state></span>
<label class="ws-sr" for="pane-${key}-pick">Page in the ${name} pane</label>
<select id="pane-${key}-pick" class="pane-pick" data-pane-pick></select>
<span class="tools"><a class="pane-tool" data-pane-full href="#" title="Open in full view"><span class="ws-sr" data-pane-full-label>Open in full view</span>${FULL}</a><button type="button" class="pane-tool" data-pane-close title="Close pane" aria-label="Close the ${name} pane">${CLOSE}</button></span>
</div>
<p class="pane-line" data-pane-line role="status"></p>
<div class="pane-body" data-pane-body tabindex="0" aria-label="${name[0].toUpperCase()}${name.slice(1)} pane content"></div>
</section>`;
}
function frame() {
return `<section class="sbs" data-side-by-side aria-labelledby="sbs-title">
<div class="panebar"><h1 id="sbs-title" tabindex="-1">Side by side</h1><span class="note" data-sbs-note></span>
<span class="ws-seg pane-tabs" role="group" aria-label="Shown pane" data-sbs-tabs></span>
<button type="button" class="ws-btn hide-m" data-pane-add>${PLUS}Add pane</button></div>
<div class="panes" data-sbs-panes>${paneShell('a')}<div class="pane-div" role="separator" tabindex="0" aria-orientation="vertical" aria-label="Resize panes" aria-controls="pane-a pane-b" aria-valuemin="${MIN}" aria-valuemax="${MAX}" data-sbs-divider></div>${paneShell('b')}</div>
</section>`;
}
// Orgs in the picker: every organization on the list. A pane draws a valid one's dashboard, Agents or
// any project the organization's project read lists; an invalid one is listed and cannot be chosen.
async function pickerHtml(p, list) {
const groups = await Promise.all((list || []).filter(o => o && ORG.test(o.id)).map(async org => {
const name = ws().label(org);
if (org.invalid) return `<optgroup label="${esc(name)} · invalid"><option disabled value="">Organization invalid</option></optgroup>`;
const rows = await projectsOf(org.id);
const opt = (route, text) => `<option value="${esc(`${org.id}${route}`)}">${esc(text)}</option>`;
const projects = rows === null ? '<option disabled value="">Projects unavailable</option>' : rows.filter(r => !r.archived && PROJECT.test(`/projects/${r.id}`)).map(r => opt(`/projects/${r.id}`, `Project: ${r.name || r.id}`)).join('');
return `<optgroup label="${esc(name)}${org.busHealthy ? '' : ' · bus unavailable'}">${opt('/organization', 'Dashboard')}${opt('/agents', 'Agents')}${projects}</optgroup>`;
}));
let html = groups.join('');
const value = paneValue(p);
// A project section, or a page the list no longer names, is still the pane's page: keep it selectable.
if (!html.includes(`value="${esc(value)}"`)) html = `<option value="${esc(value)}">${esc(p.title || value)}</option>${html}`;
return html;
}
// ---------- drawing one pane ----------
const els = p => ({
head: p.el.querySelector('[data-pane-head]'), av: p.el.querySelector('[data-pane-av]'), ttl: p.el.querySelector('[data-pane-ttl]'),
state: p.el.querySelector('[data-pane-state]'), pick: p.el.querySelector('[data-pane-pick]'), full: p.el.querySelector('[data-pane-full]'),
fullLabel: p.el.querySelector('[data-pane-full-label]'), close: p.el.querySelector('[data-pane-close]'), line: p.el.querySelector('[data-pane-line]'), body: p.el.querySelector('[data-pane-body]'),
});
const setHtml = (el, html) => { if (el && el.innerHTML !== html) el.innerHTML = html; };
const setText = (el, text) => { if (el && el.textContent !== text) el.textContent = text; };
// Links a page draws are relative to the page's organization. In a pane they name the pane's
// organization; reads the page links to (/api/...) name it too.
function rewrite(p, root) {
const prefix = `#/orgs/${enc(p.org)}`;
for (const a of root.querySelectorAll('a[href^="#/"]')) if (!a.getAttribute('href').startsWith('#/orgs/')) a.setAttribute('href', prefix + a.getAttribute('href').slice(1));
for (const a of root.querySelectorAll('a[href^="/api/"]')) if (!a.getAttribute('href').startsWith('/api/orgs/')) a.setAttribute('href', `/api/orgs/${enc(p.org)}/${a.getAttribute('href').slice(5)}`);
// The pane's title is the page's heading; the side-by-side page keeps the one level-1 heading.
for (const h of root.querySelectorAll('h1:not([aria-level])')) h.setAttribute('aria-level', '2');
}
// Focus and scroll survive a repaint of this pane only. Focus in the other pane is never taken.
function capture(p, root) {
const a = document.activeElement, inside = !!a && a !== root && root.contains(a);
return {
top: root.scrollTop,
focus: inside ? { key: a.dataset?.focusKey || null, href: a.getAttribute('href'), index: [...root.querySelectorAll(FOCUSABLE)].indexOf(a), h1: a.tagName === 'H1' } : null,
};
}
function restore(p, root, kept) {
root.scrollTop = kept.top;
const f = kept.focus, a = document.activeElement;
if (!f || (a && a !== document.body && !root.contains(a))) return;
const target = (f.key && root.querySelector(`[data-focus-key="${CSS.escape(f.key)}"]`))
|| (f.href && [...root.querySelectorAll('a[href]')].find(x => x.getAttribute('href') === f.href))
|| (f.h1 && root.querySelector('h1'))
|| root.querySelectorAll(FOCUSABLE)[f.index];
(target || root).focus({ preventScroll: true });
}
function paintBody(p, html) {
const { body } = els(p);
if (p.html === html && body.childElementCount) return;
const kept = capture(p, body), live = window.MosaicWorkspace?.holdLive?.(body);
body.innerHTML = html; p.html = html; p.project = null;
rewrite(p, body);
// E2E6 P1-1: an editor in use keeps its node, draft and focus; its ids were rewritten when first painted.
if (live && window.MosaicWorkspace.graftLive(body, live)) kept.focus = null;
restore(p, body, kept);
}
// A focus move that finishes after an asynchronous read happens only if the viewer has not
// moved on: focus is still where it was when the action started, nowhere, or inside this pane.
function mayFocus(p, before) {
const a = document.activeElement;
return !a || a === document.body || a === before || p.el.contains(a);
}
async function drawPane(p, { fresh = false, focusHead = false } = {}) {
if (!mounted || !p.el.isConnected) return;
const before = document.activeElement;
const turn = ++p.turn, gen = mountGen, live = () => mounted && gen === mountGen && turn === p.turn && p.el.isConnected;
clearTimeout(p.timer);
const e = els(p), what = page(p.route);
const list = await orgList(fresh);
if (!live()) return;
if (list) listCache = list;
const org = list?.find(o => o?.id === p.org) || null;
const name = org ? ws().label(org) : p.org;
// Header: the organization's mark, the page's title, its state, the picker and the tools.
if (org) e.head.setAttribute('style', ws().colours(org)); else e.head.removeAttribute('style');
setHtml(e.av, org ? ws().av(org, 'md') : '<span class="ws-av md" aria-hidden="true">?</span>');
const [scls, sglyph, sword] = org ? ws().state(org) : ['s-unknown', '?', 'not on your list'];
setHtml(e.state, org?.busHealthy && !org.invalid ? '' : ws().dot(scls, sglyph, sword, true));
const fullHref = `#/orgs/${enc(p.org)}${p.route}`;
if (e.full.getAttribute('href') !== fullHref) e.full.setAttribute('href', fullHref);
let line = '', html = null;
if (!list) line = 'The organization list could not be read. This pane shows what its own reads return.';
else if (!org) { line = `${p.org} is not on your organization list.`; html = '<p class="ws-line">Nothing is read for an organization that is not on your list.</p>'; }
else if (org.invalid) { line = `${name}: organization invalid${org.reason ? ` (${org.reason})` : ''}.`; html = '<p class="ws-line">Nothing is read from an invalid organization. Fix its file under Settings, Organizations.</p>'; }
else if (!org.busHealthy) line = `${name}: bus unavailable. Reads from this organization may fail; the other pane is not affected.`;
setText(e.line, line); e.line.hidden = !line;
let title = what?.kind === 'agents' ? 'Agents' : 'Dashboard';
if (html === null && what?.kind === 'dashboard') html = await ws().dashboard(p.org, { pane: true, idPrefix: `pane-${p.key}-` }).catch(() => '<p class="ws-line">Dashboard unavailable.</p>');
else if (html === null && what?.kind === 'agents') html = await ws().agentGrid('', p.org).catch(() => '<p class="ws-line">Agents unavailable.</p>');
if (!live()) return;
if (html === null && what?.kind === 'project') {
title = await drawProject(p, e, what, fresh, live);
if (title === null || !live()) return;
} else if (html !== null) paintBody(p, html);
p.title = title;
setHtml(e.ttl, `${esc(title)}<small>${esc(name)}</small>`);
p.el.setAttribute('aria-label', `${NAMES[p.key][0].toUpperCase()}${NAMES[p.key].slice(1)} pane: ${title}, ${name}`);
setText(e.fullLabel, `Open ${title}, ${name}, in full view`);
// The picker is rebuilt only while it is closed and unfocused, so a choice in progress stays.
if (document.activeElement !== e.pick) {
const options = await pickerHtml(p, list);
if (!live()) return;
if (document.activeElement !== e.pick) { setHtml(e.pick, options); e.pick.value = paneValue(p); }
}
paintBar(); fit();
if (focusHead && mayFocus(p, before)) (e.body.querySelector('h1') || e.body).focus({ preventScroll: true });
p.timer = setTimeout(() => tick(p), POLL);
}
function tick(p) {
if (!mounted || !p.el.isConnected) return;
if (paused()) { p.timer = setTimeout(() => tick(p), POLL); return; }
void drawPane(p);
}
// A project page: projects.js's header and content, mounted into the pane with the pane's
// organization, read-only (a pane never sends).
// Every write below happens only while this draw is still the pane's current one (live()), so a
// slow read never paints an old page or organization over the one the viewer has since chosen.
async function drawProject(p, e, what, fresh, live) {
const org = p.org;
const [projects, threadsRead] = await Promise.all([projectsOf(org, fresh), data.threads(org).catch(() => null)]);
if (!live() || p.org !== org) return null;
const project = projects?.find(r => r.id === what.id);
const sectionName = SECTIONS[what.section];
if (!project) {
paintBody(p, projects === null ? '<p class="ws-line">Projects unavailable. The organization did not answer the project read.</p>' : '<p class="ws-line">This project is not in the organization\'s project list.</p>');
return what.id;
}
const threads = Array.isArray(threadsRead?.rows) ? threadsRead.rows : [];
const head = window.MosaicProjects.header(project, what.section, threads);
const conv = what.section === 'conversations' ? conversations(project, threads, threadsRead) : null;
const key = JSON.stringify([org, project.id, what.section, head, conv]);
const { body } = e;
if (p.project?.key !== key) {
const kept = capture(p, body);
body.innerHTML = `<div class="chat-area pane-project">${head}${conv ?? '<div data-project-content>Reading…</div>'}</div>`;
p.html = null; p.project = { key };
rewrite(p, body);
restore(p, body, kept);
}
const content = body.querySelector('[data-project-content]');
if (content) await window.MosaicProjects.mountContent({ container: content, project, threads, section: what.section, canSend: false, org, pane: true, views: viewsOf(p, org), idPrefix: `pane-${p.key}-` });
return what.section === 'overview' ? project.name || project.id : `${project.name || project.id} · ${sectionName}`;
}
// A pane's request choice and PRD disclosure, per organization, kept on the pane so a repaint
// that replaces the project content keeps them.
function viewsOf(p, org) {
if (!p.views.has(org)) p.views.set(org, { selected: new Map(), expanded: new Set() });
return p.views.get(org);
}
function conversations(project, threads, read) {
if (!read) return '<p class="ws-line">Conversations unavailable.</p>';
const own = threads.filter(t => t && !t.shared && t.project === project.id && typeof t.id === 'string');
const rows = own.map(t => `<a class="project-conversation-row" href="#/projects/threads/${enc(t.id)}" data-focus-key="${esc(`conv:${t.id}`)}"><span class="project-conversation-icon" aria-hidden="true">◌</span><span><strong>${esc(t.name || t.id)}</strong><small>With ${esc(t.instance || 'no agent recorded')}</small></span><span aria-hidden="true">›</span></a>`).join('');
return `<div class="project-section-title"><h2>Conversations</h2></div><div data-project-conversations>${rows || '<p>No conversations yet.</p>'}</div><p class="ws-line">A conversation opens in its full view.</p>`;
}
// ---------- the bar, tabs, divider and layout ----------
function paintBar() {
if (!mounted) return;
const { root, panes, show } = mounted, two = panes.length === 2;
setText(root.querySelector('[data-sbs-note]'), `${panes.length} ${panes.length === 1 ? 'pane' : 'panes'} · each pane reads its own organization's bus and keeps its own state`);
const tabs = root.querySelector('[data-sbs-tabs]'), focusedTab = tabs.contains(document.activeElement) ? document.activeElement.dataset.paneShow : null;
const list = listCache;
const html = panes.map(p => {
const org = list?.find(o => o?.id === p.org);
return `<button type="button" data-pane-show="${p.key}" aria-pressed="${show === p.key}" aria-controls="pane-${p.key}">${org ? ws().av(org, 'xs') : ''}<span>${esc(p.title || 'Reading…')}</span></button>`;
}).join('');
if (tabs.innerHTML !== html) { tabs.innerHTML = html; if (focusedTab) tabs.querySelector(`[data-pane-show="${focusedTab}"]`)?.focus({ preventScroll: true }); }
const add = root.querySelector('[data-pane-add]');
add.disabled = two; add.title = two ? 'Side by side holds two panes. Close one to choose another.' : 'Open a second pane';
for (const p of panes) { const c = p.el.querySelector('[data-pane-close]'); c.hidden = !two; }
}
function layout() {
if (!mounted) return;
const { root, panes, w, show } = mounted, two = panes.length === 2;
const box = root.querySelector('[data-sbs-panes]'), divider = root.querySelector('[data-sbs-divider]');
box.classList.toggle('two', two);
box.style.setProperty('--sbs-a', `${w}fr`); box.style.setProperty('--sbs-b', `${100 - w}fr`);
divider.hidden = !two;
divider.setAttribute('aria-valuenow', String(w));
divider.setAttribute('aria-valuetext', `Left pane ${w} percent, right pane ${100 - w} percent`);
root.querySelector('#pane-b').hidden = !two;
for (const p of panes) p.el.classList.toggle('alt', show !== p.key);
fit();
}
// Wide screens: the panes fill the window below the bar and each scrolls on its own.
const wide = window.matchMedia('(min-width: 761px)');
function fit() {
if (!mounted) return;
const { root } = mounted;
if (!wide.matches) { root.style.height = ''; return; }
const foot = document.querySelector('body > .foot, .foot')?.getBoundingClientRect().height || 0;
const top = root.getBoundingClientRect().top;
root.style.height = `${Math.max(360, Math.floor(window.innerHeight - Math.max(top, 0) - foot))}px`;
}
function setWidth(w, persist = true) {
if (!mounted) return;
const next = clampW(w);
if (next === mounted.w) return;
mounted.w = next; layout(); if (persist) writeUrl();
}
// ---------- events (bound once to the mount root) ----------
function bind(root) {
const divider = root.querySelector('[data-sbs-divider]');
divider.addEventListener('keydown', e => {
const w = mounted?.w; if (w === undefined) return;
const next = { ArrowLeft: w - STEP, ArrowDown: w - STEP, ArrowRight: w + STEP, ArrowUp: w + STEP, PageDown: w - 10, PageUp: w + 10, Home: MIN, End: MAX }[e.key];
if (next === undefined) return;
e.preventDefault(); setWidth(next);
});
divider.addEventListener('pointerdown', e => {
if (e.button !== 0) return;
e.preventDefault(); divider.focus({ preventScroll: true }); divider.setPointerCapture(e.pointerId); divider.classList.add('dragging');
const box = root.querySelector('[data-sbs-panes]').getBoundingClientRect();
const move = ev => setWidth(((ev.clientX - box.left) / box.width) * 100, false);
const up = () => { divider.removeEventListener('pointermove', move); divider.removeEventListener('pointerup', up); divider.removeEventListener('pointercancel', up); divider.classList.remove('dragging'); writeUrl(); };
divider.addEventListener('pointermove', move); divider.addEventListener('pointerup', up); divider.addEventListener('pointercancel', up);
});
root.addEventListener('change', e => {
const pick = e.target.closest?.('[data-pane-pick]'); if (!pick || !mounted) return;
const p = mounted.panes.find(x => x.el.contains(pick)), next = parsePane(pick.value);
if (!p || !next) return;
go(p, next, false);
});
root.addEventListener('click', e => {
if (!mounted) return;
const show = e.target.closest?.('[data-pane-show]');
if (show) { mounted.show = show.dataset.paneShow === 'b' && mounted.panes.length === 2 ? 'b' : 'a'; layout(); paintBar(); writeUrl(); return; }
if (e.target.closest?.('[data-pane-add]')) { void addPane(); return; }
const close = e.target.closest?.('[data-pane-close]');
if (close) { closePane(mounted.panes.find(x => x.el.contains(close))); return; }
// A plain click on a link to a page a pane draws, in the pane's own organization, opens it in
// the pane. Anything else (another organization, a page a pane does not draw, a new tab) is
// an ordinary link to the full view.
const a = e.target.closest?.('a[href^="#/orgs/"]');
if (!a || a.hasAttribute('data-pane-full') || e.defaultPrevented || e.button !== 0 || e.metaKey || e.ctrlKey || e.shiftKey || e.altKey) return;
const p = mounted.panes.find(x => x.el.contains(a)); if (!p) return;
const m = /^#\/orgs\/([^/?#]+)(\/[^?#]*)$/.exec(a.getAttribute('href'));
let org, route;
try { org = decodeURIComponent(m?.[1] ?? ''); route = decodeURIComponent(m?.[2] ?? ''); } catch { return; }
if (org !== p.org || !page(route)) return;
e.preventDefault();
go(p, { org, route }, true);
});
}
function go(p, next, focusHead) {
p.org = next.org; p.route = next.route; p.html = null; p.project = null; p.title = null;
els(p).body.scrollTop = 0;
writeUrl();
void drawPane(p, { focusHead });
}
async function addPane() {
if (!mounted || mounted.panes.length !== 1) return;
const before = document.activeElement;
const [a] = mounted.panes, list = await orgList();
if (!mounted || mounted.panes.length !== 1) return;
const other = (list || []).find(o => o && !o.invalid && o.id !== a.org && ORG.test(o.id));
const b = makePane('b', other ? { org: other.id, route: '/organization' } : { org: a.org, route: a.route === '/agents' ? '/organization' : '/agents' });
mounted.panes.push(b); mounted.show = 'b';
layout(); paintBar(); writeUrl();
await drawPane(b);
if (mounted?.panes.includes(b) && mayFocus(b, before)) els(b).pick.focus({ preventScroll: true });
}
function closePane(p) {
if (!mounted || !p || mounted.panes.length !== 2) return;
clearTimeout(p.timer); p.turn++;
const keep = mounted.panes.find(x => x !== p);
// The remaining pane becomes the first: its page moves into pane a's element.
const a = mounted.panes[0];
if (keep !== a) {
const b = mounted.panes[1];
clearTimeout(b.timer); b.turn++;
a.org = keep.org; a.route = keep.route; a.html = null; a.project = null; a.title = keep.title; a.views = keep.views;
}
setHtml(els(mounted.panes[1]).body, ''); mounted.panes[1].html = null; mounted.panes[1].project = null;
mounted.panes = [a]; mounted.show = 'a';
layout(); paintBar(); writeUrl();
// The close button just left the page; focus goes to the remaining pane's picker now, and again
// after its draw only if the viewer has not moved elsewhere meanwhile.
els(a).pick.focus({ preventScroll: true });
const before = document.activeElement;
void drawPane(a).then(() => { if (mounted?.panes[0] === a && mayFocus(a, before)) els(a).pick.focus({ preventScroll: true }); });
}
function makePane(key, at) {
const el = mounted.root.querySelector(`#pane-${key}`);
return { key, el, org: at.org, route: at.route, turn: 0, timer: null, html: null, project: null, title: null, views: new Map() };
}
// ---------- public ----------
async function mount(container, query, { navigated = false } = {}) {
unmount();
const gen = ++mountGen;
container.innerHTML = frame();
const root = container.querySelector('[data-side-by-side]');
mounted = { root, panes: [], w: 50, show: 'a', gen, observers: [] };
// projects.js paints a project's content after its own reads; its links are rewritten as they
// land. One observer per pane element for the life of the mount, applying whichever pane object
// holds that element now, so a closed and re-added pane never runs an old organization's rewrite.
const m = mounted;
for (const key of ['a', 'b']) {
const body = root.querySelector(`#pane-${key} [data-pane-body]`);
const observer = new MutationObserver(() => {
if (mounted !== m) return;
const p = m.panes.find(x => x.key === key);
if (p) rewrite(p, body);
});
observer.observe(body, { childList: true, subtree: true });
m.observers.push(observer);
}
bind(root);
window.addEventListener('resize', fit);
document.title = 'Side by side · Mosaic Console';
if (navigated) root.querySelector('h1').focus({ preventScroll: true });
let wanted = readQuery(query);
if (!wanted.named) { const kept = readQuery(load() || ''); if (kept.a) wanted = { ...kept, named: true }; }
let at = [wanted.a, wanted.b].filter(Boolean);
if (!at.length) at = await defaults();
if (!mounted || gen !== mountGen) return;
listCache = await orgList();
if (!mounted || gen !== mountGen) return;
mounted.panes = at.slice(0, 2).map((x, i) => makePane(i ? 'b' : 'a', x));
mounted.w = Number.isFinite(wanted.w) && wanted.w ? clampW(wanted.w) : 50;
mounted.show = wanted.show === 'b' && mounted.panes.length === 2 ? 'b' : 'a';
layout(); paintBar(); writeUrl();
await Promise.all(mounted.panes.map(p => drawPane(p)));
}
function unmount() {
if (!mounted) return;
for (const p of mounted.panes) { clearTimeout(p.timer); p.turn++; }
for (const o of mounted.observers) o.disconnect();
window.removeEventListener('resize', fit);
mounted = null; mountGen++;
}
// The Console's Refresh: both panes read again now, each keeping its own focus and scroll.
function refresh() {
if (!mounted) return;
projectReads = new Map();
void orgList(true).then(rows => { if (rows) listCache = rows; });
for (const p of mounted.panes) void drawPane(p, { fresh: true });
}
// E2E6 P2-2: a pane showing the organization a write changed reads it again.
document.addEventListener('mosaic-org-changed', e => {
if (!mounted) return;
for (const p of mounted.panes) if (p.org === e.detail?.org) void drawPane(p, { fresh: true });
});
// The list the tabs draw from follows each fresh read of the organization list.
document.addEventListener('mosaic-org-list', e => { if (Array.isArray(e.detail?.rows)) listCache = e.detail.rows; });
window.MosaicPanes = Object.freeze({ mount, unmount, refresh, page });
})();
+1 -1
View File
@@ -30,7 +30,7 @@
.avatar-wrap{position:relative}.avatar-wrap>button{display:flex;align-items:center;gap:8px;min-height:44px;border:0;background:transparent;color:var(--strong);font:inherit;cursor:pointer}.avatar-initial{display:grid;place-items:center;width:34px;height:34px;border-radius:50%;background:var(--action);color:var(--onAction);font-weight:700}.avatar-menu{position:absolute;right:0;top:calc(100% + 8px);z-index:50;width:240px;background:var(--surface);border:1px solid var(--line);border-radius:var(--r);padding:8px;box-shadow:var(--shadow)}.avatar-menu[hidden]{display:none}.avatar-menu a,.avatar-menu button,.avatar-menu label,.avatar-menu #local-sign-out{display:block;width:100%;padding:9px;color:var(--text);font:inherit;text-align:left}.avatar-menu a{text-decoration:none}.avatar-menu button{background:none;border:0;cursor:pointer}.avatar-menu a:hover,.avatar-menu button:hover{background:var(--raised)}.avatar-menu label{font-size:12px;color:var(--muted)}.avatar-menu select{display:block;width:100%;min-height:44px;margin-top:4px}.avatar-menu small{display:block;color:var(--muted)}.avatar-menu #local-sign-out{opacity:.7}
#project-context,#project-tree,#board-tree{display:none!important}
.s1-section{font-size:14px;gap:12px}.s1-section[aria-current=page]{background:color-mix(in srgb,var(--action) 30%,var(--surface));color:var(--strong)}
.breadcrumbs{display:flex;gap:12px;align-items:center;margin:0 0 18px;color:var(--muted);font-size:13px}.breadcrumbs a{color:var(--action);text-decoration:none}.breadcrumbs [aria-current]{color:var(--strong)}
.breadcrumbs[hidden]{display:none}.breadcrumbs{display:flex;gap:12px;align-items:center;margin:0 0 18px;color:var(--muted);font-size:13px}.breadcrumbs a{color:var(--action);text-decoration:none}.breadcrumbs [aria-current]{color:var(--strong)}
#board-head h1{margin-bottom:0}#board-head p{margin:2px 0}.machine-off #status{display:none}
#dashboard-summary,.dashboard-card{border:1px solid var(--line);border-radius:var(--r-lg);background:var(--surface)}#dashboard-summary{margin:20px 0}.kpi-grid{display:grid;grid-template-columns:repeat(7,minmax(0,1fr));padding:18px 0}.kpi{padding:0 18px;border-right:1px solid var(--line);min-width:0}.kpi:last-child{border-right:0}.kpi div{font-size:12px;color:var(--strong);font-weight:700;min-height:36px}.kpi strong{display:block;font-size:28px;line-height:1.2;color:var(--strong)}.kpi span{display:block;color:var(--muted);font-size:12px;margin-top:4px}.kpi-footer{border-top:1px solid var(--line);padding:8px 18px;margin:0;color:var(--muted);font-size:12px}
#dashboard-cards{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px;margin:20px 0}.dashboard-card{padding:16px}.dashboard-card h2{margin:0 0 10px}.dashboard-card .processing-controls{padding:0;border:0}.dashboard-card .processing-controls strong{display:none}.dashboard-card .processing-controls .btn{min-height:44px}.dashboard-card ul{padding-left:20px}.dashboard-card a{color:var(--action)}
+19 -26
View File
@@ -27,10 +27,14 @@
}
document.addEventListener('focusin',e=>{const tab=e.target.closest?.('.project-tabs a'); if(tab) revealTab(tab.parentElement,tab);});
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const storageKey=window.MosaicOrg ? `mosaic-project-tree:${window.MosaicOrg.id}` : 'mosaic-project-tree';
// #1873 SP1: the tree and its open/closed state belong to the open organization; a switch drops both.
const storageKey=()=>window.MosaicOrg?.id ? `mosaic-project-tree:${window.MosaicOrg.id}` : 'mosaic-project-tree';
let treeRows=[], treeThreads=[], treeGeneration=0, treeState, treeRead=null, treeReadAt=0;
const treeFocus = new WeakMap();
try { treeState=JSON.parse(localStorage.getItem(storageKey) || '{}'); if (!treeState || Array.isArray(treeState) || typeof treeState !== 'object') treeState={}; } catch { treeState={}; }
const loadTreeState=()=>{ try { treeState=JSON.parse(localStorage.getItem(storageKey()) || '{}'); if (!treeState || Array.isArray(treeState) || typeof treeState !== 'object') treeState={}; } catch { treeState={}; } };
loadTreeState();
window.MosaicOrg?.ready?.then(loadTreeState);
document.addEventListener('mosaic-org-switch',()=>{ treeGeneration++; treeRows=[]; treeThreads=[]; treeRead=null; treeReadAt=0; loadTreeState(); });
// A side-by-side pane reads its own organization: its reads name that organization explicitly.
const at=(org,url)=>org && url.startsWith('/api/') ? `/api/orgs/${encodeURIComponent(org)}/${url.slice(5)}` : url;
async function read(url) {
@@ -76,7 +80,7 @@
target?.focus({preventScroll:true});
}
treeFocus.delete(container);
container.onclick=e=>{const button=e.target.closest('[data-project-disclosure]');if(!button)return;const id=button.dataset.projectDisclosure;treeState[id]=button.getAttribute('aria-expanded')!=='true';try{localStorage.setItem(storageKey,JSON.stringify(treeState));}catch{}drawTree(container,route);container.querySelector(`[data-project-disclosure="${id}"]`)?.focus();};
container.onclick=e=>{const button=e.target.closest('[data-project-disclosure]');if(!button)return;const id=button.dataset.projectDisclosure;treeState[id]=button.getAttribute('aria-expanded')!=='true';try{localStorage.setItem(storageKey(),JSON.stringify(treeState));}catch{}drawTree(container,route);container.querySelector(`[data-project-disclosure="${id}"]`)?.focus();};
} catch { if(generation===treeGeneration && container.isConnected && !document.body.classList.contains('signed-out')) {
treeRead=null;
const active=document.activeElement;
@@ -198,30 +202,22 @@
return `<h2>Reviewed deliveries <span class="project-count">${f.reviewed.length}</span></h2>${f.reviewed.length?f.reviewed.map(({r,file})=>`<div class="project-panel"><span class="project-delivery-icon" aria-hidden="true">▤</span><strong>${clean(file.name)}</strong> <span class="project-chip success">Reviewed</span><p>Request ${clean(r.id)} · from ${clean(r.thread.name)} · Reviewed delivery. Not landed or deployed.</p><div class="project-delivery-actions"><a class="btn" target="_blank" rel="noopener noreferrer" href="/api/requests/${encodeURIComponent(r.id)}/artifact/${encodeURIComponent(file.id)}/text">Open as text</a> <a class="btn" download href="/api/requests/${encodeURIComponent(r.id)}/artifact/${encodeURIComponent(file.id)}">Download</a>${deliveryPr(r)?` <a class="btn" target="_blank" rel="noopener noreferrer" href="${esc(deliveryPr(r))}">Open pull request</a>`:''}</div><p>Open shows plain text in a new tab. Downloaded HTML can be opened locally after saving.</p></div>`).join(''):`<p>${data.disabled?'Files are unavailable.':data.failed?'Reviewed files are unavailable.':data.requests.length?'No reviewed file is available.':'No request files yet. Files appear when a request in this project produces them.'}</p>`}<h2>Draft workspace <span class="project-count">${f.drafts.length}</span></h2><p>Names only. Draft files may change and are not reviewed deliveries.</p><div class="project-panel project-file-list">${f.drafts.length?f.drafts.map(({r,name})=>`<div><span><span aria-hidden="true">▤</span> <code>${clean(name)}</code></span><span>Request ${clean(r.id)} · <span class="project-chip">Draft</span></span></div>`).join(''):data.failed || data.requests.some(r=>r.workspace?.available!==true || !Array.isArray(r.workspace.entries))?'<p>Could not read draft workspace. Try again later.</p>':'<p>No draft files found.</p>'}${data.requests.some(r=>r.workspace?.truncated)?'<p>The draft list was truncated.</p>':''}</div><h2>Project documents ${docs?`<span class="project-count">${docs.length}</span>`:''}</h2><div class="project-panel project-file-list">${!project.repo?'No linked repository.':data.recordsMissing?window.MosaicRecords.markup(project.repo):!docs?'Project documents unavailable. Docs could not read this project’s repository.':docs.length?docs.map(name=>`<div><span><span aria-hidden="true">▤</span> <code>${clean(name)}</code></span><a href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent(name)}">Open in Docs</a></div>`).join(''):'No project documents found.'}</div>`;
}
const expandedPrds = new Set();
// U5: a project in a Side by side pane keeps its own request choice and PRD disclosure, so two
// panes showing the same project (or two organizations' projects with one id) never share them.
// The pane passes `views`, kept on the pane per organization, so the state outlives a repaint
// that replaces the content element (a new conversation changes the header). Without it, the
// state lives as long as the container.
const paneViews = new WeakMap();
const viewState=(container,pane,views)=>{if(!pane) return {selected:selectedRequests,expanded:expandedPrds}; if(views?.selected instanceof Map && views.expanded instanceof Set) return views; if(!paneViews.has(container)) paneViews.set(container,{selected:new Map(),expanded:new Set()}); return paneViews.get(container);};
function requirementView(data,project,selected,expandedSet=expandedPrds,idPrefix='') {
const pid=esc(idPrefix);
function requirementView(data,project,selected,expandedSet=expandedPrds) {
const options=data.requests.filter(r=>r.draft), r=options.find(x=>x.id===selected)||options[0], d=r?.draft;
const north=typeof data.north?.content==='string'?data.north.content:null;
const select=options.length>1?`<label>Request <select id="${pid}project-request-select">${options.map(x=>`<option value="${clean(x.id)}"${x===r?' selected':''}>${clean(x.id)} · ${clean(x.thread.name)}</option>`).join('')}</select></label>`:'';
const select=options.length>1?`<label>Request <select id="project-request-select">${options.map(x=>`<option value="${clean(x.id)}"${x===r?' selected':''}>${clean(x.id)} · ${clean(x.thread.name)}</option>`).join('')}</select></label>`:'';
const candidate=d?.candidate, expanded=r && expandedSet.has(project.id+':'+r.id);
const docPath=candidate?.prd_path, docLink=project.repo && typeof docPath==='string' && /^docs\/[A-Za-z0-9][A-Za-z0-9._-]{0,127}\.md$/.test(docPath) ? `#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent(docPath)}` : null;
const rows=candidate ? [['PRD version',candidate.prd_version],['Approved snapshot',d.snapshot.id || 'None'],['PRD file',docPath],['PRD blob',candidate.prd_blob],['Records commit',candidate.records_commit],['Confirmed intent commit',candidate.spec_commit],['Mode revision',candidate.mode_revision]].map(([label,value])=>`<div class="project-provenance-row"><span>${label}</span>${label==='PRD file' && docLink?`<a href="${docLink}"><code>${clean(value)}</code></a>`:`<code>${clean(value)}</code>`}</div>`).join('') : '<p>Unavailable until a PRD is read.</p>';
return `${r?`<div class="project-panel project-source">${select || `Request <code>${clean(r.id)}</code>`} · ${chip(r.state)} · from ${clean(r.thread.name)} <a href="${conversationLink(r.thread)}">Open conversation</a></div>`:select}<div class="project-columns"><section><h2>Project direction</h2><h3 id="${pid}project-north-star">North star</h3>${north!==null?`<div data-north-star></div><a class="project-text-link" href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent('spec/north-star.md')}">Open north star in Docs</a>`:data.northRecordsMissing?`<p>${window.MosaicRecords.markup(project.repo)}</p>`:data.northMissing?'<p>No north star yet.</p>':project.repo?'<p>North star unavailable. Docs could not read this project’s repository.</p>':`<p>This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet.</p>`}<h3 id="${pid}project-prd">${candidate?`PRD ${clean(candidate.prd_version)}`:'PRD'} ${candidate?`<span class="project-chip ${d.snapshot.id?'success':''}">${d.snapshot.id?'Approved':'Draft'}</span>`:''}</h3>${d?`<p>${d.snapshot.id?'Approved snapshot '+clean(d.snapshot.id):'This candidate has no active approved snapshot.'}</p><div class="project-panel project-prd-panel"><div class="project-prd-preview${expanded?' expanded':''}" data-prd></div><button type="button" class="btn project-prd-toggle" aria-expanded="${!!expanded}">${expanded?'Show less':'Show full PRD'}</button></div><h3>Requirements <span class="project-count">${d.requirements.length}</span></h3><div class="project-panel">${d.requirements.map((req,i)=>`<details data-restore-key="req:${clean(r.id)}:${clean(req.id)}"><summary>${clean(req.id)} · ${clean(req.title)}</summary><p>${clean(req.text)}</p><p>Requirement identity: <code>${clean(candidate.requirements[i]?.path)}</code> · <code>${clean(candidate.requirements[i]?.blob)}</code></p></details>`).join('')}</div>`:`<p>${(data.failed || data.requests.some(x=>x.materialFailed))?'Request or PRD unavailable. Refresh to try again.':'No current PRD candidate or approved snapshot. Waiting for a PRD submission.'}</p>`}${d && data.requests.some(x=>x.materialFailed)?'<p role="status">Some request PRDs could not be read. Refresh to try again.</p>':''}</section><aside class="project-panel project-provenance"><details data-restore-key="provenance"${matchMedia('(min-width:700px)').matches?' open':''}><summary>Version and provenance</summary>${rows}${candidate?`<p>Approval and revocation live in the conversation's Request details.</p><a href="${conversationLink(r.thread)}">Open conversation</a>`:''}</details></aside></div>`;
return `${r?`<div class="project-panel project-source">${select || `Request <code>${clean(r.id)}</code>`} · ${chip(r.state)} · from ${clean(r.thread.name)} <a data-full-view href="${conversationLink(r.thread)}">Open conversation</a></div>`:select}<div class="project-columns"><section><h2>Project direction</h2><h3 id="project-north-star">North star</h3>${north!==null?`<div data-north-star></div><a class="project-text-link" href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent('spec/north-star.md')}">Open north star in Docs</a>`:data.northRecordsMissing?`<p>${window.MosaicRecords.markup(project.repo)}</p>`:data.northMissing?'<p>No north star yet.</p>':project.repo?'<p>North star unavailable. Docs could not read this project’s repository.</p>':`<p>This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet.</p>`}<h3 id="project-prd">${candidate?`PRD ${clean(candidate.prd_version)}`:'PRD'} ${candidate?`<span class="project-chip ${d.snapshot.id?'success':''}">${d.snapshot.id?'Approved':'Draft'}</span>`:''}</h3>${d?`<p>${d.snapshot.id?'Approved snapshot '+clean(d.snapshot.id):'This candidate has no active approved snapshot.'}</p><div class="project-panel project-prd-panel"><div class="project-prd-preview${expanded?' expanded':''}" data-prd></div><button type="button" class="btn project-prd-toggle" aria-expanded="${!!expanded}">${expanded?'Show less':'Show full PRD'}</button></div><h3>Requirements <span class="project-count">${d.requirements.length}</span></h3><div class="project-panel">${d.requirements.map((req,i)=>`<details data-restore-key="req:${clean(r.id)}:${clean(req.id)}"><summary>${clean(req.id)} · ${clean(req.title)}</summary><p>${clean(req.text)}</p><p>Requirement identity: <code>${clean(candidate.requirements[i]?.path)}</code> · <code>${clean(candidate.requirements[i]?.blob)}</code></p></details>`).join('')}</div>`:`<p>${(data.failed || data.requests.some(x=>x.materialFailed))?'Request or PRD unavailable. Refresh to try again.':'No current PRD candidate or approved snapshot. Waiting for a PRD submission.'}</p>`}${d && data.requests.some(x=>x.materialFailed)?'<p role="status">Some request PRDs could not be read. Refresh to try again.</p>':''}</section><aside class="project-panel project-provenance"><details data-restore-key="provenance"${matchMedia('(min-width:700px)').matches?' open':''}><summary>Version and provenance</summary>${rows}${candidate?`<p>Approval and revocation live in the conversation's Request details.</p><a data-full-view href="${conversationLink(r.thread)}">Open conversation</a>`:''}</details></aside></div>`;
}
function overview(data,project,canSend,receipt='') {
const active=data.requests.filter(r=>r.state && !ended(r.state)), waiting=active.filter(r=>needs(r.state)), ordered=[...data.requests].sort(requestOrder), first=ordered[0], threads=[...data.threads];
if(first) threads.sort((a,b)=>Number(b.id===first.thread.id)-Number(a.id===first.thread.id));
const f=filesData(data), filesKnown=!data.failed && !!f.docs && data.requests.every(r=>r.workspace?.available===true && Array.isArray(r.workspace.entries) && r.state), count=filesKnown?f.reviewed.length+f.drafts.length+f.docs.length:'–';
const n=typeof data.north?.content==='string'?data.north.content:null, candidate=ordered.find(r=>r.draft)?.draft;
const metrics=[['Requests in progress',data.failed?'–':active.length,data.failed?'Not available yet':active[0]?label(active[0].state):'No active requests',first?conversationLink(first.thread):path(project.id,'conversations')],['Needs your input',data.failed?'–':waiting.length,data.failed?'Not available yet':waiting.length?label(waiting[0].state):'Nothing waiting',waiting[0]?conversationLink(waiting[0].thread):path(project.id,'conversations')],['Conversations',threads.length,'Project conversations',path(project.id,'conversations')],['Files',count,filesKnown?`${f.reviewed.length} reviewed · ${f.drafts.length} draft · ${f.docs.length} docs`:data.recordsMissing?'No project records yet':'Not available yet',path(project.id,'files')]];
return `${waiting.length?`<div class="project-panel project-decision" role="status">${waiting.length} ${waiting.length===1?'decision needs':'decisions need'} your input. <a class="btn primary" href="${conversationLink(waiting[0].thread)}">Review decision</a></div>`:''}<div class="project-metrics">${metrics.map(([title,value,caption,href])=>`<a href="${href}"><span>${title}</span><strong>${value}</strong><small>${clean(caption)}</small></a>`).join('')}<p>Updated just now · Showing requests from recent messages.</p></div><div class="project-columns"><section><div class="project-section-title"><h2>Current work</h2>${canSend&&!project.archived?`<a class="btn" href="${path(project.id,'conversations')}?new=1">${plusIcon}New conversation</a>`:''}</div>${threads.length?threads.map((t,i)=>i===0?card(t,workFor(data,t),data.failed):`<a class="project-row" href="${conversationLink(t)}"><strong>${clean(t.name)}</strong><small>With ${clean(t.instance)} · ${workFor(data,t) ? label(workFor(data,t).state) : data.failed ? 'Status unavailable' : 'No active request'}</small>${workFor(data,t)?chip(workFor(data,t).state):''}</a>`).join(''):'<p>No conversations yet. Start one to begin work.</p>'}<h2>Tasks <span class="project-count">${taskRefs(data).length}</span></h2><div class="project-panel">${taskRefs(data).length?taskRefs(data).slice(0,2).map(ref=>`<div>${taskLink(ref,data)}</div>`).join(''):data.failed?'<p>Request tasks unavailable. Refresh to try again.</p>':'<p>No request tasks available.</p>'}<a href="${path(project.id,'tasks')}">View all project tasks</a></div></section><aside class="project-panel"><h2>Project direction</h2><h3>North star</h3>${n!==null?`<div data-north-star></div><a class="project-text-link" href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent('spec/north-star.md')}">Open north star in Docs</a>`:`<p>${data.northRecordsMissing?window.MosaicRecords.markup(project.repo):data.northMissing?'No north star yet.':project.repo?'North star unavailable. Docs could not read this project’s repository.':"This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet."}</p>`}<h3>${candidate?'PRD '+clean(candidate.candidate.prd_version):'PRD'} ${candidate?.snapshot.id?'<span class="project-chip success">Approved</span>':''}</h3><p>${candidate?(candidate.snapshot.id?'Approved snapshot '+clean(candidate.snapshot.id):'Draft'):(data.failed || data.requests.some(x=>x.materialFailed)?'PRD unavailable.':'No current PRD available.')}</p>${candidate && data.requests.some(x=>x.materialFailed)?'<p role="status">Some request PRDs could not be read. Refresh to try again.</p>':''}<a href="${path(project.id,'requirements')}">Open PRD and requirements</a><h3>Files ${filesKnown?`<span class="project-count">${count}</span>`:''}</h3>${[...f.reviewed.map(x=>({name:x.file.name,reviewed:true})),...f.drafts.map(x=>({name:x.name,reviewed:false}))].slice(0,3).map(file=>file.reviewed?`<p><a href="${path(project.id,'files')}"><code>${clean(file.name)}</code> · Reviewed</a></p>`:`<p><code>${clean(file.name)}</code> · Draft</p>`).join('')||(data.failed?'<p>Request files unavailable.</p>':'<p>No request files available.</p>')}<a href="${path(project.id,'files')}">All files</a><h3>Project facts</h3><div class="project-provenance-row"><span>Repository</span><span>${project.repo?clean(project.repo):'Not linked'}</span></div>${roomControls(project,data.room,canSend,receipt)}<div class="project-provenance-row"><span>Mode</span><span>${first?.state?.mode?clean(modeLabel(first.state.mode)):data.failed?'Unavailable':'No active request'}</span></div></aside></div>`;
const metrics=[['Requests in progress',data.failed?'–':active.length,data.failed?'Not available yet':active[0]?label(active[0].state):'No active requests',first?conversationLink(first.thread):path(project.id,'conversations'),!!first],['Needs your input',data.failed?'–':waiting.length,data.failed?'Not available yet':waiting.length?label(waiting[0].state):'Nothing waiting',waiting[0]?conversationLink(waiting[0].thread):path(project.id,'conversations'),!!waiting[0]],['Conversations',threads.length,'Project conversations',path(project.id,'conversations')],['Files',count,filesKnown?`${f.reviewed.length} reviewed · ${f.drafts.length} draft · ${f.docs.length} docs`:data.recordsMissing?'No project records yet':'Not available yet',path(project.id,'files')]];
return `${waiting.length?`<div class="project-panel project-decision" role="status">${waiting.length} ${waiting.length===1?'decision needs':'decisions need'} your input. <a class="btn primary" data-full-view href="${conversationLink(waiting[0].thread)}">Review decision</a></div>`:''}<div class="project-metrics">${metrics.map(([title,value,caption,href,full])=>`<a${full?' data-full-view':''} href="${href}"><span>${title}</span><strong>${value}</strong><small>${clean(caption)}</small></a>`).join('')}<p>Updated just now · Showing requests from recent messages.</p></div><div class="project-columns"><section><div class="project-section-title"><h2>Current work</h2>${canSend&&!project.archived?`<a class="btn" href="${path(project.id,'conversations')}?new=1">${plusIcon}New conversation</a>`:''}</div>${threads.length?threads.map((t,i)=>i===0?card(t,workFor(data,t),data.failed):`<a class="project-row" href="${conversationLink(t)}"><strong>${clean(t.name)}</strong><small>With ${clean(t.instance)} · ${workFor(data,t) ? label(workFor(data,t).state) : data.failed ? 'Status unavailable' : 'No active request'}</small>${workFor(data,t)?chip(workFor(data,t).state):''}</a>`).join(''):'<p>No conversations yet. Start one to begin work.</p>'}<h2>Tasks <span class="project-count">${taskRefs(data).length}</span></h2><div class="project-panel">${taskRefs(data).length?taskRefs(data).slice(0,2).map(ref=>`<div>${taskLink(ref,data)}</div>`).join(''):data.failed?'<p>Request tasks unavailable. Refresh to try again.</p>':'<p>No request tasks available.</p>'}<a href="${path(project.id,'tasks')}">View all project tasks</a></div></section><aside class="project-panel"><h2>Project direction</h2><h3>North star</h3>${n!==null?`<div data-north-star></div><a class="project-text-link" href="#/docs/${encodeURIComponent(project.repo)}/${encodeURIComponent('spec/north-star.md')}">Open north star in Docs</a>`:`<p>${data.northRecordsMissing?window.MosaicRecords.markup(project.repo):data.northMissing?'No north star yet.':project.repo?'North star unavailable. Docs could not read this project’s repository.':"This project has no linked repository. The north star and project documents live in a repository. Linking one to an existing project isn't available yet."}</p>`}<h3>${candidate?'PRD '+clean(candidate.candidate.prd_version):'PRD'} ${candidate?.snapshot.id?'<span class="project-chip success">Approved</span>':''}</h3><p>${candidate?(candidate.snapshot.id?'Approved snapshot '+clean(candidate.snapshot.id):'Draft'):(data.failed || data.requests.some(x=>x.materialFailed)?'PRD unavailable.':'No current PRD available.')}</p>${candidate && data.requests.some(x=>x.materialFailed)?'<p role="status">Some request PRDs could not be read. Refresh to try again.</p>':''}<a href="${path(project.id,'requirements')}">Open PRD and requirements</a><h3>Files ${filesKnown?`<span class="project-count">${count}</span>`:''}</h3>${[...f.reviewed.map(x=>({name:x.file.name,reviewed:true})),...f.drafts.map(x=>({name:x.name,reviewed:false}))].slice(0,3).map(file=>file.reviewed?`<p><a href="${path(project.id,'files')}"><code>${clean(file.name)}</code> · Reviewed</a></p>`:`<p><code>${clean(file.name)}</code> · Draft</p>`).join('')||(data.failed?'<p>Request files unavailable.</p>':'<p>No request files available.</p>')}<a href="${path(project.id,'files')}">All files</a><h3>Project facts</h3><div class="project-provenance-row"><span>Repository</span><span>${project.repo?clean(project.repo):'Not linked'}</span></div>${roomControls(project,data.room,canSend,receipt)}<div class="project-provenance-row"><span>Mode</span><span>${first?.state?.mode?clean(modeLabel(first.state.mode)):data.failed?'Unavailable':'No active request'}</span></div></aside></div>`;
}
function tasksView(data) {
const refs=taskRefs(data);
@@ -256,9 +252,7 @@
const focus=f.id ? root.querySelector('#'+CSS.escape(f.id)) : f.details ? [...root.querySelectorAll('details[data-restore-key]')].find(el=>el.dataset.restoreKey===f.details)?.querySelector(':scope > summary') : root.querySelectorAll(FOCUSABLE)[f.index];
focus?.focus({preventScroll:true});
}
// A Side by side pane passes `idPrefix` (pane-a-, pane-b-), so the same project in both panes
// draws distinct ids; the full view passes none and keeps its ids.
async function mountContent({container,project,threads,section,canSend,restore,roomReceipt,org=null,pane=false,views:paneState=null,idPrefix=''}) {
async function mountContent({container,project,threads,section,canSend,restore,roomReceipt,org=null}) {
if(!container || !project) return;
const generation=epoch, run=(contentRuns.get(container) || 0)+1;
contentRuns.set(container,run);
@@ -266,11 +260,10 @@
const data=await gather(project,threads,org).catch(()=>null);
if(!container.isConnected || generation!==epoch || contentRuns.get(container)!==run || document.body.classList.contains('signed-out')) return;
if(!data){contentPaints.delete(container);container.textContent='Project data unavailable. Refresh to try again.';return;}
const views=viewState(container,pane,paneState), selectedRequests=views.selected, expandedPrds=views.expanded;
const selected=selectedRequests.get(project.id);
if(selected && !data.requests.some(r=>r.id===selected && r.draft)) selectedRequests.delete(project.id);
const selection=selectedRequests.get(project.id);
const view = section==='requirements'?requirementView(data,project,selection,expandedPrds,idPrefix):section==='files'?filesView(data,project):section==='tasks'?tasksView(data):overview(data,project,canSend,roomReceipt);
const view = section==='requirements'?requirementView(data,project,selection,expandedPrds):section==='files'?filesView(data,project):section==='tasks'?tasksView(data):overview(data,project,canSend,roomReceipt);
const selectedRequest=data.requests.find(r=>r.id===(selection||data.requests.find(x=>x.draft)?.id));
// The generated presentation and separately mounted Markdown determine visible content.
const signature=JSON.stringify([view, section==='requirements' ? selectedRequest?.draft?.prd : null, ['requirements','overview'].includes(section) ? data.north?.content : null, data.failed && ['files','tasks'].includes(section)]);
@@ -280,7 +273,7 @@
// Retained controls (the request selector) draw from the newest accepted read, even when
// this read changes nothing visible and the DOM is kept.
contentModels.set(container,{data,project,section,canSend,roomReceipt});
if(!pane) window.MosaicOnboarding?.offer(container,{project,section,north:data.north,docs:data.docs,threads:data.threads,canSend}); // F2: its panel sits before the container, outside draw().
window.MosaicOnboarding?.offer(container,{project,section,north:data.north,docs:data.docs,threads:data.threads,canSend}); // F2: its panel sits before the container, outside draw().
if (contentPaints.get(container) === signature) return;
contentPaints.set(container, signature);
// Capture at commit time: the user may have interacted while the read was pending.
@@ -288,12 +281,12 @@
const liveRestore=contentPaints.has(container) && container.children.length ? captureView(container) : null;
const draw=selected=>{
const {data,project,section,canSend,roomReceipt}=contentModels.get(container);
container.innerHTML=section==='requirements'?requirementView(data,project,selected,expandedPrds,idPrefix):section==='files'?filesView(data,project):section==='tasks'?tasksView(data):overview(data,project,canSend,roomReceipt);
container.innerHTML=section==='requirements'?requirementView(data,project,selected,expandedPrds):section==='files'?filesView(data,project):section==='tasks'?tasksView(data):overview(data,project,canSend,roomReceipt);
if(data.failed && ['files','tasks'].includes(section)) container.insertAdjacentHTML('afterbegin','<p role="status">Some request data could not be read; this list may be incomplete.</p>');
const selectedRequest=data.requests.find(r=>r.id===(selected||data.requests.find(x=>x.draft)?.id));
const md=container.querySelector('[data-prd]'); if(md && selectedRequest?.draft) { md.replaceChildren(window.MosaicMarkdown?.render(selectedRequest.draft.prd) || document.createTextNode(selectedRequest.draft.prd)); const toggle=container.querySelector('.project-prd-toggle'); toggle.hidden=!md.classList.contains('expanded') && md.scrollHeight<=md.clientHeight; toggle.addEventListener('click',()=>{const key=project.id+':'+selectedRequest.id; if(expandedPrds.has(key)) expandedPrds.delete(key); else expandedPrds.add(key); const open=expandedPrds.has(key); md.classList.toggle('expanded',open); toggle.setAttribute('aria-expanded',String(open));toggle.textContent=open?'Show less':'Show full PRD';}); }
const north=container.querySelector('[data-north-star]'); if(north && typeof data.north?.content==='string') { const text=section==='overview' && data.north.content.length>500 ? previewCut(data.north.content,500) : data.north.content; north.replaceChildren(window.MosaicMarkdown?.render(text) || document.createTextNode(text)); }
const requestSelect='#'+CSS.escape(idPrefix+'project-request-select');
const requestSelect='#project-request-select';
container.querySelector(requestSelect)?.addEventListener('change',e=>{selectedRequests.set(project.id,e.target.value);draw(e.target.value);container.querySelector(requestSelect)?.focus({preventScroll:true});});
};
draw(selection);
@@ -301,8 +294,8 @@
if (restore) {
restoreView(container,restore);
}
const sectionTarget=pane ? null : new URLSearchParams(location.hash.split('?')[1] || '').get('section');
if(section==='requirements' && ['prd','north-star'].includes(sectionTarget)) container.querySelector('#'+CSS.escape(idPrefix+'project-'+sectionTarget))?.scrollIntoView({block:'start'});
const sectionTarget=new URLSearchParams(location.hash.split('?')[1] || '').get('section');
if(section==='requirements' && ['prd','north-star'].includes(sectionTarget)) container.querySelector('#project-'+sectionTarget)?.scrollIntoView({block:'start'});
}
// Cut at a word boundary, unless that would leave only a markdown marker (a long heading).
function previewCut(content,max) {
+6 -5
View File
@@ -20,7 +20,8 @@
const txt = value => esc(inert(value));
const enc = encodeURIComponent;
const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,159}$/;
const STORE = window.MosaicOrg ? `mosaic-request-answer:${window.MosaicOrg.id}:` : 'mosaic-request-answer:';
// #1873 SP1: read per call, so answers stay with the organization open when they were written.
const storeOf = () => window.MosaicOrg?.id ? `mosaic-request-answer:${window.MosaicOrg.id}:` : 'mosaic-request-answer:';
const QUESTION_PHASES = ['discovery', 'prd-review', 'planning'];
const MODE_PHASES = [...QUESTION_PHASES, 'implementation', 'review', 'delivery'];
const PICKER_CODES = ['request-existing-project', 'request-attachment-selected'];
@@ -55,15 +56,15 @@
// removed once the bus has answered either way, so only a lost response leaves one behind.
const load = id => {
try {
const v = JSON.parse(sessionStorage.getItem(STORE + id));
const v = JSON.parse(sessionStorage.getItem(storeOf() + id));
return v && text(v.op) && ID.test(v.op) && text(v.text) && text(v.question) && ID.test(v.question) && positive(v.revision)
? { op: v.op, text: v.text, question: v.question, revision: v.revision } : null;
} catch { return null; }
};
const save = (id, record) => { try { sessionStorage.setItem(STORE + id, JSON.stringify(record)); } catch { /* kept in memory only */ } };
const drop = id => { try { sessionStorage.removeItem(STORE + id); } catch { /* nothing stored */ } };
const save = (id, record) => { try { sessionStorage.setItem(storeOf() + id, JSON.stringify(record)); } catch { /* kept in memory only */ } };
const drop = id => { try { sessionStorage.removeItem(storeOf() + id); } catch { /* nothing stored */ } };
const dropAll = () => {
try { for (const key of Object.keys(sessionStorage)) if (key.startsWith(STORE)) sessionStorage.removeItem(key); } catch { /* nothing stored */ }
try { for (const key of Object.keys(sessionStorage)) if (key.startsWith(storeOf())) sessionStorage.removeItem(key); } catch { /* nothing stored */ }
};
function forget() {
+38 -3
View File
@@ -462,7 +462,7 @@ html[data-organizations] .ws-chips{display:flex;flex-wrap:wrap;align-items:cente
/* Page frame (sample main column). */
html[data-organizations] .content:has(.ws){padding-top:18px;padding-inline:24px}
body:has([data-org-dashboard]) #breadcrumbs,body:has([data-org-agents]) #breadcrumbs{display:none}
body:has([data-org-dashboard]) #breadcrumbs{display:none}
html[data-organizations] .ws{font-size:14px;line-height:1.5;color:var(--text);min-width:0}
html[data-organizations] .ws h1{margin:0;font-size:28px;font-weight:800;letter-spacing:-.02em;line-height:1.15;color:var(--strong)}
html[data-organizations] .ws h1:focus,html[data-organizations] .ws h1:focus-visible{outline:none}
@@ -550,6 +550,11 @@ html[data-organizations] .ws-levels .mlabel{display:none;align-items:center;gap:
html[data-organizations] .ws-agent{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);border-radius:999px;padding:2px 10px 2px 8px;font-size:12.5px;font-weight:600;background:var(--canvas);margin:2px 4px 2px 0;color:var(--strong)}
html[data-organizations] .ws-agent small{color:var(--muted);font-weight:500;font-size:11px}
html[data-organizations] .ws-agent .ws-dot b{font-size:11px;width:10px}
html[data-organizations] .ws-agent{flex-wrap:wrap}
html[data-organizations] .ws-agent .btn{min-height:24px;padding:0 10px;font-size:11.5px;border-radius:999px}
html[data-organizations] .ws-fire-confirm{display:inline-flex;flex-wrap:wrap;align-items:center;gap:6px;font-weight:500}
html[data-organizations] [data-agents-receipt]:empty{display:none}
html[data-organizations] [data-agents-receipt] .receipt{margin:0 0 12px}
html[data-organizations] .ws-rules{display:grid;gap:10px;font-size:13px}
html[data-organizations] .ws-rules p{display:flex;flex-wrap:wrap;align-items:baseline;gap:6px;margin:0}
html[data-organizations] .ws-psel{display:inline-flex;align-items:center;gap:6px;border:1px solid var(--line);background:var(--surface);border-radius:var(--r);padding:0 0 0 8px;font-size:13px;color:var(--strong);white-space:nowrap;max-width:100%}
@@ -562,7 +567,7 @@ html[data-organizations] .ws-rules .ws-lvl{margin-right:0}
html[data-organizations] .ws-scope{margin:-8px 0 14px}
/* Across organizations (U3): the main dashboard, projects and inbox, samples 02, 04 and 05. */
body:has([data-ws-home]) #breadcrumbs,body:has([data-ws-projects]) #breadcrumbs,body:has([data-ws-inbox]) #breadcrumbs{display:none}
body:has([data-ws-home]) #breadcrumbs{display:none}
html[data-organizations] .ws-edge{box-shadow:inset 3px 0 0 var(--org)}
html[data-organizations] .ws-orgref{display:inline-flex;align-items:center;gap:6px;white-space:nowrap;color:var(--strong);font-weight:600}
html[data-organizations] .ws-chip{display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:600;padding:1px 7px;border-radius:4px;background:var(--raised);color:var(--strong);white-space:nowrap;line-height:1.5}
@@ -586,6 +591,18 @@ html[data-organizations] .ws-bar i{display:block;background:var(--org,var(--acti
html[data-organizations] .ws-by{display:flex;flex-wrap:wrap;gap:4px 10px;font-size:12px;color:var(--text)}
html[data-organizations] .ws-by>span{display:inline-flex;align-items:center;gap:4px;white-space:nowrap;font-variant-numeric:tabular-nums}
html[data-organizations] .ws-by .ws-av{width:14px;height:14px;border-radius:3px;font-size:7px}
html[data-organizations] .ws-orgtbl td{vertical-align:top}
html[data-organizations] .ws-orgtbl .who{display:flex;flex-wrap:wrap;align-items:center;gap:4px 10px;min-width:0}
html[data-organizations] .ws-orgtbl .who a{display:inline-flex;align-items:center;gap:8px;min-width:0;color:var(--strong);font-weight:700;text-decoration:none}
html[data-organizations] .ws-orgtbl .who a:hover .nm{text-decoration:underline}
html[data-organizations] .ws-orgtbl .who .ws-dot{font-size:12px;color:var(--muted)}
html[data-organizations] .ws-orgtbl .who .ws-dot.s-working b{color:var(--success)}
html[data-organizations] .ws-orgtbl .who .why{flex:1 0 100%;font-size:12px;color:var(--danger);overflow-wrap:anywhere}
html[data-organizations] .ws-orgtbl tr.off .ws-dot{color:var(--danger)}
/* #1873 SP2: a figure keeps its words on one line ("4 agents (0 working)", "none waiting"); the organization cell takes the wrap. */
html[data-organizations] .ws-orgtbl td:not(.who){white-space:nowrap}
html[data-organizations] .ws-dash [data-org-down]{margin:0 0 14px}
html[data-organizations] .ws-dash [data-org-down] .why{display:block;margin-top:4px;color:var(--muted)}
html[data-organizations] .ws-orgcards{list-style:none;margin:0;padding:0;display:grid;gap:8px;grid-template-columns:repeat(auto-fill,minmax(220px,1fr))}
html[data-organizations] .ws-orgcard a{display:grid;grid-template-columns:auto minmax(0,1fr) auto;gap:2px 10px;align-items:center;padding:9px 12px;border:1px solid var(--line);border-radius:8px;background:var(--surface);box-shadow:inset 3px 0 0 var(--org);color:var(--text);text-decoration:none;font-size:13px;height:100%}
html[data-organizations] .ws-orgcard a:hover{background:var(--raised)}
@@ -623,7 +640,7 @@ html[data-organizations] .ws-needs .ws-chip{grid-row:1/3;grid-column:3}
html[data-organizations] .ws-more-line{margin:6px 0 0}
html[data-organizations] .ws-sess td.who{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:0;width:100%}
html[data-organizations] .ws-sess td.who .ws-orgref{vertical-align:middle}
html[data-organizations] .ws-sess td.st{white-space:nowrap}
html[data-organizations] .ws-sess td.ws-st{white-space:nowrap}
/* Filters and tables on Projects and Inbox. */
html[data-organizations] .ws-toolbar{display:flex;flex-wrap:wrap;gap:8px 10px;align-items:center;margin-bottom:12px}
html[data-organizations] .ws-toolbar .ws-right{align-items:center}
@@ -669,6 +686,24 @@ html[data-organizations] .ws-ibx .q:hover{text-decoration:underline}
html[data-organizations] .ws-ibx .via{display:block;font-size:12px;color:var(--muted)}
html[data-organizations] .ws-ibx tr.on{background:color-mix(in srgb,var(--action) 10%,var(--surface))}
html[data-organizations] .ws-ibx tr.on td:first-child{box-shadow:inset 3px 0 0 var(--action)}
/* SP3: the system Inbox's filter rows and the organization and project chips on each item. */
html[data-organizations] .ws-ibx-filters{flex-direction:column;align-items:flex-start;gap:8px}
html[data-organizations] .ws-fgroup{display:flex;gap:6px 8px;align-items:center;flex-wrap:wrap}
html[data-organizations] .ws-ibx-filters .ws-fchips>.ws-label,html[data-organizations] .ws-fgroup>.ws-label{min-width:36px}
html[data-organizations] .ws-ichips{display:flex;flex-wrap:wrap;align-items:center;gap:4px 6px;margin-top:3px}
html[data-organizations] .ws-ichips .via{display:inline}
/* #1873 SP5: the system Agents table. Open and Fire sit side by side at one size; a confirm wraps in its cell. */
html[data-organizations] .ws-agt .ws-arole{font-size:12px;color:var(--muted)}
html[data-organizations] .ws-agt td.ws-act{white-space:nowrap;text-align:right;width:1%}
html[data-organizations] .ws-agt td.ws-act>*+*{margin-left:6px}
html[data-organizations] .ws-agt td.ws-act .btn.small{min-height:0;padding:4px 10px;font:600 13px/1.4 var(--font);border-radius:var(--r)}
html[data-organizations] .ws-agt .ws-fire-confirm{display:inline-flex;flex-wrap:wrap;justify-content:flex-end;align-items:center;gap:6px;white-space:normal}
html[data-organizations] .ws-agt .t2.mono{overflow-wrap:anywhere}
html[data-organizations] .ws-agt tr.on{background:color-mix(in srgb,var(--action) 10%,var(--surface))}
html[data-organizations] .ws-agt tr.on td:first-child{box-shadow:inset 3px 0 0 var(--action)}
@media (forced-colors:active){html[data-organizations] .ws-agt tr.on td:first-child{border-left:3px solid Highlight}}
html[data-organizations] .ws-ochip{background:color-mix(in srgb,var(--org,var(--muted)) 14%,var(--surface))}
html[data-organizations] .ws-ochip i{width:8px;height:8px;border-radius:999px;background:var(--org,var(--muted));flex:none}
html[data-organizations] .ws-msrc{align-items:center;gap:5px;font-size:12px;color:var(--muted);margin-bottom:2px}
html[data-organizations] .ws-insp{border:1px solid var(--line);border-radius:10px;background:var(--surface);display:flex;flex-direction:column;min-width:0;position:sticky;top:12px;max-height:calc(100vh - 80px);overflow:auto}
html[data-organizations] .ws-insp header{display:flex;align-items:center;gap:8px;padding:10px 14px;border-bottom:1px solid var(--line);background:var(--surface);position:sticky;top:0;z-index:1;box-shadow:inset 3px 0 0 var(--org)}
+136 -29
View File
@@ -10,6 +10,12 @@
// shown as the bus answered it. Vikunja tasks are read only here: the bus refuses them
// (tracker-not-store), so the board offers no control for them.
// bus.js calls view() for #/tasks in organization mode and repaints it on its own 10 s poll.
// SP4 (#1873): #/tasks is a system page, every organization on one board; #/orgs/<id>/tasks is the
// same board scoped to that organization (bus.js passes the scope). The org and project filters live
// in the address query (?org=, ?project=), so a reload keeps them. A move or edit goes to the row's own
// organization and is offered only where that organization's own config takes task changes (bus.js
// passes writesIn), never judged by the organization opened last. A card opened on the system board
// links to the task in its organization (#/orgs/<id>/tasks?task=<ref>), which opens it there.
(() => {
'use strict';
if (!document.documentElement.hasAttribute('data-organizations')) return;
@@ -56,6 +62,11 @@
// `opened` is the task as the edit dialog showed it: Save diffs against it and sends its digest, so a
// poll that reads a newer task while the dialog is open turns a stale save into a task-conflict.
let snap = null, canWrite = false, notice = null, dragging = null, dragEnded = null, opened = null;
// `scope` is the one organization of #/orgs/<id>/tasks, or null on the system board. `allowed` holds
// the organizations whose own config takes task changes from this Console, asked on every read.
let scope = null, writesIn = null, allowed = new Set(), autoOpened = null;
const ORG_ID = /^[a-z0-9][a-z0-9._-]{0,63}$/, TASK_REF = /^(?:task:\d{1,15}|vikunja:\d{1,15}\/\d{1,15})$/;
const ws = () => window.MosaicWorkspace;
const mark = () => window.MosaicWorkspace?.orgMark;
const orgOf = id => snap?.orgs.find(o => o.id === id) || { id, label: id, theme: null };
@@ -69,7 +80,7 @@
const stateOf = t => (STATE_LABEL[t.state] ? t.state : UNREAD);
// An org can answer while its tasks read fails (errors.tasks): its tasks are unavailable, not zero.
const tasksRead = o => o?.state === 'ok' && !o.errors?.tasks;
const orgWritable = o => canWrite && tasksRead(o) && o.tracker === 'built-in';
const orgWritable = o => canWrite && tasksRead(o) && o.tracker === 'built-in' && allowed.has(o.id);
const taskWritable = t => t.writable === true && typeof t.digest === 'string' && orgWritable(orgOf(t.org));
const projectName = t => t.project?.name || t.project?.key || null;
const dueText = iso => {
@@ -84,6 +95,7 @@
const PROJECT_SELECTOR = /^[a-z0-9][a-z0-9._-]{0,63}:[A-Za-z0-9._-]{1,128}$/, ROLE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
function readQuery() {
const q = new URLSearchParams({ sections: 'tasks,projects' });
if (scope) q.set('org', scope);
if (PROJECT_SELECTOR.test(filter.project)) q.set('project', filter.project);
if (filter.state) q.set('task-state', filter.state === UNREAD ? 'open' : filter.state);
if (ROLE.test(filter.assignee)) q.set('assignee', filter.assignee);
@@ -97,7 +109,6 @@
mark()?.ready().catch(() => null),
window.MosaicConsole?.ready,
]);
canWrite = window.MosaicConsole?.config?.orgSetup === true;
if (response.type === 'opaqueredirect' || !response.ok) {
const body = await response.json().catch(() => null);
throw Object.assign(new Error('read failed'), { status: response.status, message: typeof body?.message === 'string' ? body.message : null });
@@ -106,16 +117,46 @@
if (!Array.isArray(body?.orgs) || !Array.isArray(body.tasks) || !Array.isArray(body.projects)) throw new Error('read failed');
const named = new Map((list || []).map(o => [o.id, o]));
const orgs = body.orgs.map(o => ({ ...o, id: o.org, label: named.get(o.org)?.label || o.org, theme: named.get(o.org)?.theme ?? o.theme ?? null, roles: Array.isArray(o.roles) ? o.roles : [] }));
return { orgs, tasks: body.tasks, projects: body.projects, summary: body.summary, readAt: body.readAt };
// Each organization that could take a change is asked through its own config. The server sets
// orgSetup for the whole Console today, so the answer only differs where an organization's config
// read fails or 404s. With no way to ask, none is asked and the board is read only.
const asked = orgs.filter(o => tasksRead(o) && o.tracker === 'built-in');
const ask = typeof writesIn === 'function' ? writesIn : null;
const yes = ask ? await Promise.all(asked.map(o => Promise.resolve(ask(o.id)).then(v => v === true, () => false))) : [];
const takes = new Set(asked.filter((o, i) => yes[i]).map(o => o.id));
// The Console-wide word, for the head's reason: no organization that could take a change takes one.
// With none to ask, the open organization's config still says whether this Console writes at all.
const writes = asked.length ? takes.size > 0 : window.MosaicConsole?.config?.orgSetup === true;
return { orgs, tasks: body.tasks, projects: body.projects, summary: body.summary, readAt: body.readAt, takes, asked: asked.map(o => o.id), writes, view: ws()?.orgsOf?.(body) ?? null };
}
// Only the latest read lands: a filter change and the poll can both be reading.
let readSeq = 0;
const reload = async () => { const n = ++readSeq, next = await read(); if (n !== readSeq) return false; snap = next; prune(); return true; };
// A read that a newer one replaced keeps nothing; `newest` lets a view wait for the read that does.
let readSeq = 0, newest = null;
// The address the read starts from goes to prune, so a cleanup never touches a page opened since.
const reload = () => { const n = ++readSeq, at = location.hash; return (newest = read().then(next => { if (n !== readSeq) return false; snap = next; allowed = next.takes; canWrite = next.writes; return prune(at) ? reload() : true; })); };
async function refilter() { paint(); try { if (await reload()) paint(); } catch { /* the next poll shows the failed read */ } }
// A filter naming an org or project that is gone falls back to all.
function prune() {
if (filter.org && !snap.orgs.some(o => o.id === filter.org)) filter.org = '';
if (filter.project && filter.project !== '-' && !snap.projects.some(p => `${p.org}:${p.id}` === filter.project)) filter.project = '';
// The address drops it too, so it never names a filter the board is not using. A dropped project
// was filtered on the server, so it returns true and the read runs again without it.
// A project is gone only when its organization is off the list, or answered with its projects and
// the project is not among them and no task came back for it (with no other filter on). An organization that is down,
// starting or timed out, or whose projects read failed, lists no projects, so its filter stays.
// `at` is the address the read started from.
function prune(at) {
const gone = {};
if (!scope && filter.org && !snap.orgs.some(o => o.id === filter.org)) { filter.org = ''; gone.org = null; }
if (filter.project && filter.project !== '-') {
const po = snap.orgs.find(o => o.id === filter.project.split(':')[0]);
const answered = !po || (po.state === 'ok' && !po.errors?.projects);
// No task back is proof only when no other filter narrowed the read on the server.
const narrowed = filter.state || filter.assignee || filter.label;
if (answered && !narrowed && !snap.tasks.length && !snap.projects.some(p => `${p.org}:${p.id}` === filter.project)) { filter.project = ''; gone.project = null; }
}
// After this render: bus.js drops a render whose address changed while it ran. Only while the
// address is still the one the read started from, and with a repaint in case the render in
// flight was the one dropped.
if (Object.keys(gone).length) setTimeout(() => { if (location.hash === at) ws()?.setQuery?.(gone, true); }, 0);
return 'project' in gone;
}
// ---------- filters ----------
@@ -137,17 +178,17 @@
const chips = [chip('', `All <span class="n">${snap.tasks.length}</span>`)].concat(snap.orgs.map(o => chip(o.id,
`${av(o.id)}${esc(o.label)}<span class="n">${tasksRead(o) ? counts.get(o.id) : 'unavailable'}</span>`,
`${o.label}, ${tasksRead(o) ? `${counts.get(o.id)} tasks` : 'tasks unavailable'}`))).join('');
const scope = snap.orgs.filter(o => !filter.org || o.id === filter.org);
const shown = snap.orgs.filter(o => !filter.org || o.id === filter.org);
const projectOpts = opt('', `All ${snap.projects.filter(p => !filter.org || p.org === filter.org).length}`, filter.project) + opt('-', 'No project', filter.project)
+ scope.map(o => { const ps = snap.projects.filter(p => p.org === o.id); return ps.length ? `<optgroup label="${esc(o.label)}">${ps.map(p => opt(`${p.org}:${p.id}`, p.name || p.key || p.id, filter.project)).join('')}</optgroup>` : ''; }).join('');
const roles = [...new Set(scope.flatMap(o => o.roles).concat(snap.tasks.filter(t => !filter.org || t.org === filter.org).flatMap(t => t.assignees)))].sort();
+ shown.map(o => { const ps = snap.projects.filter(p => p.org === o.id); return ps.length ? `<optgroup label="${esc(o.label)}">${ps.map(p => opt(`${p.org}:${p.id}`, p.name || p.key || p.id, filter.project)).join('')}</optgroup>` : ''; }).join('');
const roles = [...new Set(shown.flatMap(o => o.roles).concat(snap.tasks.filter(t => !filter.org || t.org === filter.org).flatMap(t => t.assignees)))].sort();
if (filter.assignee && filter.assignee !== '-' && !roles.includes(filter.assignee)) roles.push(filter.assignee);
const assigneeOpts = opt('', 'Anyone', filter.assignee) + opt('-', 'Nobody', filter.assignee) + roles.map(r => opt(r, r, filter.assignee)).join('');
const stateOpts = opt('', 'Any', filter.state) + states().map(([v, l]) => opt(v, l, filter.state)).join('') + (snap.tasks.some(t => stateOf(t) === UNREAD) ? opt(UNREAD, 'State not read', filter.state) : '');
const labels = [...new Set(snap.tasks.flatMap(t => t.labels.map(String)))].sort((a, b) => a.localeCompare(b, undefined, { numeric: true }));
const labelSel = labels.length ? select('label', 'Label', opt('', 'Any', filter.label) + labels.map(l => opt(l, l, filter.label)).join(''), 'tb-label') : '';
return `<div class="tb-toolbar">
<div class="tb-chips" role="group" aria-label="Organization">${chips}</div>
${scope ? '' : `<div class="tb-chips" role="group" aria-label="Organization">${chips}</div>`}
${select('project', 'Project', projectOpts, 'tb-project')}${select('assignee', 'Assignee', assigneeOpts, 'tb-assignee')}${select('state', 'State', stateOpts, 'tb-state')}${labelSel}
<div class="tb-right"><label class="tb-search">${icon('search')}<input type="search" placeholder="Find a task" aria-label="Find a task" data-tb-q data-focus-key="tb-q" value="${esc(filter.q)}" autocomplete="off"></label></div>
</div>`;
@@ -158,12 +199,15 @@
const prio = t => (Number.isSafeInteger(t.priority) && t.priority > 0 ? `<span class="tb-chip${t.priority >= 4 ? ' warn' : ''}" title="Priority ${t.priority} of 5">P${t.priority}</span>` : '');
const due = t => { const d = t.dueDate && dueText(t.dueDate); return d ? `<span class="tb-chip${overdue(t) ? ' warn' : ''}" title="Due ${esc(t.dueDate.slice(0, 10))} (UTC)">${overdue(t) ? 'overdue' : 'due'} ${esc(d)}</span>` : ''; };
const title = t => esc(t.title || 'Untitled');
// The shared chips (workspace.js), so a card reads as the Inbox's rows do.
const orgChip = t => (snap.view && ws()?.orgChip ? ws().orgChip(snap.view, t.org, av(t.org, 'xs') || undefined) : `${av(t.org, 'xs')}<span class="ws-sr">${esc(orgOf(t.org).label)}</span>`);
const projChip = t => (projectName(t) ? (ws()?.projChip?.(projectName(t)) ?? `<span>${esc(projectName(t))}</span>`) : '');
function card(t) {
const w = taskWritable(t), k = esc(key(t));
return `<article class="tb-card ws-o${t.state === 'done' ? ' dim' : ''}" style="${colours(t.org)}" data-tb-task="${k}" data-org="${esc(t.org)}"${w ? ' draggable="true"' : ''}>
<div class="top">${av(t.org, 'xs')}<span class="ws-sr">${esc(orgOf(t.org).label)}</span><span class="id">${esc(shortId(t.ref))}</span>${trk(t.tracker)}</div>
<div class="top">${orgChip(t)}<span class="id">${esc(shortId(t.ref))}</span>${trk(t.tracker)}</div>
<div class="tt"><button type="button" class="tb-open" data-tb-open="${k}" data-focus-key="open:${k}">${title(t)}</button></div>
<div class="bot"><span>${projectName(t) ? esc(projectName(t)) : '<span class="muted">No project</span>'}</span>${who(t)}${prio(t)}${due(t)}</div>
<div class="bot">${projChip(t) || '<span><span class="muted">No project</span></span>'}${who(t)}${prio(t)}${due(t)}</div>
</article>`;
}
function kanban(rows) {
@@ -184,10 +228,10 @@
};
return `<div class="ws-tbl tb-list" data-tb-list><table><thead><tr><th scope="col">Org</th><th scope="col">Id</th><th scope="col">Task</th><th scope="col" class="hide-m">Project</th><th scope="col">State</th><th scope="col" class="hide-m">Assignee</th><th scope="col" class="hide-m">Priority</th><th scope="col" class="hide-m">Due</th></tr></thead><tbody>
${sorted.map(t => `<tr class="tb-row ws-o${t.state === 'done' ? ' dim' : ''}" style="${colours(t.org)}" data-tb-task="${esc(key(t))}" data-org="${esc(t.org)}">
<td>${av(t.org)}<span class="ws-sr">${esc(orgOf(t.org).label)}</span></td>
<td>${orgChip(t)}</td>
<td class="mono">${esc(shortId(t.ref))}<span class="t2">${t.tracker === 'vikunja' ? 'Vikunja' : 'built-in'}</span></td>
<td><button type="button" class="tb-open t1" data-tb-open="${esc(key(t))}" data-focus-key="lopen:${esc(key(t))}">${title(t)}</button><span class="t2 show-m">${esc(projectName(t) || 'No project')}</span></td>
<td class="hide-m">${projectName(t) ? esc(projectName(t)) : '<span class="muted">none</span>'}</td>
<td class="hide-m">${projChip(t) || '<span class="muted">none</span>'}</td>
<td>${stateCell(t)}</td>
<td class="hide-m">${t.assignees.length ? esc(t.assignees.join(', ')) : '<span class="muted">nobody</span>'}</td>
<td class="hide-m">${prio(t) || '<span class="muted">none</span>'}</td>
@@ -198,13 +242,14 @@
const rows = filtered(), all = snap.tasks.length;
// Project, state, assignee and label filter on the server, so the board never holds the unfiltered
// total; with one of those on, the line says how many match rather than inventing an "of N".
const onServer = new URLSearchParams(readQuery()).size > 1, n = rows.length;
// The scope's org= is where the board reads, not a filter.
const onServer = new URLSearchParams(readQuery()).size > (scope ? 2 : 1), n = rows.length;
const line = onServer ? `<p class="tb-count">Showing ${n} ${n === 1 ? 'task that matches' : 'tasks that match'} the filters.</p>`
: n !== all ? `<p class="tb-count">Showing ${n} of ${all} tasks.</p>` : '';
// An empty result is only exhaustive when every organization's tasks were read.
const unread = snap.orgs.filter(o => !tasksRead(o));
const none = what => (unread.length ? `${what} in the organizations that answered. Tasks from ${unread.map(o => o.label).join(', ')} could not be read.` : `${what}.`);
const body = !snap.orgs.length ? '<p class="ws-panel tight note">No organizations yet.</p>'
const body = !snap.orgs.length ? `<p class="ws-panel tight note">${scope ? 'This organization is not on your list.' : 'No organizations yet.'}</p>`
: !snap.orgs.some(tasksRead) ? '<p class="ws-panel tight note">No organization answered with its tasks, so no tasks could be read.</p>'
: !all && !onServer ? `<p class="ws-panel tight note">${esc(none('No tasks yet'))}</p>`
: !rows.length ? `<p class="ws-panel tight note">${esc(none('No tasks match these filters'))}</p>`
@@ -230,17 +275,33 @@
const seg = `<span class="ws-seg" role="group" aria-label="Layout"><button type="button" data-tb-layout="kanban" aria-pressed="${lay === 'kanban'}" data-focus-key="tb-layout-kanban">Kanban</button><button type="button" data-tb-layout="list" aria-pressed="${lay === 'list'}" data-focus-key="tb-layout-list">List</button></span>`;
const add = `<button type="button" class="ws-btn" data-tb-new data-focus-key="tb-new"${why ? ` disabled title="${esc(why)}"` : ''}>${icon('plus')}New task</button>`;
let sub = '';
if (snap) {
if (snap && scope) {
const n = snap.tasks.length, name = snap.orgs.find(o => o.id === scope)?.label || scope;
sub = `Tasks from ${esc(name)} only. ${n} ${n === 1 ? 'task' : 'tasks'}. <a href="#/tasks" data-focus-key="tasks-all">Every organization</a>`;
if (snap.orgs.some(o => o.tracker === 'vikunja')) sub += ' Vikunja tasks are read only here.';
if (!canWrite) sub += ' This Console takes no task changes, so the board is read only.';
} else if (snap) {
const n = snap.tasks.length, m = snap.orgs.filter(tasksRead).length, of = snap.summary?.of ?? snap.orgs.length;
sub = `${n} ${n === 1 ? 'task' : 'tasks'} from ${m} of ${of} ${of === 1 ? 'organization' : 'organizations'}. Each organization keeps its own tasks; a change made here goes only to that organization's bus.`;
if (snap.orgs.some(o => o.tracker === 'vikunja')) sub += ' Vikunja tasks are read only here.';
if (!canWrite) sub += ' This Console takes no task changes, so the board is read only.';
else {
const no = snap.asked.filter(id => !allowed.has(id)).map(id => esc(orgOf(id).label));
if (no.length) sub += ` This Console takes no task changes in ${no.length < 2 ? no[0] : `${no.slice(0, -1).join(', ')} and ${no.at(-1)}`}, so ${no.length < 2 ? 'its' : 'their'} tasks are read only here.`;
}
}
return `<div class="ws-vh"><h1 tabindex="-1">Tasks</h1><div class="ws-right">${seg}${add}</div>${sub ? `<p class="sub">${sub}</p>` : ''}</div>`;
}
const noticeLine = () => (notice ? `<p class="tb-notice${notice.error ? ' is-error' : ''}" role="${notice.error ? 'alert' : 'status'}" data-tb-notice>${esc(notice.text)}</p>` : '<p class="tb-notice" role="status" data-tb-notice></p>');
// An organization that did not answer is named first, with its reason, as on the Inbox.
function unreadLine() {
const v = snap?.view;
if (!v || !ws()?.unreadNote) return '';
const o = filter.org && !scope ? { ...v, rows: v.rows.filter(r => r.org === filter.org), unread: v.unread.filter(r => r.org === filter.org) } : v;
return ws().unreadNote(o, ['tasks'], 'tasks');
}
function markup() {
return `<section class="ws tb" data-tasks-board data-layout="${layoutNow()}">${head()}${noticeLine()}${trackers()}${toolbar()}${results()}</section>`;
return `<section class="ws tb" data-tasks-board data-layout="${layoutNow()}"${scope ? ` data-tb-scope="${esc(scope)}"` : ''}>${head()}${noticeLine()}${unreadLine()}${trackers()}${toolbar()}${results()}</section>`;
}
const failed = err => `<section class="ws tb" data-tasks-board><div class="ws-vh"><h1 tabindex="-1">Tasks</h1><p class="sub">The task board could not be read${err?.message && err.message !== 'read failed' ? `: ${esc(err.message)}` : ''}. It tries again on the next refresh.</p></div></section>`;
@@ -266,7 +327,8 @@
// Repaint in place, for the board's own changes (filters, layout, a write).
function paint(part = 'all') {
const root = document.querySelector('[data-tasks-board]');
if (!root || !snap) return;
// Only over a board drawn from a read: never over the not-on-your-list page or a failed read.
if (!root || !snap || !root.querySelector('[data-tb-results]')) return;
const kept = snapshotView(root);
if (part === 'results') root.querySelector('[data-tb-results]').outerHTML = results();
else root.outerHTML = markup();
@@ -274,9 +336,38 @@
}
// bus.js's view for #/tasks. A drag in progress holds the poll's repaint until it ends.
async function view() {
// q is the address query; opts.scope the organization of #/orgs/<id>/tasks; opts.writesIn asks one
// organization's own config whether it takes task changes.
async function view(q = new URLSearchParams(), opts = {}) {
// An address that names an organization no id can match is not the system board.
// A read still in flight from the board left behind lands nowhere and paints nothing.
if (typeof opts.scope === 'string' && opts.scope && !ORG_ID.test(opts.scope)) { ++readSeq; snap = null; return `<section class="ws tb" data-tasks-board><div class="ws-vh"><h1 tabindex="-1">Tasks</h1></div><p class="ws-panel tight note">This organization is not on your list.</p></section>`; }
const s = typeof opts.scope === 'string' && ORG_ID.test(opts.scope) ? opts.scope : null;
if (s !== scope) snap = null;
scope = s; writesIn = typeof opts.writesIn === 'function' ? opts.writesIn : null;
// The org and project filters come from the address on every render, checked; anything else is all.
const org = String(q.get('org') || ''), project = String(q.get('project') || '');
filter.org = scope || (ORG_ID.test(org) ? org : '');
filter.project = PROJECT_SELECTOR.test(project) || project === '-' ? project : '';
if (filter.org && filter.project && filter.project !== '-' && !filter.project.startsWith(`${filter.org}:`)) filter.project = '';
if (dragging) await Promise.race([dragEnded, new Promise(r => setTimeout(r, 30000))]);
try { await reload(); } catch (err) { snap = null; return failed(err); }
// Two renders at once (a first load, a poll during a filter change): the replaced one draws from the newer read.
try { let p = reload(); while (!(await p) && newest !== p) p = newest; } catch (err) { snap = null; return failed(err); }
// A not-on-your-list page opened meanwhile dropped every read; bus.js drops this render as not current.
if (!snap) return '';
// #/orgs/<id>/tasks?task=<ref> opens that task once, after bus.js has drawn the board.
const want = scope ? String(q.get('task') || '') : '';
if (!want) autoOpened = null;
else if (autoOpened !== `${scope}|${want}`) {
autoOpened = `${scope}|${want}`;
const k = `${scope}|${want}`;
setTimeout(() => {
if (!document.querySelector(`[data-tasks-board][data-tb-scope="${CSS.escape(scope || '')}"]`) || autoOpened !== k) return;
const t = TASK_REF.test(want) ? find(k) : null;
if (t) { openDialog(editForm(t), `open:${key(t)}`, t); dialogEl().dataset.fromAddress = '1'; }
else { notice = { error: true, text: `Task ${shortId(want)} is not on this board.` }; paint(); }
}, 0);
}
// Taken after the read, just before bus.js replaces the view, so focus, caret or scroll moved while
// the read was in flight is what is kept. bus.js puts focus back by key; this puts back the rest.
const kept = snapshotView(document.querySelector('[data-tasks-board]'));
@@ -317,7 +408,13 @@
d = document.createElement('dialog');
d.id = 'tb-dialog'; d.className = 'tb-dialog'; d.setAttribute('aria-labelledby', 'tb-dialog-h');
document.body.append(d);
d.addEventListener('close', () => { const back = d.dataset.return; d.innerHTML = ''; d.removeAttribute('aria-describedby'); opened = null; if (back) document.querySelector(`[data-focus-key="${CSS.escape(back)}"]`)?.focus(); });
d.addEventListener('close', () => {
const back = d.dataset.return, fromAddress = d.dataset.fromAddress === '1';
d.innerHTML = ''; d.removeAttribute('aria-describedby'); delete d.dataset.fromAddress; opened = null;
if (back) document.querySelector(`[data-focus-key="${CSS.escape(back)}"]`)?.focus();
// A task the address opened leaves the address when it closes, so a reload does not reopen it.
if (fromAddress && /^#\/orgs\/[^/?]+\/tasks\?(?:.*&)?task=/.test(location.hash)) ws()?.setQuery?.({ task: null }, true);
});
}
return d;
}
@@ -348,14 +445,17 @@
function editForm(t, refusal = null) {
const o = orgOf(t.org), w = taskWritable(t);
const why = t.tracker === 'vikunja' ? 'This task is in Vikunja. The board reads it but does not change it; change it in Vikunja.'
: !canWrite ? 'This Console takes no task changes.' : o.state !== 'ok' ? 'This organization\'s bus did not answer.' : !w ? 'The bus did not give this task a version to check a change against.' : '';
: !canWrite ? 'This Console takes no task changes.' : o.state !== 'ok' ? 'This organization\'s bus did not answer.'
: !allowed.has(t.org) ? `This Console takes no task changes in ${o.label}.` : !w ? 'The bus did not give this task a version to check a change against.' : '';
// On the system board the task also opens in its own organization.
const goto = scope ? '' : `<a class="ws-btn" href="${esc(`#/orgs/${encodeURIComponent(t.org)}/tasks?${new URLSearchParams({ task: t.ref })}`)}" data-tb-goto>Open in ${esc(o.label)}</a>`;
const facts = `<p class="tb-facts">${av(t.org, 'xs')}${esc(o.label)} · <span class="mono">${esc(shortId(t.ref))}</span> ${trk(t.tracker)}${t.requirement ? ` · <span class="mono">${esc(t.requirement)}</span>` : ''}${projectName(t) ? ` · ${esc(projectName(t))}` : ''}</p>`;
if (!w) {
return `<div class="tb-form" data-tb-form="view"><h2 id="tb-dialog-h">${title(t)}</h2>${facts}
<dl class="tb-dl"><dt>State</dt><dd>${esc(stateLabel(t.state) || 'Not read')}</dd><dt>Assignees</dt><dd>${t.assignees.length ? esc(t.assignees.join(', ')) : 'nobody'}</dd><dt>Priority</dt><dd>${prio(t) || 'none'}</dd><dt>Due</dt><dd>${due(t) || 'none'}</dd></dl>
<p class="tb-field-note">${esc(why)}</p>
${refusal ? `<p id="tb-dialog-status" class="tb-form-status" role="status" data-tb-form-status>${esc(refusal)}</p>` : ''}
<div class="tb-actions"><button type="button" class="ws-btn" data-tb-cancel>Close</button></div></div>`;
<div class="tb-actions">${goto}<span class="tb-gap"></span><button type="button" class="ws-btn" data-tb-cancel>Close</button></div></div>`;
}
return `<form method="dialog" class="tb-form" data-tb-form="edit" data-tb-key="${esc(key(t))}">
<h2 id="tb-dialog-h">Edit ${esc(shortId(t.ref))}</h2>${facts}
@@ -363,11 +463,12 @@
<div class="tb-row2">${stateSelect(t.state)}${prioSelect(t.priority)}<label>Due date<input type="date" name="due_date" value="${dateValue(t.dueDate)}"></label></div>
${roleBoxes([...new Set([...o.roles, ...t.assignees])].sort(), t.assignees)}
<p class="tb-form-status" role="alert" data-tb-form-status></p>
<div class="tb-actions"><button type="button" class="ws-btn danger" data-tb-archive>Archive</button><span class="tb-gap"></span><button type="button" class="ws-btn" data-tb-cancel>Cancel</button><button type="submit" class="ws-btn primary" data-tb-submit>Save</button></div>
<div class="tb-actions"><button type="button" class="ws-btn danger" data-tb-archive>Archive</button>${goto}<span class="tb-gap"></span><button type="button" class="ws-btn" data-tb-cancel>Cancel</button><button type="submit" class="ws-btn primary" data-tb-submit>Save</button></div>
</form>`;
}
function openDialog(html, back, task = null) {
const d = dialogEl();
delete d.dataset.fromAddress;
d.innerHTML = html; d.dataset.return = back || ''; opened = task ? structuredClone(task) : null;
if (d.querySelector('#tb-dialog-status')) d.setAttribute('aria-describedby', 'tb-dialog-status'); else d.removeAttribute('aria-describedby');
if (!d.open) d.showModal();
@@ -474,6 +575,8 @@
const d = e.target.closest?.('#tb-dialog');
if (d) {
if (e.target.closest('[data-tb-cancel]')) { e.preventDefault(); d.close(); }
// The link navigates; the dialog closes so the organization's board opens the task itself.
else if (e.target.closest('[data-tb-goto]')) { d.dataset.return = ''; d.close(); }
else if (e.target.closest('[data-tb-archive]')) { e.preventDefault(); archive(e.target.closest('form')); }
return;
}
@@ -482,8 +585,11 @@
if (lay) { layouts[phone() ? 'phone' : 'wide'] = lay.dataset.tbLayout; save(LAYOUT, JSON.stringify(layouts)); paint(); return; }
const chip = e.target.closest('[data-tb-org]');
if (chip) {
filter.org = chip.dataset.tbOrg;
if (filter.project && filter.project !== '-' && filter.org && !filter.project.startsWith(`${filter.org}:`)) { filter.project = ''; refilter(); } else paint();
// The org filter lives in the address: paint now, then bus.js re-renders from the new query.
const org = chip.dataset.tbOrg, clear = filter.project && filter.project !== '-' && org && !filter.project.startsWith(`${org}:`);
filter.org = org; if (clear) filter.project = '';
paint();
ws()?.setQuery?.({ org: org || null, ...(clear ? { project: null } : {}) }, true);
return;
}
const open = e.target.closest('[data-tb-open]');
@@ -500,6 +606,7 @@
}
if (!inBoard(e) || !snap) return;
const f = e.target.dataset?.tbFilter;
if (f === 'project') { filter.project = e.target.value; paint(); ws()?.setQuery?.({ project: e.target.value || null }, true); return; }
if (f) { filter[f] = e.target.value; refilter(); return; }
if (e.target.matches('[data-tb-move]')) move(e.target.dataset.tbMove, e.target.value);
});
+299 -68
View File
@@ -56,7 +56,8 @@
// A status mark: a glyph plus its word, shown or read aloud only.
const dot = (cls, glyph, word, shown = false) => `<span class="ws-dot ${cls}" title="${esc(word)}"><b aria-hidden="true">${glyph}</b>${shown ? esc(word) : `<span class="ws-sr">${esc(word)}</span>`}</span>`;
const orgHref = id => `#/orgs/${enc(id)}`;
const route = () => location.hash.replace(/^#\/orgs\/[^/]+/, '') || '/';
// SP3: a system route such as #/inbox has no organization prefix; both forms give the path.
const route = () => location.hash.replace(/^#(?:\/orgs\/[^/]+)?/, '') || '/';
const ensureThemes = async () => { if (!themes) themes = await data.themes().then(b => (Array.isArray(b?.themes) ? b.themes : [])).catch(() => []); return themes; };
const instancesOf = value => { const v = value?.rows?.[0]?.instances ?? value?.instances; return v && typeof v === 'object' && !Array.isArray(v) ? v : null; };
// #1873 A3: the root and project agent copies the bus booted with, from the same instances read.
@@ -104,7 +105,8 @@
const root = document.getElementById('workspace-nav'); if (!root) return;
const key = focusKey(root);
if (orgError || !orgs) { root.innerHTML = `<hr class="ws-hr"><p class="ws-line">${orgError ? 'Organizations unavailable' : 'Reading organizations…'}</p>`; return; }
const here = route(), selected = window.MosaicOrg?.id;
// SP1: a system route (the dashboard) marks no organization; an organization route marks its own.
const here = route(), selected = /^#\/orgs\//.test(location.hash) ? window.MosaicOrg?.id : null;
const rows = orgs.map(org => {
const [cls, glyph, word] = state(org), mine = org.id === selected, current = mine && here === '/organization';
return `<li data-workspace-org="${esc(org.id)}"><a class="ws-nav ws-org-row${mine && !current ? ' sel' : ''}" href="${esc(orgHref(org.id))}/organization" data-focus-key="${esc(`org:${org.id}`)}"${current ? ' aria-current="page"' : ''}>${av(org)}<span class="t">${esc(label(org))}</span>${dot(cls, glyph, word, cls !== 's-working')}</a></li>`;
@@ -227,10 +229,26 @@
return Boolean(a && a.el.isConnected);
}
// A side-by-side pane passes its own organization and { pane: true, idPrefix }: the pane has no bus
// restart (that stays in the organization's full view) and its ids carry the pane's prefix.
async function dashboard(id = window.MosaicOrg.id, opts = {}) {
const pane = opts.pane === true, why = `${opts.idPrefix || ''}ws-reload-why`;
// SP1: the reason an organization's bus can't be read, for its pages. `row` is its GET /api/workspace
// status (state, reason, boot), or null when that read gave none.
// A reason that only restates the heading ("the bus is not running", the server's fallback) is not
// repeated; the last start time, when read, still shows.
const restates = reason => /^the bus is not (running|answering)\.?$/i.test(reason.trim());
const downWhy = row => (row && row.state !== 'ok' && typeof row.reason === 'string' && row.reason ? `${row.reason}${row.boot?.at ? `, last start ${when(row.boot.at)}` : ''}` : '');
// #1873 SP2: this is the page's only bus banner (the shell's "Bus unavailable" hides on this page), so
// it carries the restart action where the Console allows it.
function downBanner(org, row) {
const stopped = org.busStopped === true;
const plain = row && row.state !== 'ok' && typeof row.reason === 'string' && row.reason && restates(row.reason);
const why = plain ? '' : downWhy(row);
const tail = plain
? (row.boot?.at ? ` <span class="why">Last start ${esc(when(row.boot.at))}.</span>` : '')
: why ? ` <span class="why">Reason: ${esc(why)}.</span>` : ' <span class="why">No reason was read.</span>';
const restart = window.MosaicConsole?.busButton?.('Restart the bus') || '';
return `<div class="banner err" role="status" data-org-down><div><b>${stopped ? 'The bus is not running.' : 'The bus is not answering.'}</b> Nothing about ${esc(label(org))}'s agents or packs can be read until it ${stopped ? 'starts' : 'answers'}.${tail}</div>${restart ? `<div class="actions">${restart}</div>` : ''}</div>`;
}
async function dashboard(id = window.MosaicOrg.id) {
const why = 'ws-reload-why';
// Only an organization the membership list names is read; anything else reads nothing more.
const [listRead] = await Promise.all([data.organizations().catch(() => null), ensureThemes()]);
const list = Array.isArray(listRead) ? listRead : null;
@@ -244,16 +262,19 @@
const threads = rowsOf(value(3)), projectRows = rowsOf(value(4)), queue = rowsOf(value(5));
const agents = rowsOf(value(6)), claims = rowsOf(value(7));
const docRead = business?.business ? await docs(id, business.business.projects).catch(() => ({ rows: [], failed: true })) : null;
// SP1: a bus that is down says so above everything else, with the reason the workspace read gives.
const downRow = org.busHealthy ? null : await data.workspace({ org: id, sections: 'projects' }).then(b => arr(b?.orgs).find(r => r?.org === id) ?? null).catch(() => null);
await window.MosaicConsole?.ready;
const name = esc(label(org));
const tracker = business?.business?.vars?.['tracker.kind'];
// Header: the bus restart is console-restart.js's button where the Console allows it, otherwise
// the same control, present and disabled, with the reason.
const restart = pane ? '' : window.MosaicConsole?.busButton?.('Restart bus', { stop: true, glyph: icon('restart') }) || '';
const offTitle = pane ? "Restart the bus from this organization's full view" : "Restarting the bus is the owner's trailed action, on a Console started with send and the action trail";
const stopTitle = pane ? "Stop the bus from this organization's full view" : "Stopping the bus is the owner's trailed action, on a Console started with send and the action trail";
const bus = restart ? `<span class="ws-busctl" data-dashboard-bus>${restart}</span>` : `<span data-dashboard-bus><button type="button" class="ws-btn" data-bus-restart-off data-focus-key="bus-restart-off" disabled title="${esc(offTitle)}">${icon('restart')}Restart bus</button> <button type="button" class="ws-btn" data-bus-stop-off data-focus-key="bus-stop-off" disabled title="${esc(stopTitle)}">Stop bus</button></span>`;
// the same control, present and disabled, with the reason. SP7 (#1873): while the bus is down and
// the down banner carries the live restart, the header draws none, so the page has one.
const restart = window.MosaicConsole?.busButton?.('Restart bus', { stop: true, glyph: icon('restart') }) || '';
const offTitle = "Restarting the bus is the owner's trailed action, on a Console started with send and the action trail";
const stopTitle = "Stopping the bus is the owner's trailed action, on a Console started with send and the action trail";
const bus = restart ? (org.busHealthy ? `<span class="ws-busctl" data-dashboard-bus>${restart}</span>` : '') : `<span data-dashboard-bus><button type="button" class="ws-btn" data-bus-restart-off data-focus-key="bus-restart-off" disabled title="${esc(offTitle)}">${icon('restart')}Restart bus</button> <button type="button" class="ws-btn" data-bus-stop-off data-focus-key="bus-stop-off" disabled title="${esc(stopTitle)}">Stop bus</button></span>`;
const reload = `<button type="button" class="ws-btn" data-org-reload data-focus-key="org-reload" disabled aria-describedby="${esc(why)}" title="Reload arrives with the cross-org update">${icon('doc')}Reload organization file</button>`;
const [bcls, bglyph] = state(org);
const meta = `<p class="ws-meta"><span>Kind not recorded</span><span>id <code>${esc(id)}</code></span><span>Tracker: ${tracker ? esc(titleCase(tracker)) : 'not set'}</span><span>${dot(bcls, bglyph, org.busHealthy ? `bus running, read ${clock()}` : org.busStopped ? `bus stopped, read ${clock()}` : `bus unavailable, read ${clock()}`, true)}</span><span id="${esc(why)}">Restart is a trailed human action; reload arrives with the cross-org update.</span></p>`;
@@ -290,8 +311,9 @@
const stoppedPanel = (attr, title) => `<section class="panel" ${attr} data-bus-stopped><h3>${title}</h3><p class="note">Not read: the bus is stopped.</p></section>`;
return `<article class="ws ws-dash" data-org-dashboard>
<nav class="ws-crumb" aria-label="Breadcrumb"><a href="#/settings/organizations">Organizations</a><span aria-hidden="true">›</span><span>${name}</span></nav>
<nav class="ws-crumb" aria-label="Breadcrumb"><a href="#/dashboard">Dashboard</a><span aria-hidden="true">›</span><span>${name}</span></nav>
<div class="ws-orghead ws-o" style="${colours(org)}">${av(org, 'lg')}<h1 tabindex="-1">${name}</h1><div class="ws-right">${bus}${reload}</div>${meta}</div>
${org.busHealthy ? '' : downBanner(org, downRow)}
${docrow}
<div class="ws-split">
<section aria-label="Measures and sessions">
@@ -320,6 +342,8 @@
// only). Every status comes from the organization's bus: its instances, and since A3 the root and
// project agent copies it booted with. Nothing here invents a status, a model or a memory.
const NOT_RUNNING = ['s-idle', '–', 'not running'];
// SP1: why a bus-backed read gave nothing, in the membership list's words.
const busWord = org => (org?.busStopped === true ? 'the bus is stopped' : 'the bus is not answering');
// A copy's status: running or not as the bus reports its runs, or why it can't launch.
const CANT = ['s-error', '▲', "can't launch"];
// #1873 CB5: the bus adds `binding` to a copy that needs a credential binding: its status code and
@@ -338,6 +362,17 @@
return hit ? { key: hit[0], copy: hit[1] } : { key: null, copy: null };
};
const LEVEL_CLS = { root: 'root', org: 'org', project: 'proj' };
// SP5: what an agent is, in words. A hired agent's definition is `org:hire-<decision>`. No read names
// the template it was hired from, so it reads as hired, and from which pack when a pack hired it;
// the definition id stays as secondary text.
const isHired = item => typeof item?.hireDecision === 'string' || /^org:hire-/.test(String(item?.definition ?? ''));
const packOf = item => (typeof item?.pack?.label === 'string' && item.pack.label ? item.pack.label : typeof item?.pack?.id === 'string' ? item.pack.id : '');
const ROLE_WORD = { 'chief-of-staff': 'Chief of staff', assistant: 'Assistant' };
const roleWords = item => {
const d = typeof item?.definition === 'string' ? item.definition : '';
if (isHired(item)) return packOf(item) ? `Hired from pack ${packOf(item)}` : 'Hired';
return ROLE_WORD[d] || d.replace(/^org:/, '') || 'not reported';
};
const projectName = (rows, id) => { const p = Array.isArray(rows) ? rows.find(r => r?.id === id) : null; return p?.name || id; };
let agentsPick = null; // the project chosen in "Available in a project", kept across repaints
// Repaints that section alone when the choice changes, one renderer per organization: a side-by-side
@@ -364,10 +399,11 @@
} else if (inst) {
rows.push(...Object.entries(inst).map(([name, v]) => ({ name, level: 'org', definition: v?.definition, model: null, scope: { kind: 'org' }, overrides: [], narrowed: [] })));
}
if (!set && inst === null) return '<p class="ws-panel tight note">Agents unavailable. The bus did not answer the instance read.</p>';
if (!set && inst === null) return `<p class="ws-panel tight note" data-agents-why>${selOrg?.busHealthy === false ? `Agents not read: ${busWord(selOrg)}.` : 'Agents unavailable. The bus did not answer the instance read.'}</p>`;
if (!rows.length) return '<p class="ws-panel tight note">No agents configured</p>';
const where = a => (a.level === 'root' ? 'Your root configuration' : a.level === 'org' ? `${label(selOrg)} file` : `${names(a.project)} project`);
const sub = a => [a.definition && a.definition !== a.name ? a.definition : '', a.overrides?.length ? `replaces the ${a.overrides.map(o => (o.level === 'org' ? 'organization' : o.level)).join(' and ')} ${a.overrides.length > 1 ? 'definitions' : 'definition'}` : '', a.narrowed?.length ? `narrowed here: ${a.narrowed.join(', ')}` : ''].filter(Boolean).join(' · ');
const hired = a => a.level === 'org' && isHired({ ...inst?.[a.name], definition: a.definition });
const sub = a => [hired(a) ? 'hired' : a.definition && a.definition !== a.name ? a.definition : '', a.level === 'org' && typeof inst?.[a.name]?.pack?.id === 'string' ? `from pack ${inst[a.name].pack.id}` : '', hired(a) ? a.definition : '', a.overrides?.length ? `replaces the ${a.overrides.map(o => (o.level === 'org' ? 'organization' : o.level)).join(' and ')} ${a.overrides.length > 1 ? 'definitions' : 'definition'}` : '', a.narrowed?.length ? `narrowed here: ${a.narrowed.join(', ')}` : ''].filter(Boolean).join(' · ');
const status = a => {
if (a.assistant) return dot('s-unknown', '?', 'status not reported', true);
if (a.level !== 'org') {
@@ -400,9 +436,10 @@
return `<div class="ws-tbl"><table><thead><tr><th scope="col">Agent</th><th scope="col">Level</th><th scope="col" class="hide-m">Defined in</th><th scope="col" class="hide-m">Memory</th><th scope="col">Status</th><th scope="col" class="hide-m">Model</th></tr></thead><tbody>${body}</tbody></table></div>${note}`;
}
async function agentGrid(note = '', selected = window.MosaicOrg?.id) {
// SP5: `opts.under` draws it below the scoped Agents table (#/orgs/<id>/agents), which owns the page heading.
async function agentGrid(note = '', selected = window.MosaicOrg?.id, opts = {}) {
const [list, levels] = await Promise.all([data.organizations().catch(() => null), data.agentLevels().catch(() => null), ensureThemes()]);
const head = `<div class="ws-vh"><h1 tabindex="-1">Agents</h1><div class="ws-right"><a class="ws-btn" href="#/settings/agents" data-focus-key="agents-edit">${icon('settings')}Edit agents</a></div><p class="sub">Agents are defined at three levels: root, organization and project. Each organization runs its own copy of a root agent, and a project's agents run only in that project. The copies are made when the organization's bus starts.${note ? ` ${note}` : ''}</p></div>`;
const head = `<div class="ws-vh">${opts.under ? '<h2>Agents by level</h2>' : '<h1 tabindex="-1">Agents</h1>'}<div class="ws-right"><a class="ws-btn" href="#/settings/agents" data-focus-key="agents-edit">${icon('settings')}Edit agents</a></div><p class="sub">Agents are defined at three levels: root, organization and project. Each organization runs its own copy of a root agent, and a project's agents run only in that project. The copies are made when the organization's bus starts.${note ? ` ${note}` : ''}</p></div>`;
if (!Array.isArray(list)) return `<section class="ws ws-agents" data-org-agents>${head}<p class="ws-panel tight note">Organizations unavailable.</p></section>`;
const valid = list.filter(org => !org.invalid);
const admitted = valid.some(org => org.id === selected);
@@ -417,7 +454,16 @@
const n = Math.max(valid.length, 1);
const cell = (org, inner, cls = '') => `<div class="ws-o${cls}" style="${colours(org)}" data-org="${esc(org.id)}"><span class="mlabel">${av(org, 'xs')}${esc(label(org))}</span>${inner}</div>`;
const endc = i => (i === results.length - 1 ? ' endc' : '');
const pill = (name, item, agents) => { const cos = item?.definition === 'chief-of-staff' || name === 'chief'; const [acls, aglyph, aword] = activity(name, item, agents); return `<span class="ws-agent${cos ? ' cos' : ''}">${dot(acls, aglyph, aword)}${esc(name)}${cos && name !== 'chief' ? ' <small>chief</small>' : ''}</span>`; };
// Ruling 2026-11-14: a card names the pack that hired its agent, and the page's own organization
// offers Fire on every card but the chief's and the assistant's (bus.js draws the control and its confirmation).
const pill = (org, name, item, agents) => {
const cos = item?.definition === 'chief-of-staff' || name === 'chief';
const [acls, aglyph, aword] = activity(name, item, agents);
const from = typeof item?.pack?.id === 'string' ? ` <small data-agent-pack="${esc(item.pack.id)}">from pack ${esc(item.pack.id)}</small>` : '';
// No Fire the bus would refuse: the assistant (and any end-protected instance) is never fired.
const fire = cos || item?.definition === 'assistant' || item?.endProtected === true ? '' : window.MosaicDecide?.fireControl(org.id, name) ?? '';
return `<span class="ws-agent${cos ? ' cos' : ''}" data-agent-card="${esc(name)}">${dot(acls, aglyph, aword)}${esc(name)}${cos && name !== 'chief' ? ' <small>chief</small>' : ''}${from}${fire}</span>`;
};
// A root or project copy in one organization's cell: its status from that organization's bus, and
// why it can't launch when it can't. No answer from the bus reads as unavailable, never as idle.
const copyPill = (copies, agents, name, project, small) => {
@@ -439,7 +485,7 @@
const on = kept.filter(a => !own(a)), replaced = kept.filter(own);
return cell(org, `${on.map(a => copyPill(copies, agents, a.name, null, 'copy')).join('') || '<span class="muted">none</span>'}${replaced.length ? `<span class="note ws-off">${esc(replaced.map(a => a.name).join(', '))} replaced by ${esc(label(org))}'s own</span>` : ''}${off.length ? `<span class="note ws-off">${esc(off.map(a => a.name).join(', '))} turned off for ${esc(label(org))}</span>` : ''}`, endc(i));
}).join('');
const orgRow = results.map(({ org, inst, agents }, i) => cell(org, inst === null ? '<span class="muted">Agents unavailable</span>' : Object.keys(inst).length ? Object.entries(inst).map(([k, v]) => pill(k, v, agents)).join('') : '<span class="muted">No agents configured</span>', endc(i))).join('');
const orgRow = results.map(({ org, inst, agents }, i) => cell(org, inst === null ? `<span class="muted" data-agents-why>${org.busHealthy === false ? `Agents not read: ${busWord(org)}` : 'Agents unavailable'}</span>` : Object.keys(inst).length ? Object.entries(inst).map(([k, v]) => pill(org, k, v, agents)).join('') : '<span class="muted">No agents configured</span>', endc(i))).join('');
// Project: the agents a project defines itself. Narrowing and exclusion show in the table.
const projRow = results.map(({ org, lv, rows, copies, agents }, i) => {
if (lv?.state !== 'ok') return cell(org, `<span class="muted">${lv?.state === 'invalid' ? 'Project agents unavailable: the organization file was refused' : 'Project agents unavailable'}</span>`, ` last${endc(i)}`);
@@ -464,8 +510,9 @@
const title = projectIds.length ? 'Available in a project' : `Agents in ${esc(label(selOrg))}`;
const table = !mine ? '<p class="ws-panel tight note">The selected organization is not on the list.</p>' : levelsTable(ctx, pick);
const rules = `<div class="ws-panel tight ws-rules"><p><span class="ws-lvl root">root</span>You define root agents in agents.json in your configuration directory. The chief cannot change them.</p><p><span class="ws-lvl org">org</span>Agents come from the organization file. Add, change or remove them under Settings, Agents.</p><p><span class="ws-lvl proj">project</span>A project in the organization file can add an agent, narrow an inherited agent's limits or exclude one. It never widens them.</p><p><span class="ws-lvl proj">override</span>The most specific level wins. A row says which definition it replaces.</p><p class="muted">An agent's harness, model and thinking are set under Settings, Routing.</p></div>`;
return `<section class="ws ws-agents" data-org-agents>${head}${band}${levelsGrid}
<div class="ws-split ws-split-agents"><section><div class="ws-sec-h"><h2>${title}</h2>${chooser}</div><div data-agents-available>${table}</div></section><section>${secH('Who changes what')}${rules}</section></div>
const receipt = selected === window.MosaicOrg?.id ? `<div data-agents-receipt role="status">${window.MosaicDecide?.fireNote() ?? ''}</div>` : '';
return `<section class="ws ws-agents" data-org-agents>${head}${receipt}${band}${levelsGrid}
<div class="ws-split ws-split-agents"><section><div class="ws-sec-h"><h2>${title}</h2>${chooser}</div><div data-agents-available data-agents-org="${esc(selected)}">${table}</div></section><section>${secH('Who changes what')}${rules}</section></div>
</section>`;
}
document.addEventListener('change', e => {
@@ -516,6 +563,13 @@
const missOf = (r, names) => { const n = r?.state === 'ok' && r.errors ? names.find(x => r.errors[x]) : null; return n ? READ_WHY[r.errors[n]] || String(r.errors[n]) : null; };
const missed = (o, names) => o.rows.filter(r => missOf(r, names)).map(r => `${esc(o.name(r.org))} (${esc(missOf(r, names))})`);
const missLine = (o, names, key, lead = 'Not read in') => { const m = missed(o, names); return m.length ? `<p class="note ws-miss" data-ws-miss="${key}">${lead} ${andList(m)}.</p>` : ''; };
// SP3/SP4: a row's organization and project as chips, and the organizations that did not answer
// named first with the reason their read gave. The Inbox and the system task board share these.
// `mark`, already-escaped markup such as the organization's avatar, takes the dot's place.
const orgChip = (o, id, mark = '<i aria-hidden="true"></i>') => `<span class="ws-chip ws-o ws-ochip" style="${o.style(id)}" data-ws-orgchip>${mark}${esc(o.name(id))}</span>`;
const projChip = name => (name ? `<span class="ws-chip outline ws-pchip" data-ws-projchip>${esc(name)}</span>` : '');
const unreadWhy = r => `${stateWords(r).replace(/, read .*$/, '')}${r.reason ? `: ${esc(r.reason)}` : ''}${r.at ? ` (read ${esc(hm(r.at))})` : ''}`;
const unreadNote = (o, names, key) => (o.unread.length ? `<p class="note ws-unread-note" data-ws-unread>Not read: ${andList(o.unread.map(unreadWhy))}.</p>` : '') + missLine(o, names, key);
// The organizations that answered and made every read a figure is built from. Only these count
// toward it: a failed read reaches the merge as an empty list, so its zero is not a figure.
const readers = (o, names) => new Set(o.rows.filter(r => r.state === 'ok' && !missOf(r, names)).map(r => r.org));
@@ -526,12 +580,18 @@
return `<section class="ws ${cls}" ${attr} data-ws-failed><div class="ws-vh"><h1 tabindex="-1">${title}</h1><p class="sub">${why}</p></div></section>`;
}
// The Inbox count in the navigation follows the cross-organization read wherever it was made.
// SP3: the sidebar's Inbox count on a page that reads one organization (the board) comes from the
// workspace read too, so it says what #/inbox lists. A failed read leaves the count as it was.
const inboxCount = () => data.workspace({ sections: ['inbox'] }).then(b => { if (!noneRead(orgsOf(b), ['inbox'])) tellInbox(arr(b.inbox).filter(d => d && typeof d.org === 'string')); }).catch(() => {});
const newest = (a, b) => (b.at ?? '').localeCompare(a.at ?? '');
const tellInbox = rows => { if (Array.isArray(rows)) document.dispatchEvent(new CustomEvent('mosaic-workspace-inbox', { detail: { open: rows.length, blocking: rows.filter(d => d?.blocking).length } })); };
// A stacked bar and its per-organization figures, one segment per organization.
const bar = (o, parts, style = '') => `<div class="ws-bar"${style ? ` style="${style}"` : ''} aria-hidden="true">${parts.filter(p => p.n > 0).map(p => `<i class="ws-o" style="${o.style(p.id)};flex:${p.n}"></i>`).join('')}</div>`;
const by = (o, parts, fmt = n => n) => `<div class="ws-by">${parts.map(p => `<span>${av(o.meta(p.id))}<span class="ws-sr">${esc(o.name(p.id))}</span>${esc(fmt(p.n))}</span>`).join('')}</div>`;
const CLASS_CHIP = { gated: 'gated', 'within-role': 'within', routine: 'routine', 'cross-role': 'cross' };
const classChip = c => (c ? `<span class="ws-chip ${CLASS_CHIP[c] || ''}">${esc(c)}</span>` : '');
// The one map of decision classes to words: the class chips and the Inbox Class filter both read it.
const TYPE_WORD = { gated: 'Gated', 'within-role': 'Within role', 'cross-role': 'Cross-role', routine: 'Routine' };
const classChip = c => (c ? `<span class="ws-chip ${CLASS_CHIP[c] || ''}">${esc(TYPE_WORD[c] || c)}</span>` : '');
const itemKey = d => `${d.org}:${d.id}`;
const roleOf = d => d.session?.role || d.raisedBy || '';
const fromWords = (o, d, withOrg = true) => [withOrg ? o.name(d.org) : '', d.project?.name || 'No project', roleOf(d)].filter(Boolean).map(esc).join(' · ');
@@ -539,7 +599,11 @@
// ---- main dashboard (sample 02) ----
async function home() {
let body;
try { [body] = await Promise.all([data.workspace({ sections: ['projects', 'sessions', 'inbox', 'tasks', 'metrics'] }), ensureThemes()]); took(body); }
let levels = null, listed = null;
// SP1: the agent counts come from the organization files (GET /api/agents/levels, owner only), so a
// stopped bus still has one; the bus state words come from the membership list. Either read may
// fail or be absent, and its column then shows no figure.
try { [body, levels, listed] = await Promise.all([data.workspace({ sections: ['projects', 'sessions', 'inbox', 'tasks', 'metrics'] }), data.agentLevels().catch(() => null), data.organizations().catch(() => null), ensureThemes()]); took(body); }
catch (err) { return failedPage('ws-home', 'data-ws-home', 'Dashboard', err); }
const o = orgsOf(body), m = body.metrics, t = m?.totals, per = arr(m?.orgs);
const inbox = arr(body.inbox), sessions = arr(body.sessions), projectRows = arr(body.projects), tasks = arr(body.tasks);
@@ -563,11 +627,29 @@
<div class="ws-tile quiet" data-ws-tile="spend"><span class="ws-label">Model spend</span><span class="ws-empty-t">No spend figures yet</span><span class="ws-delta">No model prices are read yet, so today's use has no cost figure.</span></div>
</div>` : '<p class="ws-panel tight note" data-ws-tiles>No organization answered, so there are no totals yet.</p>';
const cards = o.rows.map(r => {
const [cls, glyph, word] = orgState(r), id = r.org;
const extra = r.state === 'ok' ? '' : `<span class="why">${esc(r.reason || '')}${r.boot?.at ? `${r.reason ? ' · ' : ''}last start ${esc(when(r.boot.at))}` : ''}</span>`;
return `<li class="ws-orgcard ws-o${r.state === 'ok' ? '' : ' off'}" style="${o.style(id)}" data-ws-orgcard="${esc(id)}" data-state="${esc(r.state)}"><a href="${esc(orgHref(id))}/organization" data-focus-key="${esc(`orgcard:${id}`)}">${av(o.meta(id), 'md')}<span class="nm">${esc(o.name(id))}</span>${dot(cls, glyph, word, true)}<span class="at">read ${esc(hm(r.at))}</span>${extra}</a></li>`;
// SP1 (sample r2-01): one row per organization. A figure shows only when its read gave it; an
// organization that did not answer shows its state and reason instead of figures.
const listRow = id => (Array.isArray(listed) ? listed.find(x => x?.id === id) : null);
const projectsRead = readers(o, SRC.projects), inboxRead = readers(o, SRC.needs), sessionsRead = readers(o, SRC.sessions);
const none = '<span class="muted" title="not read">–</span>';
// The bus state as the workspace read found it; "stopped" only when the membership list says the owner stopped it.
const ROW_STATE = { ok: ['s-working', '●', 'bus running'], starting: ['s-waiting', '◐', 'bus starting'], timeout: ['s-error', '▲', 'bus not answering'], invalid: ['s-error', '▲', 'invalid'] };
const rowState = (r, fromList) => (r.state === 'down' ? ['s-offline', '○', fromList?.busStopped === true ? 'bus stopped' : 'bus down'] : ROW_STATE[r.state] || orgState(r));
const orgTable = o.rows.map(r => {
const id = r.org, fromList = listRow(id), x = per.find(p => p.org === id);
const [cls, glyph, word] = rowState(r, fromList);
const lv = levels?.orgs?.find(v => v?.id === id);
const count = lv?.state === 'ok' && Array.isArray(lv.base?.agents) ? lv.base.agents.length : null;
const working = x && sessionsRead.has(id) ? num(x.sessions?.working) : null;
const agentsCell = count === null ? none : `${plural(count, 'agent')}${working === null ? '' : ` <small class="muted">(${working} working)</small>`}`;
const projectsCell = x && projectsRead.has(id) ? plural(num(x.projects?.active), 'project') : none;
const needsCell = x && inboxRead.has(id) ? (num(x.needsYou) ? `${num(x.needsYou)} needs you` : 'none waiting') : none;
// #1873 SP2: a reason that only restates the state word ("the bus is not running" beside "bus stopped") is said once.
const reason = r.state !== 'ok' && typeof r.reason === 'string' && r.reason && !restates(r.reason) ? r.reason : '';
const why = r.state === 'ok' || !(reason || r.boot?.at) ? '' : `<span class="why">${esc(reason)}${r.boot?.at ? `${reason ? ' · ' : ''}last start ${esc(when(r.boot.at))}` : ''}</span>`;
return `<tr class="ws-o${r.state === 'ok' ? '' : ' off'}" style="${o.style(id)}" data-ws-orgrow="${esc(id)}" data-state="${esc(r.state)}"><td class="who"><a href="${esc(orgHref(id))}/organization" data-focus-key="${esc(`orgrow:${id}`)}">${av(o.meta(id))}<span class="nm">${esc(o.name(id))}</span></a>${dot(cls, glyph, word, true)}${why}</td><td>${agentsCell}</td><td class="hide-m">${projectsCell}</td><td>${needsCell}</td></tr>`;
}).join('');
const orgList = o.rows.length ? `<div class="ws-tbl"><table class="ws-orgtbl" data-ws-orgs><thead><tr><th scope="col">Organization</th><th scope="col">Agents</th><th scope="col" class="hide-m">Projects</th><th scope="col">Needs you</th></tr></thead><tbody>${orgTable}</tbody></table></div>` : '<p class="ws-panel tight note" data-ws-orgs>No organizations yet</p>';
const recent = projectRows.filter(p => p.lastActivity).slice(0, 6);
const STATE_WORD = { working: 'has a session working', waiting: 'is waiting on you', idle: 'has an idle session', none: 'no live session' };
@@ -582,15 +664,16 @@
const max = Math.max(1, ...srows.map(s => s.n));
const states = srows.length ? `<div class="ws-panel tight ws-states" data-ws-states>${srows.map(s => { const ps = [...s.g.entries()].filter(([, n]) => n > 0).map(([id, n]) => ({ id, n })); return `<div class="ws-srow"><span class="sl">${esc(s.name)}</span><span class="sn">${s.n}</span>${bar(o, ps, `width:${Math.max(4, Math.round((s.n / max) * 90))}%`)}${by(o, ps)}</div>`; }).join('')}</div>` : `<p class="ws-panel tight note" data-ws-states>${noneRead(o, ['tasks']) ? 'Tasks not read' : 'No open tasks'}</p>`;
const needs = inbox.slice(0, 5);
const needsList = needs.length ? `<ul class="ws-needs" data-ws-needs>${needs.map(d => `<li class="ws-edge ws-o" style="${o.style(d.org)}">${av(o.meta(d.org), 'md')}<a class="q" href="${esc(selHref(`/inbox?d=${enc(itemKey(d))}`))}" data-focus-key="${esc(`need:${itemKey(d)}`)}">${esc(d.question || `Decision ${d.id}`)}</a><span class="src">${fromWords(o, d)}</span>${classChip(d.class)}</li>`).join('')}</ul>${inbox.length > needs.length ? `<p class="note ws-more-line">${inbox.length - needs.length} more in the inbox</p>` : ''}` : `<p class="ws-panel tight note" data-ws-needs>${noneRead(o, ['inbox']) ? 'Decisions not read' : 'Nothing needs you'}</p>`;
// SP3: the same order as #/inbox, newest first, so these five are the Inbox's top five.
const needs = inbox.slice().sort(newest).slice(0, 5);
const needsList = needs.length ? `<ul class="ws-needs" data-ws-needs>${needs.map(d => `<li class="ws-edge ws-o" style="${o.style(d.org)}">${av(o.meta(d.org), 'md')}<a class="q" href="${esc(`#/inbox?d=${enc(itemKey(d))}`)}" data-focus-key="${esc(`need:${itemKey(d)}`)}">${esc(d.question || `Decision ${d.id}`)}</a><span class="src">${fromWords(o, d)}</span>${classChip(d.class)}</li>`).join('')}</ul>${inbox.length > needs.length ? `<p class="note ws-more-line">${inbox.length - needs.length} more in the inbox</p>` : ''}` : `<p class="ws-panel tight note" data-ws-needs>${noneRead(o, ['inbox']) ? 'Decisions not read' : 'Nothing needs you'}</p>`;
const now = sessions.filter(s => s.kind === 'thread' || s.state === 'working' || s.state === 'waiting');
const idle = sessions.length - now.length;
const who = s => (s.kind === 'thread' ? s.instance || s.thread || 'thread' : s.role || 'agent');
const what = s => s.project?.name || s.task?.title || '';
const st = s => { const [cls, glyph, word] = s.kind === 'thread' ? ['s-working', '●', 'live'] : ACTIVITY[s.state] || ['s-unknown', '?', s.state || 'not reported']; return `${dot(cls, glyph, word === 'waiting on you' ? 'waiting' : word, true)}${s.state === 'waiting' ? ' <span class="muted">on you</span>' : s.since ? ` <span class="muted">${esc(span(s.since))}</span>` : ''}`; };
const sessTable = now.length ? `<div class="ws-tbl"><table class="ws-sess" data-ws-sessions><thead><tr><th scope="col">Agent and project</th><th scope="col">Status</th></tr></thead><tbody>${now.slice(0, 8).map(s => `<tr><td class="who"><span class="ws-orgref">${av(o.meta(s.org), 'xs')}<span class="ws-sr">${esc(o.name(s.org))}: </span>${esc(who(s))}</span>${what(s) ? `<span class="muted"> · ${esc(what(s))}</span>` : ''}</td><td class="st">${st(s)}</td></tr>`).join('')}</tbody></table></div>${now.length > 8 ? `<p class="note ws-more-line">${now.length - 8} more on Agents</p>` : ''}` : `<p class="ws-panel tight note" data-ws-sessions>${noneRead(o, ['agents', 'claims']) ? 'Sessions not read' : `No session working right now${idle ? `; ${plural(idle, 'idle session')}` : ''}`}</p>`;
const sessTable = now.length ? `<div class="ws-tbl"><table class="ws-sess" data-ws-sessions><thead><tr><th scope="col">Agent and project</th><th scope="col">Status</th></tr></thead><tbody>${now.slice(0, 8).map(s => `<tr><td class="who"><span class="ws-orgref">${av(o.meta(s.org), 'xs')}<span class="ws-sr">${esc(o.name(s.org))}: </span>${esc(who(s))}</span>${what(s) ? `<span class="muted"> · ${esc(what(s))}</span>` : ''}</td><td class="ws-st">${st(s)}</td></tr>`).join('')}</tbody></table></div>${now.length > 8 ? `<p class="note ws-more-line">${now.length - 8} more on Agents</p>` : ''}` : `<p class="ws-panel tight note" data-ws-sessions>${noneRead(o, ['agents', 'claims']) ? 'Sessions not read' : `No session working right now${idle ? `; ${plural(idle, 'idle session')}` : ''}`}</p>`;
const total = t ? num(t.projects?.active) + num(t.projects?.archived) : null;
const allRead = !o.unread.length;
@@ -600,19 +683,19 @@
return `<article class="ws ws-home" data-ws-home>
<div class="ws-vh"><h1 tabindex="-1">Dashboard</h1><p class="sub">${sub}</p></div>
${tiles}
${secH('Organizations', `read ${esc(hm(body.readAt))}`)}
<ul class="ws-orgcards" data-ws-orgs>${cards || '<li class="ws-line">No organizations yet</li>'}</ul>
<div class="ws-split ws-home-split">
<section aria-label="Projects and tasks">
<section aria-label="Organizations, projects and tasks">
${secH('Organizations', `read ${esc(hm(body.readAt))}`)}
${orgList}
${secH('Recent project activity', 'latest change per project; there is no activity feed yet', `<a href="${esc(selHref('/projects'))}" data-focus-key="home-projects">All projects</a>`)}
${trail}${missLine(o, ['projects'], 'recent')}
${secH('Tasks by state', 'open tasks, every tracker', `<a href="${esc(selHref('/tasks'))}" data-focus-key="home-tasks">Open tasks</a>`)}
${states}${missLine(o, ['tasks'], 'states')}
</section>
<section aria-label="Needs you and sessions">
${secH('Needs you', '', `<a href="${esc(selHref('/inbox'))}" data-focus-key="home-inbox">Inbox</a>`)}
${secH('Needs you', '', '<a href="#/inbox" data-focus-key="home-inbox">Inbox</a>')}
${needsList}${missLine(o, ['inbox'], 'needs')}
${secH('Sessions now', '', `<a href="${esc(selHref('/agents'))}" data-focus-key="home-agents">Agents</a>`)}
${secH('Active agents', 'sessions now', '<a href="#/agents" data-focus-key="home-agents">Agents</a>')}
${sessTable}${missLine(o, ['agents', 'claims'], 'sessions')}
</section>
</div>
@@ -710,76 +793,219 @@
</section>`;
}
// ---- inbox across organizations (sample 05) ----
// `opts.hire`: a function that returns the hire, fire and change form bus.js builds for the current
// organization (D4, P0-1). It is called after the workspace read so typing or a submit result that
// lands during the read is not painted over with an older draft.
// ---- inbox across organizations (sample 05; SP3 prototype 1114 /inbox) ----
// SP3: #/inbox lists every organization's items from one read (GET /api/workspace), newest first,
// each row with its organization chip and a project chip when it has one. The organization and type
// filters live in the hash query and run on that read, so the chip counts, the sidebar count and the
// dashboard's Needs you agree. `opts.scope` is the organization of #/orgs/<id>/inbox: the same list,
// filtered to it. `opts.answer(d)` returns the answer panel bus.js builds in the row's own
// organization; `opts.answered(key)` keeps its receipt after the row leaves the list. `opts.hire`: a
// function that returns the hire, fire and change form bus.js builds for the current organization
// (D4, P0-1), shown on the scoped list only. It is called after the read so typing or a submit
// result that lands during the read is not painted over with an older draft.
const TYPE_RE = /^[a-z][a-z-]{0,31}$/;
async function inboxPage(q, opts = {}) {
const org = listParam(q, 'org', id => ORG_ID.test(id));
const scope = typeof opts.scope === 'string' && ORG_ID.test(opts.scope) ? opts.scope : null;
const org = scope ? [scope] : listParam(q, 'org', id => ORG_ID.test(id));
const type = TYPE_RE.test(String(q?.get?.('type') || '')) ? q.get('type') : null;
const want = String(q?.get?.('d') || '');
let body, all;
try {
[body, all] = await Promise.all([data.workspace({ sections: ['inbox'], org }), org ? data.workspace({ sections: ['inbox'] }) : null, ensureThemes()]);
took(body);
} catch (err) { return failedPage('ws-inbox', 'data-ws-inbox', 'Inbox', err); }
const every = orgsOf(all || body), o = orgsOf(body);
const everyRows = arr((all || body).inbox);
let body;
try { [body] = await Promise.all([data.workspace({ sections: ['inbox'] }), ensureThemes()]); took(body); }
catch (err) { return failedPage('ws-inbox', 'data-ws-inbox', 'Inbox', err); }
const every = orgsOf(body), everyRows = arr(body.inbox).filter(d => d && typeof d.org === 'string');
if (!noneRead(every, ['inbox'])) tellInbox(everyRows);
const counts = new Map();
for (const d of everyRows) counts.set(d.org, (counts.get(d.org) || 0) + 1);
const rows = arr(body.inbox);
// The organizations in view: every one, or the chosen ones.
const o = org ? { ...every, rows: every.rows.filter(r => org.includes(r.org)), unread: every.unread.filter(r => org.includes(r.org)) } : every;
const inOrg = everyRows.filter(d => !org || org.includes(d.org)).sort(newest);
const rows = inOrg.filter(d => !type || d.class === type);
const picked = want === 'none' ? null : rows.find(d => itemKey(d) === want) || (want ? null : rows[0] || null);
const qs = d => { const p = new URLSearchParams(); if (org) p.set('org', org.join(',')); p.set('d', d ? itemKey(d) : 'none'); return `/inbox?${p}`; };
const here = path => (scope ? `${orgHref(scope)}${path}` : `#${path}`);
const qs = d => { const p = new URLSearchParams(); if (org && !scope) p.set('org', org.join(',')); if (type) p.set('type', type); p.set('d', d ? itemKey(d) : 'none'); return here(`/inbox?${p}`); };
const chips = d => `${orgChip(o, d.org)}${projChip(d.project?.name)}`;
const row = d => {
const on = picked && itemKey(d) === itemKey(picked);
const on = picked && itemKey(d) === itemKey(picked), by = roleOf(d);
return `<tr class="ws-row ws-edge ws-o${on ? ' on' : ''}" style="${o.style(d.org)}" data-ws-item="${esc(itemKey(d))}">
<td class="src hide-m">${o.ref(d.org)}<span class="via">${fromWords(o, d, false)}</span></td>
<td><span class="ws-msrc show-m">${av(o.meta(d.org), 'xs')}${fromWords(o, d)}</span><a class="q" href="${esc(selHref(qs(d)))}" data-ws-select="${esc(itemKey(d))}" data-focus-key="${esc(`item:${itemKey(d)}`)}"${on ? ' aria-current="true"' : ''}>${esc(d.question || `Decision ${d.id}`)}</a><span class="via">decision <span class="mono">${esc(d.id)}</span>${d.taskRef ? ` · task ${esc(d.taskRef)}` : ''}</span><span class="show-m">${classChip(d.class)}${d.blocking ? ' <span class="ws-chip block">blocking</span>' : ''}</span></td>
<td><a class="q" href="${esc(qs(d))}" data-ws-select="${esc(itemKey(d))}" data-focus-key="${esc(`item:${itemKey(d)}`)}"${on ? ' aria-current="true"' : ''}>${esc(d.question || `Decision ${d.id}`)}</a><span class="ws-ichips">${chips(d)}<span class="via">${by ? `${esc(by)} · ` : ''}decision <span class="mono">${esc(d.id)}</span>${d.taskRef ? ` · task ${esc(d.taskRef)}` : ''}</span><span class="show-m">${classChip(d.class)}${d.blocking ? ' <span class="ws-chip block">blocking</span>' : ''}</span></span></td>
<td class="hide-m">${classChip(d.class)}${d.blocking ? ' <span class="ws-chip block">blocking</span>' : ''}</td>
<td class="num">${d.at ? `<time datetime="${esc(d.at)}">${esc(span(d.at))}</time>` : '<span class="muted">not reported</span>'}</td>
</tr>`;
};
const unread = (o.unread.length ? `<p class="note ws-unread-note" data-ws-unread>Not in this list: ${andList(o.unread.map(stateWords))}.</p>` : '') + missLine(o, ['inbox'], 'inbox');
const table = rows.length ? `<div class="ws-tbl"><table class="ws-ibx" data-ws-items><caption class="ws-sr">Items that need you</caption><thead><tr><th scope="col" class="hide-m">Source</th><th scope="col">Needs</th><th scope="col" class="hide-m">Class</th><th scope="col" class="num">Waiting</th></tr></thead><tbody>${rows.map(row).join('')}</tbody></table></div>` : `<p class="ws-panel tight note" data-ws-items>${noneRead(o, ['inbox']) ? 'Decisions not read' : org ? 'Nothing needs you in these organizations' : 'Nothing needs you'}</p>`;
// An organization that did not answer is named first, with the reason its read gave.
const unread = unreadNote(o, ['inbox'], 'inbox');
const filtered = (org && !scope) || type;
const table = rows.length ? `<div class="ws-tbl"><table class="ws-ibx" data-ws-items><caption class="ws-sr">Items that need you</caption><thead><tr><th scope="col">Needs</th><th scope="col" class="hide-m">Class</th><th scope="col" class="num">Waiting</th></tr></thead><tbody>${rows.map(row).join('')}</tbody></table></div>` : `<p class="ws-panel tight note" data-ws-items>${noneRead(o, ['inbox']) ? 'Decisions not read' : filtered ? 'Nothing matches these filters' : 'Nothing needs you'}</p>`;
// The hire, fire and change form posts to one organization's bus, so the system list links to
// each answering organization's own Inbox, where the form is: only those whose own config says this
// Console decides there, never judged by the organization opened last (its bus may be the stopped one).
// Read before the answer panel: its HTML must be the last thing this render waits for, so a
// confirmation shown while another read was in flight is never painted over with an older panel.
const asks = typeof opts.hireIn === 'function' && !scope ? o.rows.filter(r => r.state === 'ok') : [];
const hiring = (await Promise.all(asks.map(async r => ((await opts.hireIn(r.org)) === true ? r : null)))).filter(Boolean);
let insp = '';
if (picked) {
const d = picked, id = esc(d.id);
const decideHref = `${orgHref(d.org)}/inbox/${enc(d.id)}`;
const opts = arr(d.options);
const optList = opts.length ? `<ul class="ws-opts">${opts.map(x => `<li><div class="row"><span class="k">${esc(x.key)}</span><b>${esc(x.text || '')}</b></div><div class="row"><a class="ws-btn" href="${esc(decideHref)}" data-focus-key="${esc(`answer:${itemKey(d)}:${x.key}`)}">${d.console ? `Answer ${esc(x.key)}…` : 'Open the decision'}<span class="ws-sr"> on ${esc(o.name(d.org))}'s bus</span></a></div></li>`).join('')}</ul>` : `<p class="note">No options were given. <a href="${esc(decideHref)}" data-focus-key="${esc(`answer:${itemKey(d)}`)}">Open the decision</a></p>`;
const answerHtml = (await opts.answer?.(d)) || '';
const choices = arr(d.options);
const optList = choices.length ? `<ul class="ws-opts">${choices.map(x => `<li><div class="row"><span class="k">${esc(x.key)}</span><b>${esc(x.text || '')}</b></div>${answerHtml.includes('data-decide') ? '' : `<div class="row"><a class="ws-btn" href="${esc(decideHref)}" data-focus-key="${esc(`answer:${itemKey(d)}:${x.key}`)}">${d.console ? `Answer ${esc(x.key)}…` : 'Open the decision'}<span class="ws-sr"> on ${esc(o.name(d.org))}'s bus</span></a></div>`}</li>`).join('')}</ul>` : `<p class="note">No options were given. <a href="${esc(decideHref)}" data-focus-key="${esc(`answer:${itemKey(d)}`)}">Open the decision</a></p>`;
const cmds = arr(d.decide).filter(c => typeof c?.command === 'string' && c.command);
const term = cmds.length ? `<div data-ws-cmds><span class="ws-label">Answer from a terminal</span>${cmds.map(c => `<div class="ws-cmd"><code>${esc(c.command)}</code><button type="button" class="ws-btn" data-copy="${esc(c.command)}" data-focus-key="${esc(`copy:${itemKey(d)}:${c.key}`)}" aria-label="Copy the command for option ${esc(c.key)}" title="Copy">${icon('copy')}</button></div>`).join('')}<p class="note">The inbox mixes organizations, so the copied command always names the organization's bus.</p><p class="small muted" id="copy-status" role="status"></p></div>` : '<p class="note" data-ws-cmds>No terminal command for this item: its id or options cannot be passed to a shell safely.</p>';
const by = roleOf(d);
insp = `<aside class="ws-insp ws-o" style="${o.style(d.org)}" aria-label="Decision ${id}" data-ws-insp="${esc(itemKey(d))}">
<header>${av(o.meta(d.org))}<span class="ws-label">Decision <span class="mono">${id}</span></span>${classChip(d.class)}<a class="x" href="${esc(selHref(qs(null)))}" data-ws-select="none" data-focus-key="insp-close" aria-label="Close the decision">${icon('close')}</a></header>
<header>${av(o.meta(d.org))}<span class="ws-label">Decision <span class="mono">${id}</span></span>${classChip(d.class)}<a class="x" href="${esc(qs(null))}" data-ws-select="none" data-focus-key="insp-close" aria-label="Close the decision">${icon('close')}</a></header>
<div class="body">
<div class="ws-ichips">${chips(d)}</div>
<h3>${esc(d.question || `Decision ${d.id}`)}</h3>
<div class="ws-auth">${esc(o.name(d.org))} · ${esc(d.project?.name || 'No project')}${by ? ` · raised by <b>${esc(by)}</b>` : ''}${d.at ? ` at ${esc(hm(d.at))}` : ''}.${d.class === 'gated' ? ' Only you can answer a gated decision.' : ''}</div>
${d.task?.title || d.taskRef ? `<p class="note">Task ${esc(d.taskRef || '')}${d.task?.title ? ` · ${esc(d.task.title)}` : ''}</p>` : ''}
${optList}
${answerHtml}
<p><a class="ws-btn" href="${esc(decideHref)}" data-ws-open data-focus-key="${esc(`open:${itemKey(d)}`)}">Open in ${esc(o.name(d.org))}</a></p>
${term}
<div><span class="ws-label">History</span><p class="note">Not built yet.</p></div>
</div>
</aside>`;
} else if (want && want !== 'none') {
// The answered row has left the list; its receipt stays until another row is chosen.
const kept = opts.answered?.(want) || '';
if (kept) insp = `<aside class="ws-insp" aria-label="Answered" data-ws-insp="${esc(want)}"><header><span class="ws-label">Answered</span><a class="x" href="${esc(qs(null))}" data-ws-select="none" data-focus-key="insp-close" aria-label="Close">${icon('close')}</a></header><div class="body">${kept}</div></aside>`;
}
// Type chips: the decision classes the read carries, in the organizations in view.
const typeCounts = new Map();
for (const d of inOrg) if (typeof d.class === 'string' && TYPE_RE.test(d.class)) typeCounts.set(d.class, (typeCounts.get(d.class) || 0) + 1);
const types = [...new Set([...typeCounts.keys(), ...(type ? [type] : [])])].sort();
const typeChips = `<div class="ws-fchips" role="group" aria-label="Class"><span class="ws-label">Class</span><button type="button" class="f plain" data-ws-type="" data-focus-key="type:all" aria-pressed="${!type}">All <span class="n">${inOrg.length}</span></button>${types.map(c => `<button type="button" class="f plain" data-ws-type="${esc(c)}" data-focus-key="${esc(`type:${c}`)}" aria-pressed="${type === c}">${esc(TYPE_WORD[c] || c)} <span class="n">${typeCounts.get(c) || 0}</span></button>`).join('')}</div>`;
const hireIn = hiring.length ? `<p class="note" data-ws-hire-in>Hire, fire or change an agent in ${andList(hiring.map(r => `<a href="${esc(`${orgHref(r.org)}/inbox`)}" data-focus-key="${esc(`hire-in:${r.org}`)}">${esc(o.name(r.org))}</a>`))}.</p>` : '';
const orgsWith = new Set(rows.map(d => d.org)).size;
const sub = rows.length ? `${plural(rows.length, 'item')} need${rows.length === 1 ? 's' : ''} you, from ${plural(orgsWith, 'organization')}. Each row names where it came from. An item leaves only when it is answered.` : `${noneRead(o, ['inbox']) ? 'No organization\'s inbox could be read.' : missed(o, ['inbox']).length || o.unread.length ? 'Nothing needs you in the organizations that were read.' : 'Nothing needs you right now.'} An item leaves only when it is answered.`;
return `<section class="ws ws-inbox" data-ws-inbox>
const tally = rows.length ? ` ${plural(rows.length, 'item')}${scope ? '' : ` from ${plural(orgsWith, 'organization')}`}.` : '';
const sub = scope
? `Items from ${esc(o.name(scope))} only.${tally} <a href="#/inbox" data-focus-key="inbox-all">Every organization</a>`
: `Everything waiting on you, from every organization.${tally} An item leaves only when it is answered.`;
return `<section class="ws ws-inbox" data-ws-inbox${scope ? ` data-ws-scope="${esc(scope)}"` : ''}>
<div class="ws-vh"><h1 tabindex="-1">Inbox</h1><p class="sub">${sub}</p></div>
<div class="ws-toolbar">
${orgChips(every, counts, org, everyRows.length, ['inbox'])}
<div class="ws-right"><span class="ws-seg" role="group" aria-label="State" aria-describedby="ws-tabs-why"><button type="button" aria-pressed="true" data-focus-key="tab-needs">Needs you</button><button type="button" aria-pressed="false" disabled title="Not built yet">Seen</button><button type="button" aria-pressed="false" disabled title="Not built yet">Answered</button></span><span class="note" id="ws-tabs-why">Seen and Answered are not built yet.</span></div>
</div>
${unread}
<div class="ws-toolbar ws-ibx-filters">
${scope ? '' : `<div class="ws-fgroup"><span class="ws-label">Org</span>${orgChips(every, counts, org, everyRows.length, ['inbox'])}</div>`}
${typeChips}
</div>
<div class="ws-ibx-grid${insp ? ' with-insp' : ''}"><div class="ws-ibx-list">${table}
${secH('Answered today', 'kept for 24 hours, then in the trail')}
<p class="ws-panel tight note" data-ws-answered>Answered and expired items are not built yet.</p>
${typeof opts?.hire === 'function' ? opts.hire() : ''}</div>
${typeof opts.hire === 'function' ? opts.hire() : hireIn}</div>
${insp}
</div>
</section>`;
}
// ---- agents across organizations (#1873 SP5, prototype shot 14) ----
// One table of every organization's agents: the organization's own instances and the root and
// project copies its bus booted with, from each organization's instances read; what each one works
// on from the workspace read's role sessions. Filters by organization and state live in the hash.
// `opts.scope` names one organization (#/orgs/<id>/agents): the same table, that organization only.
// `opts.fireIn(org)` says from that organization's own config whether this Console decides there;
// Fire is drawn only on the system page and only there, and posts to the row's organization (bus.js).
const AGENT_STATE = [['working', 'Working'], ['waiting', 'Waiting on you'], ['idle', 'Idle'], ['running', 'Running'], ['not-running', 'Not running'], ['cant-launch', "Can't launch"]];
const AGENT_STATE_KEY = { working: 'working', 'waiting on you': 'waiting', idle: 'idle', running: 'running', 'not running': 'not-running', "can't launch": 'cant-launch' };
async function agentsPage(q, opts = {}) {
// SP5 review F11: a scope that is not an organization id is refused, never widened to the system list.
if (opts.scope != null && !(typeof opts.scope === 'string' && ORG_ID.test(opts.scope))) return '<section class="ws ws-agents-all" data-ws-agents data-ws-failed><div class="ws-vh"><h1 tabindex="-1">Agents</h1><p class="sub">That is not an organization address.</p></div></section>';
const scope = opts.scope ?? null;
const org = scope ? [scope] : listParam(q, 'org', id => ORG_ID.test(id));
const want = String(q?.get?.('state') || '');
const stateF = AGENT_STATE.some(([k]) => k === want) ? want : null;
let body;
try { [body] = await Promise.all([data.workspace({ sections: ['sessions', 'projects'] }), ensureThemes()]); took(body); }
catch (err) { return failedPage('ws-agents-all', 'data-ws-agents', 'Agents', err); }
const every = orgsOf(body);
const o = org ? { ...every, rows: every.rows.filter(r => org.includes(r.org)), unread: every.unread.filter(r => org.includes(r.org)) } : every;
const askable = (scope ? o.rows : every.rows).filter(r => r.state === 'ok');
// Each answering organization's instances, and (system page only) whether this Console decides there.
const reads = await Promise.all(askable.map(r => Promise.all([
data.instances(r.org).then(v => ({ inst: instancesOf(v), copies: copiesOf(v) }), err => ({ inst: null, copies: {}, err })),
!scope && typeof opts.fireIn === 'function' ? opts.fireIn(r.org).then(v => v === true, () => false) : false,
]).then(([v, fire]) => ({ id: r.org, ...v, fire }))));
const sessions = arr(body.sessions).filter(x => x?.kind === 'role' && typeof x.org === 'string' && typeof x.role === 'string');
const projects = arr(body.projects).filter(x => typeof x?.org === 'string');
const projectRef = (id, p) => { const hit = projects.find(x => x.org === id && (x.id === p || x.key === p)); return hit ? { id: hit.id, name: hit.name || hit.key || hit.id } : { id: p, name: p }; };
const all = [];
for (const r of reads) {
if (!r.inst) continue;
const mine = sessions.filter(x => x.org === r.id);
const agents = mine.map(x => ({ role: x.role, holder_run: x.run, state: x.state }));
const session = name => mine.find(x => x.role === name) || null;
for (const [name, item] of Object.entries(r.inst)) {
const d = activity(name, item, agents);
// Never Fire the chief, the assistant or an instance the bus would refuse to end.
const keep = item?.definition === 'chief-of-staff' || name === 'chief' || item?.definition === 'assistant' || item?.endProtected === true;
all.push({ org: r.id, key: name, name, level: 'org', role: roleWords(item), id: isHired(item) ? item.definition : '', dot: d, s: session(name), fire: r.fire && !keep });
}
for (const [key, c] of Object.entries(r.copies || {})) {
if (!c || typeof c.name !== 'string') continue;
const d = copyDot(key, c, agents);
all.push({ org: r.id, key, name: c.name, level: c.level === 'project' ? 'project' : 'root', role: roleWords(c), id: copyBlocked(c) ? copyWhy(c) : '', dot: d, s: session(key), project: c.level === 'project' && c.project ? projectRef(r.id, c.project) : null, fire: false });
}
}
for (const a of all) a.state = AGENT_STATE_KEY[a.dot[2]] || 'not-running';
const counts = new Map();
for (const a of all) counts.set(a.org, (counts.get(a.org) || 0) + 1);
const inOrg = all.filter(a => !org || org.includes(a.org)).sort((x, y) => x.org.localeCompare(y.org) || x.name.localeCompare(y.name) || x.key.localeCompare(y.key));
const filteredRows = inOrg.filter(a => !stateF || a.state === stateF);
// SP5 review F1/F2: Open addresses one agent (`#/orgs/<id>/agents?agent=<key>`). The scoped page puts
// that agent first and marks it, and draws no Open of its own, which would only link to itself.
const picked = scope ? String(q?.get?.('agent') || '') : '';
const hit = picked ? filteredRows.find(a => a.key === picked) || null : null;
const rows = hit ? [hit, ...filteredRows.filter(a => a !== hit)] : filteredRows;
const akey = a => `${a.org}:${a.key}`;
const orgChip = a => `<span class="ws-chip ws-o ws-ochip" style="${o.style(a.org)}" data-ws-orgchip><i aria-hidden="true"></i>${esc(o.name(a.org))}</span>`;
const projOf = a => a.project || a.s?.project || null;
const projChip = a => (projOf(a)?.name ? `<span class="ws-chip outline ws-pchip" data-ws-projchip>${esc(projOf(a).name)}</span>` : '');
const work = a => (a.s?.task ? `${esc(a.s.task.title || a.s.task.ref)}${a.s.task.title && a.s.task.ref ? `<span class="t2 mono">${esc(a.s.task.ref)}</span>` : ''}` : '<span class="muted">nothing reported</span>');
const LEVEL_WORD = { root: 'root agent copy', project: 'project agent' };
const row = a => `<tr class="ws-row ws-edge ws-o${a === hit ? ' on' : ''}" style="${o.style(a.org)}" data-ws-agent="${esc(akey(a))}"${a === hit ? ' aria-current="true"' : ''}>
<td class="t1">${esc(a.name)}${a.id ? `<span class="t2${a.level === 'org' ? ' mono' : ''}">${esc(a.id)}</span>` : ''}<span class="ws-ichips">${orgChip(a)}${projChip(a)}<span class="show-m ws-arole">${esc(a.role)}</span></span><span class="t2 show-m">${a.s?.task ? `Working on ${esc(a.s.task.title || a.s.task.ref)}` : 'Working on nothing reported'}</span></td>
<td class="hide-m" data-ws-role>${esc(a.role)}${a.level !== 'org' ? `<span class="t2">${esc(LEVEL_WORD[a.level])}</span>` : ''}</td>
<td>${dot(...a.dot, true)}</td>
<td class="hide-m" data-ws-work>${work(a)}</td>
${scope ? '' : `<td class="ws-act"><a class="ws-btn" href="${esc(`${orgHref(a.org)}/agents?agent=${encodeURIComponent(a.key)}`)}" data-ws-open data-focus-key="${esc(`open:${akey(a)}`)}">Open<span class="ws-sr"> ${esc(a.name)} in ${esc(o.name(a.org))}</span></a>${a.fire ? window.MosaicDecide?.fireControl(a.org, a.name, true, o.name(a.org)) ?? '' : ''}</td>`}
</tr>`;
// An organization that did not answer is named first, with the reason its read gave; one that
// answered but whose instances read failed is named too, never counted as having no agents.
const why = r => `${stateWords(r).replace(/, read .*$/, '')}${r.reason ? `: ${esc(r.reason)}` : ''}${r.at ? ` (read ${esc(hm(r.at))})` : ''}`;
const failed = reads.filter(r => !r.inst && (!org || org.includes(r.id)));
const READ_ERR = { 403: 'refused', 0: 'signed out' };
const unread = (o.unread.length ? `<p class="note ws-unread-note" data-ws-unread>Not read: ${andList(o.unread.map(why))}.</p>` : '')
+ (failed.length ? `<p class="note ws-miss" data-ws-miss="instances">Agents not read in ${andList(failed.map(r => `${esc(o.name(r.id))} (${esc(READ_ERR[r.err?.status] || r.err?.code || 'no answer')})`))}.</p>` : '')
+ missLine(o, ['agents', 'tasks'], 'agents', 'What agents work on was not read in');
const anyRead = reads.some(r => r.inst && (!org || org.includes(r.id)));
const filtered = (org && !scope) || stateF;
const table = rows.length
? `<div class="ws-tbl"><table class="ws-agt" data-ws-agent-list><caption class="ws-sr">Agents</caption><thead><tr><th scope="col">Agent</th><th scope="col" class="hide-m">Role</th><th scope="col">State</th><th scope="col" class="hide-m">Working on</th>${scope ? '' : '<th scope="col"><span class="ws-sr">Actions</span></th>'}</tr></thead><tbody>${rows.map(row).join('')}</tbody></table></div>`
: `<p class="ws-panel tight note" data-ws-agent-list>${!anyRead && o.rows.length ? 'Agents not read' : filtered ? 'Nothing matches these filters' : 'No agents'}</p>`;
const stateCounts = new Map();
for (const a of inOrg) stateCounts.set(a.state, (stateCounts.get(a.state) || 0) + 1);
const shown = AGENT_STATE.filter(([k]) => stateCounts.has(k) || k === stateF);
const stateChips = `<div class="ws-fchips" role="group" aria-label="State"><span class="ws-label">State</span><button type="button" class="f plain" data-ws-astate="" data-focus-key="astate:all" aria-pressed="${!stateF}">All <span class="n">${inOrg.length}</span></button>${shown.map(([k, w]) => `<button type="button" class="f plain" data-ws-astate="${k}" data-focus-key="${esc(`astate:${k}`)}" aria-pressed="${stateF === k}">${esc(w)} <span class="n">${stateCounts.get(k) || 0}</span></button>`).join('')}</div>`;
// The org chips count each answering organization's agents; an organization whose instances read
// failed shows "not read", as one that did not answer shows its state.
const notRead = new Set(reads.filter(r => !r.inst).map(r => r.id));
const chipOrgs = { ...every, rows: every.rows.map(r => (notRead.has(r.org) ? { ...r, errors: { ...(r.errors || {}), instances: 'not read' } } : r)) };
const orgsWith = new Set(rows.map(a => a.org)).size;
const tally = rows.length ? ` ${plural(rows.length, 'agent')}${scope ? '' : ` in ${plural(orgsWith, 'organization')}`}.` : '';
const sub = scope
? `Agents in ${esc(o.name(scope))} only.${tally} <a href="#/agents" data-focus-key="agents-all">Every organization</a>`
: `Every agent on the system, by organization.${tally} Open one to see it in its organization.`;
return `<section class="ws ws-agents-all" data-ws-agents${scope ? ` data-ws-scope="${esc(scope)}"` : ''}>
<div class="ws-vh"><h1 tabindex="-1">Agents</h1><p class="sub">${sub}</p></div>
${unread}
<div class="ws-toolbar ws-ibx-filters">
${scope ? '' : `<div class="ws-fgroup"><span class="ws-label">Org</span>${orgChips(chipOrgs, counts, org, all.length, ['instances'])}</div>`}
${stateChips}
</div>
${table}
${scope ? '' : `<div data-agents-receipt="*" role="status">${window.MosaicDecide?.fireNote('*') ?? ''}</div>`}
</section>`;
}
// ---- controls: filters write the hash query and repaint in place ----
const pathOf = () => route().split('?')[0];
const queryOf = () => new URLSearchParams(route().split('?')[1] || '');
@@ -787,7 +1013,8 @@
const q = queryOf();
for (const [k, v] of Object.entries(change)) { if (v === null || v === undefined || v === '' || (Array.isArray(v) && !v.length)) q.delete(k); else q.set(k, Array.isArray(v) ? v.join(',') : String(v)); }
const s = q.toString();
history.replaceState(history.state, '', `${selHref(pathOf())}${s ? `?${s}` : ''}`);
// SP3: the address keeps its own form, an organization's or the system's (#/inbox).
history.replaceState(history.state, '', `${/^#\/orgs\/[^/?]+/.exec(location.hash)?.[0] ?? '#'}${pathOf()}${s ? `?${s}` : ''}`);
if (render) document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
}
function setGrouping(g) {
@@ -795,8 +1022,10 @@
if (pathOf() === '/projects') document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
}
document.addEventListener('click', e => {
const page = e.target.closest?.('[data-ws-projects],[data-ws-inbox]');
const page = e.target.closest?.('[data-ws-projects],[data-ws-inbox],[data-ws-agents]');
if (!page) return;
const st = e.target.closest('[data-ws-astate]');
if (st) { setQuery({ state: st.dataset.wsAstate || null }); return; }
const chip = e.target.closest('[data-ws-org]');
if (chip) {
const id = chip.dataset.wsOrg, now = listParam(queryOf(), 'org', x => ORG_ID.test(x)) || [];
@@ -810,6 +1039,8 @@
setQuery(s === f.sort ? { sort: s, order: f.order === 'desc' ? 'asc' : 'desc' } : { sort: s, order: null });
return;
}
const kind = e.target.closest('[data-ws-type]');
if (kind) { setQuery({ type: kind.dataset.wsType || null, d: null }); return; }
const grp = e.target.closest('[data-ws-group]');
if (grp) { setGrouping(grp.dataset.wsGroup); return; }
const pick = e.target.closest('[data-ws-select]');
@@ -829,6 +1060,6 @@
// U4b: the org mark (colour and initials) for the task board (tasks-board.js).
const orgMark = Object.freeze({ ready: ensureThemes, av, colours, initials });
window.MosaicWorkspace = Object.freeze({ dashboard, holdLive, graftLive, agentGrid, icon, orgMark, refresh: () => refresh(), av, colours, label, state, dot, themes: ensureThemes, home, projectsPage, inboxPage, setGrouping, get pollMs() { return pollMs; } });
window.MosaicWorkspace = Object.freeze({ dashboard, holdLive, graftLive, agentGrid, icon, orgMark, refresh: () => refresh(), av, colours, label, state, dot, themes: ensureThemes, home, projectsPage, inboxPage, agentsPage, inboxCount, setGrouping, orgsOf, orgChip, projChip, unreadNote, setQuery, get pollMs() { return pollMs; } });
refresh();
})();
+2 -2
View File
@@ -65,12 +65,12 @@ const files = new Map([
['/', ['index.html', 'text/html; charset=utf-8']],
['/proxy.js', ['proxy.js', 'text/javascript; charset=utf-8']],
['/project-remote.js', ['project-remote.js', 'text/javascript; charset=utf-8']],
...['app.js', 'brand.js', 'bus.js', 'markdown-preview.js', 'chat.js', 'project-archive.js', 'processing.js', 'agents.js', 'federation.js', 'requests.js', 'org-create.js', 'console-restart.js', 'onboarding.js', 'workspace-data.js', 'workspace.js', 'tasks-board.js', 'panes.js'].map(f => ['/' + f, [f, 'text/javascript; charset=utf-8']]),
...['app.js', 'brand.js', 'bus.js', 'markdown-preview.js', 'chat.js', 'project-archive.js', 'processing.js', 'agents.js', 'federation.js', 'requests.js', 'org-create.js', 'console-restart.js', 'onboarding.js', 'workspace-data.js', 'workspace.js', 'tasks-board.js', 'assistant.js'].map(f => ['/' + f, [f, 'text/javascript; charset=utf-8']]),
['/files.js', ['files.js', 'text/javascript; charset=utf-8']],
['/projects.js', ['projects.js', 'text/javascript; charset=utf-8']],
['/projects.css', ['projects.css', 'text/css; charset=utf-8']],
['/files.css', ['files.css', 'text/css; charset=utf-8']],
...['shared/app.css', 'tokens.css', 'console.css', 'live.css', 'bus.css', 'shell.css', 'chat.css', 'project-archive.css', 'processing.css', 'org-create.css', 'onboarding.css', 'tasks-board.css', 'panes.css'].map(f => ['/' + f, [f, 'text/css; charset=utf-8']]),
...['shared/app.css', 'tokens.css', 'console.css', 'live.css', 'bus.css', 'shell.css', 'chat.css', 'project-archive.css', 'processing.css', 'org-create.css', 'onboarding.css', 'tasks-board.css', 'assistant.css'].map(f => ['/' + f, [f, 'text/css; charset=utf-8']]),
['/display.js', ['display.js', 'text/javascript; charset=utf-8']],
['/inbox.js', ['inbox.js', 'text/javascript; charset=utf-8']],
['/inbox.css', ['inbox.css', 'text/css; charset=utf-8']],
+1 -1
View File
@@ -28,7 +28,7 @@ const LIMIT = 4096;
const codes = {
'invalid-request': 400, 'template-secret-suspected': 400, 'starter-pack-invalid': 400,
'project-not-found': 404,
'pack-plan-stale': 409, 'starter-pack-template-changed': 409, 'organization-busy': 409,
'pack-plan-stale': 409, 'starter-pack-template-changed': 409, 'organization-busy': 409, 'template-exists': 409,
'human-required': 403, 'read-only': 403,
'not-configured': 503, 'no-bus-host': 503,
};
@@ -0,0 +1,401 @@
// SP6 (#1873): the Assistant is one system page. Up to three chat threads from any organization
// open next to each other, each the chat thread view pinned to its own organization.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const P = { alpha: '10000000-0000-4000-8000-00000000000a', beta: '10000000-0000-4000-8000-00000000000b', home: '10000000-0000-4000-8000-00000000000c' };
const T = {
a1: '20000000-0000-4000-8000-0000000000a1', a2: '20000000-0000-4000-8000-0000000000a2',
b1: '20000000-0000-4000-8000-0000000000b1', h1: '20000000-0000-4000-8000-0000000000c1',
};
const NEW = '20000000-0000-4000-8000-0000000000b9';
// Three organizations. `state.down` names the ones whose bus is stopped; `state.sent` and
// `state.created` record every chat write with the organization whose transport received it.
function orgs(state) {
const ORGS = [
{ id: 'alpha', label: 'Alpha', theme: 'rosewood' },
{ id: 'beta', label: 'Beta', theme: 'cobalt' },
{ id: 'home', label: 'Home', theme: 'grove' },
];
const PROJECTS = { alpha: [{ id: P.alpha, name: 'Spring launch' }], beta: [{ id: P.beta, name: 'API gateway' }], home: [{ id: P.home, name: 'Garden' }] };
const THREADS = {
alpha: [{ id: T.a1, project: P.alpha, name: 'Launch email', instance: 'assistant' }, { id: T.a2, project: P.alpha, name: 'Kickoff notes', instance: 'assistant' }],
beta: [{ id: T.b1, project: P.beta, name: 'Gateway auth', instance: 'assistant' }],
home: [{ id: T.h1, project: P.home, name: 'Seed order', instance: 'assistant' }],
};
const MESSAGES = { [T.a1]: 'Alpha draft is ready.', [T.a2]: 'Kickoff agenda.', [T.b1]: 'Beta tokens rotate nightly.', [T.h1]: 'Seeds arrive Monday.' };
const down = () => { throw Object.assign(new Error('bus down'), { code: 'bus-unavailable' }); };
return {
list: async () => ORGS.filter(o => !state.gone?.has(o.id)).map(o => ({ ...o, busHealthy: !state.down.has(o.id), ...(state.down.has(o.id) ? { busStopped: true } : {}) })),
resolve: async id => {
const org = ORGS.find(o => o.id === id); if (!org || state.gone?.has(id)) return null;
if (state.down.has(id)) return { busHealthy: false, reads: null, bus: {}, chat: { projects: down, threads: down, sessions: down, shares: down, messages: down } };
const threads = () => [...THREADS[id], ...state.created.filter(c => c.org === id).map(c => ({ id: c.id, project: c.project, name: c.name, instance: c.instance }))];
return {
busHealthy: true,
send: async () => ({}),
reads: { business: async () => ({ business: { id } }), settings: async () => ({}), busStatus: async () => ({ live: true, down: false }), queue: async () => ({ rows: [] }) },
bus: {
inbox: async () => [], agents: async () => [], tasks: async () => [], 'thread.claims': async () => [], messages: async () => ({ messages: [], unread: 0 }),
instances: async () => ({ business: id, revision: 'a'.repeat(64), definitions: {}, instances: { assistant: { definition: 'assistant', vars: {} } } }),
},
chat: {
projects: async () => PROJECTS[id],
threads: async ({ shared } = {}) => (shared ? [] : threads()),
sessions: async ({ thread }) => [{ id: thread, name: 'default', default: true }],
shares: async () => [],
messages: async ({ thread }) => [
...(MESSAGES[thread] ? [{ id: thread.replace(/^2/, '3'), from_role: 'assistant', body: MESSAGES[thread], at: '2026-11-15T10:00:00.000Z' }] : []),
...state.sent.filter(s => s.org === id && s.thread === thread).map(s => ({ id: s.id, from_role: 'human', body: s.body, at: '2026-11-15T10:01:00.000Z' })),
...(state.replies || []).filter(r => r.org === id && r.thread === thread).map((r, n) => ({ id: `50000000-0000-4000-8000-${String(n + 1).padStart(12, '0')}`, from_role: 'assistant', body: r.body, at: '2026-11-15T10:02:00.000Z' })),
],
send: async ({ thread, body }) => {
const sent = { org: id, thread, body, id: `40000000-0000-4000-8000-${String(state.sent.length + 1).padStart(12, '0')}` };
state.sent.push(sent);
return { id: sent.id };
},
createThread: async ({ project, name, instance }) => {
state.created.push({ org: id, project, name, instance, id: NEW });
return { id: NEW, instance };
},
},
};
},
};
}
async function open(t, { width = 1440, height = 900, hash, state = { down: new Set(['home']), sent: [], created: [] } } = {}) {
const organizations = orgs(state);
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, send: async () => ({}), board: 'http://127.0.0.1:9', log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(width, height);
const base = `http://127.0.0.1:${server.address().port}/`;
await b.navigate(base + hash);
const wait = (expression, tries = 200) => b.evaluate(`(async()=>{for(let i=0;i<${tries};i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
return { b, base, wait, state };
}
const PANE = sel => `document.querySelector('[data-assist-pane="${sel}"]')`;
const panes = `[...document.querySelectorAll('[data-assist-pane]')].map(p => p.dataset.assistPane)`;
const shown = `[...document.querySelectorAll('[data-assist-pane]')].filter(p => p.getClientRects().length).map(p => p.dataset.assistPane)`;
const query = `new URLSearchParams(location.hash.split('?')[1] || '').get('open')`;
const ready = sel => `!!${PANE(sel)}?.querySelector('.chat-log li') && !!${PANE(sel)}?.querySelector('[data-ws-orgchip]')`;
const trail = '(document.getElementById("breadcrumbs").getClientRects().length ? document.getElementById("breadcrumbs").innerText.replace(/\\s+/g, " ").trim() : null)';
const SENT = '/Accepted message|Message shown in this conversation/';
const pick = (b, value) => b.evaluate(`(() => { const s = document.querySelector('[data-assist-open]'); s.value = ${JSON.stringify(value)}; if (s.value !== ${JSON.stringify(value)}) throw Error('no option ' + ${JSON.stringify(value)}); s.dispatchEvent(new Event('change', { bubbles: true })); })()`);
test('the sidebar Assistant opens one system page, and two threads from two organizations open side by side with their chips', async t => {
const { b, wait } = await open(t, { hash: '#/orgs/alpha/tasks' });
await wait(`!!document.querySelector('#sections a[href="#/assistant"]')`);
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('#sections a')].map(a => a.textContent.trim())`).then(v => v.includes('Side by side')), false, 'no Side by side item');
await b.evaluate(`document.querySelector('#sections a[href="#/assistant"]').click()`);
await wait(`location.hash.startsWith('#/assistant') && document.querySelector('#bus-view h1')?.textContent === 'Assistant'`);
assert.equal(await b.evaluate('document.querySelector(\'#sections a[href="#/assistant"]\').getAttribute("aria-current")'), 'page');
// SP7: the page name shows once, as the heading.
assert.equal(await b.evaluate(trail), null);
await wait(`!!document.querySelector('[data-assist-open] optgroup[label^="Beta"] option[value="beta:${T.b1}"]')`);
await pick(b, `alpha:${T.a1}`);
await pick(b, `beta:${T.b1}`);
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)}`);
assert.deepEqual(await b.evaluate(panes), [`alpha:${T.a1}`, `beta:${T.b1}`]);
assert.deepEqual(await b.evaluate(shown), [`alpha:${T.a1}`, `beta:${T.b1}`], 'both panes show at 1440');
const head = sel => b.evaluate(`(() => { const p = ${PANE(sel)}; return { title: p.querySelector('[data-assist-title]').textContent, org: p.querySelector('[data-ws-orgchip]').textContent, project: p.querySelector('[data-ws-projchip]')?.textContent ?? null, close: !!p.querySelector('button[data-assist-close]') }; })()`);
assert.deepEqual(await head(`alpha:${T.a1}`), { title: 'Launch email', org: 'Alpha', project: 'Spring launch', close: true });
assert.deepEqual(await head(`beta:${T.b1}`), { title: 'Gateway auth', org: 'Beta', project: 'API gateway', close: true });
assert.match(await b.evaluate(`${PANE(`alpha:${T.a1}`)}.innerText`), /Alpha draft is ready\./);
assert.match(await b.evaluate(`${PANE(`beta:${T.b1}`)}.innerText`), /Beta tokens rotate nightly\./);
assert.doesNotMatch(await b.evaluate(`${PANE(`alpha:${T.a1}`)}.innerText`), /Beta tokens/);
// One level-1 heading on the page; each pane's own form, field and ids are its own.
assert.equal(await b.evaluate(`document.querySelectorAll('#bus-view h1').length`), 1);
const ids = await b.evaluate(`[...document.querySelectorAll('#bus-view [id]')].map(e => e.id)`);
assert.equal(new Set(ids).size, ids.length, 'no duplicate ids across panes');
assert.equal(await b.evaluate(`document.querySelectorAll('#bus-view form textarea').length`), 2);
});
test('the open set and its order live in the address, so a reload or a pasted address restores the same panes', async t => {
const hash = `#/assistant?open=beta:${T.b1},alpha:${T.a2}`;
const { b, base, wait } = await open(t, { hash });
await wait(`${ready(`beta:${T.b1}`)} && ${ready(`alpha:${T.a2}`)}`);
assert.deepEqual(await b.evaluate(panes), [`beta:${T.b1}`, `alpha:${T.a2}`]);
await pick(b, `alpha:${T.a1}`);
await wait(`${ready(`alpha:${T.a1}`)}`);
assert.equal(await b.evaluate(query), `beta:${T.b1},alpha:${T.a2},alpha:${T.a1}`);
const address = await b.evaluate('location.hash');
await b.navigate('about:blank');
await b.navigate(base + address);
await wait(`${ready(`beta:${T.b1}`)} && ${ready(`alpha:${T.a2}`)} && ${ready(`alpha:${T.a1}`)}`);
assert.deepEqual(await b.evaluate(panes), [`beta:${T.b1}`, `alpha:${T.a2}`, `alpha:${T.a1}`]);
// A hand-edited address is checked before use: bad selectors, repeats and a fourth pane are dropped.
await b.navigate('about:blank');
await b.navigate(base + `#/assistant?open=alpha:${T.a1},alpha:${T.a1},nope,../x:${T.b1},beta:not-a-uuid,beta:${T.b1},alpha:${T.a2},home:${T.h1}`);
await wait(`document.querySelectorAll('[data-assist-pane]').length === 3`);
assert.deepEqual(await b.evaluate(panes), [`alpha:${T.a1}`, `beta:${T.b1}`, `alpha:${T.a2}`]);
await wait(`${query} === 'alpha:${T.a1},beta:${T.b1},alpha:${T.a2}'`);
// With three open the picker offers no fourth.
assert.equal(await b.evaluate(`document.querySelector('[data-assist-open]').disabled`), true);
});
test('a send in organization B\'s pane reaches B\'s thread while organization A was opened last', async t => {
const state = { down: new Set(['home']), sent: [], created: [] };
const { b, wait } = await open(t, { hash: '#/orgs/beta/tasks', state });
await wait(`window.MosaicOrg?.id === 'beta'`);
await b.evaluate(`location.hash = '#/orgs/alpha/tasks'`);
await wait(`window.MosaicOrg?.id === 'alpha'`);
await b.evaluate(`location.hash = '#/assistant?open=beta:${T.b1},alpha:${T.a1}'`);
await wait(`${ready(`beta:${T.b1}`)} && ${ready(`alpha:${T.a1}`)}`);
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'alpha', 'alpha is the organization opened last');
const field = `${PANE(`beta:${T.b1}`)}.querySelector('form textarea')`;
await wait(`!${field}.disabled`);
await b.evaluate(`(() => { const el = ${field}; el.value = 'rotate the beta key'; el.dispatchEvent(new Event('input', { bubbles: true })); el.form.requestSubmit(); })()`);
await wait(`${SENT}.test(${PANE(`beta:${T.b1}`)}.innerText)`);
assert.deepEqual(state.sent.map(({ org, thread, body }) => ({ org, thread, body })), [{ org: 'beta', thread: T.b1, body: 'rotate the beta key' }]);
assert.doesNotMatch(await b.evaluate(`${PANE(`alpha:${T.a1}`)}.innerText`), /Accepted message|Message shown in this conversation/, 'the other pane shows no receipt');
assert.equal(await b.evaluate(`${PANE(`alpha:${T.a1}`)}.querySelector('form textarea').value`), '', 'the other pane keeps its own draft');
// A send in A's pane reaches A.
const other = `${PANE(`alpha:${T.a1}`)}.querySelector('form textarea')`;
await b.evaluate(`(() => { const el = ${other}; el.value = 'alpha copy'; el.dispatchEvent(new Event('input', { bubbles: true })); el.form.requestSubmit(); })()`);
await wait(`${SENT}.test(${PANE(`alpha:${T.a1}`)}.innerText)`);
assert.deepEqual(state.sent.map(({ org, thread }) => `${org}:${thread}`), [`beta:${T.b1}`, `alpha:${T.a1}`]);
// Live updates: a refresh shows the sent message in its own pane only.
await b.evaluate('window.MosaicAssistant.refresh()');
await wait(`/rotate the beta key/.test(${PANE(`beta:${T.b1}`)}.querySelector('.chat-log').innerText)`);
assert.doesNotMatch(await b.evaluate(`${PANE(`alpha:${T.a1}`)}.querySelector('.chat-log').innerText`), /rotate the beta key/);
});
test('closing a pane updates the address and leaves the others', async t => {
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1},beta:${T.b1}` });
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)}`);
await b.evaluate(`${PANE(`alpha:${T.a1}`)}.querySelector('button[data-assist-close]').click()`);
await wait(`document.querySelectorAll('[data-assist-pane]').length === 1`);
assert.equal(await b.evaluate(query), `beta:${T.b1}`);
assert.match(await b.evaluate(`${PANE(`beta:${T.b1}`)}.innerText`), /Beta tokens rotate nightly\./);
await b.evaluate(`${PANE(`beta:${T.b1}`)}.querySelector('button[data-assist-close]').click()`);
await wait(`document.querySelectorAll('[data-assist-pane]').length === 0`);
assert.equal(await b.evaluate(`location.hash`), '#/assistant');
assert.match(await b.evaluate(`document.getElementById('bus-view').innerText`), /No thread is open/);
});
test('a stopped organization is named at the top, its pane says so, and the other panes keep working', async t => {
const state = { down: new Set(['home']), sent: [], created: [] };
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1},home:${T.h1},beta:${T.b1}`, state });
await wait(`!!document.querySelector('#bus-view [data-ws-unread]') && ${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)}`);
assert.match(await b.evaluate(`document.querySelector('#bus-view [data-ws-unread]').textContent`), /Home/);
assert.doesNotMatch(await b.evaluate(`document.querySelector('#bus-view [data-ws-unread]').textContent`), /Alpha|Beta/);
await wait(`/bus is stopped/i.test(${PANE(`home:${T.h1}`)}?.querySelector('[data-assist-line]')?.textContent || '')`);
assert.equal(await b.evaluate(`${PANE(`home:${T.h1}`)}.querySelector('[data-ws-orgchip]').textContent`), 'Home');
assert.equal(await b.evaluate(`${PANE(`alpha:${T.a1}`)}.querySelector('form textarea').disabled`), false);
// Beta's bus stops while its pane is open, with an unsent message in it: that pane says so and
// only so, and holds the message; Alpha's still sends.
const betaField = `${PANE(`beta:${T.b1}`)}.querySelector('form textarea')`;
await wait(`!!${betaField} && !${betaField}.disabled`);
await b.evaluate(`(() => { const el = ${betaField}; el.value = 'beta draft'; el.dispatchEvent(new Event('input', { bubbles: true })); })()`);
state.down.add('beta');
await b.evaluate('window.MosaicAssistant.refresh()');
await wait(`/bus is stopped/i.test(${PANE(`beta:${T.b1}`)}.querySelector('[data-assist-line]')?.textContent || '') && /Beta/.test(document.querySelector('#bus-view [data-ws-unread]')?.textContent || '')`);
await wait(`!${betaField}`);
const betaBody = await b.evaluate(`${PANE(`beta:${T.b1}`)}.querySelector('.assist-body').innerText`);
assert.match(betaBody, /Nothing is read for this thread while Beta's bus is stopped\. Your unsent message is kept/);
assert.doesNotMatch(betaBody, /Refresh to try again|Read again|Conversation unavailable/, 'no line that says a refresh would help');
assert.equal(await b.evaluate('window.MosaicAssistant.hasDraft()'), true, 'the held message counts as a draft');
const field = `${PANE(`alpha:${T.a1}`)}.querySelector('form textarea')`;
assert.equal(await b.evaluate(`${field}.disabled`), false);
await b.evaluate(`(() => { const el = ${field}; el.value = 'still here'; el.dispatchEvent(new Event('input', { bubbles: true })); el.form.requestSubmit(); })()`);
await wait(`${SENT}.test(${PANE(`alpha:${T.a1}`)}.innerText)`);
assert.deepEqual(state.sent.map(({ org, body }) => `${org}:${body}`), ['alpha:still here']);
// The picker names the stopped organizations and offers none of their threads.
assert.match(await b.evaluate(`[...document.querySelectorAll('[data-assist-open] optgroup')].map(g => g.label).join('|')`), /Home · bus stopped/);
// Beta's bus starts again: its pane reads again and the held message is back in its composer.
state.down.delete('beta');
await b.evaluate('window.MosaicAssistant.refresh()');
await wait(`${ready(`beta:${T.b1}`)} && ${betaField}?.value === 'beta draft'`);
assert.deepEqual(state.sent.map(({ org, body }) => `${org}:${body}`), ['alpha:still here'], 'the held message is not sent by itself');
});
test('a pane whose organization leaves the list keeps its unsent message and does not promise it comes back', async t => {
const state = { down: new Set(['home']), gone: new Set(), sent: [], created: [] };
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1},beta:${T.b1}`, state });
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)}`);
const betaField = `${PANE(`beta:${T.b1}`)}.querySelector('form textarea')`;
await wait(`!!${betaField} && !${betaField}.disabled`);
await b.evaluate(`(() => { const el = ${betaField}; el.value = 'beta draft'; el.dispatchEvent(new Event('input', { bubbles: true })); })()`);
state.gone.add('beta');
await b.evaluate('window.MosaicAssistant.refresh()');
await wait(`/not on your organization list/.test(${PANE(`beta:${T.b1}`)}.querySelector('[data-assist-line]')?.textContent || '') && !${betaField}`);
const body = await b.evaluate(`${PANE(`beta:${T.b1}`)}.querySelector('.assist-body').innerText`);
assert.match(body, /Your unsent message is kept while this pane stays open\./);
assert.doesNotMatch(body, /comes back/, 'no promise that an organization off the list reads again');
assert.equal(await b.evaluate('window.MosaicAssistant.hasDraft()'), true);
assert.deepEqual(state.sent, []);
});
test('an open pane shows a new reply on its own, with no refresh', async t => {
const state = { down: new Set(['home']), sent: [], created: [], replies: [] };
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1},beta:${T.b1}`, state });
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)}`);
state.replies.push({ org: 'beta', thread: T.b1, body: 'Rotation finished.' });
// The page polls every 10 s; wait up to 15 s without calling refresh.
await wait(`/Rotation finished\./.test(${PANE(`beta:${T.b1}`)}.querySelector('.chat-log').innerText)`, 500);
assert.doesNotMatch(await b.evaluate(`${PANE(`alpha:${T.a1}`)}.querySelector('.chat-log').innerText`), /Rotation finished/);
});
test('the old Side by side address lands on the Assistant page', async t => {
const { b, wait } = await open(t, { hash: '#/orgs/alpha/side-by-side?a=alpha/organization&b=beta/organization&w=50&show=a' });
await wait(`location.hash === '#/assistant' && document.querySelector('#bus-view h1')?.textContent === 'Assistant'`);
assert.equal(await b.evaluate(`!!window.MosaicPanes`), false, 'the Side by side module is gone');
await b.evaluate(`location.hash = '#/side-by-side'`);
await wait(`location.hash === '#/assistant'`);
// The old per-organization Assistant address, the messages page, still opens.
await b.evaluate(`location.hash = '#/orgs/alpha/messages'`);
await wait(`document.querySelector('#bus-view h1')?.textContent === 'Messages'`);
});
test('at 390 one pane shows at a time with a tab strip to switch', async t => {
const { b, base, wait } = await open(t, { width: 390, height: 844, hash: `#/assistant?open=alpha:${T.a1},beta:${T.b1}` });
await wait(`${ready(`alpha:${T.a1}`)} && document.querySelectorAll('[data-assist-tabs] [data-assist-show]').length === 2`);
assert.deepEqual(await b.evaluate(shown), [`alpha:${T.a1}`]);
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-assist-tabs] [data-assist-show]')].map(x => [x.textContent.trim(), x.getAttribute('aria-pressed')])`), [['Launch email', 'true'], ['Gateway auth', 'false']]);
await b.evaluate(`document.querySelector('[data-assist-tabs] [data-assist-show="beta:${T.b1}"]').click()`);
await wait(`${ready(`beta:${T.b1}`)}`);
assert.deepEqual(await b.evaluate(shown), [`beta:${T.b1}`]);
assert.equal(await b.evaluate(`new URLSearchParams(location.hash.split('?')[1]).get('show')`), `beta:${T.b1}`);
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= innerWidth'), true, 'no horizontal page scroll'); // A pasted address names the shown pane however its id is cased.
await b.navigate('about:blank');
await b.navigate(base + `#/assistant?open=alpha:${T.a1},beta:${T.b1}&show=beta:${T.b1.toUpperCase()}`);
await wait(`${ready(`beta:${T.b1}`)}`);
assert.deepEqual(await b.evaluate(shown), [`beta:${T.b1}`]);
});
test('"Open thread" starts a new thread in a chosen organization through that organization\'s own route', async t => {
const state = { down: new Set(['home']), sent: [], created: [] };
const { b, wait } = await open(t, { hash: '#/assistant', state });
await wait(`!!document.querySelector('[data-assist-open] option[value="new:beta"]')`);
await pick(b, 'new:beta');
await wait(`!!document.querySelector('[data-assist-new] select[name=project] option[value="${P.beta}"]') && !!document.querySelector('[data-assist-new] select[name=instance] option[value=assistant]')`);
await b.evaluate(`(() => { const f = document.querySelector('[data-assist-new]'); f.elements.name.value = 'Rate limits'; f.requestSubmit(); })()`);
await wait(`${ready(`beta:${NEW}`)} || !!${PANE(`beta:${NEW}`)}?.querySelector('form textarea')`);
assert.deepEqual(state.created.map(({ org, project, name, instance }) => ({ org, project, name, instance })), [{ org: 'beta', project: P.beta, name: 'Rate limits', instance: 'assistant' }]);
assert.equal(await b.evaluate(query), `beta:${NEW}`);
});
// SP7: a thread link anywhere opens that thread as a pane here; a typed per-organization address
// still opens that organization's own chat view.
const follow = (b, href) => b.evaluate(`(() => { const a = document.createElement('a'); a.href = ${JSON.stringify(href)}; a.textContent = 'thread'; document.body.append(a); a.click(); a.remove(); })()`);
const type = (b, sel, text) => b.evaluate(`(() => { const el = ${PANE(sel)}.querySelector('form textarea'); el.value = ${JSON.stringify(text)}; el.dispatchEvent(new Event('input', { bubbles: true })); })()`);
const field = sel => `${PANE(sel)}?.querySelector('form textarea')`;
test('SP7: a thread link on a project page opens the thread as a pane on the Assistant page, added to the open set', async t => {
const { b, wait } = await open(t, { hash: `#/assistant?open=beta:${T.b1}` });
await wait(ready(`beta:${T.b1}`));
await b.evaluate(`location.hash = '#/orgs/alpha/projects/${P.alpha}'`);
await wait(`!!document.querySelector('#bus-view a[href$="/threads/${T.a1}"]')`);
await b.evaluate(`document.querySelector('#bus-view a[href$="/threads/${T.a1}"]').click()`);
await wait(`location.hash.startsWith('#/assistant') && ${ready(`alpha:${T.a1}`)}`);
assert.deepEqual(await b.evaluate(panes), [`beta:${T.b1}`, `alpha:${T.a1}`]);
assert.equal(await b.evaluate(query), `beta:${T.b1},alpha:${T.a1}`);
// A per-organization chat address typed or pasted still opens that organization's chat view.
await b.evaluate(`location.hash = '#/orgs/beta/projects/threads/${T.b1}'`);
await wait(`!document.querySelector('[data-assistant]') && /Beta tokens rotate nightly/.test(document.getElementById('bus-view').innerText)`);
assert.equal(await b.evaluate('location.hash'), `#/orgs/beta/projects/threads/${T.b1}`);
});
test('SP7: with three open, a fourth thread replaces the first pane with no unsent message; when all three hold one, nothing is replaced and the page says why', async t => {
const state = { down: new Set(), sent: [], created: [] };
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1},beta:${T.b1}`, state });
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)} && !${field(`alpha:${T.a1}`)}.disabled`);
await type(b, `alpha:${T.a1}`, 'alpha draft');
// On the Assistant page a thread link adds a pane in place: the typed message stays.
await follow(b, `#/orgs/alpha/projects/threads/${T.a2}`);
await wait(ready(`alpha:${T.a2}`));
assert.deepEqual(await b.evaluate(panes), [`alpha:${T.a1}`, `beta:${T.b1}`, `alpha:${T.a2}`]);
assert.equal(await b.evaluate(`${field(`alpha:${T.a1}`)}.value`), 'alpha draft');
// A fourth: Alpha's first pane holds a message, so Beta's pane, the first without one, gives way.
await follow(b, `#/orgs/home/projects/threads/${T.h1}`);
await wait(ready(`home:${T.h1}`));
assert.deepEqual(await b.evaluate(panes), [`alpha:${T.a1}`, `home:${T.h1}`, `alpha:${T.a2}`]);
assert.equal(await b.evaluate(query), `alpha:${T.a1},home:${T.h1},alpha:${T.a2}`);
assert.equal(await b.evaluate(`${field(`alpha:${T.a1}`)}.value`), 'alpha draft');
// All three hold a message: nothing is replaced and the page says why.
await wait(`!${field(`home:${T.h1}`)}.disabled && !${field(`alpha:${T.a2}`)}.disabled`);
await type(b, `home:${T.h1}`, 'home draft');
await type(b, `alpha:${T.a2}`, 'kickoff draft');
await follow(b, `#/orgs/beta/projects/threads/${T.b1}`);
await wait(`/not opened/.test(document.querySelector('[data-assist-note]').textContent)`);
assert.match(await b.evaluate(`document.querySelector('[data-assist-note]').textContent`), /all 3 panes hold an unsent message/);
assert.equal(await b.evaluate(`document.querySelector('[data-assist-note]').hasAttribute('data-refused')`), true);
assert.deepEqual(await b.evaluate(panes), [`alpha:${T.a1}`, `home:${T.h1}`, `alpha:${T.a2}`]);
assert.deepEqual(await b.evaluate(`[${field(`alpha:${T.a1}`)}.value, ${field(`home:${T.h1}`)}.value, ${field(`alpha:${T.a2}`)}.value]`), ['alpha draft', 'home draft', 'kickoff draft']);
assert.equal(await b.evaluate(query), `alpha:${T.a1},home:${T.h1},alpha:${T.a2}`);
// Closing a pane clears the reason; the thread then opens.
await b.evaluate(`${PANE(`home:${T.h1}`)}.querySelector('button[data-assist-close]').click()`);
await wait(`!/not opened/.test(document.querySelector('[data-assist-note]').textContent)`);
assert.equal(await b.evaluate(`document.querySelector('[data-assist-note]').hasAttribute('data-refused')`), false);
await follow(b, `#/orgs/beta/projects/threads/${T.b1}`);
await wait(ready(`beta:${T.b1}`));
assert.deepEqual(await b.evaluate(panes), [`alpha:${T.a1}`, `alpha:${T.a2}`, `beta:${T.b1}`]);
assert.deepEqual(state.sent, []);
});
test('SP7: each pane names its own organization\'s Messages page, and the bar no longer names the organization opened last', async t => {
const { b, wait } = await open(t, { hash: '#/orgs/beta/tasks' });
await wait(`window.MosaicOrg?.id === 'beta'`);
await b.evaluate(`location.hash = '#/assistant?open=alpha:${T.a1},beta:${T.b1}'`);
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)}`);
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-assist-pane]')].map(p => { const a = p.querySelector('.assist-pane-h a[data-assist-pane-messages]'); return a && [a.getAttribute('href'), a.getAttribute('aria-label'), a.textContent.trim()]; })`),
[['#/orgs/alpha/messages', 'Messages in Alpha', 'Messages'], ['#/orgs/beta/messages', 'Messages in Beta', 'Messages']]);
assert.doesNotMatch(await b.evaluate(`document.querySelector('.assist-bar').innerText`), /Messages/);
});
// SP7 review: a pane has no Request details, sessions or sharing, so each pane links its thread's full
// view, and a link marked data-full-view is not turned into a pane.
test('SP7: each pane links its thread\'s full view, and one plain click reaches it', async t => {
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1},beta:${T.b1}` });
await wait(`${ready(`alpha:${T.a1}`)} && ${ready(`beta:${T.b1}`)}`);
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-assist-pane]')].map(p => { const a = p.querySelector('.assist-pane-h a[data-assist-pane-full]'); return a && [a.getAttribute('href'), a.textContent.trim(), a.hasAttribute('data-full-view')]; })`),
[[`#/orgs/alpha/projects/threads/${T.a1}`, 'Full view', true], [`#/orgs/beta/projects/threads/${T.b1}`, 'Full view', true]]);
// Each pane's Full view names its thread and organization, so a screen reader can tell three apart.
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-assist-pane-full]')].map(a => a.getAttribute('aria-label'))`),
['Full view of Launch email, Alpha', 'Full view of Gateway auth, Beta']);
await b.evaluate(`${PANE(`beta:${T.b1}`)}.querySelector('a[data-assist-pane-full]').click()`);
await wait(`!document.querySelector('[data-assistant]') && /Beta tokens rotate nightly/.test(document.getElementById('bus-view').innerText)`);
assert.equal(await b.evaluate('location.hash'), `#/orgs/beta/projects/threads/${T.b1}`);
});
test('SP7: a link marked as the full view stays in the organization\'s own view, from any page', async t => {
const { b, wait } = await open(t, { hash: `#/assistant?open=alpha:${T.a1}` });
await wait(ready(`alpha:${T.a1}`));
// On the Assistant page itself: no pane is added, the browser follows the link.
await b.evaluate(`(() => { const a = document.createElement('a'); a.href = '#/orgs/beta/projects/threads/${T.b1}'; a.setAttribute('data-full-view', ''); a.textContent = 'thread'; document.body.append(a); a.click(); a.remove(); })()`);
await wait(`location.hash === '#/orgs/beta/projects/threads/${T.b1}'`);
await wait(`!document.querySelector('[data-assistant]') && /Beta tokens rotate nightly/.test(document.getElementById('bus-view').innerText)`);
// From another page: the same.
await b.evaluate(`(() => { const a = document.createElement('a'); a.href = '#/orgs/alpha/projects/threads/${T.a1}'; a.setAttribute('data-full-view', ''); a.textContent = 'thread'; document.body.append(a); a.click(); a.remove(); })()`);
await wait(`location.hash === '#/orgs/alpha/projects/threads/${T.a1}' && !document.querySelector('[data-assistant]')`);
});
// SP7 review shots: the title and the pane's tools (Full view, Messages, close) share the header's
// first row, the organization and project chips sit under it, and nothing spills out of the pane.
const headerRows = `[...document.querySelectorAll('[data-assist-pane]')].map(p => {
const h = p.querySelector('.assist-pane-h').getBoundingClientRect();
const r = s => p.querySelector(s).getBoundingClientRect();
const mid = q => Math.round(q.top + q.height / 2);
const row = ['[data-assist-title]', '[data-assist-pane-full]', '[data-assist-pane-messages]', '[data-assist-close]'].map(s => mid(r(s)));
const inside = [...p.querySelectorAll('.assist-pane-h > *, .assist-pane-h a, .assist-pane-h button')].every(e => { const q = e.getBoundingClientRect(); return q.left >= h.left - 1 && q.right <= h.right + 1; });
return { oneRow: Math.max(...row) - Math.min(...row) <= 4, chipsBelow: r('[data-assist-chips]').top >= r('[data-assist-title]').bottom - 1, inside };
})`;
// At 800 three panes are too narrow for one row: the tools wrap, and none of them leaves the pane.
const THREE = [`alpha:${T.a1}`, `alpha:${T.a2}`, `beta:${T.b1}`];
for (const [width, height, keys, oneRow] of [[1440, 900, THREE, true], [800, 900, THREE, null], [761, 900, THREE, null], [390, 844, [`beta:${T.b1}`], true]]) {
test(`SP7: a pane header keeps its tools inside the pane${oneRow ? ', title and tools on one row with the chips below' : ''}, at ${width}`, async t => {
const { b, wait } = await open(t, { width, height, hash: `#/assistant?open=${keys.join(',')}` });
await wait(keys.map(k => ready(k)).join(' && '));
await wait(`[...document.querySelectorAll('[data-assist-pane] [data-ws-orgchip]')].length === ${keys.length}`);
const rows = await b.evaluate(headerRows);
assert.deepEqual(rows.map(r => (oneRow ? r : { ...r, oneRow: null })), keys.map(() => ({ oneRow, chipsBelow: true, inside: true })));
});
}
+2 -2
View File
@@ -18,8 +18,8 @@ test('served Console browser: real board fixtures, keyboard, drafts, receipts, t
assert.equal(await b.evaluate('document.querySelector("#session-count").textContent'), '3 of 4');
await b.evaluate('document.querySelector("#hide-offline").click()');
assert.equal(await b.evaluate('document.querySelectorAll("table.sessions tbody tr").length'), 4);
// Rows 129, 154, 191, 194 and 294: chat.js, editor.js, processing.js, agents.js and federation.js are the scripts added, and #1839 adds requests.js (the intake panel under an owner's chat message), all same origin; the list is the pin, so another script is a visible change. #797 adds project-archive.js immediately after chat.js. F2 adds onboarding.js after org-create.js, and F3 adds console-restart.js after it. U2 (#1873) adds workspace-data.js and workspace.js before console-restart.js, and U4b adds tasks-board.js after workspace.js. U5 (#1873) adds panes.js (Side by side) just before bus.js, which mounts it.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("script")].map(s => s.getAttribute("src"))'), ['/editor.js', '/processing.js', '/org-create.js', '/onboarding.js', '/workspace-data.js', '/workspace.js', '/tasks-board.js', '/console-restart.js', '/display.js', '/inbox.js', '/files.js', '/project-remote.js', '/autonomy.js', '/packs.js', '/workflows.js', '/federation.js', '/brand.js', '/app.js', '/markdown-preview.js', '/projects.js', '/chat.js', '/project-archive.js', '/agents.js', '/panes.js', '/bus.js', '/requests.js']);
// Rows 129, 154, 191, 194 and 294: chat.js, editor.js, processing.js, agents.js and federation.js are the scripts added, and #1839 adds requests.js (the intake panel under an owner's chat message), all same origin; the list is the pin, so another script is a visible change. #797 adds project-archive.js immediately after chat.js. F2 adds onboarding.js after org-create.js, and F3 adds console-restart.js after it. U2 (#1873) adds workspace-data.js and workspace.js before console-restart.js, and U4b adds tasks-board.js after workspace.js. U5 (#1873) added panes.js (Side by side) just before bus.js; SP6 replaces it with assistant.js (the Assistant page), which bus.js mounts.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("script")].map(s => s.getAttribute("src"))'), ['/editor.js', '/processing.js', '/org-create.js', '/onboarding.js', '/workspace-data.js', '/workspace.js', '/tasks-board.js', '/console-restart.js', '/display.js', '/inbox.js', '/files.js', '/project-remote.js', '/autonomy.js', '/packs.js', '/workflows.js', '/federation.js', '/brand.js', '/app.js', '/markdown-preview.js', '/projects.js', '/chat.js', '/project-archive.js', '/agents.js', '/assistant.js', '/bus.js', '/requests.js']);
assert.equal(await b.evaluate(`document.querySelectorAll('script[src="/processing.js"]').length`), 1);
assert.equal(await b.evaluate(`document.querySelectorAll('script[src="/chat.js"]').length`), 1);
assert.equal(await b.evaluate('!!window.injected'), false);
@@ -60,7 +60,9 @@ const org = {
bus: { instances: async () => ({ instances: {} }), agents: async () => [], 'thread.claims': async () => [], tasks: async () => [], inbox: async () => [], messages: async () => ({ messages: [] }) },
chat: { projects: async () => [], threads: async () => [] },
};
for (const [width, route, where] of [[1440, 'orgs/acme/organization', 'the organization page'], [390, 'orgs/acme/organization', 'the organization page'], [1440, 'orgs/acme/side-by-side?a=acme/organization&b=acme/agents', 'a pane'], [390, 'orgs/acme/side-by-side?a=acme/agents&b=acme/organization&show=b', 'a pane']]) {
// SP6 (#1873) removed Side by side, whose panes also held the organization page; the Assistant
// page's panes hold chat threads only, so the organization page itself is the case left.
for (const [width, route, where] of [[1440, 'orgs/acme/organization', 'the organization page'], [390, 'orgs/acme/organization', 'the organization page']]) {
test(`E2E6 P2-13: Restart bus and Stop bus line up on ${where} at ${width}`, { timeout: 60000 }, async t => {
const server = await startServer({ port: 0, sso: createDevOwner(), send: async () => ({}), log: () => {}, organizations: { list: async () => [{ id: 'acme', label: 'Acme', busHealthy: true }], resolve: async () => org } });
t.after(() => close(server));
@@ -81,7 +81,8 @@ test('archive does not announce success for an unexpected response', { timeout:
test('archiving the current organization switches to the remaining one', { timeout: 45000 }, async t => {
const f = await fixture(t); await f.open('alpha');
await f.b.evaluate(`document.querySelector('#org-archive-open').click();document.querySelector('#org-archive-final').click()`);
await f.wait(`window.MosaicOrg?.id === 'beta' && document.querySelector('header')?.textContent.includes('beta')`);
// #1873 SP1: the breadcrumb, not the header, names the open organization.
await f.wait(`window.MosaicOrg?.id === 'beta' && /beta/i.test(document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent ?? '')`);
assert.equal((await registry.listOrgs(f.ctx)).find(e => e.id === 'alpha').state, 'archived');
});
@@ -188,6 +189,8 @@ test('fresh archived organization page offers owner restore while writes stay re
const f = await fixture(t); await f.open('beta');
await f.b.evaluate(`document.querySelector('#org-archive-open').click();document.querySelector('#org-archive-final').click()`);
await f.wait(`!document.querySelector('#org-archived').hidden`);
// #1873 SP1: another organization's address no longer reloads the page, so a fresh page is loaded on purpose.
await f.b.navigate('about:blank');
await f.b.navigate(`http://127.0.0.1:${f.port}/#/orgs/beta/settings/organizations?org=beta`);
await f.wait(`document.querySelector('#org-archived') && !document.querySelector('#org-archived').hidden`);
assert.equal(await f.b.evaluate(`document.querySelector('#org-restore').disabled`), false);
@@ -200,6 +203,16 @@ test('fresh archived organization page offers owner restore while writes stay re
assert.equal((await registry.listOrgs(f.ctx)).find(e => e.id === 'beta').state, 'active');
});
// #1873 SP1: opening the archived organization's page in place (no reload) shows its restore command.
test('an archived organization opened in place shows its restore command', { timeout: 45000 }, async t => {
const f = await fixture(t); await f.open('beta');
await f.b.evaluate(`document.querySelector('#org-archive-open').click();document.querySelector('#org-archive-final').click()`);
await f.wait(`!document.querySelector('#org-archived').hidden`);
await f.b.evaluate(`window.__sameDocument = true; location.hash = '#/orgs/beta/settings/organizations?org=beta'`);
await f.wait(`window.MosaicOrg?.id === 'beta' && /mosaic org restore beta --if-revision \\d+/.test(document.querySelector('#org-archived')?.innerText ?? '')`);
assert.equal(await f.b.evaluate(`window.__sameDocument`), true);
});
test('owner can start a down bus after setup recorded done and sees recovery guidance on refusal', { timeout: 45000 }, async t => {
const f = await fixture(t);
await f.b.evaluate(`(()=>{const old=window.fetch;window.fetch=async (input,init={})=>{const u=String(input);if(u.endsWith('/setup') && (!init.method || init.method==='GET'))return new Response(JSON.stringify({notifications:{state:'done'},queue:{state:'done'},projects:[],bus:{state:'done',verb:'mosaic bus start alpha'}}),{status:200});if(u.endsWith('/setup/bus') && init.method==='POST')return new Response(JSON.stringify({error:'stale-lock',message:'stale bus host lock'}),{status:409});return old(input,init)}})()`);
@@ -233,6 +246,8 @@ for (const capability of [{ user:true, orgSetup:false }, { tester:true, orgSetup
await f.b.evaluate(`document.querySelector('#org-archive-open').click();document.querySelector('#org-archive-final').click()`);
await f.wait(`!document.querySelector('#org-archived').hidden`);
await f.b.call('Page.addScriptToEvaluateOnNewDocument', {source:`{const old=window.fetch;window.fetch=(input,init)=>input instanceof URL && input.pathname==='/api/config'?Promise.resolve(new Response(JSON.stringify(${JSON.stringify(capability)}),{status:200})):old(input,init)}`});
// #1873 SP1: the stub applies to a new document; another organization's address alone no longer reloads.
await f.b.navigate('about:blank');
await f.b.navigate(`http://127.0.0.1:${f.port}/#/orgs/beta/settings/organizations?org=beta`);
await f.wait(`document.querySelector('#org-archived') && !document.querySelector('#org-archived').hidden`);
assert.equal(await f.b.evaluate(`document.querySelector('#org-restore').disabled`),true);
@@ -78,8 +78,9 @@ test('deleting the current organization switches the Console to a remaining orga
await b.evaluate(`document.querySelector('#org-open-form button').click()`);
await wait(`document.querySelector('#org-delete') && !document.querySelector('#org-delete').hidden`);
await b.evaluate(`document.querySelector('#org-delete-open').click();document.querySelector('#org-delete-continue').click();const i=document.querySelector('#org-delete-confirm');i.value='alpha';i.dispatchEvent(new Event('input',{bubbles:true}));document.querySelector('#org-delete-final').click()`);
// #1873 SP1: the breadcrumb, not the header, names the open organization.
let switched = false;
for (let i = 0; i < 300 && !switched; i++) { try { switched = await b.evaluate(`window.MosaicOrg?.id === 'beta' && document.querySelector('header')?.textContent.includes('beta')`); } catch {} if (!switched) await new Promise(r => setTimeout(r, 30)); }
for (let i = 0; i < 300 && !switched; i++) { try { switched = await b.evaluate(`window.MosaicOrg?.id === 'beta' && (document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent ?? '').includes('beta')`); } catch {} if (!switched) await new Promise(r => setTimeout(r, 30)); }
assert.equal(switched, true); assert.deepEqual((await registry.listOrgs(ctx)).map(e => e.id), ['beta']);
});
@@ -1,5 +1,6 @@
// On a selected org's page, the header shows why the org list failed or which org is broken,
// and Retry re-reads the list and clears the banner once it recovers (polish review F3, P19 #868).
// #1873 SP1: the breadcrumb names the open organization; the header no longer does.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as fs from 'node:fs/promises';
@@ -35,9 +36,9 @@ test('a registry error shows on a selected org page and Retry recovers', async t
await wait(f.b, `(${bannerText}).includes('Organization registry could not be read') && document.querySelector('#held [data-retry]')`);
const before = f.requests(); await fs.writeFile(file, original);
await f.b.evaluate("document.querySelector('#held [data-retry]').click()");
await wait(f.b, "!!document.querySelector('#current-organization') && !document.getElementById('org-list-banner')");
await wait(f.b, "!!document.querySelector('#breadcrumbs [data-crumb-org]') && !document.getElementById('org-list-banner')");
assert.ok(f.requests() > before, 'Retry re-read the organization list');
assert.equal(await f.b.evaluate("document.querySelectorAll('#current-organization').length"), 1);
assert.equal(await f.b.evaluate("document.querySelectorAll('#breadcrumbs [data-crumb-org]').length"), 1);
});
test('a broken org banner is replaced, not stacked, and clears after repair', async t => {
@@ -52,5 +53,5 @@ test('a broken org banner is replaced, not stacked, and clears after repair', as
await fs.writeFile(file, original);
await f.b.evaluate("document.querySelector('#held [data-retry]').click()");
await wait(f.b, "!document.getElementById('org-list-banner')");
assert.equal(await f.b.evaluate("document.querySelectorAll('#current-organization').length"), 1);
assert.equal(await f.b.evaluate("document.querySelectorAll('#breadcrumbs [data-crumb-org]').length"), 1);
});
@@ -92,7 +92,8 @@ test('creating another organization opens its setup, receipt, header and theme',
assert.ok(switched, 'new organization setup loaded after the switch');
await b.evaluate('window.MosaicAppearance.ready');
assert.match(await b.evaluate('location.hash'), /^#\/orgs\/beta\/settings\/organizations\?org=beta&step=setup/);
assert.match(await b.evaluate('document.querySelector("header").textContent'), /beta/);
// SP1: the shell no longer names the organization in its header; the breadcrumb does.
assert.match(await b.evaluate('document.querySelector("#breadcrumbs [data-crumb-org]").textContent'), /beta/);
assert.equal(await b.evaluate('document.documentElement.dataset.palette'), 'cobalt');
assert.match(await b.evaluate('document.querySelector("#org-receipt").textContent'), /Organization created.*beta/s);
});
@@ -142,18 +143,28 @@ test('sidebar lists organizations and navigating changes the route and header',
await b.viewport(390, 900);
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/alpha/settings/business`);
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelectorAll('[data-workspace-org]').length===2 && document.querySelector('#settings-page-title'))return;await new Promise(r=>setTimeout(r,30))}throw Error('Organizations did not appear')})()`);
assert.match(await b.evaluate(`document.querySelector('header').textContent`), /Alpha/);
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent==='Alpha')return;await new Promise(r=>setTimeout(r,30))}throw Error('organization crumb missing')})()`);
assert.equal(await b.evaluate(`document.querySelector('#current-organization')`), null, 'the header does not name an organization');
assert.equal(await b.evaluate(`document.querySelector('#settings-page-title').textContent`), 'Organization');
await b.evaluate('window.__sameDocument = true');
assert.equal(await b.evaluate(`!!document.querySelector('#org-picker')`), false);
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-workspace-org]')].map(o=>o.dataset.workspaceOrg)`), ['alpha', 'beta']);
await b.evaluate(`document.querySelector('[data-workspace-org=beta] a').click()`);
let switched = false;
for (let i = 0; i < 150 && !switched; i++) {
try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('header')?.textContent.includes('Beta')`); } catch { /* reload replaced the page */ }
// The sidebar opens the organization's own page: its breadcrumb is Dashboard / Beta.
try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('#breadcrumbs')?.textContent === 'Dashboard/Beta'`); } catch { /* not ready */ }
if (!switched) await new Promise(r => setTimeout(r, 30));
}
assert.equal(switched, true, 'switch completed after reload');
assert.match(await b.evaluate(`document.querySelector('body').textContent`), /Bus unavailable/);
assert.equal(switched, true, 'switch completed in place');
assert.equal(await b.evaluate('window.__sameDocument'), true, 'the switch did not reload the page');
// #1873 SP2: the organization's own page says the bus is down once, in its own banner; the shell's banner gives way there.
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('[data-org-down]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('down banner missing')})()`);
await new Promise(r => setTimeout(r, 400));
assert.equal(await b.evaluate(`document.querySelector('#bus-down').hidden`), true, 'the organization page shows one bus banner');
// On the organization's other pages the shell's banner still says it, and stays after the boot-status read.
await b.evaluate(`location.hash = '#/orgs/beta/tasks'`);
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(!document.querySelector('#bus-down').hidden)return;await new Promise(r=>setTimeout(r,30))}throw Error('offline banner missing')})()`);
await new Promise(r => setTimeout(r, 400));
assert.equal(await b.evaluate(`document.querySelector('#bus-down').hidden`), false, 'offline banner remains visible after the boot-status read');
assert.match(await b.evaluate(`document.querySelector('#bus-down').textContent`), /Bus unavailable/);
@@ -193,7 +204,7 @@ test('a chat draft is kept on Stay and discarded on an organization switch', asy
await b.evaluate(`document.querySelector('[data-discard]').click()`).catch(() => {});
let switched = false;
for (let i = 0; i < 150 && !switched; i++) {
try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('header')?.textContent.includes('Beta')`); } catch {}
try { switched = await b.evaluate(`location.hash.startsWith('#/orgs/beta/') && document.querySelector('#breadcrumbs [data-crumb-org]')?.textContent === 'Beta'`); } catch {}
if (!switched) await new Promise(r => setTimeout(r, 30));
}
assert.equal(switched, true);
@@ -212,15 +223,9 @@ test('organization switch isolates browser board preferences', async t => {
await b.navigate(base + '#/orgs/alpha/');
await b.evaluate(`document.querySelector('#show-machine').click()`);
assert.equal(await b.evaluate(`document.querySelector('#show-machine').checked`), true);
// The switch reloads the page. The navigate helper's load checks can be in flight when that
// reload commits, so set the hash in the page and poll one short check at a time.
// #1873 SP1: the switch happens in place, with no reload, and beta's own board setting applies.
await b.evaluate(`location.hash = '#/orgs/beta/'`);
let loaded = false;
for (let i = 0; i < 150 && !loaded; i++) {
try { loaded = await b.evaluate(`window.MosaicOrg?.id === 'beta' && !!document.querySelector('#show-machine')`); } catch {}
if (!loaded) await new Promise(r => setTimeout(r, 30));
}
assert.equal(loaded, true, 'beta did not load');
await b.evaluate(`(async () => { for (let i = 0; i < 150; i++) { if (window.MosaicOrg?.id === 'beta' && !!document.querySelector('#show-machine')) return; await new Promise(r => setTimeout(r, 30)); } throw Error('beta did not load'); })()`);
assert.equal(await b.evaluate(`document.querySelector('#show-machine').checked`), false);
});
@@ -0,0 +1,186 @@
// Ruling 2026-11-14: "If I choose a starter pack and apply it, that is a decision!" Driven in Chromium
// against stand-in pack, instance and decision verbs: the owner's apply hires the pack's proposals, the
// pack card says how many agents it hired and lists the open proposals with their reasons, and "Hire the
// N proposed agents" runs the hire again. The Agents page shows the new cards, each naming its pack, in
// the same response cycle as the write, and Fire removes a card at once with a receipt. Each wait is
// at most three seconds, well inside the page's ten-second poll, so the write's own redraw shows them.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdir } from 'node:fs/promises';
import { join } from 'node:path';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const REV = n => String(n).repeat(64);
const waitFor = (b, expression, what, tries = 100) => b.evaluate(`(async()=>{for(let i=0;i<${tries};i++){if(${expression})return true;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(what)}+': '+document.body.innerText.slice(0,2000))})()`);
const PACKS = [{ id: 'software-team', origin: 'shipped', pack: { label: 'Software team', description: 'Roles, a board and a review workflow.', version: '1.0.0', scope: 'organization' } }];
const FROM = { id: 'software-team', origin: 'shipped', project: null }; // the bus's instances read shape (pack-hire.test.mjs)
const PREVIEW = {
pack: { id: 'software-team', version: '1.0.0', label: 'Software team', origin: 'shipped', scope: 'organization' },
project: null, revision: REV('c'),
items: [{ item: 'board', name: 'board', target: 'board', path: 'board', mark: 'add' }],
hires: [
{ name: 'coder-1', definition: 'coder', mark: 'propose', pin: null, flagged: [{ field: 'tools', value: 'bash', reasons: ['above-chief'] }], credentialLines: [{ service: 'gitea', scope: 'repo:write' }], noHire: false },
{ name: 'reviewer-1', definition: 'reviewer', mark: 'propose', pin: null, flagged: [], credentialLines: [], noHire: false },
{ name: 'scout-1', definition: 'scout', mark: 'propose', pin: null, flagged: [], credentialLines: [], noHire: false },
],
skills: { notEnabled: [] }, chief: true, plan: {}, digest: REV('d'),
};
// busy: the bus's apply committed but its hire loop did not run (hireError), and the packs read lists one line a
// member's pack hire left in the owner's inbox (fromPack), one raised some other way and one refused.
async function fixture(t, { busy = false } = {}) {
const verbs = [], decisions = [];
const hired = new Map(); // name -> its pack provenance, as the bus's instances read reports it
let applied = null, route = false, instanceReads = 0;
const instances = () => ({ chief: { definition: 'chief-of-staff', running: [] }, assistant: { definition: 'assistant', running: [], protected: true, endProtected: true }, ...Object.fromEntries([...hired].map(([n, pack]) => [n, { definition: n.split('-')[0], running: [], pack }])) });
// The bus's hire loop, stood in: with a route every open proposal is hired; without one scout-1 is refused.
const hireLoop = () => PREVIEW.hires.map(h => {
if (hired.has(h.name)) return { name: h.name, state: 'exists' };
if (!route && h.name === 'scout-1') return { name: h.name, state: 'refused', code: 'pack-hire-route-missing' };
hired.set(h.name, FROM); const decision = `d-${hired.size}`; decisions.push(decision);
return { name: h.name, state: 'hired', decision };
});
const listed = () => applied ? [{ id: 'software-team', origin: 'shipped', project: null, hired: [...hired.keys()],
open: PREVIEW.hires.filter(h => !hired.has(h.name)).map(h => ({ name: h.name, reason: `Proposed by starter pack software-team for ${h.definition} work.`,
...(!busy || h.name === 'scout-1' ? { state: 'refused', code: 'pack-hire-route-missing' } : { state: 'awaiting-owner', decision: `inbox-${h.name}`, ...(h.name === 'coder-1' ? { fromPack: true } : {}) }) })) }] : [];
const read = async (verb, args) => {
verbs.push([verb, args]);
if (verb === 'packs.console') return { packs: PACKS, applied: listed() };
if (verb === 'pack.preview.console') return PREVIEW;
if (verb === 'autonomy.get.console') return { revision: REV('e'), autonomy: {}, levels: {} };
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
};
const write = async (verb, args) => {
verbs.push([verb, args]);
if (verb === 'pack.apply.console') { applied = true; return { revision: REV('f'), added: ['board'], pack: { id: args.pack, version: '1.0.0' }, ...(busy ? { hires: [], hireError: 'organization-busy' } : { hires: hireLoop() }) }; }
if (verb === 'pack.hire.console') return { pack: args.pack, hires: hireLoop() };
throw Object.assign(new Error('not-configured'), { code: 'not-configured' });
};
const decisionWrite = async (verb, args) => {
verbs.push([verb, args]);
if (verb === 'hire.start.console' && args.op === 'fire' && hired.has(args.name)) { hired.delete(args.name); return { id: 'fire-1', op: 'resolved', choice: 'yes' }; }
throw Object.assign(new Error('invalid-request'), { code: 'invalid-request' });
};
const server = await startServer({
port: 0, sso: createDevOwner(), send: async () => ({}), log: () => {},
organizations: {
list: async () => [{ id: 'acme', label: 'Acme', busHealthy: true }],
resolve: async () => ({
busHealthy: true, decisionWrite, requestRead: read, requestWrite: read, packsWrite: write,
workflowsRead: async () => ({ revision: REV('a'), document: { workflows: {}, projects: {}, definitions: {} }, templates: [] }), send: async () => ({}),
reads: { business: async () => ({ business: { id: 'acme', projects: [], instances: [] } }), settings: async () => ({}), queue: async () => ({ rows: [] }) },
bus: { instances: async () => { instanceReads++; return { revision: REV('b'), instances: instances(), definitions: {} }; }, agents: async () => [], 'thread.claims': async () => [], tasks: async () => [], inbox: async () => [], messages: async () => ({ messages: [] }) },
chat: { projects: async () => [], threads: async () => [] },
}),
},
});
t.after(() => close(server));
const b = await browser({ machine: false, args: ['--disable-extensions'] });
t.after(() => b.close());
await b.viewport(1440, 900);
return { b, verbs, decisions, port: server.address().port, reads: () => instanceReads, setRoute: v => { route = v; } };
}
const shot = async (b, name, selector) => {
if (!process.env.MOSAIC_UX_SHOTS) return;
await mkdir(process.env.MOSAIC_UX_SHOTS, { recursive: true });
await b.evaluate(`document.querySelector(${JSON.stringify(selector)})?.scrollIntoView({block:'start'});true`);
await b.screenshot(join(process.env.MOSAIC_UX_SHOTS, `${name}.png`));
};
test('PD apply hires the proposals, the pack card counts them, Hire the N proposed agents hires the rest, Agents shows and fires them without a poll', { timeout: 90000 }, async t => {
const f = await fixture(t);
const { b, verbs } = f;
await b.navigate(`http://127.0.0.1:${f.port}/#/orgs/acme/agents`);
await waitFor(b, `document.querySelector('[data-org-agents] [data-agent-card="chief"]')`, 'agents before');
assert.equal(await b.evaluate(`document.querySelectorAll('[data-org-agents] [data-agent-card]').length`), 2);
// Fire is offered on neither the chief nor the assistant: the bus would refuse both.
assert.equal(await b.evaluate(`document.querySelectorAll('[data-org-agents] [data-agent-fire]').length`), 0);
assert.equal(await b.evaluate(`document.querySelector('[data-agent-card="chief"] [data-agent-fire]')`), null, 'the chief has no Fire');
await shot(b, 'agents-before-1440', '[data-org-agents]');
await b.navigate(`http://127.0.0.1:${f.port}/#/orgs/acme/organization`);
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
assert.equal(await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-hired]')`), null, 'nothing applied yet');
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
await waitFor(b, `document.querySelector('[data-pack-preview]')`, 'preview');
// The preview says the apply is the hire decision and that the owner's apply approves the flagged and credential lines.
assert.match(await b.evaluate(`document.querySelector('[data-pack-hire="coder-1"]').textContent`), /Hired when you apply: applying is the hire decision, and approves the flagged and credential lines below\. A credential line is approved, not bound/);
// A hire with no credential line says nothing about binding one.
assert.match(await b.evaluate(`document.querySelector('[data-pack-hire="reviewer-1"] p').textContent`), /^Hired when you apply: applying is the hire decision\.$/);
assert.doesNotMatch(await b.evaluate(`document.querySelector('[data-pack-hire="reviewer-1"]').textContent`), /flagged and credential lines/);
await shot(b, 'pack-card-before-1440', '[data-pack="software-team"]');
await b.evaluate(`document.querySelector('[data-pack-apply]').click();true`);
await waitFor(b, `/^Applied\\./.test(document.querySelector('[data-packs-status]')?.textContent??'')`, 'apply status');
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), 'Applied. Added board. Hired coder-1, reviewer-1. Not hired: scout-1, neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Routing.');
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-hired]')`, 'hired count');
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hired]').textContent`), '2 agents hired: coder-1, reviewer-1');
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-pack-open-hire]')].map(l=>[l.dataset.packOpenHire,l.dataset.packOpenState,l.textContent])`),
[['scout-1', 'refused', 'scout-1: Proposed by starter pack software-team for scout work. not hired: neither the chief of staff nor the assistant has a harness and model to give it; set them under Settings, Routing']]);
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]').textContent`), 'Hire the 1 proposed agent');
await shot(b, 'pack-card-after-1440', '[data-pack="software-team"]');
// The route is set; the card's action hires the remaining proposal, the same loop, and nothing twice.
f.setRoute(true);
await b.evaluate(`document.querySelector('[data-pack-hire-button]').click();true`);
await waitFor(b, `document.querySelector('[data-packs-status]').textContent.startsWith('Hired scout-1.')`, 'hire status');
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), 'Hired scout-1. Already hired: coder-1, reviewer-1.');
assert.deepEqual(verbs.filter(([v]) => v === 'pack.hire.console').map(([, a]) => a), [{ pack: 'software-team' }]);
await waitFor(b, `document.querySelector('[data-pack-hired]').textContent.startsWith('3 agents hired')`, 'hired count 3');
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]')`), null, 'nothing left to hire');
assert.equal(f.decisions.length, 3);
// The Agents page: three new cards, each naming its pack.
await b.navigate(`http://127.0.0.1:${f.port}/#/orgs/acme/agents`);
await waitFor(b, `document.querySelectorAll('[data-org-agents] [data-agent-card]').length===5`, 'agents after');
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-org-agents] [data-agent-card] [data-agent-pack]')].map(s=>[s.closest('[data-agent-card]').dataset.agentCard,s.textContent])`),
[['coder-1', 'from pack software-team'], ['reviewer-1', 'from pack software-team'], ['scout-1', 'from pack software-team']]);
assert.match(await b.evaluate(`document.querySelector('[data-agents-available] tr[data-agent="coder-1"]')?.textContent ?? ''`), /from pack software-team/);
assert.equal(await b.evaluate(`document.documentElement.scrollWidth<=innerWidth`), true);
await shot(b, 'agents-after-1440', '[data-org-agents]');
// Fire asks first; Cancel fires nothing.
const card = `[data-org-agents] [data-agent-card="reviewer-1"]`;
await b.evaluate(`document.querySelector('${card} [data-agent-fire]').click();true`);
await waitFor(b, `document.querySelector('${card} [data-agent-fire-no]')`, 'fire confirm');
await b.evaluate(`document.querySelector('${card} [data-agent-fire-no]').click();true`);
await waitFor(b, `document.querySelector('${card} [data-agent-fire]')`, 'kept');
assert.equal(verbs.filter(([v]) => v === 'hire.start.console').length, 0);
// Confirm: the card goes at once, the receipt names the decision, and the page reads the bus again.
await b.evaluate(`document.querySelector('${card} [data-agent-fire]').click();true`);
await waitFor(b, `document.querySelector('${card} [data-agent-fire-yes]')`, 'fire confirm again');
const before = f.reads();
await b.evaluate(`document.querySelector('${card} [data-agent-fire-yes]').click();true`);
await waitFor(b, `document.querySelector('[data-agents-receipt]')?.textContent.includes('Fired reviewer-1')`, 'fire receipt');
assert.equal(await b.evaluate(`document.querySelector('${card}')`), null);
assert.equal(await b.evaluate(`document.querySelector('[data-agents-available] tr[data-agent="reviewer-1"]')`), null);
assert.equal(await b.evaluate(`document.querySelector('[data-agents-receipt]').textContent`), 'Fired reviewer-1. Recorded decision fire-1.');
assert.deepEqual(verbs.filter(([v]) => v === 'hire.start.console').map(([, a]) => a), [{ op: 'fire', level: 'org', name: 'reviewer-1', reason: 'Fired from the Agents page.' }]);
// The redraw the fire asked for reads the instances again and keeps the receipt.
for (let i = 0; i < 100 && f.reads() <= before; i++) await new Promise(r => setTimeout(r, 30));
assert.ok(f.reads() > before, 'the fire redraws the page from a fresh read');
await waitFor(b, `document.querySelector('[data-agents-receipt]')?.textContent.includes('Fired reviewer-1')&&document.querySelectorAll('[data-org-agents] [data-agent-card]').length===4`, 'redrawn');
assert.equal(await b.evaluate(`document.querySelectorAll('[data-org-agents] [data-agent-card]').length`), 4);
assert.equal(await b.evaluate(`document.querySelector('[data-agents-receipt]').textContent`), 'Fired reviewer-1. Recorded decision fire-1.');
});
test('PD an apply whose hire loop did not run says so; the owner card counts a pack-raised inbox line as hireable and leaves the inbox its own', { timeout: 90000 }, async t => {
const f = await fixture(t, { busy: true });
const { b } = f;
await b.navigate(`http://127.0.0.1:${f.port}/#/orgs/acme/organization`);
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-preview-button]')`, 'pack list');
await b.evaluate(`document.querySelector('[data-pack="software-team"] [data-pack-preview-button]').click();true`);
await waitFor(b, `document.querySelector('[data-pack-apply]')`, 'preview');
await b.evaluate(`document.querySelector('[data-pack-apply]').click();true`);
await waitFor(b, `/^Applied\\./.test(document.querySelector('[data-packs-status]')?.textContent??'')`, 'apply status');
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), 'Applied. Added board. The hires did not run: another pack hire on this organization was running. Use Hire on the pack card to run them.');
await waitFor(b, `document.querySelector('[data-pack="software-team"] [data-pack-open]')`, 'open lines');
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-pack-open-hire]')].map(l=>[l.dataset.packOpenHire,l.dataset.packOpenState])`),
[['coder-1', 'awaiting-owner'], ['reviewer-1', 'awaiting-owner'], ['scout-1', 'refused']]);
// coder-1 was left in the inbox by a pack hire, so the owner's pack hire approves it; reviewer-1 is the inbox's.
assert.equal(await b.evaluate(`document.querySelector('[data-pack-hire-button]').textContent`), 'Hire the 2 proposed agents');
});
+79 -5
View File
@@ -25,12 +25,14 @@ import { close } from './fixture.mjs';
const FLOW = (title) => ({ description: `${title}.`, steps: [{ title, state: 'todo', roles: ['human'] }] });
const BOARD = { columns: [{ state: 'todo', label: 'Backlog' }, { state: 'in-progress', label: 'Building' }, { state: 'in-review', label: 'Review' }, { state: 'blocked', label: 'Blocked' }, { state: 'done', label: 'Merged' }], layout: 'kanban' };
async function fixture(t, { send = true, workflows = true } = {}) {
async function fixture(t, { send = true, workflows = true, route = false, tap = null } = {}) {
const undo = []; t.after(async () => { for (const step of undo.reverse()) await step(); });
const root = mkdtempSync(join(tmpdir(), 'pk-'));
const rolesDir = rolesCopy(root), system = systemFor(root);
const doc = businessDoc(root, 'demo');
doc.plugins = { ...(doc.plugins ?? {}), harness: ['pi'] };
// Ruling 2026-11-14: a hire runs as the chief's harness and model, else the assistant's (lane pr2); this fixture has no assistant, so without a chief route it refuses pack-hire-route-missing.
if (route) doc.roles.chief.vars = { harness: 'pi', model: 'claude-opus-5-5' };
const file = writeJson(join(root, 'businesses/demo.json'), doc);
mkdirSync(join(root, 'data'), { mode: 0o700 });
const business = loadBusiness('demo', { dir: root, rolesDir });
@@ -55,7 +57,9 @@ async function fixture(t, { send = true, workflows = true } = {}) {
const upstream = `http://127.0.0.1:${board.address().port}`;
const consoleCall = kind => async (verb, args, ctx) => { calls.push([kind, verb, Object.keys(args).sort()]); return new Client({ path, console: { subject: ctx.subject } }).call(verb, args); };
const requestRead = consoleCall('read');
const packsWrite = packsCaller(consoleCall('write'));
// tap: a test's view of each write's bus result before the route shapes it.
const writer = packsCaller(consoleCall('write'));
const packsWrite = tap ? async (verb, args, ctx) => tap(verb, await writer(verb, args, ctx)) : writer;
const session = { provider: 'fixture', iss: 'https://issuer.example', sub: 'owner', name: 'jason', rootOwner: true };
let active = true;
const sso = { publicOrigin: '', publicHost: '', formTargets: () => [], session: () => active ? session : null, handle: () => {}, health: () => ({}) };
@@ -69,7 +73,7 @@ async function fixture(t, { send = true, workflows = true } = {}) {
sso.publicOrigin = base; sso.publicHost = new URL(base).host;
undo.push(() => close(web));
const onDisk = () => JSON.parse(readFileSync(file, 'utf8'));
return { base, file, root, calls, onDisk, flowReads, boardHits, failFlows: () => { flowFails = true; }, signOut: () => { active = false; }, revokeOwner: () => { session.rootOwner = false; session.user = 'legacy-user'; } };
return { base, file, root, calls, onDisk, broker: runtime.broker, flowReads, boardHits, failFlows: () => { flowFails = true; }, signOut: () => { active = false; }, revokeOwner: () => { session.rootOwner = false; session.user = 'legacy-user'; } };
}
function call(f, path, method = 'GET', body, headers = {}) {
@@ -166,8 +170,8 @@ test('SP4 the admission checks refuse before any bus call; a read-only Console s
assert.deepEqual((await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'no-such-pack' })).map((x, i) => i ? x.error : x), [404, 'starter-pack-not-found']);
const [badRole, badRoleBody] = await call(f, `${ORG}/workflows/three`, 'POST', { revision: revisionNow, workflow: { description: 'x.', steps: [{ title: 'x', state: 'todo', roles: ['ghost'] }] } });
assert.deepEqual([badRole, badRoleBody.error], [400, 'invalid-request']);
// The fenced writer calls nothing but the three write verbs.
assert.deepEqual(PACK_WRITE_VERBS, ['pack.apply.console', 'board.set.console', 'workflow.set.console']);
// The fenced writer calls nothing but the four write verbs.
assert.deepEqual(PACK_WRITE_VERBS, ['pack.apply.console', 'pack.hire.console', 'board.set.console', 'workflow.set.console']);
await assert.rejects(packsCaller(async () => ({}))('packs.console', {}, {}), /does not call packs\.console/);
f.signOut();
assert.deepEqual((await call(f, `${ORG}/packs`))[0], 401);
@@ -372,3 +376,73 @@ test('SP6 the pack picker and workflow files are the owner\'s: the tester listen
assert.ok((await res.text()).length > 100, path);
}
});
// Ruling 2026-11-14: "If I choose a starter pack and apply it, that is a decision!" The owner's apply
// hires the proposals in the same act; the packs read names the agents hired and the open proposals;
// the hire route runs the same loop on the recorded entry and hires nothing twice.
test('PD the owner apply hires the proposals; the packs read lists them; the hire route hires nothing twice', async t => {
const f = await fixture(t, { route: true });
const [, preview] = await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
const [applied, receipt] = await call(f, `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: preview.digest });
assert.equal(applied, 200, JSON.stringify(receipt));
assert.deepEqual(receipt.hires.map(h => [h.name, h.state, h.routeFrom]), [['pm-1', 'hired', 'chief'], ['coder-1', 'hired', 'chief'], ['reviewer-1', 'hired', 'chief']]);
for (const h of receipt.hires) assert.match(h.decision, /^[0-9a-f-]{36}$/);
const disk = f.onDisk();
for (const h of receipt.hires) { assert.equal(disk.roles[h.name].hireDecision, h.decision); assert.ok(disk.launch.instances.includes(h.name)); }
const [, list] = await call(f, `${ORG}/packs`);
assert.deepEqual(list.applied.map(a => [a.id, a.origin, a.project, a.hired.sort(), a.open]), [['coding', 'shipped', null, ['coder-1', 'pm-1', 'reviewer-1'], []]]);
const [hired, again] = await call(f, `${ORG}/packs/hire`, 'POST', { pack: 'coding' });
assert.equal(hired, 200, JSON.stringify(again));
assert.deepEqual(again, { pack: 'coding', hires: [{ name: 'pm-1', state: 'exists' }, { name: 'coder-1', state: 'exists' }, { name: 'reviewer-1', state: 'exists' }] });
assert.deepEqual(f.calls.at(-1), ['write', 'pack.hire.console', ['pack']]);
const asked = f.calls.length;
assert.deepEqual((await call(f, `${ORG}/packs/hire`, 'POST', { pack: 'coding', as: [] })).map((x, i) => i ? x.error : x), [400, 'invalid-request']);
assert.deepEqual((await call(f, `${ORG}/packs/hire`, 'GET')).map((x, i) => i ? x.error : x), [405, 'method-not-allowed']);
assert.equal(f.calls.length, asked);
assert.deepEqual((await call(f, `${ORG}/packs/hire`, 'POST', { pack: 'research' })).map((x, i) => i ? x.error : x), [404, 'pack-not-applied']);
});
test('PD with no chief route the apply records the pack and each hire says pack-hire-route-missing', async t => {
const f = await fixture(t);
const [, preview] = await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
const [applied, receipt] = await call(f, `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: preview.digest });
assert.equal(applied, 200, JSON.stringify(receipt));
assert.deepEqual(receipt.hires.map(h => [h.name, h.state, h.code]), [['pm-1', 'refused', 'pack-hire-route-missing'], ['coder-1', 'refused', 'pack-hire-route-missing'], ['reviewer-1', 'refused', 'pack-hire-route-missing']]);
const [, list] = await call(f, `${ORG}/packs`);
assert.deepEqual(list.applied[0].hired, []);
assert.deepEqual(list.applied[0].open.map(o => [o.name, o.state, o.code, typeof o.reason]), [['pm-1', 'refused', 'pack-hire-route-missing', 'string'], ['coder-1', 'refused', 'pack-hire-route-missing', 'string'], ['reviewer-1', 'refused', 'pack-hire-route-missing', 'string']]);
});
test('PD a member-raised awaiting-owner line reads fromPack; the owner hire route approves it; an apply whose hire loop did not run says hireError', async t => {
const f = await fixture(t);
const [, preview] = await call(f, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
await call(f, `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: preview.digest });
const doc = f.onDisk();
doc.roles.chief.vars = { harness: 'pi', model: 'claude-opus-5-5' };
writeFileSync(f.file, JSON.stringify(doc, null, 2) + '\n');
// A member with org.hire runs the pack hire on the bus (no WebUI route serves a member yet).
const member = f.broker.bindHireConsole({ business: 'demo', actor: 'alice', subject: { provider: 'test', iss: 'test', sub: 'alice' }, rights: ['org.hire', 'board.read'] });
const out = await f.broker.request(member, { verb: 'pack.hire.console', args: { pack: 'coding' } });
const waiting = out.hires.filter(x => x.state === 'awaiting-owner').map(x => x.name);
assert.ok(waiting.length > 0, JSON.stringify(out));
const [, list] = await call(f, `${ORG}/packs`);
const open = list.applied[0].open.filter(o => o.state === 'awaiting-owner');
assert.deepEqual(open.map(o => [o.name, o.fromPack]), waiting.map(n => [n, true]));
const [status, hired] = await call(f, `${ORG}/packs/hire`, 'POST', { pack: 'coding' });
assert.equal(status, 200, JSON.stringify(hired));
assert.deepEqual(hired.hires.filter(x => waiting.includes(x.name)).map(x => [x.name, x.state]), waiting.map(n => [n, 'hired']));
assert.deepEqual((await call(f, `${ORG}/packs`))[1].applied[0].open, []);
// The bus answers an apply whose hire loop did not run with hireError; the route passes a code through
// and drops anything that is not one.
for (const [given, shown] of [['organization-busy', 'organization-busy'], ['Not A Code!', undefined], [7, undefined]]) {
const g = await fixture(t, { tap: (verb, result) => verb === 'pack.apply.console' ? { ...result, hires: [], hireError: given } : result });
const [, p] = await call(g, `${ORG}/packs/preview`, 'POST', { pack: 'coding' });
const [code, receipt] = await call(g, `${ORG}/packs/apply`, 'POST', { pack: 'coding', digest: p.digest });
assert.equal(code, 200, JSON.stringify(receipt));
assert.equal(receipt.hireError, shown);
assert.deepEqual(receipt.hires, []);
}
});
@@ -56,7 +56,7 @@ async function fixture(t, { send = true } = {}) {
};
const write = async (verb, args) => {
verbs.push([verb, args]);
if (verb === 'pack.apply.console') return { revision: REV('f'), added: ['board', 'definitions.reviewer'], pack: { id: args.pack, version: '1.0.0' } };
if (verb === 'pack.apply.console') return { revision: REV('f'), added: ['board', 'definitions.reviewer'], pack: { id: args.pack, version: '1.0.0' }, hires: [{ name: 'lead-reviewer', state: 'refused', code: 'definition-not-hireable' }] };
if (verb === 'workflow.set.console') {
assert.equal(args.revision, flows.revision);
const doc = structuredClone(flows.document);
@@ -118,7 +118,7 @@ test('SP6 pack picker: list, preview with marks, flagged, credential and noHire
assert.equal(verbs.filter(([v]) => v.startsWith('pack.apply')).length, 0, 'preview writes nothing');
await b.evaluate(`document.querySelector('[data-pack-apply]').click();true`);
await waitFor(b, `/^Applied\\./.test(document.querySelector('[data-packs-status]').textContent)`, 'apply status');
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), 'Applied. Added board, definitions.reviewer. Proposed hires are recorded for the chief to raise as decisions.');
assert.equal(await b.evaluate(`document.querySelector('[data-packs-status]').textContent`), 'Applied. Added board, definitions.reviewer. Not hired: lead-reviewer, its role is on the no-hire list.');
assert.deepEqual(verbs.filter(([v]) => v === 'pack.apply.console').map(([, a]) => a), [{ pack: 'software-team', digest: REV('d') }]);
assert.equal(await b.evaluate(`document.querySelector('[data-pack-preview]')`), null);
// A project pack previews against the chosen project.
@@ -165,3 +165,9 @@ test('S4 fix stale project gather cannot enrich a newer request revision', async
const x=await b.evaluate(`({revision:document.querySelector('.project-request-intro').dataset.requestRevision,prd:document.querySelector('[data-work-prd]').textContent,files:document.querySelector('[data-work-files]').textContent})`);
assert.equal(x.revision,'2');assert.doesNotMatch(x.prd,/v3|Approved/);assert.doesNotMatch(x.files,/4 draft/);
});
// SP7 review: the requirement view sends the person to the conversation's Request details, which a pane
// does not have, so both of its "Open conversation" links are marked as the full view.
test('SP7 requirement view links the conversation\'s full view, not a pane',async t=>{const {b,wait}=await setup(t,'/projects/'+P+'/requirements');await wait(`document.querySelector('[data-prd]')`);const links=await b.evaluate(`[...document.querySelectorAll('[data-project-content] a')].filter(a=>a.textContent.trim()==='Open conversation').map(a=>a.hasAttribute('data-full-view'))`);assert.deepEqual(links,[true,true]);});
// SP7 re-check: the overview's "Review decision" and its two request counts lead to a request, which only
// the conversation's full view shows, so each link that names a conversation is marked as the full view.
test('SP7 overview decision and request links go to the conversation\'s full view',async t=>{const {b,wait}=await setup(t,'/projects');await b.evaluate(`reviewStates['request-1'].wait={kind:'decision'};document.querySelector('#refresh').click();location.hash='#/projects/${P}'`);await wait(`document.querySelector('.project-decision a')`);const got=await b.evaluate(`({decision:[...document.querySelectorAll('.project-decision a')].map(a=>[a.textContent.trim(),a.hasAttribute('data-full-view'),/\\/threads\\//.test(a.getAttribute('href'))]),metrics:[...document.querySelectorAll('.project-metrics a')].map(a=>[a.querySelector('span').textContent,/\\/threads\\//.test(a.getAttribute('href')),a.hasAttribute('data-full-view')])})`);assert.deepEqual(got,{decision:[['Review decision',true,true]],metrics:[['Requests in progress',true,true],['Needs your input',true,true],['Conversations',false,false],['Files',false,false]]});});
+8 -1
View File
@@ -67,7 +67,14 @@ test('shipped strings are unchanged, and the web keeps its write boundary', () =
const writes = read('bus.js').toString().match(/fetch\([^;]*method:\s*['"](POST|PUT|PATCH|DELETE)[^;]*;/g) ?? [];
assert.deepEqual(writes, ["fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: '{}' });", "fetch(url, { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body), cache: 'no-store', redirect: 'manual' });", "fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/settings',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision,reset:[JSON.parse(path)]}),cache:'no-store',redirect:'manual'});", "fetch(url,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/instances',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:harnessSettings.revision,plugins:{harness:selected}}),cache:'no-store',redirect:'manual'});", "fetch('/api/proxy/plugins/set',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify({revision:settings.revision,plugins:{'model-provider':next}}),cache:'no-store',redirect:'manual'});", "fetch('/api/routes',{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(payload),cache:'no-store',redirect:'manual'});", "fetch('/api/project-file', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(sent), cache: 'no-store', redirect: 'manual' });", "fetch('/api/bus/message', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ to, body: text }), cache: 'no-store', redirect: 'manual' });"]);
assert.equal(read('bus.js').toString().split(/method:/).length - 1, 11);
assert.deepEqual([...read('bus.js').toString().matchAll(/decidePost\(([^,]*),/g)].map(m => m[1]), ["`/api/decisions/hire/${templatesOnly?'templates':'start'}`", 'url', '`/api/decisions/${enc(a.id)}/confirmation`', '`/api/decisions/${enc(a.id)}/resolve`']);
// Ruling 2026-11-14 (#1873): Fire on an Agents card is a second hire.start caller, {op:'fire'}.
// SP3 (#1873): an answer from the system Inbox goes to its row's organization. decideBase is
// /api/orgs/<org> for such an answer and /api otherwise, so the route is still a decision's
// confirmation or resolve, only pinned to one organization.
// SP5 (#1873): Fire from the system Agents page goes to its row's organization the same way:
// decideBase({org}) is /api/orgs/<org>, and an agent card's Fire (no org) keeps /api.
assert.deepEqual([...read('bus.js').toString().matchAll(/decidePost\(([^,]*),/g)].map(m => m[1]), ["`/api/decisions/hire/${templatesOnly?'templates':'start'}`", "`${decideBase({ org: named })}/decisions/hire/start`", 'url', '`${decideBase(a)}/decisions/${enc(a.id)}/confirmation`', '`${decideBase(a)}/decisions/${enc(a.id)}/resolve`']);
assert.deepEqual([...read('bus.js').toString().matchAll(/const decideBase = [^;]*;/g)].map(m => m[0]), ["const decideBase = a => a.org ? `/api/orgs/${enc(a.org)}` : '/api';"]);
// Row 155 (#1649): the one fetch(url, ...) posts only to these three routes, each a literal.
// Row 176 (#1674): the tester name form adds a second /api/name caller.
assert.deepEqual([...read('bus.js').toString().matchAll(/assistantPost\(([^,]*),/g)].map(m => m[1]), ['url', "'/api/settings'", "'/api/name'", "'/api/assistant-stop'", "'/api/name'"]);
@@ -1,432 +0,0 @@
// U5 (#1873, sample 07): Side by side shows two panes, each holding one page of any organization.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
// Three organizations: two running buses and one stopped (home). `state.flip` changes what the
// running organizations report, so a refresh repaints both panes.
function orgs(state = { flip: false, seen: [] }) {
const ORGS = [
{ id: 'ddigital', label: 'Distinctly Digital', theme: 'rosewood', busHealthy: true },
{ id: 'forge', label: 'Forge', theme: 'cobalt', busHealthy: true },
{ id: 'home', label: 'Home', theme: 'grove', busHealthy: false },
];
const PROJECTS = { ddigital: [{ id: 'spring-launch', name: 'Spring launch' }, { id: 'brand-refresh', name: 'Brand refresh' }], forge: [{ id: 'api-gateway', name: 'API gateway' }], home: [] };
const INSTANCES = { ddigital: ['chief', 'copywriter', 'producer', 'editor', 'researcher', 'designer', 'analyst', 'scheduler'], forge: ['chief', 'builder', 'tester', 'reviewer', 'operator', 'scribe'] };
const THREADS = { ddigital: [{ id: 't0', name: 'Kickoff notes', project: 'spring-launch', instance: 'chief' }, { id: 't1', name: 'Launch email', project: 'spring-launch', instance: 'copywriter' }], forge: [{ id: 'f0', name: 'Gateway auth', project: 'api-gateway', instance: 'chief' }] };
const instances = id => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {},
instances: Object.fromEntries(INSTANCES[id].map((n, i) => [n, { definition: n, vars: {}, launched: true, launcher: false, protected: false, kept: false, running: [`r${i}`], alive: [] }])) });
const agents = id => INSTANCES[id].map((role, i) => ({ role, holder_run: `r${i}`, state: (i % 2 === 0) === state.flip ? 'working' : 'waiting' }));
const business = id => ({ business: { id, human: 'jason', arbiters: ['chief'], projects: PROJECTS[id].map(p => p.id), vars: {}, instances: INSTANCES[id].map(n => ({ instance: n, vars: {} })), appearance: { theme: ORGS.find(o => o.id === id).theme } } });
return {
list: async () => ORGS,
resolve: async id => {
state.seen.push(id);
const org = ORGS.find(o => o.id === id); if (!org) return null;
if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, chat: { projects: async () => [], threads: async () => [] } };
return {
busHealthy: true,
reads: { business: async () => business(id), settings: async () => ({ release: '0.0.42', launch: { limits: { total: 4 } } }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
bus: { instances: async () => instances(id), messages: async () => ({ messages: [], unread: 0 }), agents: async () => agents(id), 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [] },
chat: { projects: async () => PROJECTS[id], threads: async () => THREADS[id] },
projectFiles: async () => ({ head: 'a'.repeat(40), files: [] }),
};
},
};
}
async function open(t, { width = 1440, height = 900, hash = '#/orgs/ddigital/side-by-side', state } = {}) {
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: orgs(state), log: () => {} }); t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(width, height);
const base = `http://127.0.0.1:${server.address().port}/`;
await b.navigate(base + hash);
return { b, base, wait: waitFor(b) };
}
const text = key => `(document.querySelector("#pane-${key} [data-pane-body]")?.innerText || "")`;
const title = key => `(document.querySelector("#pane-${key} [data-pane-ttl]")?.textContent || "")`;
const query = '(() => Object.fromEntries(new URLSearchParams(location.hash.split("?")[1] || "")))()';
const pick = (b, key, value) => b.evaluate(`(() => { const s = document.querySelector("#pane-${key}-pick"); s.value = ${JSON.stringify(value)}; if (s.value !== ${JSON.stringify(value)}) throw Error("no option " + ${JSON.stringify(value)}); s.dispatchEvent(new Event("change", { bubbles: true })); })()`);
test('side by side stays dark by default under light media, and applying system or light really draws light', async t => {
const { b, wait, base } = await open(t);
await wait(`${title('a')}.length > 0 && ${title('b')}.length > 0`);
await b.evaluate('window.MosaicAppearance.ready.then(() => true)');
await b.call('Emulation.setEmulatedMedia', { features: [{ name: 'prefers-color-scheme', value: 'light' }] });
const drawn = () => b.evaluate(`({ mode: document.documentElement.getAttribute('data-mode'),
palette: document.documentElement.dataset.palette, canvas: getComputedStyle(document.body).backgroundColor,
source: window.MosaicAppearance.state().modeSource })`);
assert.deepEqual(await drawn(), { mode: 'dark', palette: 'rosewood', canvas: 'rgb(26, 20, 23)', source: 'default' });
for (const mode of ['system', 'light']) {
// U5's corrected shot recipe seeds the per-org key, then loads a fresh document.
const before = await drawn();
await b.evaluate(`localStorage.setItem('mosaic-console-appearance:ddigital', JSON.stringify({ mode: ${JSON.stringify(mode)} }))`);
assert.deepEqual(await drawn(), before, 'writing storage alone does not apply an override to this document');
await b.navigate('about:blank');
await b.navigate(`${base}?appearance=${mode}#/orgs/ddigital/side-by-side`);
await wait(`${title('a')}.length > 0 && ${title('b')}.length > 0`);
await b.evaluate('window.MosaicAppearance.ready.then(() => true)');
const result = await drawn();
assert.deepEqual(result, { mode: mode === 'system' ? null : 'light', palette: 'rosewood',
canvas: 'rgb(246, 243, 245)', source: 'browser' });
t.diagnostic(JSON.stringify({ scheme: 'light', requested: mode, ...result }));
}
});
test('the Side by side nav item opens two panes with different organizations, and the URL restores both after a reload', async t => {
const state = { flip: false, seen: [] };
const { b, base, wait } = await open(t, { hash: '#/orgs/ddigital/organization', state });
await wait('document.querySelector("[data-org-dashboard]")');
await b.evaluate('[...document.querySelectorAll("#sections > li > a")].find(a => a.textContent.trim() === "Side by side").click()');
await wait(`document.querySelectorAll(".panes > .pane:not([hidden])").length === 2 && ${title('a')}.includes("Distinctly Digital") && ${title('b')}.includes("Forge")`);
assert.doesNotMatch(await b.evaluate('document.getElementById("bus-view").innerText'), /Side by side is not built yet/i);
assert.equal(await b.evaluate('document.querySelector("#bus-view h1").textContent'), 'Side by side');
assert.equal(await b.evaluate('document.title'), 'Side by side · Mosaic Console');
assert.deepEqual(await b.evaluate(query), { a: 'ddigital/organization', b: 'forge/organization', w: '50', show: 'a' });
await wait(`${text('a')}.includes("Distinctly Digital") && ${text('b')}.includes("Forge")`);
// Each pane's links name its own organization.
assert.equal(await b.evaluate('[...document.querySelectorAll("#pane-b [data-pane-body] a[href^=\\"#/\\"]")].every(a => a.getAttribute("href").startsWith("#/orgs/forge/"))'), true);
assert.equal(await b.evaluate('document.querySelectorAll("#pane-a [data-pane-body] h1[aria-level=\\"2\\"]").length > 0'), true);
// The picker lists every organization and its projects.
const groups = await b.evaluate('[...document.querySelectorAll("#pane-b-pick optgroup")].map(g => g.label)');
assert.deepEqual(groups, ['Distinctly Digital', 'Forge', 'Home · bus unavailable']);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#pane-b-pick option")].map(o => o.value).filter(Boolean)'),
['ddigital/organization', 'ddigital/agents', 'ddigital/projects/spring-launch', 'ddigital/projects/brand-refresh', 'forge/organization', 'forge/agents', 'forge/projects/api-gateway', 'home/organization', 'home/agents']);
// Pick a project in the right pane; the left keeps its page.
await pick(b, 'b', 'forge/projects/api-gateway');
await wait(`${title('b')}.startsWith("API gateway") && ${text('b')}.includes("API gateway") && location.hash.includes("b=forge/projects/api-gateway")`);
assert.match(await b.evaluate(title('a')), /^Dashboard/);
// A project tab opens in the pane, not the full view.
await b.evaluate('[...document.querySelectorAll("#pane-b nav.project-tabs a")].find(a => /Tasks/.test(a.textContent)).click()');
await wait(`location.hash.includes("b=forge/projects/api-gateway/tasks") && ${title('b')}.includes("Tasks")`);
assert.match(await b.evaluate('location.hash'), /^#\/orgs\/ddigital\/side-by-side\?/);
// Reload: both panes come back from the URL.
await b.call('Page.reload');
await wait('document.readyState === "complete"');
await wait(`${title('a')}.startsWith("Dashboard") && ${title('a')}.includes("Distinctly Digital") && ${title('b')}.includes("API gateway") && ${title('b')}.includes("Tasks")`);
assert.deepEqual(await b.evaluate(query), { a: 'ddigital/organization', b: 'forge/projects/api-gateway/tasks', w: '50', show: 'a' });
// A shared link opens exactly what it names, whatever this browser remembered.
await b.navigate(`${base}#/orgs/forge/side-by-side?a=forge/agents&b=ddigital/projects/spring-launch&w=40&show=b`);
await wait(`${title('a')}.startsWith("Agents") && ${title('a')}.includes("Forge") && ${title('b')}.startsWith("Spring launch")`);
assert.equal(await b.evaluate('document.querySelector("[data-sbs-divider]").getAttribute("aria-valuenow")'), '40');
// A link with a route a pane does not draw falls back to the remembered layout or the default.
await b.navigate(`${base}#/orgs/ddigital/side-by-side?a=ddigital/settings&b=nope!/organization`);
await wait(`document.querySelectorAll(".panes > .pane:not([hidden])").length === 2 && ${title('a')}.length > 0 && !location.hash.includes("settings")`);
// Leaving the page stops both panes reading.
await b.evaluate('location.hash = "#/orgs/ddigital/agents"');
await wait('!document.querySelector("[data-side-by-side]") && [...document.querySelectorAll("#bus-view h1")].some(h => h.textContent.trim() === "Agents")');
assert.ok(state.seen.includes('forge') && state.seen.includes('ddigital'));
});
test('the divider resizes the panes by mouse and by keyboard', async t => {
const { b, wait } = await open(t);
await wait(`${title('a')}.length > 0 && ${title('b')}.length > 0`);
const sep = '[role=separator][data-sbs-divider]';
assert.deepEqual(await b.evaluate(`(() => { const d = document.querySelector("${sep}"); return [d.getAttribute("aria-valuenow"), d.getAttribute("aria-valuemin"), d.getAttribute("aria-valuemax"), d.getAttribute("aria-orientation"), d.tabIndex]; })()`), ['50', '25', '75', 'vertical', 0]);
const ratio = `(() => { const a = document.getElementById("pane-a").getBoundingClientRect().width, b = document.getElementById("pane-b").getBoundingClientRect().width; return Math.round(a / (a + b) * 100); })()`;
// Mouse: drag the divider to 30% of the panes' width.
const box = await b.evaluate(`(() => { const p = document.querySelector("[data-sbs-panes]").getBoundingClientRect(), d = document.querySelector("${sep}").getBoundingClientRect(); return { left: p.left, width: p.width, x: d.left + d.width / 2, y: d.top + 200 }; })()`);
const target = box.left + box.width * 0.3;
await b.call('Input.dispatchMouseEvent', { type: 'mouseMoved', x: box.x, y: box.y });
await b.call('Input.dispatchMouseEvent', { type: 'mousePressed', x: box.x, y: box.y, button: 'left', buttons: 1, clickCount: 1 });
for (const step of [0.25, 0.5, 0.75, 1]) await b.call('Input.dispatchMouseEvent', { type: 'mouseMoved', x: box.x + (target - box.x) * step, y: box.y, button: 'left', buttons: 1 });
await b.call('Input.dispatchMouseEvent', { type: 'mouseReleased', x: target, y: box.y, button: 'left', buttons: 0, clickCount: 1 });
await wait(`document.querySelector("${sep}").getAttribute("aria-valuenow") === "30" && location.hash.includes("w=30")`);
assert.ok(Math.abs(await b.evaluate(ratio) - 30) <= 1);
// Keyboard: the separator has focus after the drag; arrows step by 5, Home and End reach the limits.
assert.equal(await b.evaluate('document.activeElement.getAttribute("role")'), 'separator');
await b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'ArrowRight', code: 'ArrowRight', windowsVirtualKeyCode: 39 });
await b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowRight', code: 'ArrowRight', windowsVirtualKeyCode: 39 });
await wait(`document.querySelector("${sep}").getAttribute("aria-valuenow") === "35"`);
await b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 });
await b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 });
await b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 });
await b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 });
await wait(`document.querySelector("${sep}").getAttribute("aria-valuenow") === "25"`);
await b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 });
await b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'ArrowLeft', code: 'ArrowLeft', windowsVirtualKeyCode: 37 });
assert.equal(await b.evaluate(`document.querySelector("${sep}").getAttribute("aria-valuenow")`), '25');
await b.call('Input.dispatchKeyEvent', { type: 'keyDown', key: 'End', code: 'End', windowsVirtualKeyCode: 35 });
await b.call('Input.dispatchKeyEvent', { type: 'keyUp', key: 'End', code: 'End', windowsVirtualKeyCode: 35 });
await wait(`document.querySelector("${sep}").getAttribute("aria-valuenow") === "75" && location.hash.includes("w=75")`);
assert.ok(Math.abs(await b.evaluate(ratio) - 75) <= 1);
// Closing a pane goes back to one; the divider leaves with it. Add pane brings a second back.
await b.evaluate('document.querySelector("#pane-a [data-pane-close]").click()');
await wait(`document.getElementById("pane-b").hidden && document.querySelector("${sep}").hidden && !new URLSearchParams(location.hash.split("?")[1]).has("b") && ${title('a')}.includes("Forge")`);
assert.equal(await b.evaluate('document.activeElement.id'), 'pane-a-pick');
assert.equal(await b.evaluate('document.querySelector("#pane-a [data-pane-close]").hidden'), true);
assert.match(await b.evaluate('document.querySelector("[data-sbs-note]").textContent'), /^1 pane ·/);
await b.evaluate('document.querySelector("[data-pane-add]").click()');
await wait(`!document.getElementById("pane-b").hidden && ${title('b')}.length > 0 && new URLSearchParams(location.hash.split("?")[1]).has("b")`);
assert.equal(await b.evaluate('document.querySelector("[data-pane-add]").disabled'), true);
});
test('each pane keeps its own focus and scroll through a refresh', async t => {
const state = { flip: false, seen: [] };
const { b, wait } = await open(t, { height: 520, state, hash: '#/orgs/ddigital/side-by-side?a=ddigital/agents&b=forge/agents' });
await wait(`${text('a')}.includes("copywriter") && ${text('b')}.includes("builder")`);
const scrollable = await b.evaluate('[...document.querySelectorAll("[data-pane-body]")].map(el => el.scrollHeight - el.clientHeight)');
assert.ok(scrollable.every(n => n > 60), `both panes scroll: ${scrollable}`);
const focused = await b.evaluate('(() => { const a = document.querySelector("#pane-a [data-pane-body] a[href]"); a.focus(); return a.getAttribute("href"); })()');
await b.evaluate('document.querySelector("#pane-a [data-pane-body]").scrollTop = 40; document.querySelector("#pane-b [data-pane-body]").scrollTop = 60;');
const before = await b.evaluate(`[${text('a')}, ${text('b')}]`);
state.flip = true;
await b.evaluate('document.getElementById("refresh").click()');
await wait(`${text('a')} !== ${JSON.stringify(before[0])} && ${text('b')} !== ${JSON.stringify(before[1])}`);
assert.equal(await b.evaluate('document.querySelector("#pane-a").contains(document.activeElement) && document.activeElement.getAttribute("href")'), focused);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-pane-body]")].map(el => el.scrollTop)'), [40, 60]);
// Focus in the right pane stays there while the left repaints.
const right = await b.evaluate('(() => { const a = document.querySelector("#pane-b [data-pane-body] a[href]"); a.focus({ preventScroll: true }); return a.getAttribute("href"); })()');
state.flip = false;
await b.evaluate('document.getElementById("refresh").click()');
await wait(`${text('a')} === ${JSON.stringify(before[0])}`);
assert.equal(await b.evaluate('document.querySelector("#pane-b").contains(document.activeElement) && document.activeElement.getAttribute("href")'), right);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-pane-body]")].map(el => el.scrollTop)'), [40, 60]);
});
test('a pane whose organization is down shows its state and the other pane still works', async t => {
const { b, wait } = await open(t, { hash: '#/orgs/ddigital/side-by-side?a=home/organization&b=forge/organization' });
await wait(`${title('a')}.includes("Home") && ${title('b')}.includes("Forge") && ${text('b')}.includes("Forge")`);
await wait('/Home: bus unavailable/.test(document.querySelector("#pane-a [data-pane-line]").textContent)');
assert.equal(await b.evaluate('document.querySelector("#pane-a [data-pane-line]").getAttribute("role")'), 'status');
assert.equal(await b.evaluate('document.querySelector("#pane-a [data-pane-state]").innerText.trim().length > 0'), true);
assert.equal(await b.evaluate('document.querySelector("#pane-b [data-pane-line]").hidden'), true);
await pick(b, 'b', 'forge/agents');
await wait(`${title('b')}.startsWith("Agents") && ${text('b')}.includes("builder")`);
await pick(b, 'b', 'forge/projects/api-gateway');
await wait(`${title('b')}.startsWith("API gateway") && ${text('b')}.includes("API gateway")`);
assert.match(await b.evaluate(title('a')), /Home/);
// An organization that is not on the list is one honest line; nothing is read for it.
await b.evaluate('location.hash = "#/orgs/ddigital/side-by-side?a=ghost/organization&b=forge/agents"');
await wait(`/ghost is not on your organization list/.test(document.querySelector("#pane-a [data-pane-line]").textContent) && ${text('b')}.includes("builder")`);
});
test('on a phone one pane shows at a time, switched from the bar, with no horizontal scroll', async t => {
const { b, wait } = await open(t, { width: 390, height: 844 });
await wait(`${title('a')}.length > 0 && ${title('b')}.length > 0 && ${text('a')}.length > 0`);
const visible = '[...document.querySelectorAll(".panes > .pane")].filter(p => p.getBoundingClientRect().height > 0).map(p => p.id)';
assert.deepEqual(await b.evaluate(visible), ['pane-a']);
assert.notEqual(await b.evaluate('getComputedStyle(document.querySelector("[data-sbs-tabs]")).display'), 'none');
assert.equal(await b.evaluate('getComputedStyle(document.querySelector("[data-sbs-divider]")).display'), 'none');
assert.equal(await b.evaluate('getComputedStyle(document.querySelector("[data-pane-add]")).display'), 'none');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-sbs-tabs] button")].map(x => x.getAttribute("aria-pressed"))'), ['true', 'false']);
assert.ok(await b.evaluate('document.documentElement.scrollWidth <= innerWidth'), 'no horizontal scroll');
await b.evaluate('document.querySelector("[data-sbs-tabs] [data-pane-show=b]").click()');
await wait(`JSON.stringify(${visible}) === '["pane-b"]' && location.hash.includes("show=b")`);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-sbs-tabs] button")].map(x => x.getAttribute("aria-pressed"))'), ['false', 'true']);
assert.ok(await b.evaluate('document.documentElement.scrollWidth <= innerWidth'), 'no horizontal scroll on the second pane');
await pick(b, 'b', 'ddigital/projects/spring-launch');
await wait(`${text('b')}.includes("Spring launch")`);
assert.ok(await b.evaluate('document.documentElement.scrollWidth <= innerWidth'), 'no horizontal scroll on a project page');
});
// Review fixes (#1873 U5 review, findings 1-4). `hold(url)` makes the page's next read of that URL
// wait until `release()`; the test then changes the pane while the read is pending.
const hold = url => `(() => { const real = window.fetch; window.held = { url: ${JSON.stringify(url)}, pending: false };
window.fetch = async (u, o) => { if (window.held?.url === u && !window.held.done) { window.held.pending = true; await new Promise(r => { window.held.release = () => { window.held.done = true; r(); }; }); } return real(u, o); }; })()`;
const settled = b => b.evaluate('new Promise(r => setTimeout(r, 400))');
test('a pane closed and opened again rewrites new links for its current organization only', async t => {
const { b, wait } = await open(t);
await wait(`${title('b')}.includes("Forge") && document.querySelector("#pane-b-pick")?.options.length > 4`);
await b.evaluate('document.querySelector("#pane-b [data-pane-close]").click()');
await wait('document.querySelector("#pane-b").hidden && !document.querySelector("[data-pane-add]").disabled');
await b.evaluate('document.querySelector("[data-pane-add]").click()');
await wait(`!document.querySelector("#pane-b").hidden && ${title('b')}.length > 0`);
await pick(b, 'b', 'ddigital/organization');
await wait(`${title('b')}.includes("Distinctly Digital") && location.hash.includes("b=ddigital/organization")`);
// Content a page appends after its own reads (projects.js does this) gets the pane's organization.
await b.evaluate(`document.querySelector("#pane-b [data-pane-body]").insertAdjacentHTML("beforeend", '<a data-late href="#/docs/example">late</a><a data-late-api href="/api/files/x">file</a>')`);
await wait('document.querySelector("#pane-b [data-late]").getAttribute("href").startsWith("#/orgs/")');
assert.equal(await b.evaluate('document.querySelector("#pane-b [data-late]").getAttribute("href")'), '#/orgs/ddigital/docs/example');
assert.equal(await b.evaluate('document.querySelector("#pane-b [data-late-api]").getAttribute("href")'), '/api/orgs/ddigital/files/x');
// Leaving the page stops every pane observer: later content in the old element is left alone.
await b.evaluate('location.hash = "#/orgs/ddigital/agents"');
await wait('!document.querySelector("[data-side-by-side]")');
});
test('a slow project read never paints over the page or organization chosen since', async t => {
const { b, wait } = await open(t);
await wait(`${title('b')}.includes("Forge") && document.querySelector("#pane-b-pick")?.options.length > 4`);
// Page change while the project's thread read is pending.
await b.evaluate(hold('/api/orgs/forge/chat/threads'));
await pick(b, 'b', 'forge/projects/api-gateway');
await wait('window.held.pending');
await pick(b, 'b', 'forge/agents');
await wait(`${title('b')}.startsWith("Agents") && ${text('b')}.includes("builder")`);
await b.evaluate('window.held.release()');
await settled(b);
assert.equal(await b.evaluate(`${text('b')}.includes("API gateway")`), false, 'the old project did not replace Agents');
assert.match(await b.evaluate(title('b')), /^Agents/);
// Organization change while the read is pending: the old organization's project is not painted.
await b.evaluate(hold('/api/orgs/forge/chat/threads'));
await pick(b, 'b', 'forge/projects/api-gateway');
await wait('window.held.pending');
await pick(b, 'b', 'ddigital/projects/spring-launch');
await wait(`${title('b')}.startsWith("Spring launch") && ${text('b')}.includes("Spring launch")`);
await b.evaluate('window.held.release()');
await settled(b);
assert.equal(await b.evaluate(`${text('b')}.includes("API gateway")`), false, 'the old organization did not replace Spring launch');
assert.equal(await b.evaluate('[...document.querySelectorAll("#pane-b [data-pane-body] a[href^=\\"#/orgs/\\"]")].every(a => a.getAttribute("href").startsWith("#/orgs/ddigital/"))'), true);
});
test('the same project in both panes keeps a request choice per pane', async t => {
const { b, wait } = await open(t);
await wait(`${title('b')}.includes("Forge")`);
const { stub, P } = await import('./helpers/projects-review-fixture.mjs');
// The fixture answers the project reads of both organizations; the organization list stays real.
await b.evaluate(stub.replace('const path=String(url),method', `if(url==='/api/orgs'||url==='/api/themes')return real(url,init);const path=String(url).replace(/^\\/api\\/orgs\\/(?:ddigital|forge)\\//,'/api/'),method`));
await b.evaluate('window.MosaicPanes.refresh()');
await wait(`document.querySelector('#pane-a-pick option[value="ddigital/projects/${P}"]')`);
await b.evaluate(`location.hash = '#/orgs/ddigital/side-by-side?a=ddigital/projects/${P}/requirements&b=forge/projects/${P}/requirements'`);
const values = `[...document.querySelectorAll('[data-pane-body] select[id$="-project-request-select"]')].map(e => e.value)`;
await wait(`document.querySelectorAll('[data-pane-body] select[id$="-project-request-select"]').length === 2`);
assert.deepEqual(await b.evaluate(values), ['request-1', 'request-1']);
await b.evaluate(`(() => { const e = document.querySelector('#pane-a-project-request-select'); e.value = 'request-2'; e.dispatchEvent(new Event('change', { bubbles: true })); })()`);
await wait(`${values}[0] === 'request-2'`);
// The redrawn select gets focus back through the pane's own id.
assert.equal(await b.evaluate('document.activeElement.id'), 'pane-a-project-request-select');
await b.evaluate('window.MosaicPanes.refresh()');
await settled(b);
await wait(`document.querySelectorAll('[data-pane-body] select[id$="-project-request-select"]').length === 2`);
assert.deepEqual(await b.evaluate(values), ['request-2', 'request-1']);
});
test('a pane keeps its request choice and PRD disclosure when a new conversation repaints the project', async t => {
const { b, wait } = await open(t);
await wait(`${title('b')}.includes("Forge")`);
const { stub, P } = await import('./helpers/projects-review-fixture.mjs');
await b.evaluate(stub.replace('const path=String(url),method', `if(url==='/api/orgs'||url==='/api/themes')return real(url,init);const path=String(url).replace(/^\\/api\\/orgs\\/(?:ddigital|forge)\\//,'/api/'),method`));
await b.evaluate('window.MosaicPanes.refresh()');
await wait(`document.querySelector('#pane-a-pick option[value="ddigital/projects/${P}"]')`);
// The same organization and project in both panes.
await b.evaluate(`location.hash = '#/orgs/ddigital/side-by-side?a=ddigital/projects/${P}/requirements&b=ddigital/projects/${P}/requirements'`);
await wait(`document.querySelectorAll('[data-pane-body] select[id$="-project-request-select"]').length === 2 && document.querySelectorAll('[data-pane-body] .project-prd-toggle').length === 2`);
const state = `({ selected: [...document.querySelectorAll('[data-pane-body] select[id$="-project-request-select"]')].map(e => e.value), expanded: [...document.querySelectorAll('[data-pane-body] [data-prd]')].map(e => e.classList.contains('expanded')) })`;
await b.evaluate(`(() => { const e = document.querySelector('#pane-a-project-request-select'); e.value = 'request-2'; e.dispatchEvent(new Event('change', { bubbles: true })); })()`);
await wait(`document.querySelector('#pane-a-project-request-select').value === 'request-2'`);
await b.evaluate(`document.querySelector('#pane-a .project-prd-toggle').click()`);
await wait(`document.querySelector('#pane-a [data-prd]')?.classList.contains('expanded')`);
// A new conversation changes the header's count, so each pane replaces its project content.
const before = await b.evaluate(`document.querySelector('#pane-a .project-header p')?.textContent || ''`);
await b.evaluate(`window.fixtureThreads.push({ ...window.fixtureThreads[0], id: '20000000-0000-4000-8000-000000000004', name: 'A new conversation' }); window.MosaicPanes.refresh()`);
await wait(`(() => { const t = document.querySelector('#pane-a .project-header p')?.textContent || ''; return t !== ${JSON.stringify(before)} && /4 conversations/.test(t) && /4 conversations/.test(document.querySelector('#pane-b .project-header p')?.textContent || ''); })()`);
await settled(b);
await wait(`document.querySelectorAll('[data-pane-body] select[id$="-project-request-select"]').length === 2 && document.querySelectorAll('[data-pane-body] [data-prd]').length === 2`);
assert.deepEqual(await b.evaluate(state), { selected: ['request-2', 'request-1'], expanded: [true, false] });
});
test('a pane navigation that finishes late does not take focus from the other pane', async t => {
const { b, wait } = await open(t);
await wait(`document.querySelector('#pane-a [data-focus-key="agents-all"]') && document.querySelector('#pane-b-pick')?.options.length > 4`);
await b.evaluate(hold('/api/orgs/ddigital/bus/instances'));
await b.evaluate(`document.querySelector('#pane-a [data-focus-key="agents-all"]').click()`);
await wait('window.held.pending');
await b.evaluate(`document.querySelector('#pane-b-pick').focus(); window.held.release()`);
await wait(`${title('a')}.startsWith('Agents')`);
await settled(b);
assert.equal(await b.evaluate('document.activeElement.id'), 'pane-b-pick');
// Without a move elsewhere, the same navigation still lands on the new page's heading.
await pick(b, 'a', 'ddigital/organization');
await wait(`document.querySelector('#pane-a [data-focus-key="agents-all"]')`);
await b.evaluate(`document.querySelector('#pane-a [data-focus-key="agents-all"]').click()`);
await wait(`${title('a')}.startsWith('Agents') && document.activeElement?.tagName === 'H1' && document.querySelector('#pane-a').contains(document.activeElement)`);
});
// A1's "Available in a project" chooser, with an Agents pane per organization: each pane's choice
// redraws its own table and survives a refresh, keyed by that pane's organization.
test('each Agents pane keeps its own project choice for its organization', async t => {
const { b, wait } = await open(t, { hash: '#/orgs/ddigital/side-by-side?a=ddigital/agents&b=forge/agents' });
const a = (name, level = 'org', definition = name) => ({ name, level, definition, model: null, scope: { kind: 'org' }, overrides: [], narrowed: [] });
const set = agents => ({ state: 'ok', agents, excluded: [] });
const levels = { root: { state: 'ok', assistant: null, agents: [] }, orgs: [
{ id: 'ddigital', state: 'ok', base: set([a('chief')]), defined: { 'spring-launch': [{ name: 'social-scheduler', form: 'define' }] },
projects: { 'spring-launch': set([a('chief'), a('social-scheduler', 'project', 'coder')]), 'brand-refresh': set([a('chief')]) } },
{ id: 'forge', state: 'ok', base: set([a('chief')]), defined: { 'api-gateway': [{ name: 'load-tester', form: 'define' }] },
projects: { 'api-gateway': set([a('chief'), a('load-tester', 'project', 'coder')]), ops: set([a('chief')]) } },
] };
await b.evaluate(`(() => { const real = window.fetch; window.fetch = (url, init) => String(url).endsWith('/api/agents/levels') ? Promise.resolve(new Response(${JSON.stringify(JSON.stringify(levels))}, { headers: { 'content-type': 'application/json' } })) : real(url, init); })()`);
await b.evaluate('window.MosaicPanes.refresh()');
const select = key => `document.querySelector('#pane-${key} [data-agents-project]')`;
const rows = key => `[...document.querySelectorAll('#pane-${key} [data-agents-available] tr[data-agent]')].map(r => r.dataset.agent)`;
await wait(`${select('a')} && ${select('b')} && ${rows('a')}.includes('social-scheduler') && ${rows('b')}.includes('load-tester')`);
await b.evaluate(`(() => { const s = ${select('b')}; s.value = 'ops'; s.dispatchEvent(new Event('change', { bubbles: true })); })()`);
await wait(`!${rows('b')}.includes('load-tester')`);
assert.equal(await b.evaluate(`${rows('a')}.includes('social-scheduler')`), true);
assert.equal(await b.evaluate(`${rows('a')}.includes('load-tester')`), false);
await b.evaluate('window.MosaicPanes.refresh()');
await settled(b);
await wait(`${select('a')} && ${select('b')}`);
assert.deepEqual(await b.evaluate(`[${select('a')}.value, ${select('b')}.value]`), ['spring-launch', 'ops']);
assert.equal(await b.evaluate(`!${rows('b')}.includes('load-tester') && ${rows('a')}.includes('social-scheduler')`), true);
});
// Polish 1 (#1873): every id a pane draws is its own. With the same page in both panes no id
// appears twice, and every label, ARIA reference and in-page link resolves inside its own pane.
const idAudit = `(() => {
const count = new Map();
for (const el of document.querySelectorAll('[id]')) count.set(el.id, (count.get(el.id) || 0) + 1);
const duplicates = [...count].filter(([, n]) => n > 1).map(([id]) => id).sort();
const stray = [];
for (const pane of document.querySelectorAll('.panes > .pane:not([hidden])')) {
for (const attr of ['for', 'aria-labelledby', 'aria-describedby', 'aria-controls']) {
for (const el of pane.querySelectorAll('[' + attr + ']')) {
for (const id of el.getAttribute(attr).split(/\\s+/).filter(Boolean)) {
const target = document.getElementById(id);
if (!target || !pane.contains(target)) stray.push(pane.id + ' ' + attr + '=' + id);
}
}
}
for (const a of pane.querySelectorAll('a[href^="#"]:not([href^="#/"])')) {
const id = decodeURIComponent(a.getAttribute('href').slice(1));
const target = id && document.getElementById(id);
if (id && (!target || !pane.contains(target))) stray.push(pane.id + ' href=#' + id);
}
}
return { duplicates, stray: stray.sort() };
})()`;
test('the same project, dashboard and Agents page in both panes draw no duplicate ids, and every reference stays in its pane', async t => {
const { b, wait } = await open(t);
await wait(`${title('b')}.includes("Forge")`);
const { stub, P } = await import('./helpers/projects-review-fixture.mjs');
await b.evaluate(stub.replace('const path=String(url),method', `if(url==='/api/orgs'||url==='/api/themes')return real(url,init);const path=String(url).replace(/^\\/api\\/orgs\\/(?:ddigital|forge)\\//,'/api/'),method`));
const a = (name, level = 'org', definition = name) => ({ name, level, definition, model: null, scope: { kind: 'org' }, overrides: [], narrowed: [] });
const set = agents => ({ state: 'ok', agents, excluded: [] });
const levels = { root: { state: 'ok', assistant: null, agents: [] }, orgs: [
{ id: 'ddigital', state: 'ok', base: set([a('chief')]), defined: { [P]: [{ name: 'social-scheduler', form: 'define' }] },
projects: { [P]: set([a('chief'), a('social-scheduler', 'project', 'coder')]) } },
] };
await b.evaluate(`(() => { const real = window.fetch; window.fetch = (url, init) => String(url).endsWith('/api/agents/levels') ? Promise.resolve(new Response(${JSON.stringify(JSON.stringify(levels))}, { headers: { 'content-type': 'application/json' } })) : real(url, init); })()`);
await b.evaluate('window.MosaicPanes.refresh()');
await wait(`document.querySelector('#pane-a-pick option[value="ddigital/projects/${P}"]')`);
const both = route => `location.hash = '#/orgs/ddigital/side-by-side?a=ddigital${route}&b=ddigital${route}'`;
const pages = [
['/organization', `${title('a')}.startsWith('Dashboard') && ${title('b')}.startsWith('Dashboard') && document.querySelectorAll('[data-pane-body] [data-org-settings]').length === 2`],
['/agents', `${title('a')}.startsWith('Agents') && ${title('b')}.startsWith('Agents') && document.querySelectorAll('[data-pane-body] [data-agents-available] tr[data-agent]').length >= 2`],
[`/projects/${P}`, `${title('a')}.startsWith('Pomodoro Timer') && ${title('b')}.startsWith('Pomodoro Timer') && !${text('a')}.includes('Reading…') && !${text('b')}.includes('Reading…')`],
[`/projects/${P}/conversations`, `${title('a')}.includes('Conversations') && ${title('b')}.includes('Conversations')`],
[`/projects/${P}/tasks`, `${title('a')}.includes('Tasks') && ${title('b')}.includes('Tasks') && !${text('a')}.includes('Reading…') && !${text('b')}.includes('Reading…')`],
[`/projects/${P}/requirements`, `document.querySelectorAll('[data-pane-body] [data-prd]').length === 2 && document.querySelectorAll('[data-pane-body] select').length >= 2`],
[`/projects/${P}/files`, `${title('a')}.includes('Files') && ${title('b')}.includes('Files') && !${text('a')}.includes('Reading…') && !${text('b')}.includes('Reading…')`],
];
const found = {}, drawn = {};
for (const [route, ready] of pages) {
await b.evaluate(both(route));
await wait(ready);
await settled(b);
const page = route.replace(P, 'P');
found[page] = await b.evaluate(idAudit);
drawn[page] = await b.evaluate(`[...document.querySelectorAll('#pane-a [data-pane-body] [id]')].map(e => e.id)`);
}
assert.deepEqual(found, Object.fromEntries(pages.map(([route]) => [route.replace(P, 'P'), { duplicates: [], stray: [] }])));
// The audit is not vacuous: the dashboard draws its reload note and the requirements page its
// request select, north star and PRD headings, each with the pane's prefix.
assert.deepEqual(drawn['/organization'], ['pane-a-ws-reload-why']);
assert.deepEqual(drawn['/projects/P/requirements'], ['pane-a-project-request-select', 'pane-a-project-north-star', 'pane-a-project-prd']);
});
@@ -0,0 +1,435 @@
// SP1 (#1873, single pane slice 1): #/dashboard is the system landing route, an organization page is a
// drill-in route inside the same shell (no reload, the sidebar and top bar stay), and an organization
// whose bus is down says so with its reason. Every bus is a fake: acme and beta answer, gamma's bus is
// stopped. The real GET /api/orgs, /api/workspace and /api/agents/levels serve the page.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fileURLToPath } from 'node:url';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
async function fixture({ empty = false, bootless = false } = {}) {
const { checkRootAgents } = await import('../../organization/src/index.mjs');
const rolesDir = fileURLToPath(new URL('../../../roles', import.meta.url));
const root = { state: 'ok', ...checkRootAgents({ agentsVersion: 1, agents: {} }, { rolesDir }) };
const LIST = [
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
{ id: 'beta', label: 'Beta Works', theme: 'grove', busHealthy: true },
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false, busStopped: true },
];
const ROLES = {
acme: { chief: { definition: 'chief-of-staff' }, coder: { definition: 'coder' }, reviewer: { definition: 'reviewer' } },
beta: { chief: { definition: 'chief-of-staff' } },
gamma: { chief: { definition: 'chief-of-staff' }, researcher: { definition: 'research' } },
};
const DATA = {
acme: {
projects: [{ id: 'p-site', repo: 'site', name: 'Website', archived: false, at: at(30) }, { id: 'p-zeta', repo: 'zeta', name: 'Zeta API', archived: false, at: at(300) }],
agents: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'working', at: at(40), working: { since: at(40) } }],
inbox: [{ id: 'dec-acme-1', question: 'Ship the hero?', class: 'gated', blocking: true, raised_by_role: 'coder', at: at(10), options: [{ key: 'yes', text: 'Ship it' }] }],
},
beta: { projects: [{ id: 'p-shop', repo: 'shop', name: 'Shop', archived: false, at: at(120) }], agents: [], inbox: [] },
};
// Launch settings differ per organization so a value carried from one to the other shows.
const LAUNCH = id => ({ business: id, revision: (id === 'acme' ? 'a' : 'b').repeat(64), models: { opus: { provider: 'anthropic', model: 'claude-opus-5-5' } }, limits: { total: id === 'acme' ? 4 : 7 }, instances: {}, usage: { total: 0, providers: {}, models: {} } });
const value = (id, name) => Promise.resolve(DATA[id]?.[name] ?? (['usage', 'limits'].includes(name) ? {} : []));
const opts = id => ({
bus: { inbox: () => value(id, 'inbox'), agents: () => value(id, 'agents'), 'thread.claims': () => value(id, 'claims'), tasks: () => value(id, 'tasks'), usage: () => value(id, 'usage'), limits: () => value(id, 'limits'), decisions: () => value(id, 'decisions') },
chat: { threads: () => value(id, 'threads'), projects: () => value(id, 'projects') },
});
const member = org => ({
id: org.id, doc: { appearance: { theme: org.theme }, roles: ROLES[org.id], projects: {} },
status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : bootless ? { healthy: false, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }),
options: () => opts(org.id),
});
const instances = id => Object.fromEntries(Object.entries(ROLES[id]).map(([n, r]) => [n, { definition: r.definition, vars: {}, launched: true, launcher: false, protected: false, kept: false, running: n === 'coder' ? ['run-1'] : [], alive: [] }]));
const organizations = {
list: async () => (empty ? [] : LIST),
members: async () => (empty ? [] : LIST.map(member)),
resolve: async id => {
const org = LIST.find(o => o.id === id); if (!org) return null;
if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, chat: { projects: async () => [], threads: async () => [] } };
return {
busHealthy: true,
reads: { business: async () => ({ business: { id, human: 'jason', projects: DATA[id].projects.map(p => p.repo), appearance: { theme: org.theme } } }), settings: async () => ({ business: id, release: 'fixture', notifier: {}, launch: LAUNCH(id) }), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
bus: { messages: async () => ({ messages: [], unread: 0 }), agents: async () => DATA[id].agents, 'thread.claims': async () => [], inbox: async () => DATA[id].inbox.map(d => ({ ...d, business: id, raised_by_run: 'run', routed_to: 'human' })), tasks: async () => [], instances: async () => ({ business: id, revision: 'a'.repeat(64), launch: true, noHire: [], retired: [], definitions: {}, instances: instances(id) }) },
chat: { projects: async () => DATA[id].projects, threads: async () => [] },
};
},
};
return { organizations, agentLevels: { loadRoot: () => root, rolesDir, ctx: { configDir: '/cfg', dataRoot: '/data', instance: 'test' } } };
}
async function setup(t, { viewport = [1440, 900], path = '/', empty = false, init = null, bootless = false } = {}) {
const { organizations, agentLevels } = await fixture({ empty, bootless });
const server = await startServer({ port: 0, sso: createDevOwner(), organizations, agentLevels, log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
// `init` runs before the page's own scripts, under the display.js fetch wrapper, so it sees the scoped URL.
if (init) await b.call('Page.addScriptToEvaluateOnNewDocument', { source: init });
const base = `http://127.0.0.1:${server.address().port}`;
await b.navigate(`${base}${path}`);
return { b, base, wait: waitFor(b), text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) };
}
const rowText = org => `document.querySelector("[data-ws-orgrow=${org}]")?.innerText.replace(/\\s+/g, " ").trim() ?? ""`;
test('the bare address lands on #/dashboard without a reload and lists every organization with only the figures read', async t => {
const { b, wait, text } = await setup(t);
await wait('location.hash === "#/dashboard" && document.querySelectorAll("[data-ws-orgrow]").length === 3');
// One page load: the landing route is set in place, never by location.reload().
assert.equal(await b.evaluate('performance.getEntriesByType("navigation").length'), 1);
assert.equal(await b.evaluate('performance.getEntriesByType("navigation")[0].type'), 'navigate');
assert.equal(await text('#bus-view h1'), 'Dashboard');
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/dashboard');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-orgrow]")].map(r => r.dataset.wsOrgrow)'), ['acme', 'beta', 'gamma']);
// Agents from the levels read, projects and needs-you from the workspace read.
await wait(`${rowText('acme')}.includes("3 agents")`);
const acme = await b.evaluate(rowText('acme'));
assert.match(acme, /Acme Studio/);
assert.match(acme, /bus running/);
assert.match(acme, /2 projects/);
assert.match(acme, /1 needs you/);
assert.match(await b.evaluate(rowText('beta')), /1 agent\b/);
// gamma: down with its reason; its agent count comes from its file, the bus figures are not read.
const gamma = await b.evaluate(rowText('gamma'));
assert.match(gamma, /bus stopped/);
assert.match(gamma, /stopped by the owner/);
assert.match(gamma, /2 agents/);
assert.doesNotMatch(gamma, /\d+ projects?|\d+ needs you/);
assert.equal(await b.evaluate('document.querySelector("[data-ws-orgrow=beta] a")?.getAttribute("href")'), '#/orgs/beta/organization');
// A system route marks no organization in the sidebar and shows no breadcrumb.
assert.equal(await b.evaluate('document.querySelectorAll("#workspace-nav .sel, #workspace-nav [aria-current]").length'), 0);
assert.equal(await b.evaluate('document.querySelector(".ws-crumb")'), null);
// The top bar names no organization.
assert.equal(await b.evaluate('document.getElementById("current-organization")'), null);
});
test('an organization opens inside the same shell with a breadcrumb, and its pages keep reading that organization', async t => {
const { b, wait, text } = await setup(t);
await wait('document.querySelectorAll("[data-ws-orgrow]").length === 3');
await b.evaluate('window.__marker = 1; window.__bar = document.querySelector(".cmdbar"); window.__side = document.getElementById("workspace-nav")');
await b.evaluate('document.querySelector("[data-ws-orgrow=acme] a").click()');
await wait('location.hash === "#/orgs/acme/organization" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio"');
assert.equal(await b.evaluate('window.__marker'), 1);
assert.equal(await b.evaluate('window.__bar === document.querySelector(".cmdbar") && window.__side === document.getElementById("workspace-nav")'), true);
assert.equal(await b.evaluate('performance.getEntriesByType("navigation").length'), 1);
assert.equal(await b.evaluate('document.querySelector(".ws-crumb")?.innerText.replace(/\\s+/g, " ").trim()'), 'Dashboard › Acme Studio');
assert.equal(await b.evaluate('document.querySelector(".ws-crumb a")?.getAttribute("href")'), '#/dashboard');
assert.equal(await b.evaluate('document.getElementById("current-organization")'), null);
// The sidebar marks the open organization.
await wait('document.querySelector("#workspace-nav a[aria-current=page]")?.getAttribute("href") === "#/orgs/acme/organization"');
// The sidebar opens another organization in place; its page reads that organization's routes.
await b.evaluate('performance.clearResourceTimings(); document.querySelector("#workspace-nav a[href=\'#/orgs/beta/organization\']").click()');
await wait('location.hash === "#/orgs/beta/organization" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Beta Works"');
assert.equal(await b.evaluate('window.__marker'), 1);
// #1873 SP5: #/agents is the system Agents page, not beta's; it keeps the address and opens no organization.
await b.evaluate('location.hash = "#/agents"');
await wait('location.hash === "#/agents" && document.querySelector("[data-ws-agents]:not([data-ws-scope])")');
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'beta');
// A page inside beta scopes its reads to beta.
await b.evaluate('location.hash = "#/orgs/beta/agents"');
await wait('location.hash === "#/orgs/beta/agents" && document.querySelector("[data-org-agents]")');
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'beta');
assert.equal(await b.evaluate('window.__marker'), 1);
// The organization's control board is named as such after the organization, not as a second Dashboard.
await b.evaluate('location.hash = "#/orgs/beta/board"');
await wait('/^Dashboard\\/.+\\/Control board$/.test(document.getElementById("breadcrumbs")?.textContent ?? "")');
assert.equal(await b.evaluate('document.querySelector("#breadcrumbs [data-crumb-org]")?.getAttribute("href")'), '#/orgs/beta/organization');
// The breadcrumb goes back to the system dashboard, still without a reload.
await b.evaluate('location.hash = "#/orgs/beta/organization"');
await wait('document.querySelector(".ws-crumb a")');
await b.evaluate('document.querySelector(".ws-crumb a").click()');
await wait('location.hash === "#/dashboard" && document.querySelectorAll("[data-ws-orgrow]").length === 3');
assert.equal(await b.evaluate('window.__marker'), 1);
assert.equal(await b.evaluate('performance.getEntriesByType("navigation").length'), 1);
assert.equal(await text('#bus-view h1'), 'Dashboard');
});
test('an old #/orgs/<id>/... link still opens that page', async t => {
const { b, wait } = await setup(t, { path: '/#/orgs/beta/agents' });
await wait('document.querySelector("[data-org-agents]")');
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/agents');
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'beta');
assert.equal(await b.evaluate('performance.getEntriesByType("navigation").length'), 1);
});
test('a stopped organization says so on its page and on its agents, with the reason', async t => {
const { b, wait } = await setup(t, { path: '/#/orgs/gamma/organization' });
await wait('document.querySelector("[data-org-dashboard] [data-org-down]")');
const down = await b.evaluate('document.querySelector("[data-org-down]").innerText.replace(/\\s+/g, " ")');
assert.match(down, /The bus is not running/);
assert.match(down, /stopped by the owner/);
await b.evaluate('location.hash = "#/orgs/gamma/agents"');
await wait('document.querySelector("[data-org-agents] [data-org=gamma] [data-agents-why]")');
assert.equal(await b.evaluate('document.querySelector("[data-org=gamma] [data-agents-why]").innerText.trim()'), 'Agents not read: the bus is stopped');
const agents = await b.evaluate('document.querySelector("[data-org-agents]").innerText.replace(/\\s+/g, " ")');
assert.doesNotMatch(agents, /Agents unavailable/);
});
test('at 390 px the dashboard lists the organizations without a horizontal scroll', async t => {
const { b, wait } = await setup(t, { viewport: [390, 844] });
await wait('document.querySelectorAll("[data-ws-orgrow]").length === 3');
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= window.innerWidth'), true);
});
// Review round finding 1: with no organization yet the page keeps its first-run addresses, so the
// wordmark (href "#/") opens the first-run board, not a #/dashboard the first-run page has no view for.
test('first run: the wordmark opens the first-run board, not a Not found page', async t => {
const { b, wait } = await setup(t, { path: '/#/settings/appearance', empty: true });
await wait('document.querySelector("#bus-view h1")');
await b.evaluate('document.querySelector(".wordmark").click()');
// The board route empties the page view; give the router and render time to settle before checking.
await wait('location.hash !== "#/settings/appearance"');
await new Promise(r => setTimeout(r, 800));
assert.equal(await b.evaluate('location.hash'), '#/');
assert.equal(await b.evaluate('!!document.querySelector("#bus-view .nf")'), false);
assert.equal(await b.evaluate('window.MosaicOrg'), undefined);
});
test('a switch stops following an agent request: no poll reaches the next organization and its page shows no receipt', async t => {
const ID = '11111111-2222-4333-8444-555555555555';
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
const init = `window.__reads = []; window.__posts = []; const original = window.fetch;
window.fetch = async (url, options = {}) => { const s = String(url); let x;
if (/^\\/api\\/orgs\\/[^/]+\\/config$/.test(s)) { const r = await original(url, options), body = await r.json(); x = { ...body, send: true }; return ${json}; }
if (options.method === 'POST' && /\\/agent\\/launch$/.test(s)) { __posts.push(s); x = { request: '${ID}', at: 'x' }; return ${json}; }
if (/\\/agent\\/request\\?/.test(s)) { __reads.push(s); x = { request: '${ID}', action: 'launch', instance: 'reviewer', state: 'open', done: null, cancelled: null }; return ${json}; }
return original(url, options); };`;
const { b, wait } = await setup(t, { path: '/#/orgs/acme/settings/agents', init });
const launch = '#agents-section [data-agent-action=launch][data-agent-name=reviewer]';
await wait(`document.querySelector(${JSON.stringify(launch)}) && !document.querySelector(${JSON.stringify(launch)}).disabled`);
await b.evaluate(`document.querySelector(${JSON.stringify(launch)}).click()`);
await wait('window.__reads.length >= 1');
assert.deepEqual(await b.evaluate('window.__posts'), ['/api/orgs/acme/agent/launch']);
assert.match(await b.evaluate('window.__reads[0]'), /^\/api\/orgs\/acme\/agent\/request\?id=/);
await b.evaluate('location.hash = "#/orgs/beta/settings/agents"');
await wait('location.hash === "#/orgs/beta/settings/agents" && document.querySelector("#agents-section [data-agent-name=chief]") && !document.querySelector("#agents-section [data-agent-name=reviewer]")');
const seen = await b.evaluate('window.__reads.length');
// Two poll periods pass on beta's page.
await new Promise(r => setTimeout(r, 4500));
const reads = await b.evaluate('window.__reads');
assert.equal(reads.filter(u => u.includes('/orgs/beta/')).length, 0, reads.join(' '));
assert.equal(reads.length, seen, 'the poll stopped at the switch');
assert.equal(await b.evaluate('document.querySelector("#agents-receipt")?.textContent.trim() ?? ""'), '');
assert.equal(await b.evaluate('document.querySelector("#agents-section [data-agent-action=launch][data-agent-name=chief]")?.disabled'), false);
});
test('a save still in flight at a switch: its answer is not drawn on the next organization and its Save is not held', async t => {
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
// acme's settings POST is held until the test releases it, then answers with acme's saved values.
const init = `window.__posts = []; const original = window.fetch;
window.fetch = async (url, options = {}) => { const s = String(url); let x;
if (/^\\/api\\/orgs\\/[^/]+\\/config$/.test(s)) { const r = await original(url, options), body = await r.json(); x = { ...body, send: true }; return ${json}; }
if (options.method === 'POST' && s === '/api/orgs/acme/settings') { __posts.push(JSON.parse(options.body)); await new Promise(r => { window.__release = r; });
x = { business: 'acme', revision: 'c'.repeat(64), models: { opus: { provider: 'anthropic', model: 'claude-opus-5-5' } }, limits: { total: 5 }, instances: {}, usage: { total: 0, providers: {}, models: {} } }; return ${json}; }
return original(url, options); };`;
const { b, wait } = await setup(t, { path: '/#/orgs/acme/settings/limits', init });
const total = '#launch-settings-form input[data-setting=\'["total"]\']';
const submit = '#launch-settings-form button[type=submit]';
await wait(`document.querySelector(${JSON.stringify(total)})?.value === "4" && !document.querySelector(${JSON.stringify(submit)}).disabled`);
await b.evaluate(`(() => { const i = document.querySelector(${JSON.stringify(total)}); i.value = "5"; i.dispatchEvent(new Event("input", { bubbles: true })); document.querySelector(${JSON.stringify(submit)}).click(); })()`);
await wait('typeof window.__release === "function"');
assert.equal(await b.evaluate('window.__posts[0]?.revision'), 'a'.repeat(64));
await b.evaluate('location.hash = "#/orgs/beta/settings/limits"');
await wait(`location.hash === "#/orgs/beta/settings/limits" && document.querySelector(${JSON.stringify(total)})?.value === "7"`);
// beta's Save is its own: not held by acme's write.
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(submit)}).disabled`), false);
await b.evaluate('window.__release()');
await new Promise(r => setTimeout(r, 700));
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/settings/limits');
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(total)})?.value`), '7');
assert.equal(await b.evaluate('document.getElementById("launch-settings-receipt")?.textContent.trim() ?? ""'), '');
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(submit)}).disabled`), false);
});
test('a down banner does not repeat its heading as the reason', async t => {
// No boot record: the server's reason is its fallback, "the bus is not running", the heading's own words.
const { b, wait } = await setup(t, { path: '/#/orgs/gamma/organization', bootless: true });
await wait('document.querySelector("[data-org-dashboard] [data-org-down]")');
const down = await b.evaluate('document.querySelector("[data-org-down]").innerText.replace(/\\s+/g, " ")');
assert.match(down, /The bus is not running\./);
assert.equal((down.match(/the bus is not running/gi) || []).length, 1, down);
assert.doesNotMatch(down, /Reason:|No reason was read/);
});
test('a restart started on one organization finishes on that organization after a switch', { timeout: 60000 }, async t => {
const END = '11111111-2222-4333-8444-5555555555e1', LAUNCHED = '11111111-2222-4333-8444-5555555555a1';
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
// Every agent request read and write is recorded, whichever organization it names; the bus answers
// are stubs (terminate, closed requests, one launch). Only acme's instances read is stubbed and
// recorded (the session gone): beta's own page reads beta's instances, which is not the chain.
const init = `window.__chain = []; const original = window.fetch;
window.fetch = async (url, options = {}) => { const s = String(url); let x;
if (options.method === 'POST' && /\\/agent\\/terminate$/.test(s)) { __chain.push(s); x = { request: '${END}' }; return ${json}; }
if (options.method === 'POST' && /\\/agent\\/launch$/.test(s)) { __chain.push(s); x = { request: '${LAUNCHED}' }; return ${json}; }
if (/\\/agent\\/request\\?/.test(s)) { __chain.push(s.split('?')[0]); const id = new URL(s, location.href).searchParams.get('id');
x = { request: id, instance: 'coder', action: id === '${END}' ? 'end' : 'launch', state: 'closed', done: { run: id === '${END}' ? null : 'run-9' }, cancelled: null }; return ${json}; }
if (s === '/api/orgs/acme/bus/instances' && window.__restarting) { __chain.push(s); x = { rows: [{ instances: { coder: { running: [] } } }] }; return ${json}; }
return original(url, options); };`;
const { b, wait } = await setup(t, { path: '/#/orgs/acme/organization', init });
await wait('window.MosaicAgents && document.querySelector("[data-org-dashboard] h1")');
// The button the Routing receipt offers (agents.js restartMarkup), placed on acme's page.
await b.evaluate('window.__restarting = true; document.querySelector("[data-org-dashboard]").insertAdjacentHTML("beforeend", window.MosaicAgents.restartMarkup("coder")); document.querySelector("[data-agent-restart=coder]").click()');
await wait('window.__chain.length >= 1');
await b.evaluate('location.hash = "#/orgs/beta/organization"');
await wait('location.hash === "#/orgs/beta/organization"');
// Done when the chain has launched and read the launch request back, or as soon as any of it names beta.
await wait('window.__chain.some(u => u.includes("/orgs/beta/")) || (window.__chain.some(u => /\\/agent\\/launch$/.test(u)) && window.__chain.filter(u => /\\/agent\\/request$/.test(u)).length >= 2)', 30000);
const chain = await b.evaluate('window.__chain');
assert.deepEqual([...new Set(chain)], ['/api/orgs/acme/agent/terminate', '/api/orgs/acme/agent/request', '/api/orgs/acme/bus/instances', '/api/orgs/acme/agent/launch'], chain.join(' '));
// beta's page draws nothing of acme's chain.
assert.equal(await b.evaluate('!!document.querySelector("[data-agent-restart-status=coder]")'), false);
});
test('a file save still in flight at a switch: its outcome is not announced on the next organization', async t => {
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
// acme's file reads are stubbed; its save POST is held until the test releases it, then answers with a commit.
const init = `window.__posts = []; const original = window.fetch;
window.fetch = async (url, options = {}) => { const s = String(url); let x;
if (/^\\/api\\/orgs\\/[^/]+\\/config$/.test(s)) { const r = await original(url, options), body = await r.json(); x = { ...body, send: true, edit: true }; return ${json}; }
if (s.startsWith('/api/orgs/acme/project-file?')) { x = { path: 'docs/a.md', commit: 'a'.repeat(40), content: '# A\\n', at: new Date().toISOString() }; return ${json}; }
if (options.method === 'POST' && s === '/api/orgs/acme/project-file') { __posts.push(JSON.parse(options.body)); await new Promise(r => { window.__release = r; });
x = { path: 'docs/a.md', commit: 'c'.repeat(40) }; return ${json}; }
return original(url, options); };`;
const { b, wait } = await setup(t, { path: `/#/orgs/acme/docs/site/${encodeURIComponent('docs/a.md')}`, init });
await wait('document.querySelector("#doc-form")');
if (!await b.evaluate('!!document.querySelector("#doc-text")')) await b.evaluate('document.querySelector("#doc-mode-source").click(), true');
await wait('document.querySelector("#doc-text")?.value === "# A\\n"');
await b.evaluate('(() => { const a = document.querySelector("#doc-text"); a.value = "# A\\n\\nmore\\n"; a.dispatchEvent(new Event("input", { bubbles: true })); document.querySelector("#doc-form").requestSubmit(); })()');
await wait('typeof window.__release === "function"');
assert.equal(await b.evaluate('window.__posts[0]?.base'), 'a'.repeat(40));
await b.evaluate('location.hash = "#/orgs/beta/organization"');
await wait('location.hash === "#/orgs/beta/organization" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Beta Works"');
await b.evaluate('window.__release()');
await new Promise(r => setTimeout(r, 700));
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/organization');
assert.doesNotMatch(await b.evaluate('document.getElementById("announce")?.textContent ?? ""'), /Saved as commit|Draft kept/);
});
// SP2 item 1: an organization's own bare address is its page, not the system dashboard.
test('a bare #/orgs/<id> opens that organization\'s page', async t => {
const { b, wait } = await setup(t, { path: '/#/orgs/beta' });
await wait('location.hash === "#/orgs/beta/organization" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Beta Works"');
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'beta');
// In place too, from another organization's page.
await b.evaluate('location.hash = "#/orgs/acme"');
await wait('location.hash === "#/orgs/acme/organization" && document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio"');
assert.equal(await b.evaluate('performance.getEntriesByType("navigation").length'), 1);
// The old per-organization dashboard address is still the system dashboard.
await b.evaluate('location.hash = "#/orgs/acme/dashboard"');
await wait('location.hash === "#/dashboard" && document.querySelectorAll("[data-ws-orgrow]").length === 3');
});
// SP2 item 2: the system dashboard shows the system theme, never the organization opened last.
test('the dashboard keeps the system theme after an organization with its own theme was opened', async t => {
const { b, base, wait } = await setup(t, { path: '/#/orgs/acme/organization' });
await wait('document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio" && document.documentElement.dataset.palette === "cobalt"');
await b.evaluate('location.hash = "#/dashboard"');
await wait('document.querySelectorAll("[data-ws-orgrow]").length === 3');
await wait('document.documentElement.dataset.palette === "harbor"');
assert.equal(await b.evaluate('window.MosaicAppearance.state().organization'), null);
assert.equal(await b.evaluate('document.getElementById("org-cue").hidden'), true);
// A fresh load of the bare address, with acme stored as the last organization shown, starts on the system theme.
await b.navigate(`${base}/`);
await wait('location.hash === "#/dashboard" && document.querySelectorAll("[data-ws-orgrow]").length === 3');
await new Promise(r => setTimeout(r, 500));
assert.equal(await b.evaluate('document.documentElement.dataset.palette'), 'harbor');
// A choice made on the dashboard is the system's own: acme keeps its theme, and the dashboard keeps the choice.
await b.evaluate('window.MosaicAppearance.set({ mode: "light" })');
assert.equal(await b.evaluate('document.documentElement.dataset.mode'), 'light');
await b.evaluate('location.hash = "#/orgs/acme/organization"');
await wait('document.documentElement.dataset.palette === "cobalt"');
assert.equal(await b.evaluate('document.documentElement.dataset.mode'), 'dark');
await b.evaluate('location.hash = "#/dashboard"');
await wait('document.documentElement.dataset.palette === "harbor" && document.documentElement.dataset.mode === "light"');
});
// SP2 item 3: a stopped organization's page shows one bus banner, with the restart action and what can't be read.
test('a stopped organization\'s page shows one bus banner, with the restart action', async t => {
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
const init = `const original = window.fetch;
window.fetch = async (url, options = {}) => { const s = String(url); let x;
if (/^\\/api\\/(orgs\\/[^/]+\\/)?config$/.test(s)) { const r = await original(url, options), body = await r.json(); x = { ...body, orgSetup: true }; return ${json}; }
return original(url, options); };`;
const { b, wait } = await setup(t, { path: '/#/orgs/gamma/organization', init });
await wait('document.querySelector("[data-org-dashboard] [data-org-down] [data-bus-restart]")');
// Both shell painters (display.js on the list read, app.js on its own read) have had their turn.
await b.evaluate('window.MosaicOrg.list');
await new Promise(r => setTimeout(r, 800));
const banners = 'Array.from(document.querySelectorAll(".banner")).filter(e => !e.hidden && e.getClientRects().length && /bus/i.test(e.textContent)).map(e => e.innerText.replace(/\\s+/g, " ").trim())';
const shown = await b.evaluate(banners);
assert.equal(shown.length, 1, shown.join(' | '));
assert.match(shown[0], /The bus is not running\. Nothing about Gamma Home's agents or packs can be read until it starts\./);
assert.match(shown[0], /Restart the bus/);
assert.equal(await b.evaluate('document.getElementById("bus-down").hidden'), true);
// SP7 item 7: one restart control on the page, the banner's; the header draws no second one.
const restarts = 'Array.from(document.querySelectorAll("[data-bus-restart], [data-bus-restart-off]")).filter(e => e.getClientRects().length).map(e => e.closest("[data-org-down]") ? "banner" : "header")';
assert.deepEqual(await b.evaluate(restarts), ['banner']);
assert.equal(await b.evaluate('document.querySelector("[data-org-dashboard] .ws-orghead [data-dashboard-bus]")'), null);
// The organization's other pages keep the shell's banner, with its restart.
await b.evaluate('location.hash = "#/orgs/gamma/agents"');
await wait('!document.getElementById("bus-down").hidden && /Bus unavailable/.test(document.getElementById("bus-down").textContent)');
// And back on the organization page it gives way again.
await b.evaluate('location.hash = "#/orgs/gamma/organization"');
await wait('document.querySelector("[data-org-dashboard] [data-org-down]") && document.getElementById("bus-down").hidden');
});
// SP2 item 4: the dashboard row for a stopped organization says it once.
test('a stopped organization\'s dashboard row does not repeat its state as the reason', async t => {
const { b, wait } = await setup(t, { bootless: true });
await wait('document.querySelectorAll("[data-ws-orgrow]").length === 3');
await wait(`${rowText('gamma')}.includes("bus stopped")`);
const gamma = await b.evaluate(rowText('gamma'));
assert.doesNotMatch(gamma, /the bus is not running/i, gamma);
assert.equal(await b.evaluate('document.querySelector("[data-ws-orgrow=gamma] .why")'), null);
});
// SP2 item 6: no status-badge glyph ("?") is drawn before the live dot in the dashboard's Active agents.
test('the dashboard\'s active agents draw no stray glyph before the status dot', async t => {
const { b, wait } = await setup(t);
await wait('document.querySelector("[data-ws-sessions] tbody tr")');
const cells = await b.evaluate('Array.from(document.querySelectorAll("[data-ws-sessions] tbody td")).map(td => getComputedStyle(td, "::before").content)');
assert.ok(cells.length >= 2, String(cells));
for (const c of cells) assert.ok(c === 'none' || c === 'normal', `generated content ${c}`);
});
// SP2 item 7 (the test SP1 lacks): a read still in flight when the organization switches keeps nothing.
// acme's settings read is held across a switch to beta and then answers with a figure only it has (99);
// beta's own read then fails, so beta's page draws from what was kept. Nothing of acme's may be there.
test('a read still in flight at a switch: its answer is not kept for the next organization', async t => {
const json = 'new Response(JSON.stringify(x), { status: 200, headers: { "content-type": "application/json" } })';
const init = `window.__acme = []; window.__beta = []; const original = window.fetch;
window.fetch = async (url, options = {}) => { const s = String(url); let x;
if (s === '/api/orgs/acme/settings' && !options.method && window.__holdAcme) { await new Promise(r => window.__acme.push(r));
const r = await original(url, options), body = await r.json(); x = { ...body, launch: { ...body.launch, limits: { total: 99 } } }; return ${json}; }
if (s === '/api/orgs/beta/settings' && !options.method && window.__holdBeta) { await new Promise(r => window.__beta.push(r));
return new Response(JSON.stringify({ error: 'unavailable', message: 'beta settings read failed' }), { status: 500, headers: { 'content-type': 'application/json' } }); }
return original(url, options); };`;
const { b, wait } = await setup(t, { path: '/#/orgs/acme/settings/limits', init });
const total = '#launch-settings-form input[data-setting=\'["total"]\']';
await wait(`document.querySelector(${JSON.stringify(total)})?.value === "4"`);
// A fresh read of acme's settings starts and is held.
await b.evaluate('window.__holdAcme = true; location.hash = "#/orgs/acme/settings/tokens"');
await wait('window.__acme.length >= 1');
await b.evaluate('window.__holdBeta = true; location.hash = "#/orgs/beta/settings/limits"');
await wait('location.hash === "#/orgs/beta/settings/limits" && window.__beta.length >= 1');
// acme answers after the switch; then beta's read fails.
await b.evaluate('window.__acme.forEach(r => r())');
await new Promise(r => setTimeout(r, 400));
await b.evaluate('window.__beta.forEach(r => r())');
await wait('document.querySelector("#bus-view .banner")');
await new Promise(r => setTimeout(r, 400));
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/settings/limits');
assert.equal(await b.evaluate(`document.querySelector(${JSON.stringify(total)})?.value ?? null`), null, 'acme\'s held answer was drawn on beta');
assert.equal(await b.evaluate('!!document.querySelector("#bus-view .s1-stale")'), false);
assert.match(await b.evaluate('document.getElementById("bus-view").innerText'), /beta settings read failed/);
});
@@ -0,0 +1,263 @@
// SP5 (#1873, single pane slice 5): one Agents page for the whole system at #/agents. Every
// organization that answers adds its agents to one table: name, role, state, what it works on, its
// organization chip and a project chip when the work has a project. Filters by organization and state
// live in the hash query. Fire on a row goes to the row's own organization, never to the one opened
// last, and is offered only where that organization's own config says this Console decides. A stopped
// organization is named at the top with its reason. #/orgs/<id>/agents shows the same table, scoped.
// Every bus is a fake: acme and beta answer, gamma's bus is stopped. The real GET /api/workspace and
// the real per-organization routes serve the page.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
const HIRE = '0f3c1a2b-4d5e-4f60-8a7b-9c0d1e2f3a4b';
function fixture({ empty = false } = {}) {
const LIST = [
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
{ id: 'beta', label: 'Beta Works', theme: 'grove', busHealthy: true },
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false },
];
const DATA = {
acme: {
projects: [{ id: 'p-site', repo: 'site', name: 'Website', archived: false, at: at(30) }],
// A built-in store task assigned to coder, filed under the Website project.
tasks: [{ task_ref: 'store:1', source: 'store', at: at(20), fields: { title: 'Hero copy', state: 'in-progress', group: 'p-site', assignees: ['coder'] } }],
agents: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'working', at: at(40), working: { since: at(40), messages: 2 } }],
instances: { coder: { definition: 'coder', running: ['run-1'] }, chief: { definition: 'chief-of-staff', running: [] } },
},
beta: {
projects: [{ id: 'p-shop', repo: 'shop', name: 'Shop', archived: false, at: at(120) }],
tasks: [], agents: [{ role: 'pm', holder_run: 'run-9', harness: 'claude', state: 'waiting', at: at(15) }],
instances: { pm: { definition: 'pm', running: ['run-9'] }, 'research-2': { definition: `org:hire-${HIRE}`, hireDecision: HIRE, running: [], pack: { id: 'coding', label: 'Coding' } } },
},
};
if (empty) for (const d of Object.values(DATA)) { d.instances = {}; d.agents = []; }
const value = (id, name) => Promise.resolve(DATA[id]?.[name] ?? (['usage', 'limits'].includes(name) ? {} : []));
const opts = id => ({
bus: { inbox: () => value(id, 'inbox'), agents: () => value(id, 'agents'), 'thread.claims': () => value(id, 'claims'), tasks: () => value(id, 'tasks'), usage: () => value(id, 'usage'), limits: () => value(id, 'limits'), decisions: () => value(id, 'decisions') },
chat: { threads: () => value(id, 'threads'), projects: () => value(id, 'projects') },
});
const member = org => ({
id: org.id, doc: { appearance: { theme: org.theme } },
status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }),
options: () => opts(org.id),
});
return {
list: async () => LIST,
members: async () => LIST.map(member),
resolve: async id => {
const org = LIST.find(o => o.id === id); if (!org) return null;
if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, chat: { projects: async () => [], threads: async () => [] } };
return {
busHealthy: true,
reads: { business: async () => ({ business: { id, human: 'jason', projects: DATA[id].projects.map(p => p.repo), appearance: { theme: org.theme } } }), settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
bus: {
messages: async () => ({ messages: [], unread: 0 }), agents: async () => DATA[id].agents, 'thread.claims': async () => [], inbox: async () => [], tasks: async () => [],
instances: async () => ({ revision: 'a'.repeat(64), definitions: {}, instances: DATA[id].instances }),
},
chat: { projects: async () => DATA[id].projects, threads: async () => [] },
};
},
};
}
// Runs before the page's scripts, so display.js wraps it and it sees each request's scoped URL. Every
// organization's config says this Console decides there, except those named in `noDecide`; decision
// POSTs are recorded and answered from a queue, so no real write happens.
const stubFor = (noDecide = []) => `window.__noDecide = ${JSON.stringify(noDecide)};\n${STUB}`;
const STUB = `(() => {
const real = window.fetch.bind(window);
window.__posts = []; window.__answers = [];
const answer = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
window.fetch = async (url, init = {}) => {
const u = String(url);
if (/^\\/api\\/(?:orgs\\/[^/]+\\/)?config$/.test(u)) {
const c = await (await real(url, init)).json();
const org = (u.match(/^\\/api\\/orgs\\/([^/]+)\\//) || [])[1];
return answer(200, { ...c, send: true, decide: !window.__noDecide.includes(org) });
}
if (!u.includes('/decisions/')) return real(url, init);
window.__posts.push({ url: u, method: init.method, body: init.body });
const a = window.__answers.shift();
if (!a) throw new TypeError('no answer queued');
return answer(a.status ?? 200, a.body);
};
})();`;
async function setup(t, { viewport = [1440, 900], hash = '#/agents', empty = false, stub = false, noDecide = [] } = {}) {
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ empty }), log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
if (stub) await b.call('Page.addScriptToEvaluateOnNewDocument', { source: stubFor(noDecide) });
const base = `http://127.0.0.1:${server.address().port}`;
await b.navigate(`${base}/${hash}`);
return { b, base, wait: waitFor(b), text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) };
}
const rows = 'JSON.stringify([...document.querySelectorAll("[data-ws-agent]")].map(r => r.dataset.wsAgent))';
const are = list => `${rows} === ${JSON.stringify(JSON.stringify(list))}`;
const trail = '(document.getElementById("breadcrumbs").getClientRects().length ? document.getElementById("breadcrumbs").innerText.replace(/\\s+/g, " ").trim() : null)';
const ALL = ['acme:chief', 'acme:coder', 'beta:pm', 'beta:research-2'];
test('#/agents lists both organizations\' agents in one table, each row with its organization chip', async t => {
const { b, wait, text } = await setup(t);
await wait(are(ALL));
// A system route: the address keeps no organization and the sidebar Agents link is this page.
assert.equal(await b.evaluate('location.hash.split("?")[0]'), '#/agents');
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/agents');
assert.equal(await text('#bus-view h1'), 'Agents');
// SP7: the page name shows once, as the heading; a trail with nothing above it is not drawn.
assert.equal(await b.evaluate(trail), null);
assert.equal(await text('[data-ws-agent="acme:coder"] [data-ws-orgchip]'), 'Acme Studio');
assert.equal(await text('[data-ws-agent="beta:pm"] [data-ws-orgchip]'), 'Beta Works');
// State from the bus, and what the agent works on: its task, with the task's project chip.
assert.match(await text('[data-ws-agent="acme:coder"]'), /working/);
assert.match(await text('[data-ws-agent="beta:pm"]'), /waiting on you/);
assert.match(await text('[data-ws-agent="acme:coder"] [data-ws-work]'), /Hero copy/);
assert.equal(await text('[data-ws-agent="acme:coder"] [data-ws-projchip]'), 'Website');
assert.equal(await b.evaluate('document.querySelector(\'[data-ws-agent="beta:pm"] [data-ws-projchip]\')'), null);
// A hired agent reads by its name and role; the definition id stays as secondary text.
const hired = await b.evaluate('document.querySelector(\'[data-ws-agent="beta:research-2"] .t1\')?.firstChild?.textContent');
assert.equal(hired, 'research-2');
assert.match(await text('[data-ws-agent="beta:research-2"] [data-ws-role]'), /Hired.*Coding/);
assert.match(await text('[data-ws-agent="beta:research-2"] .t2'), new RegExp(`org:hire-${HIRE}`));
assert.match(await text('[data-ws-agent="acme:chief"] [data-ws-role]'), /Chief of staff/);
// Each row opens the agent in its own organization.
assert.equal(await b.evaluate('document.querySelector(\'[data-ws-agent="beta:pm"] a[data-ws-open]\')?.getAttribute("href")'), '#/orgs/beta/agents?agent=pm');
});
test('the organization and state filters live in the hash and survive a reload', async t => {
const { b, base, wait } = await setup(t);
await wait(are(ALL));
await b.evaluate('document.querySelector("[data-ws-agents] [data-ws-org=beta]").click()');
await wait(`location.hash.startsWith("#/agents?") && new URLSearchParams(location.hash.split("?")[1]).get("org") === "beta" && ${are(['beta:pm', 'beta:research-2'])}`);
await b.navigate(`${base}/${await b.evaluate('location.hash')}`);
await wait(`${are(['beta:pm', 'beta:research-2'])} && document.querySelector("[data-ws-org=beta]")?.getAttribute("aria-pressed") === "true"`);
// State: one chip per state the rows carry.
await b.evaluate('document.querySelector("[data-ws-agents] [data-ws-org=\'\']").click()');
await wait(are(ALL));
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-astate]")].map(x => x.dataset.wsAstate)'), ['', 'working', 'waiting', 'not-running']);
await b.evaluate('document.querySelector("[data-ws-astate=not-running]").click()');
await wait(`new URLSearchParams(location.hash.split("?")[1]).get("state") === "not-running" && ${are(['acme:chief', 'beta:research-2'])}`);
await b.navigate(`${base}/${await b.evaluate('location.hash')}`);
await wait(`${are(['acme:chief', 'beta:research-2'])} && document.querySelector("[data-ws-astate=not-running]")?.getAttribute("aria-pressed") === "true"`);
// A value the page does not know is dropped, never read as a filter.
await b.evaluate('location.hash = "#/agents?state=bogus&org=Not%20An%20Org"');
await wait(are(ALL));
await b.evaluate('location.hash = "#/agents?org=beta&state=working"');
await wait('document.querySelector("[data-ws-agent-list]")?.textContent === "Nothing matches these filters"');
});
test('firing beta\'s agent from #/agents while acme was opened last reaches beta', async t => {
const { b, wait, text } = await setup(t, { hash: '#/orgs/acme/organization', stub: true });
await wait('document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio"');
await b.evaluate('location.hash = "#/agents"');
await wait(`${are(ALL)} && document.querySelector('[data-ws-agent="beta:pm"] [data-agent-fire]')`);
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'acme');
// Never on the chief.
assert.equal(await b.evaluate('document.querySelector(\'[data-ws-agent="acme:chief"] [data-agent-fire]\')'), null);
await b.evaluate('document.querySelector(\'[data-ws-agent="beta:pm"] [data-agent-fire]\').click()');
await wait('document.querySelector(\'[data-ws-agent="beta:pm"] [data-agent-fire-yes]\')');
await b.evaluate('window.__answers.push({ body: { id: "dec-fire-1", op: "resolved", choice: "yes" } })');
await b.evaluate('document.querySelector(\'[data-ws-agent="beta:pm"] [data-agent-fire-yes]\').click()');
await wait('/Fired pm/.test(document.querySelector("[data-ws-agents] [data-agents-receipt]")?.textContent ?? "")');
// The receipt names the organization by its label, not its id.
assert.match(await text('[data-ws-agents] [data-agents-receipt]'), /^Fired pm in Beta Works\./);
const posts = await b.evaluate('window.__posts');
assert.deepEqual(posts.map(p => p.url), ['/api/orgs/beta/decisions/hire/start']);
assert.deepEqual(JSON.parse(posts[0].body), { business: 'beta', hire: { op: 'fire', level: 'org', name: 'pm', reason: 'Fired from the Agents page.' } });
assert.match(await text('[data-ws-agents] [data-agents-receipt]'), /dec-fire-1/);
assert.equal(await b.evaluate('location.hash.split("?")[0]'), '#/agents');
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'acme');
});
test('Fire follows each organization\'s own config, not the organization opened last', async t => {
// Acme is opened last and this Console decides there; beta's own config says it does not.
const { b, wait } = await setup(t, { hash: '#/orgs/acme/organization', stub: true, noDecide: ['beta'] });
await wait('document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio"');
await b.evaluate('location.hash = "#/agents"');
await wait(`${are(ALL)} && document.querySelector('[data-ws-agent="acme:coder"] [data-agent-fire]')`);
assert.equal(await b.evaluate('document.querySelector(\'[data-ws-agent="beta:pm"] [data-agent-fire]\')'), null);
assert.equal(await b.evaluate('document.querySelector(\'[data-ws-agent="beta:research-2"] [data-agent-fire]\')'), null);
});
test('a stopped organization is named at the top with its reason', async t => {
const { b, wait, text } = await setup(t);
await wait(are(ALL));
const note = await text('[data-ws-unread]');
assert.match(note, /Gamma Home/);
assert.match(note, /stopped by the owner/);
assert.equal(await b.evaluate('!!(document.querySelector("[data-ws-unread]").compareDocumentPosition(document.querySelector("[data-ws-agent-list]")) & Node.DOCUMENT_POSITION_FOLLOWING)'), true);
});
test('with no agents anywhere the table says so and still names the stopped organization', async t => {
const { wait, text } = await setup(t, { empty: true });
await wait('document.querySelector("[data-ws-agent-list]")');
assert.equal(await text('[data-ws-agent-list]'), 'No agents');
assert.match(await text('[data-ws-unread]'), /Gamma Home.*stopped by the owner/s);
});
test('#/orgs/<id>/agents shows that organization\'s rows only, with a link to every organization', async t => {
const { b, wait, text } = await setup(t, { hash: '#/orgs/beta/agents' });
await wait(are(['beta:pm', 'beta:research-2']));
assert.match(await text('[data-ws-agents] .sub'), /Beta Works/);
assert.equal(await b.evaluate('document.querySelector("[data-ws-agents] a[href=\'#/agents\']") !== null'), true);
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/agents');
// SP7: a drill-in keeps its trail back to the dashboard and the organization.
await wait(`${trail} === 'Dashboard / Beta Works / Agents'`);
// The organization's own levels grid and held roles still follow, under the one page heading.
await wait('document.querySelector("[data-org-agents]")');
assert.equal(await b.evaluate('document.querySelectorAll("#bus-view h1").length'), 1);
});
test('Open addresses the agent: the scoped page puts it first, marks it and draws no Open of its own', async t => {
const { b, wait } = await setup(t);
await wait(are(ALL));
assert.equal(await b.evaluate('document.querySelector(\'[data-ws-agent="beta:research-2"] [data-ws-open]\').getAttribute("href")'), '#/orgs/beta/agents?agent=research-2');
await b.evaluate('document.querySelector(\'[data-ws-agent="beta:research-2"] [data-ws-open]\').click()');
await wait(are(['beta:research-2', 'beta:pm']));
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/agents?agent=research-2');
assert.equal(await b.evaluate('document.querySelector(\'[data-ws-agent="beta:research-2"]\').getAttribute("aria-current")'), 'true');
assert.equal(await b.evaluate('document.querySelector(\'[data-ws-agent="beta:pm"]\').hasAttribute("aria-current")'), false);
// No self-link on the scoped page.
assert.equal(await b.evaluate('document.querySelectorAll("[data-ws-agents] [data-ws-open]").length'), 0);
assert.equal(await b.evaluate('document.querySelectorAll("[data-ws-agents] thead th").length'), 4);
// An agent the organization does not have marks nothing.
await b.evaluate('location.hash = "#/orgs/beta/agents?agent=nobody"');
await wait(`${are(['beta:pm', 'beta:research-2'])} && !document.querySelector('[data-ws-agents] [aria-current]')`);
});
test('Cancel puts focus back on the row\'s Fire, which is labelled with the organization\'s name', async t => {
const { b, wait } = await setup(t, { stub: true });
await wait(`${are(ALL)} && document.querySelector('[data-ws-agent="beta:pm"] [data-agent-fire]')`);
const fire = '\'[data-ws-agent="beta:pm"] [data-agent-fire]\'';
assert.equal(await b.evaluate(`document.querySelector(${fire}).getAttribute('aria-label')`), 'Fire pm in Beta Works');
await b.evaluate(`document.querySelector(${fire}).click()`);
await wait('document.querySelector(\'[data-ws-agent="beta:pm"] [data-agent-fire-no]\')');
assert.equal(await b.evaluate('document.querySelector(\'[data-ws-agent="beta:pm"] [data-agent-fire-confirm]\').getAttribute("aria-label")'), 'Fire pm in Beta Works?');
await b.evaluate('document.querySelector(\'[data-ws-agent="beta:pm"] [data-agent-fire-no]\').click()');
await wait(`document.activeElement === document.querySelector(${fire})`);
assert.deepEqual(await b.evaluate('window.__posts'), []);
});
test('a picked agent stays in the address through the state filter, and a scope that is not an organization id is refused', async t => {
const { b, wait } = await setup(t, { hash: '#/orgs/beta/agents?agent=research-2' });
await wait(`${are(['beta:research-2', 'beta:pm'])} && document.querySelector('[data-ws-agents] [data-ws-astate="waiting"]')`);
await b.evaluate('document.querySelector(\'[data-ws-agents] [data-ws-astate="waiting"]\').click()');
await wait(are(['beta:pm']));
const q = new URLSearchParams((await b.evaluate('location.hash')).split('?')[1]);
assert.equal(q.get('agent'), 'research-2');
assert.equal(q.get('state'), 'waiting');
assert.equal(await b.evaluate('document.querySelector("[data-ws-agents] [aria-current]")'), null);
await b.evaluate('document.querySelector(\'[data-ws-agents] [data-ws-astate=""]\').click()');
await wait(`${are(['beta:research-2', 'beta:pm'])} && document.querySelector('[data-ws-agent="beta:research-2"][aria-current="true"]')`);
const refused = await b.evaluate('window.MosaicWorkspace.agentsPage(new URLSearchParams(), { scope: "../beta" })');
assert.match(refused, /data-ws-failed/);
assert.doesNotMatch(refused, /data-ws-agent=/);
});
@@ -0,0 +1,265 @@
// SP3 (#1873, single pane slice 3): one Inbox for the whole system at #/inbox. Every organization
// that answers adds its items to one list, newest first, each row with its organization chip and a
// project chip when it has one. Filters by organization and type live in the hash query. An answer
// given from the list goes to the row's own organization, never to the one opened last. A stopped
// organization is named at the top with its reason. #/orgs/<id>/inbox is the same list, filtered.
// Every bus is a fake: acme and beta answer, gamma's bus is stopped. The real GET /api/workspace
// and the real per-organization routes serve the page.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
const ACME_DECISION = 'dec-acme-1';
const BETA_DECISION = 'dec-beta-1';
const DIGEST = 'd'.repeat(64);
function fixture({ empty = false } = {}) {
const LIST = [
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
{ id: 'beta', label: 'Beta Works', theme: 'grove', busHealthy: true },
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false },
];
const DATA = {
acme: {
projects: [{ id: 'p-site', repo: 'site', name: 'Website', archived: false, at: at(30) }],
tasks: [{ task_ref: 'local:1', project_key: 'site', at: at(20), fields: { title: 'Hero copy', done: false, bucket: 'Doing' } }],
agents: [{ role: 'coder', holder_run: 'run-1', harness: 'claude', state: 'working', at: at(40), working: { since: at(40) } }],
inbox: [{ id: ACME_DECISION, question: 'Ship the hero?', class: 'gated', blocking: true, raised_by_role: 'coder', task_ref: 'local:1', at: at(10), options: [{ key: 'yes', text: 'Ship it' }, { key: 'no', text: 'Hold' }] }],
},
beta: {
projects: [{ id: 'p-shop', repo: 'shop', name: 'Shop', archived: false, at: at(120) }],
tasks: [], agents: [{ role: 'pm', holder_run: 'run-9', harness: 'claude', state: 'waiting', at: at(15) }],
// Eligible for an answer in the Console: the bus marks it with its `console` field.
inbox: [{ id: BETA_DECISION, authorization: { action: 'x.y', target: 'shop', approvalChoice: 'high' }, question: 'Pick a launch price', class: 'within-role', blocking: false, raised_by_role: 'pm', at: at(5), options: [{ key: 'low', text: 'Low' }, { key: 'high', text: 'High' }], console: { kind: 'decision', options: [{ key: 'low', text: 'Low' }, { key: 'high', text: 'High' }], digest: DIGEST } }],
},
};
if (empty) { DATA.acme.inbox = []; DATA.beta.inbox = []; }
const value = (id, name) => Promise.resolve(DATA[id]?.[name] ?? (['usage', 'limits'].includes(name) ? {} : []));
const opts = id => ({
bus: { inbox: () => value(id, 'inbox'), agents: () => value(id, 'agents'), 'thread.claims': () => value(id, 'claims'), tasks: () => value(id, 'tasks'), usage: () => value(id, 'usage'), limits: () => value(id, 'limits'), decisions: () => value(id, 'decisions') },
chat: { threads: () => value(id, 'threads'), projects: () => value(id, 'projects') },
});
const member = org => ({
id: org.id, doc: { appearance: { theme: org.theme } },
status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }),
options: () => opts(org.id),
});
return {
list: async () => LIST,
members: async () => LIST.map(member),
resolve: async id => {
const org = LIST.find(o => o.id === id); if (!org) return null;
if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, chat: { projects: async () => [], threads: async () => [] } };
return {
busHealthy: true,
reads: { business: async () => ({ business: { id, human: 'jason', projects: DATA[id].projects.map(p => p.repo), appearance: { theme: org.theme } } }), settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
// The broker's inbox row: the decisions row, so `route_to`, plus `authorization`.
bus: { messages: async () => ({ messages: [], unread: 0 }), agents: async () => [], 'thread.claims': async () => [], inbox: async () => DATA[id].inbox.map(d => ({ ...d, business: id, raised_by_run: 'run', route_to: 'human', authorization: d.authorization ?? null })), tasks: async () => [], instances: async () => ({ business: id, instances: {} }) },
chat: { projects: async () => DATA[id].projects, threads: async () => [] },
};
},
};
}
// Runs before the page's scripts, so display.js wraps it and it sees each request's scoped URL. Every
// organization's config says this Console answers decisions, except those named in `noDecide`;
// decision POSTs are recorded and answered from a queue, so no real write happens.
const stubFor = (noDecide = []) => `window.__noDecide = ${JSON.stringify(noDecide)};\n${STUB}`;
const STUB = `(() => {
const real = window.fetch.bind(window);
window.__posts = []; window.__answers = [];
const answer = (status, body) => new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
window.fetch = async (url, init = {}) => {
const u = String(url);
if (/^\\/api\\/(?:orgs\\/[^/]+\\/)?config$/.test(u)) {
const c = await (await real(url, init)).json();
const org = (u.match(/^\\/api\\/orgs\\/([^/]+)\\//) || [])[1];
return answer(200, { ...c, send: true, decide: !window.__noDecide.includes(org) });
}
if (!u.includes('/decisions/')) return real(url, init);
window.__posts.push({ url: u, method: init.method, body: init.body });
const a = window.__answers.shift();
if (!a) throw new TypeError('no answer queued');
return answer(a.status ?? 200, a.body);
};
})();`;
async function setup(t, { viewport = [1440, 900], hash = '#/inbox', empty = false, stub = false, noDecide = [] } = {}) {
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: fixture({ empty }), log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
if (stub) await b.call('Page.addScriptToEvaluateOnNewDocument', { source: stubFor(noDecide) });
const base = `http://127.0.0.1:${server.address().port}`;
await b.navigate(`${base}/${hash}`);
return { b, base, wait: waitFor(b), text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) };
}
const trail = '(document.getElementById("breadcrumbs").getClientRects().length ? document.getElementById("breadcrumbs").innerText.replace(/\\s+/g, " ").trim() : null)';
const items = 'JSON.stringify([...document.querySelectorAll("[data-ws-item]")].map(r => r.dataset.wsItem))';
test('#/inbox lists both organizations in one list, newest first, each row with its organization and project chips', async t => {
const { b, wait, text } = await setup(t);
await wait(`${items} === ${JSON.stringify(JSON.stringify([`beta:${BETA_DECISION}`, `acme:${ACME_DECISION}`]))}`);
// A system route: the address keeps no organization and the sidebar Inbox is this page.
assert.equal(await b.evaluate('location.hash.split("?")[0]'), '#/inbox');
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/inbox');
assert.equal(await text('#bus-view h1'), 'Inbox');
// SP7: the page name shows once, as the heading.
assert.equal(await b.evaluate(trail), null);
// Organization chips on every row; the project chip only where the item has a project.
assert.equal(await text(`[data-ws-item="acme:${ACME_DECISION}"] [data-ws-orgchip]`), 'Acme Studio');
assert.equal(await text(`[data-ws-item="beta:${BETA_DECISION}"] [data-ws-orgchip]`), 'Beta Works');
assert.equal(await text(`[data-ws-item="acme:${ACME_DECISION}"] [data-ws-projchip]`), 'Website');
assert.equal(await b.evaluate(`document.querySelector('[data-ws-item="beta:${BETA_DECISION}"] [data-ws-projchip]')`), null);
// SP7: the class chip says the decision class in words, from the one map of class words.
assert.deepEqual(await b.evaluate(`[...document.querySelectorAll('[data-ws-item]')].map(r => r.querySelector('td.hide-m .ws-chip')?.textContent)`), ['Within role', 'Gated']);
// The stopped organization is named at the top, before the list, with its reason.
const note = await text('[data-ws-unread]');
assert.match(note, /Gamma Home/);
assert.match(note, /stopped by the owner/);
assert.equal(await b.evaluate('!!(document.querySelector("[data-ws-unread]").compareDocumentPosition(document.querySelector("[data-ws-items]")) & Node.DOCUMENT_POSITION_FOLLOWING)'), true);
// The sidebar Inbox count and the dashboard read the same figure.
await wait('document.querySelector("#sections a[href=\'#/inbox\'] .ws-n")?.textContent === "2"');
await b.evaluate('location.hash = "#/dashboard"');
await wait('document.querySelector("[data-ws-tile=needs]")');
assert.match(await text('[data-ws-tile=needs]'), /Needs you\s*2\s*items/i);
const needs = await b.evaluate('[...document.querySelectorAll("[data-ws-needs] a.q")].map(a => a.getAttribute("href"))');
assert.ok(needs.includes(`#/inbox?d=${encodeURIComponent(`beta:${BETA_DECISION}`)}`), JSON.stringify(needs));
assert.ok(await b.evaluate('[...document.querySelectorAll("[data-ws-home] a")].some(a => a.getAttribute("href") === "#/inbox")'));
});
test('the organization and type filters live in the hash and survive a reload', async t => {
const { b, base, wait } = await setup(t);
await wait('document.querySelectorAll("[data-ws-item]").length === 2');
await b.evaluate('document.querySelector("[data-ws-org=beta]").click()');
await wait(`location.hash.startsWith("#/inbox?") && new URLSearchParams(location.hash.split("?")[1]).get("org") === "beta" && ${items} === ${JSON.stringify(JSON.stringify([`beta:${BETA_DECISION}`]))}`);
const filtered = await b.evaluate('location.hash');
await b.navigate(`${base}/${filtered}`);
await wait(`${items} === ${JSON.stringify(JSON.stringify([`beta:${BETA_DECISION}`]))} && document.querySelector("[data-ws-org=beta]")?.getAttribute("aria-pressed") === "true"`);
// Type: the classes the read carries, each a chip; choosing one narrows the list.
await b.evaluate('document.querySelector("[data-ws-org=\'\']").click()');
await wait('document.querySelectorAll("[data-ws-item]").length === 2');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-type]")].map(x => x.dataset.wsType)'), ['', 'gated', 'within-role']);
await b.evaluate('document.querySelector("[data-ws-type=gated]").click()');
await wait(`new URLSearchParams(location.hash.split("?")[1]).get("type") === "gated" && ${items} === ${JSON.stringify(JSON.stringify([`acme:${ACME_DECISION}`]))}`);
await b.navigate(`${base}/${await b.evaluate('location.hash')}`);
await wait(`${items} === ${JSON.stringify(JSON.stringify([`acme:${ACME_DECISION}`]))} && document.querySelector("[data-ws-type=gated]")?.getAttribute("aria-pressed") === "true"`);
// Both at once with nothing left says so plainly.
await b.evaluate('location.hash = "#/inbox?org=beta&type=gated"');
await wait('document.querySelector("[data-ws-items]")?.textContent === "Nothing matches these filters"');
});
test('answering beta\'s row from the list while acme was opened last reaches beta', async t => {
const { b, wait, text } = await setup(t, { hash: '#/orgs/acme/organization', stub: true });
await wait('document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio"');
await b.evaluate('location.hash = "#/inbox"');
await wait('document.querySelectorAll("[data-ws-item]").length === 2');
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'acme');
await b.evaluate(`document.querySelector('[data-ws-select="beta:${BETA_DECISION}"]').click()`);
await wait(`document.querySelector("[data-ws-insp]")?.dataset.wsInsp === "beta:${BETA_DECISION}" && document.querySelector("#decide-section [data-decide]")`);
assert.equal(await text('[data-ws-insp] header .ws-chip'), 'Within role');
// The item also opens in its own organization.
assert.equal(await b.evaluate('document.querySelector("[data-ws-insp] [data-ws-open]")?.getAttribute("href")'), `#/orgs/beta/inbox/${BETA_DECISION}`);
await b.evaluate(`window.__answers.push({ body: { id: '${BETA_DECISION}', action: 'answer', choice: 'high', text: 'High', confirmation: 'c-1', kind: 'decision' } }, { body: { id: '${BETA_DECISION}', op: 'resolved', choice: 'high' } })`);
await b.evaluate('[...document.querySelectorAll("#decide-section [data-decide]")].find(x => x.textContent === "High").click()');
await wait('document.querySelector("#decide-section [data-decide=confirm]")');
// The confirm step names who raised the item, from beta's bus row, as the decision page does.
const confirm = await text('#decide-section');
assert.match(confirm, /Raised by pm · run run/);
assert.match(confirm, /Decision routed to: human/);
assert.doesNotMatch(confirm, /date unknown/);
assert.match(confirm, /Affected object: shop/);
await b.evaluate('document.querySelector("#decide-section [data-decide=confirm]").click()');
await wait('/Recorded/.test(document.getElementById("decide-status")?.textContent ?? "")');
const posts = await b.evaluate('window.__posts');
assert.deepEqual(posts.map(p => p.url), [`/api/orgs/beta/decisions/${BETA_DECISION}/confirmation`, `/api/orgs/beta/decisions/${BETA_DECISION}/resolve`]);
assert.deepEqual(JSON.parse(posts[1].body), { choice: 'high', confirmation: 'c-1' });
// Still a system route, still scoped to acme for everything else.
assert.equal(await b.evaluate('location.hash.split("?")[0]'), '#/inbox');
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'acme');
});
test('#/orgs/<id>/inbox is the same list filtered to that organization', async t => {
const { b, wait, text } = await setup(t, { hash: '#/orgs/beta/inbox' });
await wait(`${items} === ${JSON.stringify(JSON.stringify([`beta:${BETA_DECISION}`]))}`);
assert.match(await text('[data-ws-inbox] .sub'), /Beta Works/);
assert.equal(await b.evaluate('document.querySelector("[data-ws-inbox] a[href=\'#/inbox\']") !== null'), true);
// SP7: a drill-in keeps its trail.
await wait(`${trail} === 'Dashboard / Beta Works / Inbox'`);
// Selecting a row keeps the organization address.
await b.evaluate(`document.querySelector('[data-ws-select="beta:${BETA_DECISION}"]').click()`);
await wait(`location.hash.startsWith("#/orgs/beta/inbox?") && document.querySelector("[data-ws-insp]")?.dataset.wsInsp === "beta:${BETA_DECISION}"`);
});
test('with nothing waiting the list says so and still names the stopped organization', async t => {
const { wait, text } = await setup(t, { empty: true });
await wait('document.querySelector("[data-ws-items]")');
assert.equal(await text('[data-ws-items]'), 'Nothing needs you');
assert.match(await text('[data-ws-unread]'), /Gamma Home.*stopped by the owner/s);
});
test('the hire, fire and change form is reached by clicks from #/inbox, one link per answering organization', async t => {
const { b, wait } = await setup(t, { stub: true });
await wait('document.querySelector("[data-ws-hire-in]")');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-hire-in] a")].map(a => [a.textContent, a.getAttribute("href")])'), [['Acme Studio', '#/orgs/acme/inbox'], ['Beta Works', '#/orgs/beta/inbox']]);
// The system list has no form of its own: a hire goes to one organization's bus.
assert.equal(await b.evaluate('document.getElementById("hire-start")'), null);
await b.evaluate('[...document.querySelectorAll("[data-ws-hire-in] a")].find(a => a.textContent === "Beta Works").click()');
await wait('location.hash === "#/orgs/beta/inbox" && document.getElementById("hire-start")');
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'beta');
assert.equal(await b.evaluate('document.querySelector("#hire-start input[readonly]")?.value'), 'beta');
});
test('the hire links follow each organization\'s own config, not the organization opened last', async t => {
// Acme is opened last and this Console does not decide there; beta's config still says it does.
const { b, wait } = await setup(t, { hash: '#/orgs/acme/organization', stub: true, noDecide: ['acme'] });
await wait('document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio"');
await b.evaluate('location.hash = "#/inbox"');
await wait('document.querySelector("[data-ws-hire-in]")');
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'acme');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-hire-in] a")].map(a => a.getAttribute("href"))'), ['#/orgs/beta/inbox']);
});
test('with no organization deciding here, #/inbox shows no hire line', async t => {
const { b, wait } = await setup(t, { stub: true, noDecide: ['acme', 'beta'] });
await wait('document.querySelectorAll("[data-ws-item]").length === 2');
assert.equal(await b.evaluate('document.querySelector("[data-ws-hire-in]")'), null);
});
test('the sidebar Inbox count on an organization\'s board is every organization\'s, as #/inbox lists', async t => {
const { b, wait } = await setup(t, { hash: '#/orgs/acme/board' });
await wait('document.querySelector("#sections a[href$=\'/inbox\'] .ws-n")?.textContent === "2"');
// Held across a second board render, which reads only acme's inbox.
const reads = 'performance.getEntriesByType("resource").filter(e => new URL(e.name).pathname === "/api/orgs/acme/bus/inbox").length';
const before = await b.evaluate(reads);
assert.ok(before >= 1, String(before));
await b.evaluate('window.dispatchEvent(new HashChangeEvent("hashchange"))');
await wait(`${reads} > ${before}`);
await new Promise(r => setTimeout(r, 200));
assert.equal(await b.evaluate('document.querySelector("#sections a[href$=\'/inbox\'] .ws-n")?.textContent'), '2');
});
// SP2 gave the system dashboard the system theme. #/inbox is a system page too: it shows the system
// theme, and a choice made there is the system's own, never written to the organization opened last.
test('#/inbox keeps the system theme, and a choice made there stays off the organization opened last', async t => {
const { b, wait } = await setup(t, { hash: '#/orgs/acme/organization' });
await wait('document.documentElement.dataset.palette === "cobalt"');
await b.evaluate('location.hash = "#/inbox"');
await wait(`${items} !== "[]" && document.documentElement.dataset.palette === "harbor"`);
assert.equal(await b.evaluate('window.MosaicAppearance.state().organization'), null);
assert.equal(await b.evaluate('document.getElementById("org-cue").hidden'), true);
await b.evaluate('window.MosaicAppearance.set({ mode: "light" })');
assert.equal(await b.evaluate('document.documentElement.dataset.mode'), 'light');
assert.equal(await b.evaluate('localStorage.getItem("mosaic-console-appearance:acme")'), null);
// The organization's own Inbox is its page: its theme, and not the system's choice.
await b.evaluate('location.hash = "#/orgs/acme/inbox"');
await wait('document.documentElement.dataset.palette === "cobalt"');
assert.notEqual(await b.evaluate('document.documentElement.dataset.mode'), 'light');
await b.evaluate('location.hash = "#/inbox"');
await wait('document.documentElement.dataset.palette === "harbor" && document.documentElement.dataset.mode === "light"');
});
@@ -0,0 +1,308 @@
// SP4 (#1873, single pane slice 4): one task board for the whole system at #/tasks. Every
// organization that answers adds its tasks to one board, in the per-organization page's columns,
// each card with its organization chip and its project chip. The organization and project filters
// live in the hash query. A move goes to the row's own organization, offered only where that
// organization's own config takes task changes, never judged by the organization opened last.
// A stopped organization is named at the top with its reason. #/orgs/<id>/tasks is the same board,
// scoped to one organization, and a card opened from the system board opens there.
// Every bus is a fake: acme and beta keep their tasks in the built-in store, gamma's bus is stopped.
// The real GET /api/workspace and the real POST /api/workspace/tasks serve the page.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { startServer } from '../src/serve.mjs';
import { createDevOwner } from '../src/dev-owner.mjs';
import { browser } from './browser.mjs';
import { close } from './fixture.mjs';
const waitFor = b => expression => b.evaluate(`(async()=>{for(let i=0;i<200;i++){if(${expression})return;await new Promise(r=>setTimeout(r,30))}throw Error(${JSON.stringify(expression)})})()`);
const at = minutesAgo => new Date(Date.now() - minutesAgo * 60000).toISOString();
const D = n => String(n).repeat(64);
function fixture({ empty = false, archived = [] } = {}) {
const LIST = [
{ id: 'acme', label: 'Acme Studio', theme: 'cobalt', busHealthy: true },
{ id: 'beta', label: 'Beta Works', theme: 'grove', busHealthy: true },
{ id: 'gamma', label: 'Gamma Home', theme: 'rosewood', busHealthy: false },
];
const PROJECTS = {
acme: [{ id: 'site', repo: 'site', name: 'Website', archived: false, at: at(30) }],
beta: [{ id: 'shop', repo: 'shop', name: 'Shop', archived: false, at: at(60) }, { id: 'ads', repo: 'ads', name: 'Ads', archived: false, at: at(90) }],
};
const STORE = {
acme: [{ n: 1, title: 'Hero copy', state: 'todo', group: 'site', assignees: ['coder'] }],
beta: [{ n: 2, title: 'Price page', state: 'in-progress', group: 'shop', assignees: [] }, { n: 3, title: 'Spring banner', state: 'todo', group: 'ads', assignees: [] }],
};
if (empty) { STORE.acme = []; STORE.beta = []; }
for (const [org, list] of Object.entries(PROJECTS)) for (const p of list) p.archived = archived.includes(`${org}:${p.id}`);
const tasks = id => (STORE[id] || []).map(t => ({ source: 'store', task_ref: `task:${t.n}`, at: at(10), priority: 0, digest: D(t.n), requirement: 'REQ-WEB-1',
fields: { title: t.title, state: t.state, group: t.group, assignees: t.assignees, due_date: null } }));
const writes = [];
const taskWrite = org => async (verb, args) => { writes.push([org, verb, args]); return { task_ref: args.task_ref, digest: D(9) }; };
const opts = id => ({
bus: { inbox: async () => [], agents: async () => [], 'thread.claims': async () => [], tasks: async () => tasks(id), messages: async () => ({ messages: [], unread: 0 }) },
chat: { projects: async () => PROJECTS[id] || [], threads: async () => [] },
});
const member = org => ({
id: org.id, doc: { appearance: { theme: org.theme }, roles: { coder: {} } },
status: async () => (org.busHealthy ? { healthy: true, pid: 4242, boot: null } : { healthy: false, boot: { ok: false, at: at(90), lastGood: null, reason: 'stopped by the owner' } }),
options: () => opts(org.id),
});
return {
writes,
list: async () => LIST,
members: async () => LIST.map(member),
resolve: async id => {
const org = LIST.find(o => o.id === id); if (!org) return null;
if (!org.busHealthy) return { busHealthy: false, reads: null, bus: {}, chat: { projects: async () => [], threads: async () => [] }, taskWrite: taskWrite(id) };
return {
busHealthy: true,
reads: { business: async () => ({ business: { id, human: 'jason', projects: PROJECTS[id].map(p => p.repo), appearance: { theme: org.theme } } }), settings: async () => ({}), queue: async () => ({ rows: [] }), busStatus: async () => ({}) },
...opts(id),
bus: { ...opts(id).bus, instances: async () => ({ business: id, instances: {} }) },
taskWrite: taskWrite(id),
};
},
};
}
// Runs before the page's scripts, so display.js wraps it and it sees each request's scoped URL.
// Every organization's config says this Console takes task changes, except those named in `noWrite`.
// The real server sets orgSetup for the whole Console, so this per-organization difference is faked:
// it proves the board asks each row's own organization, which matters where one config read fails.
const STUB = noWrite => `window.__noWrite = ${JSON.stringify(noWrite)};
(() => {
const real = window.fetch.bind(window);
window.fetch = async (url, init = {}) => {
const u = String(url);
if (!/^\\/api\\/(?:orgs\\/[^/]+\\/)?config$/.test(u)) return real(url, init);
const c = await (await real(url, init)).json();
const org = (u.match(/^\\/api\\/orgs\\/([^/]+)\\//) || [])[1];
return new Response(JSON.stringify({ ...c, orgSetup: c.orgSetup === true && !window.__noWrite.includes(org) }), { status: 200, headers: { 'content-type': 'application/json' } });
};
})();`;
async function setup(t, { viewport = [1440, 900], hash = '#/tasks', empty = false, noWrite = [], archived = [] } = {}) {
const orgs = fixture({ empty, archived });
const server = await startServer({ port: 0, sso: createDevOwner(), organizations: orgs, send: async () => ({}), log: () => {} });
t.after(() => close(server));
const b = await browser({ machine: false, args: ['--disable-extensions'] }); t.after(() => b.close());
await b.viewport(...viewport);
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: STUB(noWrite) });
const base = `http://127.0.0.1:${server.address().port}`;
await b.navigate(`${base}/${hash}`);
return { b, base, orgs, wait: waitFor(b), text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) };
}
const trail = '(document.getElementById("breadcrumbs").getClientRects().length ? document.getElementById("breadcrumbs").innerText.replace(/\\s+/g, " ").trim() : null)';
const cards = 'JSON.stringify([...document.querySelectorAll("[data-tasks-board] [data-tb-task]")].map(e => e.dataset.tbTask).sort())';
const ALL = JSON.stringify(JSON.stringify(['acme|task:1', 'beta|task:2', 'beta|task:3']));
const BETA = JSON.stringify(JSON.stringify(['beta|task:2', 'beta|task:3']));
test('#/tasks shows both organizations\' tasks on one board, each card with its organization and project chips', async t => {
const { b, wait, text } = await setup(t);
await wait(`${cards} === ${ALL}`);
// A system route: the address keeps no organization and the sidebar Tasks is this page.
assert.equal(await b.evaluate('location.hash'), '#/tasks');
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/tasks');
assert.equal(await text('#bus-view h1'), 'Tasks');
// SP7: the page name shows once, as the heading.
assert.equal(await b.evaluate(trail), null);
// The per-organization page's columns.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll(".tb-col h3")].map(h => h.textContent)'), ['To do', 'In progress', 'Review', 'Blocked', 'Done']);
// One chip names the organization, with its avatar in place of the dot.
assert.equal(await b.evaluate('[...document.querySelectorAll(\'[data-tb-task="acme|task:1"] [data-ws-orgchip]\')].map(c => [!!c.querySelector(".ws-av"), c.lastChild.textContent]).join("|")'), 'true,Acme Studio');
assert.equal(await b.evaluate('[...document.querySelectorAll(\'[data-tb-task="beta|task:2"] [data-ws-orgchip]\')].map(c => [!!c.querySelector(".ws-av"), c.lastChild.textContent]).join("|")'), 'true,Beta Works');
assert.equal(await text('[data-tb-task="acme|task:1"] [data-ws-projchip]'), 'Website');
assert.equal(await text('[data-tb-task="beta|task:3"] [data-ws-projchip]'), 'Ads');
assert.equal(await b.evaluate('document.getElementById("bus-down").hidden'), true);
// The first load draws the board once, with no "last read failed" banner from a render the next one replaced.
assert.equal(await b.evaluate('document.querySelector("#bus-view .s1-stale")'), null);
});
test('the organization and project filters live in the address and survive a reload', async t => {
const { b, base, wait } = await setup(t);
await wait(`${cards} === ${ALL}`);
await b.evaluate('document.querySelector("[data-tb-org=beta]").click()');
await wait(`location.hash === "#/tasks?org=beta" && ${cards} === ${BETA}`);
await b.evaluate('(() => { const s = document.querySelector("[data-tb-filter=project]"); s.value = "beta:shop"; s.dispatchEvent(new Event("change", { bubbles: true })); })()');
await wait(`location.hash === "#/tasks?org=beta&project=beta%3Ashop" && ${cards} === ${JSON.stringify(JSON.stringify(['beta|task:2']))}`);
await b.navigate(`${base}/?reload=1#/tasks?org=beta&project=beta%3Ashop`);
await wait(`${cards} === ${JSON.stringify(JSON.stringify(['beta|task:2']))}`);
assert.equal(await b.evaluate('document.querySelector("[data-tb-org=beta]").getAttribute("aria-pressed")'), 'true');
assert.equal(await b.evaluate('document.querySelector("[data-tb-filter=project]").value'), 'beta:shop');
// A hand-edited value that is not an organization id or a project is ignored, not read as a filter.
await b.navigate(`${base}/?reload=2#/tasks?org=Not%20An%20Id&project=nope`);
await wait(`${cards} === ${ALL}`);
assert.equal(await b.evaluate('document.querySelector("[data-tb-org=\'\']").getAttribute("aria-pressed")'), 'true');
// An organization or project that is not on the list falls back to all, and the address drops it.
await b.navigate(`${base}/?reload=3#/tasks?org=gone&project=beta%3Agone`);
await wait(`${cards} === ${ALL} && location.hash === "#/tasks"`);
});
test('a move on beta\'s row while acme was opened last reaches beta, and acme\'s own config keeps its rows read only', async t => {
const { b, wait, orgs } = await setup(t, { hash: '#/orgs/acme/organization', noWrite: ['acme'] });
await wait('document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio"');
await b.evaluate('location.hash = "#/tasks"');
await wait(`${cards} === ${ALL}`);
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'acme');
await b.evaluate('document.querySelector("[data-tb-layout=list]").click()');
await wait('document.querySelector("[data-tb-move=\'beta|task:2\']")');
// Acme's config takes no task changes, so its row has no State control and its card does not drag.
assert.equal(await b.evaluate('document.querySelector("[data-tb-move^=acme]")'), null);
await b.evaluate('(() => { const s = document.querySelector("[data-tb-move=\'beta|task:2\']"); s.value = "in-review"; s.dispatchEvent(new Event("change", { bubbles: true })); })()');
await wait('/moved to Review in Beta Works/.test(document.querySelector("[data-tb-notice]").textContent)');
assert.deepEqual(orgs.writes, [['beta', 'tasks.edit', { task_ref: 'task:2', expect: D(2), state: 'in-review' }]]);
assert.equal(await b.evaluate('window.MosaicOrg.id'), 'acme');
});
test('a stopped organization is named at the top of the board with its reason', async t => {
const { b, wait, text } = await setup(t);
await wait(`${cards} === ${ALL}`);
const note = await text('[data-ws-unread]');
assert.match(note, /Gamma Home/);
assert.match(note, /stopped by the owner/);
assert.equal(await b.evaluate('!!(document.querySelector("[data-ws-unread]").compareDocumentPosition(document.querySelector(".tb-toolbar")) & Node.DOCUMENT_POSITION_FOLLOWING)'), true);
});
test('with no tasks anywhere the board says so and still names the stopped organization', async t => {
const { b, wait, text } = await setup(t, { empty: true });
await wait('/No tasks yet/.test(document.querySelector("[data-tb-results]")?.textContent || "")');
assert.match(await text('[data-tb-results]'), /Gamma Home could not be read/);
assert.match(await text('[data-ws-unread]'), /Gamma Home/);
});
test('#/orgs/beta/tasks shows beta\'s tasks only, with a link to every organization', async t => {
const { b, base, wait } = await setup(t, { hash: '#/orgs/beta/tasks' });
await wait(`${cards} === ${BETA}`);
assert.equal(await b.evaluate('location.hash'), '#/orgs/beta/tasks');
assert.equal(await b.evaluate('document.querySelector("[data-tasks-board]").dataset.tbScope'), 'beta');
// SP7: a drill-in keeps its trail.
await wait(`${trail} === 'Dashboard / Beta Works / Tasks'`);
// No filter is on, so no "match the filters" line: the scope is not a filter.
assert.equal(await b.evaluate('document.querySelector("[data-tasks-board] .tb-count")'), null);
assert.equal(await b.evaluate('document.querySelector("[data-tb-org]")'), null);
assert.match(await b.evaluate('document.querySelector("[data-tasks-board] .sub").textContent'), /Tasks from Beta Works only/);
assert.equal(await b.evaluate('document.querySelector("[data-tasks-board] .sub a")?.getAttribute("href")'), '#/tasks');
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]")?.getAttribute("href")'), '#/tasks');
// The sidebar Tasks link opens the system board.
await b.evaluate('document.querySelector("#sections a[href=\'#/tasks\']").click()');
await wait(`location.hash === "#/tasks" && ${cards} === ${ALL}`);
// An address that names no possible organization is not the system board.
await b.navigate(`${base}/?reload=1#/orgs/Not%20An%20Id/tasks`);
await wait('/not on your list/.test(document.querySelector("[data-tasks-board]")?.textContent || "")');
assert.equal(await b.evaluate(cards), '[]');
});
test('a card opened from the system board opens the task in its organization', async t => {
const { b, wait } = await setup(t, { hash: '#/orgs/acme/organization' });
await wait('document.querySelector("[data-org-dashboard] h1")?.textContent === "Acme Studio"');
await b.evaluate('location.hash = "#/tasks"');
await wait(`${cards} === ${ALL}`);
await b.evaluate('document.querySelector("[data-tb-open=\'beta|task:3\']").click()');
await wait('document.querySelector("#tb-dialog[open] [data-tb-goto]")');
assert.equal(await b.evaluate('document.querySelector("#tb-dialog [data-tb-goto]").getAttribute("href")'), '#/orgs/beta/tasks?task=task%3A3');
assert.equal(await b.evaluate('document.querySelector("#tb-dialog [data-tb-goto]").textContent'), 'Open in Beta Works');
await b.evaluate('document.querySelector("#tb-dialog [data-tb-goto]").click()');
await wait('location.hash.startsWith("#/orgs/beta/tasks") && window.MosaicOrg.id === "beta" && document.querySelector("[data-tasks-board]")?.dataset.tbScope === "beta"');
await wait('document.querySelector("#tb-dialog[open] form[data-tb-form=edit]")?.dataset.tbKey === "beta|task:3"');
// The scoped page offers no second hop to the organization it is already in.
assert.equal(await b.evaluate('document.querySelector("#tb-dialog [data-tb-goto]")'), null);
// Closing the task takes it off the address, so a reload does not open it again.
await b.evaluate('document.querySelector("#tb-dialog [data-tb-cancel]").click()');
await wait('location.hash === "#/orgs/beta/tasks" && !document.querySelector("#tb-dialog").open');
});
// Holds each task board read for ?hold= ms (or window.__hold, set later) and counts the reads that
// started and the ones that came back, so a test can act while a read is in flight. A task write is
// held for window.__holdW ms and counted the same way.
const HOLD = `window.__hold = Number(new URLSearchParams(location.search).get('hold')) || 0; window.__started = 0; window.__landed = 0;
window.__holdW = 0; window.__wStarted = 0; window.__wLanded = 0;
(() => {
const real = window.fetch.bind(window);
window.fetch = async (url, init = {}) => {
if (String(url) === '/api/workspace/tasks' && init.method === 'POST' && window.__holdW) {
window.__wStarted++;
await new Promise(r => setTimeout(r, window.__holdW));
try { return await real(url, init); } finally { window.__wLanded++; }
}
if (!/^\\/api\\/workspace\\?sections=tasks(?:%2C|,)projects/.test(String(url))) return real(url, init);
window.__started++;
if (window.__hold) await new Promise(r => setTimeout(r, window.__hold));
try { return await real(url, init); } finally { window.__landed++; }
};
})();`;
const settle = b => b.evaluate('new Promise(r => setTimeout(r, 200))');
test('a project filter stays in the address while its organization does not answer', async t => {
const { b, orgs, wait } = await setup(t, { hash: '#/tasks?project=beta%3Ashop' });
const SHOP = JSON.stringify(JSON.stringify(['beta|task:2']));
await wait(`${cards} === ${SHOP}`);
const list = await orgs.list();
list[1].busHealthy = false;
await b.evaluate('document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))');
await wait('/Beta Works/.test(document.querySelector("[data-tasks-board] [data-ws-unread]")?.textContent || "")');
await settle(b);
assert.equal(await b.evaluate('location.hash'), '#/tasks?project=beta%3Ashop');
list[1].busHealthy = true;
await b.evaluate('document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))');
await wait(`${cards} === ${SHOP} && !/Beta Works/.test(document.querySelector("[data-tasks-board] [data-ws-unread]")?.textContent || "")`);
assert.equal(await b.evaluate('location.hash'), '#/tasks?project=beta%3Ashop');
assert.equal(await b.evaluate('document.querySelector("[data-tb-filter=project]").value'), 'beta:shop');
});
test('a gone filter is cleaned from the tasks address only, never from a page opened while it was read', async t => {
const { b, base, wait } = await setup(t);
await wait(`${cards} === ${ALL}`);
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: HOLD });
await b.navigate(`${base}/?hold=800#/tasks?org=gone`);
await wait('window.__started >= 1');
await b.evaluate('location.hash = "#/inbox?org=acme"');
await wait('window.__landed >= 1');
await settle(b);
assert.equal(await b.evaluate('location.hash'), '#/inbox?org=acme');
});
test('a read in flight does not paint the board over the page for an address no organization matches', async t => {
const { b, base, wait } = await setup(t);
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: HOLD });
await b.navigate(`${base}/?reload=1#/tasks`);
await wait(`${cards} === ${ALL}`);
await b.evaluate('window.__hold = 800; window.__started = 0; window.__landed = 0');
await b.evaluate('(() => { const s = document.querySelector("[data-tb-filter=state]"); s.value = "todo"; s.dispatchEvent(new Event("change", { bubbles: true })); })()');
await wait('window.__started >= 1');
await b.evaluate('location.hash = "#/orgs/Not%20An%20Id/tasks"');
await wait('/not on your list/.test(document.querySelector("[data-tasks-board]")?.textContent || "")');
await wait('window.__landed >= window.__started');
await settle(b);
assert.match(await b.evaluate('document.querySelector("[data-tasks-board]")?.textContent || ""'), /not on your list/);
assert.equal(await b.evaluate(cards), '[]');
});
test('a move still writing when the not-on-your-list page opens does not paint the board over it', async t => {
const { b, base, wait } = await setup(t);
await b.call('Page.addScriptToEvaluateOnNewDocument', { source: HOLD });
await b.navigate(`${base}/?reload=1#/tasks`);
await wait(`${cards} === ${ALL}`);
await b.evaluate('document.querySelector("[data-tb-layout=list]").click()');
await wait('document.querySelector("[data-tb-move=\'beta|task:2\']")');
await b.evaluate('window.__holdW = 800; window.__started = 0; window.__landed = 0');
await b.evaluate('(() => { const s = document.querySelector("[data-tb-move=\'beta|task:2\']"); s.value = "in-review"; s.dispatchEvent(new Event("change", { bubbles: true })); })()');
await wait('window.__wStarted >= 1');
await b.evaluate('location.hash = "#/orgs/Not%20An%20Id/tasks"');
await wait('/not on your list/.test(document.querySelector("[data-tasks-board]")?.textContent || "")');
await wait('window.__wLanded >= 1 && window.__landed >= window.__started');
await settle(b);
assert.match(await b.evaluate('document.querySelector("[data-tasks-board]")?.textContent || ""'), /not on your list/);
assert.equal(await b.evaluate(cards), '[]');
});
test('an archived project keeps its filter while it has tasks, and while another filter matches none of them', async t => {
const { b, wait } = await setup(t, { hash: '#/tasks?project=beta%3Ashop', archived: ['beta:shop'] });
await wait(`${cards} === ${JSON.stringify(JSON.stringify(['beta|task:2']))}`);
await settle(b);
assert.equal(await b.evaluate('location.hash'), '#/tasks?project=beta%3Ashop');
// No shop task is done: the read comes back empty because of the state filter, not because shop is gone.
await b.evaluate('(() => { const s = document.querySelector("[data-tb-filter=state]"); s.value = "done"; s.dispatchEvent(new Event("change", { bubbles: true })); })()');
await wait(`${cards} === "[]" && /No tasks match/.test(document.querySelector("[data-tb-results]")?.textContent || "")`);
await settle(b);
assert.equal(await b.evaluate('location.hash'), '#/tasks?project=beta%3Ashop');
});
@@ -73,7 +73,7 @@ async function open(t, { refuse = null, tasksFail = [], send = true, width = 144
t.after(() => close(server));
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(width, height);
const url = `http://127.0.0.1:${server.address().port}/#/orgs/forge/tasks`;
const url = `http://127.0.0.1:${server.address().port}/#/tasks`;
await b.navigate(url);
const wait = waitFor(b);
await wait('document.querySelector("[data-tasks-board] [data-tb-tracker=home]")');
@@ -68,7 +68,7 @@ async function open(t, fixture = orgs()) {
t.after(() => close(server));
const b = await browser({ machine: false, args: ['--disable-extensions'] }); t.after(() => b.close());
await b.viewport(1440, 900);
const url = `http://127.0.0.1:${server.address().port}/#/orgs/forge/tasks`;
const url = `http://127.0.0.1:${server.address().port}/#/tasks`;
await b.navigate(url);
const wait = waitFor(b);
await wait('document.querySelector("[data-tasks-board] [data-tb-tracker=forge]")');
+1 -1
View File
@@ -85,7 +85,7 @@ test('SP8 the owner previews a template (nothing written), saves it with the dig
assert.equal(readFileSync(f.saved('demo-shape'), 'utf8'), preview.json);
assert.deepEqual(readFileSync(f.file), before, 'the organization file is unchanged');
const [again, againBody] = await call(f, `${ORG}/templates`, 'POST', { name: 'demo-shape', digest: preview.digest });
assert.deepEqual([again, againBody.error], [400, 'invalid-request']);
assert.deepEqual([again, againBody.error], [409, 'template-exists']);
const [, list] = await call(f, `${ORG}/templates`);
assert.deepEqual(list.templates.map(x => [x.name, x.scope]), [['demo-shape', 'org']]);
// The preview and the list went over the read; only the saves used the fenced writer.
@@ -97,7 +97,7 @@ test('sidebar follows sample 01 and Queue opens from the organization dashboard,
await b.viewport(1440, 900);
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/ddigital/organization`);
await wait('document.querySelector("[data-org-dashboard] [data-org-settings]") && document.querySelectorAll("#workspace-nav .ws-proj").length === 3');
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#sections > li > a .t")].map(e => e.textContent)'), ['Dashboard', 'Inbox', 'Tasks', 'Projects', 'Side by side', 'Agents', 'Assistant']);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#sections > li > a .t")].map(e => e.textContent)'), ['Dashboard', 'Inbox', 'Tasks', 'Projects', 'Agents', 'Assistant']);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("#sections-foot a")].map(e => e.textContent.trim())'), ['Settings']);
assert.match(await b.evaluate('document.querySelector("[data-org-toggle]").textContent.replace(/\\s+/g, " ").trim()'), /^Organizations\s*3$/);
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-workspace-org]")].map(li => [li.dataset.workspaceOrg, !!li.querySelector(".ws-av"), [...li.querySelector(".ws-dot").classList].find(c => c.startsWith("s-"))])'),
@@ -119,7 +119,8 @@ test('sidebar follows sample 01 and Queue opens from the organization dashboard,
await b.evaluate('document.querySelector("[data-org-queue]").click()');
await wait('location.hash === "#/orgs/ddigital/queue" && [...document.querySelectorAll("#bus-view h1")].some(h => h.textContent.trim() === "Queue")');
// Every sidebar view is built: Inbox (U3, workspace-pages-browser.test.mjs), Tasks (U4b,
// tasks-board-browser.test.mjs) and Side by side (U5, side-by-side-browser.test.mjs).
// tasks-board-browser.test.mjs) and Assistant (SP6, assistant-threads-browser.test.mjs), which
// replaced Side by side.
});
test('organization dashboard renders every section from the per-organization reads', async t => {
@@ -370,7 +371,7 @@ test('an unavailable selected bus does not hide other organizations on Agents',
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/beta/agents`);
await b.evaluate(`(async()=>{for(let i=0;i<150;i++){if(document.querySelector('[data-org-agents]'))return;await new Promise(r=>setTimeout(r,30))}throw Error('organization agent grid missing')})()`);
const text=await b.evaluate('document.querySelector("[data-org-agents]").innerText');
assert.match(text,/Alpha/); assert.match(text,/chief/); assert.match(text,/Beta/); assert.match(text,/Agents unavailable/);
assert.match(text,/Alpha/); assert.match(text,/chief/); assert.match(text,/Beta/); assert.match(text,/Agents not read: the bus is not answering/); assert.doesNotMatch(text,/Agents unavailable/);
});
test('a failed conversation read says unavailable, never that none exists', async t => {
@@ -484,7 +485,8 @@ test('agents grid shows each agent\'s level and where it is defined, per project
assert.match(await b.evaluate('document.querySelector("[data-agents-available] .ws-away").innerText'), /social-scheduler \(Spring launch only\), copywriter \(excluded in this project\) and every Forge or Home agent/);
// Home, where the reviewer is turned off: the table says so.
await b.navigate(`http://127.0.0.1:${server.address().port}/#/orgs/home/agents`);
await waitFor(b)('document.querySelector("[data-org-agents] h2")?.innerText === "Agents in Home"');
// #1873 SP5: the scoped page puts the levels grid under its own "Agents by level" h2; this is the section's title.
await waitFor(b)('document.querySelector("[data-org-agents] .ws-split-agents h2")?.innerText === "Agents in Home"');
assert.match(await b.evaluate('document.querySelector("[data-agents-available]").innerText'), /reviewer \(turned off for Home\)/);
});
@@ -75,16 +75,17 @@ async function setup(t, { viewport = [1440, 900], hash = '/', workspaceTimeoutMs
const b = await browser({ machine: false }); t.after(() => b.close());
await b.viewport(...viewport);
const base = `http://127.0.0.1:${server.address().port}`;
await b.navigate(`${base}/#/orgs/acme${hash}`);
// SP3: a hash that starts with # is a whole address (#/inbox is a system route).
await b.navigate(`${base}/${hash.startsWith('#') ? hash : `#/orgs/acme${hash}`}`);
return { b, base, wait: waitFor(b), text: sel => b.evaluate(`document.querySelector(${JSON.stringify(sel)})?.innerText ?? null`) };
}
test('Dashboard renders every section across organizations, and a stopped one shows its state while the others render', async t => {
const { b, wait, text } = await setup(t);
await wait('document.querySelector("[data-ws-home] [data-ws-tiles]") && document.querySelectorAll("[data-ws-orgcard]").length === 3');
await wait('document.querySelector("[data-ws-home] [data-ws-tiles]") && document.querySelectorAll("[data-ws-orgrow]").length === 3');
// The Dashboard nav item is this page.
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page] .t")?.textContent'), 'Dashboard');
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]").getAttribute("href")'), '#/');
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page]").getAttribute("href")'), '#/dashboard');
assert.equal(await text('#bus-view h1'), 'Dashboard');
// Tiles: needs you, sessions, open tasks, projects, and an honest line for spend.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-tile]")].map(e => e.dataset.wsTile)'), ['needs', 'sessions', 'tasks', 'projects', 'spend']);
@@ -92,12 +93,12 @@ test('Dashboard renders every section across organizations, and a stopped one sh
assert.match(await text('[data-ws-tile=projects]'), /Projects\s*4\s*3 active/i);
assert.match(await text('[data-ws-tile=spend]'), /No spend figures yet/);
assert.doesNotMatch(await text('[data-ws-tile=spend]'), /\$|\d/);
// Organization cards: two running with their read, the stopped one with its state and the time it was read.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-orgcard]")].map(e => [e.dataset.wsOrgcard, e.dataset.state])'), [['acme', 'ok'], ['beta', 'ok'], ['gamma', 'down']]);
assert.match(await text('[data-ws-orgcard=gamma]'), /Gamma Home/);
assert.match(await text('[data-ws-orgcard=gamma]'), /down/);
assert.match(await text('[data-ws-orgcard=gamma]'), /stopped by the owner/);
assert.equal(await b.evaluate('document.querySelector("[data-ws-orgcard=beta] a").getAttribute("href")'), '#/orgs/beta/organization');
// SP1: one organization row each: two running, the stopped one with its state and reason.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-orgrow]")].map(e => [e.dataset.wsOrgrow, e.dataset.state])'), [['acme', 'ok'], ['beta', 'ok'], ['gamma', 'down']]);
assert.match(await text('[data-ws-orgrow=gamma]'), /Gamma Home/);
assert.match(await text('[data-ws-orgrow=gamma]'), /bus down/);
assert.match(await text('[data-ws-orgrow=gamma]'), /stopped by the owner/);
assert.equal(await b.evaluate('document.querySelector("[data-ws-orgrow=beta] a").getAttribute("href")'), '#/orgs/beta/organization');
assert.match(await text('[data-ws-home] .sub'), /2 of 3 organizations answered/);
assert.match(await text('[data-ws-home] .sub'), /Gamma Home down, read \d\d:\d\d/);
// Recent project activity across both running organizations, newest first, each linking into its org.
@@ -107,7 +108,7 @@ test('Dashboard renders every section across organizations, and a stopped one sh
// Needs you lists both organizations' decisions, newest raised first as the read orders them.
const needs = await b.evaluate('[...document.querySelectorAll("[data-ws-needs] a.q")].map(a => [a.textContent, a.getAttribute("href")])');
assert.equal(needs.length, 2);
assert.ok(needs.some(([q, h]) => q === 'Ship the hero?' && h === `#/orgs/acme/inbox?d=${encodeURIComponent(`acme:${ACME_DECISION}`)}`), JSON.stringify(needs));
assert.ok(needs.some(([q, h]) => q === 'Ship the hero?' && h === `#/inbox?d=${encodeURIComponent(`acme:${ACME_DECISION}`)}`), JSON.stringify(needs));
assert.ok(needs.some(([q]) => q === 'Pick a launch price'));
// Sessions now: the working and the waiting role, each with its organization.
assert.match(await text('[data-ws-sessions]'), /coder/);
@@ -179,7 +180,7 @@ test('Projects sorts and filters by each key, remembers the grouping, and rows o
const location = hash => decodeURIComponent(hash);
test('Inbox lists both organizations, copies a command with --org and the full id, and deciding needs human proof', async t => {
const { b, base, wait, text } = await setup(t, { hash: '/inbox' });
const { b, base, wait, text } = await setup(t, { hash: '#/inbox' });
await wait('document.querySelectorAll("[data-ws-item]").length === 2 && document.querySelector("[data-ws-insp]")');
assert.equal(await b.evaluate('document.querySelector("#sections a[aria-current=page] .t")?.textContent'), 'Inbox');
assert.equal(await b.evaluate('document.querySelector("[data-not-built]")'), null);
@@ -187,13 +188,15 @@ test('Inbox lists both organizations, copies a command with --org and the full i
assert.deepEqual(items.map(([k]) => k).sort(), [`acme:${ACME_DECISION}`, `beta:${BETA_DECISION}`]);
// Each row names its organization, project and session.
const acme = items.find(([k]) => k.startsWith('acme'))[1];
assert.match(acme, /Acme Studio/); assert.match(acme, /Website/); assert.match(acme, /coder/); assert.match(acme, /gated/);
assert.match(acme, /Acme Studio/); assert.match(acme, /Website/); assert.match(acme, /coder/); assert.match(acme, /Gated/);
const beta = items.find(([k]) => k.startsWith('beta'))[1];
assert.match(beta, /Beta Works/); assert.match(beta, /No project/); assert.match(beta, /pm/);
assert.match(beta, /Beta Works/); assert.match(beta, /pm/);
// SP3: a project chip only where the item has a project.
assert.equal(await b.evaluate(`document.querySelector('[data-ws-item="beta:${BETA_DECISION}"] [data-ws-projchip]')`), null);
assert.match(await text('[data-ws-unread]'), /Gamma Home down/);
// Tabs the data can't back say so.
assert.deepEqual(await b.evaluate('[...document.querySelectorAll("[data-ws-inbox] .ws-seg button")].map(x => [x.textContent, x.disabled])'), [['Needs you', false], ['Seen', true], ['Answered', true]]);
assert.match(await text('[data-ws-inbox]'), /not built yet/);
// SP3: the prototype's Org and Type filter rows; the Seen and Answered placeholders are gone.
assert.equal(await b.evaluate('document.querySelector("[data-ws-inbox] .ws-seg")'), null);
assert.ok(await b.evaluate('document.querySelectorAll("[data-ws-type]").length > 1'));
// Select the acme decision; the inspector shows it, and the selection stays in the hash.
// A pointer click focuses the link before it activates; .click() alone does not.
await b.evaluate(`(() => { const a = document.querySelector('[data-ws-select="acme:${ACME_DECISION}"]'); a.focus(); a.click(); })()`);
@@ -216,7 +219,7 @@ test('Inbox lists both organizations, copies a command with --org and the full i
await wait('[...document.querySelectorAll("#bus-view h1")].length > 0 && !document.querySelector("#bus-view .loading")');
assert.equal(await b.evaluate('document.querySelector("#decide-section [data-decide]")'), null);
// Filter to one organization.
await b.navigate(`${base}/#/orgs/acme/inbox`);
await b.navigate(`${base}/#/inbox`);
await wait('document.querySelectorAll("[data-ws-item]").length === 2');
await b.evaluate('document.querySelector("[data-ws-org=beta]").click()');
await wait(`document.querySelectorAll("[data-ws-item]").length === 1 && document.querySelector("[data-ws-item]").dataset.wsItem === ${JSON.stringify(`beta:${BETA_DECISION}`)}`);
@@ -243,18 +246,18 @@ test('A poll repaints in place: focus, caret and scroll stay where they were', a
assert.deepEqual(await b.evaluate('[document.activeElement?.dataset.focusKey, document.activeElement.selectionStart]'), ['proj-name', 2]);
// The Dashboard and the Inbox repaint the same way.
await b.evaluate('location.hash = "#/orgs/acme/"');
await wait('document.querySelectorAll("[data-ws-orgcard]").length === 3');
await b.evaluate('document.querySelector("[data-ws-orgcard=beta] a").focus()');
await wait('document.querySelectorAll("[data-ws-orgrow]").length === 3');
await b.evaluate('document.querySelector("[data-ws-orgrow=beta] a").focus()');
await b.evaluate('window.__marker = document.querySelector("[data-ws-orgs]"); document.dispatchEvent(new CustomEvent("mosaic-workspace-render"))');
await wait('document.querySelector("[data-ws-orgs]") !== window.__marker');
assert.equal(await b.evaluate('document.activeElement?.dataset.focusKey'), 'orgcard:beta');
assert.equal(await b.evaluate('document.activeElement?.dataset.focusKey'), 'orgrow:beta');
// No loading view replaced the page during that repaint.
assert.equal(await b.evaluate('document.querySelector("#bus-view .loading")'), null);
});
test('Phone width: no horizontal scroll on any of the three pages, and the drawer opens and closes', async t => {
const { b, wait } = await setup(t, { viewport: [390, 844] });
for (const [hash, ready] of [['/', '[data-ws-orgcard]'], ['/projects', '[data-ws-project]'], ['/inbox', '[data-ws-item]']]) {
for (const [hash, ready] of [['/', '[data-ws-orgrow]'], ['/projects', '[data-ws-project]'], ['/inbox', '[data-ws-item]']]) {
await b.evaluate(`location.hash = "#/orgs/acme${hash}"`);
await wait(`document.querySelector(${JSON.stringify(ready)})`);
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, hash);
@@ -270,10 +273,11 @@ test('Phone width: no horizontal scroll on any of the three pages, and the drawe
await b.evaluate('document.querySelector("#sections a[href=\'#/projects\']").click()');
await wait('location.hash === "#/orgs/acme/projects" && document.querySelector("[data-ws-project]")');
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true);
// An inbox row at phone width puts its source on its own line above the question.
await b.evaluate('location.hash = "#/orgs/acme/inbox"');
await wait('document.querySelector("[data-ws-item] .ws-msrc")');
assert.equal(await b.evaluate(`(() => { const r = document.querySelector('[data-ws-item]'), s = r.querySelector('.ws-msrc').getBoundingClientRect(), q = r.querySelector('a.q').getBoundingClientRect(); return s.height > 0 && s.bottom <= q.top + 1; })()`), true, 'source above question');
// An inbox row at phone width puts its organization chip on its own line below the question.
await b.evaluate('location.hash = "#/inbox"');
await wait('document.querySelectorAll("[data-ws-item]").length === 2');
assert.equal(await b.evaluate(`(() => { const r = document.querySelector('[data-ws-item]'), s = r.querySelector('[data-ws-orgchip]').getBoundingClientRect(), q = r.querySelector('a.q').getBoundingClientRect(); return s.height > 0 && s.top >= q.bottom - 1; })()`), true, 'organization below question');
assert.equal(await b.evaluate('document.documentElement.scrollWidth <= document.documentElement.clientWidth'), true, 'system inbox');
});
test('A read that an answering organization could not make says not read, never zero', async t => {
@@ -297,7 +301,7 @@ test('A read that an answering organization could not make says not read, never
await wait('document.querySelector("[data-ws-miss=projects]")');
assert.match(await text('[data-ws-miss=projects]'), /Not read in Beta Works/);
// Inbox: the note names it, and the chip carries no count.
await b.evaluate('location.hash = "#/orgs/acme/inbox"');
await b.evaluate('location.hash = "#/inbox"');
await wait('document.querySelector("[data-ws-miss=inbox]")');
assert.match(await text('[data-ws-miss=inbox]'), /Not read in Beta Works \(the chat channel is off\)/);
assert.match(await text('[data-ws-org=beta] .n'), /not read/i);
@@ -342,7 +346,7 @@ test('With every organization down the dashboard and inbox show no totals and no
assert.equal(await text('[data-ws-states]'), 'Tasks not read');
assert.equal(await text('[data-ws-recent]'), 'Projects not read');
assert.equal(await text('[data-ws-sessions]'), 'Sessions not read');
await b.evaluate('location.hash = "#/orgs/acme/inbox"');
await b.evaluate('location.hash = "#/inbox"');
await wait('document.querySelector("[data-ws-items]")');
assert.equal(await text('[data-ws-items]'), 'Decisions not read');
await b.evaluate('location.hash = "#/orgs/acme/projects?grouping=flat"');