Compare commits
94
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b39d5e2ff3 | ||
|
|
c85c768a4a | ||
|
|
b7649ecd73 | ||
|
|
0354452971 | ||
|
|
bbbefb3f28 | ||
|
|
2f91ff5bea | ||
|
|
1ca3a38f86 | ||
|
|
cb80b2b8a8 | ||
|
|
fd300b4fe3 | ||
|
|
a88302d6eb | ||
|
|
820f45e474 | ||
|
|
2e9a2068bd | ||
|
|
fe6c22e0f2 | ||
|
|
9eed814d3c | ||
|
|
7ee606cda2 | ||
|
|
b2d52b57c1 | ||
|
|
cbf1836bd7 | ||
|
|
6fe3625fae | ||
|
|
24551c9eea | ||
|
|
cad9cd057f | ||
|
|
4f24501801 | ||
|
|
02e053866a | ||
|
|
ff096afa27 | ||
|
|
70af20e29d | ||
|
|
d92cdefc1d | ||
|
|
9994f89790 | ||
|
|
4a9c7a931c | ||
|
|
5c7194e05b | ||
|
|
f0bf85befe | ||
|
|
c26879637a | ||
|
|
2fc97a3edb | ||
|
|
68df55130e | ||
|
|
6ad1d33dd1 | ||
|
|
5fba4726dc | ||
|
|
69ce460f91 | ||
|
|
307f88be3e | ||
|
|
bfd3ed6811 | ||
|
|
5b6b39f080 | ||
|
|
2d7d7be5ca | ||
|
|
f73c761ad3 | ||
|
|
8b4a26dd2b | ||
|
|
11d2b43b3a | ||
|
|
8aefc0f7a9 | ||
|
|
9cff3255e6 | ||
|
|
d50d79cddd | ||
|
|
fb3bd16052 | ||
|
|
13615e12b9 | ||
|
|
bd29e756a5 | ||
|
|
6bd9be78ac | ||
|
|
3a84f46b6e | ||
|
|
208439814a | ||
|
|
7c6571768f | ||
|
|
3597e0daf6 | ||
|
|
3116f43e65 | ||
|
|
c66f1ec00c | ||
|
|
9400e0d94d | ||
|
|
a9912983e6 | ||
|
|
626321608f | ||
|
|
5f965cdb30 | ||
|
|
8296d33100 | ||
|
|
69ac78b97e | ||
|
|
a2a7df73df | ||
|
|
789e2bcdd4 | ||
|
|
02df2a3a25 | ||
|
|
b982404963 | ||
|
|
5dd940165d | ||
|
|
ed4f45ed23 | ||
|
|
79df01f1de | ||
|
|
d7b98b4698 | ||
|
|
0f29fe0d92 | ||
|
|
32be3a01bc | ||
|
|
f97e0d3aeb | ||
|
|
eebdb2f0ce | ||
|
|
5373b110ac | ||
|
|
3885f4628b | ||
|
|
ba9933309b | ||
|
|
0785af8129 | ||
|
|
d1b01329bc | ||
|
|
c7aecbffa9 | ||
|
|
bb2f79f3d9 | ||
|
|
e24e7e93a2 | ||
|
|
387f73a7a4 | ||
|
|
61371adb10 | ||
|
|
b913f0f4c8 | ||
|
|
bfd2cc5e79 | ||
|
|
3e53af3941 | ||
|
|
359b3299b4 | ||
|
|
65f7288cea | ||
|
|
211b32ef1a | ||
|
|
163972e08e | ||
|
|
23e504f331 | ||
|
|
23b5e24ebc | ||
|
|
266f3a45ff | ||
|
|
0c35eeed9d |
No files matched your search
@@ -6347,3 +6347,9 @@ R5 quote fallback room (#797 D3, 2026-11-06, MVP3 lead): r4 review P2 found that
|
||||
2026-11-09 UTC, PRD 1.20 and defect l (#1873, #1886; PRs #1887 03fe321b1 and #1888 7a97cfc4f). PRD 1.20: Jason approved draft 2 at 22:57Z ("The file looks fine other than that"; the Montage module name stays deferred). The PRD now has 118 requirements, with REQ-WS-1..8, REQ-AGENT-1..3, REQ-SYS-1..2, REQ-ACCT-1..2 and REQ-SETUP-1..2 added and REQ-ASSIST-1, REQ-USER-1, REQ-TASK-1 and REQ-WEB-3 amended. Builder Codex Terra xhigh declined to commit because stack-copy failed 20/1 (node-gyp missing from the test Node's npm); that failure is pre-existing on 483eccb3d, so the lead committed. Sol review APPROVE 0 (word-for-word diff against draft 2, catalog order, both requirements tests). Defect l: before, an agent that declared a store credential made the next bus start refuse, because Credentials refuses a missing store root and only issue() created it. After: start creates the root 0700 when any reference names the store; a root that exists with loose modes or as a symlink still refuses. Two new credential-verbs tests fail on the parent. Bus suite 171 files one at a time, 1713/0 (Node 26.12.1, env -i). Sol review APPROVE 0. uiorg redeployed at 7a97cfc4f, 23:15Z. Follow-up: the stack-copy node-gyp test environment. Reports: /mnt/storage/scratch/mosaic-lead/reports/{prd120-land,prd120-review,defectl-review}.md.
|
||||
|
||||
2026-11-10 UTC, unified workspace U1 and SYS1 (#1873; PRs #1889 d35447005 and #1890 2c6556ab1). U1, before: each org page read only its own bus and nothing read every org at once. After: /api/workspace returns projects, sessions, inbox, tasks and metrics from every org the owner holds, each row tagged with its org and each org with a state (ok, starting, down, timeout, invalid); `mosaic console restart` and `mosaic org reload <org>` send the F3 routes. Sol review CHANGES 0/2 on 2109458b3: malformed data from one org turned the whole read into a 503, and the per-org deadline left sockets and transport children running. Terra fix 0672d5fe8 validates each org's result inside its boundary and carries an absolute deadline and AbortSignal through the status check and transport; the new workspace-failures test is 0/10 on the parent and 10/0 on the fix. The lead re-pinned the webui bus.mjs hash in bus channel-proof (the deliberate signal/deadline change; nonces, argv and limits unchanged) and amended as d35447005. SYS1, before: no system-type kind. After: a system-type plug-in kind with five modules (business-management, coding, creative-writing, marketing, montage), an org enable list under plugins.system-type, owner-only project selection with an append-only project_system_types table (migration 3t-3u) and CLI verbs; the modules grant no tools yet (REQ-SYS-2 deferred). Sol review CHANGES 1/2 on a9629f332: the restore guard did not count project_system_types, the CLI channel did not admit the two project verbs, and the #811 migration-reader pin still expected 18 steps. Lead fix 2c6556ab1 (rebased on d35447005) adds the table to COUNTED and LISTED with refusal and in-run recount tests, admits both verbs with a run()-level channel test (red on the unfixed channel), and moves the pin to 19 steps ending 3t-3u; fix files 323/0 and rebase overlap files 63/0 (Node 26.12.1, one file at a time, env -i). Full gate on a9629f332 4040/5: the two stack-release pins above, and tester-reads 3/3, which also fails on 1616d1dd6 (project.mjs:95 refuses an org --tester init; follow-up). Correction to the uiorg deploy at 00:50Z: the deploy script switched the tree without the offline schema migration, so all five buses refused to start (normal startup refuses an older schema by design). The lead ran migrate-schema.mjs for the five org stores (3t to 3u, all ready), restarted the buses (201 each) and added the migration to the deploy script with stop-on-refusal. test3 refused writer-locked and stays down, as before. Reports: /mnt/storage/scratch/mosaic-lead/reports/{u1-review,u1-fix,org-sys1-build,sys1-review}.md.
|
||||
|
||||
2026-11-13 UTC, starter packs replace system types (#1873; PRs #1949 c0a60ed3a, #1950 1e65ff3f8, #1951 755ba3fa8, #1952 1ced0e392, #1953 dfef78834, #1955 9a649abf8, #1956 991eb8c33, #1957 34dd33101, #1959 0251acdad and #1960 e6ab8bc1f; final e6ab8bc1f). Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git; the Lead wrote no entry at the time. Before: SYS1 (PR #1890, 2c6556ab1) made system types a plug-in kind with five modules, an org enable list under plugins.system-type and an append-only project_system_types table (migration 3t-3u); the modules granted no tools. After: the design docs/plans/2026-11-12_starter-packs-design.md landed as PR #1949 (doc only) after three fix rounds; Jason's FULL SEND at 21:06Z on 11-12 answered Q1 to Q3: system-type removed outright with no legacy, SP10 dropped, SP9 deletes the kind and drops project_system_types. Slices in landing order: SP3 the org keys packs, board and workflows and the applyPack writer op; SP1 the starter-pack plug-in kind and its checker; SP7 workflow guidance in the harness prompt; SP2 the five shipped packs; SP4 pack, board and workflow verbs, routes and CLI words; SP6 board labels, pack picker and workflow editor on the WebUI organization page; SP5 the chief applies a pack's non-definition half and raises hires from its proposals; SP8 the owner saves an organization's shape as a template; SP9 system types removed outright and bus schema 3v-3w dropping project_system_types. Test counts, Lead check then lane gate: SP3 98 files 1294/0, 1828/1; SP1 51 files 708/0, 2854/1; SP7 1281/0, 2537/1; SP2 150/0, 1556/1 at 18add86cb before its rebase onto SP7; SP4 4848/2, 6049/1; SP6 371 files 4233/1, 8262/23; SP5 229 files 2721/0, 8061/2; SP8 415 files 4650/1, 8125/2; SP9 497 files 5542/1, 8655/28. Each single Lead check red is CHAT-01 (host Python lacks jsonschema), red on base too; SP4's second red was the fixture federation-host.mjs wrongly in the run list, and Lead check lists are filtered to *.test.mjs since. The lane gate reds the log names are base or environment reds: CHAT-01, 19 agents/*/work probes, budget-supervisor 3v, ui-browser SSO, six v1 .woodpecker files and one claude-session timing test. Every slice was deployed to uiorg 7350 and verified; at e6ab8bc1f (03:46Z on 11-13) the offline 3v-3w migration ran on all five live stores, 5 stop 200, 5 bus schema 3w ready, 5 setup 201, the system-types route and its js returned 404, and no org file named system-type, so no wipe was needed. Corrections: the Lead's 21:38Z carry that SP2 pack steps must drop id was reversed at 21:46Z: pack steps keep id (SP1 checker) and SP4 drops id when it copies a step into the org file. The Lead's SP7 brief misstated the workflow shape; the lane built to the SP3 loader, which was correct. SP5's last commit before landing changed the broker canonical string builder after its re-check with no suite test; the Lead compared it with organization canonicalJson (7/7 same) and accepted it, and the integer-key pin test is deferred. SP9's first gate, before its rebase, ran packages/cli/live/ui-browser.test.mjs, which binds its own fixture on 17443, a lane rule breach; nothing was listening before or after, and the file was left out of later gates. The 'bus recover' deploy step refuses rc=3 in the agent shell on every deploy since D1; it is harmless while bus stop succeeds. Reports: /mnt/storage/scratch/mosaic-lead/reports/{starter-pack-design-build,starter-pack-design-recheck2,sp1-build-1112-starter-packs,sp2-build-1112-starter-packs,sp3-build-1112-starter-packs,sp4-build,sp5-build,sp6-build,sp7-build,sp8-build,sp9-build,sp9-rebase-recheck}.md.
|
||||
|
||||
2026-11-15 UTC, applying a starter pack is the hire decision, with the route fallback (#1873; PR #1963, b913f0f4c; commits 359b3299b and 3e53af394 lane pd, bfd2cc5e7 and b913f0f4c lane pr2). Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git. Before: section 3 of the starter packs design said apply never hires; a person's apply left the pack's hires as proposals for the chief to raise or for a person with org.hire to start. On 7350 at 65f7288ce Jason applied packs and saw no agents. His ruling at 20:48Z on 11-14, verbatim: "Damnit. If I choose a starter pack and apply it, that is a decision!" After, lane pd: a person's apply (pack.apply.console from the WebUI, pack.apply from the CLI) raises one hire decision per proposal after the pack's commit and resolves it, with the evidence an inbox approval leaves. The owner's apply approves flagged and credential lines; a member with org.hire hires only proposals with neither, and the rest wait for the owner as awaiting-owner. An agent apply hires nothing. Hires are written with no credential material, so services show unbound until someone binds them. The design's section 3 carries a 2026-11-14 change note. Route fallback: at 22:03Z the Lead found every 7350 chief had model null, so pack hires would refuse pack-hire-route-missing on Jason's orgs. Ruling at 22:13Z: the hire route is the chief's, else the org assistant's harness and model, else refuse; lane pr2 stacked on pd. Tests: pd gate 3957/0 at its first commit, review changes 6 (2 P2) fixed or deferred, re-check APPROVE; Lead check of pd with pr2 333 files 3813/1, the red a control-board scan.test mtime-tie flake in a file neither lane touched, 70/0 three times alone. Lead ruling on the re-check's P2 1: a member pack hire surface is a follow-up row, because a new transport for a member hire cap is a security boundary and the owner path covers apply; Jason said "proceed". Deployed b913f0f4c at 01:03Z on 11-15: stop 5, schema 3w 5, setup 5. The Lead ran pack hire on faceless (montage ideas-1 and research-1, coding pm-1, coder-1 and reviewer-1, all on fixture-deterministic) and acme (business-management pm-1 and research-1 on opus), each with routeFrom assistant. Related fix the same night: Jason reported "adapter exited 127" in Messages. Lane r127 found the Lead's deploy-uiorg.sh (a scratch script, not in the repository) started the Console without MOSAIC_CLAUDE_BIN, so claude-code sessions ran the /usr/bin/claude wrapper whose target under /opt the sandbox does not bind. The Lead patched the script and landed PR #1964 387f73a7a, which makes exit 127 name the missing program; Lead check 16 files 285/0. Both assistant kinds replied on 7350 at 387f73a7a by 03:33Z. Reports: /mnt/storage/scratch/mosaic-lead/reports/{pd-build,pd-review,pd-recheck,pr2-build,pr2-review,r127-build,r127-review,r127-recheck}.md.
|
||||
|
||||
2026-11-15 UTC, single pane slices sp1 to sp14 (#1873; PRs #1965 to #1978; final c26879637). Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git. Before: a Side by side page sat in the sidebar beside the organization pages, and Jason's walkthrough on 65f7288ce (20:48Z on 11-14) found agents from an applied pack not visible. His direction: #/dashboard system-wide, no organization URL base, side-by-side Assistant threads in place of Side by side, and the 3-click rule. The Lead ruled at 03:33Z on 11-15 that #/orgs/<id>/... stays the address of an org page but is a route inside one global shell, with no reload and no mode switch. After, slice by slice (PR, tip, Lead check, lane gate): sp1 shell, #/dashboard system page, org drill-in without reload, a down org says so (#1965, c7aecbffa, 128/0, 1031/0, two reviews, nine findings fixed); sp2 dashboard polish, bare org route, theme, one down banner (#1966, d1b01329b, 132/0); sp3 system Inbox (#1967, 3885f4628, 111/0, 892/0; a theme fix and a render-order fix were read by the Lead, not a reviewer); sp5 system Agents, landed before sp4 (#1968, f97e0d3ae, 89/0 plus unified-workspace 18/0, 745/0); sp4 system Tasks, which the Lead rebased onto f97e0d3ae with three one-line union conflicts (#1969, ed4f45ed2, 131/0, 937/0 before the rebase); sp6 system Assistant with up to three threads from any org side by side, the open set in the hash, Side by side removed from the sidebar and #/side-by-side landing on Assistant (#1970, 789e2bcdd, 95/0, 1472/0, four review rounds); sp7 seven small fixes (#1971, a9912983e, 141/0, 1483/0, three review rounds); sp8 KPI tiles from real reads only and the 3-clicks table (#1972, c66f1ec00, 119/0 plus org-live-edit-browser 4/0 alone, 1490/2 with two load flakes that each passed alone twice, three small fixes not re-reviewed); sp9 read-only workflow list and graph per org (#1973, 7c6571768, 143/0, 1504/0); sp10 workflow edit in the graph (#1974, bd29e756a, 146/0, 1515/0); sp11 eight fixes including agent counts that disagreed and Done this week (#1975, 5b6b39f08, 164/0, 1527/0, three review rounds); sp12 agent drawer from #/agents and org session rows (#1976, 69ce460f9, 196/0, 191 files 1538/0); sp13 organization page fits its width, #/orgs/<id>?query parses, drawer state pending until the instances read answers (#1977, 68df55130, 205/0, 192 files 1547/0); sp14 Queue card off the organization page, running not read where an answer carries no runs, kept Assistant pane messages keyed by an opaque viewer, drawer repaint without new page reads (#1978, commits 2fc97a3ed and c26879637, 218/0, 192 files 1549/0, review changes 1 with the P2 fixed, re-check approve). sp14 adds `viewer` to /api/config (32 hex of sha256 over provider, iss and sub; `local` without sign-in) and adds no route. The Lead ruled at landing of sp13 that the Queue card leaves the organization page; #/queue stays. State at c26879637: system pages #/dashboard, #/inbox, #/agents, #/tasks and #/assistant; org pages at #/orgs/<id>/... inside the same shell. Each slice was deployed to uiorg 7350 with five buses up (deploy log per tip under reports/deploy-<sha>.log); sp1 and sp8 to sp14 record 5 stop, 5 schema 3w and 5 setup. An acme assistant reply was checked live after sp1 and sp6 to sp14; after sp4, #/agents showed the acme assistant running mid-reply; the log records no reply check for sp2, sp3 and sp5. Corrections: sp15 was launched at 19:23Z on a wrong premise. The Lead had told Jason, from reading code only, that the broker's async instances path was the real cause of the sp12 drawer saying not running. The lane stopped at BASE with no diff: the shipped runtime answers instances synchronously (runtime.mjs:1263), and a probe on a real startBroker showed the running and alive arrays present. The sp12 live shot had a 9000 ms screenshot budget that caught the paint before the read; the sp13 shot at 30000 ms shows State running. sp15 closed at 19:26Z with no change and no bus row; sp14's running not read item now only guards a failed or odd read. The Lead's lesson: prove a fault live before naming it a cause. The sp14 live shots read 0 running because they were taken right after the bus restart, before any session started. Follow-ups after sp14: empty space under Active agent sessions at 1440, a drawer pending gap, viewer read once per tab with an unsalted hash, the open pane set kept per browser, and the Dashboard org table scrolling sideways at 390. Reports: /mnt/storage/scratch/mosaic-lead/reports/{sp1-build,sp2-build,sp3-build,sp4tasks-build,sp5agents-build,sp6threads-build,sp7polish-build,sp8kpis-build,sp9workflows-build,sp10workflowedit-build,sp11fixes-build,sp12agentdrawer-build,sp13orgpagefit-build,sp14orgpagetruth-build,sp15businstancesruns-build}.md.
|
||||
@@ -2124,3 +2124,9 @@ are never rewritten or removed; corrections are new entries.
|
||||
2026-11-09 UTC | Mos (lead, Claude Opus 5.5) | Organizations F3 fix round and landing (#1873) | PR #1884 merged a8f9f0957; review P3 fixed, P1 README corrected with follow-up #1883; 195/0 focused suite; uiorg redeployed 22:45Z.
|
||||
2026-11-09 UTC | Mos (lead, Claude Opus 5.5) | PRD 1.20 landing and defect l (#1873, #1886) | PR #1887 merged 03fe321b1, PR #1888 merged 7a97cfc4f; both Sol reviews APPROVE 0; bus suite 1713/0; uiorg redeployed 23:15Z; U1, U2 and U4a builds dispatched.
|
||||
2026-11-10 UTC | Mos (lead, Claude Opus 5.5) | U1 and SYS1 landings (#1873) | PR #1889 merged d35447005, PR #1890 merged 2c6556ab1; both Sol reviews CHANGES, fixed (U1 by Terra, SYS1 by the lead); uiorg at 2c6556ab1 after the missed 3t-3u store migration was run; deploy script now migrates.
|
||||
2026-11-10 UTC | Sage (Lead) | redact3 landing (#1873) | PR #1912 merged 96c900d21 at 23:56Z, gate 268 files 3412/0, Opus review changes 2 fixed; uiorg deploy started. Backfilled 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git.
|
||||
2026-11-11 UTC | Sage (Lead) | Organizations, redaction, accounts, dev readiness and credential binding landings (#1873) | PRs #1913 to #1944 merged, a4eed1e21 to 6d0e9f89b: A2, golden1, TI, redact4, A3, M3 with M3-recon, acct-anchor, org-names, polish2, run sheet doc, cred-bind design, PL1, base-reds, redact5, T1, timing2, cleanup-time, A4, supcost, defscan, redact6, AU, D4, D3, harness-scan, D2, D1, CB01, bus-stop, agent-guard, proxy-ui, CB2. Jason approved CB0 to CB5 at 17:55Z. Per-landing check counts are in uidev/LEAD-1110.md. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-12 UTC | Sage (Lead) | E1, E2, CB3, E3, CB4 and starter packs design, SP3, SP1, SP7, SP2, SP4 landings (#1873) | PRs #1945 8827905ba (E1), #1946 666f4d686 (E2), #1947 0b8fe202b (CB3), #1948 2ad4b30eb (E3), #1949 c0a60ed3a (design), #1950 1e65ff3f8 (SP3), #1951 755ba3fa8 (SP1), #1952 1ced0e392 (SP7), #1953 dfef78834 (SP2), #1954 95c2ce143 (CB4), #1955 9a649abf8 (SP4). Jason's FULL SEND on starter packs at 21:06Z: system types removed outright, SP10 dropped. The log first dated the E1 landing 11-11; its own correction and git put it at 02:48Z on 11-12. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-13 UTC | Sage (Lead) | Starter packs SP6, SP5, SP8, SP9 and CB5 landings; E2E round 6 started (#1873) | PRs #1956 991eb8c33 (SP6), #1957 34dd33101 (SP5), #1958 a9d72b3cd (CB5, credential binding CB0 to CB5 complete), #1959 0251acdad (SP8), #1960 e6ab8bc1f (SP9). uiorg 7350 at e6ab8bc1f: bus schema 3w on all five stores, system-types route 404. E2E R6 CLI and WebUI lanes started 23:59Z. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-14 UTC | Sage (Lead) | E2E round 6 fixes and the pack apply ruling (#1873) | E2E R6 CLI 0/0/7, WebUI 0/3/15. PR #1961 23b5e24eb (f6w) and PR #1962 65f7288ce (f6c) merged; uiorg verified at 65f7288ce 02:40Z. Jason's walkthrough at 20:48Z: applying a starter pack is a decision, plus the single pane direction. Route fallback ruled 22:13Z. Backfilled 2026-11-16 by lane docs-1116.
|
||||
2026-11-15 UTC | Sage (Lead) | Pack decision, exit 127 fix and single pane slices sp1 to sp14 (#1873) | PR #1963 b913f0f4c (pd with pr2), PR #1964 387f73a7a (r127), PRs #1965 to #1978 (sp1 to sp14), final c26879637 at 20:19Z; each deployed to uiorg 7350. sp15 launched 19:23Z on a wrong premise (a bus instances fault that did not exist) and closed 19:26Z with no change. Backfilled 2026-11-16 by lane docs-1116.
|
||||
@@ -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 |
|
||||
|
||||
@@ -586,3 +586,4 @@ git history + Gitea issues.
|
||||
|
||||
- 2026-09-26 (sage, lead): Jason's ruling: Sage leads the project, Darkwing is a collaborating seat, more seats to follow, development stays in T3 for now. The fleet Sage seat that took Invoice Ninja coordination outside Jason's instructions is being decommissioned; moving work onto the new stack is the fix. Suites all green. Rows 24 and 25 pushed (1685deb4..43d7574d). Open: about 11 days of uncommitted agent work in the tree (row 16 launch files, row 22, #1512, WUI evidence), 23 untracked aws-* skill directories in skills/ from 2026-09-21, and Jason's target for the next phase.
|
||||
- 2026-10-13 (sage, lead): Jason's PM re-test on 664199f7 is finished (Mos; PM run rcc0f72be8b17; Vikunja #228). Paging, the Board's held roles, the Messages page and the #229 loop (coder push 010d30cb, review, approve, PM close) all worked; #230 and #231 are done, #232 stays open for the secrets-path probe. Two faults checked and dropped: the reviewer did run the tests before its verdict, and the PM's clone did hold the row 95 Board code. Two filed: row 104 (#1598) seat git identity, row 105 (#1599) a review request says whether a reviewer is running. Rows 96, 101-105 briefed; row 85 released to build. Row 85's live steps, any bus restart and row 102's public/ change each need Mos's go. Row 100 waits on Jason (Vikunja #257). Formatting, Jason's direction: no formatting row now. Chat output will be formatted in the TUI and WebUI the way chat interfaces usually do it, made our own; T3 Code's chat is his example. Carry it into the TUI and WebUI chat work.
|
||||
- 2026-11-15 (sage, lead; written 2026-11-16 by lane docs-1116 from uidev/LEAD-1110.md and git): single pane state at c26879637 (#1873, PRs #1965 to #1978). One WebUI shell. System pages #/dashboard, #/inbox, #/agents, #/tasks and #/assistant cover every organization; #/queue stays its own page. Organization pages are #/orgs/<id>/... routes inside the same shell, with no reload and no mode switch (Lead ruling 03:33Z 11-15). Side by side is gone from the sidebar; the Assistant page holds up to three threads from any organization side by side, and #/side-by-side lands there. The organization page has KPI tiles from real reads, a workflow list and graph with edit, an agent drawer (?agent=<org>:<name>), and no Queue card. Where an instances answer carries no runs the page says running was not read, never 0. /api/config names an opaque `viewer` that keys kept Assistant pane messages. Applying a starter pack is the hire decision (PR #1963 b913f0f4c). Follow-ups: empty space under Active agent sessions at 1440, a drawer pending gap, viewer read once per tab with an unsalted hash, the open pane set kept per browser, the Dashboard org table scrolling sideways at 390. Detail: BUILD-LOG.md 2026-11-15 entries.
|
||||
@@ -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.
|
||||
+247
-56
@@ -11,7 +11,7 @@ import { initializeControl, processingStatus } from '../../processing-control/sr
|
||||
import { NAME as HARNESS_NAME } from '../../plugins/src/kinds.mjs';
|
||||
import { loadRequirements } from '../../tasks/src/requirements.mjs';
|
||||
import { MERGE, LandingRefusal, readLanding } from './landing.mjs';
|
||||
import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope } from '../../organization/src/vocabulary.mjs';
|
||||
import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope, SYSTEM_ONLY_REFUSAL, systemOnly } from '../../organization/src/vocabulary.mjs';
|
||||
|
||||
// Kept closed while S1 lands; its vocabulary is the integration authority.
|
||||
export const ACTIONS = Object.freeze([
|
||||
@@ -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,162 @@ 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');
|
||||
// #1873 triage-fence: a recorded pin never hires a system-only template, by reference or as the
|
||||
// inline copy of one (the inline composition below drops from).
|
||||
if (systemOnly(pin.template) || systemOnly(hire.entry?.from?.template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
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 +6947,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 +7006,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 +7026,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 +7041,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 +7065,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};
|
||||
@@ -7016,7 +7205,7 @@ export class Broker {
|
||||
// name; a file check (BusinessError) is invalid-request, anything else outcome-unknown.
|
||||
#packFail(e) {
|
||||
const code = e?.code ?? '';
|
||||
if (['credential-leak', 'pack-plan-stale', 'revision-conflict', 'invalid-request', 'human-required', 'not-configured'].includes(code)
|
||||
if (['credential-leak', 'pack-plan-stale', 'revision-conflict', 'invalid-request', 'human-required', 'not-configured', SYSTEM_ONLY_REFUSAL].includes(code)
|
||||
|| /^(starter-pack|definition|organization)-[a-z-]+$/.test(code)) fail(code);
|
||||
if (e?.name === 'BusinessError') fail('invalid-request');
|
||||
throw new BusError('outcome-unknown');
|
||||
@@ -7048,6 +7237,8 @@ export class Broker {
|
||||
if ((verb === "instance.hire" || verb === "instance.fire") && e.code === "definition-not-hireable") fail(e.code);
|
||||
// Row 194 (B7, webby-0094 N3): the limits writer's keep check, against the file, as well.
|
||||
if (e.code === "instance-kept") fail(e.code);
|
||||
// #1873 triage-fence: a system-only template refuses by its one code on every write.
|
||||
if (e.code === SYSTEM_ONLY_REFUSAL) fail(e.code);
|
||||
// #1873 T1: the definition writer's refusals pass by code; a composition refusal stays invalid-request.
|
||||
if (Object.hasOwn(DEFINITION_BUS_KEYS, verb) && /^definition-[a-z-]+$/.test(e.code ?? "")) fail(e.code);
|
||||
// Row 194 (brief item 8): a fire's or a delete's revoke failed, and nothing was written.
|
||||
|
||||
@@ -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]);
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -199,6 +199,13 @@ group(
|
||||
"R10: only the caller's own saved templates",
|
||||
"List your saved templates and use one of those names. A saved template is visible only to the owner who saved it."
|
||||
);
|
||||
// #1873 triage-fence: a template on the system-only list (organization vocabulary.mjs SYSTEM_ONLY)
|
||||
// joins no organization by any path.
|
||||
group(
|
||||
"template-system-only",
|
||||
"R8/R10: a system-only role template joins no organization",
|
||||
"This role template serves the system outside every organization. Pick another template or definition; no hire, change, pack, import or instance write gives an organization one."
|
||||
);
|
||||
group(
|
||||
"starter-pack-template-changed",
|
||||
"R8: a pack's hash pin must match the current template",
|
||||
@@ -218,6 +225,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 +245,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",
|
||||
|
||||
@@ -40,6 +40,7 @@ import { instanceSettings } from '../../organization/src/instance-settings.mjs';
|
||||
import { organizationWriter, OrganizationError, setReplyLimits } from '../../organization/src/organization.mjs';
|
||||
import { definitionVerbs, DEFINITION_BUS_VERBS } from '../../organization/src/definition-verbs.mjs';
|
||||
import { ORG_PREFIX, orgDefinitionName, compositionOf, readTemplate, entryFromTemplate, lineDiff, PRIMITIVES } from '../../organization/src/definitions.mjs';
|
||||
import { SYSTEM_ONLY_REFUSAL, systemOnly } from '../../organization/src/vocabulary.mjs';
|
||||
import { installedStarterPacks, readSavedTemplate } from '../../plugins/src/starter-pack.mjs';
|
||||
import { TemplateError, templateList, templatePreview, templateSave } from '../../organization/src/template-save.mjs';
|
||||
import { checkComposition } from '../../organization/src/composition.mjs';
|
||||
@@ -300,7 +301,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'); };
|
||||
@@ -313,7 +314,10 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
async function loadPack(name, actor) {
|
||||
if (typeof name !== 'string' || name.length > 128) bad();
|
||||
if (name.startsWith(SAVED_PREFIX)) return readSavedTemplate({ configDir, account: actor, name: name.slice(SAVED_PREFIX.length), rolesDir });
|
||||
const found = (await installed()).find(p => p.id === name);
|
||||
const { packs, refused } = await installedStarterPacks({ dataRoot, rolesDir });
|
||||
const found = packs.find(p => p.id === name);
|
||||
// #1873 triage-fence: an installed pack refused for naming a system-only template says so.
|
||||
if (!found && refused.some(r => r.name === name && r.code === SYSTEM_ONLY_REFUSAL)) throw new BusError(SYSTEM_ONLY_REFUSAL);
|
||||
if (!found) throw new BusError('starter-pack-not-found');
|
||||
return found;
|
||||
}
|
||||
@@ -332,6 +336,9 @@ function packOps({ writer, rolesDir, dataRoot, system, registryFor, assertClean,
|
||||
// The entry a pack definition writes: a template reference becomes the template's own entry, pinned
|
||||
// by its hash (a moved hash refuses), and a full entry is copied as it is. Neither carries rev.
|
||||
function entryOf(value) {
|
||||
// #1873 triage-fence: preview and apply both refuse a pack naming a system-only template, as a
|
||||
// reference or as the from of a full entry.
|
||||
if (systemOnly(value?.template) || systemOnly(value?.from?.template)) throw new BusError(SYSTEM_ONLY_REFUSAL);
|
||||
if (Object.hasOwn(value, 'template') && Object.hasOwn(value, 'sha256') && Object.keys(value).length === 2) {
|
||||
const template = readTemplate(rolesDir, value.template);
|
||||
if (template.sha256 !== value.sha256) throw new BusError('starter-pack-template-changed');
|
||||
@@ -501,9 +508,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();
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -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});
|
||||
});
|
||||
@@ -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
|
||||
@@ -39,7 +42,8 @@ const baselines = {
|
||||
// deadline; userCall shares transport(). Nonces, argv and limits are unchanged.
|
||||
// #1873 A3: STATUS maps credential-unbound, copy-refused, project-refused and project-agent-elsewhere
|
||||
// to 409; no proof or transport change.
|
||||
"packages/webui/src/bus.mjs": "d8f3e0eb5299fdb192e98a1238ca693aae7c36af9a21de72d5f5d39610589377",
|
||||
// #1873 triage-fence: STATUS maps template-system-only to 400; no proof or transport change.
|
||||
"packages/webui/src/bus.mjs": "cd08e1beb49e9e881bb1b308f2ab3343a480b47dd9b17ccbd16e120d341d7511",
|
||||
};
|
||||
const repoFile = path => new URL("../../../" + path, import.meta.url);
|
||||
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -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); }
|
||||
});
|
||||
@@ -43,7 +43,8 @@ test('Broker keeps the sandbox client import closure: only the listed imports, n
|
||||
// Row 236 (#1742, #436b) reads giteaName and parseGiteaUrl for the Gitea grant path.
|
||||
// FED R3 r5 (row 274, #414) reads covers, a user's grant check, from it.
|
||||
// Row 219 reads THREAD_DEFINITIONS from the same vocabulary for creative thread admission.
|
||||
"import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope } from '../../organization/src/vocabulary.mjs';",
|
||||
// #1873 triage-fence reads SYSTEM_ONLY_REFUSAL and systemOnly from the same vocabulary.
|
||||
"import { pluginName, ID_PATTERN, THREAD_DEFINITIONS, END_PROTECTED, forkProblem, forkUrl, credentialKind, validArgv, commandAllowed, HOST_ID, CREATIVE_DEFINITIONS, giteaName, parseGiteaUrl, covers, grantScopeOf, grantInScope, SYSTEM_ONLY_REFUSAL, systemOnly } from '../../organization/src/vocabulary.mjs';",
|
||||
]);
|
||||
assert.doesNotMatch(source, /\bimport\s*\(/);
|
||||
assert.doesNotMatch(readFileSync(new URL('../src/proxy-page-vocabulary.mjs', import.meta.url), 'utf8'), /\bimport\b/);
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
// #1873 lane triage-fence: through the broker, no organization gains the system-only Triage
|
||||
// template. Pack preview and apply, the Console hire start, the chief's hire.raise and
|
||||
// decision.raise, and instances.set add as the human and the tester each refuse with
|
||||
// template-system-only; the Console's hire template list omits triage. The coding pack still
|
||||
// previews as before. Fixtures live in a temp directory.
|
||||
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 { Broker } from '../src/broker.mjs';
|
||||
import { Store } from '../src/store.mjs';
|
||||
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';
|
||||
import { hireDecisions } from '../../organization/src/hire-decisions.mjs';
|
||||
import { organizationWriter } from '../../organization/src/organization.mjs';
|
||||
import { loadBusiness } from '../../organization/src/organization-config.mjs';
|
||||
import { businessDoc, rolesCopy, systemFor, writeJson } from '../../organization/tests/helpers.mjs';
|
||||
|
||||
const CODE = 'template-system-only';
|
||||
const SUBJECT = { provider: 'test', iss: 'https://issuer.test', sub: 'owner' };
|
||||
const ROUTE = { harness: 'pi', model: 'claude-opus-5-5' };
|
||||
|
||||
// The broker started as the runtime starts it, with the organization writer and installed packs.
|
||||
async function runtime(t) {
|
||||
const { startBroker } = await import('../src/runtime.mjs');
|
||||
const root = mkdtempSync(join(tmpdir(), 'sobus-'));
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root, 'demo');
|
||||
doc.plugins = { harness: ['pi'] };
|
||||
doc.roles.chief.vars = { ...ROUTE };
|
||||
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: [] } } };
|
||||
const businesses = { demo: { id: 'demo', human: 'jason', arbiters: { technical: 'chief', delivery: 'chief' }, roles, vars: { 'bus.tester': true } } };
|
||||
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 owner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
|
||||
const human = b.bindHuman({ business: 'demo', human: 'jason', via: 'cli', outsideAgent: true });
|
||||
const tester = b.bindTester({ business: 'demo' });
|
||||
const call = async (verb, args = {}, cap = owner) => b.request(cap, { verb, args });
|
||||
const file = () => readFileSync(join(root, 'businesses/demo.json'), 'utf8');
|
||||
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 });
|
||||
};
|
||||
return { b, root, rolesDir, owner, human, tester, call, file, install };
|
||||
}
|
||||
|
||||
// The A4 broker with the real hire service, so the chief's raise and the Console start reach it.
|
||||
function hires(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'sohire-')), rolesDir = rolesCopy(root);
|
||||
writeJson(join(root, 'businesses/demo.json'), { ...businessDoc(root, 'demo'), plugins: { harness: ['pi'] } });
|
||||
const storeRoot = join(root, 'data'); mkdirSync(storeRoot, { mode: 0o700 });
|
||||
const writer = organizationWriter({ dir: root, rolesDir }), store = new Store(storeRoot);
|
||||
const service = hireDecisions({ writer, rolesDir, dataRoot: storeRoot, configDir: root, assertClean: () => {} });
|
||||
const loaded = () => { const doc = loadBusiness('demo', { dir: root, rolesDir }); return { ...doc, roles: Object.fromEntries(Object.entries(doc.roles).map(([k, e]) => [k, { ...doc.definitions[e.definition], ...e }])) }; };
|
||||
const b = new Broker({ store, businesses: { demo: loaded() }, hires: service });
|
||||
t.after(() => { store.close(); rmSync(root, { recursive: true, force: true }); });
|
||||
const owner = b.bindConsole({ business: 'demo', human: 'jason', subject: SUBJECT });
|
||||
const chief = b.bindLaunch({ business: 'demo', role: 'chief', run: 'chief-run', harness: 'pi' });
|
||||
b.request(chief, { verb: 'role.claim' });
|
||||
const call = (cap, verb, args = {}) => b.request(cap, { verb, args });
|
||||
const triage = { template: 'triage', sha256: templateHash(rolesDir, 'triage') };
|
||||
const hire = (extra = {}) => ({ op: 'hire', level: 'org', name: 'sorter', role: triage, route: ROUTE, reason: 'Sort the inbox', ...extra });
|
||||
const decisions = () => store.get('SELECT count(*) n FROM decisions').n;
|
||||
return { owner, chief, call, hire, decisions };
|
||||
}
|
||||
|
||||
const refuses = async (promise) => assert.rejects(Promise.resolve().then(() => promise), (e) => e?.code === CODE);
|
||||
|
||||
test('pack preview refuses an installed pack that defines triage', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const pack = { ...codingPack(), id: 'sorting', label: 'Sorting' };
|
||||
pack.definitions = { ...pack.definitions, triage: { template: 'triage', sha256: templateHash(h.rolesDir, 'triage') } };
|
||||
h.install(pack);
|
||||
const before = h.file();
|
||||
await refuses(h.call('pack.preview.console', { pack: 'sorting' }));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('pack apply refuses an installed pack that defines triage', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const pack = { ...codingPack(), id: 'sorting', label: 'Sorting' };
|
||||
pack.definitions = { ...pack.definitions, triage: { template: 'triage', sha256: templateHash(h.rolesDir, 'triage') } };
|
||||
h.install(pack);
|
||||
const before = h.file();
|
||||
await refuses(h.call('pack.apply.console', { pack: 'sorting', digest: 'a'.repeat(64) }));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('instances.set add refuses triage for the human', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const { revision } = await h.call('instances', {}, h.human);
|
||||
const before = h.file();
|
||||
await refuses(h.call('instances.set', { revision, instance: 'sorter', op: 'add', definition: 'triage' }, h.human));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('instances.set add refuses triage for the tester', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const { revision } = await h.call('instances', {}, h.human);
|
||||
const before = h.file();
|
||||
await refuses(h.call('instances.set', { revision, instance: 'sorter', op: 'add', definition: 'triage' }, h.tester));
|
||||
assert.equal(h.file(), before);
|
||||
});
|
||||
|
||||
test('the instances read offers no triage add', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const view = await h.call('instances', {}, h.human);
|
||||
assert.equal(Object.hasOwn(view.definitions, 'triage'), false);
|
||||
});
|
||||
|
||||
test('the Console hire start refuses a triage template', async (t) => {
|
||||
const f = hires(t);
|
||||
await refuses(f.call(f.owner, 'hire.start.console', f.hire()));
|
||||
assert.equal(f.decisions(), 0);
|
||||
});
|
||||
|
||||
test('the chief hire.raise refuses a triage template at org, project and root level', async (t) => {
|
||||
const f = hires(t);
|
||||
await refuses(f.call(f.chief, 'hire.raise', f.hire()));
|
||||
await refuses(f.call(f.chief, 'hire.raise', f.hire({ level: 'project', project: 'stack' })));
|
||||
await refuses(f.call(f.chief, 'hire.raise', f.hire({ level: 'root' })));
|
||||
assert.equal(f.decisions(), 0);
|
||||
});
|
||||
|
||||
test('the chief decision.raise naming role.hire or role.change refuses a triage template', async (t) => {
|
||||
const f = hires(t);
|
||||
await refuses(f.call(f.chief, 'decision.raise', { action: 'role.hire', hire: f.hire() }));
|
||||
await refuses(f.call(f.chief, 'decision.raise', { action: 'role.change', hire: f.hire({ op: 'change', name: 'coder' }) }));
|
||||
assert.equal(f.decisions(), 0);
|
||||
});
|
||||
|
||||
test('the Console hire template list omits triage and keeps the rest', async (t) => {
|
||||
const f = hires(t);
|
||||
const names = (await f.call(f.owner, 'hire.templates.console')).templates.map((x) => x.name);
|
||||
assert.ok(!names.includes('triage'));
|
||||
assert.ok(names.includes('coder') && names.includes('reviewer'));
|
||||
});
|
||||
|
||||
// The guard: a shipped pack previews and applies as before, and an installed pack with no triage loads.
|
||||
test('the shipped coding pack and an installed pack without triage preview as before', async (t) => {
|
||||
const h = await runtime(t);
|
||||
const preview = await h.call('pack.preview.console', { pack: 'coding' });
|
||||
assert.match(preview.digest, /^[a-f0-9]{64}$/);
|
||||
h.install({ ...codingPack(), id: 'plain', label: 'Plain' });
|
||||
const plain = await h.call('pack.preview.console', { pack: 'plain' });
|
||||
assert.match(plain.digest, /^[a-f0-9]{64}$/);
|
||||
const out = await h.call('pack.apply.console', { pack: 'coding', digest: preview.digest });
|
||||
assert.deepEqual(out.hires.map((x) => [x.name, x.state]), [['pm-1', 'hired'], ['coder-1', 'hired'], ['reviewer-1', 'hired']]);
|
||||
});
|
||||
@@ -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 }])
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 } = {}) {
|
||||
|
||||
@@ -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 };
|
||||
|
||||
@@ -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');
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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');
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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');
|
||||
|
||||
@@ -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 });
|
||||
|
||||
@@ -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>`');
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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';
|
||||
|
||||
@@ -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']);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
});
|
||||
@@ -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)` });
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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.
|
||||
@@ -9,6 +9,7 @@ import { join } from "node:path";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { checkDefinitions } from "./definitions.mjs";
|
||||
import { loadRole } from "./role.mjs";
|
||||
import { SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
import { checkVars, mergeVars, REGISTRY } from "./vars.mjs";
|
||||
import { deepFreeze, isPlainObject, readJsonFile, rejectUnknownKeys, requireDistinctList, requireId, requireObject } from "./util.mjs";
|
||||
|
||||
@@ -27,6 +28,8 @@ export function rootAgentsPath(configDir) {
|
||||
function definitionOf(name, at, rolesDir, cache, definitions = {}) {
|
||||
if (typeof name === "string" && name.startsWith("org:") && Object.hasOwn(definitions,name)) return definitions[name];
|
||||
requireId(name, `${at}.definition`);
|
||||
// #1873 triage-fence: no root or project agent, and so no copy of one, names a system-only template.
|
||||
if (systemOnly(name)) refuse(`${SYSTEM_ONLY_REFUSAL}: ${at}.definition names ${name}, a template no organization may hold`);
|
||||
if (!cache.has(name)) {
|
||||
// A role refusal names host paths; this message travels to the Console, so it names none.
|
||||
try { cache.set(name, loadRole(rolesDir, name)); }
|
||||
|
||||
@@ -15,6 +15,7 @@ import { OrganizationError } from "./organization.mjs";
|
||||
import {
|
||||
diffDefinition, entryFromTemplate, instancesNaming, readTemplate, templateHashes, checkDefinitionName, ORG_PREFIX,
|
||||
} from "./definitions.mjs";
|
||||
import { SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
|
||||
// The verb names the policy table maps, following R1's hire.resolve.console.
|
||||
export const DEFINITION_VERBS = Object.freeze({
|
||||
@@ -64,6 +65,8 @@ export function definitionVerbs({ writer, rolesDir, assertClean }) {
|
||||
// Copies a template into definitions with from set to its name and current hash.
|
||||
function importTemplate(id, { revision, template, as = template }, caller) {
|
||||
authorize(caller, "import");
|
||||
// #1873 triage-fence: no organization imports a system-only template.
|
||||
if (systemOnly(template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
checkDefinitionName(as, "definition name");
|
||||
const source = readTemplate(rolesDir, template);
|
||||
const result = writer.setDefinition(id, as, (current) => {
|
||||
@@ -125,5 +128,5 @@ export function definitionVerbs({ writer, rolesDir, assertClean }) {
|
||||
return { organization: id, revision, ...diffDefinition(document, name, rolesDir) };
|
||||
}
|
||||
|
||||
return { import: importTemplate, edit, invent, remove, list, show, diff, templates: () => templateHashes(rolesDir) };
|
||||
return { import: importTemplate, edit, invent, remove, list, show, diff, templates: () => templateHashes(rolesDir).filter(({ template }) => !systemOnly(template)) };
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import { createHash } from "node:crypto";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { buildRegistry, checkComposition } from "./composition.mjs";
|
||||
import { validateRoleDocument } from "./role.mjs";
|
||||
import { ID_PATTERN } from "./vocabulary.mjs";
|
||||
import { ID_PATTERN, SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
import { canonicalJson, deepFreeze } from "./util.mjs";
|
||||
|
||||
export const ORG_PREFIX = "org:";
|
||||
@@ -88,6 +88,8 @@ export function checkDefinition(name, entry, { assertClean = NO_STORE, where = "
|
||||
keysOnly(entry.from, FROM_KEYS, `${at}.from`);
|
||||
if (typeof entry.from.template !== "string" || !ID_PATTERN.test(entry.from.template)) refuse(`${at}.from.template must be a template name matching ${ID_PATTERN}`);
|
||||
if (typeof entry.from.sha256 !== "string" || !HEX64.test(entry.from.sha256)) refuse(`${at}.from.sha256 must be 64 lowercase hex characters`);
|
||||
// #1873 triage-fence: no organization definition copies a system-only template.
|
||||
if (systemOnly(entry.from.template)) refuse(`${SYSTEM_ONLY_REFUSAL}: ${at}.from.template names ${entry.from.template}, a template no organization may hold`);
|
||||
}
|
||||
if (!plain(entry.role)) refuse(`${at}.role must be a JSON object`);
|
||||
keysOnly(entry.role, ROLE_KEYS, `${at}.role`);
|
||||
|
||||
@@ -8,7 +8,7 @@ import { compositionOf, entryFromTemplate, readTemplate, templateHashes } from '
|
||||
import { readRootAgentsFile, changeRootAgent } from './agent-levels-write.mjs';
|
||||
import { validateBusinessDocument } from './organization-config.mjs';
|
||||
import { canonicalJson, isPlainObject, readJsonFile } from './util.mjs';
|
||||
import { ID_PATTERN, NETWORKS } from './vocabulary.mjs';
|
||||
import { ID_PATTERN, NETWORKS, SYSTEM_ONLY_REFUSAL, systemOnly } from './vocabulary.mjs';
|
||||
import { OrganizationError } from './organization.mjs';
|
||||
import { resolveInstance } from './resolve.mjs';
|
||||
import { checkRoutes } from './launch-settings.mjs';
|
||||
@@ -204,6 +204,8 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
if ('template' in input.role) { id(input.role.template); if (!/^[a-f0-9]{64}$/.test(input.role.sha256??'') || Object.keys(input.role).length!==2) fail('invalid-request'); }
|
||||
if ('definition' in input.role) { id(input.role.definition); if (!Number.isSafeInteger(input.role.rev) || Object.keys(input.role).length!==2) fail('invalid-request'); }
|
||||
if ('inline' in input.role && Object.keys(input.role).length!==1) fail('invalid-request');
|
||||
// #1873 triage-fence: no hire or change at any level copies a system-only template.
|
||||
if (systemOnly(input.role.template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
} else if (['role','route','credentials','personality'].some(k=>k in input)) fail('invalid-request');
|
||||
const {document:doc,revision} = writer.read(business);
|
||||
const loaded = validateBusinessDocument(doc,`${business}.json`,{rolesDir,dataRoot});
|
||||
@@ -226,6 +228,7 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
if ('template' in ref) { const template=readTemplate(rolesDir,ref.template); if(template.sha256!==ref.sha256) fail('decision-stale'); entry=entryFromTemplate(template); }
|
||||
else if ('definition' in ref) { entry=doc.definitions?.[ref.definition]; if(!entry || entry.rev!==ref.rev) fail('definition-rev-conflict'); entry=structuredClone(entry); }
|
||||
else entry={rev:1,role:{},instructions:''};
|
||||
if (systemOnly(entry.from?.template)) fail(SYSTEM_ONLY_REFUSAL);
|
||||
let c='inline' in ref ? structuredClone(ref.inline) : compositionOf(entry);
|
||||
if ('credentials' in input) c.credentials=structuredClone(input.credentials);
|
||||
if ('personality' in input) c.personality=structuredClone(input.personality);
|
||||
@@ -387,5 +390,5 @@ export function hireDecisions({ writer, rolesDir, configDir, dataRoot, assertCle
|
||||
const result=writer.reverseHireDecision(business,p,{...caller,beforeWrite:guard,beforePublish:publicationGuard});
|
||||
return {...result,...(r.op==='change' && stopped?.running?{relaunch:publicOf(p)}:{})};
|
||||
}
|
||||
return {prepare,reverse,templates:()=>({templates:templateHashes(rolesDir).map(({template,sha256})=>({name:template,sha256}))}),preview:async(business,decision,caller)=>{const p=await adjusted(business,decision,caller.adjust);if(Date.parse(p.expiresAt)<=(caller.now??Date.now)())fail('decision-expired');authorizeHire(publicOf(p),caller);return publicOf(p);},rootRefusal,rootActive:name=>rootRefusal(name)===null,check:async(...args)=>{await check(...args);},apply,read: decision => publicOf(read(decision))};
|
||||
return {prepare,reverse,templates:()=>({templates:templateHashes(rolesDir).filter(({template})=>!systemOnly(template)).map(({template,sha256})=>({name:template,sha256}))}),preview:async(business,decision,caller)=>{const p=await adjusted(business,decision,caller.adjust);if(Date.parse(p.expiresAt)<=(caller.now??Date.now)())fail('decision-expired');authorizeHire(publicOf(p),caller);return publicOf(p);},rootRefusal,rootActive:name=>rootRefusal(name)===null,check:async(...args)=>{await check(...args);},apply,read: decision => publicOf(read(decision))};
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import { resolveInstance } from "./resolve.mjs";
|
||||
import { loadRole } from "./role.mjs";
|
||||
import { refuse } from "./errors.mjs";
|
||||
import { isPlainObject, canonicalJson } from "./util.mjs";
|
||||
import { CREATIVE_DEFINITIONS, CREATIVE_SERVICE, END_PROTECTED, HOST_SERVICE, ID_PATTERN, checkGrantScope, grantScopeOf } from "./vocabulary.mjs";
|
||||
import { CREATIVE_DEFINITIONS, CREATIVE_SERVICE, END_PROTECTED, HOST_SERVICE, ID_PATTERN, SYSTEM_ONLY_REFUSAL, checkGrantScope, grantScopeOf, systemOnly } from "./vocabulary.mjs";
|
||||
|
||||
const SET_KEYS = ["revision", "instance", "op", "definition", "vars", "launch", "tracker"];
|
||||
const VETO_KEYS = ["revision", "op", "name"];
|
||||
@@ -93,6 +93,8 @@ const sameCredentialServices = (before, after) => credentialServices(before).joi
|
||||
// Row 194 (brief item 7): the human's add passes credentials true and lifts it. The tester's add,
|
||||
// change and hire keep it.
|
||||
function definitionFor(rolesDir, name, { credentials = false } = {}) {
|
||||
// #1873 triage-fence: no add or change of definition gives an instance a system-only template.
|
||||
if (systemOnly(name)) throw new OrganizationError(SYSTEM_ONLY_REFUSAL);
|
||||
if (closed(name)) throw new OrganizationError("organization-definition-refused");
|
||||
const definition = loadRole(rolesDir, name);
|
||||
if (definition.roleVersion !== 2) throw new OrganizationError("invalid-request", `role definition ${name} is version 1`);
|
||||
@@ -153,6 +155,8 @@ export function instanceSettings({ dir, rolesDir, system, levels = () => null, r
|
||||
const out = {};
|
||||
for (const file of readdirSync(rolesDir).filter(f => f.endsWith(".json")).sort()) {
|
||||
const name = file.slice(0, -5);
|
||||
// #1873 triage-fence: the add list never offers a system-only template.
|
||||
if (systemOnly(name)) continue;
|
||||
let definition;
|
||||
try {
|
||||
definition = loadRole(rolesDir, name);
|
||||
@@ -183,6 +187,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 {
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -12,7 +12,7 @@ import { checkVars } from "./vars.mjs";
|
||||
import { parseCredentialRef } from "./credentials.mjs";
|
||||
import { loadRole } from "./role.mjs";
|
||||
import { checkDefinition, checkDefinitions, checkDefinitionName, orgDefinitionName, ORG_PREFIX } from "./definitions.mjs";
|
||||
import { END_PROTECTED, parseRepoRemote } from "./vocabulary.mjs";
|
||||
import { END_PROTECTED, parseRepoRemote, SYSTEM_ONLY_REFUSAL, systemOnly } from "./vocabulary.mjs";
|
||||
import { checkPlugins, checkUsageSettings, NAME as KIND_NAME } from "../../plugins/src/kinds.mjs";
|
||||
import { checkMapping } from "../../library/src/mapping.mjs";
|
||||
import { forkProblem, giteaName, parseGiteaUrl, HOST_SERVICE, CREATIVE_DEFINITIONS } from "./vocabulary.mjs";
|
||||
@@ -113,6 +113,8 @@ function checkPin(pin, where) {
|
||||
if (!shape) refuse(`${where} must be {template, sha256}, {definition, rev} or {inline}`);
|
||||
if (shape[0] === "template") {
|
||||
requireId(pin.template, `${where}.template`);
|
||||
// #1873 triage-fence: no pack proposal pins a system-only template.
|
||||
if (systemOnly(pin.template)) refuse(`${SYSTEM_ONLY_REFUSAL}: ${where}.template names ${pin.template}, a template no organization may hold`);
|
||||
if (typeof pin.sha256 !== "string" || !HEX64.test(pin.sha256)) refuse(`${where}.sha256 must be 64 lowercase hex characters`);
|
||||
} else if (shape[0] === "definition") {
|
||||
checkDefinitionName(pin.definition, `${where}.definition`);
|
||||
@@ -285,8 +287,11 @@ function checkRoles(roles, file, rolesDir, business, hasLibrary, orgDefinitions)
|
||||
rejectUnknownKeys(entry, ["definition", "holder", "vars", "tracker", "credentials", "identity", "publish", "hosts", "hireDecision"], at);
|
||||
// #1873 T1: "org:<name>" names one of this file's definitions; anything else is a template.
|
||||
const orgName = orgDefinitionName(entry.definition);
|
||||
if (orgName === null) requireId(entry.definition, `${at}.definition`);
|
||||
else if (!Object.hasOwn(orgDefinitions, ORG_PREFIX + checkDefinitionName(orgName, `${at}.definition after org:`))) {
|
||||
if (orgName === null) {
|
||||
requireId(entry.definition, `${at}.definition`);
|
||||
// #1873 triage-fence: no instance names a system-only template.
|
||||
if (systemOnly(entry.definition)) refuse(`${SYSTEM_ONLY_REFUSAL}: ${at}.definition names ${entry.definition}, a template no organization may hold`);
|
||||
} else if (!Object.hasOwn(orgDefinitions, ORG_PREFIX + checkDefinitionName(orgName, `${at}.definition after org:`))) {
|
||||
refuse(`definition-missing: ${at}.definition names ${ORG_PREFIX}${orgName}, which definitions doesn't declare`);
|
||||
}
|
||||
const definition = Object.hasOwn(definitions, entry.definition) ? definitions[entry.definition]
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -209,6 +209,15 @@ export const THREAD_DEFINITIONS = Object.freeze([THREAD_DEFINITION, ...CREATIVE_
|
||||
// organization write may give an instance one of them, except the human's instances.set for a
|
||||
// creative definition (row 213).
|
||||
export const END_PROTECTED = THREAD_DEFINITIONS;
|
||||
// #1873 lane triage-fence: the shipped templates no organization may hold. Jason approved the
|
||||
// Triage template on 2026-11-16; its use outside an organization waits for his ruling. Every path
|
||||
// by which an organization could gain a role reads this list and refuses with SYSTEM_ONLY_REFUSAL:
|
||||
// a hire or change at org, project or root level, a pack preview or apply, instances.set, the
|
||||
// organization file's own validation, and every template list a page offers. The template itself
|
||||
// still loads and validates as a template.
|
||||
export const SYSTEM_ONLY = Object.freeze(["triage"]);
|
||||
export const SYSTEM_ONLY_REFUSAL = "template-system-only";
|
||||
export const systemOnly = name => typeof name === "string" && SYSTEM_ONLY.includes(name);
|
||||
|
||||
// Row 199 (#1697, design D9c): the Gitea URL parse. It lives here because the broker reads it and
|
||||
// this file imports nothing. Gitea's name rule for users and repositories: letters, digits, "_", "."
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// #1873 lane triage-fence: the Triage template is system-only. Jason approved the template on
|
||||
// 2026-11-16; no organization may hold it until he rules on its use outside one. Every place an
|
||||
// organization could gain it refuses with one code, template-system-only, and the template itself
|
||||
// still loads and validates as a template. Fixtures live in a temp directory.
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
// A namespace import, so a run against the commit before the fence fails test by test, not at load.
|
||||
import * as vocabulary from "../src/vocabulary.mjs";
|
||||
import { checkDefinition, entryFromTemplate, readTemplate, templateHash, templateHashes } from "../src/definitions.mjs";
|
||||
import { loadRole } from "../src/role.mjs";
|
||||
import { validateBusinessDocument } from "../src/organization-config.mjs";
|
||||
import { checkProjectAgents, checkRootAgents } from "../src/agent-levels.mjs";
|
||||
import { hireDecisions } from "../src/hire-decisions.mjs";
|
||||
import { instanceSettings } from "../src/instance-settings.mjs";
|
||||
import { definitionVerbs } from "../src/definition-verbs.mjs";
|
||||
import { organizationWriter } from "../src/organization.mjs";
|
||||
import { ROLE_RIGHTS } from "../src/org-rights.mjs";
|
||||
import { checkPack, installedStarterPacks } from "../../plugins/src/starter-pack.mjs";
|
||||
import { businessDoc, rolesCopy, systemFor, tmp, writeJson } from "./helpers.mjs";
|
||||
|
||||
const CODE = "template-system-only";
|
||||
const coded = (e) => e?.code === CODE;
|
||||
const prefixed = (e) => e?.name === "BusinessError" && e.message.startsWith(`${CODE}: `);
|
||||
const OWNER = { actor: "jason", agent: false, rights: ["org.hire"], owner: true, instanceOwner: true, subject: { provider: "test", iss: "https://test", sub: "owner" } };
|
||||
const DEF_OWNER = { actor: "jason", rights: [...ROLE_RIGHTS.owner], agent: false };
|
||||
const ROUTE = { harness: "pi", model: "claude-opus-5-5" };
|
||||
|
||||
function rootDir(t) {
|
||||
const root = tmp();
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
return root;
|
||||
}
|
||||
|
||||
function hireSetup(t) {
|
||||
const root = mkdtempSync(join(tmpdir(), "so-"));
|
||||
t.after(() => rmSync(root, { recursive: true, force: true }));
|
||||
const rolesDir = rolesCopy(root);
|
||||
writeJson(join(root, "businesses/demo.json"), { ...businessDoc(root, "demo"), plugins: { harness: ["pi"] } });
|
||||
const writer = organizationWriter({ dir: root, rolesDir });
|
||||
const dataRoot = join(root, "data");
|
||||
mkdirSync(dataRoot, { mode: 0o700 });
|
||||
const service = hireDecisions({ writer, rolesDir, configDir: root, dataRoot, assertClean: () => {} });
|
||||
const triage = { template: "triage", sha256: templateHash(rolesDir, "triage") };
|
||||
let n = 0;
|
||||
const prepare = (extra) => service.prepare("demo", { op: "hire", level: "org", name: "sorter", role: triage, route: ROUTE, reason: "Sort the inbox", ...extra },
|
||||
{ id: `1111111${n++}-1111-4111-8111-111111111111`, expiresAt: "2099-01-01T00:00:00.000Z" });
|
||||
return { root, rolesDir, writer, service, prepare, triage };
|
||||
}
|
||||
|
||||
function settingsSetup(t) {
|
||||
const root = rootDir(t);
|
||||
const rolesDir = rolesCopy(root);
|
||||
const dir = join(root, "config");
|
||||
const doc = businessDoc(root, "acme");
|
||||
doc.plugins = { harness: ["pi", "claude-code"] };
|
||||
writeJson(join(dir, "businesses", "acme.json"), doc);
|
||||
return { rolesDir, settings: instanceSettings({ dir, rolesDir, system: systemFor(root) }) };
|
||||
}
|
||||
|
||||
function verbsSetup(t) {
|
||||
const root = rootDir(t);
|
||||
const dir = join(root, "config");
|
||||
const rolesDir = rolesCopy(root);
|
||||
writeJson(join(dir, "businesses/acme.json"), businessDoc(root));
|
||||
const writer = organizationWriter({ dir, rolesDir });
|
||||
return { root, dir, rolesDir, writer, verbs: definitionVerbs({ writer, rolesDir, assertClean: () => {} }) };
|
||||
}
|
||||
|
||||
test("the list is one name, triage, and its refusal code is template-system-only", () => {
|
||||
assert.deepEqual([...(vocabulary.SYSTEM_ONLY ?? [])], ["triage"]);
|
||||
assert.equal(vocabulary.SYSTEM_ONLY_REFUSAL, CODE);
|
||||
assert.equal(vocabulary.systemOnly?.("triage"), true);
|
||||
assert.equal(vocabulary.systemOnly?.("coder"), false);
|
||||
assert.equal(vocabulary.systemOnly?.(undefined), false);
|
||||
});
|
||||
|
||||
test("triage still loads and validates as a template", (t) => {
|
||||
const rolesDir = rolesCopy(rootDir(t));
|
||||
const role = loadRole(rolesDir, "triage");
|
||||
assert.equal(role.roleVersion, 2);
|
||||
const source = readTemplate(rolesDir, "triage");
|
||||
assert.match(source.sha256, /^[a-f0-9]{64}$/);
|
||||
assert.ok(templateHashes(rolesDir).some(({ template }) => template === "triage"));
|
||||
});
|
||||
|
||||
test("hire refuses a triage template at org level", async (t) => {
|
||||
const f = hireSetup(t);
|
||||
await assert.rejects(f.prepare(), coded);
|
||||
});
|
||||
|
||||
test("hire refuses a triage template at project level", async (t) => {
|
||||
const f = hireSetup(t);
|
||||
await assert.rejects(f.prepare({ level: "project", project: "stack" }), coded);
|
||||
});
|
||||
|
||||
test("hire refuses a triage template at root level", async (t) => {
|
||||
const f = hireSetup(t);
|
||||
await assert.rejects(f.prepare({ level: "root" }), coded);
|
||||
});
|
||||
|
||||
test("a change refuses to move an org instance onto triage", async (t) => {
|
||||
const f = hireSetup(t);
|
||||
await assert.rejects(f.prepare({ op: "change", name: "coder" }), coded);
|
||||
});
|
||||
|
||||
test("the hire template list a page offers omits triage and keeps every other template", (t) => {
|
||||
const f = hireSetup(t);
|
||||
const offered = f.service.templates().templates.map(({ name }) => name);
|
||||
assert.ok(!offered.includes("triage"));
|
||||
assert.deepEqual(offered, templateHashes(f.rolesDir).map(({ template }) => template).filter((n) => n !== "triage"));
|
||||
});
|
||||
|
||||
test("instances add refuses triage for the human and the tester", (t) => {
|
||||
const f = settingsSetup(t);
|
||||
for (const actor of ["jason", "tester"]) {
|
||||
const revision = f.settings.read("acme").revision;
|
||||
assert.throws(() => f.settings.set("acme", { revision, instance: "sorter", op: "add", definition: "triage" }, actor), coded, actor);
|
||||
}
|
||||
});
|
||||
|
||||
test("instances change of definition refuses triage", (t) => {
|
||||
const f = settingsSetup(t);
|
||||
const revision = f.settings.read("acme").revision;
|
||||
assert.throws(() => f.settings.set("acme", { revision, instance: "coder", op: "change", definition: "triage" }, "jason"), coded);
|
||||
});
|
||||
|
||||
test("the instances add list omits triage", (t) => {
|
||||
const f = settingsSetup(t);
|
||||
assert.equal(Object.hasOwn(f.settings.read("acme").definitions, "triage"), false);
|
||||
});
|
||||
|
||||
test("an organization file whose roles name triage is refused", (t) => {
|
||||
const root = rootDir(t);
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root);
|
||||
doc.roles.sorter = { definition: "triage" };
|
||||
assert.throws(() => validateBusinessDocument(doc, join(root, "acme.json"), { rolesDir }), prefixed);
|
||||
});
|
||||
|
||||
test("an organization definition copied from triage is refused", (t) => {
|
||||
const rolesDir = rolesCopy(rootDir(t));
|
||||
const entry = entryFromTemplate(readTemplate(rolesDir, "triage"));
|
||||
assert.throws(() => checkDefinition("sorter", entry), prefixed);
|
||||
});
|
||||
|
||||
test("a root agent naming triage is refused", (t) => {
|
||||
const rolesDir = rolesCopy(rootDir(t));
|
||||
assert.throws(() => checkRootAgents({ agentsVersion: 1, agents: { sorter: { definition: "triage" } } }, { rolesDir }), prefixed);
|
||||
});
|
||||
|
||||
test("a project agent naming triage is refused", (t) => {
|
||||
const rolesDir = rolesCopy(rootDir(t));
|
||||
assert.throws(() => checkProjectAgents({ sorter: { definition: "triage" } }, { rolesDir, where: "projects.stack.agents" }), prefixed);
|
||||
});
|
||||
|
||||
test("a pack record proposing a triage hire is refused", (t) => {
|
||||
const root = rootDir(t);
|
||||
const rolesDir = rolesCopy(root);
|
||||
const doc = businessDoc(root);
|
||||
doc.packs = [{ id: "coding", version: "1.0.0", sha256: "a".repeat(64), origin: "shipped", scope: "org", project: null,
|
||||
at: "2026-11-12T20:00:00.000Z", by: "jason", added: [], proposedHires: [{ name: "sorter-1", pin: { template: "triage", sha256: "a".repeat(64) } }] }];
|
||||
assert.throws(() => validateBusinessDocument(doc, join(root, "acme.json"), { rolesDir }), prefixed);
|
||||
});
|
||||
|
||||
test("import refuses triage and the definitions template list omits it", (t) => {
|
||||
const f = verbsSetup(t);
|
||||
const revision = f.writer.read("acme").revision;
|
||||
assert.throws(() => f.verbs.import("acme", { revision, template: "triage" }, DEF_OWNER), coded);
|
||||
const listed = f.verbs.templates().map(({ template }) => template);
|
||||
assert.deepEqual(listed, templateHashes(f.rolesDir).map(({ template }) => template).filter((n) => n !== "triage"));
|
||||
});
|
||||
|
||||
test("a starter pack naming triage is refused when checked", async (t) => {
|
||||
const rolesDir = rolesCopy(rootDir(t));
|
||||
const { starterPack } = await import("../../plugins/starter-pack/coding/index.mjs");
|
||||
const doc = starterPack();
|
||||
doc.definitions = { ...doc.definitions, triage: { template: "triage", sha256: templateHash(rolesDir, "triage") } };
|
||||
assert.throws(() => checkPack(doc, { origin: "installed", rolesDir, name: doc.id }), coded);
|
||||
});
|
||||
|
||||
// The guard: the fence changes nothing for any other template or any shipped pack.
|
||||
test("every other shipped template imports as before and every shipped pack loads unchanged", async (t) => {
|
||||
const f = verbsSetup(t);
|
||||
const all = templateHashes(f.rolesDir).map(({ template }) => template);
|
||||
const others = all.filter((n) => n !== "triage");
|
||||
assert.equal(others.length, all.length - 1);
|
||||
// Each template's import outcome, measured on 5c7194e05 before the fence: chief-of-staff carries
|
||||
// role.hire, which a hired agent may not hold, so its import refused before and still does.
|
||||
const refusedBefore = ["chief-of-staff"];
|
||||
const outcome = {};
|
||||
for (const template of others) {
|
||||
try {
|
||||
f.verbs.import("acme", { revision: f.writer.read("acme").revision, template }, DEF_OWNER);
|
||||
outcome[template] = "imported";
|
||||
} catch (e) {
|
||||
assert.ok(!String(e.message).includes(CODE) && e.code !== CODE, template);
|
||||
outcome[template] = "refused";
|
||||
}
|
||||
}
|
||||
assert.deepEqual(Object.keys(outcome).filter((n) => outcome[n] === "refused"), refusedBefore.filter((n) => others.includes(n)));
|
||||
const defs = f.writer.read("acme").document.definitions;
|
||||
assert.deepEqual(Object.keys(defs).sort(), others.filter((n) => outcome[n] === "imported").sort());
|
||||
const { packs, refused } = await installedStarterPacks({ dataRoot: null });
|
||||
assert.deepEqual(refused, []);
|
||||
assert.deepEqual(packs.map((p) => p.id).sort(), ["business-management", "coding", "creative-writing", "marketing", "montage"]);
|
||||
});
|
||||
@@ -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");
|
||||
});
|
||||
|
||||
|
||||
@@ -258,6 +258,24 @@ export returns:
|
||||
`gateTimeout`, `bundle`, `env`, `turnEnd`, `outputPolicy` and `transcript` give its
|
||||
sandbox binds, web, tool names, S0 lines, bundle files, adapter variables,
|
||||
how a turn ends and where its transcripts land.
|
||||
- `envNames` and `installRoots({env})` (#1873 triage-fences) are optional and
|
||||
outside `kinds.mjs`. A session the Console hosts with no organization
|
||||
(Triage) reads them; organization launches do not. `envNames` lists the
|
||||
names `env()` returns, less the provider's. The host takes a route's
|
||||
`harnessEnv` name only when it is listed here and is not one the host
|
||||
always refuses: `MOSAIC_*`, `NODE_*`, `LD_*`, `DYLD_*`, `PYTHON*`, `BASH_*`,
|
||||
`GIT_*`, `MALLOC_*`, `NPM_CONFIG_*`, `XDG_*`, any name ending in `_DIR`,
|
||||
`_CONF` or `_CONFIG`, PATH, HOME, TMPDIR, ENV, the founder's and the
|
||||
provider's names, and named shell, proxy, libc, OpenSSL and Java hooks. `installRoots` lists the directories
|
||||
where the adapter and the mounts live. A hosted adapter or mount source
|
||||
must resolve inside one of them, and never in or around the data root,
|
||||
the config directory, HOME, `/srv/mosaic` or a path with a `secret`
|
||||
segment. HOME does not count against a source inside the stack's own
|
||||
code, so a copy or a worktree under HOME still passes. Every claude-code
|
||||
name is `MOSAIC_*`, so a hosted session cannot run Claude Code yet. pi's
|
||||
`MOSAIC_TOOLS`, `MOSAIC_EXTENSIONS` and `MOSAIC_THINKING` are refused the
|
||||
same way, so a hosted pi gets no tools and no extension until the host
|
||||
sets those names itself.
|
||||
- `compactions({store, cursors, budget, streams, first})` reads a thread
|
||||
session's native store for row 270's compaction count (row 307). Core keeps
|
||||
the ledger (`packages/seat/src/compactions.mjs`) and passes `store` as
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
// session.json. packages/plugins/README.md lists the interface.
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { accessSync, constants, realpathSync, statSync } from "node:fs";
|
||||
import { delimiter, isAbsolute, join } from "node:path";
|
||||
import { delimiter, dirname, isAbsolute, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { claudeBuiltins, MCP_PREFIX } from "../../../harness/src/gate.mjs";
|
||||
import { hasSessionCredential, SESSION_CREDENTIALS } from "../../../seat/src/session.mjs";
|
||||
@@ -145,6 +145,16 @@ export function env({ files, policy, session, proxy = null }) {
|
||||
};
|
||||
}
|
||||
|
||||
// #1873 triage-fences: the names env() returns, less the proxy's, and the directories its adapter
|
||||
// and mounts live in: the pinned binary's when MOSAIC_CLAUDE_BIN is set. A hosted session's host
|
||||
// (Triage) takes harnessEnv names and mount sources only from these; launches don't read them.
|
||||
export const envNames = Object.freeze(["MOSAIC_TOOLS", "MOSAIC_CLAUDE_SETTINGS", "MOSAIC_CLAUDE_MCP_CONFIG", "MOSAIC_THINKING", "MOSAIC_MODEL_ACTIVITY_SOURCE"]);
|
||||
export function installRoots({ env = {} } = {}) {
|
||||
const roots = [join(REPO, "adapters", "claude"), join(REPO, "tools", "unslop-hook")];
|
||||
if (env.MOSAIC_CLAUDE_BIN) roots.push(dirname(realpathSync(env.MOSAIC_CLAUDE_BIN)));
|
||||
return roots;
|
||||
}
|
||||
|
||||
// A turn ends when claude exits; there is no marker.
|
||||
export const turnEnd = () => "exit";
|
||||
export const transcript = ({ runDir, store = null }) => (store ? store.projects : join(runDir, "home", ".claude", "projects"));
|
||||
|
||||
@@ -118,6 +118,14 @@ export function env({ policy, tools, session, proxy = null }) {
|
||||
};
|
||||
}
|
||||
|
||||
// #1873 triage-fences: the names env() returns, less the provider key, and the directories its
|
||||
// adapter and mounts live in. A hosted session's host (Triage) takes harnessEnv names and mount
|
||||
// sources only from these; launches don't read them. The host refuses every MOSAIC_* name from a
|
||||
// route, so MOSAIC_TOOLS, MOSAIC_EXTENSIONS and MOSAIC_THINKING are listed only to say what env()
|
||||
// hands a session: a hosted pi needs the host to set them itself (a later slice).
|
||||
export const envNames = Object.freeze(["PI_OFFLINE", "MOSAIC_TOOLS", "MOSAIC_EXTENSIONS", "PI_PROVIDER", "PI_MODEL", "MOSAIC_THINKING"]);
|
||||
export const installRoots = () => [join(REPO, "adapters", "pi"), join(REPO, "packages", "plugins", "harness", "pi"), realpathSync(join(REPO, "node_modules")), join(REPO, "tools", "unslop-hook")];
|
||||
|
||||
// The extension writes the turn marker at agent_end; an exit without it is a failed turn.
|
||||
export const turnEnd = () => "marker";
|
||||
export const transcript = ({ runDir, store = null }) => (store ? store.session : join(runDir, "session"));
|
||||
|
||||
@@ -20,7 +20,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { types } from "node:util";
|
||||
import { ENTRY_KEYS, checkDefinition, readTemplate } from "../../organization/src/definitions.mjs";
|
||||
import { parseJsonFileText } from "../../organization/src/util.mjs";
|
||||
import { ID_PATTERN, NETWORKS } from "../../organization/src/vocabulary.mjs";
|
||||
import { ID_PATTERN, NETWORKS, SYSTEM_ONLY_REFUSAL, systemOnly } from "../../organization/src/vocabulary.mjs";
|
||||
import { NAME, PluginError } from "./kinds.mjs";
|
||||
import { hasModule, loadInstalled } from "./loader.mjs";
|
||||
|
||||
@@ -163,6 +163,9 @@ function checkDefinitions(definitions, { origin, rolesDir, id }) {
|
||||
const at = `starter pack definitions.${name}`;
|
||||
const entry = definitions[name];
|
||||
if (!plain(entry)) fail("starter-pack-invalid", `${at} must be a JSON object`, id);
|
||||
// #1873 triage-fence: a pack never carries a system-only template, as a reference or as a from.
|
||||
const named = entry.template ?? (plain(entry.from) ? entry.from.template : undefined);
|
||||
if (systemOnly(named)) fail(SYSTEM_ONLY_REFUSAL, `${at} names template ${named}, which no organization may hold`, id);
|
||||
const keys = Object.keys(entry);
|
||||
if (keys.length === REF_KEYS.length && REF_KEYS.every((k) => keys.includes(k))) {
|
||||
// A template reference: the whole template, pinned by its hash.
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
// the launch (sandbox-unavailable).
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { existsSync, lstatSync, mkdirSync, readlinkSync, realpathSync } from "node:fs";
|
||||
import { existsSync, lstatSync, mkdirSync, readlinkSync, realpathSync, statSync } from "node:fs";
|
||||
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ID_PATTERN } from "../../organization/src/vocabulary.mjs";
|
||||
@@ -193,6 +193,155 @@ export function sandboxArgv(list, runDir, command, { business, role, bwrap = BWR
|
||||
return [bwrap, ...NAMESPACES, ...argsOf(list), "--remount-ro", "/", "--setenv", "HOME", join(runDir, "home"), "--setenv", "TMPDIR", "/tmp", ...identity, "--chdir", runDir, "--", ...KILL_WITH_PARENT, ...command];
|
||||
}
|
||||
|
||||
// #1873 triage-fences: what a model route may hand a hosted session, checked before the host
|
||||
// writes anything and again in hostedBinds. The adapter and each mount's source must be a clean
|
||||
// absolute path whose real path lies under one of the harness module's install roots, named under
|
||||
// that same root, and outside every protected path: the data root, the config directory and HOME
|
||||
// the caller passes, the run directory, ALWAYS_PROTECTED, and any path with a segment that
|
||||
// contains "secret" in any case. A protected path counts in its own spelling and its real path, and
|
||||
// a source may neither lie inside one nor contain one. The bind's source is the real path, so a
|
||||
// link swapped after the check cannot steer it. A mount's dest (its source when it names none) is
|
||||
// never /tmp, the run directory or a system bind's dest, nor inside or around one, never a parent
|
||||
// of or equal to a runner file, the adapter or node, and never in or around another mount's dest.
|
||||
// At most HOSTED_MOUNTS_MAX mounts. A refusal is a HostedRouteError naming its fence, never a path.
|
||||
// `codeRoot` is the stack's own code and `codeHolder` the one protected path that may hold it:
|
||||
// HOME, when the stack runs from a copy or a worktree under it. That path does not refuse a source
|
||||
// whose named and real paths both lie in the code root. Every other check still applies to it, and
|
||||
// no other protected path, the run directory or ALWAYS_PROTECTED is ever set aside. A code root in
|
||||
// or around the run directory or ALWAYS_PROTECTED, in either path's spelling or real path, is refused.
|
||||
export const HOSTED_MOUNTS_MAX = 8;
|
||||
const ROOTS_MAX = 16;
|
||||
const PATH_MAX = 4096;
|
||||
const ALWAYS_PROTECTED = Object.freeze(["/srv/mosaic", "/proc", "/sys", "/dev", "/run", "/root", "/boot"]);
|
||||
const MOUNT_KEYS = Object.freeze(["src", "dest", "why"]);
|
||||
|
||||
export class HostedRouteError extends Error {
|
||||
constructor(fence, message) {
|
||||
super(`hosted binds: ${message}`);
|
||||
this.code = "hosted-binds-refused";
|
||||
this.fence = fence;
|
||||
}
|
||||
}
|
||||
const refuseRoute = (fence, message) => { throw new HostedRouteError(fence, message); };
|
||||
|
||||
// Absolute, already normal (no "..", ".", "//" or trailing slash), not "/", no NUL.
|
||||
const cleanPath = (p) => typeof p === "string" && p.length > 1 && p.length <= PATH_MAX && !p.includes("\0") && isAbsolute(p) && resolve(p) === p;
|
||||
const within = (child, parent) => child === parent || child.startsWith(parent + "/");
|
||||
const overlaps = (a, b) => within(a, b) || within(b, a);
|
||||
const secretPath = (p) => p.split("/").some((seg) => /secret/i.test(seg));
|
||||
const realOr = (p) => { try { return realpathSync(p); } catch { return p; } };
|
||||
const plainObject = (o) => o !== null && typeof o === "object" && !Array.isArray(o) && [Object.prototype, null].includes(Object.getPrototypeOf(o));
|
||||
|
||||
export function checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot = null, codeHolder = null, runDir, node = process.execPath }) {
|
||||
if (!cleanPath(runDir)) refuseRoute("protected", "the run directory is not a clean absolute path");
|
||||
if (!Array.isArray(protectedPaths)) refuseRoute("protected", "no protected paths were given");
|
||||
// Lists are copied once, so a Proxy cannot answer one length to a check and another to the map.
|
||||
protectedPaths = Array.from(protectedPaths);
|
||||
let code = null;
|
||||
if (codeRoot !== null) {
|
||||
if (!cleanPath(codeRoot)) refuseRoute("protected", "the code root is not a clean absolute path");
|
||||
if (!protectedPaths.includes(codeHolder)) refuseRoute("protected", "the code root's holder is not a protected path");
|
||||
code = [codeRoot, realOr(codeRoot)];
|
||||
const fixed = [runDir, ...ALWAYS_PROTECTED].flatMap((g) => [g, realOr(g)]);
|
||||
if (code.some((c) => fixed.some((g) => overlaps(c, g)))) refuseRoute("protected", "the code root is in or around a path that is never set aside");
|
||||
}
|
||||
// Each guarded entry: its spellings, and whether a source in the code root is clear of it.
|
||||
const guarded = [];
|
||||
for (const [p, mayHoldCode] of [...ALWAYS_PROTECTED.map((g) => [g, false]), ...protectedPaths.map((g) => [g, g === codeHolder]), [runDir, false]]) {
|
||||
if (!cleanPath(p)) refuseRoute("protected", "a protected path is not a clean absolute path");
|
||||
const spellings = [p, realOr(p)];
|
||||
const holdsCode = mayHoldCode && code !== null && spellings.some((g) => code.some((c) => c !== g && within(c, g)));
|
||||
guarded.push({ spellings, holdsCode });
|
||||
}
|
||||
if (!Array.isArray(installRoots)) refuseRoute("roots", "the harness module declares no usable install roots");
|
||||
installRoots = Array.from(installRoots);
|
||||
if (installRoots.length === 0 || installRoots.length > ROOTS_MAX) refuseRoute("roots", "the harness module declares no usable install roots");
|
||||
const roots = installRoots.map((r) => {
|
||||
if (!cleanPath(r)) refuseRoute("roots", "an install root is not a clean absolute path");
|
||||
let real;
|
||||
try { real = realpathSync(r); } catch { refuseRoute("roots", "an install root is missing"); }
|
||||
if (real === "/" || !statSync(real).isDirectory()) refuseRoute("roots", "an install root is not a directory");
|
||||
return { named: r, real };
|
||||
});
|
||||
const source = (src, fence, what) => {
|
||||
if (!cleanPath(src)) refuseRoute(fence, `${what} is not a clean absolute path`);
|
||||
let real;
|
||||
try { real = realpathSync(src); } catch { refuseRoute(fence, `${what} is missing`); }
|
||||
if (!roots.some((r) => (within(src, r.named) || within(src, r.real)) && within(real, r.real))) refuseRoute(fence, `${what} is not under an install root`);
|
||||
const inCode = code !== null && code.some((c) => within(src, c)) && within(real, code[1]);
|
||||
if (guarded.some((g) => !(g.holdsCode && inCode) && [src, real].some((p) => g.spellings.some((s) => overlaps(p, s))))) refuseRoute(fence, `${what} is in or around a protected path`);
|
||||
if ([src, real].some(secretPath)) refuseRoute(fence, `${what} is in a secrets path`);
|
||||
return real;
|
||||
};
|
||||
const adapterReal = source(adapter, "adapter", "the adapter");
|
||||
if (!statSync(adapterReal).isFile()) refuseRoute("adapter", "the adapter is not a file");
|
||||
if (!Array.isArray(harnessMounts)) refuseRoute("mounts", `a hosted session takes at most ${HOSTED_MOUNTS_MAX} harness mounts`);
|
||||
harnessMounts = Array.from(harnessMounts);
|
||||
if (harnessMounts.length > HOSTED_MOUNTS_MAX) refuseRoute("mounts", `a hosted session takes at most ${HOSTED_MOUNTS_MAX} harness mounts`);
|
||||
const apart = ["/tmp", runDir, ...systemBinds(node).map((b) => b.dest ?? b.src)];
|
||||
const kept = [...RUNNER_FILES, adapter, node];
|
||||
const dests = [];
|
||||
const mounts = harnessMounts.map((m, i) => {
|
||||
const what = `harness mount ${i + 1}`;
|
||||
if (!plainObject(m) || Object.keys(m).some((k) => !MOUNT_KEYS.includes(k))) refuseRoute("mounts", `${what} is not { src, dest, why }`);
|
||||
// Each field is read once, so a getter cannot answer one value to a check and another to the bind.
|
||||
const { src, dest: named, why } = m;
|
||||
if (typeof why !== "string" || !why || why.length > 256) refuseRoute("mounts", `${what} is not { src, dest, why }`);
|
||||
if (named !== undefined && !cleanPath(named)) refuseRoute("mount-dest", `${what}'s dest is not a clean absolute path`);
|
||||
const real = source(src, "mount-src", what);
|
||||
const dest = named ?? src;
|
||||
if (apart.some((p) => overlaps(dest, p)) || kept.some((p) => within(p, dest)) || dests.some((d) => overlaps(dest, d))) refuseRoute("mount-dest", `${what}'s dest would cover a path the session needs`);
|
||||
dests.push(dest);
|
||||
return { src: real, dest, why };
|
||||
});
|
||||
return { adapter: { src: adapterReal, dest: adapter }, mounts };
|
||||
}
|
||||
|
||||
// #1873 triage-host: the binds for a session the Console hosts in no organization (Triage). It
|
||||
// gets the system part, the runner's files, the adapter and the harness module's mounts like any
|
||||
// session, and from the data root exactly two directories: its own `runDir` read-write, and
|
||||
// `healthDir` read-only over runDir/work/health, inside the workspace the read tools' gate allows. The run's bundle/, session.json and the relay socket the runner
|
||||
// calls through stay read-only inside it, and its tmp/ is /tmp. There is no workspace, broker,
|
||||
// launch or git socket, thread store or org root. Each source inside runDir must be what the host
|
||||
// just made there, never a link the session left: bwrap resolves a bind's source on the host.
|
||||
// The adapter and the mounts pass checkHostedRoute against `installRoots`, `protectedPaths` and
|
||||
// `codeRoot` with its `codeHolder` here too; without install roots nothing binds.
|
||||
export function hostedBinds({ runDir, healthDir, adapter, harnessMounts = [], installRoots, protectedPaths, codeRoot = null, codeHolder = null, relaySocket, node = process.execPath, readOnly = [] }) {
|
||||
if (relaySocket !== join(runDir, "relay.sock")) throw new Error("hosted binds: the relay socket must be the run directory's relay.sock");
|
||||
const healthDest = join(runDir, "work", "health");
|
||||
for (const p of [runDir, healthDir, join(runDir, "bundle"), join(runDir, "tmp"), join(runDir, "work"), healthDest]) {
|
||||
let st;
|
||||
try { st = lstatSync(p); } catch { throw new Error(`hosted binds: ${p === healthDir ? "the health directory" : relative(runDir, p) || "the run directory"} is missing`); }
|
||||
if (st.isSymbolicLink() || !st.isDirectory()) throw new Error(`hosted binds: ${p === healthDir ? "the health directory" : relative(runDir, p) || "the run directory"} is not a directory`);
|
||||
}
|
||||
for (const [p, ok] of [[join(runDir, "session.json"), (st) => st.isFile()], [relaySocket, (st) => st.isSocket()]]) {
|
||||
let st;
|
||||
try { st = lstatSync(p); } catch { throw new Error(`hosted binds: ${relative(runDir, p)} is missing`); }
|
||||
if (!ok(st)) throw new Error(`hosted binds: ${relative(runDir, p)} is not what the host made`);
|
||||
}
|
||||
const route = checkHostedRoute({ adapter, harnessMounts, installRoots, protectedPaths, codeRoot, codeHolder, runDir, node });
|
||||
const out = systemBinds(node);
|
||||
for (const f of RUNNER_FILES) out.push({ kind: "ro", src: f, why: "a repository file the runner loads" });
|
||||
out.push({ kind: "ro", src: route.adapter.src, ...(route.adapter.src !== adapter ? { dest: adapter } : {}), why: "the harness adapter the runner starts each turn" });
|
||||
for (const m of route.mounts) out.push({ kind: "ro", src: m.src, ...(m.dest !== m.src ? { dest: m.dest } : {}), why: m.why });
|
||||
for (const f of readOnly) out.push({ kind: "ro", src: f, why: "a test fixture" });
|
||||
out.push(
|
||||
{ kind: "rw", src: runDir, why: "the session's own state: turns/, session/, work/, tools.sock, turn.done, home/, tmp/" },
|
||||
{ kind: "ro", src: healthDir, dest: healthDest, why: "the health snapshots the Console writes, read-only, inside the workspace the read tools reach" },
|
||||
{ kind: "ro", src: join(runDir, "bundle"), why: "the run's bundle stays as the host wrote it" },
|
||||
{ kind: "ro", src: join(runDir, "session.json"), why: "the session file stays as the host wrote it" },
|
||||
{ kind: "ro", src: relaySocket, why: "the host's relay, the only broker the runner reaches" },
|
||||
{ kind: "rw", src: join(runDir, "tmp"), dest: "/tmp", why: "a private /tmp, on disk in the run directory" },
|
||||
);
|
||||
return out;
|
||||
}
|
||||
|
||||
// The command line for a hosted session: as sandboxArgv, with no git identity, since a hosted
|
||||
// session belongs to no organization and holds no git verb.
|
||||
export function hostedArgv(list, runDir, command, { bwrap = BWRAP } = {}) {
|
||||
return [bwrap, ...NAMESPACES, ...argsOf(list), "--remount-ro", "/", "--setenv", "HOME", join(runDir, "home"), "--setenv", "TMPDIR", "/tmp", "--chdir", runDir, "--", ...KILL_WITH_PARENT, ...command];
|
||||
}
|
||||
|
||||
// Whether bwrap runs here at all: the namespaces and the system binds, then
|
||||
// setpriv and `true`. Returns null, or why not.
|
||||
export function sandboxProblem({ bwrap = BWRAP } = {}) {
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
// #1873 triage-host: the binds of a session the Console hosts in no organization. From the data root
|
||||
// it gets its own run directory and the health directory, read-only, and nothing else; every source
|
||||
// inside the run directory must be what the host made, never a link.
|
||||
import { test } from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { createServer } from "node:net";
|
||||
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
|
||||
import { dirname, join } from "node:path";
|
||||
import { HOSTED_MOUNTS_MAX, RUNNER_FILES, checkHostedRoute, hostedArgv, hostedBinds } from "../src/sandbox.mjs";
|
||||
|
||||
function layout(t) {
|
||||
const root = mkdtempSync(join(process.env.TMPDIR, "hb-"));
|
||||
const dataRoot = join(root, "data");
|
||||
const runDir = join(dataRoot, "triage", "agent");
|
||||
const healthDir = join(dataRoot, "triage", "health");
|
||||
for (const d of [join(dataRoot, "orgs"), join(dataRoot, "triage", "host"), healthDir, join(runDir, "bundle"), join(runDir, "tmp"), join(runDir, "work", "health")]) mkdirSync(d, { recursive: true });
|
||||
writeFileSync(join(runDir, "session.json"), "{}");
|
||||
const install = join(root, "install");
|
||||
mkdirSync(install);
|
||||
const adapter = join(install, "adapter.sh");
|
||||
writeFileSync(adapter, "exit 0\n");
|
||||
return new Promise((resolve) => {
|
||||
const server = createServer().listen(join(runDir, "relay.sock"), () => {
|
||||
t.after(() => server.close());
|
||||
resolve({ root, dataRoot, runDir, healthDir, adapter, install, relaySocket: join(runDir, "relay.sock"), installRoots: [install], protectedPaths: [dataRoot] });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test("hosted binds hold the run directory and the health directory of the data root, and nothing else of it", async (t) => {
|
||||
const p = await layout(t);
|
||||
const list = hostedBinds({ runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths });
|
||||
const fromData = list.filter((b) => typeof b.src === "string" && b.src.startsWith(p.dataRoot + "/"));
|
||||
assert.deepEqual(fromData.map((b) => [b.kind, b.src, b.dest ?? null]), [
|
||||
["rw", p.runDir, null],
|
||||
["ro", p.healthDir, join(p.runDir, "work", "health")],
|
||||
["ro", join(p.runDir, "bundle"), null],
|
||||
["ro", join(p.runDir, "session.json"), null],
|
||||
["ro", p.relaySocket, null],
|
||||
["rw", join(p.runDir, "tmp"), "/tmp"],
|
||||
]);
|
||||
for (const f of RUNNER_FILES) assert.ok(list.some((b) => b.kind === "ro" && b.src === f), f);
|
||||
assert.ok(list.some((b) => b.kind === "ro" && b.src === p.adapter));
|
||||
assert.ok(!list.some((b) => b.src === p.root || b.src === p.dataRoot || (typeof b.src === "string" && b.src.startsWith(join(p.dataRoot, "orgs")))));
|
||||
assert.ok(!list.some((b) => b.src === process.env.HOME || b.dest === process.env.HOME));
|
||||
assert.ok(list.every((b) => typeof b.why === "string" && b.why.length > 0));
|
||||
});
|
||||
|
||||
test("hosted binds refuse a relay socket elsewhere, and any source in the run directory that the host did not make", async (t) => {
|
||||
const p = await layout(t);
|
||||
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
|
||||
assert.throws(() => hostedBinds({ ...base, relaySocket: join(p.root, "bus.sock") }), /relay socket must be the run directory's relay\.sock/);
|
||||
// A link in place of each directory the binds read: bwrap would follow it on the host.
|
||||
for (const d of ["bundle", "tmp", "work"]) {
|
||||
rmSync(join(p.runDir, d), { recursive: true });
|
||||
symlinkSync(join(p.dataRoot, "orgs"), join(p.runDir, d));
|
||||
assert.throws(() => hostedBinds(base), /is not a directory/, d);
|
||||
rmSync(join(p.runDir, d));
|
||||
mkdirSync(join(p.runDir, d === "work" ? join("work", "health") : d), { recursive: true });
|
||||
}
|
||||
rmSync(join(p.runDir, "work", "health"), { recursive: true });
|
||||
symlinkSync(join(p.dataRoot, "triage", "host"), join(p.runDir, "work", "health"));
|
||||
assert.throws(() => hostedBinds(base), /is not a directory/);
|
||||
rmSync(join(p.runDir, "work", "health"));
|
||||
mkdirSync(join(p.runDir, "work", "health"));
|
||||
rmSync(join(p.runDir, "session.json"));
|
||||
symlinkSync(join(p.dataRoot, "orgs"), join(p.runDir, "session.json"));
|
||||
assert.throws(() => hostedBinds(base), /session\.json is not what the host made/);
|
||||
rmSync(join(p.runDir, "session.json"));
|
||||
writeFileSync(join(p.runDir, "session.json"), "{}");
|
||||
assert.throws(() => hostedBinds({ ...base, healthDir: join(p.root, "absent") }), /the health directory is missing/);
|
||||
hostedBinds(base);
|
||||
});
|
||||
|
||||
test("the hosted command line sets no git identity and runs the command under the namespaces", async (t) => {
|
||||
const p = await layout(t);
|
||||
const argv = hostedArgv(hostedBinds({ runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths }), p.runDir, ["node", "runner.mjs", p.runDir], { bwrap: "/b/bwrap" });
|
||||
assert.equal(argv[0], "/b/bwrap");
|
||||
assert.deepEqual(argv.slice(1, 5), ["--unshare-user", "--unshare-pid", "--unshare-ipc", "--as-pid-1"]);
|
||||
assert.deepEqual(argv.slice(-3), ["node", "runner.mjs", p.runDir]);
|
||||
assert.ok(!argv.some((a) => a.startsWith("GIT_")));
|
||||
const home = argv.indexOf("HOME");
|
||||
assert.equal(argv[home + 1], join(p.runDir, "home"));
|
||||
assert.ok(argv.includes("--remount-ro"));
|
||||
});
|
||||
|
||||
// #1873 triage-fences: hostedBinds checks the adapter and the mounts again, so a caller that skips
|
||||
// the host's own check still binds nothing outside the install roots.
|
||||
test("hosted binds refuse without install roots or protected paths, and refuse an adapter or a mount source outside the roots or in a protected path", async (t) => {
|
||||
const p = await layout(t);
|
||||
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
|
||||
const refused = (opts, fence, label) => assert.throws(() => hostedBinds({ ...base, ...opts }), (e) => e.code === "hosted-binds-refused" && e.fence === fence, label);
|
||||
refused({ installRoots: undefined }, "roots", "no roots");
|
||||
refused({ installRoots: [] }, "roots", "empty roots");
|
||||
refused({ installRoots: ["/"] }, "roots", "root /");
|
||||
refused({ installRoots: [join(p.root, "absent")] }, "roots", "missing root");
|
||||
refused({ installRoots: [p.adapter] }, "roots", "a file as root");
|
||||
refused({ protectedPaths: undefined }, "protected", "no protected paths");
|
||||
refused({ protectedPaths: ["relative"] }, "protected", "relative protected path");
|
||||
writeFileSync(join(p.root, "out.sh"), "x");
|
||||
refused({ adapter: join(p.root, "out.sh") }, "adapter", "adapter outside");
|
||||
symlinkSync(join(p.root, "out.sh"), join(p.install, "link.sh"));
|
||||
refused({ adapter: join(p.install, "link.sh") }, "adapter", "adapter link out");
|
||||
refused({ adapter: p.install }, "adapter", "adapter is a directory");
|
||||
refused({ harnessMounts: [{ src: join(p.install, "link.sh"), why: "w" }] }, "mount-src", "mount link out");
|
||||
refused({ harnessMounts: [{ src: join(p.dataRoot, "orgs"), why: "w" }], installRoots: [p.root] }, "mount-src", "mount in the data root");
|
||||
refused({ harnessMounts: [{ src: p.root, why: "w" }], installRoots: [p.root] }, "mount-src", "mount around the data root");
|
||||
mkdirSync(join(p.install, "secrets"));
|
||||
writeFileSync(join(p.install, "secrets", "k"), "x");
|
||||
refused({ harnessMounts: [{ src: join(p.install, "secrets", "k"), why: "w" }] }, "mount-src", "mount in secrets");
|
||||
writeFileSync(join(p.install, "m"), "x");
|
||||
refused({ harnessMounts: Array.from({ length: HOSTED_MOUNTS_MAX + 1 }, (_, i) => ({ src: join(p.install, "m"), dest: `/opt/m${i}`, why: "w" })) }, "mounts", "too many");
|
||||
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: "/tmp/m", why: "w" }] }, "mount-dest", "dest under /tmp");
|
||||
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: p.runDir, why: "w" }] }, "mount-dest", "dest is the run dir");
|
||||
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: join(p.runDir, "session.json"), why: "w" }] }, "mount-dest", "dest is session.json");
|
||||
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: "/usr", why: "w" }] }, "mount-dest", "dest is a system bind");
|
||||
refused({ harnessMounts: [{ src: join(p.install, "m"), dest: dirname(RUNNER_FILES[0]), why: "w" }] }, "mount-dest", "dest holds a runner file");
|
||||
refused({ harnessMounts: [{ src: join(p.install, "m"), why: "w", kind: "rw" }] }, "mounts", "a kind of its own");
|
||||
});
|
||||
|
||||
test("hosted binds bind the real file of a link that stays inside the install root, at the path the route named", async (t) => {
|
||||
const p = await layout(t);
|
||||
writeFileSync(join(p.install, "real.mjs"), "x");
|
||||
symlinkSync(join(p.install, "real.mjs"), join(p.install, "named.mjs"));
|
||||
symlinkSync(p.adapter, join(p.install, "adapter-link.sh"));
|
||||
const list = hostedBinds({
|
||||
runDir: p.runDir, healthDir: p.healthDir, adapter: join(p.install, "adapter-link.sh"), relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths,
|
||||
harnessMounts: [{ src: join(p.install, "named.mjs"), why: "w" }, { src: join(p.install, "real.mjs"), dest: "/opt/real.mjs", why: "w2" }],
|
||||
});
|
||||
assert.ok(list.some((b) => b.kind === "ro" && b.src === p.adapter && b.dest === join(p.install, "adapter-link.sh")));
|
||||
assert.ok(list.some((b) => b.kind === "ro" && b.src === join(p.install, "real.mjs") && b.dest === join(p.install, "named.mjs") && b.why === "w"));
|
||||
assert.ok(list.some((b) => b.kind === "ro" && b.src === join(p.install, "real.mjs") && b.dest === "/opt/real.mjs" && b.why === "w2"));
|
||||
assert.ok(!list.some((b) => b.src === join(p.install, "named.mjs")));
|
||||
});
|
||||
|
||||
test("a protected path that holds the code root (HOME over a copy or a worktree) does not refuse a source inside the code root; everything else still holds", async (t) => {
|
||||
const p = await layout(t);
|
||||
// home/ holds the code root code/, which holds the install root.
|
||||
const home = join(p.root, "home");
|
||||
const code = join(home, "code");
|
||||
const inst = join(code, "inst");
|
||||
mkdirSync(join(inst, "secrets"), { recursive: true });
|
||||
for (const f of ["adapter.sh", "m", join("secrets", "k")]) writeFileSync(join(inst, f), "x");
|
||||
writeFileSync(join(home, "outside"), "x");
|
||||
mkdirSync(join(code, "data"));
|
||||
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: join(inst, "adapter.sh"), relaySocket: p.relaySocket, installRoots: [inst], protectedPaths: [p.dataRoot, home], codeRoot: code, codeHolder: home };
|
||||
const refused = (opts, fence, label) => assert.throws(() => hostedBinds({ ...base, ...opts }), (e) => e.code === "hosted-binds-refused" && e.fence === fence, label);
|
||||
const list = hostedBinds({ ...base, harnessMounts: [{ src: join(inst, "m"), dest: "/opt/m", why: "w" }] });
|
||||
assert.ok(list.some((b) => b.src === join(inst, "adapter.sh")) && list.some((b) => b.src === join(inst, "m") && b.dest === "/opt/m"));
|
||||
// Without the code root, HOME refuses the same adapter.
|
||||
refused({ codeRoot: null }, "adapter", "no code root");
|
||||
// A code root that is HOME itself sets nothing aside.
|
||||
refused({ codeRoot: home }, "adapter", "code root is HOME");
|
||||
// A source under HOME outside the code root, even inside an install root.
|
||||
refused({ installRoots: [home], adapter: join(home, "outside") }, "adapter", "outside the code root");
|
||||
// A link inside the code root to a file outside it.
|
||||
symlinkSync(join(home, "outside"), join(inst, "out"));
|
||||
refused({ installRoots: [inst, home], harnessMounts: [{ src: join(inst, "out"), why: "w" }] }, "mount-src", "link out of the code root");
|
||||
// A protected path inside the code root still refuses.
|
||||
writeFileSync(join(code, "data", "f"), "x");
|
||||
refused({ installRoots: [code], protectedPaths: [p.dataRoot, home, join(code, "data")], harnessMounts: [{ src: join(code, "data", "f"), why: "w" }] }, "mount-src", "protected path in the code root");
|
||||
// The secrets check still holds inside the code root.
|
||||
refused({ harnessMounts: [{ src: join(inst, "secrets", "k"), why: "w" }] }, "mount-src", "secrets in the code root");
|
||||
// The run directory and the fixed list are never set aside, and a code root around them is refused.
|
||||
refused({ codeRoot: p.root, installRoots: [p.root], harnessMounts: [{ src: join(p.dataRoot, "orgs"), why: "w" }] }, "protected", "code root holds the run dir");
|
||||
refused({ codeRoot: "/srv/mosaic/x" }, "protected", "code root in a fixed path");
|
||||
refused({ codeRoot: "relative" }, "protected", "relative code root");
|
||||
// Only the named holder sets the code aside: another protected path that holds the code still refuses.
|
||||
refused({ protectedPaths: [p.dataRoot, home, p.root] }, "adapter", "a second protected path holds the code");
|
||||
refused({ codeHolder: null }, "protected", "no holder");
|
||||
refused({ codeHolder: join(p.root, "elsewhere") }, "protected", "a holder that is not a protected path");
|
||||
// A run directory named through a link: a code root in its real path is refused before any check.
|
||||
const realRun = join(home, "run");
|
||||
mkdirSync(join(realRun, "code", "inst"), { recursive: true });
|
||||
writeFileSync(join(realRun, "code", "inst", "a.sh"), "x");
|
||||
symlinkSync(realRun, join(p.root, "runlink"));
|
||||
assert.throws(() => checkHostedRoute({ adapter: join(realRun, "code", "inst", "a.sh"), harnessMounts: [], installRoots: [join(realRun, "code", "inst")], protectedPaths: [p.dataRoot, home], codeRoot: join(realRun, "code"), codeHolder: home, runDir: join(p.root, "runlink") }), (e) => e.fence === "protected", "code root in the run dir's real path");
|
||||
});
|
||||
|
||||
test("a list that answers one length to the check and another later is read once", async (t) => {
|
||||
const p = await layout(t);
|
||||
const items = [];
|
||||
for (let i = 0; i <= HOSTED_MOUNTS_MAX; i++) { writeFileSync(join(p.install, `m${i}`), "x"); items.push({ src: join(p.install, `m${i}`), dest: `/opt/m${i}`, why: "w" }); }
|
||||
let reads = 0;
|
||||
const mounts = new Proxy(items, { get: (o, k) => (k === "length" ? (reads++ === 0 ? 1 : o.length) : o[k]) });
|
||||
assert.throws(() => checkHostedRoute({ adapter: p.adapter, harnessMounts: mounts, installRoots: p.installRoots, protectedPaths: p.protectedPaths, runDir: p.runDir }), (e) => e.fence === "mounts");
|
||||
// Install roots: two short answers pass the count, then a long one would add roots the count never saw.
|
||||
const roots = [];
|
||||
for (let i = 0; i <= 16; i++) { roots.push(join(p.root, `r${i}`)); mkdirSync(roots[i]); }
|
||||
writeFileSync(join(roots[16], "a.sh"), "x");
|
||||
let rootReads = 0;
|
||||
const rootList = new Proxy(roots, { get: (o, k) => (k === "length" ? (rootReads++ < 2 ? 1 : o.length) : o[k]) });
|
||||
assert.throws(() => checkHostedRoute({ adapter: join(roots[16], "a.sh"), harnessMounts: [], installRoots: rootList, protectedPaths: p.protectedPaths, runDir: p.runDir }), (e) => e.fence === "adapter");
|
||||
// Protected paths: the holder check sees HOME, then a shorter answer would leave HOME unguarded.
|
||||
const home = join(p.root, "home");
|
||||
mkdirSync(join(home, "code"), { recursive: true });
|
||||
writeFileSync(join(home, "f"), "x");
|
||||
let guardReads = 0;
|
||||
const guards = new Proxy([p.dataRoot, home], { get: (o, k) => (k === "length" ? (guardReads++ === 0 ? 2 : 1) : o[k]) });
|
||||
assert.throws(() => checkHostedRoute({ adapter: p.adapter, harnessMounts: [{ src: join(home, "f"), dest: "/opt/f", why: "w" }], installRoots: [p.install, home], protectedPaths: guards, codeRoot: join(home, "code"), codeHolder: home, runDir: p.runDir }), (e) => e.fence === "protected" || e.fence === "mount-src");
|
||||
});
|
||||
|
||||
test("each mount field is read once, and no mount's dest lies in or around another's", async (t) => {
|
||||
const p = await layout(t);
|
||||
const base = { runDir: p.runDir, healthDir: p.healthDir, adapter: p.adapter, relaySocket: p.relaySocket, installRoots: p.installRoots, protectedPaths: p.protectedPaths };
|
||||
writeFileSync(join(p.install, "m"), "x");
|
||||
writeFileSync(join(p.install, "n"), "x");
|
||||
let reads = 0;
|
||||
const list = hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), why: "w", get dest() { return reads++ === 0 ? undefined : "/opt/../tmp"; } }] });
|
||||
assert.equal(reads, 1);
|
||||
assert.ok(list.some((b) => b.src === join(p.install, "m") && b.dest === undefined));
|
||||
assert.ok(!list.some((b) => b.dest === "/opt/../tmp"));
|
||||
for (const [a, b] of [["/opt/x", "/opt/x/f"], ["/opt/x/f", "/opt/x"], ["/opt/x", "/opt/x"]]) {
|
||||
assert.throws(() => hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), dest: a, why: "w" }, { src: join(p.install, "n"), dest: b, why: "w" }] }), (e) => e.fence === "mount-dest", `${a} then ${b}`);
|
||||
}
|
||||
assert.equal(hostedBinds({ ...base, harnessMounts: [{ src: join(p.install, "m"), dest: "/opt/x", why: "w" }, { src: join(p.install, "n"), dest: "/opt/xy", why: "w" }] }).filter((b) => b.dest?.startsWith("/opt/")).length, 2);
|
||||
});
|
||||
@@ -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
|
||||
|
||||
@@ -165,6 +165,8 @@ const STATUS = {
|
||||
// Row 155 (#1649): the assistant's settings, seat names and stop. A name in use or no run to stop
|
||||
// is the user's to resolve by reading again.
|
||||
'organization-not-assistant': 400, 'organization-definition-refused': 400, 'unknown-model': 400,
|
||||
// #1873 triage-fence: a template no organization may hold.
|
||||
'template-system-only': 400,
|
||||
'name-taken': 409, 'name-is-instance': 400, 'name-is-role': 400, 'not-assistant': 400, 'not-held': 409,
|
||||
// Row 165 (#1662): role instances. An id already taken is the user's to resolve by reading again.
|
||||
'organization-instance-exists': 409, 'organization-unknown-instance': 400,
|
||||
|
||||
@@ -34,10 +34,12 @@ import { isAbsolute, join } from 'node:path';
|
||||
import { actionTrail } from './action-trail.mjs';
|
||||
import { reviveBuses } from './bus-revive.mjs';
|
||||
import { createProxyAdmin, orgCatalogue } from './proxy-admin.mjs';
|
||||
import { createTriageHost } from './triage-host.mjs';
|
||||
import { composeSnapshot, readSystemConfig, readOrgConfig } from './triage-snapshot.mjs';
|
||||
import { busesStopped } from '../../cli/src/proxy-admin-host.mjs';
|
||||
import { agentLevelsWriteRoutes } from './agent-levels-write.mjs';
|
||||
import { RESTART_EXIT } from '../../cli/src/org-console.mjs';
|
||||
import { ID_PATTERN } from '../../organization/src/vocabulary.mjs';
|
||||
import { ID_PATTERN, systemOnly } from '../../organization/src/vocabulary.mjs';
|
||||
import { selectorScope } from '../../organization/src/selector.mjs';
|
||||
// The bus verifies the Console's exact same-tree script in /proc, whose argv preserves a
|
||||
// relative shell argument even though Node's process.argv resolves it. Re-exec the same
|
||||
@@ -202,8 +204,9 @@ try {
|
||||
// and the preview are reads over requestRead.
|
||||
templatesWrite: session.user === undefined && sendOn ? templatesCaller(consoleCall({ dataRoot: root, socket: paths.socket, business: id })) : null,
|
||||
// Starter packs SP6 (#1873): the owner's workflow read, the organization file and its revision as the
|
||||
// writer reads them (the read `mosaic org workflow set` takes its revision from), and the V2 template names.
|
||||
workflowsRead: session.user === undefined ? () => ({ ...organizationWriter({ dir: configDir(), rolesDir: rolesDir() }).read(id), templates: templateHashes(rolesDir()).map(t => t.template) }) : null,
|
||||
// writer reads them (the read `mosaic org workflow set` takes its revision from), and the V2 template names
|
||||
// less the system-only ones. packs-http's workflowsRead drops them again and is the tested gate.
|
||||
workflowsRead: session.user === undefined ? () => ({ ...organizationWriter({ dir: configDir(), rolesDir: rolesDir() }).read(id), templates: templateHashes(rolesDir()).map(t => t.template).filter(t => !systemOnly(t)) }) : null,
|
||||
reads: consoleReads({ root: REPO, queueRoot: options.checkout ?? REPO, system, configDir: configDir(), rolesDir: rolesDir(), business: id, orgRoot: root }),
|
||||
};
|
||||
},
|
||||
@@ -227,20 +230,40 @@ try {
|
||||
return out;
|
||||
},
|
||||
}) : null;
|
||||
// #1873 triage-host: the instance owner's Triage session, hosted by the Console in no organization.
|
||||
// Nothing starts here; the owner's first message starts it. No model route store exists without a
|
||||
// schema change, so none is wired: the read says no route is set and nothing launches.
|
||||
const triage = system && (devOwner || ssoOn) ? createTriageHost({
|
||||
dataRoot: system.dataRoot, route: null, devOwner: Boolean(devOwner), log: line => console.log(line),
|
||||
readSnapshot: () => composeSnapshot({
|
||||
orgs: () => listOrgs({ configDir: configDir(), dataRoot: system.dataRoot, instance }),
|
||||
busStatus: id => orgBusStatus({ configDir: configDir(), dataRoot: system.dataRoot, instance }, id),
|
||||
processing: async id => {
|
||||
const org = (await listOrgs({ configDir: configDir(), dataRoot: system.dataRoot, instance })).find(o => o.id === id);
|
||||
if (!org) return null;
|
||||
return busCaller({ dataRoot: org.root, socket: orgPaths(org.root).socket, business: id, timeoutMs: 5000 })('processing.status');
|
||||
},
|
||||
orgConfig: id => readOrgConfig(id),
|
||||
proxy: () => proxyAdmin.status(),
|
||||
systemConfig: () => readSystemConfig(),
|
||||
}),
|
||||
}) : null;
|
||||
let server, testerServer = null;
|
||||
// F3: the restart route closes every listener and connection, then exits RESTART_EXIT for the
|
||||
// supervisor to relaunch. Without --supervised the route answers not-supervised.
|
||||
const restart = supervised ? () => {
|
||||
sso?.close(); testerServer?.close();
|
||||
// The Triage session gets SIGTERM now and SIGKILL before the 2 s exit below.
|
||||
const triageStopped = triage ? triage.stop({ graceMs: 1500 }) : Promise.resolve();
|
||||
setTimeout(() => process.exit(RESTART_EXIT), 2000).unref();
|
||||
server.close(() => process.exit(RESTART_EXIT));
|
||||
server.close(() => triageStopped.finally(() => process.exit(RESTART_EXIT)));
|
||||
server.closeAllConnections();
|
||||
} : null;
|
||||
const trail = system ? actionTrail(join(system.dataRoot, 'console')) : null;
|
||||
// #1873 A2: Settings > Agents writes for the root and project levels, beside the levels read.
|
||||
const agentLevelRoutes = organizations ? [agentLevelsWriteRoutes({ configDir: configDir(), rolesDir: rolesDir(), trail })] : [];
|
||||
try {
|
||||
server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, routes: agentLevelRoutes, preselect: options.business ?? null });
|
||||
server = await startServer({ restart, trail, ...(lan ? { host: lan.bind, devAllowHosts: lan.allowHosts } : {}), board: options.board, port: options.port, bus, reads, preview: options.preview, sso, proof, send, settingsWrite, projectFiles, projectFile, libraryFile, libraryStatus, librarySync, libraryRevert, librarySave, projectSave, chat, nameWrite, assistantStop, instancesWrite, routesWrite, agentWrite, proxyCall, proxyAdmin, triage, processing, decisionWrite, requestRead, requestWrite, userOptions, federation: system?.federation ?? null, organizations, agentLevels, routes: agentLevelRoutes, preselect: options.business ?? null });
|
||||
} catch (err) { sso?.close(); throw err; }
|
||||
if (testerSocket) {
|
||||
const call = busCaller({ dataRoot: system.dataRoot, socket: socketPath(system.dataRoot), business: options.business ?? null, cli: TESTER_CLI });
|
||||
@@ -277,7 +300,7 @@ try {
|
||||
// D2 (P0-3): the dev Console reattaches to the buses that still run and brings back the ones its
|
||||
// unit stop killed. It runs after the Console answers, so a slow bus never delays the page.
|
||||
if (organizations && trail) reviveBuses({ ctx: { configDir: configDir(), dataRoot: system.dataRoot, instance }, listOrgs, busStatus: orgBusStatus, busRevive: orgBusRevive, trail, log: line => console.log(line) }).catch(() => console.log('bus revive: stopped on an unexpected error'));
|
||||
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => { sso?.close(); server.close(); testerServer?.close(); });
|
||||
for (const signal of ['SIGINT', 'SIGTERM']) process.once(signal, () => { sso?.close(); server.close(); testerServer?.close(); triage?.stop(); });
|
||||
} catch (err) {
|
||||
console.error(`refused: ${err.message}`);
|
||||
process.exitCode = 2;
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
// rechecks everything in the resolve transaction. Nothing here retries.
|
||||
import { createHash, randomBytes } from 'node:crypto';
|
||||
import { BusReadError, subjectOk } from './bus.mjs';
|
||||
import { ID_PATTERN } from '../../organization/src/vocabulary.mjs';
|
||||
|
||||
export const DECISION_ROUTE = /^\/api\/decisions\/([^/]*)\/(confirmation|resolve|start|templates)$/;
|
||||
// The endpoint contract, design section 4. Each refusal is one of these, never a 200.
|
||||
@@ -42,21 +43,118 @@ const BUS_CODES = {
|
||||
'decision-closed': 'decision-closed', 'decision-stale': 'decision-stale', 'invalid-choice': 'decision-stale',
|
||||
'invalid-request': 'invalid-request', 'hire-owner-required':'hire-owner-required','right-required':'right-required','decision-expired':'decision-expired','hire-resolution-required':'hire-resolution-required',
|
||||
};
|
||||
// D4 (#1873, P1-2): a hire, fire or change start the bus definitely refused keeps its own code,
|
||||
// but only for codes the broker raises before it records the decision: the proposal checks in
|
||||
// hire-decisions.mjs prepare(), which #raiseHire runs before its INSERT. hire.start.console then
|
||||
// resolves the decision and applies it in #hireConsole, and those steps can raise other codes (and
|
||||
// some of the same generic ones) after the decision exists or is consumed, so every code not listed
|
||||
// here stays outcome-unknown. Review P3: an allowlist, not a pass-through of any well-formed code.
|
||||
// D4 (#1873, P1-2) and E2E6 P1-2: a hire, fire or change start the bus definitely refused keeps its
|
||||
// own code and a next step. hire.start.console runs prepare() (hire-decisions.mjs) before it records
|
||||
// the decision, then #hireConsole checks it, consumes it, and applies it. apply() runs check() again
|
||||
// and the writers, authorityHost and #fireApproved run after the consume, so most codes can come from
|
||||
// either side of it; for a fire the agent's runs may already be stopped. The code alone does not say
|
||||
// which, and the inbox cannot tell either: it lists no closed decision (broker inbox verb), so a
|
||||
// consumed one simply drops out of it. Those codes therefore say part of the change may already be
|
||||
// applied and send the user to the Agents page (re-check finding 1). Only codes
|
||||
// that prepare() alone raises say "Nothing was applied.": the route checks (checkRoutes runs in
|
||||
// prepare(), and in adjusted() only for an adjust, which a start never carries), definition-shared,
|
||||
// definition-not-hireable and no-chief-of-staff. organization-uncertain, a lost reply and the
|
||||
// bus server's own request codes (request-timeout and invalid-envelope can fire while the request is
|
||||
// processing) stay outcome-unknown.
|
||||
const NONE = ' Nothing was applied.';
|
||||
const EITHER = ' Part of it may already be applied: check the Agents page before trying again.';
|
||||
const CHECK = ' Check the Agents page and the inbox before trying again.';
|
||||
const HIRE_START_REFUSALS = {
|
||||
'model-provider-unavailable': [409, 'The model proxy does not offer this model, or its catalogue is not ready. Pick a model it offers, or ask the owner to check Settings > Model proxy. Nothing was applied.'],
|
||||
'model-catalogue-unavailable': [503, 'The model catalogue could not be read, so this model could not be checked. Check Settings > Model proxy, then try again. Nothing was applied.'],
|
||||
'model-harness-incompatible': [409, 'This model does not run on the chosen harness. Pick another model or harness. Nothing was applied.'],
|
||||
'thinking-unsupported': [409, 'The chosen harness does not apply this thinking level. Clear Thinking or pick a level it applies. Nothing was applied.'],
|
||||
'definition-not-hireable': [409, 'This organization does not hire agents from this role template. Pick another template. Nothing was applied.'],
|
||||
'definition-shared': [409, 'Another agent uses the same role definition, so this change cannot replace it. Nothing was applied.'],
|
||||
'no-chief-of-staff': [409, 'This organization has no chief of staff, so a hire, fire or change cannot be checked against it. Nothing was applied.'],
|
||||
'model-provider-unavailable': [409, 'The model proxy does not offer this model, or its catalogue is not ready. Pick a model it offers, or ask the owner to check Settings > Model proxy.' + NONE],
|
||||
'model-catalogue-unavailable': [503, 'The model catalogue could not be read, so this model could not be checked. Check Settings > Model proxy, then try again.' + NONE],
|
||||
'model-harness-incompatible': [409, 'This model does not run on the chosen harness. Pick another model or harness.' + NONE],
|
||||
'thinking-unsupported': [409, 'The chosen harness does not apply this thinking level. Clear Thinking or pick a level it applies.' + NONE],
|
||||
'unknown-model': [409, 'This model is not one of the organization\'s models. Pick a model listed under Settings > Model proxy.' + NONE],
|
||||
'harness-off': [409, 'This harness is not switched on for the organization. Pick a harness listed under Settings > Routing, or ask the owner to switch it on.' + NONE],
|
||||
'harness-refused': [409, 'The harness refused this route. Clear Thinking, or pick another model or harness under Settings > Routing.' + NONE],
|
||||
'template-system-only': [409, 'This role template is for the system, not for an organization. Pick another template.' + NONE],
|
||||
'definition-not-hireable': [409, 'This organization does not hire agents from this role template. Pick another template.' + NONE],
|
||||
'definition-shared': [409, 'Another agent uses the same role definition, so this change cannot replace it.' + NONE],
|
||||
'definition-rev-conflict': [409, 'The role definition changed since it was read. Reload the page and propose again.' + EITHER],
|
||||
'definition-missing': [409, 'The agent\'s role definition is missing from the organization file. Check the Agents page.' + EITHER],
|
||||
'definition-secret-check-required': [503, 'The bus cannot check role text for secrets right now. Ask the owner to check the organization bus.' + EITHER],
|
||||
'credential-leak': [409, 'The proposal carries a value the credential store holds. Remove it from the role text or the reason.' + EITHER],
|
||||
'no-chief-of-staff': [409, 'This organization has no chief of staff, so a hire, fire or change cannot be checked against it.' + NONE],
|
||||
'project-agents-invalid': [409, 'That project is not a code project of this organization. Pick a code project from Projects; a library project has no agents.' + EITHER],
|
||||
'organization-unknown-instance': [409, 'No agent has that name at this level. Check the name on the Agents page.' + EITHER],
|
||||
'organization-instance-exists': [409, 'An agent already has that name at this level. Pick another name, or propose a change to that agent.' + EITHER],
|
||||
'organization-instance-retired': [409, 'That name belonged to a fired agent and cannot be reused. Pick another name.' + EITHER],
|
||||
'organization-instance-referenced': [409, 'Another part of the organization still names this agent. Remove those references first.' + EITHER],
|
||||
'instance-kept': [409, 'This agent is kept by the organization and cannot be fired or replaced this way.' + EITHER],
|
||||
'root-fire-shared': [409, 'This root agent is shared with other organizations, so it cannot be fired from here.' + EITHER],
|
||||
'decision-stale': [409, 'The role template or the organization changed since it was read. Reload the templates and propose again.' + EITHER],
|
||||
'organization-refused': [409, 'The organization file refused this change. Check the role and route against the organization checks.' + EITHER],
|
||||
'not-configured': [503, 'This Console\'s bus has no hire support configured. Ask the owner to check the organization bus.' + EITHER],
|
||||
'organization-busy': [409, 'The organization is busy with another write.' + CHECK],
|
||||
'fire-in-progress': [409, 'A fire of this agent is already in progress.' + CHECK],
|
||||
'instance-fired': [409, 'This agent was fired.' + CHECK],
|
||||
'copy-unavailable': [409, 'This copy is not available for credentials.' + CHECK],
|
||||
'copy-refused': [409, 'The copy refused this credential change.' + CHECK],
|
||||
'copy-stale': [409, 'The copy changed since it was read. Reload the Agents page.' + CHECK],
|
||||
'root-policy-unreadable': [503, 'The root policy could not be read.' + CHECK],
|
||||
'credential-definition-unpinned': [409, 'The copy\'s role definition is not pinned, so credentials cannot be bound to it.' + CHECK],
|
||||
'credential-binding-changed': [409, 'The copy\'s credential binding changed since it was read.' + CHECK],
|
||||
'credential-role-changed': [409, 'The copy\'s role changed since it was read.' + CHECK],
|
||||
'credential-unbound': [409, 'The copy has no credential binding to remove.' + CHECK],
|
||||
'credential-revoking': [409, 'The copy\'s credential is being revoked.' + CHECK],
|
||||
'credential-scope-exceeded': [409, 'The requested credential scope is wider than the role allows.' + CHECK],
|
||||
// The fields passed the shape check below, so a malformed answer here is a value the organization
|
||||
// checks refused: most often a model that is not a launch.models key.
|
||||
'invalid-request': [400, 'The bus refused a value in this proposal. Pick a model listed under Settings > Model proxy and a role the organization checks accept.' + EITHER],
|
||||
};
|
||||
// A reply the endpoint cannot read as a definite answer: no answer, or the bus server's request
|
||||
// codes. Anything else that reads as a code is a definite refusal.
|
||||
const NO_ANSWER = new Set(['outcome-unknown', 'invalid-response', 'response-too-large', 'organization-uncertain', 'request-timeout', 'invalid-envelope', 'incomplete-request', 'revision-conflict-revoked']);
|
||||
const CODE = /^[a-z][a-z-]{0,63}$/;
|
||||
const definiteStart = err => err instanceof BusReadError && typeof err.code === 'string' && CODE.test(err.code) &&
|
||||
!NO_ANSWER.has(err.code) && !err.code.startsWith('outcome-unknown') ? err.code : null;
|
||||
// E2E6 P2-4: the start's own shape check, the structural rules prepare() applies, so a malformed
|
||||
// proposal names its field and rule before anything leaves for the bus. A binding request keeps the
|
||||
// bus's own check (its shape lives in copy-bindings.mjs).
|
||||
const HIRE_KEYS = ['op', 'level', 'project', 'name', 'role', 'credentials', 'personality', 'route', 'reason', 'binding'];
|
||||
const plain = x => x !== null && typeof x === 'object' && !Array.isArray(x);
|
||||
const idOk = x => typeof x === 'string' && ID_PATTERN.test(x) && !['human', 'tester', 'user'].includes(x);
|
||||
const ID_RULE = 'lowercase letters, digits, dot, dash or underscore, starting with a letter or digit, at most 64 characters, and not human, tester or user';
|
||||
export function hireProblem(hire) {
|
||||
if (!plain(hire)) return { field: 'hire', rule: 'must be an object' };
|
||||
const extra = Object.keys(hire).find(k => !HIRE_KEYS.includes(k));
|
||||
if (extra) return { field: extra, rule: 'is not a hire field' };
|
||||
if ('binding' in hire) return null;
|
||||
for (const k of ['op', 'level', 'name', 'reason']) if (!Object.hasOwn(hire, k)) return { field: k, rule: 'is required' };
|
||||
if (!['hire', 'fire', 'change'].includes(hire.op)) return { field: 'op', rule: 'must be hire, fire or change' };
|
||||
if (!['org', 'project', 'root'].includes(hire.level)) return { field: 'level', rule: 'must be org, project or root' };
|
||||
if (!idOk(hire.name)) return { field: 'name', rule: `must be ${ID_RULE}` };
|
||||
if (typeof hire.reason !== 'string' || !hire.reason.trim()) return { field: 'reason', rule: 'must not be blank' };
|
||||
if (hire.reason.length > 500) return { field: 'reason', rule: 'must be at most 500 characters' };
|
||||
if (hire.level === 'project' && !idOk(hire.project)) return { field: 'project', rule: 'must name a code project at project level' };
|
||||
if (hire.level !== 'project' && 'project' in hire) return { field: 'project', rule: 'is only for project level' };
|
||||
if (hire.op === 'fire') {
|
||||
const k = ['role', 'route', 'credentials', 'personality'].find(x => x in hire);
|
||||
return k ? { field: k, rule: 'is not used by fire' } : null;
|
||||
}
|
||||
const route = hire.route;
|
||||
if (!plain(route)) return { field: 'route', rule: 'must name a harness and a model' };
|
||||
const rk = Object.keys(route).find(k => !['harness', 'model', 'thinking'].includes(k));
|
||||
if (rk) return { field: `route.${rk}`, rule: 'is not a route field' };
|
||||
for (const k of ['harness', 'model']) if (!Object.hasOwn(route, k)) return { field: `route.${k}`, rule: 'is required' };
|
||||
for (const [k, v] of Object.entries(route)) if (typeof v !== 'string' || !v || v.length > 200) return { field: `route.${k}`, rule: 'must be text of 1 to 200 characters' };
|
||||
const role = hire.role;
|
||||
if (!plain(role)) return { field: 'role', rule: 'must name a role template' };
|
||||
const kinds = ['template', 'definition', 'inline'].filter(k => k in role);
|
||||
if (kinds.length !== 1) return { field: 'role', rule: 'must name exactly one of a template, a definition or an inline role' };
|
||||
const ok = { template: ['template', 'sha256'], definition: ['definition', 'rev'], inline: ['inline'] }[kinds[0]];
|
||||
const rx = Object.keys(role).find(k => !ok.includes(k));
|
||||
if (rx) return { field: `role.${rx}`, rule: `is not used with role.${kinds[0]}` };
|
||||
if (kinds[0] === 'template') {
|
||||
if (!idOk(role.template)) return { field: 'role.template', rule: `must be ${ID_RULE}` };
|
||||
if (!DIGEST.test(role.sha256 ?? '')) return { field: 'role.sha256', rule: 'must be the template\'s 64-character digest; read the templates again' };
|
||||
}
|
||||
if (kinds[0] === 'definition') {
|
||||
if (!idOk(role.definition)) return { field: 'role.definition', rule: `must be ${ID_RULE}` };
|
||||
if (!Number.isSafeInteger(role.rev)) return { field: 'role.rev', rule: 'must be a whole number' };
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// #1873 CB5: the owner's next step once a copy credential binding decision is approved, fixed text
|
||||
// (design section 6 and its three steps). Nothing in it comes from the decision, the bus or a token.
|
||||
export const BINDING_NEXT = Object.freeze({
|
||||
@@ -156,6 +254,14 @@ export async function decisionHTTP(req, res, { path, decide, session, live, conf
|
||||
if(step==='start' || step==='templates') {
|
||||
const allowed=step==='start'?['business','hire']:['business'];
|
||||
if(id!=='hire' || Object.keys(value).length!==allowed.length || Object.keys(value).some(k=>!allowed.includes(k)) || !subjectOk(value.business))return refuse('invalid-request');
|
||||
if(step==='start') {
|
||||
const problem=hireProblem(value.hire);
|
||||
if(problem) {
|
||||
const label=problem.field[0].toUpperCase()+problem.field.slice(1);
|
||||
line(`error=invalid-request field=${problem.field}`);
|
||||
return json(res,400,{error:'invalid-request',field:problem.field,rule:problem.rule,message:`${label} ${problem.rule}. Nothing was sent to the bus.`});
|
||||
}
|
||||
}
|
||||
if(live()!==session)return refuse('sign-in-required');
|
||||
try {
|
||||
const result=await decide.call(step==='start'?'hire.start.console':'hire.templates.console',step==='start'?value.hire:{},{subject,business:value.business});
|
||||
@@ -167,11 +273,18 @@ export async function decisionHTTP(req, res, { path, decide, session, live, conf
|
||||
? (value.hire.binding.services===null?'unbind':'bind') : null;
|
||||
return json(res,200,step==='start'?{id:result.id,op:result.op,choice:result.choice,...(change?{next:BINDING_NEXT[change]}:{})}:result);
|
||||
} catch(err) {
|
||||
if(step!=='start' || !(err instanceof BusReadError) || !Object.hasOwn(HIRE_START_REFUSALS,err.code))
|
||||
return refuse(busCode(err,step==='start'?'outcome-unknown':'confirmation-unavailable'));
|
||||
const [status,message]=HIRE_START_REFUSALS[err.code];
|
||||
line(`error=${err.code}`);
|
||||
return json(res,status,{error:err.code,message});
|
||||
if(step!=='start')return refuse(busCode(err,'confirmation-unavailable'));
|
||||
const code=definiteStart(err);
|
||||
if(!code)return refuse('outcome-unknown');
|
||||
if(Object.hasOwn(HIRE_START_REFUSALS,code)) {
|
||||
const [status,message]=HIRE_START_REFUSALS[code];
|
||||
line(`error=${code}`);
|
||||
return json(res,status,{error:code,message});
|
||||
}
|
||||
if(Object.hasOwn(BUS_CODES,code))return refuse(BUS_CODES[code]);
|
||||
// A definite refusal this page has no wording for keeps its code, with a safe next step.
|
||||
line(`error=${code}`);
|
||||
return json(res,409,{error:code,message:'The bus refused this proposal.'+CHECK});
|
||||
}
|
||||
}
|
||||
if (step === 'confirmation') {
|
||||
|
||||
@@ -29,9 +29,11 @@ export function organizationConsole({ ctx, listOrgs, showOrg, resolveOrg, orgPat
|
||||
result.push({ id: entry.id, label: entry.id, invalid: true, reason: publicReason(ctx, error) });
|
||||
continue;
|
||||
}
|
||||
let busHealthy = false;
|
||||
try { busHealthy = (await busStatus(ctx, entry.id)).healthy === true; } catch { /* offline metadata remains visible */ }
|
||||
result.push({ id: entry.id, label: entry.id, theme: verified.shown.doc?.appearance?.theme ?? null, busHealthy });
|
||||
// E2E6 P2-8: a bus with no host recorded (stopped by its owner, or never started) is "stopped",
|
||||
// not a failure. A host that is recorded but does not answer stays plain unavailable.
|
||||
let busHealthy = false, busStopped = false;
|
||||
try { const s = await busStatus(ctx, entry.id); busHealthy = s?.healthy === true; busStopped = !busHealthy && s?.pid == null; } catch { /* offline metadata remains visible */ }
|
||||
result.push({ id: entry.id, label: entry.id, theme: verified.shown.doc?.appearance?.theme ?? null, busHealthy, ...(busStopped ? { busStopped: true } : {}) });
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -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,19 @@
|
||||
// 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(?:\/([^/]+))?)$/;
|
||||
import { systemOnly } from '../../organization/src/vocabulary.mjs';
|
||||
|
||||
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);
|
||||
@@ -37,10 +43,10 @@ const REVISION = /^[a-f0-9]{64}$/;
|
||||
// A board or workflow body stays small; the organization config caps both (WORKFLOWS_MAX, board columns).
|
||||
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,
|
||||
'invalid-request': 400, 'credential-leak': 400, 'starter-pack-invalid': 400, 'definition-invalid': 400, 'template-system-only': 400,
|
||||
'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 +95,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 +130,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
|
||||
@@ -154,7 +173,8 @@ async function workflowsRead(res, { workflows, live, session, writable }) {
|
||||
}
|
||||
const roles = {
|
||||
definitions: Object.keys(plain(doc.definitions) ? doc.definitions : {}).sort(),
|
||||
templates: current.templates.filter(n => typeof n === 'string').sort(),
|
||||
// #1873 triage-followups: a system-only template (organization vocabulary SYSTEM_ONLY) is never offered.
|
||||
templates: current.templates.filter(n => typeof n === 'string' && !systemOnly(n)).sort(),
|
||||
};
|
||||
return json(res, 200, { workflows: flowsOf(doc), projects, roles, revision: current.revision, writable });
|
||||
}
|
||||
@@ -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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[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})` : ''}.`);
|
||||
|
||||
@@ -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(); };
|
||||
|
||||
@@ -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)}
|
||||
}
|
||||
@@ -0,0 +1,568 @@
|
||||
// #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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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 ----------
|
||||
// SP11: a pane's unsent message is kept per thread for the life of the browser tab, so leaving the
|
||||
// Assistant page (a Full view link included) and coming back puts it in the composer again.
|
||||
// sessionStorage can be missing or refuse a write; the Map still keeps it while the page lives.
|
||||
// SP14: the kept messages belong to the person who typed them. They are stored with the viewer the
|
||||
// page's /api/config read names (bus.js, window.MosaicViewer), and read back only by a page that
|
||||
// read the same viewer. An entry stored under another viewer, or under none (an older entry, a
|
||||
// failed read), is removed unread, so a tab that never saw a sign-out (another tab signed out, the
|
||||
// session expired) does not hand one person's text to the next. A Console with no sign-in has one
|
||||
// fixed viewer. Until the viewer is read nothing is written; with none, messages live only in the page.
|
||||
const DRAFTS = 'mosaic-assistant-drafts';
|
||||
const kept = new Map();
|
||||
let viewer = null, known = false, viewerRead = null;
|
||||
const saveKept = () => {
|
||||
if (!known) return;
|
||||
try { if (kept.size && viewer) sessionStorage.setItem(DRAFTS, JSON.stringify({ viewer, drafts: Object.fromEntries(kept) })); else sessionStorage.removeItem(DRAFTS); } catch { /* the Map still holds it */ }
|
||||
};
|
||||
const ready = () => (viewerRead ??= (async () => {
|
||||
let v = null, stored = null;
|
||||
try { v = await window.MosaicViewer; } catch { /* no viewer */ }
|
||||
try { stored = JSON.parse(sessionStorage.getItem(DRAFTS) || 'null'); } catch { /* none kept */ }
|
||||
viewer = typeof v === 'string' && v ? v : null;
|
||||
known = true;
|
||||
const own = !draftsOff && viewer && stored && typeof stored === 'object' && stored.viewer === viewer && stored.drafts && typeof stored.drafts === 'object' && !Array.isArray(stored.drafts);
|
||||
if (own) for (const [k, t] of Object.entries(stored.drafts)) if (!kept.has(k) && typeof t === 'string' && t.trim() && parse(`open=${k}`).keys[0] === k) kept.set(k, t);
|
||||
saveKept();
|
||||
})());
|
||||
const typedIn = p => p.chat?.draft?.() || p.draft || p.el?.querySelector('form textarea')?.value || '';
|
||||
// Signed out, by an expired session or by the Sign out form: the kept drafts go and nothing is kept
|
||||
// again, not even by the pagehide the form's own submit causes, so the next person to sign in on
|
||||
// this tab never sees text typed before.
|
||||
let draftsOff = false;
|
||||
function keep(p) { if (draftsOff) return; const text = typedIn(p); if (text.trim()) kept.set(p.key, text); else kept.delete(p.key); saveKept(); }
|
||||
function drop(p) { if (kept.delete(p.key)) saveKept(); }
|
||||
window.addEventListener('pagehide', () => { if (mounted) for (const p of mounted.panes) keep(p); });
|
||||
function forgetDrafts() {
|
||||
draftsOff = true; kept.clear(); saveKept();
|
||||
try { sessionStorage.removeItem(DRAFTS); } catch { /* nothing to remove */ }
|
||||
if (mounted) for (const p of mounted.panes) { p.draft = ''; const t = p.el?.querySelector('form textarea'); if (t) t.value = ''; }
|
||||
}
|
||||
document.addEventListener('mosaic-signed-out', forgetDrafts);
|
||||
document.addEventListener('submit', e => { if (e.target?.id === 'sign-out') forgetDrafts(); }, true);
|
||||
function makePane(key) {
|
||||
const { org, id } = split(key);
|
||||
const p = { key, org, id, n: ++paneSeq, el: null, chat: null, first: true, title: null, draft: kept.get(key) || '', 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.
|
||||
// SP11: a pane whose send is in flight, or whose sent message the conversation does not show yet,
|
||||
// is held too, until its receipt is in.
|
||||
const holds = p => !!p.draft.trim() || !!p.chat?.hasDraft() || !!p.chat?.busy?.();
|
||||
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);
|
||||
drop(old); 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 or a message waiting to show. Send or clear one, wait for a sent message to show, 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}`;
|
||||
});
|
||||
|
||||
// SP11: closing a pane that holds unsent text asks first; a close drops the kept text.
|
||||
function closePane(p) {
|
||||
if (!mounted || !p) return;
|
||||
const at = mounted.panes.indexOf(p);
|
||||
if (at < 0) return;
|
||||
if (typedIn(p).trim() && !window.confirm(`Close ${p.title || 'this thread'}? Its unsent message is lost.`)) return;
|
||||
drop(p);
|
||||
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();
|
||||
const gen = ++mountGen;
|
||||
// SP14: the kept messages are known only once the viewer is; a page left meanwhile mounts nothing.
|
||||
await ready();
|
||||
if (gen !== mountGen) return;
|
||||
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;
|
||||
// SP14: a full set offers no fourth from the start, not only once the organization reads answer.
|
||||
root.querySelector('[data-assist-open]').disabled = mounted.panes.length >= MAX;
|
||||
await draw({ navigated: true });
|
||||
}
|
||||
function unmount() {
|
||||
if (!mounted) { mountGen++; return; }
|
||||
clearTimeout(mounted.timer);
|
||||
for (const p of mounted.panes) { keep(p); 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)) { keep(p); 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 });
|
||||
})();
|
||||
@@ -22,19 +22,25 @@
|
||||
const r=await fetch(path(org,step),body===undefined?{cache:'no-store'}:{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});
|
||||
const value=await r.json();if(!r.ok)throw Error(guidance[value.error]??`The bus refused: ${value.error??'outcome unknown'}. Refresh before retrying.`);return value;
|
||||
}
|
||||
async function load(org) {try{states.set(org,await call(org,''));}catch(error){states.set(org,{error:error.message});}}
|
||||
// E2E6 P1-1: a poll reloads this state; the last save's receipt and the open review list stay.
|
||||
// A failed poll keeps the last good read only while the page holds the form (dirty, or a field has
|
||||
// focus), so the held form is not dropped (review P3). A clean form shows the read error (re-check P3).
|
||||
const held=org=>{const form=[...document.querySelectorAll('[data-autonomy-org]')].find(n=>n.dataset.autonomyOrg===org)?.querySelector('[data-autonomy-form]');return !!form&&(form.hasAttribute('data-live-dirty')||form.contains(document.activeElement));};
|
||||
async function load(org) {const prev=states.get(org),keep={status:prev?.status??'',reviewOpen:prev?.reviewOpen===true};try{states.set(org,{...await call(org,''),...keep});}catch(error){states.set(org,prev&&!prev.error&&held(org)?{...prev,...keep}:{error:error.message,...keep});}}
|
||||
function section(org) {
|
||||
const s=states.get(org);
|
||||
if(!s || s.error)return `<section class="panel" data-autonomy><h3>Autonomy</h3><p>${esc(s?.error??'Autonomy could not be read.')}</p></section>`;
|
||||
const v=s.autonomy??{};
|
||||
return `<section class="panel" data-autonomy data-autonomy-org="${esc(org)}"><h3>Autonomy</h3><p>Choose how closely you follow each class of decision. Hard waits, flagged grants and credentials always need a person.</p><form data-autonomy-form>
|
||||
const v=s.autonomy??{},fk=k=>` data-focus-key="${esc(`autonomy-${k}:${org}`)}"`;
|
||||
// The form carries the revision it was drawn from: a form a poll kept (workspace holdLive) saves
|
||||
// against that revision, so it cannot overwrite a change it never showed.
|
||||
return `<section class="panel" data-autonomy data-autonomy-org="${esc(org)}" data-live-key="${esc(`autonomy:${org}`)}"><h3>Autonomy</h3><p>Choose how closely you follow each class of decision. Hard waits, flagged grants and credentials always need a person.</p><form data-autonomy-form data-revision="${esc(JSON.stringify(s.revision??null))}">
|
||||
<div class="autonomy-fields">${classes.map(k=>`<label>${labels[k]}<select name="${k}"${s.writable?'':' disabled'}>${levels.map(l=>`<option${s.levels[k]===l?' selected':''}>${l}</option>`).join('')}</select></label>`).join('')}</div>
|
||||
<div class="autonomy-fields"><label>Reverse window (hours)<input type="number" name="reverseWindowHours" min="1" max="168" value="${v.reverseWindowHours??24}"${s.writable?'':' disabled'}></label><label>Authority resolver<input name="authorityResolver" maxlength="64" value="${esc(v.authorityResolver??'')}" autocomplete="off"${s.writable?'':' disabled'}></label></div>
|
||||
<label class="autonomy-checkbox"><input name="notices" type="checkbox"${v.notices===true?' checked':''}${s.writable?'':' disabled'}> Console notices for decisions near the loop</label>
|
||||
<label class="autonomy-checkbox"><input name="notices" type="checkbox"${fk('notices')}${v.notices===true?' checked':''}${s.writable?'':' disabled'}> Console notices for decisions near the loop</label>
|
||||
<p>In the loop, the arbiter resolves and you confirm before work takes effect. Near the loop, work takes effect and you can reverse it within the window. Out of the loop, the trail records it without a notice.</p>
|
||||
${s.writable?'<button class="btn" type="submit">Save autonomy</button>':'<p>Only the owner can change autonomy.</p>'}
|
||||
<p data-autonomy-status role="status"></p></form>
|
||||
${s.writable?`<details><summary>Review reversals before moving out of the loop</summary><p>Read the decision trail and its reversals before recording your review.</p>${classes.map(k=>`<button class="btn" type="button" data-autonomy-review="${k}">Record review: ${labels[k]}</button>`).join('')}</details>`:''}</section>`;
|
||||
${s.writable?`<p><button class="btn" type="submit"${fk('save')}>Save autonomy</button> <button class="btn" type="button" data-autonomy-discard${fk('discard')}>Discard changes</button></p>`:'<p>Only the owner can change autonomy.</p>'}
|
||||
<p data-autonomy-status role="status">${esc(s.status)}</p></form>
|
||||
${s.writable?`<details data-autonomy-review-list${s.reviewOpen?' open':''}><summary${fk('review-list')}>Review reversals before moving out of the loop</summary><p>Read the decision trail and its reversals before recording your review.</p>${classes.map(k=>`<button class="btn" type="button" data-autonomy-review="${k}"${fk(`review-${k}`)}>Record review: ${labels[k]}</button>`).join('')}</details>`:''}</section>`;
|
||||
}
|
||||
function notice(d) {
|
||||
if(!d?.autonomy)return '';
|
||||
@@ -49,9 +55,16 @@
|
||||
const autonomy=Object.fromEntries(classes.map(k=>[k,fields.get(k)]));autonomy.notices=fields.has('notices');autonomy.reverseWindowHours=Number(fields.get('reverseWindowHours'));
|
||||
if(fields.get('authorityResolver'))autonomy.authorityResolver=fields.get('authorityResolver');
|
||||
const button=form.querySelector('button[type="submit"]'),status=form.querySelector('[data-autonomy-status]');button.disabled=true;
|
||||
try{const r=await call(org,'',{revision:s.revision,autonomy});s.revision=r.revision;s.autonomy=autonomy;s.levels=Object.fromEntries(classes.map(k=>[k,autonomy[k]]));status.textContent=`Saved. Receipt ${r.transaction}.`;}
|
||||
catch(error){status.textContent=error.message;}finally{button.disabled=false;}
|
||||
let base=s.revision;try{if(form.dataset.revision)base=JSON.parse(form.dataset.revision);}catch{/* drawn without one */}
|
||||
try{const r=await call(org,'',{revision:base,autonomy});s.revision=r.revision;s.autonomy=autonomy;s.levels=Object.fromEntries(classes.map(k=>[k,autonomy[k]]));s.status=`Saved. Receipt ${r.transaction}.`;form.dataset.revision=JSON.stringify(r.revision);delete form.dataset.liveDirty;status.textContent=s.status;}
|
||||
catch(error){s.status=error.message;status.textContent=s.status;}finally{button.disabled=false;}
|
||||
});
|
||||
// An edited form is dirty until it saves: holdLive keeps a dirty form through every poll.
|
||||
const dirty=e=>{const form=e.target.closest?.('[data-autonomy-form]');if(form)form.dataset.liveDirty='1';};
|
||||
document.addEventListener('input',dirty);document.addEventListener('change',dirty);
|
||||
// Review P3: Discard drops the held form and draws the last read in its place.
|
||||
document.addEventListener('click',e=>{const b=e.target.closest?.('[data-autonomy-discard]');const el=b?.closest('[data-autonomy-org]');if(!el||!states.get(el.dataset.autonomyOrg))return;const org=el.dataset.autonomyOrg;el.outerHTML=section(org);[...document.querySelectorAll('[data-autonomy-org]')].find(n=>n.dataset.autonomyOrg===org)?.querySelector('[data-autonomy-discard]')?.focus();});
|
||||
document.addEventListener('toggle',e=>{if(!e.target.matches?.('[data-autonomy-review-list]'))return;const s=states.get(e.target.closest('[data-autonomy-org]')?.dataset.autonomyOrg);if(s)s.reviewOpen=e.target.open;},true);
|
||||
document.addEventListener('click',async e=>{
|
||||
const button=e.target.closest('[data-autonomy-confirm],[data-autonomy-reverse],[data-autonomy-review]');if(!button)return;
|
||||
const section=button.closest('[data-autonomy-org]'),org=section.dataset.autonomyOrg,status=section.querySelector('[data-autonomy-status]');
|
||||
|
||||
@@ -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',workflows:'Workflows',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');
|
||||
|
||||
@@ -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;
|
||||
@@ -204,7 +208,7 @@
|
||||
out.groupAs = m?.from_role === 'human' ? 'request' : m?.decision ? 'decision' : 'other';
|
||||
} else if (r.table === 'decisions') {
|
||||
out.kind = 'decision.raised'; out.decision = r.id; out.actor = { role: r.raised_by_role, run: r.raised_by_run };
|
||||
out.text = `Raised a ${r.class} decision for ${r.route_to}: ${String(r.question).split('\n')[0]}`;
|
||||
out.text = `Raised a ${String(classWord(r.class)).toLowerCase()} decision for ${r.route_to}: ${String(r.question).split('\n')[0]}`;
|
||||
} else if (r.table === 'decision_events') {
|
||||
// The human answers from the CLI (via cli) or, since row 252 (#1753), a grant request from the
|
||||
// signed-in Console (via console); every other row is the broker's.
|
||||
@@ -239,7 +243,9 @@
|
||||
const badge = (text, kind = 'muted') => `<span class="badge badge-${kind}">${txt(text)}</span>`;
|
||||
// Class chip: the decision class, the action in mono. BLOCKING is its own chip (CSS capitalises it; the text stays lowercase).
|
||||
const CLASSES = ['routine', 'within-role', 'cross-role', 'gated'];
|
||||
const chip = (cls, action) => `<span class="tag${CLASSES.includes(cls) ? ` tag-${cls}` : ''}">${txt(cls)} · <code>${txt(action)}</code></span>`;
|
||||
// SP11: the class in the Inbox's words, from workspace.js's map.
|
||||
const classWord = cls => window.MosaicWorkspace?.classWord?.(cls) ?? cls;
|
||||
const chip = (cls, action) => `<span class="tag${CLASSES.includes(cls) ? ` tag-${cls}` : ''}">${txt(classWord(cls))} · <code>${txt(action)}</code></span>`;
|
||||
const blockChip = text => `<span class="tag tag-block">${txt(text)}</span>`;
|
||||
// An empty state says what would appear and where it comes from.
|
||||
const empty = (what, from) => `<div class="empty"><b>${what}</b>${from ? `<p>${from}</p>` : ''}</div>`;
|
||||
@@ -264,8 +270,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 +281,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,12 +349,14 @@
|
||||
});
|
||||
|
||||
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() {
|
||||
if (replies === null) return '<p class="small warn">The replies to it could not be read. Read again to retry; <code>mosaic inbox</code> in a terminal lists them.</p>';
|
||||
if (!replies.length) return '<p class="small muted">No reply yet. One shows here when the role answers, as the page refreshes.</p>';
|
||||
return `<h3 class="small">Replies <span class="count">${replies.length}</span></h3><ol class="s1-plain s1-replies">${replies.map(m => `<li><p class="small muted">${txt(m.from_role)} ${when(m.at)} · ${txt(m.class)} · <a href="#/trail/message/${enc(m.id)}">trail</a></p><p class="s1-q">${txt(m.body)}</p></li>`).join('')}</ol>${replies.length >= REPLIES ? `<p class="small muted">The first ${REPLIES} replies show here.</p>` : ''}`;
|
||||
return `<h3 class="small">Replies <span class="count">${replies.length}</span></h3><ol class="s1-plain s1-replies">${replies.map(m => `<li><p class="small muted">${txt(m.from_role)} ${when(m.at)} · ${txt(classWord(m.class))} · <a href="#/trail/message/${enc(m.id)}">trail</a></p><p class="s1-q">${txt(m.body)}</p></li>`).join('')}</ol>${replies.length >= REPLIES ? `<p class="small muted">The first ${REPLIES} replies show here.</p>` : ''}`;
|
||||
}
|
||||
const draft = { to: '', body: '' };
|
||||
function composerHtml() {
|
||||
@@ -462,14 +471,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 +604,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 +617,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 +631,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 +641,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;
|
||||
@@ -578,7 +709,7 @@
|
||||
if (after !== null && !SAFE.test(after)) return notFound('The message cursor is not a message id.');
|
||||
const page = await get('messages', after === null ? undefined : after);
|
||||
const body = page.rows.length ? `<ul id="message-list" class="waiting s1-replies">${page.rows.map(m =>
|
||||
`<li class="wait-item"><p class="small muted">${txt(m.from_role)} · ${txt(m.class)} · ${when(m.at)} · ${m.read ? 'Read' : 'Unread'} · <a href="#/trail/message/${enc(m.id)}">trail</a></p><p class="s1-message">${messageText(m)}</p></li>`).join('')}</ul>`
|
||||
`<li class="wait-item"><p class="small muted">${txt(m.from_role)} · ${txt(classWord(m.class))} · ${when(m.at)} · ${m.read ? 'Read' : 'Unread'} · <a href="#/trail/message/${enc(m.id)}">trail</a></p><p class="s1-message">${messageText(m)}</p></li>`).join('')}</ul>`
|
||||
: empty('No messages to you.', 'Messages appear here as the bus is read.');
|
||||
return `${head('Messages', `${readNote(get)} Every message to you, newest first. Reading here marks nothing read.`)}
|
||||
<p class="small muted">${page.total} messages · ${page.unread} unread</p>${body}
|
||||
@@ -771,12 +902,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 +927,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 +1123,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 +1146,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 +1203,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 +1270,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 +1300,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 +1378,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 +1614,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 +1626,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,17 +1690,43 @@
|
||||
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.
|
||||
// SP11: with no organization it is still the Dashboard (it says so and offers New organization);
|
||||
// #/ is then the Console's own board.
|
||||
if ((n === 0 && window.MosaicOrg) || (a === 'dashboard' && n === 1 && window.MosaicWorkspace)) 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();
|
||||
if (a === 'organization' && n === 1 && window.MosaicOrg) return window.MosaicWorkspace.dashboard(undefined, { q, configIn: orgConfig });
|
||||
// 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, configIn: orgConfig }));
|
||||
return agentsView(get, q, org);
|
||||
}
|
||||
if (a === 'agents' && n === 1) return agentsView(get);
|
||||
// SP9 (#1873): #/orgs/<id>/workflows lists an organization's workflows; #/orgs/<id>/workflows/<name> draws one, read only.
|
||||
if (a === 'workflows' && (n === 1 || n === 2) && window.MosaicOrg && window.MosaicWorkflows?.page) {
|
||||
const scope = /^#\/orgs\/([^/?]+)/.exec(location.hash)?.[1];
|
||||
let org = null; try { org = scope ? decodeURIComponent(scope) : window.MosaicOrg.id; } catch { return notFound(); }
|
||||
return org ? window.MosaicWorkflows.page(org, n === 2 ? b : null, q) : notFound();
|
||||
}
|
||||
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.`);
|
||||
if (a === 'settings' && (n === 1 || (n === 2 && [...settingsPages.map(p=>p[0]),'names'].includes(b)))) return settingsView(get, b || 'appearance');
|
||||
@@ -1577,7 +1741,15 @@
|
||||
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');
|
||||
// SP12: the organization page repaints in place too when only its query changes (the agent drawer).
|
||||
const drawerPage = path => wsPage(path) || (path === '/organization' && !!window.MosaicOrg);
|
||||
// A hash change that only opens, closes or switches the agent drawer is a repaint, not a navigation.
|
||||
const agentOnly = (from, to) => {
|
||||
const split = u => { const h = String(u || '').split('#')[1] ?? ''; const [p, q = ''] = h.split('?'); const n = new URLSearchParams(q); const agent = n.get('agent'); n.delete('agent'); n.sort(); return { p, rest: n.toString(), agent }; };
|
||||
const a = split(from), b = split(to);
|
||||
return a.p === b.p && a.rest === b.rest && a.agent !== b.agent && /^\/(agents|(orgs\/[^/?]+\/)?organization)$/.test(b.p);
|
||||
};
|
||||
const wsPage = path => (path === '/dashboard' && !!window.MosaicWorkspace) || !!window.MosaicOrg && (path === '/' || path === '' || path === '/dashboard' || path === '/projects' || path === '/inbox' || path === '/agents' || path === '/tasks' || /^\/workflows(\/[^/]+)?$/.test(path));
|
||||
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,14 +1799,22 @@
|
||||
// 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).
|
||||
const samePage = wsPage(path) && typeof shown === 'string' && shown.split('?')[0] === path;
|
||||
const samePage = drawerPage(path) && typeof shown === 'string' && shown.split('?')[0] === path;
|
||||
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 +1827,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 +1872,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;
|
||||
@@ -1743,8 +1933,11 @@
|
||||
// A route edit after the markup was prepared must win over that pending redraw.
|
||||
if(path==='/settings/routing' && routeVersion!==routesEditVersion){render(false);return;}
|
||||
const k = !navigated && (shown === route || samePage) ? keep() : null;
|
||||
// E2E6 P1-1: an org-page editor in use keeps its node, draft and focus across the repaint.
|
||||
const heldLive = k ? window.MosaicWorkspace?.holdLive?.($('bus-view')) : null;
|
||||
unmountEditor();
|
||||
$('bus-view').innerHTML = html; shown = route;
|
||||
if (heldLive) window.MosaicWorkspace.graftLive($('bus-view'), heldLive);
|
||||
syncAppearance(true);
|
||||
if (path.startsWith('/docs/')) paintDoc();
|
||||
if (path === '/organization') window.MosaicConsole?.attachBus(document.querySelector('[data-dashboard-bus]'));
|
||||
@@ -1756,8 +1949,11 @@
|
||||
if (k) restore(k);
|
||||
// Message on the Board (row 95) lands in the form it opened, addressed to the role.
|
||||
else if (focusSend && $('send-body')) { $('send-body').focus(); announce(`Message to ${draft.to}`); }
|
||||
// SP17: a step link on an organization's Workflows card lands in that step's title field.
|
||||
else if (navigated && window.MosaicWorkflows?.landed?.()) { /* landed() focused the field and said so */ }
|
||||
else if (navigated && h1) { const target=settingsFocusDisclosure&&path.startsWith('/settings/') ? $('settings-disclosure') : path.startsWith('/settings/') ? ($('settings-page-title')||h1) : h1; settingsFocusDisclosure=false; target.focus(); announce(target.textContent); }
|
||||
focusSend = false;
|
||||
window.MosaicWorkspace?.afterPaint?.();
|
||||
schedule();
|
||||
}
|
||||
|
||||
@@ -1809,7 +2005,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)}` }));
|
||||
@@ -1831,7 +2027,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(); }
|
||||
});
|
||||
@@ -1871,11 +2069,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,
|
||||
@@ -1906,7 +2106,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);
|
||||
@@ -1923,16 +2123,50 @@
|
||||
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);
|
||||
};
|
||||
configRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(applyConfig).catch(() => {});
|
||||
configRead = fetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => { if (r.type === 'opaqueredirect') { signOut(); return null; } return r.json(); }).then(c => { applyConfig(c); return c; }).catch(() => null);
|
||||
// SP14 (#1873): who is signed in, from this same read, for what the page keeps per person
|
||||
// (assistant.js's kept pane messages). null when the read failed or named nobody.
|
||||
window.MosaicViewer = configRead.then(c => (typeof c?.viewer === 'string' && c.viewer ? c.viewer : null));
|
||||
// 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.
|
||||
// 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.
|
||||
document.addEventListener('mosaic-workspace-render', () => { if (wsPage(routeOf().split('?')[0])) render(false); });
|
||||
document.addEventListener('mosaic-workspace-render', () => { if (drawerPage(routeOf().split('?')[0])) render(false); });
|
||||
document.addEventListener('mosaic-workspace-inbox', e => { const d = e.detail; if (d && Number.isFinite(d.open)) { inboxCount = { open: d.open, blocking: Number.isFinite(d.blocking) ? d.blocking : 0 }; sections(routeOf().split('?')[0]); } });
|
||||
// This context comes from the conversations renderer after its authorized read.
|
||||
let projectContext = null;
|
||||
@@ -2009,8 +2243,12 @@
|
||||
});
|
||||
nav.addEventListener('click', e => { if (drawerOpen && e.target.closest('a[href^="#/"]')) drawer(false, false); });
|
||||
window.addEventListener('resize', () => { if (drawerOpen && innerWidth >= 760) drawer(false, false); if (drawerOpen) $('nav-overflow').hidden = nav.scrollHeight <= nav.clientHeight + 1; });
|
||||
window.addEventListener('hashchange', () => render(true));
|
||||
window.addEventListener('hashchange', e => render(!agentOnly(e.oldURL, e.newURL)));
|
||||
$('refresh').addEventListener('click', () => render(false));
|
||||
$('pause').addEventListener('click', () => setTimeout(schedule)); // after app.js flips aria-pressed
|
||||
render(false).then(() => { if (!$('bus-view').hidden) { const h1 = $('bus-view').querySelector('h1'); if (h1 && location.hash.startsWith('#/')) h1.focus(); } });
|
||||
// #1873 triage-followups: the first render ends by focusing the page's heading. A drawer or dialog the
|
||||
// reader opened before then keeps its focus: the Triage drawer, an agent drawer, the narrow-screen
|
||||
// menu or any open dialog.
|
||||
const holdsFocus = () => { const a = document.activeElement; return !!a && (!!a.closest('.ws-drawer:not([hidden]), [data-ws-drawer], dialog[open], [role="dialog"], [role="alertdialog"]') || (drawerOpen && nav.contains(a))); };
|
||||
render(false).then(() => { if (!$('bus-view').hidden && !holdsFocus()) { const h1 = $('bus-view').querySelector('h1'); if (h1 && location.hash.startsWith('#/')) h1.focus(); } });
|
||||
})();
|
||||
@@ -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.
|
||||
@@ -15,6 +20,17 @@
|
||||
const inert = value => String(value ?? '').replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f\u202a-\u202e\u2066-\u2069]/g,
|
||||
c => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'));
|
||||
const txt = value => esc(inert(value));
|
||||
// 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;
|
||||
@@ -24,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;
|
||||
@@ -66,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;
|
||||
}
|
||||
@@ -75,11 +90,21 @@
|
||||
signedOut = true; forget();
|
||||
document.dispatchEvent(new Event('mosaic-signed-out'));
|
||||
}
|
||||
// SP11: whether the thread's agent runs no process, from the bus instances read the Agents page uses.
|
||||
// true: paused or stopped; false: running; null: the read failed or does not list the agent.
|
||||
async function agentIdle(instance, signal) {
|
||||
try {
|
||||
const res = await fetch(pane ? `/api/orgs/${encodeURIComponent(env.org)}/bus/instances` : '/api/bus/instances', { cache: 'no-store', redirect: 'manual', signal });
|
||||
if (!res.ok || res.type === 'opaqueredirect') return null;
|
||||
const item = (await res.json())?.rows?.[0]?.instances?.[instance];
|
||||
return item && typeof item === 'object' && Array.isArray(item.running) ? item.running.length === 0 : null;
|
||||
} catch (err) { if (err.name === 'AbortError') throw err; return null; }
|
||||
}
|
||||
async function request(path, value, signal) {
|
||||
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) }),
|
||||
});
|
||||
@@ -101,12 +126,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' : '';
|
||||
@@ -161,12 +188,12 @@
|
||||
function messageBody(m) {
|
||||
if (m.from_role !== 'human' && typeof m.body === 'string' && m.body.startsWith('The turn failed: ')) return `<div class="chat-body">The assistant couldn't reply. Try again, or check Agents.<div class="small">Details: ${txt(m.body.slice('The turn failed: '.length))}</div></div>`;
|
||||
const r = renderReply?.(m.body, { check: m.check ?? null, name: m.from_role, changed: changedBy(m.check) });
|
||||
if (r?.kind === 'reply') return `<div class="chat-body">${txt(r.text)}</div>${r.citations.length ? cites(r.citations) : ''}`;
|
||||
if (r?.kind === 'reply') return `<div class="chat-body">${prose(r.text)}</div>${r.citations.length ? cites(r.citations) : ''}`;
|
||||
if (r?.kind === 'notice') {
|
||||
const v = reverts.get(r.commit) ?? {};
|
||||
return `<div class="chat-body chat-notice"><span>${txt(r.text)}</span> ${current.archiveUnknown || current.projectArchived || window.MosaicOrg ? '' : `<button class="btn" type="button" data-revert="${esc(r.commit)}"${disabled(v.pending)}>Revert</button>`} <span class="chat-revert-receipt" role="status">${txt(v.receipt ?? '')}</span></div>`;
|
||||
}
|
||||
return `<div class="chat-body">${txt(m.body)}</div>`;
|
||||
return `<div class="chat-body">${prose(m.body)}</div>`;
|
||||
}
|
||||
const ago = iso => {
|
||||
const minutes = Math.floor((Date.now() - Date.parse(iso)) / 60000);
|
||||
@@ -196,7 +223,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 });
|
||||
@@ -238,6 +266,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);
|
||||
@@ -257,11 +287,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()) {
|
||||
@@ -271,7 +302,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);
|
||||
@@ -283,7 +314,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) => {
|
||||
@@ -294,9 +325,13 @@
|
||||
});
|
||||
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.
|
||||
// SP11: Resume shows unless the instances read says the agent is running.
|
||||
const resumable = threadWrites() && current.agentIdle !== false;
|
||||
const resume = resumable ? `<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>${resumable ? `<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>${resumable ? `<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({
|
||||
@@ -472,19 +507,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;
|
||||
@@ -509,7 +545,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')) {
|
||||
@@ -523,6 +559,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);
|
||||
@@ -559,7 +596,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; }
|
||||
@@ -601,8 +638,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>';
|
||||
@@ -632,8 +669,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);
|
||||
@@ -687,13 +726,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;
|
||||
@@ -733,7 +772,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) {
|
||||
@@ -762,7 +801,7 @@
|
||||
paint(); return;
|
||||
}
|
||||
const old = current;
|
||||
current = { container, kind, id, orgArchived: old?.orgArchived ?? false, loading: true, archiveUnknown: kind === 'thread' && !user && !tester, settings: !!settings, section, path: originalPath, canSend, user, tester, chatGrants: [], thread: old && old.id === id ? old.thread : null, shared: old && old.id === id ? old.shared : false, projects: old?.projects ?? [], threads: old?.threads ?? [], repos: old?.repos ?? [], instances: old?.instances ?? [], instanceError: kind === 'project' ? 'Reading thread instances…' : '', error: '', readFailed: false, channelDisabled: old?.channelDisabled ?? false, refused: false, legacyDefault: old && old.id === id ? old.legacyDefault : false, sessions: old && old.id === id ? old.sessions ?? [] : [], session: match[3] ?? (old && old.id === id ? old.session : null), key: match[3] ? id + '/' + match[3] : old && old.id === id ? old.key : id };
|
||||
current = { container, kind, id, orgArchived: old?.orgArchived ?? false, loading: true, archiveUnknown: kind === 'thread' && !user && !tester, settings: !!settings, section, path: originalPath, canSend, user, tester, chatGrants: [], thread: old && old.id === id ? old.thread : null, shared: old && old.id === id ? old.shared : false, projects: old?.projects ?? [], threads: old?.threads ?? [], repos: old?.repos ?? [], instances: old?.instances ?? [], instanceError: kind === 'project' ? 'Reading thread instances…' : '', error: '', readFailed: false, channelDisabled: old?.channelDisabled ?? false, refused: false, legacyDefault: old && old.id === id ? old.legacyDefault : false, sessions: old && old.id === id ? old.sessions ?? [] : [], session: match[3] ?? (old && old.id === id ? old.session : null), key: match[3] ? id + '/' + match[3] : old && old.id === id ? old.key : id, agentIdle: old && old.id === id ? old.agentIdle : null };
|
||||
current.projectArchived = current.projects.some(p => p.id === (kind === 'project' ? id : current.thread?.project) && p.archived);
|
||||
if (kind === 'thread' && old?.kind === 'thread' && old.id === id && !navigated && old.archiveUnknown === false && old.projects.some(p => p.id === old.thread?.project)) current.archiveUnknown = false;
|
||||
if (current.projectArchived) current.archiveUnknown = false;
|
||||
@@ -770,8 +809,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');
|
||||
@@ -812,7 +851,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);
|
||||
@@ -827,7 +867,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
|
||||
@@ -845,6 +885,10 @@
|
||||
if (g !== generation || out()) return;
|
||||
current.shares = shares.rows;
|
||||
}
|
||||
if (kind === 'thread' && current.thread && threadWrites()) {
|
||||
current.agentIdle = await agentIdle(current.thread.instance, signal);
|
||||
if (g !== generation || out()) return;
|
||||
}
|
||||
let s = null, page = null, after = null;
|
||||
if (kind === 'thread' && catalog === null) {
|
||||
current.legacyDefault = true; current.sessions = []; current.session = null;
|
||||
@@ -955,7 +999,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;
|
||||
@@ -985,17 +1029,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;
|
||||
@@ -1007,7 +1051,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');
|
||||
@@ -1021,8 +1065,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;
|
||||
@@ -1107,25 +1151,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';
|
||||
@@ -1134,9 +1178,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(); }
|
||||
@@ -1151,16 +1195,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);
|
||||
@@ -1172,7 +1217,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);
|
||||
}
|
||||
});
|
||||
@@ -1243,7 +1288,27 @@
|
||||
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 });
|
||||
// SP11: the unsent text of a pane's thread, and whether a write is in flight or a sent message
|
||||
// still waits for the conversation to show it.
|
||||
const draft = () => [...states.values()].find(s => s.draft?.trim())?.draft || '';
|
||||
const busy = () => [...states.values()].some(s => s.pending || !!s.receiptId);
|
||||
// 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, draft, busy, 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, draft: chat.draft, busy: chat.busy });
|
||||
}
|
||||
window.MosaicChat = Object.freeze({ render: main.render, leave: main.leave, forget: main.forget, projectPath: main.projectPath, hasDraft: main.hasDraft, pane });
|
||||
})();
|
||||
@@ -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?.() || window.MosaicWorkflows?.hasDraft?.()
|
||||
|| document.querySelector('.settings-dot')
|
||||
|| [...document.querySelectorAll('#reply, #conv-reply, #doc-source, #send-body')].some(el => !!el.value?.trim()));
|
||||
|
||||
|
||||
@@ -1,60 +1,366 @@
|
||||
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 triage-drawer: the instance owner's Triage drawer, one system-level entry in the top bar.
|
||||
// It reads /api/config and /api/triage through the fetch this file starts with, before the
|
||||
// organization wrapper below replaces it, so both reads stay unscoped: Triage is in no organization.
|
||||
// The entry, the drawer and every Triage request exist only when that config says triage: true.
|
||||
// Every value from the read goes in as text, never as markup. The drawer reads only while open.
|
||||
(() => {
|
||||
const systemFetch = window.fetch.bind(window);
|
||||
const POLL_MS = 4000;
|
||||
// Control, format (direction, zero-width, soft hyphen, word joiner, tag), separator and default-ignorable
|
||||
// characters (fillers, variation selectors) never reach the page; newline and tab stay.
|
||||
const HIDDEN = /(?![\n\t])[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/gu;
|
||||
const clean = (value, max = 8000) => (typeof value === 'string' ? value : value === null || value === undefined ? '' : String(value)).replace(/\r\n?/g, '\n').replace(HIDDEN, '').slice(0, max);
|
||||
const when = value => window.MosaicLocalTime(clean(value, 64));
|
||||
const el = (tag, cls, text) => { const n = document.createElement(tag); if (cls) n.className = cls; if (text !== undefined) n.textContent = clean(text); return n; };
|
||||
const NO_ROUTE = 'No model route is set for Triage, so Triage will not start. The instance owner sets the route first.';
|
||||
let config = null, entry = null, drawer = null, parts = null, timer = null, gen = 0, sending = false, lastTranscript = '', lastHealth = '', shown = [];
|
||||
|
||||
const read = () => systemFetch('/api/config', { cache: 'no-store', redirect: 'manual' }).then(r => (r.ok ? r.json() : null)).catch(() => null);
|
||||
read().then(c => { if (c && c.triage === true) { config = c; addEntry(); } });
|
||||
|
||||
function addEntry() {
|
||||
const bar = document.querySelector('.cmd-right');
|
||||
if (!bar || document.getElementById('triage-open')) return;
|
||||
entry = el('button', 'header-action');
|
||||
entry.id = 'triage-open'; entry.type = 'button'; entry.title = 'Triage';
|
||||
entry.setAttribute('aria-label', 'Triage'); entry.setAttribute('aria-expanded', 'false'); entry.setAttribute('aria-controls', 'triage-drawer');
|
||||
const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
|
||||
svg.setAttribute('class', 'i'); svg.setAttribute('viewBox', '0 0 24 24'); svg.setAttribute('aria-hidden', 'true');
|
||||
path.setAttribute('d', 'M3 12h4l3-8 4 16 3-8h4');
|
||||
svg.append(path); entry.append(svg, el('span', '', 'Triage'));
|
||||
entry.addEventListener('click', () => (drawer && !drawer.hidden ? close() : open()));
|
||||
bar.insertBefore(entry, document.getElementById('refresh') ?? bar.firstChild);
|
||||
}
|
||||
|
||||
function build() {
|
||||
drawer = el('aside', 'ws-drawer triage-drawer');
|
||||
drawer.id = 'triage-drawer';
|
||||
drawer.setAttribute('aria-labelledby', 'triage-title');
|
||||
const hd = el('div', 'hd'), title = el('h2', '', 'Triage'), x = el('button', 'x', '×');
|
||||
title.id = 'triage-title'; title.tabIndex = -1;
|
||||
x.type = 'button'; x.setAttribute('aria-label', 'Close Triage');
|
||||
x.addEventListener('click', close);
|
||||
hd.append(title, x);
|
||||
const state = el('p', 'triage-state'); state.id = 'triage-state'; state.setAttribute('role', 'status');
|
||||
const healthSec = el('details', 'triage-health-sec'); healthSec.open = true;
|
||||
const healthSum = el('summary', '', 'Health');
|
||||
const health = el('ul', 'triage-health'); health.id = 'triage-health';
|
||||
healthSec.append(healthSum, health);
|
||||
const convo = el('h3', 'triage-convo-title', 'Conversation');
|
||||
const transcript = el('ol', 'triage-transcript'); transcript.id = 'triage-transcript'; transcript.tabIndex = 0;
|
||||
transcript.setAttribute('aria-label', 'Triage conversation');
|
||||
const compose = el('div', 'triage-compose');
|
||||
drawer.append(hd, state, healthSec, convo, transcript, compose);
|
||||
drawer.addEventListener('keydown', e => { if (e.key === 'Escape') { e.preventDefault(); close(); } });
|
||||
document.body.append(drawer);
|
||||
parts = { title, state, health, transcript, compose, box: null, send: null, status: null, off: null };
|
||||
}
|
||||
|
||||
// The message box is built once and never rewritten or removed by a read, so a draft survives every
|
||||
// poll. A read that turns sending off hides the box; one that turns it on again shows it.
|
||||
function composer(view) {
|
||||
const c = parts.compose;
|
||||
const canSend = config.triageSend === true && view.send === true;
|
||||
const READ_ONLY = 'This Console is read-only, so messages cannot be sent from here.';
|
||||
if (!canSend && !parts.box) {
|
||||
if (!parts.off || !parts.off.isConnected) { parts.off = el('p', 'note triage-send-off'); parts.off.id = 'triage-send-off'; c.append(parts.off); }
|
||||
parts.off.textContent = READ_ONLY;
|
||||
return;
|
||||
}
|
||||
if (!parts.box) {
|
||||
c.replaceChildren();
|
||||
const label = el('label', 'triage-label', 'Message to Triage');
|
||||
label.htmlFor = 'triage-text';
|
||||
const box = el('textarea', 'triage-text'); box.id = 'triage-text'; box.rows = 3; box.maxLength = 8000;
|
||||
box.setAttribute('aria-describedby', 'triage-send-off triage-send-status');
|
||||
box.addEventListener('keydown', e => { if (e.key === 'Enter' && (e.ctrlKey || e.metaKey)) { e.preventDefault(); submit(); } });
|
||||
const row = el('div', 'triage-send-row');
|
||||
const send = el('button', 'ws-btn primary triage-send', 'Send'); send.id = 'triage-send'; send.type = 'button';
|
||||
send.addEventListener('click', submit);
|
||||
const hint = el('span', 'triage-hint', 'Ctrl+Enter sends');
|
||||
row.append(send, hint);
|
||||
const off = el('p', 'note triage-send-off'); off.id = 'triage-send-off';
|
||||
const status = el('p', 'triage-send-status'); status.id = 'triage-send-status'; status.setAttribute('role', 'status');
|
||||
c.append(label, box, off, row, status);
|
||||
Object.assign(parts, { label, box, send, status, off, row });
|
||||
}
|
||||
for (const n of [parts.label, parts.box, parts.row]) n.hidden = !canSend;
|
||||
if (!canSend) { parts.off.textContent = READ_ONLY; parts.box.disabled = parts.send.disabled = true; return; }
|
||||
// A route that is not set, or a session over its cap, turns the box off and says why.
|
||||
const until = typeof view.overCapUntil === 'string' && view.overCapUntil ? view.overCapUntil : null;
|
||||
const reason = view.route !== 'set' ? 'Sending is off: no model route is set for Triage.'
|
||||
: until ? `Sending is off: Triage is over its daily token cap until ${when(until)}.` : '';
|
||||
parts.off.textContent = reason;
|
||||
parts.box.disabled = !!reason;
|
||||
parts.send.disabled = !!reason || sending;
|
||||
}
|
||||
|
||||
const stateLine = view => {
|
||||
if (view.route !== 'set') return clean(view.routeMessage) || NO_ROUTE;
|
||||
if (view.overCapUntil) return clean(view.capMessage) ? `${clean(view.capMessage)} Local time: ${when(view.overCapUntil)}.` : `Triage is over its daily token cap. It takes messages again at ${when(view.overCapUntil)}.`;
|
||||
if (view.running === true) return 'Running.';
|
||||
const x = view.lastExit;
|
||||
if (x && typeof x === 'object') {
|
||||
const how = [x.code !== null && x.code !== undefined ? `code ${clean(x.code)}` : '', x.signal ? `signal ${clean(x.signal)}` : ''].filter(Boolean).join(', ') || 'no code';
|
||||
return `Not running. Last exit: ${how} at ${when(x.at)}.`;
|
||||
}
|
||||
return 'Not running. No run has ended yet.';
|
||||
};
|
||||
|
||||
const notRead = v => v === 'not read' || v === null || v === undefined || typeof v !== 'object';
|
||||
const configWords = c => (notRead(c) ? 'not read' : c.valid === true ? 'valid' : `not valid${c.code ? ` (${clean(c.code)})` : ''}`);
|
||||
function healthLines(s) {
|
||||
if (notRead(s)) return ['Health: not read'];
|
||||
const lines = [];
|
||||
lines.push(notRead(s.console) ? 'Console: not read' : `Console: ${clean(s.console.state) || 'not read'}, ${when(s.console.at)}`);
|
||||
if (notRead(s.proxy)) lines.push('Proxy: not read');
|
||||
else {
|
||||
const p = s.proxy;
|
||||
const words = [p.healthy === true ? 'healthy' : p.healthy === false ? 'not healthy' : 'health not read'];
|
||||
if (p.initialized === false) words.push('not set up');
|
||||
if (p.installed === false) words.push('not installed');
|
||||
if (typeof p.active === 'string' && p.active) words.push(`unit ${clean(p.active)}`);
|
||||
if (p.fence === true) words.push('fence set');
|
||||
lines.push(`Proxy: ${words.join(', ')}`);
|
||||
}
|
||||
lines.push(`System config: ${configWords(s.systemConfig)}`);
|
||||
const orgs = s.organizations;
|
||||
if (notRead(orgs) || !Array.isArray(orgs.list)) lines.push('Organizations: not read');
|
||||
else if (!orgs.list.length) lines.push('Organizations: none');
|
||||
else for (const o of orgs.list) {
|
||||
if (!o || typeof o !== 'object') continue;
|
||||
const bus = notRead(o.bus) ? 'bus not read' : `bus ${clean(o.bus.state) || 'not read'}${o.bus.lastStart && o.bus.lastStart.ok === false ? `, last start failed ${when(o.bus.lastStart.at)}` : ''}`;
|
||||
const proc = notRead(o.processing) ? 'processing not read' : o.processing.invalid === true ? 'processing state not valid' : o.processing.halted === true ? 'processing stopped' : 'processing on';
|
||||
lines.push(`${clean(o.id) || 'unnamed'}: ${bus}, ${proc}, config ${configWords(o.config)}`);
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
const WHO = { owner: 'You', triage: 'Triage', host: 'Console' };
|
||||
function entryNode(m, owners) {
|
||||
const from = Object.hasOwn(WHO, m.from) ? m.from : 'other';
|
||||
const li = el('li', `triage-msg from-${from}`);
|
||||
li.dataset.from = from;
|
||||
const head = el('div', 'triage-msg-head');
|
||||
head.append(el('strong', '', WHO[from] ?? 'Unknown sender'), el('span', 'triage-when', when(m.at)));
|
||||
li.append(head);
|
||||
if (m.in_reply_to && (from === 'triage' || from === 'host')) {
|
||||
const asked = owners.get(m.in_reply_to);
|
||||
li.append(el('p', 'triage-reply', asked !== undefined ? `Reply to: ${asked.length > 120 ? `${asked.slice(0, 119)}…` : asked}` : 'Reply to an earlier message'));
|
||||
}
|
||||
li.append(el('p', 'triage-text-body', m.text));
|
||||
if (from === 'triage') {
|
||||
const cards = Array.isArray(m.cards) ? m.cards.filter(c => c && typeof c === 'object') : [];
|
||||
if (cards.length) {
|
||||
const list = el('ul', 'triage-cards');
|
||||
list.setAttribute('aria-label', 'Suggested commands');
|
||||
for (const c of cards) {
|
||||
const card = el('li', 'triage-card');
|
||||
card.append(el('span', 'triage-card-meta', `Step: ${clean(c.step)} · Organization: ${clean(c.org)}`), el('code', 'triage-card-cmd', c.command));
|
||||
list.append(card);
|
||||
}
|
||||
li.append(list);
|
||||
}
|
||||
const dropped = Number.isSafeInteger(m.dropped) && m.dropped > 0 ? m.dropped : 0;
|
||||
if (dropped) li.append(el('p', 'triage-dropped', `${dropped} ${dropped === 1 ? 'card' : 'cards'} dropped: not a known step or organization.`));
|
||||
}
|
||||
return li;
|
||||
}
|
||||
|
||||
function render(view) {
|
||||
// Where the reader is, measured before anything above the conversation changes its height.
|
||||
const t = parts.transcript, atBottom = t.scrollHeight - t.scrollTop - t.clientHeight < 24, top = t.scrollTop;
|
||||
parts.state.textContent = stateLine(view);
|
||||
parts.state.dataset.kind = view.route !== 'set' ? 'off' : view.overCapUntil ? 'cap' : view.running === true ? 'running' : 'stopped';
|
||||
const lines = healthLines(view.snapshot);
|
||||
const healthKey = JSON.stringify(lines);
|
||||
if (healthKey !== lastHealth) { lastHealth = healthKey; parts.health.replaceChildren(...lines.map(l => el('li', l.endsWith('not read') ? 'not-read' : '', l))); }
|
||||
// The box first: it sets the conversation's height, which the scroll position below depends on.
|
||||
composer(view);
|
||||
const list = Array.isArray(view.transcript) ? view.transcript.filter(m => m && typeof m === 'object') : [];
|
||||
const key = JSON.stringify(list);
|
||||
if (key !== lastTranscript) {
|
||||
const first = lastTranscript === '';
|
||||
// The host keeps the newest 200 lines, so a new line can drop old ones from the top. A reader who
|
||||
// has scrolled up keeps the line they are reading at the same place, not the same scroll number.
|
||||
const edge = () => t.getBoundingClientRect().top;
|
||||
let anchor = null;
|
||||
if (!first && !atBottom) {
|
||||
const i = [...t.children].findIndex(n => n.getBoundingClientRect().bottom > edge() + 1);
|
||||
if (i >= 0 && shown[i] !== undefined) anchor = { i, key: shown[i], off: t.children[i].getBoundingClientRect().top - edge() };
|
||||
}
|
||||
lastTranscript = key;
|
||||
const owners = new Map(list.filter(m => m.from === 'owner' && typeof m.id === 'string').map(m => [m.id, clean(m.text)]));
|
||||
if (list.length) t.replaceChildren(...list.map(m => entryNode(m, owners)));
|
||||
else t.replaceChildren(el('li', 'triage-empty', 'No messages yet.'));
|
||||
const next = list.map(m => JSON.stringify(m));
|
||||
// Lines only drop from the top and add at the bottom, so the anchor moves up by the number dropped.
|
||||
// That finds the right one of two identical lines; anything else falls back to the first match.
|
||||
const fits = d => shown.length - d <= next.length && shown.slice(d).every((k, n) => next[n] === k);
|
||||
let j = -1;
|
||||
if (anchor) { let d = 0; while (d <= anchor.i && !fits(d)) d += 1; j = d <= anchor.i ? anchor.i - d : next.indexOf(anchor.key); }
|
||||
shown = next;
|
||||
if (first || atBottom) t.scrollTop = t.scrollHeight;
|
||||
else {
|
||||
t.scrollTop = top;
|
||||
if (j >= 0) t.scrollTop += t.children[j].getBoundingClientRect().top - edge() - anchor.off;
|
||||
else if (anchor) t.scrollTop = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Only the newest read renders and schedules the next one, so a send's read and the timer's never
|
||||
// run two chains at once, and an answer that lands after close is dropped.
|
||||
async function poll() {
|
||||
const mine = ++gen;
|
||||
clearTimeout(timer);
|
||||
let view = null, failed = null;
|
||||
try {
|
||||
const r = await systemFetch('/api/triage', { cache: 'no-store', redirect: 'manual' });
|
||||
if (r.ok) view = await r.json(); else failed = r.status;
|
||||
} catch { failed = 'no answer'; }
|
||||
if (mine !== gen || !drawer || drawer.hidden) return;
|
||||
if (view && typeof view === 'object') render(view);
|
||||
else { parts.state.textContent = `Triage could not be read (${failed}). The drawer tries again shortly.`; parts.state.dataset.kind = 'error'; }
|
||||
timer = setTimeout(poll, POLL_MS);
|
||||
}
|
||||
|
||||
function open() {
|
||||
if (!drawer) build();
|
||||
drawer.hidden = false;
|
||||
entry.setAttribute('aria-expanded', 'true');
|
||||
if (!parts.state.dataset.kind) { parts.state.textContent = 'Reading Triage.'; parts.state.dataset.kind = 'reading'; }
|
||||
poll().then(() => { if (!drawer.hidden && !drawer.contains(document.activeElement)) (parts.box && !parts.box.disabled ? parts.box : parts.title).focus(); });
|
||||
}
|
||||
|
||||
function close() {
|
||||
if (!drawer || drawer.hidden) return;
|
||||
gen += 1;
|
||||
clearTimeout(timer); timer = null;
|
||||
drawer.hidden = true;
|
||||
entry.setAttribute('aria-expanded', 'false');
|
||||
entry.focus();
|
||||
}
|
||||
|
||||
// Plain words for each answer. A refused send keeps the draft; an unknown outcome is never resent.
|
||||
function answer(status, body) {
|
||||
const code = body && typeof body.error === 'string' ? body.error : '';
|
||||
if (status === 202) return { sent: true, text: 'Sent. Triage answers in the conversation above.' };
|
||||
// These come after the host wrote the message, with its "did not start" line under it.
|
||||
if (code === 'triage-route-invalid' || code === 'triage-start-failed') return { text: `Not delivered: ${code === 'triage-start-failed' ? 'the Triage session did not start' : 'Triage did not start because the model route\'s answer is not usable'}. The message is in the conversation with the Console's note; it was not sent again.` };
|
||||
// This one can come before or after the message is written.
|
||||
if (code === 'triage-dir-unsafe') return { text: 'Not delivered: a Triage directory is not safe to use. It was not sent again: check the conversation before you send it again.' };
|
||||
if (status === 409) return { text: code === 'triage-no-route' ? 'Not sent: no model route is set for Triage. The instance owner sets the route first.' : code === 'triage-route-refused' ? 'Not sent: the model route refused to start Triage.' : 'Not sent: the model route\'s answer is not usable.' };
|
||||
if (status === 429) {
|
||||
if (code === 'triage-over-cap') {
|
||||
const until = typeof body.until === 'string' ? clean(body.until) : '';
|
||||
return { text: until ? `Not sent: Triage is over its daily token cap. It takes messages again at ${when(until)} (${until}).` : 'Not sent: Triage is over its daily token cap.' };
|
||||
}
|
||||
return { text: 'Not sent: Triage has too many messages waiting. Try again in a moment.' };
|
||||
}
|
||||
if (status === 400) return { text: code === 'triage-message-empty' ? 'Not sent: the message is empty.' : code === 'triage-message-too-long' ? 'Not sent: the message is too long.' : 'Not sent: the Console did not accept this as a Triage message.' };
|
||||
if (status === 403) return { text: code === 'read-only' ? 'Not sent: this Console is read-only.' : 'Not sent: the Console refused a request that did not come from this page.' };
|
||||
if (status === 503 && code === 'outcome-unknown') return { unknown: true, text: 'Triage did not answer. The message may or may not have arrived. It was not sent again: check the conversation before you send it again.' };
|
||||
if (status === 503) return { text: `Not sent: ${clean(body && body.message) || 'Triage could not take the message'}.` };
|
||||
if (status === 401 || status === 404) return { text: 'Not sent: this page can no longer reach Triage. Reload the page.' };
|
||||
return { text: `Not sent: the Console answered ${status}.` };
|
||||
}
|
||||
|
||||
async function submit() {
|
||||
if (sending || !parts.box || parts.box.disabled) return;
|
||||
const text = parts.box.value;
|
||||
if (!text.trim()) { parts.status.textContent = 'Not sent: the message is empty.'; return; }
|
||||
sending = true; parts.send.disabled = true; parts.status.textContent = 'Sending…';
|
||||
let result;
|
||||
try {
|
||||
const r = await systemFetch('/api/triage/message', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ text }), cache: 'no-store', redirect: 'manual' });
|
||||
result = answer(r.status, await r.json().catch(() => null));
|
||||
} catch {
|
||||
result = { unknown: true, text: 'The Console did not answer. The message may or may not have arrived. It was not sent again: check the conversation before you send it again.' };
|
||||
}
|
||||
sending = false;
|
||||
if (!parts.box) return;
|
||||
// The status line can grow the composer; a reader at the bottom of the transcript stays there.
|
||||
const t = parts.transcript, atBottom = t.scrollHeight - t.scrollTop - t.clientHeight < 24;
|
||||
parts.status.textContent = result.text;
|
||||
parts.status.dataset.kind = result.sent ? 'ok' : result.unknown ? 'unknown' : 'refused';
|
||||
// Only a 202 clears the box, and only when the reader has not typed more since.
|
||||
if (result.sent && parts.box.value === text) parts.box.value = '';
|
||||
parts.send.disabled = parts.box.disabled;
|
||||
if (atBottom) t.scrollTop = t.scrollHeight;
|
||||
if (drawer && !drawer.hidden) poll();
|
||||
}
|
||||
})();
|
||||
// #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\/[^/]+/, '') || '/';
|
||||
// SP13: the organization segment stops at `/` or `?`, so `#/orgs/<id>?agent=…` names <id>.
|
||||
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] ? '/' : m[1][0] === '?' ? `/${m[1]}` : 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 +368,119 @@ 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;
|
||||
// SP11: the Assistant keeps its panes' unsent text per thread, so it is not asked about here.
|
||||
const dirty = () => window.MosaicChat?.hasDraft?.() || window.MosaicOrgCreate?.hasDraft?.() || window.MosaicWorkflows?.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?.();
|
||||
window.MosaicWorkflows?.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.
|
||||
|
||||
@@ -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><link rel="stylesheet" href="/workflows.css"><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>
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
.org-field-err{display:block;font-size:13px;color:var(--danger);margin:4px 0 0}
|
||||
.org-field-err code,.org-errors code{overflow-wrap:anywhere}
|
||||
.org-verb code{overflow-wrap:normal;word-break:normal}
|
||||
.cmd-word{display:inline-block;max-width:100%;overflow-wrap:anywhere}
|
||||
.org-start-row{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:24px;align-items:start}
|
||||
.org-inline{display:grid;grid-template-columns:minmax(0,1fr) auto;gap:6px 8px;align-items:center}
|
||||
.org-inline label{grid-column:1/-1;font-size:14px;font-weight:600;color:var(--strong)}
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
(() => {
|
||||
const $ = id => document.getElementById(id);
|
||||
const txt = v => String(v ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[c]);
|
||||
// E2E6 minor: a command shown as "Same as" wraps between words, never inside a flag such as
|
||||
// --if-revision. Each word is an inline-block; one longer than the line still breaks inside itself.
|
||||
const cmd = v => `<code>${String(v ?? '').split(' ').map(w => `<span class="cmd-word">${txt(w)}</span>`).join(' ')}</code>`;
|
||||
// #1873 P1-6: the remote check a repository receipt records, in one plain line.
|
||||
const CHECKED = { reachable: 'reachable', 'needs-credential': 'needs a credential', unreachable: 'unreachable' };
|
||||
const checkLine = r => `Remote check: ${CHECKED[r.check.result] ?? 'unknown'}, ${r.check.message}. Origin: ${r.origin ?? 'none'}.`;
|
||||
@@ -253,7 +256,7 @@
|
||||
$('org-archive').hidden = mode !== 'edit' || state !== 'active'; $('org-archived').hidden = mode !== 'edit' || state !== 'archived';
|
||||
$('org-restore-verb').textContent = state === 'archived' ? `Same as mosaic org restore ${id} --if-revision ${revision}` : '';
|
||||
$('org-editor-title').textContent = mode === 'create' ? `New organization: ${id}` : `Organization: ${id}`;
|
||||
$('org-editor-verb').innerHTML = verb ? `Same as <code>${txt(verb)}</code>` : '';
|
||||
$('org-editor-verb').innerHTML = verb ? `Same as ${cmd(verb)}` : '';
|
||||
$('org-save').textContent = mode === 'create' ? 'Save organization' : 'Save changes';
|
||||
$('org-errors').hidden = true;
|
||||
renderForm(); renderJSON(true);
|
||||
@@ -318,7 +321,7 @@
|
||||
{ title: 'Initialize project records', verb: `mosaic project init ${id} ${project}` },
|
||||
];
|
||||
const list = $('org-quick-steps');
|
||||
list.innerHTML = steps.map((s, i) => `<li class="panel org-step" data-quick-step="${i}" tabindex="-1"><div class="org-step-head"><h4>${txt(s.title)}</h4><span class="org-pill">Not started</span></div><p class="org-verb">Same as <code>${txt(s.verb)}</code></p><p class="org-field-err" role="alert"></p></li>`).join('');
|
||||
list.innerHTML = steps.map((s, i) => `<li class="panel org-step" data-quick-step="${i}" tabindex="-1"><div class="org-step-head"><h4>${txt(s.title)}</h4><span class="org-pill">Not started</span></div><p class="org-verb">Same as ${cmd(s.verb)}</p><p class="org-field-err" role="alert"></p></li>`).join('');
|
||||
const run = $('org-quick-run'); run.disabled = true; $('org-quick-open').disabled = true; $('org-advanced-open').disabled = true; $('org-preset').disabled = true; $('org-thinking').disabled = true; banner('');
|
||||
let current = 0;
|
||||
try {
|
||||
@@ -404,7 +407,7 @@
|
||||
}
|
||||
function showReceipt(title, body) {
|
||||
const box = $('org-receipt');
|
||||
box.innerHTML = `<h3 id="org-receipt-title">${txt(title)}</h3><p>Same as <code>${txt(body.verb)}</code></p><pre class="org-pre">${txt(JSON.stringify(body.receipt, null, 2))}</pre>`;
|
||||
box.innerHTML = `<h3 id="org-receipt-title">${txt(title)}</h3><p>Same as ${cmd(body.verb)}</p><pre class="org-pre">${txt(JSON.stringify(body.receipt, null, 2))}</pre>`;
|
||||
box.hidden = false; status(`${title}. Receipt shown.`);
|
||||
}
|
||||
async function refreshList() {
|
||||
@@ -454,7 +457,7 @@
|
||||
const c = st.choice.get(key) || {}, remote = c.mode === 'remote';
|
||||
return `<li class="panel org-step org-step-${cls}" data-step="${txt(key)}" aria-labelledby="org-step-${i}-title">
|
||||
<div class="org-step-head"><h4 id="org-step-${i}-title"><span class="org-step-n">${i + 1}</span> ${txt(title)}</h4><span class="org-pill ${cls}">${txt(stateLabel)}</span></div>
|
||||
<p class="org-verb">Same as <code>${txt(s.verb || '')}</code></p>
|
||||
<p class="org-verb">Same as ${cmd(s.verb || '')}</p>
|
||||
${s.message ? `<p class="org-help">${txt(s.message)}</p>` : ''}
|
||||
${key.startsWith('project:') && s.receipt?.check ? `<p class="org-help" data-remote-check>${txt(checkLine(s.receipt))}</p>` : ''}
|
||||
${s.lastError ? `<p class="org-field-err" role="alert">${txt(s.lastError)}</p>` : ''}
|
||||
@@ -570,7 +573,7 @@
|
||||
: `The bus did not start: ${bus.message || 'no reason was given.'}`;
|
||||
const offer = (!known || bus.outcome !== 'done') && canWrite;
|
||||
const box = $('org-archive-success');
|
||||
box.innerHTML = `<p>Organization restored. ${txt(line)}</p>${known && bus.verb ? `<p class="org-verb">Same as <code>${txt(bus.verb)}</code></p>` : ''}${offer ? `<p><button type="button" data-restore-bus="${txt(id)}">Restart bus</button> <span role="status" data-restore-bus-receipt></span></p>` : ''}`;
|
||||
box.innerHTML = `<p>Organization restored. ${txt(line)}</p>${known && bus.verb ? `<p class="org-verb">Same as ${cmd(bus.verb)}</p>` : ''}${offer ? `<p><button type="button" data-restore-bus="${txt(id)}">Restart bus</button> <span role="status" data-restore-bus-receipt></span></p>` : ''}`;
|
||||
box.hidden = false; box.focus();
|
||||
}
|
||||
// Restart bus for the restored organization, the same route as the dashboard's (console-restart.js).
|
||||
@@ -620,13 +623,13 @@
|
||||
if (r.status !== 200) {
|
||||
$('org-delete-error').textContent = `The outcome is unknown. ${r.body.message || `Deletion stopped (${r.body.error || r.status}).`} Inspect the receipt and resume with the CLI.`;
|
||||
const receipt = r.body.receipt;
|
||||
$('org-delete-progress').innerHTML = `<p>Same as <code>${txt(r.body.verb || `mosaic org delete ${id} --confirm ${id}`)}</code></p><ol class="org-steps"><li class="panel org-step">Bus: ${receipt?.bus ? 'Done' : r.body.step === 'bus' ? 'Stopped' : 'Not started'}</li><li class="panel org-step">Local files: ${receipt?.moves?.length || 0} moved; ${txt(r.body.step || 'deletion')} stopped</li><li class="panel org-step">Registry: ${receipt?.registry === 'removed' ? 'Done' : 'Not complete'}</li></ol>`;
|
||||
$('org-delete-progress').innerHTML = `<p>Same as ${cmd(r.body.verb || `mosaic org delete ${id} --confirm ${id}`)}</p><ol class="org-steps"><li class="panel org-step">Bus: ${receipt?.bus ? 'Done' : r.body.step === 'bus' ? 'Stopped' : 'Not started'}</li><li class="panel org-step">Local files: ${receipt?.moves?.length || 0} moved; ${txt(r.body.step || 'deletion')} stopped</li><li class="panel org-step">Registry: ${receipt?.registry === 'removed' ? 'Done' : 'Not complete'}</li></ol>`;
|
||||
status('Deletion stopped.'); return;
|
||||
}
|
||||
if (!verifiedReply(r, 'delete')) throw Error('unknown deletion outcome');
|
||||
editorDirty = false; setupDirty.clear(); $('org-editor').hidden = true; $('org-setup').hidden = true; $('org-delete').hidden = true; $('org-archive').hidden = true; $('org-archived').hidden = true;
|
||||
const box = $('org-delete-success');
|
||||
box.innerHTML = `<h3>Organization deleted</h3><p>Same as <code>${txt(r.body.verb)}</code></p><ol class="org-steps"><li class="panel org-step org-step-done">Bus stopped or was already stopped: Done</li><li class="panel org-step org-step-done">Local files moved to the deleted folder: Done</li><li class="panel org-step org-step-done">Organization removed from the list: Done</li></ol><details><summary>Receipt</summary><pre class="org-pre">${txt(JSON.stringify(r.body.receipt, null, 2))}</pre></details>`;
|
||||
box.innerHTML = `<h3>Organization deleted</h3><p>Same as ${cmd(r.body.verb)}</p><ol class="org-steps"><li class="panel org-step org-step-done">Bus stopped or was already stopped: Done</li><li class="panel org-step org-step-done">Local files moved to the deleted folder: Done</li><li class="panel org-step org-step-done">Organization removed from the list: Done</li></ol><details><summary>Receipt</summary><pre class="org-pre">${txt(JSON.stringify(r.body.receipt, null, 2))}</pre></details>`;
|
||||
const rows = await refreshOrganizations(); box.hidden = false; box.focus(); status('Organization deleted.');
|
||||
switchIfCurrentRemoved(id, rows);
|
||||
} catch { $('org-delete-error').textContent = 'The outcome is unknown. Inspect the receipt and resume with the CLI.'; $('org-delete-progress').innerHTML = `<p>Resume with <code>${txt(`mosaic org delete ${id} --confirm ${id}`)}</code></p>`; }
|
||||
|
||||
@@ -1,15 +1,20 @@
|
||||
[data-packs],[data-workflows]{margin-top:16px}
|
||||
:is(.pack-list,.pack-hires,.wf-list){list-style:none;margin:8px 0;padding:0}
|
||||
:is(.pack-row,.pack-hire,.wf-item){border-top:1px solid var(--border);padding:12px 0;overflow-wrap:anywhere}
|
||||
.pack-list,.pack-hires{list-style:none;margin:8px 0;padding:0}
|
||||
.pack-row,.pack-hire{border-top:1px solid var(--border);padding:12px 0;overflow-wrap:anywhere}
|
||||
.pack-preview{border:1px solid var(--border);border-radius:var(--r);padding:12px;margin:12px 0;overflow-wrap:anywhere}
|
||||
.pack-preview .ws-tbl{overflow-x:auto}
|
||||
.pack-nohire,.wf-missing,.wf-note{color:var(--danger)}
|
||||
/* E2E6 P2-3: the preview's overflow-wrap:anywhere let the table squeeze words ("Workfl ow"). Cells wrap
|
||||
at word breaks; only a path, which has none, may break anywhere. */
|
||||
.pack-preview .ws-tbl :is(td,th){overflow-wrap:normal;word-break:normal}
|
||||
.pack-preview .ws-tbl td code{overflow-wrap:anywhere}
|
||||
.pack-nohire,.wf-missing{color:var(--danger)}
|
||||
.wf-missing{font-size:.9em}
|
||||
.wf-steps{margin:6px 0;padding-left:22px}.wf-steps li{margin:4px 0}
|
||||
.wf-editor{display:grid;gap:12px;margin:12px 0}
|
||||
.wf-step{border:1px solid var(--border);border-radius:var(--r);padding:12px;display:grid;gap:10px;min-width:0}
|
||||
:is(.wf-editor,[data-packs]) label{display:flex;flex-direction:column;gap:6px;min-width:0}
|
||||
:is(.wf-editor,[data-packs]) :is(select,input,textarea){width:100%;box-sizing:border-box;min-height:44px;padding:8px 12px;border:1px solid var(--border);border-radius:var(--r);background:var(--canvas);color:var(--text);font:inherit}
|
||||
: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}
|
||||
[data-packs] label{display:flex;flex-direction:column;gap:6px;min-width:0}
|
||||
[data-packs] :is(select,input,textarea){width:100%;box-sizing:border-box;min-height:44px;padding:8px 12px;border:1px solid var(--border);border-radius:var(--r);background:var(--canvas);color:var(--text);font:inherit}
|
||||
[data-packs] .btn{min-height:44px;margin:4px 8px 4px 0}
|
||||
[data-packs] :is(button,select,input,textarea):focus-visible{outline:2px solid var(--focus);outline-offset:2px}
|
||||
[data-packs] [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}
|
||||
@@ -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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
@@ -16,6 +20,7 @@
|
||||
'starter-pack-template-changed': 'A role template this pack pins has changed. The pack needs a new version.',
|
||||
'starter-pack-invalid': 'This pack does not pass its checks against the organization.',
|
||||
'definition-invalid': 'A role in this pack does not pass the organization checks.',
|
||||
'template-system-only': 'This pack names a role template that is for the system, not for an organization. It cannot be applied.',
|
||||
'project-not-found': 'That project is not in the organization file.',
|
||||
'credential-leak': 'The pack carries a value the credential store holds. It cannot be applied.',
|
||||
'read-only': 'This Console was started without send. Packs can be previewed, not applied.',
|
||||
@@ -25,7 +30,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',
|
||||
@@ -39,11 +60,15 @@
|
||||
if (!r.ok) throw Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`);
|
||||
return value;
|
||||
}
|
||||
// E2E6 P1-1, P2-2: a poll reloads the list but keeps the open preview, the project picked for each
|
||||
// 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 s = { packs: null, writable: false, error: null, projects: null, preview: null, status: '' };
|
||||
const prev = states.get(org);
|
||||
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
|
||||
@@ -69,7 +94,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>`;
|
||||
}
|
||||
@@ -81,38 +110,66 @@
|
||||
const hires = Array.isArray(v.hires) && v.hires.length ? `<h4>Hires</h4><ul class="pack-hires">${v.hires.map(hireBlock).join('')}</ul>` : '<p class="note">The pack proposes no hires.</p>';
|
||||
const skills = v.skills?.notEnabled?.length ? `<p data-pack-skills>Skills this machine has not enabled: ${v.skills.notEnabled.map(n => `<code>${esc(n)}</code>`).join(', ')}</p>` : '';
|
||||
const chief = v.chief === false ? '<p class="note">The organization has no chief, so no line is compared against one.</p>' : '';
|
||||
const apply = s.writable ? `<button class="btn" type="button" data-pack-apply>Apply this plan</button>` : '<p class="note">This Console was started without send. Packs can be previewed, not applied.</p>';
|
||||
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'
|
||||
? s.projects === null ? '<p class="note">The project list could not be read.</p>' : s.projects.length
|
||||
? `<label>Project<select data-pack-project>${s.projects.map(id => `<option value="${esc(id)}">${esc(id)}</option>`).join('')}</select></label>`
|
||||
? `<label>Project<select data-pack-project data-focus-key="${esc(`pack-project:${org}:${entry.id}`)}">${s.projects.map(id => `<option value="${esc(id)}"${s.picks[entry.id] === id ? ' selected' : ''}>${esc(id)}</option>`).join('')}</select></label>`
|
||||
: '<p class="note">No code project to apply this pack to.</p>'
|
||||
: '';
|
||||
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>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)}"><h3>Starter packs</h3><p>${esc(s?.error ?? 'Starter packs could not be read.')}</p></section>`;
|
||||
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)}"><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);
|
||||
if (el) el.outerHTML = section(org);
|
||||
}
|
||||
document.addEventListener('change', e => {
|
||||
const select = e.target.closest?.('[data-pack-project]');
|
||||
const s = select && states.get(select.closest('[data-packs-org]')?.dataset.packsOrg);
|
||||
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) };
|
||||
@@ -122,11 +179,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 };
|
||||
})();
|
||||
@@ -1,83 +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)}
|
||||
}
|
||||
/* 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}
|
||||
}
|
||||
@@ -1,477 +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 => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[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);
|
||||
body.innerHTML = html; p.html = html; p.project = null;
|
||||
rewrite(p, body);
|
||||
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 });
|
||||
}
|
||||
// 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 });
|
||||
})();
|
||||
@@ -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)}
|
||||
|
||||
@@ -86,7 +86,17 @@
|
||||
.breadcrumbs:has(.project-crumb-current) a::after { content:''; position:absolute; top:0; bottom:0; left:50%; width:max(100%,44px); transform:translateX(-50%); }
|
||||
.chat-area:has(.project-header),.chat-area:has(.project-list-head) { max-width:none; margin-inline:0; }
|
||||
.project-tabs { scrollbar-width:none; } .project-tabs::-webkit-scrollbar { display:none; }
|
||||
@media (max-width:699px) { .project-tabs { mask-image:linear-gradient(to right, #000 calc(100% - 22px), transparent 100%); } }
|
||||
/* E2E6 P2-12: a strip wider than the screen fades out over its last 48px, so a cut tab reads as "more
|
||||
this way". Where scroll timelines exist the fade runs only while there is more to scroll: a strip that
|
||||
fits has an inactive timeline and keeps the 0px initial value (review P3), and the fade goes once the
|
||||
strip is scrolled to its end. Without scroll timelines the 48px fade is static. */
|
||||
@property --tabs-fade { syntax:'<length>'; inherits:false; initial-value:0px; }
|
||||
@keyframes project-tabs-cue { 0%, 92% { --tabs-fade:48px; } 100% { --tabs-fade:0px; } }
|
||||
@media (max-width:699px) {
|
||||
.project-tabs { mask-image:linear-gradient(to right, #000 calc(100% - var(--tabs-fade)), transparent 100%); }
|
||||
@supports (animation-timeline: scroll()) { .project-tabs { animation:project-tabs-cue linear both; animation-timeline:scroll(self inline); } }
|
||||
@supports not (animation-timeline: scroll()) { .project-tabs { --tabs-fade:48px; } }
|
||||
}
|
||||
.project-chip { white-space:nowrap; flex:none; }
|
||||
@media(max-width:699px) { .project-stepper span { white-space:nowrap; font-size:10.5px; padding:4px 1px; }.project-work-head { align-items:flex-start; } }
|
||||
|
||||
@@ -336,7 +346,8 @@ body:has(.chat-area .project-header):has(.project-chat) .breadcrumbs { margin-bo
|
||||
/* Header actions use the specified compact widths while retaining 44px targets. */
|
||||
.project-primary-action { box-sizing:border-box; flex:none; }
|
||||
@media (min-width:1200px) {
|
||||
.project-header:not([data-project-conversation="true"]) { width:calc(100vw - 270px); }
|
||||
/* E2E6 P2-11: 100vw counts the page scrollbar; max-width keeps the header inside its column. */
|
||||
.project-header:not([data-project-conversation="true"]) { width:calc(100vw - 270px); max-width:100%; box-sizing:border-box; }
|
||||
.project-header:not([data-project-conversation="true"]) .project-actions { align-self:flex-start; margin-top:4px; }
|
||||
.project-primary-action:nth-of-type(1) { width:130px; }
|
||||
.project-primary-action:nth-of-type(2) { width:88px; }
|
||||
@@ -504,3 +515,5 @@ body:has(.chat-area .project-header):has(.project-chat) .breadcrumbs { margin-bo
|
||||
|
||||
/* Keep the action in flow when a read error occupies the top of the page. */
|
||||
@media (min-width:700px) { .chat-area:has(.chat-error) .project-create:not([open]) { position:static; margin:12px 0; } }
|
||||
/* E2E6 P2-15: inline code in a chat bubble keeps the bubble's text colour on a light tint. */
|
||||
.project-chat .chat-body code { font-size:.92em; padding:0 .3em; border-radius:4px; background:color-mix(in srgb, currentColor 12%, transparent); color:inherit; }
|
||||
@@ -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) {
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -301,6 +301,11 @@ button:disabled,[aria-disabled=true]{cursor:not-allowed}
|
||||
#agents-table tbody th,#routes-table tbody th{text-transform:none;font-size:14px;font-weight:600;color:var(--strong)}
|
||||
@media(max-width:759px){.settings-content .routing-panel{border:0;background:transparent;padding:0}.routing-panel .table-wrap{border:0;overflow:visible}.routing-panel #routes-table tr{display:grid;grid-template-columns:1fr 1fr;gap:0 10px;background:var(--surface)}.routing-panel #routes-table th,.routing-panel #routes-table td:first-of-type,.routing-panel #routes-table .fallback-cell:first-of-type{grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4){grid-column:1/-1}.routing-panel #routes-table td:nth-of-type(4)::before{content:'Fallback: None'}.routing-panel #routes-table .fallback-open td:nth-of-type(4)::before{content:'Fallback harness'}}
|
||||
.settings-content label:has(>input[type=checkbox]){display:inline-flex;align-items:center;gap:8px;min-height:44px;padding:0 8px}
|
||||
/* E2E6 minor: the harness checkboxes sit side by side, each keeping its 44px target, instead of one per
|
||||
50px row. Save and the receipt keep their own full-width rows. */
|
||||
.settings-content fieldset.harness-control{display:flex;flex-wrap:wrap;align-items:center;gap:6px 12px}
|
||||
.settings-content fieldset.harness-control>legend{flex-basis:100%}
|
||||
.settings-content fieldset.harness-control>:is(button,p){flex-basis:100%}
|
||||
.settings-content :is(.instance-form,.level-form) textarea,.settings-content .assistant-form textarea{display:block;width:100%}
|
||||
.route-definition{display:none}.settings-spinner{display:inline-block;width:16px;height:16px;border:2px solid currentColor;border-right-color:transparent;border-radius:50%;vertical-align:middle;animation:settings-spin .8s linear infinite}@keyframes settings-spin{to{transform:rotate(360deg)}}@media(prefers-reduced-motion:reduce){.settings-spinner{animation:none}}
|
||||
@media(max-width:759px){#routes-table .route-definition{display:inline;float:right;color:var(--muted);font-size:12px;font-weight:400}}
|
||||
@@ -444,6 +449,9 @@ html[data-organizations] .ws-btn:disabled,html[data-organizations] .ws-busctl [d
|
||||
html[data-organizations] .ws-btn svg.i{width:15px;height:15px}
|
||||
/* The live bus restart is console-restart.js's own button; it carries its icon through repaints,
|
||||
so the icon stays on the button however wide the receipt below it is. */
|
||||
/* E2E6 P2-13: the disabled pair (a pane, or a Console without the trail) sits in a flex row too. As two
|
||||
inline-flex boxes on one line, Restart bus took its baseline from its glyph and sat 2.6px above Stop bus. */
|
||||
html[data-organizations] [data-dashboard-bus]:not(.ws-busctl){display:inline-flex;flex-wrap:wrap;align-items:center;gap:6px}
|
||||
html[data-organizations] .ws-busctl{display:inline-flex;flex-direction:column;align-items:flex-end}
|
||||
html[data-organizations] .ws-busctl .bus-restart{display:inline-flex;flex-direction:column;align-items:flex-end;gap:4px}
|
||||
html[data-organizations] .ws-busctl .bus-buttons{display:inline-flex;flex-wrap:wrap;gap:6px;justify-content:flex-end}
|
||||
@@ -454,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}
|
||||
@@ -477,6 +485,17 @@ html[data-organizations] .ws-panel.tight{padding:12px 14px}
|
||||
html[data-organizations] .ws-split{display:grid;grid-template-columns:minmax(0,1.45fr) minmax(0,1fr);gap:16px;align-items:start}
|
||||
html[data-organizations] .ws-split{margin-top:22px}
|
||||
html[data-organizations] .ws-split>section>.ws-sec-h:first-child{margin-top:0}
|
||||
/* SP13: a column whose first child wraps its heading (the Workflows card) starts level with the other. */
|
||||
html[data-organizations] .ws-split>section>:first-child>.ws-sec-h:first-child{margin-top:0}
|
||||
/* SP13 (#1873): the organization page's two columns stack once its content is narrower than both need,
|
||||
with or without the agent drawer beside it: a wrap, not a viewport breakpoint. */
|
||||
html[data-organizations] .ws-dash>.ws-split{display:flex;flex-wrap:wrap;align-items:flex-start}
|
||||
html[data-organizations] .ws-dash>.ws-split>section{flex:1.45 1 480px;min-width:0}
|
||||
html[data-organizations] .ws-dash>.ws-split>section+section{flex:1 1 360px}
|
||||
/* E2E6 P1-3: the long editors (Autonomy, Packs, Workflows) span the page below the split, so neither
|
||||
column runs screens past the other at 1440. */
|
||||
html[data-organizations] .ws-wide{display:grid;grid-template-columns:minmax(0,1fr);gap:16px;margin-top:22px}
|
||||
html[data-organizations] .ws-wide>.panel{margin:0}
|
||||
|
||||
/* Organization dashboard (sample 03). */
|
||||
html[data-organizations] .ws-orghead{display:flex;flex-wrap:wrap;align-items:center;gap:14px;margin-bottom:14px}
|
||||
@@ -494,9 +513,13 @@ html[data-organizations] .ws-doc:hover{background:var(--raised)}
|
||||
html[data-organizations] .ws-doc svg.i{width:14px;height:14px;color:var(--muted)}
|
||||
html[data-organizations] .ws-doc small{font-weight:500;color:var(--muted);font-size:11px}
|
||||
html[data-organizations] .ws-more{font-size:13px;font-weight:600;margin-left:4px;color:var(--action);text-decoration:none}
|
||||
html[data-organizations] .ws-tiles{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px}
|
||||
html[data-organizations] .ws-tile{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:12px 14px;display:grid;gap:6px;align-content:start}
|
||||
html[data-organizations] .ws-tile.is-empty{grid-column:1/-1;border-style:dashed;background:transparent}
|
||||
/* SP8 (#1873): one row of figure tiles under the page heading, each a link to the page that lists what it counts. */
|
||||
html[data-organizations] .ws-tiles{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin:0 0 16px}
|
||||
html[data-organizations] .ws-tiles.six{grid-template-columns:repeat(6,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-tile{background:var(--surface);border:1px solid var(--line);border-radius:8px;padding:12px 14px;display:grid;gap:6px;align-content:start;min-width:0;color:inherit;text-decoration:none}
|
||||
html[data-organizations] a.ws-tile:hover{border-color:color-mix(in srgb,var(--action) 45%,var(--line))}
|
||||
html[data-organizations] a.ws-tile:focus-visible{outline:2px solid var(--action);outline-offset:2px}
|
||||
html[data-organizations] .ws-tile>.ws-label{font-size:12.5px;font-weight:600;letter-spacing:0;text-transform:none}
|
||||
html[data-organizations] .ws-empty-t{font-size:13.5px;font-weight:600;color:var(--strong)}
|
||||
html[data-organizations] .ws-tbl{overflow-x:auto;border:1px solid var(--line);border-radius:8px;background:var(--surface)}
|
||||
html[data-organizations] .ws-tbl table{width:100%;border-collapse:collapse;font-size:13px;margin:0}
|
||||
@@ -506,15 +529,20 @@ html[data-organizations] .ws-tbl tr:last-child td{border-bottom:0}
|
||||
html[data-organizations] .ws-tbl .t1{color:var(--strong)}
|
||||
html[data-organizations] .ws-tbl .t2{display:block;font-size:12px;color:var(--muted)}
|
||||
html[data-organizations] .ws-tbl td.mono{font-family:var(--mono);font-size:12.5px;white-space:nowrap}
|
||||
html[data-organizations] .ws-cfg{display:grid;list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--surface)}
|
||||
html[data-organizations] .ws-cfg{container-type:inline-size;display:grid;list-style:none;margin:0;padding:0;border:1px solid var(--line);border-radius:8px;overflow:hidden;background:var(--surface)}
|
||||
html[data-organizations] .ws-cfg li{display:grid;align-items:center;grid-template-columns:18px 132px minmax(0,1fr) auto auto;gap:0 10px;padding:7px 12px;border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent)}
|
||||
html[data-organizations] .ws-cfg li:last-child{border-bottom:0}
|
||||
html[data-organizations] .ws-cfg svg.i{width:16px;height:16px;color:var(--muted)}
|
||||
html[data-organizations] .ws-cfg .k{font-size:13px;font-weight:600;color:var(--strong)}
|
||||
html[data-organizations] .ws-cfg .v{font-size:12px;color:var(--muted);min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
html[data-organizations] .ws-cfg .v{font-size:12px;color:var(--muted);min-width:0;overflow-wrap:anywhere}
|
||||
html[data-organizations] .ws-cfg .src-tag{font:500 11px var(--mono);color:var(--accent);white-space:nowrap}
|
||||
html[data-organizations] .ws-cfg .go{font-size:12.5px;font-weight:600;color:var(--action);text-decoration:none;min-width:32px;text-align:right}
|
||||
html[data-organizations] .ws-cfg a.go:hover{text-decoration:underline}
|
||||
/* SP13: a Settings card narrower than its five columns need puts each value on its own line. */
|
||||
@container (max-width:560px){
|
||||
html[data-organizations] .ws-cfg li{grid-template-columns:18px minmax(0,1fr) auto auto}
|
||||
html[data-organizations] .ws-cfg .v{grid-column:2/-1;grid-row:2}
|
||||
}
|
||||
html[data-organizations] .ws-cfg li.danger .k,html[data-organizations] .ws-cfg li.danger svg.i,html[data-organizations] .ws-cfg li.danger .go,html[data-organizations] .ws-cfg li.danger .src-tag{color:var(--danger)}
|
||||
|
||||
/* Agents (sample 08). */
|
||||
@@ -538,6 +566,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%}
|
||||
@@ -550,7 +583,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}
|
||||
@@ -563,9 +596,8 @@ html[data-organizations] .ws-tbl .ws-dot.s-working b,html[data-organizations] .w
|
||||
html[data-organizations] .ws-tbl .ws-dot.s-waiting b{color:var(--warning)}
|
||||
html[data-organizations] .ws-tbl .ws-dot.s-error b{color:var(--danger)}
|
||||
html[data-organizations] .ws-tbl .ws-dot.s-idle b,html[data-organizations] .ws-tbl .ws-dot.s-offline b{color:var(--muted)}
|
||||
html[data-organizations] .ws-g5{display:grid;gap:10px;grid-template-columns:repeat(5,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-tile .ws-big{font-size:24px;font-weight:800;color:var(--strong);letter-spacing:-.02em;font-variant-numeric:tabular-nums;line-height:1.1}
|
||||
html[data-organizations] .ws-tile .ws-big small{font-size:13px;font-weight:600;color:var(--muted);letter-spacing:0;margin-left:4px}
|
||||
html[data-organizations] .ws-tile .ws-big small{font-size:13px;font-weight:600;color:var(--muted);letter-spacing:0}
|
||||
html[data-organizations] .ws-tile .ws-delta{font-size:12px;color:var(--muted)}
|
||||
html[data-organizations] .ws-tile .ws-delta b{color:var(--success);font-weight:600}
|
||||
html[data-organizations] .ws-tile.quiet{border-style:dashed;background:transparent}
|
||||
@@ -574,6 +606,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)}
|
||||
@@ -611,7 +655,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}
|
||||
@@ -657,6 +701,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)}
|
||||
@@ -676,8 +738,41 @@ html[data-organizations] .ws-cmd{display:flex;gap:6px;align-items:center;min-wid
|
||||
html[data-organizations] .ws-cmd code{flex:1;min-width:0;overflow-x:auto;white-space:nowrap;background:var(--surface);border:1px solid var(--line);border-radius:4px;padding:3px 6px;font-size:12px;color:var(--strong)}
|
||||
html[data-organizations] .ws-cmd .ws-btn{padding:4px 6px}
|
||||
html[data-organizations] #copy-status:empty{display:none}
|
||||
/* SP12 (#1873): the agent drawer, a non-modal region at the right of the page; the page stays under it. */
|
||||
html[data-organizations] .ws-drawer-open{color:inherit;font-weight:inherit;text-decoration:underline;text-decoration-color:color-mix(in srgb,currentColor 35%,transparent);text-underline-offset:3px}
|
||||
html[data-organizations] .ws-drawer-open:hover{text-decoration-color:currentColor}
|
||||
html[data-organizations] .ws-drawer{position:fixed;top:var(--bar-h,52px);right:0;bottom:0;width:min(420px,100vw);z-index:40;display:flex;flex-direction:column;background:var(--surface);border-left:1px solid var(--line);box-shadow:-8px 0 24px color-mix(in srgb,#000 14%,transparent);overflow:auto;overscroll-behavior:contain}
|
||||
html[data-organizations] .ws-drawer .hd{display:flex;align-items:center;gap:8px;padding:12px 14px 12px 17px;border-bottom:1px solid var(--line);background:var(--surface);position:sticky;top:0;z-index:1;box-shadow:inset 4px 0 0 var(--org,var(--action))}
|
||||
html[data-organizations] .ws-drawer h2{margin:0;font-size:18px;font-weight:800;color:var(--strong);overflow-wrap:anywhere;min-width:0}
|
||||
html[data-organizations] .ws-drawer h2:focus{outline:none}
|
||||
html[data-organizations] .ws-drawer h2:focus-visible{outline:2px solid var(--action);outline-offset:2px}
|
||||
html[data-organizations] .ws-drawer .x{margin-left:auto;flex:none;width:32px;height:32px;border:1px solid var(--line);border-radius:6px;background:var(--canvas);color:var(--strong);font-size:20px;line-height:1;cursor:pointer}
|
||||
html[data-organizations] .ws-drawer .body{padding:14px;display:grid;gap:16px;align-content:start}
|
||||
html[data-organizations] .ws-drawer-fields{margin:0;display:grid;gap:8px}
|
||||
html[data-organizations] .ws-drawer-f{display:grid;grid-template-columns:96px minmax(0,1fr);gap:8px;align-items:baseline;font-size:13px}
|
||||
html[data-organizations] .ws-drawer-f dt{color:var(--muted);font-weight:600}
|
||||
html[data-organizations] .ws-drawer-f dd{margin:0;color:var(--strong);overflow-wrap:anywhere;min-width:0}
|
||||
html[data-organizations] .ws-drawer-f code,html[data-organizations] .ws-drawer .mono{font:12px var(--mono)}
|
||||
html[data-organizations] .ws-drawer-sec{display:grid;gap:6px;margin:0}
|
||||
html[data-organizations] .ws-drawer-sec h3{margin:0;font:700 11px/1.3 var(--font);letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
|
||||
html[data-organizations] .ws-drawer-list{list-style:none;margin:0;padding:0;display:grid;gap:4px;font-size:13px}
|
||||
html[data-organizations] .ws-drawer-list li{border:1px solid var(--line);border-radius:6px;padding:6px 9px;background:var(--canvas);overflow-wrap:anywhere}
|
||||
html[data-organizations] .ws-drawer-list .t2{margin-left:4px;font-size:12px;color:var(--muted)}
|
||||
html[data-organizations] .ws-drawer .ws-more{font-size:13px}
|
||||
html[data-organizations] .ws-drawer .note{margin:0}
|
||||
html[data-organizations] .ws-drawer-acts{display:flex;flex-wrap:wrap;gap:8px;align-items:center;border-top:1px solid var(--line);padding-top:12px}
|
||||
html[data-organizations] .ws-drawer-confirm{display:flex;flex-wrap:wrap;gap:8px;align-items:center;font-size:13px;color:var(--strong);flex-basis:100%}
|
||||
html[data-organizations] .ws-drawer .ws-btn.danger{color:var(--danger)}
|
||||
html[data-organizations] .ws-drawer-status{margin:0;flex-basis:100%;font-size:13px;color:var(--strong)}
|
||||
html[data-organizations] .ws-drawer-status:empty{display:none}
|
||||
html[data-organizations] .ws-drawer-acts .note{flex-basis:100%}
|
||||
/* Wide screens: the page keeps clear of the drawer, so nothing sits under it. */
|
||||
@media (min-width:1200px){html[data-organizations] body:has(.ws-drawer) .content{padding-right:calc(420px + 22px)}}
|
||||
@media (max-width:700px){
|
||||
html[data-organizations] .ws-drawer{top:0;left:0;right:0;width:auto;border-left:0;box-shadow:none}
|
||||
}
|
||||
@media (max-width:1100px){
|
||||
html[data-organizations] .ws-g5{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-tiles.six{grid-template-columns:repeat(3,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-ibx-grid.with-insp{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-insp{position:static;max-height:none}
|
||||
}
|
||||
@@ -687,11 +782,9 @@ html[data-organizations] #copy-status:empty{display:none}
|
||||
html[data-organizations] .content:has(.ws){padding:14px 16px 24px}
|
||||
html[data-organizations] .tree{padding:10px 12px 20px}
|
||||
html[data-organizations] .ws h1{font-size:24px}
|
||||
html[data-organizations] .ws-split,html[data-organizations] .ws-tiles{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-tile.is-empty{grid-column:auto}
|
||||
html[data-organizations] .ws-split{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-tiles,html[data-organizations] .ws-tiles.six{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-sec-h .note{flex-basis:100%;order:3}
|
||||
html[data-organizations] .ws-cfg li{grid-template-columns:18px minmax(0,1fr) auto auto}
|
||||
html[data-organizations] .ws-cfg .v{grid-column:2/-1;grid-row:2}
|
||||
html[data-organizations] .ws-meta{padding-left:0;margin-top:0}
|
||||
html[data-organizations] .ws-orghead .ws-right{margin-left:0}
|
||||
html[data-organizations] .ws-busctl,html[data-organizations] .ws-busctl .bus-restart{align-items:flex-start}
|
||||
@@ -704,9 +797,6 @@ html[data-organizations] #copy-status:empty{display:none}
|
||||
html[data-organizations] .ws-levels>.span{grid-column:auto}
|
||||
html[data-organizations] .ws-levels>.last.lh{border-bottom:1px solid color-mix(in srgb,var(--line) 60%,transparent)}
|
||||
html[data-organizations] .ws-levels .mlabel{display:flex}
|
||||
html[data-organizations] .ws-g5{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-g5.keep2{grid-template-columns:repeat(2,minmax(0,1fr))}
|
||||
html[data-organizations] .ws-g5.keep2>:last-child:nth-child(odd){grid-column:1/-1}
|
||||
html[data-organizations] .ws-orgcards{grid-template-columns:minmax(0,1fr)}
|
||||
html[data-organizations] .ws-srow{grid-template-columns:92px 20px minmax(0,1fr)}
|
||||
html[data-organizations] .ws-srow .ws-by{grid-column:1/-1}
|
||||
@@ -720,3 +810,54 @@ html[data-organizations] #copy-status:empty{display:none}
|
||||
html[data-organizations] .ws-av.mob{display:inline-grid;margin-right:6px;vertical-align:-3px}
|
||||
html[data-organizations] .ws-tbl .t2.mono.hide-m{display:none}
|
||||
}
|
||||
/* #1873 triage-drawer: the owner's Triage drawer, in the agent drawer family. It sits above an open
|
||||
agent drawer, keeps its own header and message box in view, and scrolls the conversation alone. */
|
||||
#triage-drawer{position:fixed;top:var(--bar-h,52px);right:0;bottom:0;width:min(440px,100vw);z-index:41;display:flex;flex-direction:column;overflow:hidden;background:var(--surface);color:var(--text);border-left:1px solid var(--line);box-shadow:-8px 0 24px color-mix(in srgb,#000 14%,transparent)}
|
||||
#triage-drawer[hidden]{display:none}
|
||||
#triage-drawer .hd{display:flex;align-items:center;gap:8px;padding:12px 14px 12px 17px;border-bottom:1px solid var(--line);flex:none;box-shadow:inset 4px 0 0 var(--action)}
|
||||
#triage-drawer h2{margin:0;font-size:18px;font-weight:800;color:var(--strong)}
|
||||
#triage-drawer h2:focus{outline:none}
|
||||
#triage-drawer .x{margin-left:auto;flex:none;width:32px;height:32px;border:1px solid var(--line);border-radius:6px;background:var(--canvas);color:var(--strong);font-size:20px;line-height:1;cursor:pointer}
|
||||
#triage-drawer .triage-state{margin:0;padding:10px 14px;flex:none;font-size:14px;font-weight:600;color:var(--strong);border-bottom:1px solid var(--line);overflow-wrap:anywhere}
|
||||
#triage-drawer .triage-state[data-kind=off],#triage-drawer .triage-state[data-kind=cap]{color:var(--warning);background:color-mix(in srgb,var(--warning) 9%,var(--surface))}
|
||||
#triage-drawer .triage-state[data-kind=running]::before{content:"";display:inline-block;width:8px;height:8px;margin-right:7px;border-radius:50%;background:var(--success);vertical-align:1px}
|
||||
#triage-drawer .triage-health-sec{flex:none;padding:8px 14px;border-bottom:1px solid var(--line)}
|
||||
#triage-drawer .triage-health-sec summary{cursor:pointer;font:700 11px/1.6 var(--font);letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
|
||||
#triage-drawer .triage-health{list-style:none;margin:6px 0 0;padding:0;display:grid;gap:3px;max-height:24vh;overflow:auto;font-size:12.5px;color:var(--strong)}
|
||||
#triage-drawer .triage-health li{overflow-wrap:anywhere;padding-left:12px;position:relative}
|
||||
#triage-drawer .triage-health li::before{content:"";position:absolute;left:0;top:.5em;width:6px;height:6px;border-radius:50%;background:var(--line)}
|
||||
#triage-drawer .triage-health li.not-read{color:var(--muted)}
|
||||
#triage-drawer .triage-convo-title{margin:0;padding:10px 14px 4px;flex:none;font:700 11px/1.3 var(--font);letter-spacing:.06em;text-transform:uppercase;color:var(--muted)}
|
||||
#triage-drawer .triage-transcript{list-style:none;margin:0;padding:4px 14px 12px;flex:1 1 auto;min-height:120px;overflow:auto;overscroll-behavior:contain;display:flex;flex-direction:column;gap:8px}
|
||||
#triage-drawer .triage-transcript:focus-visible{outline:2px solid var(--action);outline-offset:-2px}
|
||||
#triage-drawer .triage-msg{border:1px solid var(--line);border-radius:8px;padding:8px 10px;background:var(--canvas);font-size:13.5px;overflow-wrap:anywhere}
|
||||
#triage-drawer .triage-msg.from-owner{background:color-mix(in srgb,var(--action) 8%,var(--surface));border-color:color-mix(in srgb,var(--action) 30%,var(--line))}
|
||||
#triage-drawer .triage-msg.from-host,#triage-drawer .triage-msg.from-other{background:transparent;border-style:dashed;color:var(--muted)}
|
||||
#triage-drawer .triage-msg-head{display:flex;gap:8px;align-items:baseline;margin-bottom:3px}
|
||||
#triage-drawer .triage-msg-head strong{color:var(--strong);font-size:13px}
|
||||
#triage-drawer .triage-when{font-size:11.5px;color:var(--muted)}
|
||||
#triage-drawer .triage-reply{margin:0 0 4px;padding-left:8px;border-left:3px solid var(--line);font-size:12.5px;color:var(--muted)}
|
||||
#triage-drawer .triage-text-body{margin:0;white-space:pre-wrap;color:var(--strong)}
|
||||
#triage-drawer .from-host .triage-text-body,#triage-drawer .from-other .triage-text-body{color:inherit}
|
||||
#triage-drawer .triage-cards{list-style:none;margin:8px 0 0;padding:0;display:grid;gap:6px}
|
||||
#triage-drawer .triage-card{display:grid;gap:4px;border:1px solid var(--line);border-radius:6px;padding:6px 8px;background:var(--surface)}
|
||||
#triage-drawer .triage-card-meta{font-size:12px;color:var(--muted)}
|
||||
#triage-drawer .triage-card-cmd{display:block;font:12px/1.5 var(--mono);color:var(--strong);white-space:pre-wrap;overflow-wrap:anywhere;user-select:all}
|
||||
#triage-drawer .triage-dropped{margin:6px 0 0;font-size:12px;color:var(--warning)}
|
||||
#triage-drawer .triage-empty{color:var(--muted);font-size:13px}
|
||||
#triage-drawer .triage-compose{flex:none;display:grid;gap:6px;padding:10px 14px 14px;border-top:1px solid var(--line);background:var(--surface)}
|
||||
#triage-drawer .triage-label{font-size:12px;font-weight:700;color:var(--muted)}
|
||||
#triage-drawer .triage-text{width:100%;box-sizing:border-box;min-height:64px;max-height:30vh;resize:vertical;padding:8px 10px;border:1px solid var(--line);border-radius:6px;background:var(--canvas);color:var(--strong);font:14px/1.45 var(--font)}
|
||||
#triage-drawer .triage-text:disabled{opacity:.6;cursor:not-allowed}
|
||||
#triage-drawer .triage-send-row{display:flex;align-items:center;gap:10px}
|
||||
#triage-drawer .triage-send{display:inline-flex;align-items:center;min-height:36px;padding:4px 16px;border:1px solid var(--action);border-radius:var(--r,6px);background:var(--action);color:var(--canvas);font:700 13px/1.4 var(--font);cursor:pointer}
|
||||
#triage-drawer .triage-send:disabled{background:var(--raised);border-color:var(--line);color:var(--muted);cursor:not-allowed}
|
||||
#triage-drawer .triage-hint{font-size:12px;color:var(--muted)}
|
||||
#triage-drawer .note{margin:0;font-size:12.5px;color:var(--warning)}
|
||||
#triage-drawer .note:empty,#triage-drawer .triage-send-status:empty{display:none}
|
||||
#triage-drawer .triage-send-status{margin:0;font-size:13px;color:var(--strong)}
|
||||
#triage-drawer .triage-send-status[data-kind=refused]{color:var(--danger)}
|
||||
#triage-drawer .triage-send-status[data-kind=unknown]{color:var(--warning)}
|
||||
#triage-drawer .triage-send-status[data-kind=ok]{color:var(--success)}
|
||||
@media (min-width:1200px){body:has(#triage-drawer:not([hidden])) .content{padding-right:calc(440px + 22px)}}
|
||||
@media (max-width:700px){#triage-drawer{top:0;left:0;width:auto;border-left:0;box-shadow:none;z-index:60}html:has(#triage-drawer:not([hidden])),body:has(#triage-drawer:not([hidden])){overflow:hidden}#triage-drawer .triage-health{max-height:18vh}}
|
||||
@@ -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;
|
||||
@@ -35,7 +41,13 @@
|
||||
// The layout is remembered per viewer and per width: a phone opens on List until its viewer picks
|
||||
// Kanban, a wide screen on Kanban until its viewer picks List.
|
||||
const layouts = (() => { try { const v = JSON.parse(load(LAYOUT) || '{}'); return v && typeof v === 'object' ? v : {}; } catch { return {}; } })();
|
||||
const filter = { org: '', project: '', assignee: '', state: '', label: '', q: '' };
|
||||
// done: 'week' shows the tasks the Dashboard's Done this week tile counts. It stays in the browser:
|
||||
// the rows already carry done and their last change, the same test the tile's count uses.
|
||||
const filter = { org: '', project: '', assignee: '', state: '', label: '', q: '', done: '' };
|
||||
let addrAssignee = '';
|
||||
const WEEK_MS = 7 * 24 * 3600 * 1000;
|
||||
const doneThisWeek = t => t.done && t.changedAt && Date.now() - Date.parse(t.changedAt) <= WEEK_MS;
|
||||
const DONE_NOTE = 'Done this week counts done tasks by their last change; the bus records no time a task was done.';
|
||||
// The board style in force: the filtered project's when it has one, else the one organization's the
|
||||
// view is narrowed to (by the org chip or by a project of that org), else none.
|
||||
function activeBoard() {
|
||||
@@ -56,6 +68,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 +86,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 +101,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 +115,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 +123,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 ----------
|
||||
@@ -126,6 +173,7 @@
|
||||
&& (!filter.assignee || (filter.assignee === '-' ? !t.assignees.length : t.assignees.includes(filter.assignee)))
|
||||
&& (!filter.state || stateOf(t) === filter.state)
|
||||
&& (!filter.label || t.labels.map(String).includes(filter.label))
|
||||
&& (!filter.done || doneThisWeek(t))
|
||||
&& (!q || !needle || `${t.title ?? ''} ${shortId(t.ref)} ${projectName(t) ?? ''}`.toLowerCase().includes(needle)));
|
||||
}
|
||||
const select = (name, label, options, focus) => `<label class="tb-sel"><span class="ws-label">${esc(label)}</span><select data-tb-filter="${name}" data-focus-key="${focus}">${options}</select></label>`;
|
||||
@@ -137,17 +185,18 @@
|
||||
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>`}
|
||||
${filter.done ? '<button type="button" class="tb-f plain" data-tb-done aria-pressed="true" aria-label="Clear Done this week: done tasks last changed in the past 7 days" data-focus-key="tb-done">Done this week <span aria-hidden="true">×</span></button>' : ''}
|
||||
${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 +207,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 +236,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 +250,15 @@
|
||||
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;
|
||||
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>` : '';
|
||||
// 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 note = filter.done ? ` ${DONE_NOTE}` : '';
|
||||
const line = onServer ? `<p class="tb-count">Showing ${n} ${n === 1 ? 'task that matches' : 'tasks that match'} the filters.${note}</p>`
|
||||
: n !== all ? `<p class="tb-count">Showing ${n} of ${all} tasks.${note}</p>` : note ? `<p class="tb-count">${note.trim()}</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 +284,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 +336,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 +345,44 @@
|
||||
}
|
||||
|
||||
// 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 : '';
|
||||
filter.done = q.get('done') === 'week' ? 'week' : '';
|
||||
// SP12: `assignee` in the address (the agent drawer's link) sets the Assignee filter once per new
|
||||
// value; the select changes it after that, and a poll does not put the address's value back.
|
||||
const who = String(q.get('assignee') || '');
|
||||
// When the address drops it, the filter it set goes too, unless the select has changed it since.
|
||||
if (who !== addrAssignee) { const was = addrAssignee; addrAssignee = who; if (ROLE.test(who)) filter.assignee = who; else if (!who && was && filter.assignee === was) filter.assignee = ''; }
|
||||
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 +423,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 +460,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 +478,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 +590,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,10 +600,14 @@
|
||||
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;
|
||||
}
|
||||
if (e.target.closest('[data-tb-done]')) { filter.done = ''; paint(); ws()?.setQuery?.({ done: null }, true); return; }
|
||||
const open = e.target.closest('[data-tb-open]');
|
||||
if (open) { const t = find(open.dataset.tbOpen); if (t) openDialog(editForm(t), open.dataset.focusKey, t); return; }
|
||||
const add = e.target.closest('[data-tb-new]');
|
||||
@@ -500,6 +622,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);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
/* SP9 (#1873): the read-only workflow pages (#/orgs/<id>/workflows[/<name>]) and the organization
|
||||
page's Workflows card. Colours come from the theme tokens, so light and dark both follow the theme. */
|
||||
.wfg{min-width:0}
|
||||
.wfg h2{font-size:15px;margin:22px 0 8px}
|
||||
.wfg-scope:first-of-type h2{margin-top:6px}
|
||||
.wfg-list{list-style:none;margin:0;padding:0;background:var(--surface);border:1px solid var(--line);border-radius:10px}
|
||||
.wfg-item{padding:12px 14px;border-top:1px solid var(--line-soft,var(--line));overflow-wrap:anywhere}
|
||||
.wfg-item:first-child{border-top:0}
|
||||
.wfg-item-h{display:flex;flex-wrap:wrap;align-items:baseline;gap:4px 10px}
|
||||
.wfg-item-h a{font-weight:600;color:var(--action,var(--accent));text-decoration:none}
|
||||
.wfg-item-h a:hover{text-decoration:underline}
|
||||
.wfg-desc{margin:4px 0 0;color:var(--muted);font-size:13.5px}
|
||||
.wfg-chain{list-style:none;display:flex;flex-wrap:wrap;gap:4px 0;margin:8px 0 0;padding:0;font-size:13px;color:var(--text)}
|
||||
.wfg-chain li{display:inline-flex;align-items:center}
|
||||
.wfg-chain li+li::before{content:"\2192";color:var(--muted);padding:0 8px}
|
||||
:is(.wfg,.wfg-card) a:focus-visible{outline:2px solid var(--focus);outline-offset:2px;border-radius:4px}
|
||||
|
||||
/* The graph scrolls inside its own frame when it is wider than the frame; the page never does. */
|
||||
.wfg-frame{max-width:100%;overflow-x:auto;background:var(--surface);border:1px solid var(--line);border-radius:10px;padding:8px}
|
||||
.wfg-graph{display:block}
|
||||
.wfg-graph.is-vertical{width:100%;max-width:340px;height:auto;margin:0 auto}
|
||||
.wfg-node{cursor:pointer;text-decoration:none}
|
||||
.wfg-node rect{fill:var(--canvas);stroke:var(--line);stroke-width:1.5}
|
||||
.wfg-node:hover rect{stroke:var(--muted)}
|
||||
.wfg-node.is-sel rect{stroke:var(--accent);stroke-width:2.5;fill:var(--raised)}
|
||||
.wfg-node:focus{outline:none}
|
||||
.wfg-node:focus-visible rect{stroke:var(--focus);stroke-width:3}
|
||||
.wfg-node text{font-family:var(--font);fill:var(--text)}
|
||||
.wfg-meta{font-size:12px;fill:var(--muted)!important;letter-spacing:.02em}
|
||||
.wfg-title{font-size:15px;font-weight:600;fill:var(--strong,var(--text))!important}
|
||||
.wfg-roles{font-size:13px;font-family:var(--mono)!important;fill:var(--text)}
|
||||
.wfg-miss{font-size:12px;fill:var(--danger)!important}
|
||||
.wfg-node .wfg-none{fill:var(--muted);font-family:var(--font)}
|
||||
.wfg-edge{fill:none;stroke:var(--muted);stroke-width:1.5}
|
||||
.wfg-arrow{fill:var(--muted)}
|
||||
|
||||
.wfg-detail{margin-top:16px;overflow-wrap:anywhere}
|
||||
.wfg-detail h2{margin:0 0 10px}
|
||||
.wfg-dl{display:grid;grid-template-columns:max-content minmax(0,1fr);align-items:baseline;gap:8px 16px;margin:0 0 12px}
|
||||
.wfg-dl dt{color:var(--muted);font-size:13px}
|
||||
.wfg-dl dd{margin:0}
|
||||
@media (max-width:700px){
|
||||
.wfg-dl{grid-template-columns:minmax(0,1fr);gap:2px}
|
||||
.wfg-dl dd{margin-bottom:8px}
|
||||
}
|
||||
|
||||
/* The organization page's card, above Settings in the right column. */
|
||||
.wfg-card>.ws-sec-h{margin-top:0}
|
||||
.wfg-card+.ws-sec-h{margin-top:22px}
|
||||
.wfg-cardlist{list-style:none;margin:0}
|
||||
.wfg-cardlist li+li{border-top:1px solid var(--line-soft,var(--line))}
|
||||
.wfg-cardlist a{display:block;padding:8px 0;color:var(--text);text-decoration:none;overflow-wrap:anywhere}
|
||||
.wfg-cardlist a:hover strong{text-decoration:underline}
|
||||
.wfg-cardlist strong{color:var(--action,var(--accent))}
|
||||
/* SP17: each step of a workflow as a link to its form, under the workflow's link. */
|
||||
.wfg-cardlist .wfg-card-steps{list-style:none;display:flex;flex-wrap:wrap;gap:2px 0;margin:-4px 0 0;padding:0 0 8px;font-size:13px}
|
||||
.wfg-cardlist .wfg-card-steps li{display:inline-flex;align-items:center;border:0}
|
||||
.wfg-cardlist .wfg-card-steps li+li::before{content:"\2192";color:var(--muted);padding:0 6px}
|
||||
.wfg-cardlist .wfg-card-steps a{display:inline-block;padding:4px 0;color:var(--action,var(--accent));text-decoration:underline;text-decoration-color:color-mix(in srgb,currentColor 40%,transparent);text-underline-offset:2px}
|
||||
.wfg-cardlist .wfg-card-steps a:hover{text-decoration-color:currentColor}
|
||||
.wfg-card [data-wfg-none]{margin:0 0 8px}
|
||||
.wfg-card p:last-child{margin-bottom:0}
|
||||
|
||||
/* SP10 (#1873): editing a workflow in its graph. The bar above the graph holds Unsaved, Discard and Delete
|
||||
workflow; the step panel holds the step's form with Save (SP17) and the step actions; the list page holds
|
||||
New workflow. */
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-step-acts,.wfg-form,.wfg-new) .ws-btn{min-height:32px}
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-form) .ws-btn.primary{background:var(--action);color:var(--onAction);border-color:var(--action)}
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-form) .ws-btn.primary:hover:not(:disabled){background:color-mix(in srgb,var(--action) 88%,var(--strong))}
|
||||
/* SP17 shots: a Save with nothing to save reads as off, not as the action colour. */
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-form) .ws-btn.primary:disabled{background:var(--raised);color:var(--muted);border-color:var(--line)}
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-step-acts) .ws-btn.danger{color:var(--danger)}
|
||||
html[data-organizations] :is(.wfg-bar,.wfg-step-acts,.wfg-form,.wfg-new) .ws-btn:focus-visible{outline:2px solid var(--focus);outline-offset:2px}
|
||||
.wfg-bar{display:flex;flex-wrap:wrap;align-items:center;gap:8px 12px;margin:0 0 10px}
|
||||
.wfg-acts{display:inline-flex;flex-wrap:wrap;align-items:center;gap:8px;margin-left:auto}
|
||||
.wfg-bar:not(.is-dirty) .wfg-acts:empty{display:none}
|
||||
.wfg-badge{display:inline-block;padding:2px 8px;border-radius:999px;font-size:12px;font-weight:600;color:var(--strong,var(--text));background:color-mix(in srgb,var(--accent) 18%,var(--surface));border:1px solid color-mix(in srgb,var(--accent) 45%,var(--line))}
|
||||
.wfg-confirm{display:inline-flex;flex-wrap:wrap;align-items:center;gap:8px;font-size:13.5px}
|
||||
.wfg-status,.wfg-stale{flex-basis:100%;margin:0;font-size:13.5px;overflow-wrap:anywhere}
|
||||
.wfg-stale{color:var(--danger)}
|
||||
.wfg-ro{margin:0 0 10px}
|
||||
.wfg-step-acts{display:flex;flex-wrap:wrap;gap:8px;margin:0 0 12px}
|
||||
.wfg-form{display:grid;gap:10px;min-width:0}
|
||||
.wfg-form h2{margin:0}
|
||||
.wfg-form h3{font-size:14px;margin:6px 0 0}
|
||||
.wfg-form>label,.wfg-form label:has(>select){display:grid;gap:4px;font-size:13px;color:var(--muted)}
|
||||
.wfg-form [hidden]{display:none!important}
|
||||
.wfg-form textarea{font:14px/1.4 var(--font);color:var(--text);background:var(--canvas);border:1px solid var(--line);border-radius:6px;padding:6px 8px;min-width:0;max-width:100%;resize:vertical}
|
||||
.wfg-form>label:has(>textarea){display:grid;gap:4px;font-size:13px;color:var(--muted)}
|
||||
.wfg-form textarea:focus-visible{outline:2px solid var(--focus);outline-offset:1px}
|
||||
.wfg-stepform,.wfg-metaform{margin:0 0 14px}
|
||||
.wfg-form input:not([type=checkbox]),.wfg-form select{font:14px/1.4 var(--font);color:var(--text);background:var(--canvas);border:1px solid var(--line);border-radius:6px;padding:6px 8px;min-width:0;max-width:100%}
|
||||
.wfg-form :is(input,select):focus-visible{outline:2px solid var(--focus);outline-offset:1px}
|
||||
.wfg-form .note{margin:0}
|
||||
.wfg-roles-pick{border:1px solid var(--line);border-radius:8px;padding:8px 12px 10px;margin:0;min-width:0;display:grid;grid-template-columns:repeat(auto-fill,minmax(180px,1fr));gap:4px 12px}
|
||||
.wfg-roles-pick legend{font-size:13px;color:var(--muted);padding:0 4px}
|
||||
.wfg-pick-h{grid-column:1/-1;margin:6px 0 0;font-size:12px;color:var(--muted)}
|
||||
.wfg-pick{display:flex;align-items:baseline;gap:6px;font-size:13.5px;color:var(--text);overflow-wrap:anywhere;min-width:0}
|
||||
.wfg-pick input{margin:0;flex:none}
|
||||
.wfg-why{margin:0;color:var(--danger);font-size:13.5px}
|
||||
.wfg-why:empty{display:none}
|
||||
.wfg-form-acts{display:flex;flex-wrap:wrap;gap:8px;margin:0}
|
||||
.wfg-new{margin:0 0 12px}
|
||||
.wfg-newform{margin:0 0 16px}
|
||||
@media (max-width:700px){
|
||||
.wfg-acts{margin-left:0}
|
||||
.wfg-roles-pick{grid-template-columns:minmax(0,1fr)}
|
||||
}
|
||||
@@ -1,9 +1,11 @@
|
||||
// Starter packs SP6 (#1873, design section 8): the owner's workflow list and editor on an
|
||||
// organization's page. GET /api/orgs/<id>/workflows reads the org's and each code project's workflows
|
||||
// with the file revision; a save is POST .../workflows/<name> {revision, workflow, project?} and a delete
|
||||
// DELETE .../workflows/<name> {revision, project?} (workflow.set.console). The bus checks the shape; this
|
||||
// page marks a step role that resolves to no org definition or role template (and is not `human`) as
|
||||
// naming no current role. Every organization-supplied string goes through esc.
|
||||
// Starter packs SP6 (#1873, design section 8): an organization's workflows. GET /api/orgs/<id>/workflows reads
|
||||
// the org's and each code project's workflows with the file revision; a save is POST .../workflows/<name>
|
||||
// {revision, workflow, project?} and a delete DELETE .../workflows/<name> {revision, project?}
|
||||
// (workflow.set.console). The bus checks the shape; this page marks a step role that resolves to no org
|
||||
// definition or role template (and is not `human`) as naming no current role. Every organization-supplied
|
||||
// string goes through esc.
|
||||
// SP17: the graph page is the one editor. The organization page's old form editor is gone; its card links to
|
||||
// each workflow and each step, and a step's panel is its edit form with Save.
|
||||
(() => {
|
||||
'use strict';
|
||||
const esc = x => String(x ?? '').replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
||||
@@ -33,154 +35,795 @@
|
||||
const r = await fetch(url, method === 'GET' ? { cache: 'no-store' } : { method, headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) });
|
||||
let value = null;
|
||||
try { value = await r.json(); } catch { value = null; }
|
||||
if (!r.ok) throw Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`);
|
||||
// The refusal code rides on the error, so a caller with its own words for one (the graph editor) can use them.
|
||||
if (!r.ok) throw Object.assign(Error(guidance[value?.error] ?? `The bus refused: ${value?.error ?? 'outcome unknown'}.`), { code: value?.error ?? null });
|
||||
return value;
|
||||
}
|
||||
const plain = v => v !== null && typeof v === 'object' && !Array.isArray(v);
|
||||
// #1873: the templates no organization may hold (organization vocabulary SYSTEM_ONLY). The server leaves
|
||||
// them out of the read; this filter stays so a step role never resolves to one and the picker never offers one.
|
||||
const SYSTEM_ONLY = ['triage'];
|
||||
const offered = list => (list || []).filter(r => !SYSTEM_ONLY.includes(r));
|
||||
async function read(org, s) {
|
||||
const value = await call(`${base(org)}/workflows`, 'GET');
|
||||
if (!plain(value) || !plain(value.workflows) || !plain(value.projects) || !plain(value.roles) || typeof value.revision !== 'string') throw Error('The workflow read returned an unexpected answer.');
|
||||
s.data = value;
|
||||
s.known = new Set([...(value.roles.definitions || []), ...(value.roles.templates || []), 'human']);
|
||||
s.known = new Set([...(value.roles.definitions || []), ...offered(value.roles.templates), 'human']);
|
||||
}
|
||||
// SP17: a write in flight holds the poll. Each organization counts its writes (epoch moves when one starts
|
||||
// and when it ends); a read that began before a write ended, or answers while one is in flight, is dropped
|
||||
// and the page keeps what it has, which the write's answer brings up to date (written()).
|
||||
const writes = new Map();
|
||||
const writeState = org => { if (!writes.has(org)) writes.set(org, { epoch: 0, inflight: 0 }); return writes.get(org); };
|
||||
async function writing(org, fn) {
|
||||
const w = writeState(org);
|
||||
w.epoch++; w.inflight++;
|
||||
try { return await fn(); } finally { w.inflight--; w.epoch++; }
|
||||
}
|
||||
async function load(org) {
|
||||
const s = { data: null, known: new Set(), error: null, editing: null, confirm: null, status: '' };
|
||||
try { await read(org, s); } catch (error) { s.error = error.message; }
|
||||
const prev = states.get(org), w = writeState(org), began = w.epoch;
|
||||
const s = { data: null, known: new Set(), error: null };
|
||||
const raced = () => !!prev?.data && (w.inflight > 0 || w.epoch !== began);
|
||||
try { await read(org, s); if (raced()) return; } catch (error) {
|
||||
if (raced()) return;
|
||||
// Review P3: a failed poll while a change to this organization's workflows is held keeps the last good
|
||||
// read, so the page still draws the change and its form, and graftLive puts the held form and focus back.
|
||||
// SP17: the failure is still said; the page draws the last read under that line.
|
||||
if (prev?.data && held(org).length) Object.assign(s, { data: prev.data, known: prev.known, readError: error.message });
|
||||
else s.error = error.message;
|
||||
}
|
||||
states.set(org, s);
|
||||
}
|
||||
const scopes = s => [['', 'Organization', s.data.workflows], ...Object.keys(s.data.projects).sort().map(p => [p, `Project ${p}`, s.data.projects[p]])];
|
||||
const roleChip = (s, role) => s.known.has(role)
|
||||
? `<code>${esc(role)}</code>`
|
||||
: `<code>${esc(role)}</code> <span class="wf-missing" data-wf-missing>${MISSING}</span>`;
|
||||
function stepItem(s, step) {
|
||||
const roles = Array.isArray(step?.roles) ? step.roles : [];
|
||||
return `<li data-wf-step><span>${esc(step?.title)}</span> <span class="muted">${esc(STATE_LABEL[step?.state] ?? step?.state)}</span> <span class="wf-roles">${roles.map(r => roleChip(s, r)).join(', ')}</span></li>`;
|
||||
}
|
||||
function workflowItem(org, s, scope, name, w) {
|
||||
const steps = Array.isArray(w?.steps) ? w.steps : [];
|
||||
const confirm = s.confirm && s.confirm.scope === scope && s.confirm.name === name;
|
||||
const actions = !s.data.writable ? '' : confirm
|
||||
? `<p>Delete this workflow? <button class="btn" type="button" data-wf-delete-yes>Delete</button> <button class="btn" type="button" data-wf-delete-no>Keep</button></p>`
|
||||
: `<p><button class="btn" type="button" data-wf-edit>Edit</button> <button class="btn" type="button" data-wf-delete>Delete</button></p>`;
|
||||
return `<li class="wf-item" data-wf="${esc(name)}" data-wf-scope="${esc(scope)}"><strong data-wf-title>${esc(w?.title || name)}</strong> <span class="muted"><code>${esc(name)}</code></span>
|
||||
${w?.description ? `<p>${esc(w.description)}</p>` : ''}<ol class="wf-steps">${steps.map(st => stepItem(s, st)).join('')}</ol>${actions}</li>`;
|
||||
}
|
||||
function stepRow(s, step, i) {
|
||||
const roles = step.roles.split(',').map(r => r.trim()).filter(Boolean);
|
||||
const missing = roles.filter(r => !s.known.has(r));
|
||||
return `<fieldset class="wf-step" data-wf-edit-step="${i}"><legend>Step ${i + 1}</legend>
|
||||
<label>Title<input name="title" maxlength="120" value="${esc(step.title)}" autocomplete="off"></label>
|
||||
<label>State<select name="state">${STATES.map(([v, l]) => `<option value="${v}"${step.state === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>
|
||||
<label>Roles, separated by commas<input name="roles" value="${esc(step.roles)}" autocomplete="off"></label>
|
||||
<p class="wf-note" data-wf-step-missing>${missing.length ? `${missing.map(r => `<code>${esc(r)}</code>`).join(', ')} ${MISSING}` : ''}</p>
|
||||
<button class="btn" type="button" data-wf-step-remove>Remove step</button></fieldset>`;
|
||||
}
|
||||
function editor(s) {
|
||||
const e = s.editing;
|
||||
if (!e) return '';
|
||||
const scopeField = e.isNew
|
||||
? `<label>Where<select name="scope">${scopes(s).map(([v, l]) => `<option value="${esc(v)}"${e.scope === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label><label>Name<input name="name" maxlength="64" value="${esc(e.name)}" autocomplete="off" placeholder="lowercase letters, digits, dashes"></label>`
|
||||
: `<p>${e.scope ? `Project ${esc(e.scope)}` : 'Organization'}, <code>${esc(e.name)}</code></p>`;
|
||||
return `<form class="wf-editor" data-wf-editor><h4>${e.isNew ? 'New workflow' : 'Edit workflow'}</h4>${scopeField}
|
||||
<label>Title<input name="title" maxlength="120" value="${esc(e.draft.title)}" autocomplete="off"></label>
|
||||
<label>Description<textarea name="description" maxlength="1000" rows="2">${esc(e.draft.description)}</textarea></label>
|
||||
${e.draft.steps.map((st, i) => stepRow(s, st, i)).join('')}
|
||||
<p><button class="btn" type="button" data-wf-step-add>Add step</button> <button class="btn" type="submit">Save workflow</button> <button class="btn" type="button" data-wf-cancel>Cancel</button></p>
|
||||
<p class="note">Roles name an organization role, a role template, or <code>human</code>.</p></form>`;
|
||||
}
|
||||
function section(org) {
|
||||
const s = states.get(org);
|
||||
if (!s || s.error) return `<section class="panel" data-workflows data-workflows-org="${esc(org)}"><h3>Workflows</h3><p>${esc(s?.error ?? 'Workflows could not be read.')}</p></section>`;
|
||||
const lists = scopes(s).map(([scope, label, flows]) => {
|
||||
const names = Object.keys(flows || {}).sort();
|
||||
return `<div class="wf-scope" data-wf-scope-list="${esc(scope)}"><h4>${esc(label)}</h4>${names.length ? `<ul class="wf-list">${names.map(n => workflowItem(org, s, scope, n, flows[n])).join('')}</ul>` : '<p class="note">No workflows.</p>'}</div>`;
|
||||
}).join('');
|
||||
const add = s.data.writable ? (s.editing ? '' : '<p><button class="btn" type="button" data-wf-new>New workflow</button></p>') : '<p class="note">Only the owner, on a Console started with send, can change workflows.</p>';
|
||||
return `<section class="panel" data-workflows data-workflows-org="${esc(org)}"><h3>Workflows</h3><p>A workflow lists the steps a task goes through, the state each step puts it in and the roles that do it.</p>${lists}${add}${editor(s)}<p role="status" data-workflows-status>${esc(s.status)}</p></section>`;
|
||||
}
|
||||
function redraw(org) {
|
||||
const el = [...document.querySelectorAll('[data-workflows-org]')].find(n => n.dataset.workflowsOrg === org);
|
||||
if (el) el.outerHTML = section(org);
|
||||
}
|
||||
// The editor's current values back into the draft, so adding or removing a step keeps what was typed.
|
||||
function capture(root, s) {
|
||||
const form = root.querySelector('[data-wf-editor]');
|
||||
if (!form || !s.editing) return;
|
||||
const e = s.editing;
|
||||
if (e.isNew) { e.scope = form.elements.scope?.value ?? e.scope; e.name = form.elements.name?.value ?? e.name; }
|
||||
e.draft.title = form.querySelector(':scope > label > input[name="title"]').value;
|
||||
e.draft.description = form.elements.description.value;
|
||||
e.draft.steps = [...form.querySelectorAll('[data-wf-edit-step]')].map(f => ({ title: f.querySelector('[name="title"]').value, state: f.querySelector('[name="state"]').value, roles: f.querySelector('[name="roles"]').value }));
|
||||
}
|
||||
const flowsIn = (s, scope) => scope ? s.data.projects[scope] : s.data.workflows;
|
||||
const target = (s, scope) => scope ? { project: scope } : {};
|
||||
async function reload(org, s, status) {
|
||||
try { await read(org, s); s.status = status; } catch (error) { s.status = `${status} ${error.message}`; }
|
||||
// SP10: the save check. A step is {title, state, roles: [names]}. The order of the checks: the name, a name
|
||||
// the scope already holds, a role that names no current role, then the shape the bus checks
|
||||
// (organization-config checkWorkflows: 1 to 20 steps, each with a title and 1 to 8 distinct roles), named
|
||||
// here before the bus refuses it in general words.
|
||||
function stepRefusal(st, n) {
|
||||
if (!String(st.title ?? '').trim()) return `Step ${n} needs a title.`;
|
||||
if (!st.roles.length) return `Step ${n} needs at least one role.`;
|
||||
if (st.roles.length > 8) return `Step ${n} names ${st.roles.length} roles. A step takes at most eight.`;
|
||||
if (new Set(st.roles).size !== st.roles.length) return `Step ${n} names the same role twice.`;
|
||||
return '';
|
||||
}
|
||||
document.addEventListener('click', async ev => {
|
||||
const button = ev.target.closest('[data-wf-new],[data-wf-edit],[data-wf-cancel],[data-wf-step-add],[data-wf-step-remove],[data-wf-delete],[data-wf-delete-yes],[data-wf-delete-no]');
|
||||
if (!button) return;
|
||||
const root = button.closest('[data-workflows-org]'), org = root?.dataset.workflowsOrg, s = states.get(org);
|
||||
if (!s?.data) return;
|
||||
const item = button.closest('[data-wf]'), scope = item?.dataset.wfScope ?? '', name = item?.dataset.wf;
|
||||
if (button.hasAttribute('data-wf-new')) {
|
||||
s.editing = { isNew: true, scope: '', name: '', draft: { title: '', description: '', steps: [{ title: '', state: 'todo', roles: '' }] } };
|
||||
} else if (button.hasAttribute('data-wf-edit')) {
|
||||
const w = flowsIn(s, scope)?.[name];
|
||||
s.editing = { isNew: false, scope, name, draft: { title: w?.title ?? '', description: w?.description ?? '', steps: (w?.steps ?? []).map(st => ({ title: st.title ?? '', state: st.state ?? 'todo', roles: (st.roles ?? []).join(', ') })) } };
|
||||
} else if (button.hasAttribute('data-wf-cancel')) {
|
||||
s.editing = null;
|
||||
} else if (button.hasAttribute('data-wf-step-add')) {
|
||||
capture(root, s); s.editing.draft.steps.push({ title: '', state: 'todo', roles: '' });
|
||||
} else if (button.hasAttribute('data-wf-step-remove')) {
|
||||
capture(root, s); s.editing.draft.steps.splice(Number(button.closest('[data-wf-edit-step]').dataset.wfEditStep), 1);
|
||||
} else if (button.hasAttribute('data-wf-delete')) {
|
||||
s.confirm = { scope, name };
|
||||
} else if (button.hasAttribute('data-wf-delete-no')) {
|
||||
s.confirm = null;
|
||||
} else if (button.hasAttribute('data-wf-delete-yes')) {
|
||||
button.disabled = true;
|
||||
try {
|
||||
await call(`${base(org)}/workflows/${encodeURIComponent(name)}`, 'DELETE', { revision: s.data.revision, ...target(s, scope) });
|
||||
s.confirm = null;
|
||||
await reload(org, s, `Deleted ${name}.`);
|
||||
} catch (error) { s.status = error.message; }
|
||||
}
|
||||
redraw(org);
|
||||
});
|
||||
document.addEventListener('input', ev => {
|
||||
const field = ev.target.closest('[data-wf-edit-step] [name="roles"]');
|
||||
if (!field) return;
|
||||
const s = states.get(field.closest('[data-workflows-org]')?.dataset.workflowsOrg);
|
||||
if (!s) return;
|
||||
const missing = field.value.split(',').map(r => r.trim()).filter(r => r && !s.known.has(r));
|
||||
// textContent and created nodes only: a typed name never becomes markup.
|
||||
const note = field.closest('[data-wf-edit-step]').querySelector('[data-wf-step-missing]');
|
||||
note.textContent = missing.length ? `${missing.join(', ')} ${MISSING}` : '';
|
||||
});
|
||||
document.addEventListener('submit', async ev => {
|
||||
if (!ev.target.matches('[data-wf-editor]')) return;
|
||||
ev.preventDefault();
|
||||
const root = ev.target.closest('[data-workflows-org]'), org = root?.dataset.workflowsOrg, s = states.get(org);
|
||||
if (!s?.editing) return;
|
||||
capture(root, s);
|
||||
const e = s.editing;
|
||||
if (!NAME.test(e.name)) { s.status = NAME_RULE; redraw(org); return; }
|
||||
function refusal(s, { isNew, scope, name, steps }) {
|
||||
if (!NAME.test(name)) return NAME_RULE;
|
||||
// A save is a set: a new workflow under a name the scope already holds would replace it without a word.
|
||||
if (e.isNew && Object.hasOwn(flowsIn(s, e.scope) ?? {}, e.name)) { s.status = `A workflow named ${e.name} already exists here. Edit it instead.`; redraw(org); return; }
|
||||
const workflow = {
|
||||
...(e.draft.title.trim() ? { title: e.draft.title.trim() } : {}),
|
||||
...(e.draft.description.trim() ? { description: e.draft.description.trim() } : {}),
|
||||
steps: e.draft.steps.map(st => ({ title: st.title.trim(), state: st.state, roles: st.roles.split(',').map(r => r.trim()).filter(Boolean) })),
|
||||
};
|
||||
const button = ev.target.querySelector('button[type="submit"]');
|
||||
button.disabled = true;
|
||||
try {
|
||||
await call(`${base(org)}/workflows/${encodeURIComponent(e.name)}`, 'POST', { revision: s.data.revision, workflow, ...target(s, e.scope) });
|
||||
s.editing = null;
|
||||
await reload(org, s, `Saved ${e.name}.`);
|
||||
} catch (error) { s.status = error.message; }
|
||||
redraw(org);
|
||||
if (isNew && Object.hasOwn(flowsIn(s, scope) ?? {}, name)) return `A workflow named ${name} already exists here. Edit it instead.`;
|
||||
// E2E6 P2-1: a step role that names no current role is named before the bus refuses it generically.
|
||||
const unknown = steps.flatMap((st, i) => st.roles.filter(r => !s.known.has(r)).map(r => [i + 1, r]));
|
||||
if (unknown.length) return `${unknown.map(([i, r]) => `Step ${i}: ${r}`).join('; ')} ${unknown.length === 1 ? 'names' : 'name'} no current role. Use an organization role, a role template or human.`;
|
||||
if (!steps.length) return 'A workflow needs at least one step.';
|
||||
if (steps.length > 20) return 'A workflow has at most 20 steps.';
|
||||
for (const [i, st] of steps.entries()) { const why = stepRefusal(st, i + 1); if (why) return why; }
|
||||
return '';
|
||||
}
|
||||
const shape = ({ title = '', description = '', steps }) => ({
|
||||
...(title.trim() ? { title: title.trim() } : {}),
|
||||
...(description.trim() ? { description: description.trim() } : {}),
|
||||
steps: steps.map(st => ({ title: st.title.trim(), state: st.state, roles: [...st.roles] })),
|
||||
});
|
||||
window.MosaicWorkflows = { load, section };
|
||||
const flowUrl = (org, name) => `${base(org)}/workflows/${encodeURIComponent(name)}`;
|
||||
// The revision is the one the editor opened on: a change made since then is a revision-conflict, not overwritten.
|
||||
const saveFlow = (org, s, { scope, name, revision, workflow }) => call(flowUrl(org, name), 'POST', { revision, workflow, ...target(s, scope) });
|
||||
const removeFlow = (org, s, { scope, name, revision }) => call(flowUrl(org, name), 'DELETE', { revision, ...target(s, scope) });
|
||||
// ---------- SP9 (#1873): the read-only view ----------
|
||||
// #/orgs/<id>/workflows lists the organization's workflows; #/orgs/<id>/workflows/<name>[?project=<p>]
|
||||
// draws one as an inline-SVG graph. The data is the same read as the editor above: each step's title,
|
||||
// state and roles, in file order. A workflow has no edges or branches in the file, so a step hands on to
|
||||
// the next one. Nothing else is drawn: no gate, no inputs and no running mark, because no read gives them.
|
||||
const WS = () => window.MosaicWorkspace;
|
||||
const orgHash = org => `#/orgs/${encodeURIComponent(org)}`;
|
||||
const flowHref = (org, scope, name, step) => {
|
||||
const q = new URLSearchParams();
|
||||
if (scope) q.set('project', scope);
|
||||
if (step) q.set('step', String(step));
|
||||
return `${orgHash(org)}/workflows/${encodeURIComponent(name)}${q.size ? `?${q}` : ''}`;
|
||||
};
|
||||
const stepsOf = w => (Array.isArray(w?.steps) ? w.steps.filter(st => st && typeof st === 'object') : []);
|
||||
const rolesOf = st => (Array.isArray(st?.roles) ? st.roles.filter(r => typeof r === 'string') : []);
|
||||
const count = n => `${n} step${n === 1 ? '' : 's'}`;
|
||||
const stateLabel = st => STATE_LABEL[st?.state] ?? String(st?.state ?? '');
|
||||
const scopeLabel = scope => (scope ? `Project ${scope}` : 'Organization');
|
||||
// Each scope that holds a workflow, the organization first. Names are own keys only.
|
||||
const listed = s => scopes(s).map(([scope, label, flows]) => [scope, label, Object.keys(plain(flows) ? flows : {}).sort().map(n => [n, flows[n]])]);
|
||||
const total = s => listed(s).reduce((n, [, , rows]) => n + rows.length, 0);
|
||||
// The organization's bus state from the membership list, and for one that is down the workspace read's
|
||||
// reason in the Inbox's words (orgsOf + unreadNote, the data-ws-unread note).
|
||||
async function orgOf(org) {
|
||||
const list = await window.MosaicWorkspaceData.organizations().catch(() => null);
|
||||
const row = Array.isArray(list) ? list.find(o => o?.id === org && !o.invalid) : null;
|
||||
if (!row) return { row: null, list: Array.isArray(list) };
|
||||
let unread = '';
|
||||
if (!row.busHealthy) {
|
||||
const body = await window.MosaicWorkspaceData.workspace({ org, sections: 'projects' }).catch(() => null);
|
||||
const o = body ? WS().orgsOf({ orgs: (Array.isArray(body.orgs) ? body.orgs : []).filter(r => r?.org === org) }) : null;
|
||||
unread = o?.unread.length ? WS().unreadNote(o, [], 'workflows')
|
||||
: `<p class="note ws-unread-note" data-ws-unread>Not read: ${esc(row.label || org)} ${row.busStopped ? 'bus stopped' : 'bus not answering'}. No reason was read.</p>`;
|
||||
}
|
||||
return { row, unread, stopped: !row.busHealthy && row.busStopped === true, label: row.label || org };
|
||||
}
|
||||
const head = (title, sub) => `<div class="ws-vh"><h1 tabindex="-1">${title}</h1><p class="sub">${sub}</p></div>`;
|
||||
const applyLink = (org, s) => (s?.data?.writable
|
||||
? `<p><a class="ws-btn" href="${esc(`${orgHash(org)}/organization`)}" data-wfg-apply data-focus-key="wfg-apply">Apply a pack</a></p>`
|
||||
: '<p class="note">A starter pack brings workflows. Only the owner, on a Console started with send, can apply one.</p>');
|
||||
const none = (org, s, label) => `<p class="note" data-wfg-none>No workflows in ${esc(label)} yet.</p>${applyLink(org, s)}`;
|
||||
|
||||
// Layout: left to right on a wide screen, top to bottom on a narrow one. The graph scrolls inside its
|
||||
// own frame when it is wider than the frame; the page never does.
|
||||
const NARROW = '(max-width: 700px)';
|
||||
const narrow = () => window.matchMedia(NARROW).matches;
|
||||
// SP10 (sp9 follow-up): box text is fitted by its measured width in the font it is drawn in, not by a
|
||||
// character count, so a line ends inside its box with an ellipsis and a short name shows whole. The clip
|
||||
// path stays as a backstop. Without a canvas the old per-character estimate is used.
|
||||
let ctx;
|
||||
function measure(text, font, per) {
|
||||
if (ctx === undefined) { try { ctx = document.createElement('canvas').getContext('2d'); } catch { ctx = null; } }
|
||||
if (!ctx) return text.length * per;
|
||||
ctx.font = font;
|
||||
return ctx.measureText(text).width;
|
||||
}
|
||||
const token = (name, fallback) => getComputedStyle(document.documentElement).getPropertyValue(name).trim() || fallback;
|
||||
const fonts = () => ({
|
||||
title: [`600 15px ${token('--font', 'sans-serif')}`, 8.6],
|
||||
roles: [`13px ${token('--mono', 'monospace')}`, 7.9],
|
||||
miss: [`12px ${token('--font', 'sans-serif')}`, 6.8],
|
||||
});
|
||||
function fit(text, [font, per], max) {
|
||||
if (measure(text, font, per) <= max) return text;
|
||||
let lo = 0, hi = text.length;
|
||||
while (lo < hi) { const mid = (lo + hi + 1) >> 1; if (measure(`${text.slice(0, mid)}…`, font, per) <= max) lo = mid; else hi = mid - 1; }
|
||||
return `${text.slice(0, lo)}…`;
|
||||
}
|
||||
// Up to two lines broken at spaces; the second ends in … when the title is longer.
|
||||
function wrap(text, f, max) {
|
||||
const words = String(text ?? '').split(/\s+/).filter(Boolean), lines = [''];
|
||||
let over = false;
|
||||
for (const w of words) {
|
||||
const cur = lines[lines.length - 1], next = cur ? `${cur} ${w}` : w;
|
||||
if (!cur || measure(next, f[0], f[1]) <= max) lines[lines.length - 1] = next;
|
||||
else if (lines.length < 2) lines.push(w);
|
||||
else { lines[1] = `${lines[1]} ${w}`; over = true; }
|
||||
}
|
||||
if (measure(lines[0], f[0], f[1]) > max) return [fit(lines[0], f, max)];
|
||||
if (lines[1] && (over || measure(lines[1], f[0], f[1]) > max)) lines[1] = fit(lines[1], f, max);
|
||||
return lines;
|
||||
}
|
||||
function graph(org, s, scope, name, steps, sel) {
|
||||
const vertical = narrow(), f = fonts();
|
||||
const W = vertical ? 300 : 188, GAP = vertical ? 32 : 36, PAD = 14;
|
||||
// Text runs from x+12 and ends 12px before the box edge; 2px more absorbs a font that loads after the measure.
|
||||
const room = W - 26;
|
||||
// One role a line, at most three lines: with four or more, two roles and "+N more". Every role is in the label and the detail panel.
|
||||
const roleLines = st => { const r = rolesOf(st); return !r.length ? [] : r.length <= 3 ? r : [...r.slice(0, 2), `+${r.length - 2} more`]; };
|
||||
// A role that names no current role: "No current role:" and then each such role on its own line, at most
|
||||
// two lines, so the whole name shows (a name longer than the box ends in …).
|
||||
const missing = st => rolesOf(st).filter(r => !s.known.has(r));
|
||||
const missLines = st => { const m = missing(st); return m.length <= 2 ? m : [m[0], `+${m.length - 1} more`]; };
|
||||
const titleEnd = st => 46 + (wrap(st.title, f.title, room).length - 1) * 19;
|
||||
const rolesY = st => titleEnd(st) + 24;
|
||||
const missY = st => rolesY(st) + (Math.max(roleLines(st).length, 1) - 1) * 17 + 18;
|
||||
// Each box is as tall as the tallest step needs: meta, one or two title lines, its role lines, and the missing-role lines if any.
|
||||
const bottom = st => (missing(st).length ? missY(st) + missLines(st).length * 15 : missY(st) - 18);
|
||||
const H = Math.max(...steps.map(st => bottom(st) + 16));
|
||||
const pos = i => (vertical ? [PAD, PAD + i * (H + GAP)] : [PAD + i * (W + GAP), PAD]);
|
||||
const width = vertical ? W + 2 * PAD : PAD * 2 + steps.length * W + (steps.length - 1) * GAP;
|
||||
const height = vertical ? PAD * 2 + steps.length * H + (steps.length - 1) * GAP : H + 2 * PAD;
|
||||
const edges = steps.slice(1).map((_, i) => {
|
||||
const [x, y] = pos(i), [x2, y2] = pos(i + 1);
|
||||
const d = vertical ? `M${x + W / 2} ${y + H} V${y2 - 3}` : `M${x + W} ${y + H / 2} H${x2 - 3}`;
|
||||
return `<path class="wfg-edge" d="${d}" data-wfg-edge="${i + 1}-${i + 2}" marker-end="url(#wfg-arrow)"/>`;
|
||||
}).join('');
|
||||
const nodes = steps.map((st, i) => {
|
||||
const [x, y] = pos(i), n = i + 1, roles = rolesOf(st), miss = missing(st);
|
||||
const lines = wrap(st.title, f.title, room), on = sel === n;
|
||||
const label = `Step ${n} of ${steps.length}: ${st.title ?? ''}. ${stateLabel(st)}. Roles ${roles.join(', ')}${miss.length ? `; ${miss.join(', ')} ${MISSING}` : ''}.`;
|
||||
const rl = roleLines(st), more = roles.length > 3;
|
||||
const roleText = rl.length
|
||||
? rl.map((r, j) => `<tspan x="${x + 12}" dy="${j ? 17 : 0}"${more && j === rl.length - 1 ? ' data-wfg-more' : ''}>${esc(more && j === rl.length - 1 ? r : fit(r, f.roles, room))}</tspan>`).join('')
|
||||
: '<tspan class="wfg-none">No roles recorded</tspan>';
|
||||
const missText = miss.length
|
||||
? `<text class="wfg-miss" data-wfg-missing x="${x + 12}" y="${y + missY(st)}"><tspan x="${x + 12}" dy="0">No current role:</tspan>${missLines(st).map((r, j) => `<tspan x="${x + 12}" dy="15"${miss.length > 2 && j === 1 ? ' data-wfg-more' : ''}>${esc(miss.length > 2 && j === 1 ? r : fit(r, f.miss, room))}</tspan>`).join('')}</text>`
|
||||
: '';
|
||||
return `<a class="wfg-node${on ? ' is-sel' : ''}" href="${esc(flowHref(org, scope, name, n))}" data-wfg-step="${n}" data-focus-key="${esc(`wfg-step:${n}`)}" aria-label="${esc(label)}"${on ? ' aria-current="step"' : ''}>
|
||||
<title>${esc(`${st.title ?? ''}${roles.length ? ` (${roles.join(', ')})` : ''}`)}</title><rect x="${x}" y="${y}" width="${W}" height="${H}" rx="10"/>
|
||||
<clipPath id="wfg-clip-${n}"><rect x="${x + 2}" y="${y}" width="${W - 10}" height="${H}"/></clipPath>
|
||||
<g clip-path="url(#wfg-clip-${n})">
|
||||
<text class="wfg-meta" x="${x + 12}" y="${y + 22}">${esc(fit(`Step ${n} · ${stateLabel(st)}`, f.miss, room))}</text>
|
||||
<text class="wfg-title" data-wfg-title x="${x + 12}" y="${y + 46}">${lines.map((l, j) => `<tspan x="${x + 12}" dy="${j ? 19 : 0}">${esc(l)}${j < lines.length - 1 ? ' ' : ''}</tspan>`).join('')}</text>
|
||||
<text class="wfg-roles" data-wfg-roles x="${x + 12}" y="${y + rolesY(st)}">${roleText}</text>
|
||||
${missText}</g></a>`;
|
||||
}).join('');
|
||||
return `<svg class="wfg-graph${vertical ? ' is-vertical' : ''}" data-wfg-graph role="group" aria-label="${esc(`${count(steps.length)}, in order`)}" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}" xmlns="http://www.w3.org/2000/svg">
|
||||
<defs><marker id="wfg-arrow" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="8" markerHeight="8" orient="auto"><path class="wfg-arrow" d="M0 0L10 5L0 10z"/></marker></defs>${edges}${nodes}</svg>`;
|
||||
}
|
||||
|
||||
// ---------- SP10 (#1873): editing a workflow in its graph ----------
|
||||
// A change is held in the page, not written, until Save: the graph draws the pending workflow, the bar says
|
||||
// Unsaved, and Save sends one POST with the revision the page read (saveFlow, the form's write). A refusal is
|
||||
// shown in words and the pending change kept. The poll redraws from the pending workflow, never over it.
|
||||
// When the file changes while a change is pending: if this workflow is as the page read it, the new revision
|
||||
// is taken (a workflow write sets only this workflow, so nothing else is overwritten); if this workflow
|
||||
// changed, the bar says so and offers Discard. Drafts live per organization until saved or discarded, and
|
||||
// the organization-switch and restart guards ask before dropping one (hasDraft).
|
||||
const drafts = new Map(), notes = new Map(), newForms = new Map();
|
||||
const dkey = (org, scope, name) => JSON.stringify([org, scope, name]);
|
||||
const norm = w => ({
|
||||
title: typeof w?.title === 'string' ? w.title : '', description: typeof w?.description === 'string' ? w.description : '',
|
||||
steps: stepsOf(w).map(st => ({ title: String(st.title ?? ''), state: st.state, roles: rolesOf(st) })),
|
||||
});
|
||||
const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
|
||||
const changed = d => d.isNew || !same(d.flow, d.base);
|
||||
const editDirty = e => !!e && !same({ title: e.title, state: e.state, roles: e.roles }, e.orig);
|
||||
const pending = d => !!d && (changed(d) || editDirty(d.edit));
|
||||
// The steps as the graph draws them: the pending workflow with the open step's edit as typed.
|
||||
const preview = d => {
|
||||
const e = d?.edit;
|
||||
if (!d) return null;
|
||||
if (e?.mode !== 'edit' || !d.flow.steps[e.i] || !editDirty(e)) return d.flow.steps;
|
||||
return d.flow.steps.map((st, j) => (j === e.i ? { title: e.title.trim() || st.title, state: e.state, roles: [...e.roles] } : st));
|
||||
};
|
||||
// The names of this organization's workflows with a change held on the page.
|
||||
const heldKeys = org => [...drafts].filter(([k, d]) => JSON.parse(k)[0] === org && pending(d)).map(([k]) => JSON.parse(k).slice(1));
|
||||
const held = org => heldKeys(org).map(([, name]) => name);
|
||||
// The organization card's word for a held change (a bus stop or restart keeps it): each held workflow
|
||||
// links back to its page, where the change is as typed.
|
||||
const heldCardNote = org => {
|
||||
const keys = heldKeys(org);
|
||||
if (!keys.length) return '';
|
||||
return `<p class="ws-panel tight note" data-wfg-held>Unsaved change kept on this page: ${keys.map(([scope, name]) => `<a href="${esc(flowHref(org, scope, name))}" data-wfg-held-link data-focus-key="${esc(`wfg-held:${scope}:${name}`)}">${esc(name)}${scope ? ` (project ${esc(scope)})` : ''}</a>`).join(', ')}.</p>`;
|
||||
};
|
||||
const READ_ONLY = 'Only the owner, on a Console started with send, can change workflows.';
|
||||
// The graph's own words for a refusal where the form's would mislead: the change is kept, not lost.
|
||||
const kept = {
|
||||
'revision-conflict': 'Not saved: the organization file changed since this page read it. Your change is kept. Discard to load the current version.',
|
||||
'organization-busy': 'Not saved: the organization is busy with another write. Your change is kept. Try Save again shortly.',
|
||||
'no-bus-host': 'Not saved: the organization bus is not running. Your change is kept. Save again once it runs.',
|
||||
'invalid-request': 'Not saved: the bus refused the workflow. Check each step has a title, a state and one to eight distinct roles. Your change is kept.',
|
||||
};
|
||||
const say = text => { const live = document.getElementById('announce'); if (live) { live.textContent = ''; live.textContent = text; } };
|
||||
|
||||
// A pending change measured against the fresh read; drops one with nothing left to keep.
|
||||
function settle(org, s, scope, name, fresh) {
|
||||
const key = dkey(org, scope, name), d = drafts.get(key);
|
||||
if (!d) return null;
|
||||
if (d.busy) return d;
|
||||
const now = fresh ? norm(fresh) : null;
|
||||
if (d.isNew) { d.stale = !!fresh; if (!fresh) d.revision = s.data.revision; }
|
||||
else if (now && same(now, d.base)) { d.revision = s.data.revision; d.stale = false; }
|
||||
else if (now && !changed(d) && !(d.edit?.mode === 'edit' && editDirty(d.edit) && !same(now.steps[d.edit.i], d.base.steps[d.edit.i]))) {
|
||||
// Only other parts changed: take them. A typed step whose step changed elsewhere is stale below instead.
|
||||
Object.assign(d, { base: now, flow: structuredClone(now), revision: s.data.revision, stale: false });
|
||||
if (d.edit?.mode === 'edit' && d.edit.i >= now.steps.length) d.edit = null;
|
||||
} else d.stale = true;
|
||||
if (!changed(d) && (!d.edit || (d.edit.mode === 'edit' && !editDirty(d.edit))) && !d.confirm && !d.status) { drafts.delete(key); return null; }
|
||||
return d;
|
||||
}
|
||||
function draftFor(org, s, scope, name) {
|
||||
const key = dkey(org, scope, name);
|
||||
if (drafts.has(key)) return drafts.get(key);
|
||||
const fresh = flowsIn(s, scope)?.[name];
|
||||
if (!fresh) return null;
|
||||
const base = norm(fresh), d = { isNew: false, base, flow: structuredClone(base), revision: s.data.revision, edit: null, confirm: false, status: '', busy: false, stale: false };
|
||||
drafts.set(key, d);
|
||||
notes.delete(key);
|
||||
return d;
|
||||
}
|
||||
// The role picker: human, the organization's roles, the role templates, and first any role the step names
|
||||
// that resolves to none of those (checked and marked, so leaving it in is a choice the save check names).
|
||||
function rolePick(s, chosen, prefix, off = false) {
|
||||
const defs = [...(s.data.roles.definitions || [])].sort(), tpl = offered(s.data.roles.templates).filter(r => !defs.includes(r)).sort();
|
||||
const odd = chosen.filter(r => !s.known.has(r));
|
||||
const box = (r, mark = '') => `<label class="wfg-pick"><input type="checkbox" name="role" value="${esc(r)}"${chosen.includes(r) ? ' checked' : ''} data-focus-key="${esc(`${prefix}:role:${r}`)}"> <code>${esc(r)}</code>${mark}</label>`;
|
||||
const group = (title, list, mark) => (list.length ? `<p class="wfg-pick-h">${title}</p>${list.map(r => box(r, mark)).join('')}` : '');
|
||||
return `<fieldset class="wfg-roles-pick" data-wfg-roles-pick${off ? ' disabled' : ''}><legend>Roles, one to eight</legend>
|
||||
${group('Named in this step', odd, ` <span class="wf-missing" data-wfg-pick-missing>${MISSING}</span>`)}${box('human', ' <span class="muted">a person</span>')}
|
||||
${group('This organization\'s roles', defs.filter(r => r !== 'human'), '')}${group('Role templates', tpl.filter(r => r !== 'human'), '')}</fieldset>`;
|
||||
}
|
||||
const stateSelect = (value, key, off = false) => `<label>State<select name="state" data-focus-key="${esc(key)}"${off ? ' disabled' : ''}>${STATES.map(([v, l]) => `<option value="${v}"${value === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>`;
|
||||
// A new step's form: Add step puts it in the graph on this page, unsaved.
|
||||
function addForm(org, s, scope, name, d) {
|
||||
const e = d.edit, n = e.i + 1;
|
||||
return `<form class="wfg-form" data-wfg-form data-wfg-add-form data-live-key="${esc(`wfg-form:${org}:${scope}:${name}:add:${e.i}`)}" data-live-hold novalidate>
|
||||
<h2 data-wfg-form-title>New step ${n}</h2>
|
||||
<label>Title<input name="title" maxlength="120" value="${esc(e.title)}" autocomplete="off" data-focus-key="wfg-f-title"></label>
|
||||
${stateSelect(e.state, 'wfg-f-state')}${rolePick(s, e.roles, 'wfg-f')}
|
||||
<p class="wfg-why" data-wfg-why>${esc(e.why ?? '')}</p>
|
||||
<p class="wfg-form-acts"><button type="submit" class="ws-btn primary" data-wfg-add-step data-focus-key="wfg-f-add">Add step</button> <button type="button" class="ws-btn" data-wfg-cancel data-focus-key="wfg-f-cancel">Cancel</button></p>
|
||||
<p class="note">Add step puts it in the graph on this page. Save writes the workflow to the organization file.</p></form>`;
|
||||
}
|
||||
// SP17: the Save inside a panel form. It saves the whole workflow, the open step's edit with it.
|
||||
// The line that says what Save did or why it did not: next to Save, wherever Save is. A refused delete
|
||||
// (d.atBar) is said in the bar, next to Delete workflow.
|
||||
const statusOf = (org, scope, name, d) => d?.status || notes.get(dkey(org, scope, name)) || '';
|
||||
const formStatus = (org, scope, name, d) => (d?.atBar ? '' : statusOf(org, scope, name, d));
|
||||
const statusLine = text => (text ? `<p class="wfg-status" data-wfg-status>${esc(text)}</p>` : '');
|
||||
const saveButton = d => {
|
||||
const busy = !!d?.busy, on = pending(d) && !busy;
|
||||
return `<button type="button" class="ws-btn primary" data-wfg-save data-focus-key="wfg-save"${on ? '' : ' disabled'}>${busy ? 'Saving…' : 'Save'}</button>`;
|
||||
};
|
||||
// SP17: a selected step's panel is its edit form. It shows the step as the page holds it, or the edit typed
|
||||
// into it, and holds its node across a repaint only once it differs from the step (data-live-hold).
|
||||
function editForm(org, s, scope, name, steps, sel, d) {
|
||||
const i = sel - 1, st = steps[i], e = d?.edit?.mode === 'edit' && d.edit.i === i ? d.edit : null;
|
||||
const v = e ?? { title: st.title, state: st.state, roles: rolesOf(st), why: '' }, dirty = editDirty(e), off = !!d?.busy;
|
||||
return `<form class="wfg-form wfg-stepform" data-wfg-form data-wfg-step-form="${i}" data-live-key="${esc(`wfg-form:${org}:${scope}:${name}:edit:${i}`)}"${dirty ? ' data-live-hold' : ''} novalidate aria-label="${esc(`Step ${sel}`)}">
|
||||
<label>Title<input name="title" maxlength="120" value="${esc(v.title)}" autocomplete="off" data-focus-key="wfg-f-title"${off ? ' disabled' : ''}></label>
|
||||
${stateSelect(v.state, 'wfg-f-state', off)}${rolePick(s, v.roles, 'wfg-f', off)}
|
||||
<p class="wfg-why" data-wfg-why>${esc(v.why ?? '')}</p>
|
||||
<p class="wfg-form-acts">${saveButton(d)} <button type="button" class="ws-btn" data-wfg-cancel data-focus-key="wfg-f-cancel"${dirty ? '' : ' hidden'}>Reset step</button></p>${statusLine(formStatus(org, scope, name, d))}</form>`;
|
||||
}
|
||||
// SP17: with no step selected, the panel edits the workflow's title and description, which the old
|
||||
// organization-page form did. Each change goes into the pending workflow at once.
|
||||
function metaForm(org, s, scope, name, d, w) {
|
||||
return `<form class="wfg-form wfg-metaform" data-wfg-form data-wfg-meta-form data-live-key="${esc(`wfg-meta:${org}:${scope}:${name}`)}"${pending(d) ? ' data-live-hold' : ''} novalidate aria-label="Workflow">
|
||||
<label>Title<input name="title" maxlength="120" value="${esc(w.title)}" autocomplete="off" data-focus-key="wfg-m-title"${d?.busy ? ' disabled' : ''}></label>
|
||||
<label>Description<textarea name="description" maxlength="1000" rows="2" data-focus-key="wfg-m-desc"${d?.busy ? ' disabled' : ''}>${esc(w.description)}</textarea></label>
|
||||
<p class="wfg-form-acts">${saveButton(d)}</p>${statusLine(formStatus(org, scope, name, d))}</form>`;
|
||||
}
|
||||
// `inPanel`: the panel shows a form with its own Save, so the bar does not repeat it.
|
||||
function bar(org, s, scope, name, d, inPanel) {
|
||||
if (!s.data.writable) return `<p class="note wfg-ro" data-wfg-readonly>${READ_ONLY}</p>`;
|
||||
const dirty = pending(d), busy = d?.busy ? ' disabled' : '';
|
||||
// With a panel form, the status sits with that form's Save instead.
|
||||
const status = inPanel ? (d?.atBar ? d.status : '') : statusOf(org, scope, name, d);
|
||||
const stale = d?.stale ? `<p class="wfg-stale" data-wfg-stale>${d.isNew ? `A workflow named ${esc(name)} now exists here. Save will be refused. Discard to drop this one.` : 'The organization file changed this workflow since the page read it. Save will be refused. Discard to load the current version.'}</p>` : '';
|
||||
const acts = d?.confirm
|
||||
? `<span class="wfg-confirm" data-wfg-confirm>Delete ${esc(name)} from the organization file? <button type="button" class="ws-btn danger" data-wfg-delete-yes data-focus-key="wfg-delete-yes"${busy}>Delete workflow</button> <button type="button" class="ws-btn" data-wfg-delete-no data-focus-key="wfg-delete-no"${busy}>Keep</button></span>`
|
||||
: `${dirty ? `<button type="button" class="ws-btn" data-wfg-discard data-focus-key="wfg-discard"${busy}>Discard</button>${inPanel ? '' : ` <button type="button" class="ws-btn primary" data-wfg-save data-focus-key="wfg-save"${busy}>${d.busy ? 'Saving…' : 'Save'}</button>`}` : ''}${d?.isNew ? '' : ` <button type="button" class="ws-btn danger" data-wfg-delete data-focus-key="wfg-delete"${busy}>Delete workflow</button>`}`;
|
||||
return `<div class="wfg-bar${dirty ? ' is-dirty' : ''}" data-wfg-bar>${dirty ? `<span class="wfg-badge" data-wfg-unsaved>Unsaved${d.isNew ? ', not in the file yet' : ''}</span>` : ''}<span class="wfg-acts">${acts}</span>
|
||||
${statusLine(status)}${stale}</div>`;
|
||||
}
|
||||
const stepRef = (org, scope, name, steps, n) => `<a href="${esc(flowHref(org, scope, name, n))}" data-wfg-go="${n}">Step ${n}, ${esc(steps[n - 1].title)}</a>`;
|
||||
function actions(steps, sel, d) {
|
||||
const busy = d?.busy ? ' disabled' : '';
|
||||
if (!sel) return `<p class="wfg-step-acts" data-wfg-actions><button type="button" class="ws-btn" data-wfg-add data-focus-key="wfg-add"${busy}>Add a step at the end</button></p>`;
|
||||
const dis = c => (c || d?.busy ? ' disabled' : '');
|
||||
return `<p class="wfg-step-acts" data-wfg-actions><button type="button" class="ws-btn" data-wfg-add data-focus-key="wfg-add"${dis(steps.length >= 20)}>Add a step after</button>
|
||||
<button type="button" class="ws-btn" data-wfg-up data-focus-key="wfg-up"${dis(sel === 1)}>Move earlier</button>
|
||||
<button type="button" class="ws-btn" data-wfg-down data-focus-key="wfg-down"${dis(sel === steps.length)}>Move later</button>
|
||||
<button type="button" class="ws-btn danger" data-wfg-remove data-focus-key="wfg-remove"${dis(steps.length === 1)}>Remove step</button></p>`;
|
||||
}
|
||||
function detail(org, s, scope, name, steps, sel, d, w) {
|
||||
const writable = !!s.data.writable;
|
||||
if (writable && d?.edit?.mode === 'add') return `<section class="panel wfg-detail" data-wfg-detail>${addForm(org, s, scope, name, d)}</section>`;
|
||||
if (!sel) {
|
||||
return writable
|
||||
? `<section class="panel wfg-detail" data-wfg-detail><h2>This workflow</h2>${metaForm(org, s, scope, name, d, w)}<p class="note">Select a step in the graph to change it.</p>${actions(steps, 0, d)}</section>`
|
||||
: `<section class="panel wfg-detail" data-wfg-detail><h2>Step details</h2><p class="note">Select a step to see its roles, the state it puts a task in and the step it hands on to.</p></section>`;
|
||||
}
|
||||
const st = steps[sel - 1], roles = rolesOf(st);
|
||||
const roleList = roles.map(r => r === 'human' ? '<code>human</code> (a person)' : s.known.has(r) ? `<code>${esc(r)}</code>` : `<code>${esc(r)}</code> <span class="wf-missing" data-wfg-missing>${MISSING}</span>`).join(', ');
|
||||
const fields = writable ? '' : `
|
||||
<dt>Roles</dt><dd data-wfg-field="roles">${roleList || '<span class="muted">None recorded</span>'}</dd>
|
||||
<dt>Puts the task in</dt><dd data-wfg-field="state">${esc(stateLabel(st))}</dd>`;
|
||||
return `<section class="panel wfg-detail" data-wfg-detail><h2 data-wfg-detail-title>${esc(st.title)}</h2>${writable ? editForm(org, s, scope, name, steps, sel, d) : ''}<dl class="wfg-dl">
|
||||
<dt>Position</dt><dd data-wfg-field="position">Step ${sel} of ${steps.length}</dd>${fields}
|
||||
<dt>Comes after</dt><dd data-wfg-field="after">${sel > 1 ? stepRef(org, scope, name, steps, sel - 1) : 'Nothing: this is the first step'}</dd>
|
||||
<dt>Hands on to</dt><dd data-wfg-field="next">${sel < steps.length ? stepRef(org, scope, name, steps, sel + 1) : 'Nothing: this is the last step'}</dd>
|
||||
</dl>${writable ? actions(steps, sel, d) : ''}<p class="note">The workflow file records no gate or inputs for a step, and no read says which step a task is on now.</p></section>`;
|
||||
}
|
||||
function graphBody(org, s, name, q) {
|
||||
const scope = q.get('project') || '';
|
||||
if (scope && !Object.hasOwn(s.data.projects, scope)) return { title: esc(name), sub: '', body: `<p class="note" data-wfg-unknown>No code project named ${esc(scope)} in the organization file.</p>` };
|
||||
const flows = flowsIn(s, scope), fresh = plain(flows) && Object.hasOwn(flows, name) ? flows[name] : null;
|
||||
const d = s.data.writable ? settle(org, s, scope, name, fresh) : null;
|
||||
const note = notes.get(dkey(org, scope, name));
|
||||
if (!fresh && !d) return { title: esc(name), sub: '', body: `${note ? `<p class="wfg-status" data-wfg-status>${esc(note)}</p>` : ''}<p class="note" data-wfg-unknown>No workflow named ${esc(name)} in ${scope ? `project ${esc(scope)}` : 'the organization'}.</p>` };
|
||||
const w = d ? d.flow : norm(fresh), steps = w.steps;
|
||||
const raw = Number(q.get('step')), sel = Number.isInteger(raw) && raw >= 1 && raw <= steps.length ? raw : 0;
|
||||
if (d && !d.busy) park(d, sel - 1);
|
||||
const sub = `${esc(scopeLabel(scope))}, <code>${esc(name)}</code>, ${count(steps.length)}.${w.description ? ` ${esc(w.description)}` : ''}`;
|
||||
const body = steps.length
|
||||
? `${bar(org, s, scope, name, d, !!s.data.writable && d?.edit?.mode !== 'add')}<div class="wfg-frame" data-wfg-frame>${graph(org, s, scope, name, d ? preview(d) : steps, sel)}</div>${detail(org, s, scope, name, steps, sel, d, w)}`
|
||||
: `${bar(org, s, scope, name, d)}<p class="note">This workflow has no steps.</p>`;
|
||||
return { title: esc(w.title || name), sub, body };
|
||||
}
|
||||
|
||||
// The list page's New workflow form: where, a name, and the first step. Create opens it in the graph, unsaved.
|
||||
function newForm(org, s) {
|
||||
const f = newForms.get(org);
|
||||
if (!f) return `<p class="wfg-new"><button type="button" class="ws-btn" data-wfg-new data-focus-key="wfg-new">New workflow</button></p>`;
|
||||
return `<form class="wfg-form wfg-newform panel" data-wfg-form data-wfg-newform data-live-key="${esc(`wfg-new:${org}`)}" data-live-hold novalidate>
|
||||
<h2>New workflow</h2>
|
||||
<label>Where<select name="scope" data-focus-key="wfg-n-scope">${scopes(s).map(([v, l]) => `<option value="${esc(v)}"${f.scope === v ? ' selected' : ''}>${esc(l)}</option>`).join('')}</select></label>
|
||||
<label>Name<input name="name" maxlength="64" value="${esc(f.name)}" autocomplete="off" placeholder="lowercase letters, digits, dashes" data-focus-key="wfg-n-name"></label>
|
||||
<p class="note">${NAME_RULE}</p>
|
||||
<h3>First step</h3>
|
||||
<label>Title<input name="title" maxlength="120" value="${esc(f.title)}" autocomplete="off" data-focus-key="wfg-n-title"></label>
|
||||
${stateSelect(f.state, 'wfg-n-state')}${rolePick(s, f.roles, 'wfg-n')}
|
||||
<p class="wfg-why" data-wfg-why>${esc(f.why ?? '')}</p>
|
||||
<p class="wfg-form-acts"><button type="submit" class="ws-btn primary" data-wfg-create data-focus-key="wfg-n-create">Create</button> <button type="button" class="ws-btn" data-wfg-new-cancel data-focus-key="wfg-n-cancel">Cancel</button></p>
|
||||
<p class="note">Create opens it in its graph. It is written to the organization file when you save it there.</p></form>`;
|
||||
}
|
||||
// The rows each scope lists: the file's workflows, and any new one not saved yet.
|
||||
function rowsWithDrafts(org, s) {
|
||||
return listed(s).map(([scope, label, rows]) => {
|
||||
const names = new Set(rows.map(([n]) => n));
|
||||
const fresh = [...drafts.entries()].map(([k, d]) => [JSON.parse(k), d]).filter(([[o, sc, n], d]) => o === org && sc === scope && d.isNew && !names.has(n)).map(([[, , n], d]) => [n, d.flow]);
|
||||
return [scope, label, [...rows, ...fresh].sort(([p], [q]) => (p < q ? -1 : p > q ? 1 : 0))];
|
||||
});
|
||||
}
|
||||
function listBody(org, s, label) {
|
||||
const writable = !!s.data.writable, rows = writable ? rowsWithDrafts(org, s) : listed(s);
|
||||
const top = `${notes.has(dkey(org, '', '')) ? `<p class="wfg-status" data-wfg-status>${esc(notes.get(dkey(org, '', '')))}</p>` : ''}${writable ? newForm(org, s) : `<p class="note wfg-ro" data-wfg-readonly>${READ_ONLY}</p>`}`;
|
||||
if (!rows.some(([, , r]) => r.length)) return `${top}${none(org, s, label)}`;
|
||||
return top + rows.filter(([scope, , r]) => !scope || r.length).map(([scope, label2, r]) => `<section class="wfg-scope" data-wfg-scope-list="${esc(scope)}"><h2>${esc(label2)}</h2>${r.length ? `<ul class="wfg-list">${r.map(([name, w]) => {
|
||||
const steps = stepsOf(w), d = drafts.get(dkey(org, scope, name)), pending = d && changed(d);
|
||||
return `<li class="wfg-item" data-wfg-item="${esc(name)}" data-wfg-scope="${esc(scope)}"><div class="wfg-item-h"><a href="${esc(flowHref(org, scope, name))}" data-wfg-open data-focus-key="${esc(`wfg-open:${scope}:${name}`)}">${esc(w?.title || name)}</a>${w?.title ? ` <code>${esc(name)}</code>` : ''} <span class="muted">${count(steps.length)}</span>${pending ? ` <span class="wfg-badge" data-wfg-unsaved>Unsaved${d.isNew ? ', not in the file yet' : ''}</span>` : ''}</div>
|
||||
${w?.description ? `<p class="wfg-desc">${esc(w.description)}</p>` : ''}<ol class="wfg-chain" data-wfg-chain aria-label="Steps in order">${steps.map(st => `<li>${esc(st.title)}</li>`).join('')}</ol></li>`;
|
||||
}).join('')}</ul>` : '<p class="note">None at the organization level.</p>'}</section>`).join('');
|
||||
}
|
||||
|
||||
// The page for #/orgs/<org>/workflows (name null) or #/orgs/<org>/workflows/<name>. page() reads; compose()
|
||||
// draws from what was read, so an edit on the page redraws at once (paint) without waiting for a read.
|
||||
const shown = { org: null, name: null, info: null };
|
||||
function compose(org, name, q, info) {
|
||||
const attr = name === null ? 'data-wfg-list' : 'data-wfg-page';
|
||||
const wrapIt = (title, sub, body) => `<article class="ws wfg" ${attr} data-wfg-org="${esc(org)}"${name === null ? '' : ` data-wfg-name="${esc(name)}"`}>${head(title, sub)}${info.unread}${body}</article>`;
|
||||
// Review P3: a change held for this organization that the page cannot draw now is said to be kept.
|
||||
const names = held(org), s = states.get(org);
|
||||
const keptNote = !names.length ? '' : s?.readError && s.data
|
||||
? `<p class="note" data-wfg-error>The last workflows read failed: ${esc(s.readError.replace(/\.$/, ''))}. The page shows the read before it.</p><p class="note" data-wfg-held>Unsaved change to ${names.map(n => esc(n)).join(', ')} is kept on this page.</p>`
|
||||
: `<p class="note" data-wfg-held>Unsaved change to ${names.map(n => esc(n)).join(', ')} is kept on this page. It comes back when the workflows can be read.</p>`;
|
||||
// E2E6 P2-8: a stopped bus is not read; the note above says why.
|
||||
if (info.stopped) return wrapIt(name === null ? 'Workflows' : esc(name), `Workflows in ${esc(info.label)}.`, keptNote);
|
||||
if (!s?.data) return wrapIt(name === null ? 'Workflows' : esc(name), `Workflows in ${esc(info.label)}.`, `<p class="note" data-wfg-error>${esc(s?.error ?? 'Workflows could not be read.')}</p>${keptNote}`);
|
||||
const lastRead = s.readError ? keptNote : '';
|
||||
if (name === null) return wrapIt('Workflows', `The steps a task goes through in ${esc(info.label)}, in order, with the roles that do each.${s.data.writable ? ' Open one to change it.' : ''}`, lastRead + listBody(org, s, info.label));
|
||||
const g = graphBody(org, s, name, q);
|
||||
return wrapIt(g.title, g.sub, lastRead + g.body);
|
||||
}
|
||||
async function page(org, name, q) {
|
||||
const info = await orgOf(org);
|
||||
if (!info.row) return `<article class="ws wfg" ${name === null ? 'data-wfg-list' : 'data-wfg-page'} data-wfg-org="${esc(org)}">${head('Organization unavailable', info.list ? 'This organization is not on your list.' : 'The organization list could not be read.')}</article>`;
|
||||
if (!info.stopped) await load(org);
|
||||
Object.assign(shown, { org, name, info });
|
||||
return compose(org, name, q, info);
|
||||
}
|
||||
const query = () => new URLSearchParams(location.hash.split('?')[1] || '');
|
||||
// Redraw the open workflow page from the page's state, then put focus on `focus` (a data-focus-key).
|
||||
function paint(focus) {
|
||||
const el = document.querySelector('#bus-view [data-wfg-list], #bus-view [data-wfg-page]');
|
||||
if (!el || !shown.info || el.dataset.wfgOrg !== shown.org || (el.dataset.wfgName ?? null) !== shown.name) return;
|
||||
el.outerHTML = compose(shown.org, shown.name, query(), shown.info);
|
||||
const el2 = focus && document.querySelector(`#bus-view [data-focus-key="${CSS.escape(focus)}"]`);
|
||||
if (!el2) return;
|
||||
el2.focus();
|
||||
// A text field takes focus with the caret after its text, ready to change it.
|
||||
if (el2.matches('input:not([type=checkbox])')) el2.setSelectionRange(el2.value.length, el2.value.length);
|
||||
}
|
||||
// The open graph page: its organization, scope, name, read and pending change.
|
||||
function here(el) {
|
||||
const root = el.closest('[data-wfg-page]');
|
||||
if (!root || root.dataset.wfgOrg !== shown.org) return null;
|
||||
const org = shown.org, name = shown.name, scope = query().get('project') || '', s = states.get(org);
|
||||
if (!s?.data?.writable) return null;
|
||||
return { org, name, scope, s, key: dkey(org, scope, name) };
|
||||
}
|
||||
const selected = () => { const n = Number(query().get('step')); return Number.isInteger(n) && n > 0 ? n : 0; };
|
||||
const select = step => WS()?.setQuery?.({ step: step || null }, false);
|
||||
function openForm(d, mode, i, st) {
|
||||
const roles = st ? [...st.roles] : [];
|
||||
d.edit = { mode, i, title: st?.title ?? '', state: st?.state ?? 'todo', roles, why: '', orig: { title: st?.title ?? '', state: st?.state ?? 'todo', roles: [...roles] } };
|
||||
}
|
||||
function readForm(form, into) {
|
||||
into.title = form.elements.title.value;
|
||||
into.state = form.elements.state.value;
|
||||
into.roles = [...form.querySelectorAll('input[name="role"]:checked')].map(i => i.value);
|
||||
if (form.elements.scope) into.scope = form.elements.scope.value;
|
||||
if (form.elements.name) into.name = form.elements.name.value.trim();
|
||||
}
|
||||
function why(form, into, text) {
|
||||
into.why = text;
|
||||
// Direct text: the form may be the held node a repaint grafted back.
|
||||
const p = form.querySelector('[data-wfg-why]');
|
||||
if (p) p.textContent = text;
|
||||
say(text);
|
||||
}
|
||||
|
||||
// SP17: the selected step's form, its edit (made at the first change) and its message line.
|
||||
const stepFormEl = () => document.querySelector('#bus-view [data-wfg-page] [data-wfg-step-form]');
|
||||
// The open step edit carried into the pending workflow: '' when there was nothing to carry or it went in,
|
||||
// or the reason it cannot (the edit is kept and the form says why).
|
||||
function carry(d) {
|
||||
const e = d?.edit;
|
||||
if (!e || e.mode !== 'edit') return '';
|
||||
if (!editDirty(e)) { d.edit = null; return ''; }
|
||||
const st = { title: e.title.trim(), state: e.state, roles: [...e.roles] };
|
||||
const refused = stepRefusal(st, e.i + 1);
|
||||
if (refused) { const form = stepFormEl(); if (form) why(form, e, refused); else { e.why = refused; say(refused); } return refused; }
|
||||
d.flow.steps[e.i] = st; d.edit = null;
|
||||
return '';
|
||||
}
|
||||
// SP17 review: an open edit of a step other than the one shown (a card step link, the address or Back opened
|
||||
// another step) goes into the pending workflow as typed, never dropped. A step the save check refuses is then
|
||||
// named by Save, which checks every step.
|
||||
function park(d, i) {
|
||||
const e = d?.edit;
|
||||
if (!e || e.mode !== 'edit' || e.i === i) return;
|
||||
if (editDirty(e) && d.flow.steps[e.i]) d.flow.steps[e.i] = { title: e.title.trim(), state: e.state, roles: [...e.roles] };
|
||||
d.edit = null;
|
||||
}
|
||||
// SP17 review: while a Save or delete is in flight the form's fields take no typing, so nothing typed then is
|
||||
// dropped when the answer redraws the form. Drawn off when busy; a held form (data-live-hold) is set here.
|
||||
const lockForms = off => document.querySelectorAll('#bus-view [data-wfg-page] :is([data-wfg-step-form],[data-wfg-meta-form])').forEach(f =>
|
||||
f.querySelectorAll('input[name="title"],textarea,select,[data-wfg-roles-pick]').forEach(c => { c.disabled = off; }));
|
||||
const toAddTitle = () => document.querySelector('#bus-view [data-wfg-page] [data-wfg-add-form] input[name="title"]')?.focus();
|
||||
// Put focus back in the step form's title after a refusal (the form may be a held node).
|
||||
const toTitle = () => { const f = stepFormEl()?.elements.title; if (f) { f.focus(); f.setSelectionRange(f.value.length, f.value.length); } };
|
||||
|
||||
document.addEventListener('click', async ev => {
|
||||
const btn = ev.target.closest('[data-wfg-new],[data-wfg-new-cancel],[data-wfg-add],[data-wfg-up],[data-wfg-down],[data-wfg-remove],[data-wfg-cancel],[data-wfg-discard],[data-wfg-save],[data-wfg-delete],[data-wfg-delete-no],[data-wfg-delete-yes]');
|
||||
if (!btn || btn.disabled) return;
|
||||
if (btn.matches('[data-wfg-new],[data-wfg-new-cancel]')) {
|
||||
const org = btn.closest('[data-wfg-list]')?.dataset.wfgOrg;
|
||||
if (!org || org !== shown.org) return;
|
||||
if (btn.hasAttribute('data-wfg-new')) { newForms.set(org, { scope: '', name: '', title: '', state: 'todo', roles: [], why: '' }); notes.delete(dkey(org, '', '')); paint('wfg-n-name'); }
|
||||
else { newForms.delete(org); paint('wfg-new'); }
|
||||
return;
|
||||
}
|
||||
const at = here(btn);
|
||||
if (!at) return;
|
||||
const { org, name, scope, s, key } = at;
|
||||
const sel = selected();
|
||||
if (btn.hasAttribute('data-wfg-discard')) {
|
||||
const d = drafts.get(key);
|
||||
drafts.delete(key);
|
||||
if (d?.isNew) { location.hash = `${orgHash(org)}/workflows`; return; }
|
||||
say(`Discarded the change to ${name}.`);
|
||||
return paint('wfg-delete');
|
||||
}
|
||||
if (btn.hasAttribute('data-wfg-save')) return save(at);
|
||||
if (btn.matches('[data-wfg-delete-yes]')) return remove(at);
|
||||
const d = draftFor(org, s, scope, name) ?? drafts.get(key);
|
||||
if (!d) return;
|
||||
d.status = ''; d.atBar = false;
|
||||
const steps = d.flow.steps;
|
||||
if (btn.hasAttribute('data-wfg-cancel')) {
|
||||
// The new step's Cancel goes back to the step it was opened from; the step form's Reset puts the step back.
|
||||
if (d.edit?.mode === 'edit') { d.edit = null; say(`Step ${sel} is back as the page holds it.`); return paint('wfg-f-title'); }
|
||||
d.edit = null; select(sel); return paint(sel ? 'wfg-f-title' : 'wfg-add');
|
||||
}
|
||||
// Moving, adding or removing a step takes the open step's edit with it first.
|
||||
if (carry(d)) return toTitle();
|
||||
if (btn.hasAttribute('data-wfg-add')) { openForm(d, 'add', sel ? sel : steps.length, null); return paint('wfg-f-title'); }
|
||||
if (btn.matches('[data-wfg-up],[data-wfg-down]') && steps[sel - 1]) {
|
||||
const to = btn.hasAttribute('data-wfg-up') ? sel - 1 : sel + 1;
|
||||
if (to < 1 || to > steps.length) return;
|
||||
[steps[sel - 1], steps[to - 1]] = [steps[to - 1], steps[sel - 1]];
|
||||
select(to);
|
||||
say(`Moved step ${sel} to position ${to}.`);
|
||||
const key2 = btn.hasAttribute('data-wfg-up') ? (to > 1 ? 'wfg-up' : 'wfg-down') : (to < steps.length ? 'wfg-down' : 'wfg-up');
|
||||
return paint(key2);
|
||||
}
|
||||
if (btn.hasAttribute('data-wfg-remove') && steps[sel - 1] && steps.length > 1) {
|
||||
const [gone] = steps.splice(sel - 1, 1);
|
||||
const next = Math.min(sel, steps.length);
|
||||
select(next);
|
||||
say(`Removed step ${sel}, ${gone.title}.`);
|
||||
return paint(`wfg-step:${next}`);
|
||||
}
|
||||
if (btn.hasAttribute('data-wfg-delete')) { d.confirm = true; return paint('wfg-delete-no'); }
|
||||
if (btn.hasAttribute('data-wfg-delete-no')) { d.confirm = false; return paint('wfg-delete'); }
|
||||
});
|
||||
// SP17: the page's read brought up to date from a write's answer: the workflow as sent (or gone) and the
|
||||
// revision the write answered. Without a revision in the answer the page reads the file again.
|
||||
async function written(org, s, scope, name, workflow, answer) {
|
||||
const now = states.get(org) ?? s, flows = now.data ? flowsIn(now, scope) : null;
|
||||
if (plain(flows) && typeof answer?.revision === 'string' && /^[0-9a-f]{64}$/.test(answer.revision)) {
|
||||
if (workflow) flows[name] = workflow; else delete flows[name];
|
||||
now.data.revision = answer.revision;
|
||||
return;
|
||||
}
|
||||
try { await read(org, now); } catch { /* the next poll reads it */ }
|
||||
}
|
||||
async function save({ org, name, scope, s, key }) {
|
||||
const d = drafts.get(key);
|
||||
if (!d || d.busy) return;
|
||||
// SP17 review: a new step typed in the add form is not saved over or dropped: Save says so and keeps the
|
||||
// form. So is one in which only the state was changed. An add form left as it opened is closed and the
|
||||
// rest is saved.
|
||||
if (d.edit?.mode === 'add') {
|
||||
if (d.edit.title.trim() || d.edit.roles.length || editDirty(d.edit)) {
|
||||
d.atBar = false; d.status = `Not saved: new step ${d.edit.i + 1} is not added yet. Press Add step, or Cancel to drop it.`;
|
||||
say(d.status); paint(); return toAddTitle();
|
||||
}
|
||||
d.edit = null;
|
||||
}
|
||||
// SP17: the open step's edit goes in with the save; one the save check refuses stays in its form.
|
||||
const unfit = carry(d);
|
||||
d.atBar = false;
|
||||
if (unfit) { d.status = `Not saved: ${unfit}`; say(d.status); paint(); return toTitle(); }
|
||||
const refused = refusal(s, { isNew: d.isNew, scope, name, steps: d.flow.steps });
|
||||
if (refused) { d.status = refused; say(refused); return paint('wfg-save'); }
|
||||
if (!changed(d)) return paint();
|
||||
d.busy = true; d.status = 'Saving…'; paint(); lockForms(true);
|
||||
try {
|
||||
const workflow = shape(d.flow);
|
||||
await writing(org, async () => written(org, s, scope, name, workflow, await saveFlow(org, s, { scope, name, revision: d.revision, workflow })));
|
||||
drafts.delete(key);
|
||||
notes.set(key, `Saved ${name}.`);
|
||||
say(`Saved ${name}.`);
|
||||
// Focus stays in the form it was saved from, so the line saying Saved stays in view (at 390 a jump to the
|
||||
// graph node put it below the fold).
|
||||
paint(selected() ? 'wfg-f-title' : 'wfg-m-title');
|
||||
} catch (error) {
|
||||
d.busy = false;
|
||||
d.status = kept[error.code] ?? `Not saved: ${error.message} Your change is kept.`;
|
||||
say(d.status);
|
||||
paint('wfg-save'); lockForms(false);
|
||||
}
|
||||
}
|
||||
async function remove({ org, name, scope, s, key }) {
|
||||
const d = drafts.get(key);
|
||||
if (!d || d.busy) return;
|
||||
d.busy = true; paint(); lockForms(true);
|
||||
try {
|
||||
// The revision of the workflow the page shows (settle moves it on only while this workflow is unchanged):
|
||||
// a change made to it since is refused, not deleted over.
|
||||
await writing(org, async () => written(org, s, scope, name, null, await removeFlow(org, s, { scope, name, revision: d.revision })));
|
||||
drafts.delete(key);
|
||||
notes.set(dkey(org, '', ''), `Deleted ${name}.`);
|
||||
say(`Deleted ${name}.`);
|
||||
location.hash = `${orgHash(org)}/workflows`;
|
||||
} catch (error) {
|
||||
d.busy = false; d.confirm = false; d.atBar = true;
|
||||
// Recheck B: Discard shows only with a pending change; without one the next read draws the current version.
|
||||
d.status = error.code === 'revision-conflict' ? `Not deleted: the organization file changed this workflow since the page read it. ${changed(d) ? 'Discard to load the current version.' : 'The page shows the current version at its next read.'}` : `Not deleted: ${error.message}`;
|
||||
say(d.status);
|
||||
paint('wfg-delete'); lockForms(false);
|
||||
}
|
||||
}
|
||||
// SP17: after a change in a panel form, the bar and the form's own buttons follow it without redrawing the
|
||||
// form, so the caret stays where it is.
|
||||
function follow(at, d, form) {
|
||||
const old = document.querySelector('#bus-view [data-wfg-page] [data-wfg-bar]');
|
||||
if (old) old.outerHTML = bar(at.org, at.s, at.scope, at.name, d, true);
|
||||
const save = form.querySelector('[data-wfg-save]');
|
||||
if (save) save.disabled = !pending(d) || !!d.busy;
|
||||
form.querySelector('[data-wfg-cancel]')?.toggleAttribute('hidden', !editDirty(d.edit));
|
||||
form.toggleAttribute('data-live-hold', form.matches('[data-wfg-step-form]') ? editDirty(d.edit) : pending(d));
|
||||
// A status from before this change no longer applies.
|
||||
const text = formStatus(at.org, at.scope, at.name, d), line = form.querySelector('[data-wfg-status]');
|
||||
if (line && !text) line.remove(); else if (line) line.textContent = text;
|
||||
// The graph draws the step as typed, so the box shows the change before Save.
|
||||
const frame = document.querySelector('#bus-view [data-wfg-page] [data-wfg-frame]');
|
||||
if (frame && form.matches('[data-wfg-step-form]')) frame.innerHTML = graph(at.org, at.s, at.scope, at.name, preview(d), Number(form.dataset.wfgStepForm) + 1);
|
||||
}
|
||||
// Every change in a form goes into the page's state at once, so any repaint draws what was entered.
|
||||
document.addEventListener('input', ev => {
|
||||
const form = ev.target.closest('[data-wfg-form]');
|
||||
if (!form) return;
|
||||
if (form.matches('[data-wfg-newform]')) { const f = newForms.get(shown.org); if (f) readForm(form, f); return; }
|
||||
const at = here(form);
|
||||
if (!at) return;
|
||||
if (form.matches('[data-wfg-add-form]')) { const d = drafts.get(at.key); if (d?.edit) readForm(form, d.edit); return; }
|
||||
const d = draftFor(at.org, at.s, at.scope, at.name) ?? drafts.get(at.key);
|
||||
if (!d || d.busy) return;
|
||||
d.status = ''; d.atBar = false;
|
||||
if (form.matches('[data-wfg-meta-form]')) {
|
||||
d.flow.title = form.elements.title.value;
|
||||
d.flow.description = form.elements.description.value;
|
||||
return follow(at, d, form);
|
||||
}
|
||||
const i = Number(form.dataset.wfgStepForm);
|
||||
if (!(d.edit?.mode === 'edit' && d.edit.i === i)) { if (!d.flow.steps[i]) return; park(d, i); openForm(d, 'edit', i, d.flow.steps[i]); }
|
||||
readForm(form, d.edit);
|
||||
follow(at, d, form);
|
||||
});
|
||||
document.addEventListener('submit', ev => {
|
||||
const form = ev.target.closest?.('[data-wfg-form]');
|
||||
if (!form) return;
|
||||
ev.preventDefault();
|
||||
if (form.matches('[data-wfg-newform]')) {
|
||||
const org = shown.org, s = states.get(org), f = newForms.get(org);
|
||||
if (!f || !s?.data?.writable) return;
|
||||
readForm(form, f);
|
||||
const step = { title: f.title, state: f.state, roles: f.roles };
|
||||
const refused = refusal(s, { isNew: true, scope: f.scope, name: f.name, steps: [step] })
|
||||
|| (drafts.get(dkey(org, f.scope, f.name))?.isNew ? `A new workflow named ${f.name} is already open here, not saved yet.` : '');
|
||||
if (refused) return why(form, f, refused);
|
||||
drafts.set(dkey(org, f.scope, f.name), { isNew: true, base: null, flow: { title: '', description: '', steps: [{ ...step, title: step.title.trim() }] }, revision: s.data.revision, edit: null, confirm: false, status: '', busy: false, stale: false });
|
||||
newForms.delete(org);
|
||||
notes.delete(dkey(org, f.scope, f.name));
|
||||
location.hash = flowHref(org, f.scope, f.name, 1);
|
||||
return;
|
||||
}
|
||||
const at = here(form);
|
||||
if (!at) return;
|
||||
// Enter in the step or workflow form is its Save.
|
||||
if (!form.matches('[data-wfg-add-form]')) { if (!form.querySelector('[data-wfg-save]')?.disabled) save(at); return; }
|
||||
const d = drafts.get(at.key);
|
||||
if (!d?.edit) return;
|
||||
readForm(form, d.edit);
|
||||
const e = d.edit, st = { title: e.title.trim(), state: e.state, roles: e.roles };
|
||||
const refused = stepRefusal(st, e.i + 1);
|
||||
if (refused) return why(form, e, refused);
|
||||
d.flow.steps.splice(e.i, 0, st);
|
||||
d.edit = null; d.status = '';
|
||||
select(e.i + 1);
|
||||
say(`Added step ${e.i + 1}. Not saved yet.`);
|
||||
paint('wfg-save');
|
||||
});
|
||||
// Escape in a step form is its Cancel or Reset.
|
||||
document.addEventListener('keydown', ev => {
|
||||
if (ev.key !== 'Escape') return;
|
||||
const form = ev.target.closest?.('[data-wfg-add-form],[data-wfg-step-form]');
|
||||
const b = form?.querySelector('[data-wfg-cancel]');
|
||||
if (b && !b.hidden) b.click();
|
||||
});
|
||||
// The organization-switch and restart guards (display.js, console-restart.js) ask before these are lost.
|
||||
function hasDraft() {
|
||||
return [...drafts.values()].some(pending)
|
||||
|| [...newForms.values()].some(f => f.name || f.title.trim() || f.roles.length);
|
||||
}
|
||||
function forget() { drafts.clear(); newForms.clear(); }
|
||||
// The organization page's card: each workflow as a link to its graph, and under it each step as a link to
|
||||
// that step's form (SP17), from the page's one workflow read.
|
||||
function card(org, { stopped = false, label = org } = {}) {
|
||||
const all = `<a href="${esc(`${orgHash(org)}/workflows`)}" data-wfg-all data-focus-key="wfg-all">All workflows</a>`;
|
||||
const h = note => `<div class="ws-sec-h"><h2>Workflows</h2>${note ? `<span class="note">${note}</span>` : ''}${all}</div>`;
|
||||
const heldNote = heldCardNote(org);
|
||||
if (stopped) return `<div class="wfg-card" data-wfg-card data-bus-stopped>${h('')}<p class="ws-panel tight note">Not read: the bus is stopped.</p>${heldNote}</div>`;
|
||||
const s = states.get(org);
|
||||
if (!s?.data) return `<div class="wfg-card" data-wfg-card>${h('')}<p class="ws-panel tight note" data-wfg-error>${esc(s?.error ?? 'Workflows could not be read.')}</p>${heldNote}</div>`;
|
||||
const rows = listed(s).flatMap(([scope, , list]) => list.map(([name, w]) => [scope, name, w]));
|
||||
if (!rows.length) return `<div class="wfg-card" data-wfg-card>${h('none')}<div class="ws-panel tight">${none(org, s, label)}</div>${heldNote}</div>`;
|
||||
const stepLinks = (scope, name, w) => {
|
||||
const steps = stepsOf(w);
|
||||
if (!steps.length) return '';
|
||||
return `<ol class="wfg-card-steps" aria-label="${esc(`Steps of ${w?.title || name}`)}">${steps.map((st, i) => `<li><a href="${esc(flowHref(org, scope, name, i + 1))}" data-wfg-card-step="${i + 1}" data-focus-key="${esc(`wfg-card:${scope}:${name}:${i + 1}`)}" aria-label="${esc(`Change step ${i + 1}, ${st.title ?? ''}`)}">${esc(st.title)}</a></li>`).join('')}</ol>`;
|
||||
};
|
||||
return `<div class="wfg-card" data-wfg-card>${h(String(rows.length))}<ul class="ws-panel tight wfg-cardlist">${rows.map(([scope, name, w]) => `<li><a href="${esc(flowHref(org, scope, name))}" data-wfg-card-item data-focus-key="${esc(`wfg-card:${scope}:${name}`)}"><strong>${esc(w?.title || name)}</strong> <span class="muted">${count(stepsOf(w).length)}${scope ? `, project ${esc(scope)}` : ''}</span></a>${stepLinks(scope, name, w)}</li>`).join('')}</ul>${heldNote}</div>`;
|
||||
}
|
||||
// SP17: a step link on the card lands in that step's title field, ready to type (bus.js asks landed() after
|
||||
// the page it opens is drawn, in place of focusing the heading).
|
||||
let landing = null;
|
||||
function landed() {
|
||||
const want = landing;
|
||||
landing = null;
|
||||
if (!want || location.hash !== want) return false;
|
||||
const form = stepFormEl(), f = form?.elements.title;
|
||||
if (!f) return false;
|
||||
// The title and the Save under it both in view (at 390 Save was below the fold), the title winning on a short screen.
|
||||
f.focus({ preventScroll: true });
|
||||
form.querySelector('[data-wfg-save]')?.scrollIntoView({ block: 'nearest' });
|
||||
f.scrollIntoView({ block: 'nearest' });
|
||||
f.setSelectionRange(f.value.length, f.value.length);
|
||||
say(`Step ${Number(form.dataset.wfgStepForm) + 1}, ${f.value}. Change it and press Save.`);
|
||||
return true;
|
||||
}
|
||||
document.addEventListener('click', ev => {
|
||||
if (ev.button !== 0 || ev.metaKey || ev.ctrlKey || ev.shiftKey || ev.altKey) return;
|
||||
const cardStep = ev.target.closest('[data-wfg-card-step]');
|
||||
if (cardStep) { landing = cardStep.getAttribute('href'); return; }
|
||||
// A step box or a step link in the details selects that step in the address (setQuery repaints). The open
|
||||
// step's edit goes into the pending workflow first; one the save check refuses keeps the step selected.
|
||||
const link = ev.target.closest('[data-wfg-step],[data-wfg-go]');
|
||||
if (link && WS()?.setQuery) {
|
||||
ev.preventDefault();
|
||||
const at = here(link), d = at && drafts.get(at.key);
|
||||
if (d && carry(d)) return toTitle();
|
||||
WS().setQuery({ step: link.dataset.wfgStep ?? link.dataset.wfgGo });
|
||||
return;
|
||||
}
|
||||
// Apply a pack: the pack picker on the organization page, scrolled into view.
|
||||
const apply = ev.target.closest('a[data-wfg-apply]');
|
||||
if (!apply) return;
|
||||
const show = () => { const p = document.querySelector('[data-packs]'); if (!p) return false; p.scrollIntoView({ block: 'start' }); return true; };
|
||||
if (location.hash === apply.getAttribute('href') && show()) { ev.preventDefault(); return; }
|
||||
const until = Date.now() + 8000;
|
||||
const wait = () => { if (location.hash === apply.getAttribute('href') && document.querySelector('[data-org-dashboard] [data-packs]')) setTimeout(show, 0); else if (Date.now() < until) setTimeout(wait, 60); };
|
||||
setTimeout(wait, 60);
|
||||
});
|
||||
// Crossing the narrow breakpoint redraws the graph in the other direction.
|
||||
window.matchMedia(NARROW).addEventListener('change', () => {
|
||||
if (document.querySelector('[data-wfg-graph]')) document.dispatchEvent(new CustomEvent('mosaic-workspace-render'));
|
||||
});
|
||||
// section(): the organization page's old form editor is gone (SP17); workspace.js still asks for it.
|
||||
const section = () => '';
|
||||
window.MosaicWorkflows = { load, section, page, card, hasDraft, forget, landed };
|
||||
})();
|
||||
@@ -5,7 +5,12 @@
|
||||
const read = async path => {
|
||||
const response = await fetch(path, { cache: 'no-store', redirect: 'manual' });
|
||||
// The status travels with the failure, so a caller can tell a refusal (403) from a bus that is down.
|
||||
if (!response.ok || response.type === 'opaqueredirect') { const error = new Error('Read unavailable'); error.status = response.type === 'opaqueredirect' ? 0 : response.status; throw error; }
|
||||
// E2E6 P2-6: the server's refusal code and its redacted message travel too, so a section can say why.
|
||||
if (!response.ok || response.type === 'opaqueredirect') {
|
||||
const error = new Error('Read unavailable'); error.status = response.type === 'opaqueredirect' ? 0 : response.status;
|
||||
if (response.type !== 'opaqueredirect') try { const body = await response.json(); if (typeof body?.error === 'string') error.code = body.error; if (typeof body?.message === 'string') error.detail = body.message; } catch { /* no JSON body */ }
|
||||
throw error;
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
const orgPath = (id, path) => `/api/orgs/${encodeURIComponent(id)}/${path}`;
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,10 +1,11 @@
|
||||
import { AUTONOMY_ROUTE, autonomyHTTP } from './autonomy-http.mjs';
|
||||
import { proxyHTTP } from './proxy-http.mjs';
|
||||
import { proxyAdminHTTP } from './proxy-admin.mjs';
|
||||
import { triageHTTP, TRIAGE_PATHS } from './triage-http.mjs';
|
||||
import { createServer } from 'node:http';
|
||||
import { bindTesterSocket, TESTER_ORIGIN } from './tester-socket.mjs';
|
||||
import { readFileSync, openSync, fstatSync, closeSync, constants } from 'node:fs';
|
||||
import { timingSafeEqual, randomUUID } from 'node:crypto';
|
||||
import { timingSafeEqual, randomUUID, createHash } from 'node:crypto';
|
||||
import { resolve } from 'node:path';
|
||||
import { isIP } from 'node:net';
|
||||
import { BusReadError, busStatus as coreBusStatus, subjectOk, sendOutcome } from './bus.mjs';
|
||||
@@ -65,12 +66,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']],
|
||||
@@ -86,6 +87,7 @@ const files = new Map([
|
||||
['/packs.js', ['packs.js', 'text/javascript; charset=utf-8']],
|
||||
['/workflows.js', ['workflows.js', 'text/javascript; charset=utf-8']],
|
||||
['/packs.css', ['packs.css', 'text/css; charset=utf-8']],
|
||||
['/workflows.css', ['workflows.css', 'text/css; charset=utf-8']],
|
||||
...[400, 500, 600, 700].map(w => [`/assets/fonts/manrope-${w}.woff2`, [`assets/fonts/manrope-${w}.woff2`, 'font/woff2']]),
|
||||
...[400, 500, 700].map(w => [`/assets/fonts/jetbrains-mono-${w}.woff2`, [`assets/fonts/jetbrains-mono-${w}.woff2`, 'font/woff2']]),
|
||||
]);
|
||||
@@ -250,6 +252,10 @@ const one = (req, name) => (req.headersDistinct[name]?.length === 1 ? req.header
|
||||
// Q175 phase 1 (#1690): under --sso the writer comes from a session the handler already checked,
|
||||
// so it carries `sso: true` and the public origin. The header-preview signer is read-only.
|
||||
const signedIn = (req, p) => p.sso === true || one(req, p.header) === p.user;
|
||||
// SP14 (#1873): who is signed in, as an opaque stable name the page keys what it stores per person by
|
||||
// (the Assistant's kept pane messages). A hash of the session's subject, never the subject itself. A
|
||||
// Console with no sign-in has one fixed local viewer.
|
||||
const viewerOf = session => (typeof session?.sub === 'string' && session.sub ? createHash('sha256').update(JSON.stringify([String(session.provider ?? ''), String(session.iss ?? ''), session.sub])).digest('hex').slice(0, 32) : 'local');
|
||||
const ownOrigin = p => p.origin ?? `https://${p.host}`;
|
||||
async function busSend(req, res, { send, preview, log }) {
|
||||
if (!signedIn(req, preview)) return json(res, 401, { error: 'sign-in required' });
|
||||
@@ -420,6 +426,7 @@ const INSTANCE_REASONS = {
|
||||
'organization-unknown-instance': 'the business has no such instance; add it instead',
|
||||
'organization-definition-refused': 'this form neither adds nor changes an assistant, and moves no instance to the assistant definition; an assistant changes only in the Assistant section',
|
||||
'organization-launch-not-configured': 'the business file has no launch block, so launch membership can\'t change',
|
||||
'template-system-only': 'that role template is for the system, not for an organization; pick another definition',
|
||||
'organization-no-change': 'the business file already says that',
|
||||
'organization-project-mismatch': 'a project file\'s id differs from its key in the business file; mosaic org config validate shows it',
|
||||
'organization-unresolvable-instance': 'an instance wouldn\'t resolve against a project file; mosaic org config validate shows why',
|
||||
@@ -805,7 +812,7 @@ async function libraryStatusRead(res, read, search) {
|
||||
// `log` takes one line per send attempt that got past sign-in; never the body. `fieldsFile` is for
|
||||
// tests; the field table is otherwise the committed packages/tasks/fields.json.
|
||||
// `agentWrite` (row 194, D7) is `(verb, args) => Promise` for the Agents section's verbs and instance.request.
|
||||
export async function startServer({ host = '127.0.0.1', port = 7330, board = DEFAULT_BOARD, timeout = 20000, bus = null, reads = null, preview = null, sso = null, tester = false, testerSocket = null, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, proxyAdmin = null, processing = null, decisionWrite = null, requestRead = null, requestWrite = null, userOptions = null, federation = null, organizations = null, preselect = null, routes = [], orgAdmin = null, devAllowHosts = [], log = line => console.log(line), fieldsFile = undefined, restart = null, trail = null, boot = randomUUID(), workspaceTimeoutMs = undefined, agentLevels = null } = {}) {
|
||||
export async function startServer({ host = '127.0.0.1', port = 7330, board = DEFAULT_BOARD, timeout = 20000, bus = null, reads = null, preview = null, sso = null, tester = false, testerSocket = null, testerAuthHeader = null, proof = null, testerProofHeader = null, send = null, settingsWrite = null, projectFiles = null, projectFile = null, projectSave = null, libraryStatus = null, libraryRevert = null, chat = null, nameWrite = null, assistantStop = null, instancesWrite = null, routesWrite = null, agentWrite = null, proxyCall = null, proxyAdmin = null, triage = null, processing = null, decisionWrite = null, requestRead = null, requestWrite = null, userOptions = null, federation = null, organizations = null, preselect = null, routes = [], orgAdmin = null, devAllowHosts = [], log = line => console.log(line), fieldsFile = undefined, restart = null, trail = null, boot = randomUUID(), workspaceTimeoutMs = undefined, agentLevels = null } = {}) {
|
||||
// org-lan-bind: the dev owner on the LAN is an explicit opt-in. `devAllowHosts` names the Host
|
||||
// names (without a port) a remote browser may use; only the dev owner takes them, and only with
|
||||
// them may it bind a non-loopback IPv4 address. SSO, preview and tester listeners stay loopback.
|
||||
@@ -929,7 +936,10 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
if (match) {
|
||||
orgId = match[1];
|
||||
path = `/api/${match[2]}`;
|
||||
} else if (!orgList && path !== '/api/config' && !hook) {
|
||||
} else if (!orgList && path !== '/api/config' && !hook
|
||||
// #1873 triage-host: the Triage routes pass only for the instance owner's own session on the
|
||||
// public name; every other caller gets this Console's unknown /api/ answer. The gate below checks again.
|
||||
&& !(triage && TRIAGE_PATHS.includes(path) && !tester && named && sso !== null && sso.session(req)?.rootOwner === true)) {
|
||||
return json(res, 404, { error: 'org-unavailable' });
|
||||
}
|
||||
}
|
||||
@@ -1042,6 +1052,11 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
if (path.startsWith('/api/proxy/')) return proxyHTTP(req, res, { path, call: proxyCall, named, tester, granted,
|
||||
send, origin: sso ? (localOrigin ?? sso.publicOrigin) : `https://${preview.host}`, user: signer?.user, log });
|
||||
}
|
||||
// #1873 triage-host: the Triage session's two routes answer only the instance owner's own session on
|
||||
// the public name, with no organization selected. Anyone else falls through to the answer an
|
||||
// unknown route gives them, so the routes are not visible to a caller who cannot use them.
|
||||
if (TRIAGE_PATHS.includes(path) && triage && !tester && !granted && named && sso !== null && orgId === null && !hook && currentSession?.rootOwner === true)
|
||||
return triageHTTP(req, res, { path, triage, send: owner.send !== null, origin: localOrigin ?? sso.publicOrigin, log });
|
||||
|
||||
// Row 252: Approve and Deny. The tester listener never offers them. Anywhere else without a signed-in
|
||||
// session on the public name under --sso and --send, they are read-only.
|
||||
@@ -1085,7 +1100,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
return templatesHTTP(req, res, { path, owner, read: requestRead, write: send ? templatesWrite : null,
|
||||
session: ssoSession, live: () => { const live = sso.session(req); return live?.rootOwner === true ? live : null; }, origin: localOrigin ?? sso?.publicOrigin });
|
||||
}
|
||||
if (tester && ['/project-remote.js', '/project-remote.css', '/files.js', '/files.css', '/packs.js', '/packs.css', '/workflows.js'].includes(path)) return json(res, 403, { error: 'owner-only' });
|
||||
if (tester && ['/project-remote.js', '/project-remote.css', '/files.js', '/files.css', '/packs.js', '/packs.css', '/workflows.js', '/workflows.css'].includes(path)) return json(res, 403, { error: 'owner-only' });
|
||||
// Row 194 (#1692, D4.1): the tester also launches and terminates.
|
||||
if (tester && !['GET', 'HEAD'].includes(req.method) && !['/api/instances', '/api/routes', '/api/name', '/api/agent/launch', '/api/agent/terminate'].includes(path) && !TESTER_CHAT_WRITE.test(path))
|
||||
return json(res, 403, { error: 'read-only', sent: false });
|
||||
@@ -1234,7 +1249,7 @@ export async function startServer({ host = '127.0.0.1', port = 7330, board = DEF
|
||||
// `send`: the page shows the composer only where a send can pass (the public name, --send on).
|
||||
// `edit`: the editor shows Save only where a save can pass, the same test as the route's.
|
||||
// `user` and `federation` (FED R6) only when there is one, so the owner's config is unchanged.
|
||||
if (path === '/api/config') return json(res, 200, { board: upstream, ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), ...(proxyAdmin && !tester && !granted && named && sso !== null && currentSession?.rootOwner === true ? { proxyAdmin: true, proxyAdminSend: owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && named && currentSession?.instanceRole === 'operator' && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named });
|
||||
if (path === '/api/config') return json(res, 200, { board: upstream, viewer: viewerOf(currentSession), ...(organizations && preselect ? { preselect } : {}), ...(tester ? { tester: true } : {}), ...(sso ? { sso: true } : {}), ...(sso?.devOwner ? { devOwner: true } : {}), ...(granted ? { user: true, chatGrants } : {}), ...(!tester && !granted && named && sso !== null && requestRead ? { requests: true, requestWrites: Boolean(send && requestWrite), workspaceFiles: true, projectRemotes: true, projectRemoteWrites: Boolean(send && requestWrite) } : {}), ...(hub ? { federation: hub } : {}), ...(organizations ? { orgSetup: !tester && !granted && named && sso !== null && owner.send !== null } : {}), ...(proxyAdmin && !tester && !granted && named && sso !== null && currentSession?.rootOwner === true ? { proxyAdmin: true, proxyAdminSend: owner.send !== null } : {}), ...(triage && !tester && !granted && named && sso !== null && orgId === null && currentSession?.rootOwner === true ? { triage: true, triageSend: owner.send !== null } : {}), send: !organizations && !tester && Boolean(send) && named, ...(organizations && orgId ? { chatSend: !tester && Boolean(send) && named && orgBusHealthy, settingsSend: !tester && !granted && Boolean(send) && named && orgBusHealthy } : {}), boot, consoleRestart: !tester && named && currentSession?.instanceRole === 'operator' && owner.send !== null && restart !== null && trail !== null, decide: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(decisionWrite) && named && sso !== null, edit: !organizations && !tester && !granted && Boolean(send) && Boolean(projectSave) && named, northStarApprove: (!organizations || (orgId !== null && orgBusHealthy)) && !tester && !granted && Boolean(send) && Boolean(projectSave) && Boolean(projectFile) && named });
|
||||
if (path === '/healthz') return json(res, 200, { ok: true, ...(sso ? { sso: sso.health() } : {}) });
|
||||
if (path === '/favicon.ico') { res.writeHead(204); return res.end(); }
|
||||
const file = files.get(path);
|
||||
|
||||
@@ -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,60 @@
|
||||
// #1873 triage-host: the command cards a Triage reply may carry (design section 4). The agent
|
||||
// proposes a card as `{ step, org }` in a fenced ```cards block of its reply. The server keeps a card
|
||||
// only when its keys are exactly step and org, its step is one of CARD_STEPS and its org is in the
|
||||
// registry, and it renders the command text itself from the fixed map below. Anything else is
|
||||
// dropped and counted. The rest of the reply is plain text: control characters are removed and it
|
||||
// is clipped. A card has no Run action; the owner copies the command into a terminal.
|
||||
|
||||
import { ID_PATTERN } from "../../organization/src/vocabulary.mjs";
|
||||
|
||||
export const CARD_STEPS = Object.freeze({
|
||||
// On a --dev-local-owner Console the bus starts in that mode, as the Organization page's own step says.
|
||||
"bus-start": (org, { devOwner = false } = {}) => `mosaic bus start ${org}${devOwner === true ? " --dev-local-owner" : ""} --detach`,
|
||||
"bus-restart": (org) => `mosaic bus restart ${org}`,
|
||||
"bus-recover": (org) => `mosaic bus recover ${org}`,
|
||||
"bus-stop": (org) => `mosaic bus stop ${org}`,
|
||||
"org-config-validate": (org) => `mosaic org config validate ${org}`,
|
||||
});
|
||||
export const MAX_CARDS = 5;
|
||||
export const MAX_TEXT = 8000;
|
||||
const FENCE = /```cards[ \t]*\r?\n([\s\S]*?)\r?\n?```/g;
|
||||
|
||||
// Plain text: no control characters other than newline and tab, and no more than MAX_TEXT.
|
||||
export function plainText(value, max = MAX_TEXT) {
|
||||
if (typeof value !== "string") return "";
|
||||
// eslint-disable-next-line no-control-regex
|
||||
return value.replace(/\r\n?/g, "\n").replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u061c\u180e\u2028\u2029\ufeff---]/g, "").slice(0, max);
|
||||
}
|
||||
|
||||
// One card, or null. orgIds is the set of registry ids the snapshot read.
|
||||
export function validateCard(card, orgIds, opts = {}) {
|
||||
if (!card || typeof card !== "object" || Array.isArray(card) || Object.getPrototypeOf(card) !== Object.prototype) return null;
|
||||
const keys = Object.keys(card);
|
||||
if (keys.length !== 2 || !keys.includes("step") || !keys.includes("org")) return null;
|
||||
const { step, org } = card;
|
||||
if (typeof step !== "string" || !Object.hasOwn(CARD_STEPS, step)) return null;
|
||||
if (typeof org !== "string" || !ID_PATTERN.test(org) || !orgIds?.has?.(org)) return null;
|
||||
return { step, org, command: CARD_STEPS[step](org, opts) };
|
||||
}
|
||||
|
||||
// The reply split into its plain text and the cards the server keeps.
|
||||
export function extractCards(reply, orgIds, opts = {}) {
|
||||
const source = typeof reply === "string" ? reply : "";
|
||||
const cards = [];
|
||||
let dropped = 0;
|
||||
const seen = new Set();
|
||||
const text = source.replace(FENCE, (_, body) => {
|
||||
let parsed;
|
||||
try { parsed = JSON.parse(body); } catch { dropped += 1; return ""; }
|
||||
const list = Array.isArray(parsed) ? parsed : [parsed];
|
||||
for (const item of list) {
|
||||
const card = validateCard(item, orgIds, opts);
|
||||
const key = card && `${card.step} ${card.org}`;
|
||||
if (!card || seen.has(key) || cards.length >= MAX_CARDS) { dropped += 1; continue; }
|
||||
seen.add(key);
|
||||
cards.push(card);
|
||||
}
|
||||
return "";
|
||||
});
|
||||
return { text: plainText(text.trim()), cards, dropped };
|
||||
}
|
||||
@@ -0,0 +1,525 @@
|
||||
// #1873 triage-host: the Triage session's host, held by the Console (design sections 1 and 4).
|
||||
//
|
||||
// Directories, under <dataRoot>/triage/ (0700, real directories owned by this user):
|
||||
// health/ the snapshot the Console writes (triage-snapshot.mjs); mounted read-only
|
||||
// agent/ the session's own run directory; mounted read-write, with bundle/, session.json and
|
||||
// relay.sock read-only inside it
|
||||
// host/ the transcript (transcript.jsonl, 0600) and the runner's log; never mounted
|
||||
// Nothing else of the data root, no org root, bus socket, config directory or secrets directory is
|
||||
// in the sandbox (packages/seat/src/sandbox.mjs, hostedBinds).
|
||||
//
|
||||
// The session starts on the owner's first message, never when the Console starts. Its spawn
|
||||
// environment is SPAWN_ENV_ALLOW and the route's ROUTE_ENV_ALLOW names; bwrap adds HOME and TMPDIR.
|
||||
// No MOSAIC_CONFIG, no MOSAIC_BUS_* and no Console variable reaches it.
|
||||
//
|
||||
// The relay is the only broker the runner reaches. It answers the runner's own lifecycle verbs with
|
||||
// fixed answers that change nothing, hands over the owner's queued messages, and keeps a
|
||||
// message.send only when it is addressed to "human": that text goes into the transcript and its
|
||||
// cards are checked (triage-cards.mjs). Every other verb, decision.raise and event.emit included,
|
||||
// a send to anyone else and a call with the wrong capability are refused with RELAY_REFUSED.
|
||||
//
|
||||
// A model route comes from an injected `route` ({ admit() }). Without one nothing launches and the
|
||||
// state says so. The route's answer names the harness: adapter, its mounts, harnessEnv, turnEnd,
|
||||
// model and provider, and the proxy variables for the spawn. Over the cap the route refuses until
|
||||
// the next day, and the message is refused with its code.
|
||||
//
|
||||
// #1873 triage-fences: the host checks a copy of the route's answer before it writes anything, and
|
||||
// uses only that copy. harnessEnv names must be in the harness module's envNames and pass
|
||||
// refusedHarnessName; values are clean strings. env holds only ROUTE_ENV_ALLOW names, with
|
||||
// ANTHROPIC_BASE_URL loopback http on a port (the host's proxyPort when it names one) and the
|
||||
// token matching the host's tokenPattern when it names one. The adapter and the mounts pass
|
||||
// checkHostedRoute (sandbox.mjs) against the module's installRoots and the data root, the config
|
||||
// directory and HOME (HOME not counted against the stack's own code), here and again in
|
||||
// hostedBinds. A refused answer reaches no spawn, answers triage-route-invalid, and writes
|
||||
// ROUTE_REFUSED to the transcript; a refusal at the binds also removes what the start wrote.
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
import { randomBytes, timingSafeEqual } from "node:crypto";
|
||||
import { appendFileSync, closeSync, lstatSync, mkdirSync, openSync, readFileSync, rmSync, chmodSync, writeFileSync } from "node:fs";
|
||||
import { createServer } from "node:net";
|
||||
import { homedir } from "node:os";
|
||||
import { dirname, join } from "node:path";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { BWRAP, REPO, RUNNER_FILES, checkHostedRoute, hostedArgv, hostedBinds } from "../../seat/src/sandbox.mjs";
|
||||
import { isProviderVariable } from "../../seat/src/session.mjs";
|
||||
import { configDir as systemConfigDir } from "../../organization/src/organization-config.mjs";
|
||||
import { typedTools } from "../../harness/src/tools.mjs";
|
||||
import { builtinTools } from "../../harness/src/bundle.mjs";
|
||||
import { FOUNDER_ENV } from "../../harness/src/runner.mjs";
|
||||
import { extractCards, plainText } from "./triage-cards.mjs";
|
||||
import { SNAPSHOT_FILE, writeSnapshot } from "./triage-snapshot.mjs";
|
||||
|
||||
export const RUNNER = RUNNER_FILES[0];
|
||||
export const RELAY_REFUSED = "triage-refused";
|
||||
export const MESSAGE_MAX = 4000;
|
||||
export const TRANSCRIPT_KEEP = 200;
|
||||
export const QUEUE_MAX = 20;
|
||||
export const UNANSWERED = "Triage stopped before it answered this message. Send it again.";
|
||||
export const NOT_STARTED = "Triage did not start, so this message was not delivered.";
|
||||
export const NOT_TAKEN = "Triage stopped before it read this message. Send it again.";
|
||||
export const ROUTE_REFUSED = "Triage did not start: the model route's answer did not pass the host's checks, so this message was not delivered.";
|
||||
// An over-cap answer is held for at most this long; a later time is not taken.
|
||||
export const CAP_HOLD_MAX_MS = 48 * 3600 * 1000;
|
||||
const ISO_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,3})?Z$/;
|
||||
const LINE_MAX = 64 * 1024;
|
||||
// The id the host gives each owner message. A reply may name only such an id.
|
||||
const OWNER_ID = /^owner-[0-9a-f]{12}$/;
|
||||
const CAP = /^[0-9a-f]{64}$/;
|
||||
|
||||
// The spawn's environment: these names from the Console's own environment, PATH fixed, and the
|
||||
// route's proxy variables. bwrap sets HOME and TMPDIR inside.
|
||||
export const SPAWN_ENV_ALLOW = Object.freeze(["PATH", "LANG", "LC_ALL", "TZ", "TERM"]);
|
||||
export const ROUTE_ENV_ALLOW = Object.freeze(["ANTHROPIC_BASE_URL", "ANTHROPIC_AUTH_TOKEN"]);
|
||||
const ENV_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
||||
const ENV_VALUE_MAX = 4096;
|
||||
const HARNESS_ENV_MAX = 64;
|
||||
// Refused in harnessEnv even when the harness module declares them: the runner's own MOSAIC_*
|
||||
// values, loader, libc and interpreter hooks, the shell's start files, a tool's config directory
|
||||
// and the founder's, an askpass program, a CA bundle or a base URL. A provider name (every ANTHROPIC_* among them) goes through route env or nowhere.
|
||||
const REFUSED_PREFIX = /^(MOSAIC_|NODE_|LD_|DYLD_|PYTHON|BASH_|GIT_|MALLOC_|NPM_CONFIG_|XDG_)/;
|
||||
const REFUSED_SUFFIX = /_(DIR|CONF|CONFIG|ASKPASS|CA_BUNDLE|BASE_URL)$/;
|
||||
const REFUSED_NAMES = new Set([
|
||||
"PATH", "HOME", "TMPDIR", "BASH_ENV", "ENV", "SSH_AUTH_SOCK", "SHELL", "SHELLOPTS", "BASHOPTS", "PS4", "IFS", "CDPATH",
|
||||
"GLOBIGNORE", "PROMPT_COMMAND", "ZDOTDIR", "PERL5OPT", "PERL5LIB", "RUBYOPT", "RUBYLIB", "PERLLIB", "LESSOPEN", "LESSCLOSE", "HOSTALIASES", "HTTP_PROXY", "HTTPS_PROXY", "ALL_PROXY", "NO_PROXY",
|
||||
"GCONV_PATH", "GLIBC_TUNABLES", "LOCPATH", "OPENSSL_CONF", "OPENSSL_ENGINES", "OPENSSL_MODULES", "SSL_CERT_FILE", "SSL_CERT_DIR",
|
||||
"JAVA_TOOL_OPTIONS", "_JAVA_OPTIONS", "JDK_JAVA_OPTIONS",
|
||||
...FOUNDER_ENV,
|
||||
]);
|
||||
export const refusedHarnessName = (k) => typeof k !== "string" || !ENV_NAME.test(k) || REFUSED_PREFIX.test(k) || REFUSED_SUFFIX.test(k) || REFUSED_NAMES.has(k) || isProviderVariable(k);
|
||||
// No control character of any kind (C0, DEL, C1) and no line or paragraph separator.
|
||||
const cleanValue = (v) => typeof v === "string" && v.length <= ENV_VALUE_MAX && !/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/.test(v);
|
||||
const plainObject = (o) => o !== null && typeof o === "object" && !Array.isArray(o) && [Object.prototype, null].includes(Object.getPrototypeOf(o));
|
||||
// The proxy is on this machine: http, 127.0.0.1, a port, nothing after it.
|
||||
const LOOPBACK_URL = /^http:\/\/127\.0\.0\.1:([1-9][0-9]{0,4})$/;
|
||||
const HARNESS_NAME = /^[a-z][a-z0-9-]{0,31}$/;
|
||||
|
||||
// The harness module a route names, from the repository's own tree; null when there is none.
|
||||
async function repoHarnessModule(name) {
|
||||
if (!HARNESS_NAME.test(name)) return null;
|
||||
const file = join(REPO, "packages", "plugins", "harness", name, "index.mjs");
|
||||
try { if (!lstatSync(file).isFile()) return null; } catch { return null; }
|
||||
return import(pathToFileURL(file).href);
|
||||
}
|
||||
|
||||
export function triageEnv(source, routeEnv = {}, { node = process.execPath } = {}) {
|
||||
const env = { PATH: `${dirname(node)}:/usr/bin:/bin` };
|
||||
for (const k of SPAWN_ENV_ALLOW) if (k !== "PATH" && typeof source?.[k] === "string" && source[k].length <= 256) env[k] = source[k];
|
||||
for (const k of ROUTE_ENV_ALLOW) if (typeof routeEnv?.[k] === "string" && routeEnv[k].length <= 4096) env[k] = routeEnv[k];
|
||||
return env;
|
||||
}
|
||||
|
||||
// The relay's fixed answers. None of them reaches a bus or changes anything.
|
||||
const LIFECYCLE = Object.freeze({
|
||||
"role.claim": () => ({ library: false }),
|
||||
state: () => ({ launch: { state: "on", at: null, event: null }, tasks: { open: [], total: 0, cap: 0 } }),
|
||||
"processing.status": () => ({ halted: false, invalid: false }),
|
||||
"usage.begin": () => ({}),
|
||||
"usage.end": () => ({}),
|
||||
"role.release": () => ({}),
|
||||
});
|
||||
|
||||
export class TriageError extends Error {
|
||||
constructor(code, message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
}
|
||||
|
||||
function realDir(path, { create = true } = {}) {
|
||||
let st;
|
||||
try {
|
||||
st = lstatSync(path);
|
||||
} catch (e) {
|
||||
if (e.code !== "ENOENT" || !create) throw new TriageError("triage-dir-unsafe", "a Triage directory is missing");
|
||||
mkdirSync(path, { mode: 0o700 });
|
||||
st = lstatSync(path);
|
||||
}
|
||||
if (st.isSymbolicLink() || !st.isDirectory()) throw new TriageError("triage-dir-unsafe", "a Triage directory is not a real directory");
|
||||
if (typeof process.getuid === "function" && st.uid !== process.getuid()) throw new TriageError("triage-dir-unsafe", "a Triage directory is not owned by the Console's user");
|
||||
chmodSync(path, 0o700);
|
||||
}
|
||||
|
||||
// A directory inside agent/, which the session can write: removed whole (rm never follows a link)
|
||||
// and made again, so a link the session left there can't steer a bind or a host write.
|
||||
function freshDir(path) {
|
||||
rmSync(path, { recursive: true, force: true });
|
||||
mkdirSync(path, { mode: 0o700 });
|
||||
}
|
||||
|
||||
export function triagePaths(dataRoot) {
|
||||
const root = join(dataRoot, "triage");
|
||||
return { root, health: join(root, "health"), agent: join(root, "agent"), host: join(root, "host"), transcript: join(root, "host", "transcript.jsonl"), log: join(root, "host", "runner.log") };
|
||||
}
|
||||
|
||||
// The prompt is the role's contract and the host's own lines: where the snapshot is and how a
|
||||
// card is written. It names the snapshot inside the session, never a host path of the data root.
|
||||
export function hostPrompt(contract, { snapshotPath, steps }) {
|
||||
return [
|
||||
contract.trimEnd(),
|
||||
"",
|
||||
"## This host",
|
||||
"",
|
||||
`- The health snapshot is the JSON file ${snapshotPath}. Read it at the start of each turn; it is the only health you can see. A field that says "not read" was not read; say so, never guess it.`,
|
||||
"- Each message arrives as one turn and your final answer goes back to the person. send_message reaches only \"human\"; this host refuses every other call.",
|
||||
"- Propose each fix as a card in one fenced block marked cards, holding a JSON array of objects with exactly two keys, step and org, for example:",
|
||||
"```cards",
|
||||
'[{"step": "bus-start", "org": "alpha"}]',
|
||||
"```",
|
||||
`- step is one of: ${steps.join(", ")}. org is an organization id from the snapshot. The Console writes the command for each card; never write a command yourself. A card with anything else is dropped.`,
|
||||
"",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
function sameCap(a, b) {
|
||||
if (typeof a !== "string" || !CAP.test(a)) return false;
|
||||
return timingSafeEqual(Buffer.from(a), Buffer.from(b));
|
||||
}
|
||||
|
||||
// The relay server. `onSend(body)` keeps a human-bound send; `take()` returns the queued owner
|
||||
// messages; `read(id)` drops one that was answered.
|
||||
export function createRelay({ socket, cap, take, read, onSend, log = () => {} }) {
|
||||
const answer = (conn, value) => { try { conn.end(JSON.stringify(value) + "\n"); } catch {} };
|
||||
const refuse = (conn) => answer(conn, { ok: false, error: RELAY_REFUSED, reason: "the Triage host answers only a message to the person" });
|
||||
const server = createServer((conn) => {
|
||||
let buf = "";
|
||||
let done = false;
|
||||
conn.setTimeout(30_000, () => conn.destroy());
|
||||
conn.on("error", () => {});
|
||||
conn.on("data", (chunk) => {
|
||||
if (done) return;
|
||||
buf += chunk.toString("utf8");
|
||||
if (buf.length > LINE_MAX) { done = true; return refuse(conn); }
|
||||
const nl = buf.indexOf("\n");
|
||||
if (nl < 0) return;
|
||||
done = true;
|
||||
let req;
|
||||
try { req = JSON.parse(buf.slice(0, nl)); } catch { return refuse(conn); }
|
||||
if (!req || typeof req !== "object" || !sameCap(req.cap, cap) || typeof req.verb !== "string") return refuse(conn);
|
||||
const args = req.args && typeof req.args === "object" && !Array.isArray(req.args) ? req.args : {};
|
||||
const verb = req.verb;
|
||||
try {
|
||||
if (Object.hasOwn(LIFECYCLE, verb)) return answer(conn, { ok: true, result: LIFECYCLE[verb]() });
|
||||
if (verb === "message.receive") return answer(conn, { ok: true, result: take() });
|
||||
if (verb === "message.read") { read(args.id); return answer(conn, { ok: true, result: {} }); }
|
||||
if (verb === "message.send" && args.to === "human" && typeof args.body === "string" && args.body.length <= 32768) {
|
||||
// Only an id the host issued is kept. The model writes this field, and the transcript serves it.
|
||||
onSend({ body: args.body, in_reply_to: typeof args.in_reply_to === "string" && OWNER_ID.test(args.in_reply_to) ? args.in_reply_to : null });
|
||||
return answer(conn, { ok: true, result: { id: `triage-${randomBytes(6).toString("hex")}` } });
|
||||
}
|
||||
} catch (e) {
|
||||
log(`triage relay: ${verb} failed: ${e.code ?? "error"}`);
|
||||
}
|
||||
log(`triage relay: refused ${/^[a-z][a-z0-9._-]{0,63}$/.test(verb) ? verb : "a verb"}`);
|
||||
return refuse(conn);
|
||||
});
|
||||
});
|
||||
return new Promise((resolve, reject) => {
|
||||
server.once("error", reject);
|
||||
server.listen(socket, () => {
|
||||
server.off("error", reject);
|
||||
chmodSync(socket, 0o600);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// createTriageHost({ dataRoot, route, readSnapshot, env, node, bwrap, now, devOwner, log })
|
||||
// route { admit() -> { ok: true, adapter, harness, harnessEnv, harnessMounts, turnEnd, model,
|
||||
// provider, env } | { ok: false, code, until? } } or null for no route
|
||||
// readSnapshot async () -> the snapshot (triage-snapshot.mjs composeSnapshot), written to health/
|
||||
// pollInterval the runner's receive interval in ms, for tests; the runner's default otherwise
|
||||
// proxyPort the port ANTHROPIC_BASE_URL must name, or null for any port
|
||||
// tokenPattern a RegExp the whole ANTHROPIC_AUTH_TOKEN must match, or null for no shape check
|
||||
// harnessModule async (name) -> the harness module (envNames, installRoots) or null; the
|
||||
// repository's packages/plugins/harness/<name> by default
|
||||
// home HOME, which no mount may reach outside the stack's own code; the Console user's by default
|
||||
export function createTriageHost({ dataRoot, route = null, readSnapshot = async () => null, env = process.env, node = process.execPath, bwrap = BWRAP, now = () => new Date(), devOwner = false, log = () => {}, roleDir = join(REPO, "roles"), readOnly = [], pollInterval = null, proxyPort = null, tokenPattern = null, harnessModule = repoHarnessModule, home = homedir() }) {
|
||||
if (typeof dataRoot !== "string" || !dataRoot.startsWith("/")) throw new TriageError("triage-no-data-root", "no data root");
|
||||
if (proxyPort !== null && !(Number.isInteger(proxyPort) && proxyPort > 0 && proxyPort <= 65535)) throw new TypeError("proxyPort must be a port number or null");
|
||||
if (tokenPattern !== null && !(tokenPattern instanceof RegExp)) throw new TypeError("tokenPattern must be a RegExp or null");
|
||||
if (typeof harnessModule !== "function") throw new TypeError("harnessModule must be a function");
|
||||
const tokenShape = tokenPattern && new RegExp(`^(?:${tokenPattern.source})$`, tokenPattern.flags.replace(/[gmy]/g, ""));
|
||||
// What no mount source may lie in or around, besides the run directory and the fixed list. HOME
|
||||
// does not refuse the stack's own code when the stack runs from under it (a copy or a worktree).
|
||||
const protectedPaths = [dataRoot, systemConfigDir(env), home];
|
||||
const codeRoot = REPO;
|
||||
const paths = triagePaths(dataRoot);
|
||||
const role = JSON.parse(readFileSync(join(roleDir, "triage.json"), "utf8"));
|
||||
const contract = readFileSync(join(roleDir, role.contract), "utf8");
|
||||
let last = null; // the last snapshot written
|
||||
let lastAt = null; // when it was written, in ms
|
||||
let child = null;
|
||||
let relay = null;
|
||||
let starting = null;
|
||||
let lastExit = null;
|
||||
let cap = null;
|
||||
let overCapUntil = null; // the route's over-cap answer, held until its time passes
|
||||
const queue = [];
|
||||
|
||||
const ensureDirs = () => {
|
||||
mkdirSync(dataRoot, { recursive: true, mode: 0o700 });
|
||||
for (const d of [paths.root, paths.health, paths.agent, paths.host]) realDir(d);
|
||||
};
|
||||
|
||||
const append = (entry) => {
|
||||
ensureDirs();
|
||||
const fd = openSync(paths.transcript, "a", 0o600);
|
||||
try { appendFileSync(fd, JSON.stringify(entry) + "\n"); } finally { closeSync(fd); }
|
||||
chmodSync(paths.transcript, 0o600);
|
||||
};
|
||||
|
||||
const transcript = () => {
|
||||
let text = "";
|
||||
try {
|
||||
const st = lstatSync(paths.transcript);
|
||||
if (!st.isFile()) return [];
|
||||
text = readFileSync(paths.transcript, "utf8");
|
||||
} catch { return []; }
|
||||
const out = [];
|
||||
for (const line of text.split("\n")) {
|
||||
if (!line) continue;
|
||||
try { out.push(JSON.parse(line)); } catch {}
|
||||
}
|
||||
return out.slice(-TRANSCRIPT_KEEP);
|
||||
};
|
||||
|
||||
const orgIds = () => new Set(Array.isArray(last?.organizations?.list) ? last.organizations.list.map((o) => o.id) : []);
|
||||
|
||||
// One refresh at a time: a read and a message that arrive together share it.
|
||||
let refreshing = null;
|
||||
const refresh = () => refreshing ??= (async () => {
|
||||
ensureDirs();
|
||||
let snap = null;
|
||||
try { snap = await readSnapshot(); } catch { snap = null; }
|
||||
if (snap && typeof snap === "object") {
|
||||
writeSnapshot(paths.health, snap);
|
||||
last = snap;
|
||||
lastAt = now().getTime();
|
||||
}
|
||||
return last;
|
||||
})().finally(() => { refreshing = null; });
|
||||
|
||||
const writeBundle = (admitted) => {
|
||||
const a = paths.agent;
|
||||
for (const d of ["bundle", "tmp", "work", "home"]) freshDir(join(a, d));
|
||||
mkdirSync(join(a, "work", "health"), { mode: 0o700 });
|
||||
// turns/ goes too: the runner numbers turns from 1 and opens each turn file exclusively, so a
|
||||
// turns/ left by the last run stops the next one at its first turn.
|
||||
for (const f of ["session.json", "relay.sock", "tools.sock", "turn.done", "turns"]) rmSync(join(a, f), { recursive: true, force: true });
|
||||
// The session's history stays across starts, unless the session put something other than a
|
||||
// real directory there.
|
||||
try { realDir(join(a, "session")); } catch { freshDir(join(a, "session")); }
|
||||
const resolved = { limits: { authority: role.authority, tools: role.tools }, definition: "triage", pluginTools: [] };
|
||||
const tools = typedTools({ resolved }).filter((t) => t.name === "send_message");
|
||||
const workspace = join(a, "work");
|
||||
const policy = { harness: admitted.harness, workspace, tools: builtinTools(role.tools), typed: tools.map((t) => t.name), network: role.network, needs: [], credentials: [] };
|
||||
const bundle = { prompt: join(a, "bundle", "prompt.md"), policy: join(a, "bundle", "policy.json"), tools: join(a, "bundle", "tools.json") };
|
||||
const steps = ["bus-start", "bus-restart", "bus-recover", "bus-stop", "org-config-validate"];
|
||||
writeFileSync(bundle.prompt, hostPrompt(contract, { snapshotPath: join(workspace, "health", SNAPSHOT_FILE), steps }), { mode: 0o600, flag: "wx" });
|
||||
writeFileSync(bundle.policy, JSON.stringify(policy, null, 2) + "\n", { mode: 0o600, flag: "wx" });
|
||||
writeFileSync(bundle.tools, JSON.stringify(tools, null, 2) + "\n", { mode: 0o600, flag: "wx" });
|
||||
const session = {
|
||||
bundle, adapter: admitted.adapter, harness: admitted.harness, harnessEnv: admitted.harnessEnv, turnEnd: admitted.turnEnd,
|
||||
workspace, sessionDir: join(a, "session"), toolSocket: join(a, "tools.sock"), turnMarker: join(a, "turn.done"),
|
||||
brokerSocket: join(a, "relay.sock"), business: "system", instance: "triage", run: `triage-${now().toISOString().replace(/[^0-9]/g, "").slice(0, 14)}`,
|
||||
model: admitted.model, provider: admitted.provider ?? "",
|
||||
...(Number.isInteger(pollInterval) && pollInterval >= 100 ? { pollInterval } : {}),
|
||||
};
|
||||
writeFileSync(join(a, "session.json"), JSON.stringify(session, null, 2) + "\n", { mode: 0o600, flag: "wx" });
|
||||
};
|
||||
|
||||
// The route's answer, checked. It returns a copy taken once, so a getter or a later change to
|
||||
// the route's object cannot hand the bundle or the binds anything the checks did not see, and
|
||||
// the module's install roots, for hostedBinds. The log names the fence, never a value.
|
||||
const checkAdmitted = async (answer) => {
|
||||
const refuse = (fence) => {
|
||||
log(`triage host: route refused: ${fence}`);
|
||||
throw new TriageError("triage-route-invalid", "the model route's answer is not usable");
|
||||
};
|
||||
let a;
|
||||
try { a = structuredClone(answer); } catch { refuse("shape"); }
|
||||
if (!plainObject(a) || typeof a.adapter !== "string" || !["marker", "exit"].includes(a.turnEnd)
|
||||
|| typeof a.model !== "string" || !a.model || typeof a.harness !== "string" || !HARNESS_NAME.test(a.harness)
|
||||
|| (a.provider !== undefined && typeof a.provider !== "string")) refuse("shape");
|
||||
let mod = null;
|
||||
try { mod = await harnessModule(a.harness); } catch { mod = null; }
|
||||
const declared = mod?.envNames;
|
||||
if (!Array.isArray(declared) || typeof mod.installRoots !== "function") refuse("module");
|
||||
const he = a.harnessEnv;
|
||||
if (!plainObject(he) || Object.keys(he).length > HARNESS_ENV_MAX) refuse("harness-env");
|
||||
for (const [k, v] of Object.entries(he)) if (refusedHarnessName(k) || !declared.includes(k) || !cleanValue(v)) refuse("harness-env");
|
||||
const re = a.env ?? {};
|
||||
if (!plainObject(re) || Object.entries(re).some(([k, v]) => !ROUTE_ENV_ALLOW.includes(k) || !cleanValue(v))) refuse("route-env");
|
||||
const url = LOOPBACK_URL.exec(re.ANTHROPIC_BASE_URL ?? "");
|
||||
if (!url || Number(url[1]) > 65535 || (proxyPort !== null && Number(url[1]) !== proxyPort)) refuse("route-env");
|
||||
if (tokenShape && !(typeof re.ANTHROPIC_AUTH_TOKEN === "string" && tokenShape.test(re.ANTHROPIC_AUTH_TOKEN))) refuse("route-env");
|
||||
let installRoots;
|
||||
try { installRoots = structuredClone(mod.installRoots({ env })); } catch { refuse("module"); }
|
||||
try {
|
||||
checkHostedRoute({ adapter: a.adapter, harnessMounts: a.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, codeHolder: home, runDir: paths.agent, node });
|
||||
} catch (e) {
|
||||
if (e?.code === "hosted-binds-refused") refuse(e.fence);
|
||||
throw e;
|
||||
}
|
||||
return { admitted: a, installRoots };
|
||||
};
|
||||
|
||||
const start = async (answer) => {
|
||||
const { admitted, installRoots } = await checkAdmitted(answer);
|
||||
ensureDirs();
|
||||
writeBundle(admitted);
|
||||
cap = randomBytes(32).toString("hex");
|
||||
relay = await createRelay({
|
||||
socket: join(paths.agent, "relay.sock"), cap,
|
||||
take: () => {
|
||||
const out = queue.filter((m) => !m.delivered);
|
||||
for (const m of out) m.delivered = true;
|
||||
return out.map(({ id, body, at }) => ({ id, from_role: "human", class: "REQUEST", body, at }));
|
||||
},
|
||||
read: (id) => {
|
||||
const i = queue.findIndex((m) => m.id === id);
|
||||
if (i >= 0) queue.splice(i, 1);
|
||||
},
|
||||
// A reply that names a queued message answers it: the message leaves the queue here, so a
|
||||
// session that ends before its message.read leaves no "unanswered" line under an answer.
|
||||
onSend: ({ body, in_reply_to }) => {
|
||||
const { text, cards, dropped } = extractCards(body, orgIds(), { devOwner: devOwner === true });
|
||||
append({ at: now().toISOString(), from: "triage", text, cards, dropped, ...(in_reply_to ? { in_reply_to } : {}) });
|
||||
const i = in_reply_to ? queue.findIndex((m) => m.id === in_reply_to) : -1;
|
||||
if (i >= 0) queue.splice(i, 1);
|
||||
},
|
||||
log,
|
||||
});
|
||||
let list;
|
||||
try {
|
||||
list = hostedBinds({ runDir: paths.agent, healthDir: paths.health, adapter: admitted.adapter, harnessMounts: admitted.harnessMounts ?? [], installRoots, protectedPaths, codeRoot, codeHolder: home, relaySocket: join(paths.agent, "relay.sock"), node, readOnly });
|
||||
} catch (e) {
|
||||
if (e?.code !== "hosted-binds-refused") throw e;
|
||||
log(`triage host: route refused at the binds: ${e.fence}`);
|
||||
// Nothing of the refused start stays: the relay, its socket, the bundle and session.json go.
|
||||
relay?.close();
|
||||
relay = null;
|
||||
for (const f of ["relay.sock", "session.json", "bundle"]) rmSync(join(paths.agent, f), { recursive: true, force: true });
|
||||
throw new TriageError("triage-route-invalid", "the model route's answer is not usable");
|
||||
}
|
||||
const argv = hostedArgv(list, paths.agent, [node, RUNNER, paths.agent], { bwrap });
|
||||
const out = openSync(paths.log, "a", 0o600);
|
||||
try {
|
||||
child = spawn(argv[0], argv.slice(1), { env: triageEnv(env, admitted.env, { node }), detached: true, stdio: ["pipe", out, out] });
|
||||
} finally {
|
||||
closeSync(out);
|
||||
}
|
||||
const mine = child;
|
||||
const closeRelay = () => {
|
||||
relay?.close();
|
||||
relay = null;
|
||||
rmSync(join(paths.agent, "relay.sock"), { force: true });
|
||||
};
|
||||
mine.on("error", () => {});
|
||||
mine.stdin.on("error", () => {});
|
||||
mine.stdin.end(JSON.stringify({ cap }) + "\n");
|
||||
mine.on("exit", (code, signal) => {
|
||||
if (child !== mine) return;
|
||||
lastExit = { code: Number.isInteger(code) ? code : null, signal: signal ?? null, at: now().toISOString() };
|
||||
child = null;
|
||||
// Every message still queued leaves it, so none holds a slot with no session to answer it, and
|
||||
// the transcript says which: one the session took and never answered, or one it never read.
|
||||
for (const m of queue.splice(0)) {
|
||||
try { append({ at: now().toISOString(), from: "host", in_reply_to: m.id, text: m.delivered ? UNANSWERED : NOT_TAKEN }); } catch { log("triage host: transcript write failed"); }
|
||||
}
|
||||
closeRelay();
|
||||
});
|
||||
// A launcher that cannot run (missing, not executable) fires "error" and never "exit": the start
|
||||
// failed, so the caller writes NOT_STARTED and the host is not left reporting a session.
|
||||
try {
|
||||
await new Promise((resolve, reject) => { mine.once("spawn", resolve); mine.once("error", reject); });
|
||||
} catch (e) {
|
||||
if (child === mine) child = null;
|
||||
closeRelay();
|
||||
log(`triage host: launcher did not run: ${e.code ?? "error"}`);
|
||||
throw new TriageError("triage-start-failed", "the Triage session did not start");
|
||||
}
|
||||
};
|
||||
|
||||
// The cap is the route's to count. Once it answers over the cap with a time in the next two days,
|
||||
// the host refuses without asking again until that time, so a later answer cannot reopen the day.
|
||||
const capUntil = () => {
|
||||
if (overCapUntil !== null && Date.parse(overCapUntil) <= now().getTime()) overCapUntil = null;
|
||||
return overCapUntil;
|
||||
};
|
||||
const admit = async () => {
|
||||
if (!route || typeof route.admit !== "function") return { ok: false, code: "triage-no-route" };
|
||||
const held = capUntil();
|
||||
if (held !== null) return { ok: false, code: "triage-over-cap", until: held };
|
||||
let a;
|
||||
try { a = await route.admit(); } catch { return { ok: false, code: "triage-route-unreadable" }; }
|
||||
if (a?.ok === true) return a;
|
||||
const code = ["triage-no-route", "triage-over-cap"].includes(a?.code) ? a.code : "triage-route-refused";
|
||||
if (code !== "triage-over-cap") return { ok: false, code };
|
||||
const until = typeof a.until === "string" && ISO_TIME.test(a.until) ? Date.parse(a.until) : NaN;
|
||||
const ahead = until - now().getTime();
|
||||
if (!(ahead > 0 && ahead <= CAP_HOLD_MAX_MS)) return { ok: false, code };
|
||||
overCapUntil = new Date(until).toISOString();
|
||||
return { ok: false, code, until: overCapUntil };
|
||||
};
|
||||
|
||||
return {
|
||||
paths,
|
||||
get running() { return child !== null; },
|
||||
get pid() { return child?.pid ?? null; },
|
||||
routeSet: () => Boolean(route && typeof route.admit === "function"),
|
||||
async state() {
|
||||
return {
|
||||
route: this.routeSet() ? "set" : "not set",
|
||||
overCapUntil: capUntil(),
|
||||
running: child !== null,
|
||||
lastExit,
|
||||
snapshot: last,
|
||||
transcript: transcript(),
|
||||
};
|
||||
},
|
||||
refresh,
|
||||
snapshotAt: () => lastAt,
|
||||
// The owner's message: checked, admitted by the route, written to the transcript, queued, and
|
||||
// the session started when it isn't running.
|
||||
async message(raw) {
|
||||
const text = plainText(typeof raw === "string" ? raw : "", MESSAGE_MAX + 1).trim();
|
||||
if (!text) throw new TriageError("triage-message-empty", "the message is empty");
|
||||
if (text.length > MESSAGE_MAX) throw new TriageError("triage-message-too-long", `a message holds at most ${MESSAGE_MAX} characters`);
|
||||
if (queue.length >= QUEUE_MAX) throw new TriageError("triage-busy", "Triage has too many messages waiting");
|
||||
const admitted = await admit();
|
||||
if (!admitted.ok) throw Object.assign(new TriageError(admitted.code, admitted.code === "triage-over-cap" ? "Triage is over its daily cap" : admitted.code === "triage-no-route" ? "no model route is set for Triage" : "the model route refused"), admitted.until ? { until: admitted.until } : {});
|
||||
await refresh();
|
||||
const at = now().toISOString();
|
||||
const id = `owner-${randomBytes(6).toString("hex")}`;
|
||||
append({ at, from: "owner", id, text });
|
||||
queue.push({ id, body: text, at, delivered: false });
|
||||
if (!child) {
|
||||
starting ??= start(admitted).finally(() => { starting = null; });
|
||||
try { await starting; }
|
||||
catch (e) {
|
||||
const i = queue.findIndex((m) => m.id === id);
|
||||
if (i >= 0) queue.splice(i, 1);
|
||||
try { append({ at: now().toISOString(), from: "host", in_reply_to: id, text: e?.code === "triage-route-invalid" ? ROUTE_REFUSED : NOT_STARTED }); } catch {}
|
||||
relay?.close();
|
||||
relay = null;
|
||||
log(`triage host: start failed: ${e.code ?? "error"}`);
|
||||
throw e instanceof TriageError ? e : new TriageError("triage-start-failed", "the Triage session did not start");
|
||||
}
|
||||
}
|
||||
return { id, at };
|
||||
},
|
||||
async stop({ graceMs = 5000 } = {}) {
|
||||
const c = child;
|
||||
if (c) {
|
||||
try { process.kill(-c.pid, "SIGTERM"); } catch {}
|
||||
await new Promise((resolve) => {
|
||||
const t = setTimeout(() => { try { process.kill(-c.pid, "SIGKILL"); } catch {} resolve(); }, graceMs);
|
||||
c.once("exit", () => { clearTimeout(t); resolve(); });
|
||||
});
|
||||
}
|
||||
relay?.close();
|
||||
relay = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// #1873 triage-host: the two owner routes of the Triage session. serve.mjs sends a request here only
|
||||
// for the instance owner's own session (rootOwner, signed in on the public name, no organization
|
||||
// selected); everyone else falls through to the answer an unknown route gives. The read carries the
|
||||
// transcript, the last health snapshot and the cards; the write carries one owner message and also
|
||||
// needs --send and the same-origin checks the org admin routes use. No body, path, token or
|
||||
// exception text reaches a response or a log line.
|
||||
|
||||
export const TRIAGE_PATHS = Object.freeze(["/api/triage", "/api/triage/message"]);
|
||||
export const BODY_MAX = 16384;
|
||||
// A read refreshes the snapshot when the one it holds is older than this.
|
||||
export const SNAPSHOT_MAX_AGE_MS = 30000;
|
||||
export const capMessage = until => `Triage is over its daily token cap. It takes messages again at ${until}.`;
|
||||
export const NO_ROUTE_MESSAGE = "No model route is set for Triage, so Triage will not start. The instance owner sets the route first.";
|
||||
|
||||
const STATUS = Object.freeze({
|
||||
"invalid-request": 400,
|
||||
"triage-message-empty": 400,
|
||||
"triage-message-too-long": 400,
|
||||
"triage-no-route": 409,
|
||||
"triage-route-refused": 409,
|
||||
"triage-route-invalid": 409,
|
||||
"triage-over-cap": 429,
|
||||
"triage-busy": 429,
|
||||
});
|
||||
// Fixed words for each code; the host's own messages are fixed too, but the route never forwards text.
|
||||
const MESSAGES = Object.freeze({
|
||||
"invalid-request": "the request is not a Triage message",
|
||||
"triage-message-empty": "the message is empty",
|
||||
"triage-message-too-long": "the message is too long",
|
||||
"triage-no-route": NO_ROUTE_MESSAGE,
|
||||
"triage-route-refused": "the model route refused to start Triage",
|
||||
"triage-route-invalid": "the model route's answer is not usable",
|
||||
"triage-route-unreadable": "the model route could not be read",
|
||||
"triage-over-cap": "Triage is over its daily token cap and starts again after the time shown",
|
||||
"triage-busy": "Triage has too many messages waiting",
|
||||
"triage-dir-unsafe": "a Triage directory is not safe to use",
|
||||
"triage-start-failed": "the Triage session did not start",
|
||||
"outcome-unknown": "Triage did not answer",
|
||||
});
|
||||
|
||||
const json = (res, status, value) => {
|
||||
res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" });
|
||||
res.end(JSON.stringify(value));
|
||||
};
|
||||
const one = (req, name) => (req.headersDistinct[name]?.length === 1 ? req.headersDistinct[name][0] : null);
|
||||
|
||||
async function readBody(req) {
|
||||
if ((req.headers["content-type"] ?? "").split(";")[0].trim().toLowerCase() !== "application/json") throw Error();
|
||||
const chunks = [];
|
||||
let size = 0;
|
||||
for await (const chunk of req) {
|
||||
size += chunk.length;
|
||||
if (size > BODY_MAX) throw Error();
|
||||
chunks.push(chunk);
|
||||
}
|
||||
const value = JSON.parse(Buffer.concat(chunks));
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw Error();
|
||||
if (Object.keys(value).some((k) => k !== "text") || typeof value.text !== "string") throw Error();
|
||||
return value.text;
|
||||
}
|
||||
|
||||
// The read's answer. `send` tells the drawer whether it may offer the message box.
|
||||
export async function triageView(triage, { send, now = Date.now } = {}) {
|
||||
const held = triage.snapshotAt?.() ?? null;
|
||||
if (held === null || now() - held > SNAPSHOT_MAX_AGE_MS) await triage.refresh();
|
||||
const s = await triage.state();
|
||||
return {
|
||||
route: s.route,
|
||||
...(s.route === "set" ? {} : { routeMessage: NO_ROUTE_MESSAGE }),
|
||||
overCapUntil: s.overCapUntil ?? null,
|
||||
...(s.overCapUntil ? { capMessage: capMessage(s.overCapUntil) } : {}),
|
||||
running: s.running,
|
||||
lastExit: s.lastExit,
|
||||
snapshot: s.snapshot,
|
||||
transcript: s.transcript,
|
||||
send: send === true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function triageHTTP(req, res, { path, triage, send, origin, log = () => {} }) {
|
||||
const done = (status, value) => {
|
||||
// Method, path and status only.
|
||||
log(`${new Date().toISOString()} ${req.method} ${path} ${status}`);
|
||||
return json(res, status, value);
|
||||
};
|
||||
// `code` is always a key of MESSAGES.
|
||||
const refuse = (code, extra = {}) => done(STATUS[code] ?? 503, { error: code, message: MESSAGES[code], ...extra });
|
||||
if (path === "/api/triage") {
|
||||
if (req.method !== "GET") return done(405, { error: "method not allowed" });
|
||||
try { return done(200, await triageView(triage, { send })); }
|
||||
catch { return refuse("outcome-unknown"); }
|
||||
}
|
||||
if (req.method !== "POST") return done(405, { error: "method not allowed" });
|
||||
if (!send) return done(403, { error: "read-only" });
|
||||
if (one(req, "origin") !== origin) return done(403, { error: "cross-origin request refused" });
|
||||
if (one(req, "sec-fetch-site") !== "same-origin") return done(403, { error: "cross-site request refused" });
|
||||
let text;
|
||||
try { text = await readBody(req); } catch { return refuse("invalid-request"); }
|
||||
try {
|
||||
return done(202, await triage.message(text));
|
||||
} catch (error) {
|
||||
const code = typeof error?.code === "string" && Object.hasOwn(MESSAGES, error.code) ? error.code : "outcome-unknown";
|
||||
return refuse(code, code === "triage-over-cap" && typeof error.until === "string" ? { until: error.until } : {});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
// #1873 triage-host: the health snapshot the Console writes for the Triage session (design
|
||||
// section 2). It is composed from reads that already exist, keeps only the fields on the fixed list
|
||||
// below, and is written as one JSON file in <dataRoot>/triage/health/, which the session mounts
|
||||
// read-only. States, times, counts and codes only: no token, key, host path, pid or upstream text.
|
||||
// A read that fails, times out or answers outside its fixed shape says "not read", never a guess.
|
||||
// Run records and logs are a later slice.
|
||||
//
|
||||
// The fixed field list (SNAPSHOT_FIELDS names the top level):
|
||||
// snapshotVersion 1
|
||||
// at when the Console composed it (ISO time)
|
||||
// console { state: "answering", at } the Console wrote this, so it answered at `at`
|
||||
// proxy { initialized, installed, active, healthy, fence } or "not read"
|
||||
// systemConfig { valid, exit, code } or "not read"
|
||||
// organizations { count, list: [ { id, bus, processing, config } ] } or "not read"
|
||||
// bus { state: running | not-answering | stopped | dead, lastStart: { ok, at } | null } or "not read"
|
||||
// processing { halted, invalid } or "not read"
|
||||
// config { valid, exit, code } or "not read"
|
||||
//
|
||||
// The system config check runs scripts/mosaic-config.mjs validate in a child. Its stdout is the
|
||||
// resolved config, so it is never read (stdio "ignore"), and loadSystem is not used. Its stderr
|
||||
// names the config path and data-root facts, so only its first line's leading word is matched
|
||||
// against SYSTEM_CONFIG_CODES; the text itself never leaves this module.
|
||||
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { spawn } from "node:child_process";
|
||||
import { chmodSync, renameSync, rmSync, writeFileSync } from "node:fs";
|
||||
import { join, resolve, dirname } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { ID_PATTERN } from "../../organization/src/vocabulary.mjs";
|
||||
|
||||
const REPO = resolve(dirname(fileURLToPath(import.meta.url)), "..", "..", "..");
|
||||
export const CONFIG_SCRIPT = join(REPO, "scripts", "mosaic-config.mjs");
|
||||
export const ORG_CONFIG_SCRIPT = join(REPO, "packages", "organization", "src", "cli.mjs");
|
||||
export const NOT_READ = "not read";
|
||||
export const SNAPSHOT_VERSION = 1;
|
||||
export const SNAPSHOT_FILE = "snapshot.json";
|
||||
export const SNAPSHOT_FIELDS = Object.freeze(["snapshotVersion", "at", "console", "proxy", "systemConfig", "organizations"]);
|
||||
export const BUS_STATES = Object.freeze(["running", "not-answering", "stopped", "dead"]);
|
||||
const UNIT_ACTIVE = Object.freeze(["active", "inactive", "failed", "activating", "deactivating", "reloading", "unknown"]);
|
||||
export const READ_TIMEOUT_MS = 5000;
|
||||
export const MAX_ORGS = 200;
|
||||
// At most this many organizations are read at once; each read can start a node child for its config check.
|
||||
export const ORG_READS_AT_ONCE = 4;
|
||||
|
||||
// What a failed system config check may say. Each refusal code the validator prints as its first
|
||||
// word passes as itself; a known sentence maps to a fixed code; anything else is the exit's general
|
||||
// code. Nothing else of stderr is kept.
|
||||
const PRINTED_CODES = Object.freeze([
|
||||
"instance-config-mismatch", "instance-name-invalid", "instance-root-unclaimed", "instance-root-mismatch",
|
||||
"proxy-rotate-grace-invalid", "proxy-first-output-invalid", "proxy-config-invalid",
|
||||
]);
|
||||
const SENTENCES = Object.freeze([
|
||||
["configuration not found", "config-not-found"],
|
||||
["configuration is not valid JSON", "config-not-json"],
|
||||
["configuration path must be a regular", "config-not-regular-file"],
|
||||
["configuration file is not readable", "config-unreadable"],
|
||||
["configuration must be a JSON object", "config-not-object"],
|
||||
["unsupported configVersion", "config-version-unsupported"],
|
||||
["unsupported environment", "config-environment-unsupported"],
|
||||
['execution "dataRoot"', "config-data-root-invalid"],
|
||||
["unsupported execution.", "config-execution-unsupported"],
|
||||
["unsupported ", "config-key-unsupported"],
|
||||
]);
|
||||
const EXIT_CODES = Object.freeze({ 1: "config-check-failed", 2: "config-invalid", 3: "config-missing-or-unclaimed", 4: "config-check-usage" });
|
||||
export const SYSTEM_CONFIG_CODES = Object.freeze([...new Set([...PRINTED_CODES, ...SENTENCES.map(([, c]) => c), ...Object.values(EXIT_CODES), "config-check-failed"])]);
|
||||
|
||||
// The org config check (`mosaic org config validate ID`) is read by its exit code alone.
|
||||
const ORG_EXIT_CODES = Object.freeze({ 2: "org-config-invalid", 3: "org-config-system-unreadable", 4: "org-config-check-usage" });
|
||||
export const ORG_CONFIG_CODES = Object.freeze([...Object.values(ORG_EXIT_CODES), "org-config-check-failed"]);
|
||||
|
||||
// stderr's first line, already without its "mosaic-config: " prefix, to one fixed code.
|
||||
export function systemConfigCode(exit, firstLine) {
|
||||
if (exit === 0) return null;
|
||||
const line = typeof firstLine === "string" ? firstLine.replace(/^mosaic-config: /, "") : "";
|
||||
const word = line.match(/^([a-z][a-z0-9-]{2,63})(?::|$)/)?.[1];
|
||||
if (word && PRINTED_CODES.includes(word)) return word;
|
||||
for (const [start, code] of SENTENCES) if (line.startsWith(start)) return code;
|
||||
return EXIT_CODES[exit] ?? "config-check-failed";
|
||||
}
|
||||
|
||||
// A child run for its exit code. stdout is never opened. stderr is read only when `stderr` is
|
||||
// true, at most 4 KiB, and only its first line is returned to the caller in this module.
|
||||
export function runExitOnly(argv, { env, timeoutMs = READ_TIMEOUT_MS, stderr = false } = {}) {
|
||||
return new Promise((done) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawn(argv[0], argv.slice(1), { env, stdio: ["ignore", "ignore", stderr ? "pipe" : "ignore"] });
|
||||
} catch {
|
||||
return done(null);
|
||||
}
|
||||
let err = "";
|
||||
let settled = false;
|
||||
const finish = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
done(value);
|
||||
};
|
||||
const timer = setTimeout(() => {
|
||||
try { child.kill("SIGKILL"); } catch {}
|
||||
finish(null);
|
||||
}, timeoutMs);
|
||||
child.stderr?.on("data", (b) => {
|
||||
if (err.length < 4096) err += b.toString("utf8").slice(0, 4096 - err.length);
|
||||
});
|
||||
child.on("error", () => finish(null));
|
||||
child.on("close", (code, signal) => finish(signal || !Number.isInteger(code) ? null : { exit: code, firstLine: err.split("\n")[0] }));
|
||||
});
|
||||
}
|
||||
|
||||
// { valid, exit, code } from the validator, or "not read" when it did not run to an exit.
|
||||
export async function readSystemConfig({ env = process.env, run = runExitOnly, node = process.execPath, timeoutMs = READ_TIMEOUT_MS } = {}) {
|
||||
const r = await run([node, CONFIG_SCRIPT, "validate"], { env, timeoutMs, stderr: true });
|
||||
if (!r || !Number.isInteger(r.exit)) return NOT_READ;
|
||||
const code = systemConfigCode(r.exit, r.firstLine);
|
||||
return { valid: r.exit === 0, exit: r.exit, code };
|
||||
}
|
||||
|
||||
export async function readOrgConfig(id, { env = process.env, run = runExitOnly, node = process.execPath, timeoutMs = READ_TIMEOUT_MS } = {}) {
|
||||
if (typeof id !== "string" || !ID_PATTERN.test(id)) return NOT_READ;
|
||||
const r = await run([node, ORG_CONFIG_SCRIPT, "validate", id], { env, timeoutMs, stderr: false });
|
||||
if (!r || !Number.isInteger(r.exit)) return NOT_READ;
|
||||
return { valid: r.exit === 0, exit: r.exit, code: r.exit === 0 ? null : ORG_EXIT_CODES[r.exit] ?? "org-config-check-failed" };
|
||||
}
|
||||
|
||||
const ISO = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(\.\d{1,9})?Z$/;
|
||||
const isoOrNull = (v) => (typeof v === "string" && ISO.test(v) ? v : null);
|
||||
const bool = (v) => (typeof v === "boolean" ? v : null);
|
||||
|
||||
// Each read under its own deadline; a throw, a timeout or a null is "not read".
|
||||
async function bounded(fn, timeoutMs) {
|
||||
let timer;
|
||||
try {
|
||||
const value = await Promise.race([
|
||||
Promise.resolve().then(fn),
|
||||
new Promise((resolve) => { timer = setTimeout(() => resolve(NOT_READ), timeoutMs); }),
|
||||
]);
|
||||
return value ?? NOT_READ;
|
||||
} catch {
|
||||
return NOT_READ;
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
|
||||
// The fixed shapes. Anything outside them is "not read".
|
||||
export function proxyFields(status) {
|
||||
if (!status || typeof status !== "object") return NOT_READ;
|
||||
const unit = status.unit && typeof status.unit === "object" ? status.unit : {};
|
||||
const out = {
|
||||
initialized: bool(status.init?.initialized),
|
||||
installed: bool(unit.installed),
|
||||
active: UNIT_ACTIVE.includes(unit.active) ? unit.active : "unknown",
|
||||
healthy: bool(unit.healthy),
|
||||
fence: bool(status.fence?.set),
|
||||
};
|
||||
return out.initialized === null && out.installed === null && out.healthy === null ? NOT_READ : out;
|
||||
}
|
||||
|
||||
// busStatus (packages/cli/src/org-bus.mjs) answers healthy and pid; a refusal from its state check
|
||||
// (a host it cannot account for, a CliError) is a dead host, as the Console's bus revive reads it.
|
||||
export function busFields(status, refusedDead = false) {
|
||||
if (refusedDead) return { state: "dead", lastStart: null };
|
||||
if (!status || typeof status !== "object" || typeof status.healthy !== "boolean") return NOT_READ;
|
||||
const state = status.healthy ? "running" : Number.isSafeInteger(status.pid) ? "not-answering" : "stopped";
|
||||
const boot = status.boot && typeof status.boot === "object" && typeof status.boot.ok === "boolean" && isoOrNull(status.boot.at)
|
||||
? { ok: status.boot.ok, at: status.boot.at } : null;
|
||||
return { state, lastStart: boot };
|
||||
}
|
||||
|
||||
export function processingFields(p) {
|
||||
if (!p || typeof p !== "object" || typeof p.halted !== "boolean") return NOT_READ;
|
||||
return { halted: p.halted, invalid: p.invalid === true };
|
||||
}
|
||||
|
||||
function configFields(c, codes) {
|
||||
if (!c || typeof c !== "object" || typeof c.valid !== "boolean" || !Number.isInteger(c.exit)) return NOT_READ;
|
||||
return { valid: c.valid, exit: c.exit, code: c.code === null || codes.includes(c.code) ? c.code : null };
|
||||
}
|
||||
|
||||
// readers: { orgs() -> [{ id, state }], busStatus(id) -> status (a CliError, or a throw with
|
||||
// `dead: true`, is a dead host), processing(id), orgConfig(id), proxy(), systemConfig() }. Each may be missing.
|
||||
// fn over items, at most `limit` running at once; the results keep the items' order.
|
||||
async function mapLimit(items, limit, fn) {
|
||||
const out = new Array(items.length);
|
||||
let next = 0;
|
||||
const worker = async () => { while (next < items.length) { const i = next++; out[i] = await fn(items[i]); } };
|
||||
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, worker));
|
||||
return out;
|
||||
}
|
||||
|
||||
// The organization stage runs under one deadline, `timeoutMs` from its start, however many
|
||||
// organizations there are: an organization whose reads have not finished by then is "not read", and
|
||||
// one not yet begun is not read at all. A whole snapshot takes at most about two timeouts.
|
||||
export async function composeSnapshot(readers = {}, { now = () => new Date(), timeoutMs = READ_TIMEOUT_MS, clock = Date.now } = {}) {
|
||||
const at = now().toISOString();
|
||||
const read = (name, ...args) => (typeof readers[name] === "function" ? bounded(() => readers[name](...args), timeoutMs) : Promise.resolve(NOT_READ));
|
||||
const [proxyRaw, systemRaw, orgsRaw] = await Promise.all([read("proxy"), read("systemConfig"), read("orgs")]);
|
||||
let organizations = NOT_READ;
|
||||
if (Array.isArray(orgsRaw)) {
|
||||
const active = orgsRaw.filter((o) => o && typeof o === "object" && o.state === "active" && typeof o.id === "string" && ID_PATTERN.test(o.id)).slice(0, MAX_ORGS);
|
||||
const deadline = clock() + timeoutMs;
|
||||
const list = await mapLimit(active, ORG_READS_AT_ONCE, async ({ id }) => {
|
||||
const left = deadline - clock();
|
||||
if (left <= 0) return { id, bus: NOT_READ, processing: NOT_READ, config: NOT_READ };
|
||||
const readOrg = (name) => (typeof readers[name] === "function" ? bounded(() => readers[name](id), left) : NOT_READ);
|
||||
const [bus, processing, config] = await Promise.all([
|
||||
typeof readers.busStatus === "function"
|
||||
? bounded(async () => {
|
||||
try { return busFields(await readers.busStatus(id)); }
|
||||
catch (e) { return e?.name === "CliError" || e?.dead === true ? busFields(null, true) : NOT_READ; }
|
||||
}, left)
|
||||
: NOT_READ,
|
||||
readOrg("processing"),
|
||||
readOrg("orgConfig"),
|
||||
]);
|
||||
return { id, bus: bus === NOT_READ ? NOT_READ : bus, processing: processingFields(processing), config: configFields(config, ORG_CONFIG_CODES) };
|
||||
});
|
||||
organizations = { count: list.length, list };
|
||||
}
|
||||
return {
|
||||
snapshotVersion: SNAPSHOT_VERSION,
|
||||
at,
|
||||
console: { state: "answering", at },
|
||||
proxy: proxyFields(proxyRaw),
|
||||
systemConfig: configFields(systemRaw, SYSTEM_CONFIG_CODES),
|
||||
organizations,
|
||||
};
|
||||
}
|
||||
|
||||
// One file, replaced whole: written beside itself at 0600, then renamed over the last one.
|
||||
export function writeSnapshot(healthDir, snapshot) {
|
||||
const file = join(healthDir, SNAPSHOT_FILE);
|
||||
const temp = join(healthDir, `.${SNAPSHOT_FILE}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`);
|
||||
try {
|
||||
writeFileSync(temp, JSON.stringify(snapshot, null, 2) + "\n", { mode: 0o600 });
|
||||
chmodSync(temp, 0o600);
|
||||
renameSync(temp, file);
|
||||
} finally {
|
||||
rmSync(temp, { force: true });
|
||||
}
|
||||
return file;
|
||||
}
|
||||
Loaded 100 of 143 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user