feat(hub): requirements 023 to 031 and line comments on grant-time code

023 box heads: one head band per box under its top border; in widget mode
its controls join the widget title band.
024 Match card content: merge cards show their diff (the runner previews a
review's tree against its worktree HEAD), every card carries legal and
architecture scores, the null under command cards is gone.
025 Radio speak card: no hint text, a rounder flowing card, a MAYDAY toggle
beside push to talk.
026 widget zoom: zoom a widget's content by keyboard and the context menu.
027 slash skill suggestions: every field that messages agents suggests
skills after a slash, from a skills index the tree timer writes.
028 Resources accounts: an Accounts panel (provider, renewal, resets, usage
and remaining, host-local, emails never in git) and panel checkboxes.
029 Controls layout: Rules and Groups pages laid out.
030 Yes/No answers as buttons, and nothing hides: rows the runner cannot
run stay greyed with the reason.
031 mic in fields.
Line comments (operator 2026-11-24): wherever code waits for a grant
(Waits on Operator, the stream, the review overlay) selected lines or a
right-clicked row take a comment that marks its lines and collects on the
card; Deny opens with them as the reason and Call preselected, Grant sends
them after the signed grant as one post. Requirement 003 decision 4 and
its contract follow.

Tests are written for every requirement and run once on this head.

🎯 Fix: 80 %
💥 Break: 20 %
💸 Tokens: –
⏱️ Velocity: –
🛡️ Security: ~95 %
🏆 Score: 61
🚦 Gate: ⛔ fix 80 % < 90, break 20 % > 5; security ~95 % < 100: ask the operator before the commit

Created-with: https://s.veen.world/skills
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Kevin Veen-BirkenbachandClaude Opus 5.5 committed 2026-11-25 01:22:03 +00:00
1 parent 7d1926e3de
commit 2722cda1b5
120 files changed
+5371 -485

No files matched your search

+32 -14
View File
@@ -29,9 +29,17 @@ changed and what it costs, and a gate means something again.
2026-11-11). A commit that reads the working tree (`-a`, `--all`, `-i`,
`-o`, `-p`, a pathspec, a chain or a wrapper) is not approvable here: the
hook sends no Ask and Claude Code asks instead.
4. **Inline feedback**: selected lines of a diff or a command go back to the
agent as one radio `post` with path, line range, quote and text, through
the right-click menu, the key `f` or a button at the selection.
4. **Inline feedback** (changed by the operator 2026-11-24): selected lines of
a diff or a command, or the code row a right-click hits, take a comment
through the right-click menu, the key `f` or a button at the selection,
wherever code waits for a grant (Waits on Operator, the stream, the review
overlay). The comments collect on their card, mark their lines and go out
with its decision: Deny opens with them as the reason and Call
preselected, so the requesting agent reads them at once; after Grant they
follow as one post `Granted: <title>. Notes:` with one
`<path>:<lines>: <comment>` per comment. Rejected: one immediate post per
selection, which scattered the feedback over many messages and reached
the agent before it knew whether its change was granted.
5. **Kanban**: columns Waiting, Running and Done; Blocked and Stopped become
labels; `operator/*` rows stay off the board; swimlanes P1, P2, P3, P4+ and
Unpinned (by WSJF), collapsible; Done older than 24 h hidden by default.
@@ -210,10 +218,17 @@ flowchart TD
`git ls-files -s -z`, read without writing the index or running a hook;
a different tree at approval
turns it into a deny "staged tree changed since the preview".
- [ ] Selecting lines in a diff or a command and choosing Feedback (right-click
menu, key `f`, or the button at the selection) posts one radio `post` to
the requesting agent with path, line range, quote and text; the feedback
shows under the card.
- [ ] Selecting lines in a diff or a command, or right-clicking a code row,
and choosing Comment (right-click menu, key `f`, or the button at the
selection) saves a comment on the card without sending it: the lines
carry a mark, the comment shows under them and in the card's list,
which can remove it.
- [ ] Deny on a card with comments opens Deny via … with Call preselected
and the comments as the reason; the signed denial carries them to the
requester and clears them.
- [ ] Grant on a card with comments sends them after the signed grant as one
post `Granted: <title>. Notes:` to the requester and clears them; a
failed signature keeps them.
### W2 Kanban
@@ -374,9 +389,11 @@ The work packages meet only through these interfaces:
cap and for withheld content), note empty or "content withheld". An Ask
for a `git commit` carries the same `diff` from `permission_hook.py`; a
body past the hub's limit goes without it.
- **Feedback**: a feedback is a message to the requesting agent through the
existing signed message flow, text `Feedback on <ref> <path>:<from>-<to>:
"<quote>" <text>`.
- **Feedback**: line comments `<path>:<from>[-<to>]: <comment>`, joined by
`;` and a line break, travel as the reason of a signed denial (channel
Call) or, after a signed grant, as the text `Granted: <title>. Notes:` and
the comments of one post through the existing signed message flow. Posts
`Feedback on <ref> …` from before 2026-11-24 still show under their card.
- **Resources**: the host unit writes `samples.jsonl` (`{t, disks: [{mount,
used, total}], cpu, ram, swap, load, gpus: [{name, util, vram_used,
vram_total} | {name, asleep: true}], queue: {waiting, active}}`),
@@ -445,8 +462,8 @@ The work packages meet only through these interfaces:
parents derive; receipt tree sha with unstaged and untracked files;
hook pass and refuse; queue wait on `after`.
- [x] Resources sample parsing on fixtures (df, meminfo, nvidia-smi, asleep
GPU); token offsets; retention fold; diff cap and masking; feedback
payload.
GPU); token offsets; retention fold; diff cap and masking; line
comment text.
- [x] W4 part of the item above: sample parsing on fixtures (df, meminfo,
CPU ticks between runs, nvidia-smi, asleep and unread GPU); token
offsets, a message counted once across fork transcripts; retention
@@ -467,8 +484,9 @@ The work packages meet only through these interfaces:
- [x] The sampler writes rows in a scratch HOME.
- E2E, headless Chromium and Firefox at 1920, 1366 and 390 px:
- [ ] Tasks badge, no Inbox entry, operator cards with bulk actions, review
diff expanded, feedback by right-click and `f` reaching the radio
store.
diff expanded, line comments by right-click and `f` reaching the
requester in the Deny call and the Grant post, kept when signing
fails.
- [ ] Kanban lanes, no Blocked or Stopped column, drags to column, lane and
dependency, Apply with a test passkey, arrows and the dashed queue
line, card popup; forecast two lines and ∞.
+86
View File
@@ -0,0 +1,86 @@
# 023 - Box Heads
## User Story
As the operator, I want every view's controls in one head band right under
its box's top border, the way Home widget title bars sit today, so that
controls never float as a separate card and a widget shows one head.
## Decisions (operator-confirmed 2026-11-23; do not re-litigate)
1. **Head band**: every view whose controls sit in a `.card.controls` box
today (Match, Tasks, Resources, Agents, Artifacts, Kanban, Controls)
gets a `.box-head` band instead: first child of the view's box, flush
with its top and side borders, one line below it, height, padding and
button size of `.home-head`. Rejected: title and controls on one line
without a band (operator: a separate section like the widgets); a sticky
bar inside the box (two bars in widget mode).
2. **Widget mode**: on a Home tile the band's controls move into the tile's
`.home-head`, as Match does today, so a tile has one head; a control
that does not fit stays reachable through the tile's context menu.
3. **Card top edge**: the Match card's gradient bar and head pattern reach
the card's top edge and both rounded corners, with no plain strip.
4. **One helper**: one function builds the band for every view (SPOT).
5. **Timing**: 023 to 031 are implemented serially in number order; tests
are written per requirement and run once after 031 (operator
2026-11-23).
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes" --> A1
subgraph A["🧱 A · Band"]
A1["🧩 Band helper"] --> A2["🪟 Every view uses it"]
A2 --> A3["✍️ Unit and E2E tests written"]
end
A3 --> B1
subgraph B["🏠 B · Widgets and card edge"]
B1["🧩 Tile heads take the controls"] --> B2["🎨 Card top edge flush"]
B2 --> B3["✍️ Tests written"]
end
B3 --> C1
subgraph C["🧪 C · After 030"]
C1["🧪 All tests of 023 to 030 once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Band
- [ ] A DOM scan of Match, Tasks, Resources, Agents, Artifacts, Kanban and
Controls finds one `.box-head` per view as the first child of its box
and no `.card.controls`.
- [ ] Per view the band's top, left and right edges equal the box's inner
edges (0 px apart) at 1920, 1366 and 390.
- [ ] At 1920 a one-row band's height and its button size equal
`.home-head`'s within 1 px; at narrower widths the band wraps into
rows of that height.
### Widget mode
- [ ] Each of these views pinned to Home has no `.box-head` inside
`.home-body`; its controls sit in `.home-head` or its context menu.
### Card edge
- [ ] A computed-style probe of the front Match card finds, for all five
patterns, a 0 px top border, the 6 px bar as the card's own first
background layer, the head flush with the card top and the hatch
mask starting at 6 px.
### Tests
- [ ] Unit: the band helper renders title, count and controls in order.
- [ ] Integration: n/a: client layout only, no server change.
- [ ] E2E: Chromium and Firefox at 1920, 1366 and 390: the scans and the
probe; screenshots per view and tile.
@@ -0,0 +1,92 @@
# 024 - Match Card Content
## User Story
As the operator, I want every Match card to show what it changes and no
stray text, so that I can decide a merge from its card.
## Decisions (operator-confirmed 2026-11-23; do not re-litigate)
1. **Merge diff**: a commit card whose stage shipped no diff gets the diff
of its staged tree against its worktree's HEAD (for a merge: the change
onto the first parent), computed by the hub the way the command card's
merge preview is, bound to the card's tree; "No diff shipped with this
stage." stays only when the tree cannot be read, with the reason.
Rejected: making agents ship merge diffs (old cards stay empty).
2. **No stray text**: the "null" under the Match buttons goes; no text of
the Match view or its Home tile reads "null" or "undefined"; a reason
that is empty or `-` shows no reason line.
3. **Legal and architecture chips**: the score labels gain ⚖️ Legal and
🏛️ Architecture (022 decision 8); a card shows them when its score text
carries them, in the order 🎯 💥 💸 ⏱️ 🛡️ ⚖️ 🏛️ 🏆. The values come from
022 with Quality 004 to 006. Rejected: the hub computing them (operator:
022 owns them).
4. **One count**: the Tasks tab badge and the page title count exactly
the open cards Match shows, from the same server list, and follow every
state poll; today the badge counts unsettled inbox items (operator rows
included) and showed 3 while Match said "0 cards wait" (operator
2026-11-23).
5. **Timing**: 023 decision 5.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes, after 023" --> A1
subgraph A["🔀 A · Merge diff"]
A1["🧩 Diff of the staged tree for diffless commit cards"] --> A2["✍️ Unit and integration tests written"]
end
A2 --> B1
subgraph B["🧹 B · Text and chips"]
B1["🧩 Stray null gone"] --> B2["⚖️ 🏛️ chips in the label file"]
B2 --> B3["✍️ Tests written"]
end
B3 --> C1
subgraph C["🧪 C · After 030"]
C1["🧪 All tests of 023 to 030 once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Merge diff
- [ ] A review of a fixture merge commit with a tree and no diff yields a
card whose files hold the merge's changed files with their hunks.
- [ ] The card turns stale when HEAD moves after it was added.
- [ ] A review whose tree is missing shows "No diff shipped with this
stage." plus the read error.
### Stray text
- [ ] A DOM scan of the Match view and its Home tile over fixture cards of
every kind finds no text node equal to "null" or "undefined".
- [ ] A command card with reason `-` or empty has no `.match-reason`.
### Chips
- [ ] A score text with ⚖️ and 🏛️ values yields eight chips in decision 3's
order; one without them yields no empty ⚖️ or 🏛️ chip.
### Count
- [ ] With fixture state holding three operator rows that are no Match card
and one ask, the badge reads 1 and Match "1 card waits".
- [ ] Answering that ask drops the badge to hidden and the title count away
within one state poll, without a reload.
### Tests
- [ ] Unit: merge diff on a fixture repo (merge, plain commit, missing
tree), chip order, the badge equals the open card count.
- [ ] Integration: `/api/match` serves the merge card with its files and
marks it stale after a HEAD move.
- [ ] E2E: a merge card shows its diff; the text scan; screenshots.
+68
View File
@@ -0,0 +1,68 @@
# 025 - Radio Speak Card
## User Story
As the operator, I want a calm, rounded Speak card with MAYDAY next to PTT,
so that I write without fine print and raise or lift a mayday where I send.
## Decisions (operator-confirmed 2026-11-23; do not re-litigate)
1. **No hint line**: "Post arrives at the end of the turn. Your passkey
signs every message." goes; each channel's meaning moves to its option's
title, the signature note to PTT's tooltip.
2. **MAYDAY toggle**: one button right of the PTT split button. Without an
active mayday it reads MAYDAY, asks in an in-page confirm and sends the
typed text as mayday to all; with one active it is pressed, reads
"Cancel mayday" and lifts it (`clear-mayday`). Mayday leaves the channel
select; the separate cancel button goes. Rejected: Mayday in the select
(two ways to one alarm).
3. **Flowing shape**: one surface without inner boxes: Channel and To as one
joined pill row, the textarea below, footer Record, mic, MAYDAY and PTT
in one row; card radius 14 px, fields 10 px; usable at 390.
4. **Timing**: 023 decision 5.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes, after 024" --> A1
subgraph A["📻 A · Speak card"]
A1["🧹 Hint line gone, titles on the options"] --> A2["🆘 MAYDAY toggle beside PTT"]
A2 --> A3["🎨 One flowing surface"]
A3 --> A4["✍️ Unit and E2E tests written"]
end
A4 --> C1
subgraph C["🧪 C · After 030"]
C1["🧪 All tests of 023 to 030 once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
- [ ] The Speak card holds neither hint sentence.
- [ ] The channel select has no mayday option; every option has a title.
- [ ] MAYDAY is the next sibling of the PTT split button.
- [ ] MAYDAY opens the in-page confirm; Confirm sends one mayday row with
the typed text, Cancel sends nothing.
- [ ] With an active mayday the button has `aria-pressed="true"` and reads
"Cancel mayday"; confirming clears it and it reads MAYDAY again.
- [ ] `grep -n 'window.confirm' orchestrator/templates/page-composer.js`
finds nothing.
- [ ] The card has no descendant `.card`; its radius is 14 px, its fields'
10 px.
- [ ] At 390 the footer fits the card width without horizontal scroll.
### Tests
- [ ] Unit: toggle state from `state.silence`; the select without mayday.
- [ ] Integration: n/a: the server's mayday and clear paths are unchanged.
- [ ] E2E: raise and cancel a mayday, the layout probes at 1920, 1366 and
390; screenshots.
+69
View File
@@ -0,0 +1,69 @@
# 026 - Widget Zoom
## User Story
As the operator, I want to zoom a widget's content in and out, so that a
small tile shows more and a large one stays readable.
## Decisions (operator-confirmed 2026-11-23; do not re-litigate)
1. **Per tile**: each Home pin keeps a zoom of 50 to 200 % in 10 % steps,
default 100 %, in the hub view store (like 017's legend state); it scales
the tile body, never the head. Rejected: browser zoom (whole page); tile
size (the resize handle exists).
2. **Keys**: with a tile focused outside a text field, `+` zooms in, `-`
out, `0` resets; Ctrl+wheel over the body zooms; `?` lists them.
Rejected: Ctrl+plus (browser zoom).
3. **Right-click**: the tile's context menu gets Zoom in, Zoom out and
Reset zoom with the current percent.
4. **Redraw**: charts redraw at the zoomed size; above 100 % the body
scrolls.
5. **Timing**: 023 decision 5.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes, after 025" --> A1
subgraph A["🗄️ A · State"]
A1["🧮 View store key for the tile zoom"] --> A2["✍️ Unit and integration tests written"]
end
A2 --> B1
subgraph B["🔍 B · Zoom"]
B1["⌨️ Keys and Ctrl+wheel"] --> B2["🖱️ Context menu entries"]
B2 --> B3["📈 Charts redraw at the zoomed size"]
B3 --> B4["✍️ E2E tests written"]
end
B4 --> C1
subgraph C["🧪 C · After 030"]
C1["🧪 All tests of 023 to 030 once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
- [ ] Three `+` on a focused tile set its body zoom to 130 %; the head keeps
its size.
- [ ] `0` resets to 100 %; `-` stops at 50 %, `+` at 200 %.
- [ ] Ctrl+wheel up zooms in one step per notch; the plain wheel scrolls.
- [ ] The context menu lists Zoom in, Zoom out and "Reset zoom (130 %)",
each acting as its key.
- [ ] The zoom survives a reload and shows in a second browser; the view
store refuses values outside 50 to 200 or off the 10 % grid with 400.
- [ ] A zoomed chart's SVG width equals the body width divided by the zoom.
- [ ] The `?` help lists the zoom keys.
### Tests
- [ ] Unit: view store validation of the zoom key; key handling.
- [ ] Integration: the zoom persists across a hub restart.
- [ ] E2E: keys, wheel, menu and persistence at 1920, 1366 and 390;
screenshots.
@@ -0,0 +1,83 @@
# 027 - Slash Skill Suggestions
## User Story
As the operator, I want skill suggestions when I type "/" in any message to
agents, so that I call a skill by its exact name without looking it up.
## Decisions (operator-confirmed 2026-11-23; do not re-litigate)
1. **Source**: a host timer writes a skills index (name, description,
source) next to `branch-tree.json`, from `~/.claude/skills`,
`~/.agents/skills` and every repository of the pkgmgr tree
(`.claude/skills`, `.agents/skills`); the hub serves it at `/api/skills`
with name, description and source only. In a field tied to an agent or
card, the skills of its repository rank first. Rejected: mounting every
repository into the hub.
2. **Fields**: every field whose text reaches an agent: radio composer,
agent message, Match feedback and line comments, choice "Other" answers,
reject feedback, rule request replies, diff feedback; one shared helper
attaches to each.
3. **Trigger**: "/" at the field's start or after whitespace opens a list
filtered by the typed prefix (name matches first); ↑/↓ move, Enter or Tab
inserts `/<name>` and a space, Esc closes; "/" inside a word or path
opens nothing;
the global "/" search key keeps working outside text fields.
4. **No send**: picking only inserts text.
5. **Timing**: 023 decision 5.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes, after 026" --> A1
subgraph A["📚 A · Index"]
A1["🗂️ Host timer writes the skills index"] --> A2["🌐 /api/skills"]
A2 --> A3["✍️ Unit and integration tests written"]
end
A3 --> B1
subgraph B["⌨️ B · Suggestions"]
B1["🧩 Shared slash helper"] --> B2["🔗 Attached to every agent field"]
B2 --> B3["✍️ E2E tests written"]
end
B3 --> C1
subgraph C["🧪 C · After 030"]
C1["🧪 All tests of 023 to 030 once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Index
- [ ] The index lists fixture skills of all three sources with their
source; a name in two sources shows once per source.
- [ ] `/api/skills` serves name, description and source only, sorted by
name; no path and no body.
- [ ] A new skill folder shows in `/api/skills` after the next timer run,
without a hub restart.
### Suggestions
- [ ] In each field of decision 2, "/kvb-org-r" lists kvb-org-radio first;
Enter inserts "/kvb-org-radio " at the caret.
- [ ] In a field tied to a core card, a core project skill ranks above a
global one with the same prefix.
- [ ] "a/b" opens no list; Esc closes the list and keeps the text.
- [ ] A test enumerates decision 2's fields and finds the helper on each.
### Tests
- [ ] Unit: frontmatter parser (missing description, no `SKILL.md`), filter
and rank order.
- [ ] Integration: the timer's index over fixture dirs, `/api/skills`,
refresh.
- [ ] E2E: every field of decision 2; screenshots.
@@ -0,0 +1,90 @@
# 028 - Resources Accounts
## User Story
As the operator, I want Resources to show my provider accounts with renewal,
weekly reset and usage, and to pick its panels, so that I see which account
to work on and when the next one resets.
## Decisions (operator-confirmed 2026-11-23; do not re-litigate)
1. **Host only**: accounts are entered in the hub (add, edit, remove) and
stored as `accounts.json` with mode 0600 in the hub's state dir; never in
git, the view store, the radio or a commit; fixtures use example.org.
2. **Fields**: provider, email, renewal (weekday, time), weekly reset
(weekday, time), resubscribe date, autorenew, optional weekly token
limit, optional note; local time.
3. **Active account**: a SessionStart hook writes the session id and
`oauthAccount.emailAddress` from `~/.claude.json` (that field only) into
the council; the hub maps each session's token rows to its account.
Rejected: mounting `~/.claude.json` into the hub (it holds more than the
email); a provider usage API (subscriptions have none).
4. **Usage**: per account: since the last weekly reset, today, total;
remaining = limit minus used since reset, only with a limit; unmapped
sessions count as "unassigned".
5. **Panel picker**: a Panels menu in the Resources head (023) with
checkboxes Hardware, Tokens, Combined and Accounts; one stays on; stored
in the view store.
6. **Order**: rows sort by next weekly reset; the active account is marked.
7. **Timing**: 023 decision 5.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes, after 027" --> A1
subgraph A["🔐 A · Accounts store"]
A1["🗄️ accounts.json 0600 and its API"] --> A2["🪝 SessionStart hook maps session to email"]
A2 --> A3["✍️ Unit and integration tests written"]
end
A3 --> B1
subgraph B["📊 B · Panel"]
B1["🧮 Usage per account since reset"] --> B2["🗂️ Accounts panel and Panels menu"]
B2 --> B3["✍️ E2E tests written"]
end
B3 --> C1
subgraph C["🧪 C · After 030"]
C1["🧪 All tests of 023 to 030 once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Store
- [ ] Adding an account writes `accounts.json` with mode 0600; the skills
repo stays clean; the radio and view store files hold no account
email (grep).
- [ ] The API refuses a bad email, weekday, time or a negative limit with
400.
### Mapping and usage
- [ ] The hook on a fixture `~/.claude.json` writes one mapping line with
session and email and no other field.
- [ ] Fixture token rows of two mapped sessions give each account's used
since reset, today and total equal to the fixture sums; remaining is
limit minus used; without a limit it shows "—"; unmapped rows count
as "unassigned".
- [ ] Rows sort by next reset; the active account carries a marker.
### Panel picker
- [ ] The Panels menu hides and shows each panel; the last checked box
cannot be unchecked; the choice survives a reload.
### Tests
- [ ] Unit: validation, next-reset arithmetic across a DST change, usage
aggregation, hook extraction.
- [ ] Integration: accounts API and file mode; hook to mapping to usage.
- [ ] E2E: add, edit and remove an account, the panel picker at 1920, 1366
and 390; screenshots.
+67
View File
@@ -0,0 +1,67 @@
# 029 - Controls Layout
## User Story
As the operator, I want the Controls tabs (Tools, Rules, Groups) laid out
like the other views, so that I find their forms at once and the settings
list shows what matters.
## Decisions (operator-confirmed 2026-11-23; do not re-litigate)
1. **Head**: Controls with its Tools, Rules and Groups switch sits in the
023 box head, not floating beside the content.
2. **Width and alignment**: the Groups and Rule sets cards span the content
width; form labels share one baseline; the mic button sits inside its
field's end, as 031 builds it.
3. **Settings list**: files whose folder does not exist hide behind a "show
N missing" toggle; rows with an error chip come first, then by path.
4. **Chips**: group members and set rules are checkbox chips (members with
faces) instead of multi-select boxes; an empty rule list says how to
create a rule.
5. **Timing**: 023 decision 5.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes, after 028" --> A1
subgraph A["🎛️ A · Controls"]
A1["🧱 Switch in the box head"] --> A2["📐 Full width, aligned labels, mic inside"]
A2 --> A3["🗂️ Missing files folded, errors first"]
A3 --> A4["☑️ Member and rule chips"]
A4 --> A5["✍️ Unit and E2E tests written"]
end
A5 --> C1
subgraph C["🧪 C · After 030"]
C1["🧪 All tests of 023 to 030 once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
- [ ] On every Controls tab the switch sits in `.box-head` at the box's top
edge.
- [ ] The Groups and Rule sets cards are as wide as the Rules card (within
1 px).
- [ ] Per form all labels share one top offset (within 1 px); each mic
button lies inside its field.
- [ ] With 40 fixture paths of which 30 lack their folder, the list shows
10 rows and "show 30 missing", which reveals them; error rows first.
- [ ] Checking two member chips and saving signs a group of those two.
- [ ] `grep -n 'multiple' orchestrator/templates/page-rules.js` finds no
multi-select.
### Tests
- [ ] Unit: settings list filter and order.
- [ ] Integration: n/a: the signed group and rule set APIs are unchanged.
- [ ] E2E: the layout probes and a group creation at 1920, 1366 and 390;
screenshots.
+127
View File
@@ -0,0 +1,127 @@
# 030 - Yes/No Answers as Buttons
## User Story
As the operator, I want to answer a plain yes/no question with the Accept
and Reject buttons I already have, and to see every real choice in the
Stream, so that I do not read a numbered form for a single decision and no
decision hides from me.
## Decisions (operator-confirmed 2026-11-23; do not re-litigate)
1. **Boolean cards**: permission asks (allow, deny) and choices whose only
options are Yes and No. Choices with named options or multi-select keep
the full numbered form with its Other answer. Rejected: every
two-option card (named options are real choices).
2. **Match**: a boolean card shows no form; Accept answers Yes, Reject
answers No through the existing feedback dialog, whose optional text
reaches the agent as what to do instead.
3. **Stream, Waits on Operator, Home**: a boolean item shows the existing
green grant button with bulk selection (020) and a decline button with
an optional comment; no numbered form.
4. **Real choices in the Stream**: every open choice with named options or
multi-select (decision rows and `decision_request` cards) shows in the
Stream with its full numbered form, not only in Match and Waits on
Operator (operator 2026-11-23: the tasks must not hide there).
5. **Answered and running in the Stream**: the Stream also keeps granted,
declined and answered items, each with its outcome pill, and an operator
command the hub runner executes shows its live output box there, as in
Waits on Operator (operator 2026-11-23).
6. **Same answers**: the signed answers stay as today; only the controls
change.
7. **Timing**: 023 decision 5.
8. **Nothing hides** (operator 2026-11-23, after Match dropped every row
with an open hub job): every open item `operator.py list` shows, and
every review, ask and decision, appears in Match, the Tasks views
(list, board, Waits on Operator), the Stream and on Home tiles of those.
Where an area cannot act on it (a hub runner job queued or running for
it, no command or no absolute directory, a view that only shows), the
item stays visible, greyed out, its buttons disabled, and a tooltip on
it names the reason (for a queued job: how long, and which job the
runner runs meanwhile). Rejected: hiding such items; a separate list
of hidden items.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes, after 029" --> A1
subgraph A["🔘 A · Boolean answers"]
A1["🧮 Boolean classifier"] --> A2["🃏 Match: Accept and Reject only"]
A2 --> A3["✅ Stream and Home: grant and decline"]
A3 --> A4["✍️ Unit and integration tests written"]
end
A4 --> B1
subgraph B["🗳️ B · Real choices"]
B1["📜 Open choices shown in the Stream"] --> B2["✍️ E2E tests written"]
end
B2 --> C1
subgraph C["🧪 C · All of 023 to 030"]
C1["🧪 All tests of 023 to 030 once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### Boolean answers
- [ ] A boolean ask card in Match has no numbered form; Accept sends allow,
Reject sends deny, with its feedback text when one is typed.
- [ ] A Stream ask shows grant and decline and no numbered form; three
selected asks are granted at once through the 020 bulk path.
- [ ] Decline with a comment delivers it to the agent; without one, a plain
deny.
- [ ] A Yes/No choice renders as boolean; a choice with "Commit B11" and
"Don't commit" and a multi-select choice keep the form with Other.
### Real choices
- [ ] An open fixture decision row with four named options shows in the
Stream with its numbered form and Other answer; picking one there
settles it in Match and Waits on Operator too.
### Answered and running
- [ ] A granted ask stays in the Stream with a "granted" pill, a declined
one with "declined" and its comment, an answered choice with its pick.
- [ ] While the hub runner executes an operator row, its Stream entry shows
the live output box, and its lines grow with each state poll, as in
Waits on Operator.
### Same answers
- [ ] The signed records for allow, deny and deny with text equal today's
(fixture comparison).
### Nothing hides
- [ ] For a fixture register of open operator rows (free, one with a
queued hub job, one with a running job, one without an absolute
directory, one decision row), the set of row ids in Match, Tasks
list, Waits on Operator and the Stream each equals the set
`operator.py list --json` prints.
- [ ] The rows with a job or without an absolute directory render greyed
(`data-blocked`), Accept and Reject disabled, and their tooltip names
the reason; keyboard and swipe refuse them with the same reason.
- [ ] The queued row's reason names its minutes in the queue and the job
the runner runs meanwhile.
- [ ] The Match badge counts only cards that can act.
### Tests
- [ ] Unit: the boolean classifier (asks, Yes/No, named options,
multi-select); the blocked reason of a queued, a running and a free
row.
- [ ] Integration: allow, deny and deny with text through the API give
today's signed records; a Stream pick settles the decision row; the
row sets of the nothing-hides fixture per area.
- [ ] E2E: Match and Stream at 1920, 1366 and 390, including the greyed
cards and their tooltips; screenshots.
+93
View File
@@ -0,0 +1,93 @@
# 031 - Mic in Fields
## User Story
As the operator, I want the microphone joined into every text field it
serves, so that field and mic read as one control instead of a loose button
beside or below it.
## Decisions (operator-confirmed 2026-11-23; do not re-litigate)
1. **One-line fields**: the mic is a segment at the right end inside the
field's frame, the field's height, divided from the text by a 1 px line;
field and segment share one border and radius. Applies to every one-line
field with a mic, among them the Stream search, the command line, rule
and group forms and choice "Other" answers.
2. **Textareas: footer strip** (operator pick 2026-11-23): the textarea and
a slim footer row share one frame, divided by a 1 px line; the mic sits
at the footer's right end; the footer's left side holds what belongs to
the field (Record in the radio composer, a character count where a limit
exists). Rejected: a floating corner button (covers text next to the
resize handle); a top-right corner button (collides with the first
line); the mic in the label line (no longer joined); a full-height side
segment (clunky when tall).
3. **One helper**: the shared mic component (`page-mic.js`) builds both
frames for every field it serves, the automatic sweep included; no
field places its mic by hand. 025's composer footer and 029's forms use
it.
4. **States**: the segment and the footer button keep the mic's idle,
recording and transcribing looks; the frame's focus ring covers field
and mic together.
5. **Timing**: implemented after 030, before the one test run of 023 to
031.
## Approach
```mermaid
flowchart TD
subgraph P["🧭 0 · Preparation"]
P1["📋 Write requirement"] --> P2{"✅ Operator approves?"}
P2 -- "✏️ corrections" --> P1
end
P2 -- "🤖 yes, after 030" --> A1
subgraph A["🎙️ A · Frames"]
A1["🧩 Mic helper builds the one-line frame"] --> A2["🧩 Footer strip frame for textareas"]
A2 --> A3["🔗 Every mic field uses the helper"]
A3 --> A4["✍️ Unit and E2E tests written"]
end
A4 --> C1
subgraph C["🧪 C · All of 023 to 031"]
C1["🧪 All tests of 023 to 031 once"] --> C2{"🟢 Green?"}
C2 -- "🔴 no: fix" --> C1
C2 -- "🟢 yes" --> CF{"💬 Operator feedback on screenshots?"}
CF -- "✏️ changes" --> A1
end
CF -- "👍 fits" --> D1["🏁 Review, commit with operator OK, hand-over"]
```
## Acceptance Criteria
### One-line fields
- [ ] A DOM scan finds every mic of a one-line field inside the same frame
element as its field, as its last child.
- [ ] Per one-line field the mic segment's top and bottom equal the field
frame's inner edges (within 1 px), its right edge the frame's inner
right edge, and a 1 px divider sits between text and mic.
- [ ] Typed text never runs under the mic segment (text box right edge
left of the divider).
### Textareas
- [ ] Every textarea with a mic sits in a frame with a footer row below it,
divided by a 1 px line; the mic is the footer's last child.
- [ ] The radio composer's footer holds Record on the left and the mic on
the right (025).
- [ ] Resizing the textarea by its handle keeps the footer attached and the
mic visible.
### States
- [ ] Recording shows the recording look on the segment or footer button;
focus in the field draws one ring around the whole frame.
- [ ] `grep -nE "micButton\(" orchestrator/templates/*.js` finds no caller
outside `page-mic.js` that inserts the button itself.
### Tests
- [ ] Unit: the helper builds the one-line frame and the footer frame and
keeps the button state.
- [ ] Integration: n/a: no server change.
- [ ] E2E: the scans and geometry probes on Stream, Match, radio, agent
page, Controls and the command line at 1920, 1366 and 390;
screenshots.
+10
View File
@@ -25,3 +25,13 @@ skill defines the format.
- [019 - Reveal withheld diff content](019-reveal-withheld-diff.md)
- [020 - Bulk grant mode and continuous diff](020-bulk-grant-mode.md)
- [021 - TokenEconomizer by default](021-tokeneconomizer-by-default.md)
- [022 - Analysis Skills from Quality](022-analysis-skills-from-quality.md)
- [023 - Box Heads](023-box-heads.md)
- [024 - Match Card Content](024-match-card-content.md)
- [025 - Radio Speak Card](025-radio-speak-card.md)
- [026 - Widget Zoom](026-widget-zoom.md)
- [027 - Slash Skill Suggestions](027-slash-skill-suggestions.md)
- [028 - Resources Accounts](028-resources-accounts.md)
- [029 - Controls Layout](029-controls-layout.md)
- [030 - Yes/No Answers as Buttons](030-yes-no-answers.md)
- [031 - Mic in Fields](031-mic-in-fields.md)
+57 -18
View File
@@ -29,9 +29,11 @@
tokens: add the input, output, cache-read and cache-write tokens of the
usage fields in the Claude Code transcripts under --transcripts since
each file's byte offset to <state>/tokens.jsonl as {t, agent, model,
input, output, cache_read, cache_write}, t the hour; agent is the
name the council claim of the session carries, else the session id's
first 8 characters. A message counts once by its message id and
input, output, cache_read, cache_write, account?}, t the hour; agent
is the name the council claim of the session carries, else the
session id's first 8 characters; account is the email the
SessionStart hook mapped the session to in the council's
session-accounts.jsonl, left out for an unmapped session. A message counts once by its message id and
request id, also when written over several lines or copied into a
fork's transcript. <state>/offsets.json holds {files: {path: offset},
seen: {hour: [key digest]}}, seen keeping the hours this run read and
@@ -97,6 +99,8 @@ HOST_DIGITS = (("cpu", 1), ("ram", 1), ("swap", 1), ("load", 2), ("psi_some", 2)
CLAIMS = ("*/claim.json", "*/*/claim.json")
SAMPLES = "samples.jsonl"
TOKENS = "tokens.jsonl"
SESSION_ACCOUNTS = "session-accounts.jsonl"
EMAIL_CHARS = 254
OFFSETS = "offsets.json"
TICKS = "cpu.json"
SWAPPED = "swap.json"
@@ -115,18 +119,28 @@ def read_text(path: Path) -> str:
return ""
def read_json(path: Path) -> object:
def read_capped(path: Path) -> str:
"""Returns:
The parsed JSON of path, read without following a symlink and only
from a regular file of at most JSON_BYTES; None when that fails.
The text of path, read without following a symlink and only from a
regular file of at most JSON_BYTES; "" when that fails.
"""
try:
with os.fdopen(os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK), "rb") as handle:
if not stat.S_ISREG(os.fstat(handle.fileno()).st_mode):
return None
return ""
data = handle.read(JSON_BYTES + 1)
return None if len(data) > JSON_BYTES else json.loads(data.decode("utf-8"))
except (OSError, ValueError, RecursionError):
return "" if len(data) > JSON_BYTES else data.decode("utf-8")
except (OSError, ValueError):
return ""
def read_json(path: Path) -> object:
"""Returns:
The parsed JSON of read_capped(path); None when that fails.
"""
try:
return json.loads(read_capped(path))
except (ValueError, RecursionError):
return None
@@ -526,8 +540,12 @@ def retain(rows: list[dict], now: float) -> list[dict]:
def read_rows(path: Path) -> list[dict]:
return json_lines(read_text(path))
def json_lines(text: str) -> list[dict]:
rows = []
for line in read_text(path).splitlines():
for line in text.splitlines():
try:
row = json.loads(line)
except (ValueError, RecursionError):
@@ -608,6 +626,20 @@ def claim_names(council: Path) -> dict[str, str]:
return names
def session_accounts(council: Path) -> dict[str, str]:
"""Returns:
Each session's account email from the lines the SessionStart hook
appends to <council>/session-accounts.jsonl, the last one winning.
Agents may write the file, so it is read through read_capped() and
an email longer than EMAIL_CHARS is dropped.
"""
found = {}
for row in json_lines(read_capped(council / SESSION_ACCOUNTS)):
if isinstance(row.get("session"), str) and isinstance(row.get("email"), str) and len(row["email"]) <= EMAIL_CHARS:
found[row["session"]] = row["email"]
return found
def epoch(value: object) -> float | None:
if not isinstance(value, str):
return None
@@ -700,24 +732,30 @@ def scan(path: Path, start: int, budget: int, seen: dict[int, set[str]]) -> tupl
def token_rows(sums: dict[tuple, list[int]]) -> list[dict]:
"""Args:
sums: per (t, agent, model, width) the counts in COUNTS order.
sums: per (t, agent, model, width, account) the counts in COUNTS
order, account "" for a session the hook mapped to none.
Returns:
One token row per key in key order; a row other than hourly names
its width.
its width, a row of a mapped session its account.
"""
return [{"t": t, "agent": agent, "model": model, **dict(zip(NAMES, counts, strict=True)), **({} if width == HOUR else {"width": width})} for (t, agent, model, width), counts in sorted(sums.items())]
return [
{"t": t, "agent": agent, "model": model, **dict(zip(NAMES, counts, strict=True)), **({} if width == HOUR else {"width": width}), **({"account": account} if account else {})}
for (t, agent, model, width, account), counts in sorted(sums.items())
]
def token_key(row: dict, line: float) -> tuple:
"""Returns:
(t, agent, model, width) of the row a token row merges into: its day
(UTC) when the row is daily or the day ended by line, else its hour.
(t, agent, model, width, account) of the row a token row merges
into: its day (UTC) when the row is daily or the day ended by line,
else its hour.
"""
day = int(row["t"] // DAY * DAY)
account = row["account"] if isinstance(row.get("account"), str) else ""
if row.get("width") == DAY or day + DAY <= line:
return day, row["agent"], row["model"], DAY
return row["t"], row["agent"], row["model"], HOUR
return day, row["agent"], row["model"], DAY, account
return row["t"], row["agent"], row["model"], HOUR, account
def add(sums: dict[tuple, list[int]], key: tuple, counts: tuple[int, ...]) -> None:
@@ -775,6 +813,7 @@ def count_tokens(transcripts: Path, council: Path, state: Path, now: float, budg
offsets = stored.get("files") if isinstance(stored, dict) and isinstance(stored.get("files"), dict) else {}
seen = seen_of(stored.get("seen") if isinstance(stored, dict) else None)
names = claim_names(council)
accounts = session_accounts(council)
sums: dict[tuple, list[int]] = {}
files, touched = {}, set()
for path in sorted(transcripts.rglob("*.jsonl")):
@@ -791,7 +830,7 @@ def count_tokens(transcripts: Path, council: Path, state: Path, now: float, budg
seen.setdefault(hour, set()).update(read)
touched.add(hour)
for ts, session, model, counts in found:
add(sums, (int(ts // HOUR * HOUR), names.get(session) or session[:8], model, HOUR), counts)
add(sums, (int(ts // HOUR * HOUR), names.get(session) or session[:8], model, HOUR, accounts.get(session, "")), counts)
rows = token_rows(sums)
append_rows(state / TOKENS, rows)
kept = {"files": files, "seen": kept_seen(seen, touched, now)}
+40 -4
View File
@@ -220,13 +220,49 @@ def preview(row: dict, rules: Path | None) -> dict | None:
return {"task": row["task"], "command": row["command"], "head": head, **shown}
def review_preview(row: dict, rules: Path | None) -> dict | None:
"""Args:
row: a pending review that shipped no diff, with id, worktree, tree
and head, the HEAD the hub last saw, None for none.
rules: the MEDUSA rules directory.
Returns:
{id, head, diff}: the review's tree against its worktree's HEAD
(staged_diff.tree_diff), or {id, head, error} when it cannot be
built; None while HEAD is the one the hub saw.
"""
try:
head = staged_diff.head_of(Path(row["worktree"]))
except PREVIEW_FAILURES as error:
head, shown = "", {"error": str(error)[:ERROR_LIMIT]}
else:
shown = None
if head == row["head"]:
return None
if shown is None:
try:
shown = {"diff": staged_diff.tree_diff(Path(row["worktree"]), row["tree"], rules)[0]}
except PREVIEW_FAILURES as error:
shown = {"error": str(error)[:ERROR_LIMIT]}
return {"id": row["id"], "head": head, **shown}
def oversized(shown: dict, keys: tuple[str, ...]) -> dict:
if len(json.dumps(shown).encode()) <= hub_limits.DIFF_BODY_LIMIT:
return shown
return {**{key: shown[key] for key in keys}, "error": f"the preview passes the hub's {hub_limits.DIFF_BODY_LIMIT} bytes"}
def previews(base: str, rules: Path | None) -> None:
for row in call(base, PREVIEWS, None)["rows"]:
listed = call(base, PREVIEWS, None)
for row in listed["rows"]:
shown = preview(row, rules)
if shown is not None and len(json.dumps(shown).encode()) > hub_limits.DIFF_BODY_LIMIT:
shown = {"task": row["task"], "command": row["command"], "head": shown["head"], "error": f"the preview passes the hub's {hub_limits.DIFF_BODY_LIMIT} bytes"}
if shown is not None:
call(base, PREVIEWS, shown)
call(base, PREVIEWS, oversized(shown, ("task", "command", "head")))
for row in listed["reviews"]:
shown = review_preview(row, rules)
if shown is not None:
call(base, PREVIEWS, oversized(shown, ("id", "head")))
def council_refusal(council: Path) -> str | None:
+4 -3
View File
@@ -209,12 +209,13 @@ def digest(data: bytes | None) -> str:
def view_of(path: str) -> dict:
"""Returns:
{"path", "exists", "sha256", "error", "settings"}: settings only the
{"path", "exists", "folder", "sha256", "error", "settings"}: folder
False when the path's directory is missing, settings only the
permissions and sandbox sections; error why the file was unreadable,
for anything unforeseen only the exception's class, so one bad path
never keeps the others or the view from being written.
"""
entry = {"path": path, "exists": False, "sha256": "", "error": "", "settings": {}}
entry = {"path": path, "exists": False, "folder": True, "sha256": "", "error": "", "settings": {}}
try:
return read_view(path, entry)
except Exception as error: # noqa: BLE001
@@ -225,7 +226,7 @@ def read_view(path: str, entry: dict) -> dict:
try:
parent = parent_of(path)
except FileNotFoundError:
return {**entry, "error": MISSING_DIRECTORY}
return {**entry, "folder": False, "error": MISSING_DIRECTORY}
except OSError as error:
return {**entry, "error": f"a link or no directory on the path: {error.strerror}"}
try:
+143
View File
@@ -0,0 +1,143 @@
#!/usr/bin/env python3
"""Args:
--home: the home whose ~/.claude/skills and ~/.agents/skills are read.
--tree: the branch-tree.json pkgmgr branch tree writes; each of its
repositories' .claude/skills and .agents/skills are read.
--output: the index the Agent Orchestrator serves at /api/skills, e.g.
~/.local/state/pkgmgr/tree/skills-index.json.
Returns:
Runs on the host, because the hub's container sees no repository:
replaces --output with {"written": <epoch>, "skills": [{"name",
"description", "source"}]}, one entry per skill folder holding a
SKILL.md, sorted by name and source; source is ~/.claude/skills,
~/.agents/skills or the repository's path. The exit code is 0.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import stat
import tempfile
import time
from pathlib import Path
HOME_SOURCES = (".claude/skills", ".agents/skills")
SKILL_FILE = "SKILL.md"
HEAD_BYTES = 16384
TREE_BYTES = 8 << 20
NAME = re.compile(r"[A-Za-z0-9:_.-]{1,100}")
DESCRIPTION_CHARS = 300
FIELD = re.compile(r"^(name|description):[ \t]*(.*)$")
BLOCKS = (">", "|", ">-", "|-", ">+", "|+")
def read_head(path: Path, limit: int) -> str:
"""Returns:
The first limit bytes of path as text, read without following a
symlink and only from a regular file.
Raises:
OSError: path is missing, a symlink or no regular file.
"""
handle = os.open(path, os.O_RDONLY | os.O_NOFOLLOW | os.O_NONBLOCK)
with os.fdopen(handle, "rb") as stream:
if not stat.S_ISREG(os.fstat(stream.fileno()).st_mode):
raise OSError(f"{path}: no regular file")
return stream.read(limit).decode("utf-8", "replace")
def front_matter(text: str) -> dict[str, str]:
"""Returns:
name and description from the YAML front matter that opens text,
each one line with its quotes stripped, a folded or literal block
joined into it; none without a closed front matter.
"""
lines = text.splitlines()
if not lines or lines[0].strip() != "---":
return {}
found, folding = {}, None
for line in lines[1:]:
if line.strip() == "---":
return {key: " ".join(value.split()) for key, value in found.items()}
match = FIELD.match(line)
if match:
value = match.group(2).strip()
folding = match.group(1) if value in BLOCKS else None
found[match.group(1)] = "" if folding else value.strip("\"'")
elif folding and line[:1] in (" ", "\t"):
found[folding] += f" {line.strip()}"
else:
folding = None
return {}
def skill_of(folder: Path, source: str) -> dict | None:
"""Returns:
{name, description, source} of a skill folder: the front matter's
name, else the folder's; None without a readable SKILL.md or with a
name outside NAME.
"""
try:
fields = front_matter(read_head(folder / SKILL_FILE, HEAD_BYTES))
except OSError:
return None
name = fields.get("name") or folder.name
if not NAME.fullmatch(name):
return None
return {"name": name, "description": fields.get("description", "")[:DESCRIPTION_CHARS], "source": source}
def skills_in(root: Path, source: str) -> list[dict]:
try:
folders = sorted(path for path in root.iterdir() if path.is_dir())
except OSError:
return []
return [found for folder in folders if (found := skill_of(folder, source)) is not None]
def repositories(tree: Path) -> list[str]:
"""Returns:
The absolute repository paths of the branch tree; none when it is
unreadable.
"""
try:
scan = json.loads(read_head(tree, TREE_BYTES))
except (OSError, ValueError, RecursionError):
return []
repos = scan.get("repos") if isinstance(scan, dict) else None
return sorted({repo["path"] for repo in repos if isinstance(repo, dict) and isinstance(repo.get("path"), str) and repo["path"].startswith("/")}) if isinstance(repos, list) else []
def index(home: Path, tree: Path) -> list[dict]:
found = [skill for part in HOME_SOURCES for skill in skills_in(home / part, f"~/{part}")]
found += [skill for repo in repositories(tree) for part in HOME_SOURCES for skill in skills_in(Path(repo) / part, repo)]
unique = {(skill["name"], skill["source"]): skill for skill in found}
return [unique[key] for key in sorted(unique)]
def write(output: Path, data: dict) -> None:
with tempfile.NamedTemporaryFile("w", encoding="utf-8", dir=output.parent, prefix=f".{output.name}.", delete=False) as handle:
try:
json.dump(data, handle)
except BaseException:
os.unlink(handle.name)
raise
os.replace(handle.name, output)
def main() -> int:
parser = argparse.ArgumentParser(description="Index the skills an agent message may name for the Agent Orchestrator.")
parser.add_argument("--home", type=Path, required=True)
parser.add_argument("--tree", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
write(args.output, {"written": time.time(), "skills": index(args.home, args.tree)})
return 0
if __name__ == "__main__":
raise SystemExit(main())
+168
View File
@@ -0,0 +1,168 @@
from __future__ import annotations
import contextlib
import datetime
import re
from pathlib import Path
from .errors import Missing, ToolError
from .fields import FIELDS, decode, visible
from .ledger import Ledger
from .records import read_jsonl
from .resources import HOUR, RESOURCES, TOKENS, rows_between
from .settings import flag, section
ACCOUNTS = "accounts.json"
SESSION_ACCOUNTS = "session-accounts.jsonl"
KEYS = ("provider", "email", "renewal", "reset", "resubscribe", "autorenew", "limit", "note")
MOMENT = ("day", "time")
EMAIL = re.compile(r"[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63})*\.[A-Za-z]{2,24}")
TIME = re.compile(r"(?:[01][0-9]|2[0-3]):[0-5][0-9]")
DATE = re.compile(r"[0-9]{4}-[0-9]{2}-[0-9]{2}")
PROVIDER = re.compile(r"(?=[^\x00-\x1f\x7f]*\S)[^\x00-\x1f\x7f]{1,40}")
NOTE_LIMIT = 200
LIMIT_CAP = 10**15
RECENT = 8 * 24 * HOUR
COUNTS = ("input", "output", "cache_read", "cache_write")
def moment(value: object, name: str) -> dict:
"""Returns:
{day, time}: day 0 for Sunday to 6 for Saturday as Date.getDay()
counts, time HH:MM local; anything else raises ToolError.
"""
data = section(value, name, MOMENT)
day, time = data["day"], data["time"]
if isinstance(day, bool) or not isinstance(day, int) or not 0 <= day <= 6:
raise ToolError(f"{name}.day must be a weekday from 0 (Sunday) to 6 (Saturday)")
if not isinstance(time, str) or not TIME.fullmatch(time):
raise ToolError(f"{name}.time must be a time HH:MM")
return {"day": day, "time": time}
def resubscribe(value: object) -> str:
if value == "":
return ""
if isinstance(value, str) and DATE.fullmatch(value):
with contextlib.suppress(ValueError):
return datetime.date.fromisoformat(value).isoformat()
raise ToolError("resubscribe must be a date YYYY-MM-DD or empty")
def valid_account(raw: object) -> dict:
"""Args:
raw: the account as the page sent it, every key of KEYS.
Returns:
The account; a missing or unknown key, a bad email, weekday, time or
date, or a negative limit raises ToolError.
"""
data = section(raw, "account", KEYS)
if not isinstance(data["provider"], str) or not PROVIDER.fullmatch(data["provider"]):
raise ToolError("provider must be one line of 1 to 40 characters")
if not isinstance(data["email"], str) or not EMAIL.fullmatch(data["email"]):
raise ToolError("email must be an address like name@example.org")
limit = data["limit"]
if limit is not None and (isinstance(limit, bool) or not isinstance(limit, int) or not 0 <= limit <= LIMIT_CAP):
raise ToolError(f"limit must be empty or a whole number of tokens from 0 to {LIMIT_CAP}")
if not isinstance(data["note"], str) or len(data["note"]) > NOTE_LIMIT:
raise ToolError(f"note must be text of at most {NOTE_LIMIT} characters")
account = {
"provider": data["provider"].strip(),
"email": data["email"],
"renewal": moment(data["renewal"], "renewal"),
"reset": moment(data["reset"], "reset"),
"resubscribe": resubscribe(data["resubscribe"]),
"autorenew": flag(data["autorenew"], "autorenew"),
"limit": limit,
"note": data["note"].strip(),
}
visible({"provider": account["provider"], "note": account["note"]})
return account
def mapping(file: Path) -> dict[str, str]:
"""Returns:
Each session's email, the last line the SessionStart hook wrote for
it winning, in the order the sessions first appear.
"""
found: dict[str, str] = {}
for row in read_jsonl(file):
session, email = row.get("session"), row.get("email")
if isinstance(session, str) and isinstance(email, str) and EMAIL.fullmatch(email):
found[session] = email
return found
def active(file: Path) -> str | None:
"""Returns:
The email of the newest mapping line: the account the host's
Claude Code logged in with at the last session start.
"""
emails = [row.get("email") for row in read_jsonl(file)]
valid = [email for email in emails if isinstance(email, str) and EMAIL.fullmatch(email)]
return valid[-1] if valid else None
def usage(rows: list[dict], now: float) -> dict[str, dict]:
"""Args:
rows: token rows {t, agent, model, input, output, cache_read,
cache_write, account?, width?}.
now: the epoch seconds the recent hours end at.
Returns:
Per account email, "" for rows of no mapped session: {total, hours},
total the tokens of every row, hours [t, tokens] per hourly row of
the last 8 days in time order, for the page to sum from the local
weekly reset and midnight.
"""
found: dict[str, dict] = {}
for row in rows:
account = row.get("account") if isinstance(row.get("account"), str) else ""
tokens = sum(value for value in (row.get(name) for name in COUNTS) if isinstance(value, int) and not isinstance(value, bool) and value > 0)
entry = found.setdefault(account, {"total": 0, "hours": {}})
entry["total"] += tokens
t = row.get("t")
if "width" not in row and isinstance(t, int | float) and now - RECENT <= t <= now:
entry["hours"][int(t)] = entry["hours"].get(int(t), 0) + tokens
return {account: {"total": entry["total"], "hours": sorted(entry["hours"].items())} for account, entry in found.items()}
class Accounts:
def __init__(self, state: Path, kept: Path, council: Path) -> None:
self.ledger = Ledger(state / ACCOUNTS)
self.tokens = kept / RESOURCES / TOKENS
self.sessions = council / SESSION_ACCOUNTS
def view(self, now: float) -> dict:
"""Returns:
{accounts, active, usage}: the stored accounts, the active
account's email or None, and usage() of every token row.
"""
return {"accounts": self.ledger.listed(), "active": active(self.sessions), "usage": usage(rows_between(self.tokens, 0, now, 0), now)}
def save(self, body: bytes) -> dict:
"""Args:
body: {account, id}: id "" adds the account, else it replaces
the account of that id.
"""
data = section(decode(body), "body", ("account", "id"))
account = valid_account(data["account"])
if data["id"] == "":
return self.ledger.add(account)
changed = self.ledger.change(self.known(data), account)
if changed is None:
raise Missing("no such account")
return changed
def drop(self, account_id: str) -> dict:
if not self.ledger.remove(account_id):
raise Missing("no such account")
return {"removed": account_id}
@staticmethod
def known(data: dict) -> str:
pattern, hint = FIELDS["id"]
if not isinstance(data["id"], str) or not pattern.fullmatch(data["id"]):
raise ToolError(f"id must be empty or {hint}")
return data["id"]
+6 -5
View File
@@ -253,22 +253,23 @@ class Firewall:
def settings_files(self) -> tuple[list[dict], dict]:
"""Returns:
The listed settings files the host writer last read, each
{"path", "exists", "sha256", "error", "settings", "own"} with
settings only the part signing.settings_view() keeps, and the
view's written time, error and tools_of().
{"path", "exists", "folder", "sha256", "error", "settings", "own"}
with settings only the part signing.settings_view() keeps and
folder False only when the writer found no directory for the
path, and the view's written time, error and tools_of().
"""
view = read_json(self.firewall_spool.root / VIEW)
files = view.get("files") if isinstance(view, dict) else None
if not isinstance(files, list):
return [], {"written": None, "error": "no settings view yet: the kvb-orchestrator-firewall unit writes it on the host", "tools": None}
shown = [{**entry, "settings": signing.settings_view(entry["settings"]), "error": str(entry.get("error") or ""), "own": entry.get("own") is True} for entry in files if shaped_file(entry)]
shown = [{**entry, "settings": signing.settings_view(entry["settings"]), "error": str(entry.get("error") or ""), "folder": entry.get("folder") is not False, "own": entry.get("own") is True} for entry in files if shaped_file(entry)]
return shown, {"written": view.get("written"), "error": "", "tools": tools_of(shown, view.get("known"))}
def firewall(self) -> dict:
files, meta = self.settings_files()
now = time.time()
asks = self.recent_subjects("ask", now)
listed = [{key: entry[key] for key in ("path", "exists", "sha256", "error")} | {"groups": counted(grouped(entry["settings"].get("permissions")), asks, now), "sandbox": sandbox_entries(entry["settings"].get("sandbox"), "sandbox")} for entry in files]
listed = [{key: entry[key] for key in ("path", "exists", "folder", "sha256", "error")} | {"groups": counted(grouped(entry["settings"].get("permissions")), asks, now), "sandbox": sandbox_entries(entry["settings"].get("sandbox"), "sandbox")} for entry in files]
rules = {rule["id"]: stored_hits(rule, asks, now) for rule in self.rules.listed()}
return {**meta, "files": listed, "lists": list(signing.SETTINGS_LISTS), "patterns": deny_patterns(), "groups": self.groups.listed(), "sets": self.rule_sets.listed(), "days": RECENT_DAYS, "rules": rules}
+14 -2
View File
@@ -13,6 +13,7 @@ from .exchange import PLAIN_CSP, Exchange
from .rates import rated
from .resources import RESOURCES, sampled
from .scores import scored
from .skillindex import SKILLS_INDEX, served
BODY_LIMIT = 1 << 20
UPLOAD_LIMIT = 50 << 20
@@ -78,7 +79,9 @@ FIREWALL_STATE = re.compile(r"/api/firewall/settings/([0-9a-f]{16})")
FIREWALL_DROP = re.compile(r"/api/firewall/(groups|sets)/([0-9a-f]{16})/delete")
FIREWALL_STATUS = {"settings_preview": HTTPStatus.OK, "change_settings": HTTPStatus.ACCEPTED, "add_group": HTTPStatus.CREATED, "add_set": HTTPStatus.CREATED}
WAV_POSTS = (STT_ROUTE, VOICE_ROUTE)
ACTION_POSTS = ("/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
ACCOUNTS_ROUTE = "/api/accounts"
ACCOUNT_DROP = re.compile(r"/api/accounts/([0-9a-f]{16})/delete")
ACTION_POSTS = (ACCOUNTS_ROUTE, "/api/rules", "/api/nl", SETTINGS_ROUTE, TTS_ROUTE, STT_ROUTE, SIGN_ROUTE, RULE_SIGN_ROUTE, CLEANUP_ROUTE, OFFICES_ROUTE, TASKS_ROUTE, VOICE_ROUTE, MESSAGE_SIGN_ROUTE, SETTINGS_SIGN_ROUTE, CHOICES_ROUTE, CHOICES_SIGN_ROUTE, GATES_ROUTE, TOKEN_ROUTE, *FIREWALL_POSTS)
class Handler(Exchange):
@@ -137,8 +140,12 @@ class Handler(Exchange):
self.answer(lambda: hub.events(self.query()), HTTPStatus.OK)
elif path == "/api/tree":
self.answer(hub.repositories, HTTPStatus.OK)
elif path == "/api/skills":
self.answer(lambda: served(hub.tree.file.with_name(SKILLS_INDEX)), HTTPStatus.OK)
elif path == MATCH_ROUTE:
self.answer(hub.match_cards, HTTPStatus.OK)
elif path == ACCOUNTS_ROUTE:
self.answer(lambda: hub.accounts.view(time.time()), HTTPStatus.OK)
elif path == "/api/resources":
self.answer(lambda: sampled(hub.kept / RESOURCES, hub.span(self.query(), time.time())), HTTPStatus.OK)
elif path == "/api/scores":
@@ -182,6 +189,11 @@ class Handler(Exchange):
return lambda body: self.answer(lambda: hub.sign_board(body), HTTPStatus.OK)
if board:
return lambda body: self.answer(lambda: hub.board(board.group(1), body), HTTPStatus.OK)
drop = ACCOUNT_DROP.fullmatch(path)
if path == ACCOUNTS_ROUTE:
return lambda body: self.answer(lambda: hub.accounts.save(body), HTTPStatus.OK)
if drop:
return lambda _body: self.answer(lambda: hub.accounts.drop(drop.group(1)), HTTPStatus.OK)
reveal = REVEAL_ROUTE.fullmatch(path)
if reveal:
method = hub.sign_reveal if reveal.group(3) else hub.reveal
@@ -263,7 +275,7 @@ class Handler(Exchange):
return None
def posted(self, path: str) -> bool:
return any(pattern.fullmatch(path) for pattern in (INBOX_ROUTE, UNDO_ROUTE, RULE_ROUTE, REQUEST_ROUTE, RUNNER_ROUTE, FIREWALL_DROP, REVEAL_ROUTE))
return any(pattern.fullmatch(path) for pattern in (INBOX_ROUTE, UNDO_ROUTE, RULE_ROUTE, REQUEST_ROUTE, RUNNER_ROUTE, FIREWALL_DROP, REVEAL_ROUTE, ACCOUNT_DROP))
def runner(self, path: str, body: bytes) -> None:
hub = self.server.hub
+3
View File
@@ -10,6 +10,7 @@ from pathlib import Path
import jinja2
from markupsafe import Markup
from .accounts import Accounts
from .approving import Approving
from .artifacts import Touched
from .asking import Asking
@@ -140,6 +141,7 @@ class Hub(Mcp, Reviewing, Revealing, Asking, Messaging, Choosing, Approving, Den
match_snapshots: Ledger
merge_previews: Ledger
live_state: LiveState
accounts: Accounts
def hosts(self) -> tuple[str, str]:
return f"127.0.0.1:{self.public_port}", f"localhost:{self.public_port}"
@@ -208,6 +210,7 @@ def open_hub(council: Path, pages: Path, public_port: int, state: Path, host_sta
voice_notes=VoiceNotes(state / "voice", host_state / "voice", speech, lambda: {message["voice"] for message in messages.listed() if message.get("voice")}),
replay=state / "replay" / "messages.json",
view_store=ViewStore(state / "view.json"),
accounts=Accounts(state, places.kept, council),
match_snapshots=Ledger(state / "match.json"),
merge_previews=Ledger(state / "previews.json"),
live_state=LiveState(live_ttl),
+4 -3
View File
@@ -8,7 +8,7 @@ from .council import read_claims
from .denying import requester_of
from .errors import ToolError
from .fields import decode, expect
from .jobs import console_of
from .jobs import console_of, row_blocked
from .names import Directory
from .records import digest, iso_epoch
from .register import adder, operator_rows, runnable
@@ -21,7 +21,7 @@ SNOOZE_LIMIT = 8 * 86400
class Inbox:
def inbox(self, now: float, tasks: dict[str, dict], directory: Directory) -> list[dict]:
claims = read_claims(self.council)
base = {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": []}
base = {"agent": "", "to": "", "detail": "", "green": False, "gate": "", "score": "", "warnings": [], "options": [], "recommended": "", "multi": False, "check": "", "command": "", "directory": "", "sha256": "", "runnable": False, "deniable": False, "job": None, "rule": None, "dry_run": None, "diff": None, "settled": False, "answered": "", "reviews": [], "blocked": ""}
items = []
for review in self.reviews.pending():
created = iso_epoch(review["created"]) or now
@@ -38,6 +38,7 @@ class Inbox:
fields = {"title": decision["question"][:300], "agent": decision["agent"], "green": recommended != "", "options": decision["options"], "recommended": recommended, "multi": bool(decision.get("multi"))}
items.append({**base, "kind": "decision", "id": decision["id"], "ts": decision["created_ts"], **fields})
held = self.open_jobs()
reasons = self.blocked_rows(now)
consoles = self.consoles()
pattern = task_pattern(self.scripts.skills)
rows = [row for row in operator_rows(tasks) if pattern is not None and pattern.fullmatch(row["task"])]
@@ -45,7 +46,7 @@ class Inbox:
busy = row["task"] in held
answer = self.answers.get(row["task"])
fields = {"answered": answer["label"] if answered(answer, row) else "", "title": row["command"], "detail": row["why"], "agent": adder(tasks[row["task"]]), "to": requester_of(claims, adder(tasks[row["task"]]))[0], "command": row["command"], "directory": row["directory"], "sha256": digest(row["command"]), "check": row["check"], "options": row["options"], "recommended": row["recommended"]}
state = {"runnable": runnable(row) and not busy, "deniable": not busy, "job": console_of(consoles.get(row["task"])), "reviews": self.linked(row["command"])}
state = {"runnable": runnable(row) and not busy, "deniable": not busy, "job": console_of(consoles.get(row["task"])), "reviews": self.linked(row["command"]), "blocked": row_blocked(row, reasons)}
items.append({**base, "kind": "operator", "id": row["task"], "ts": self.watch.first(row["task"], now), **fields, **state})
listed = {row["task"] for row in rows}
for task, job in consoles.items():
+42
View File
@@ -14,6 +14,7 @@ CONSOLE = ("id", "status", "code", "output", "created_ts", "started", "finished"
TASK_JOB = "task"
GATE_JOB = "gate"
CHANGES = (TASK_JOB, GATE_JOB)
UNRUNNABLE = "The hub runner needs a command and an absolute directory, and this row lacks one; run it with operator.py run in a terminal."
def runner_job(job: dict) -> dict:
@@ -32,10 +33,51 @@ def console_of(job: dict | None) -> dict | None:
return None if job is None else {**{key: job[key] for key in CONSOLE}, "output": job["output"][-OUTPUT_LIMIT:]}
def minutes_since(ts: float | None, now: float) -> int:
return max(0, round((now - (ts or now)) / 60))
def blocked_reasons(jobs: list[dict], now: float) -> dict[str, str]:
"""Args:
jobs: every hub job record.
Returns:
Per task with a queued or running job why its row cannot be run or
denied now: how long the runner runs it, or how long it waits and
which job the runner, which runs one job at a time, started last.
"""
open_jobs = [job for job in jobs if job["status"] in JOB_OPEN]
running = max((job for job in open_jobs if job["status"] == "running"), key=lambda job: job["started"] or 0, default=None)
ahead = "" if running is None else f" behind {running['task']}, which runs for {minutes_since(running['started'], now)} min"
reasons = {}
for job in sorted(open_jobs, key=lambda job: job["created_ts"]):
if job["status"] == "running":
reasons[job["task"]] = f"The hub runner runs it for {minutes_since(job['started'], now)} min; its result comes in Waits on Operator."
else:
reasons[job["task"]] = f"Queued in the hub runner for {minutes_since(job['created_ts'], now)} min{ahead}; the runner runs one job at a time."
return reasons
def row_blocked(row: dict, reasons: dict[str, str]) -> str:
"""Args:
row: an open operator row.
reasons: blocked_reasons() of the hub jobs.
Returns:
Why no area can run or deny the row now, "" when one can: its open
hub job, else for a command row without a command or an absolute
directory UNRUNNABLE; a decision row is answered, never run.
"""
return reasons.get(row["task"]) or ("" if row["check"] == "decision" or runnable(row) else UNRUNNABLE)
class Jobs:
def open_jobs(self) -> set[str]:
return {job["task"] for job in self.jobs.listed() if job["status"] in JOB_OPEN}
def blocked_rows(self, now: float) -> dict[str, str]:
return blocked_reasons(self.jobs.listed(), now)
def consoles(self) -> dict[str, dict]:
latest: dict[str, dict] = {}
for job in sorted(self.jobs.listed(), key=lambda job: job["created_ts"]):
+24 -6
View File
@@ -8,6 +8,7 @@ from .denying import requester_of
from .diffs import stored_diff
from .errors import Conflict, Missing, ToolError
from .fields import decode, expect, field
from .jobs import row_blocked
from .payloads import denied_roots, payload_files, payload_hash
from .previewing import merge_hash
from .records import digest, iso_epoch, read_jsonl
@@ -59,8 +60,8 @@ class Matching:
senders = {review["id"]: review.get("agent", "") for review in reviews}
cards = [{**self.commit_card(review, born_of(senders[review["id"]], names, claims), labels), "to": requester_of(claims, senders[review["id"]])[0]} for review in reviews if not self.batches.holds("review", review["id"])]
tasks = read_register(self.council / REGISTER)
held = self.open_jobs()
rows = [row for row in operator_rows(tasks) if row["check"] != "decision" and row["task"] not in held]
blocked = self.blocked_rows(now)
rows = [row for row in operator_rows(tasks) if row["check"] != "decision"]
releasing = {f"operator:{row['task']}" for row in rows if self.batches.holds("operator", row["task"])}
roots = denied_roots(self.settings_files()[0])
scan = self.tree.get()
@@ -68,7 +69,7 @@ class Matching:
if f"operator:{row['task']}" in releasing:
continue
owner = adder(tasks[row["task"]])
cards.append({**self.command_card(row, owner, born_of(owner, names, claims), roots, scan, labels), "to": requester_of(claims, owner)[0]})
cards.append({**self.command_card(row, owner, born_of(owner, names, claims), roots, scan, labels), "to": requester_of(claims, owner)[0], "blocked": row_blocked(row, blocked)})
items = self.inbox(now, tasks, self.directory(claims, read_jsonl(self.council / NEWS), now))
cards += [self.waiting_card(item, born_of(item["agent"], names, claims), scan, labels) for item in items if self.waits(item)]
asked = {row["task"] for row in operator_rows(tasks) if row["check"] == "decision"}
@@ -82,6 +83,17 @@ class Matching:
store.remove(snapshot["id"])
return {"now": now, "cards": cards}
def match_open(self, inbox: list[dict]) -> int:
"""Returns:
How many cards match_cards() lists that can be decided, by its
filters without building them: pending reviews, open command rows
not held by a release and without a row_blocked() reason, and the
inbox items waits() keeps.
"""
reviews = sum(1 for review in self.reviews.pending() if not self.batches.holds("review", review["id"]))
rows = sum(1 for row in self.open_rows() if not self.batches.holds("operator", row["task"]) and not row_blocked(row, {}))
return reviews + rows + sum(1 for item in inbox if self.waits(item))
def commit_card(self, review: dict, born: float | None, labels: dict | None) -> dict:
live = review.get("live_tree")
reason = "the staged tree changed since it was added" if live not in (None, review["tree"]) else ""
@@ -89,12 +101,17 @@ class Matching:
files = stored_diff(self.reviews.pages, "review", review["id"])["diff"]
except Missing:
files = None
preview = self.review_preview(review["id"])
if preview is not None:
files = preview.get("diff")
reason = reason or ("HEAD moved since it was added" if preview.get("moved") else "")
place = {"repo": repository_of(review.get("repo", "")), "branch": review["branch"], "worktree": review["worktree"]}
return {
"id": f"review:{review['id']}", "kind": "commit", "ref": review["id"], "agent": review.get("agent", ""), "born": born, "created_ts": iso_epoch(review["created"]),
**place, "title": review["title"], "score": review.get("score", ""), "metrics": metric_chips(review.get("score", ""), labels, True), "gate": review.get("gate", ""),
"hash": review["tree"], "live_hash": live or review["tree"],
"stale": bool(reason), "stale_reason": reason, "files": files, "command": "", "directory": review["worktree"], "reason": "",
"diff_error": None if preview is None else preview.get("error"),
}
def card_payload(self, row: dict, roots: list[str] | None) -> tuple[list[dict], str, dict | None]:
@@ -113,10 +130,11 @@ class Matching:
"""Returns:
Whether an inbox item is a Match card of its own: an ask, a
choice, a rule request, or a decision row not yet answered with
its current question, none held by a release in its undo window;
commits and commands have their own cards.
its current question, none held by a release in its undo window
nor snoozed in Waits on Operator; commits and commands have their
own cards.
"""
if item["held"]:
if item["held"] or item["until"]:
return False
if item["kind"] == "operator":
return item["check"] == "decision" and not item["settled"] and item["job"] is None and not item["answered"]
+60 -7
View File
@@ -4,9 +4,9 @@ import json
import re
import time
from .diffs import valid_diff
from .diffs import stored_diff, valid_diff
from .errors import Conflict, Missing, ToolError
from .fields import bounded, decode, expect
from .fields import bounded, decode, expect, field
from .records import digest
from .register import OPERATOR, REGISTER, operator_rows, read_register
from .signed import signing
@@ -15,12 +15,18 @@ OBJECT_ID = re.compile(r"[0-9a-f]{40}|[0-9a-f]{64}")
ERROR_LIMIT = 500
SHOWN = ("task", "command", "head", "base", "target", "diff")
FAILED = ("task", "command", "head", "error")
REVIEW_SHOWN = ("id", "head", "diff")
REVIEW_FAILED = ("id", "head", "error")
def card_id(task: str) -> str:
return f"operator:{task}"
def review_card(review_id: str) -> str:
return f"review:{review_id}"
def object_id(payload: dict, name: str, empty: bool) -> str:
value = payload[name]
if not isinstance(value, str) or not (OBJECT_ID.fullmatch(value) or (empty and value == "")):
@@ -51,22 +57,69 @@ class Previewing:
found = self.merge_previews.get(card_id(row["task"]))
return found if found is not None and found["command"] == row["command"] else None
def shipped(self, review_id: str) -> bool:
try:
return bool(stored_diff(self.reviews.pages, "review", review_id)["diff"])
except Missing:
return False
def review_preview(self, review_id: str) -> dict | None:
"""Returns:
The runner's diff of a review that shipped none, its staged tree
against its worktree's HEAD: {head, diff} or {head, error}, with
moved, the HEAD it saw later, once HEAD moved; None before any.
"""
return None if self.shipped(review_id) else self.merge_previews.get(review_card(review_id))
def preview_rows(self) -> dict:
"""Returns:
{"rows"}: every open operator row in an absolute directory with
the HEAD of the preview the hub holds, None for none, for the
runner to preview the git merges among them.
{"rows", "reviews"}: every open operator row in an absolute
directory with the HEAD of the preview the hub holds, None for
none, for the runner to preview the git merges among them; and
every pending review in an absolute worktree that shipped no
diff, with its tree and the HEAD the hub last saw, for the
runner to diff the tree against HEAD.
"""
rows = [row for row in self.open_rows() if row["directory"].startswith("/")]
return {"rows": [{"task": row["task"], "command": row["command"], "directory": row["directory"], "head": (self.preview_of(row) or {}).get("head")} for row in rows]}
reviews = [review for review in self.reviews.pending() if review["worktree"].startswith("/") and not self.shipped(review["id"])]
seen = {review["id"]: self.merge_previews.get(review_card(review["id"])) or {} for review in reviews}
return {
"rows": [{"task": row["task"], "command": row["command"], "directory": row["directory"], "head": (self.preview_of(row) or {}).get("head")} for row in rows],
"reviews": [{"id": review["id"], "worktree": review["worktree"], "tree": review["tree"], "head": seen[review["id"]].get("moved") or seen[review["id"]].get("head")} for review in reviews],
}
def record_review_preview(self, payload: dict) -> dict:
expect(payload, REVIEW_FAILED if "error" in payload else REVIEW_SHOWN)
review_id = field(payload, "id")
review = self.reviews.get(review_id)
if review is None or review["status"] != "pending":
raise Missing(review_id)
head = object_id(payload, "head", "error" in payload)
key = review_card(review_id)
found = self.merge_previews.get(key)
if found is not None and "diff" in found and found["head"] != head:
self.merge_previews.change(key, {"moved": head})
return {"id": key, "head": head}
record = {"head": head, "taken": time.time()}
if "error" in payload:
record["error"] = bounded(payload, "error", ERROR_LIMIT)
else:
record["diff"] = valid_diff(payload["diff"])
self.merge_previews.remove(key)
self.merge_previews.insert(key, record)
return {"id": key, "head": head}
def record_preview(self, body: bytes) -> dict:
"""Args:
body: from the runner, {task, command, head, base, target, diff}
for a git merge row, or {task, command, head, error} when it
could not preview it; head is empty when HEAD is unreadable.
could not preview it; {id, head, diff} or {id, head, error}
for a review that shipped no diff; head is empty when HEAD is
unreadable.
"""
payload = decode(body)
if "id" in payload:
return self.record_review_preview(payload)
expect(payload, FAILED if "error" in payload else SHOWN)
task = payload["task"]
if not isinstance(task, str) or not task.startswith(OPERATOR) or not signing.TASK.fullmatch(task):
+9 -4
View File
@@ -10,7 +10,7 @@ LABELS = "kvb-check-score/labels.json"
FILE_LIMIT = 64 << 20
VARIATION = "️"
VALUE = r"([0-9]+(?:\.[0-9]+)?(?:\s*%|:[0-9]+(?:\.[0-9]+)?)?|–|-|new)(?![0-9.])"
CHIP_EXTRAS = ("value",)
CHIP_EXTRAS = ("legal", "architecture", "value")
def checked(labels: object) -> dict | None:
@@ -71,7 +71,8 @@ def metric_chips(score: str, labels: dict | None, bare: bool) -> list[dict]:
text, where "fix 2 tests" is no score.
Returns:
In label order, then the CHIP_EXTRAS, per metric whose emoji (with or
In label order, each CHIP_EXTRAS entry right before the metric its
"before" names, else after all, per metric whose emoji (with or
without its variation selector) or label or former label stands
right before a value in score (the label alone only when bare), the
first such value: {"id", "emoji", "label", "value"}; none without
@@ -79,8 +80,12 @@ def metric_chips(score: str, labels: dict | None, bare: bool) -> list[dict]:
"""
found = []
extras = (labels or {}).get("extras")
shown = [(key, extras[key]) for key in CHIP_EXTRAS if isinstance(extras, dict) and checked({"metrics": {key: extras.get(key)}})]
for key, metric in [*(labels or {}).get("metrics", {}).items(), *shown]:
ordered = list((labels or {}).get("metrics", {}).items())
for key in CHIP_EXTRAS:
if isinstance(extras, dict) and checked({"metrics": {key: extras.get(key)}}):
keys = [name for name, _ in ordered]
ordered.insert(keys.index(extras[key]["before"]) if extras[key].get("before") in keys else len(ordered), (key, extras[key]))
for key, metric in ordered:
emoji = re.escape(metric["emoji"].removesuffix(VARIATION)) + f"{VARIATION}?"
names = "|".join(re.escape(name) for name in (metric["label"], *metric.get("former", [])))
alone = rf"|\b(?:{names})\s*:?\s*" if bare else ""
@@ -0,0 +1,40 @@
from __future__ import annotations
import re
from pathlib import Path
from .records import read_json
SKILLS_INDEX = "skills-index.json"
NAME = re.compile(r"[A-Za-z0-9:_.-]{1,100}")
TEXT_CHARS = 300
SOURCE_CHARS = 1000
SKILLS_LIMIT = 2000
def entry(raw: object) -> dict | None:
"""Returns:
{name, description, source} of an index row whose name matches NAME
and whose description and source are strings within their limits;
None for any other row.
"""
if not isinstance(raw, dict):
return None
name, description, source = raw.get("name"), raw.get("description"), raw.get("source")
if not isinstance(name, str) or not NAME.fullmatch(name) or not isinstance(description, str) or not isinstance(source, str) or not source or len(source) > SOURCE_CHARS:
return None
return {"name": name, "description": description[:TEXT_CHARS], "source": source}
def served(file: Path) -> dict:
"""Args:
file: the index client/skills_index.py writes next to the branch tree.
Returns:
{"skills"}: its valid rows, at most SKILLS_LIMIT, sorted by name and
source; none while the file is missing or unreadable.
"""
data = read_json(file)
rows = data.get("skills") if isinstance(data, dict) else None
found = [shown for raw in rows[:SKILLS_LIMIT] if (shown := entry(raw)) is not None] if isinstance(rows, list) else []
return {"skills": sorted(found, key=lambda row: (row["name"], row["source"]))}
+4 -3
View File
@@ -9,6 +9,7 @@ from .crons import cron_event
from .errors import Missing, ToolError
from .events import event, event_filters, wanted
from .fields import instant, single, whole
from .jobs import row_blocked
from .names import Directory
from .receipts import read_of
from .records import iso_epoch, read_jsonl
@@ -81,12 +82,12 @@ class Timeline:
source = directory.key(decision["agent"], decision["created_ts"])
who = {"agent": directory.at(source, decision["created_ts"]) or decision["agent"], "now": directory.now(source), "session": source}
rows.append(event({"id": f"decision:{decision['id']}", "ts": decision["created_ts"], "kind": "decision", **who, "title": decision["question"][:300], "text": text, "waiting": status == "pending", "ref": ref}))
held = self.open_jobs()
reasons = self.blocked_rows(now)
for row in operator_rows(tasks):
first = self.watch.first(row["task"], now)
if first <= end:
ref = {key: row[key] for key in ("task", "directory", "check", "status")}
rows.append(event({"id": f"operator:{row['task']}", "ts": first, "kind": "operator", "title": row["command"], "text": row["why"], "waiting": row["task"] not in held, "ref": ref}))
ref = {**{key: row[key] for key in ("task", "directory", "check", "status")}, "blocked": row_blocked(row, reasons)}
rows.append(event({"id": f"operator:{row['task']}", "ts": first, "kind": "operator", "title": row["command"], "text": row["why"], "waiting": True, "ref": ref}))
rows += [change for change in self.watch.listed() if begin <= change["ts"] <= end]
rows += [cron_event(cron, directory) for cron in self.schedules(claims, now) if cron["created"] <= end and (cron["active"] or cron["created"] >= begin)]
rows += [row for row in self.log.listed() if begin <= row["ts"] <= end]
+3 -3
View File
@@ -58,9 +58,9 @@ ENCODER_CSP = (
)
def badges(inbox: list[dict], claims: list[dict], jobs: list[dict], now: float) -> dict[str, int]:
def badges(cards: int, claims: list[dict], jobs: list[dict], now: float) -> dict[str, int]:
return {
"tasks": sum(1 for item in inbox if not item["until"] and not item["settled"]),
"tasks": cards,
"agents": len({claim["agent"] for claim in claims if claim["beat"] is not None and claim["beat"] >= now - ACTIVE}),
"artifacts": sum(1 for job in jobs if job["status"] in JOB_OPEN),
}
@@ -146,7 +146,7 @@ class View:
"speech": {**self.speech.describe(), "gate": self.speech_gate.state()},
"people": people,
"inbox": inbox,
"badges": badges(inbox, claims, self.jobs.listed(), now),
"badges": badges(self.match_open(inbox), claims, self.jobs.listed(), now),
"pending": self.batches.listed(),
"rules": [{**{key: value for key, value in rule.items() if key != "proof"}, "signed": rule.get("proof") is not None} for rule in self.rules.listed()],
"approvers": self.keys(),
+44 -8
View File
@@ -15,9 +15,9 @@ from .settings import flag, section
VIEW_LIMIT = 64 << 10
CHANGE_LIMIT = 2 * VIEW_LIMIT + (1 << 10)
VIEW = {
"resources": {"hidden": [], "tokens": "interval", "combined": False, "combinedHidden": []},
"resources": {"hidden": [], "tokens": "interval", "panels": ["hardware", "tokens", "accounts"], "combinedHidden": []},
"burn": {"overlays": []},
"home": {"pins": []},
"home": {"pins": [], "zoom": {}},
"kanban": {"hidden": []},
"legend": {"views": {}, "tiles": {}},
"approval": {"mode": "direct"},
@@ -37,8 +37,10 @@ OVERLAYS = ("fix", "break", "tokens", "velocity", "security", "score")
KANBAN_LAYERS = ("line", "jobs")
PINS_LIMIT = 64
SPAN = (1, 12)
ZOOM = (50, 200, 10)
METRIC = "metric"
CHARTS = ("hardware", "tokens", "combined")
PANELS = (*CHARTS, "accounts")
SHOWN_LIMIT = 100
FNV_PRIME = 0x01000193
FNV_SEEDS = (0x811C9DC5, 0x01000193)
@@ -145,6 +147,30 @@ def pins(value: object) -> list[dict]:
return found
def zooms(value: object) -> dict[str, int]:
"""Returns:
home.zoom: pin keys kind:id to a whole percent from 50 to 200 in
steps of 10; anything else raises ToolError.
"""
low, high, step = ZOOM
if not isinstance(value, dict) or not all(isinstance(key, str) and PIN_KEY.fullmatch(key) for key in value):
raise ToolError("home.zoom must map pin keys kind:id to a percent")
if not all(not isinstance(zoom, bool) and isinstance(zoom, int) and low <= zoom <= high and zoom % step == 0 for zoom in value.values()):
raise ToolError(f"home.zoom must hold whole percents from {low} to {high} in steps of {step}")
return dict(value)
def shown_panels(value: object) -> list[str]:
"""Returns:
resources.panels: the distinct Resources panels shown, at least
one; anything else raises ToolError.
"""
panels = members(value, "resources.panels", "panels", PANELS)
if not panels:
raise ToolError("resources.panels must show at least one panel")
return panels
def legend_flags(value: object, name: str, known: Callable[[str], object], what: str) -> dict[str, bool]:
"""Args:
value: a map of legend owners to whether their legend shows.
@@ -168,7 +194,7 @@ def valid_view(raw: object) -> dict:
Returns:
The document with every key of VIEW and nothing else; any other
key, a missing one or a malformed value raises ToolError. The
legend state of a tile whose pin left Home is dropped.
legend state and zoom of a tile whose pin left Home are dropped.
"""
data = section(raw, "view", tuple(VIEW))
resources = section(data["resources"], "resources", tuple(VIEW["resources"]))
@@ -188,11 +214,11 @@ def valid_view(raw: object) -> dict:
"resources": {
"hidden": series_ids(resources["hidden"], "resources.hidden"),
"tokens": resources["tokens"],
"combined": flag(resources["combined"], "resources.combined"),
"panels": shown_panels(resources["panels"]),
"combinedHidden": series_ids(resources["combinedHidden"], "resources.combinedHidden"),
},
"burn": {"overlays": members(burn["overlays"], "burn.overlays", "metrics", OVERLAYS)},
"home": {"pins": pinned},
"home": {"pins": pinned, "zoom": {key: zoom for key, zoom in zooms(home["zoom"]).items() if key in keys}},
"kanban": {"hidden": members(kanban["hidden"], "kanban.hidden", "layers", KANBAN_LAYERS)},
"legend": {
"views": legend_flags(legend["views"], "legend.views", LEGEND_PANELS.__contains__, f"panels of {', '.join(LEGEND_PANELS)}"),
@@ -204,10 +230,20 @@ def valid_view(raw: object) -> dict:
def upgraded(raw: object) -> object:
"""Returns:
A stored document of an older hub with each VIEW section it lacks
at its default; anything else as it is.
A stored document of an older hub with each VIEW section, and each
key of a section, it lacks at its default, and resources.combined,
which resources.panels replaced, turned into the panels it showed;
anything else as it is.
"""
return {**copy.deepcopy(VIEW), **raw} if isinstance(raw, dict) else raw
if not isinstance(raw, dict):
return raw
resources = raw.get("resources")
if isinstance(resources, dict) and "combined" in resources and "panels" not in resources:
combined = resources["combined"] is True
kept = {key: value for key, value in resources.items() if key != "combined"}
raw = {**raw, "resources": {**kept, "panels": ["combined", "accounts"] if combined else list(VIEW["resources"]["panels"])}}
merged = {**copy.deepcopy(VIEW), **raw}
return {name: {**copy.deepcopy(VIEW[name]), **value} if name in VIEW and isinstance(value, dict) else value for name, value in merged.items()}
def slot(view: dict, path: object) -> tuple[dict, str]:
@@ -1,5 +1,5 @@
[Unit]
Description=Agent Orchestrator tree: pkgmgr branch tree and the pkgmgr branch cleanup --local dry run into the files the orchestrator reads, while its page polls
Description=Agent Orchestrator tree: pkgmgr branch tree, the pkgmgr branch cleanup --local dry run and the skills index into the files the orchestrator reads, while its page polls
[Service]
Type=oneshot
@@ -7,6 +7,7 @@ Environment=PATH=/usr/bin:/bin
ExecCondition=/bin/sh -c 'test -n "$(find %h/.local/state/kvb-orchestrator/tree-heartbeat -mmin -5 2>/dev/null)"'
ExecStart=%h/.local/share/kvb-orchestrator/pkgmgr/bin/pkgmgr branch tree --format json --output %h/.local/state/pkgmgr/tree/branch-tree.json
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/local_plan.py --tree %h/.local/state/pkgmgr/tree/branch-tree.json --pkgmgr %h/.local/share/kvb-orchestrator/pkgmgr/bin/pkgmgr --budget 240
ExecStart=/usr/bin/env python3 %h/.local/share/kvb-orchestrator/client/skills_index.py --home %h --tree %h/.local/state/pkgmgr/tree/branch-tree.json --output %h/.local/state/pkgmgr/tree/skills-index.json
Nice=10
IOSchedulingClass=idle
CPUQuota=50%
+40
View File
@@ -0,0 +1,40 @@
const Answers = (() => {
const plain = (option) => String(option.label).trim().toLowerCase();
/**
* @param item - an inbox item or Match card with kind, and for a choice its options and multi.
* @returns {Object|null} {yes, no}: the labels of a single choice whose only options are Yes and No, else null.
*/
function pair(item) {
const options = item.options || [];
if (item.multi || options.length !== 2) {
return null;
}
const yes = options.find((option) => plain(option) === "yes");
const no = options.find((option) => plain(option) === "no");
return yes && no ? {yes: yes.label, no: no.label} : null;
}
/**
* @param item - as pair() takes it.
* @returns {boolean} whether Accept and Reject answer it without a numbered form: a permission ask or a Yes/No choice.
*/
const boolean = (item) => item.kind === "ask" || pair(item) !== null;
/**
* @param no - the No label of the choice.
* @param text - the typed comment, maybe empty or multi-line.
* @param limit - the longest answer the hub takes.
* @returns {string} No without a comment, else "No: comment" on one line as the Other answer, cut to limit; never an option label.
*/
function declined(no, text, limit) {
const line = text.replace(/\s+/g, " ").trim();
return line ? `${no}: ${line}`.slice(0, limit).trim() : no;
}
return {pair, boolean, declined};
})();
if (typeof module === "object" && module.exports) {
module.exports = Answers;
}
+1 -8
View File
@@ -1,7 +1,6 @@
const Diffs = (() => {
"use strict";
const COLLAPSE = 400;
const QUOTE_LIMIT = 2000;
const HUNK = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;
const KINDS = {"+": "add", "-": "del", " ": "ctx"};
@@ -45,15 +44,9 @@ const Diffs = (() => {
return [from, from + quote.split("\n").length - 1];
}
function quoted(text) {
const clean = String(text).trim();
return clean.length > QUOTE_LIMIT ? `${clean.slice(0, QUOTE_LIMIT)}…` : clean;
}
const feedback = (ref, path, from, to, quote, words) => `Feedback on ${ref} ${path}:${from}-${to}: "${quoted(quote)}" ${String(words).trim()}`;
const feedbackOf = (messages, ref) => messages.filter((message) => String(message.text).startsWith(`Feedback on ${ref} `));
return {COLLAPSE, QUOTE_LIMIT, rows, collapsed, span, lineSpan, quoted, feedback, feedbackOf};
return {COLLAPSE, rows, collapsed, span, lineSpan, feedbackOf};
})();
if (typeof module === "object" && module.exports) {
module.exports = Diffs;
+32 -9
View File
@@ -90,11 +90,11 @@ h1 { margin: 0; font-size: var(--fs-lg); font-weight: 680; letter-spacing: -.01e
.updated.offline::before { background: var(--bad); box-shadow: 0 0 0 3px var(--bad-soft); }
body.leitstand { --fs-xs: 13px; --fs-sm: 14px; --fs-md: 16px; --fs-lg: 18px; --fs-xl: 21px; --fs-2xl: 26px; --fs-3xl: 44px; }
.shell { padding: var(--sp-4) var(--sp-4) var(--sp-6); }
main { min-width: 0; min-height: calc(100vh - var(--head) - var(--sp-6) - var(--sp-4)); padding: var(--sp-5) var(--sp-5) 80px; background: var(--glass); border: 1px solid color-mix(in srgb, var(--line) 70%, transparent); border-radius: var(--radius-lg); box-shadow: var(--shadow); }
main { --main-pad: var(--sp-5); --main-top: var(--main-pad); min-width: 0; min-height: calc(100vh - var(--head) - var(--sp-6) - var(--sp-4)); padding: var(--main-top) var(--main-pad) 80px; background: var(--glass); border: 1px solid color-mix(in srgb, var(--line) 70%, transparent); border-radius: var(--radius-lg); box-shadow: var(--shadow); }
@media (max-width: 640px) {
.top, .navbar, .banner { gap: var(--sp-2); padding: var(--sp-2) var(--sp-3); }
.shell { padding: var(--sp-2) var(--sp-2) var(--sp-6); }
main { padding: var(--sp-3) var(--sp-3) 88px; border-radius: var(--radius); }
main { --main-pad: var(--sp-3); padding: var(--main-top) var(--main-pad) 88px; border-radius: var(--radius); }
.menu-box { position: fixed; top: auto; right: var(--sp-2); left: var(--sp-2); width: auto; }
.replay { flex-basis: 100%; min-width: 0; }
.sheet { padding: 0; }
@@ -217,9 +217,12 @@ table.diff tr.more td { padding: 8px 16px; color: var(--muted); font-style: ital
.route .headline { font-weight: 600; overflow-wrap: anywhere; }
.filters { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 12px; margin-bottom: 10px; }
.filters select, .filters input, .field { padding: 6px 10px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); }
.filters input[type="search"] { flex: 1; min-width: 200px; }
.filters input[type="search"], .filters > .mic-line { flex: 1; min-width: 200px; }
.graph { display: grid; gap: 14px; }
.controls { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 18px; padding: 10px 14px; }
.box-head { display: flex; flex: none; flex-wrap: wrap; align-items: center; gap: 6px 10px; margin: calc(-1 * var(--main-top)) calc(-1 * var(--main-pad)) 0; padding: 4px 6px 4px 8px; border-bottom: 1px solid var(--line); font-size: var(--fs-sm); }
.box-head > .box-title { display: inline-flex; align-items: center; gap: 6px; margin: 0; font-size: var(--fs-sm); font-weight: 650; }
.box-head .field { padding-block: 3px; }
.box-head > .box-slot { display: contents; }
.segmented { display: inline-flex; padding: 3px; gap: 2px; border-radius: 10px; background: var(--sunken); border: 1px solid var(--line); }
.segmented button { padding: 4px 11px; border: 0; border-radius: 8px; background: transparent; color: var(--muted); font-size: var(--fs-sm); font-weight: 580; cursor: pointer; }
.segmented button[aria-selected="true"], .segmented button[aria-pressed="true"] { background: var(--panel); color: var(--text); box-shadow: var(--shadow); }
@@ -341,15 +344,27 @@ textarea { width: 100%; min-height: 84px; padding: 8px 10px; border: 1px solid v
.palette-box input { width: 100%; padding: 14px 16px; border: 0; background: transparent; font-size: var(--fs-lg); outline: none; }
.palette-row { display: flex; align-items: center; gap: 6px; padding-right: 10px; border-bottom: 1px solid var(--line); }
.palette-row input { flex: 1; min-width: 0; }
.mic { flex: none; }
.mic-frame { min-width: 0; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); }
.mic-frame:focus-within { outline: 2px solid var(--accent); outline-offset: 1px; }
.mic-frame > :is(input, textarea, .field) { border: 0; border-radius: 0; background: transparent; box-shadow: none; outline: none; }
.mic-line { display: flex; align-items: stretch; width: 100%; }
:is(.filters, .box-head, .palette-row, .row, .tool-add, .actions, .chips) > .mic-line { flex: 1 1 12rem; width: auto; }
.mic-line > input { flex: 1; width: auto; min-width: 0; }
.mic-area { display: flex; flex-direction: column; width: 100%; }
.mic-area > textarea { display: block; width: 100%; min-width: 0; }
.mic-foot { display: flex; align-items: center; gap: 6px; min-height: 32px; padding: 2px 3px 2px 8px; border-top: 1px solid var(--line); }
.mic { display: inline-grid; flex: none; place-items: center; min-width: 34px; padding: 0 8px; border: 0; background: transparent; color: var(--muted); cursor: pointer; }
.mic:hover:not(:disabled) { background: var(--hover); color: var(--text); }
.mic:disabled { cursor: not-allowed; opacity: .55; }
.mic-line > .mic { border-left: 1px solid var(--line); border-radius: 0 9px 9px 0; }
.mic-foot > .mic { min-height: 28px; border-radius: 8px; }
.palette-row > .mic-line { border: 0; border-radius: 0; }
.mic[aria-pressed="true"] { background: var(--bad-soft); color: var(--bad); animation: mic-pulse 1.2s ease-in-out infinite; }
.mic-auto { margin-left: 4px; vertical-align: middle; }
textarea + .mic-auto { display: flex; margin: 4px 0 0 auto; }
.mic-live { position: fixed; left: 50%; bottom: calc(18px + env(safe-area-inset-bottom, 0px)); z-index: 60; display: flex; align-items: center; gap: 8px; max-width: calc(100vw - 32px); padding: 8px 14px; transform: translateX(-50%); border-radius: 999px; background: var(--bad); color: #fff; font-weight: 650; box-shadow: var(--shadow-lift); }
.mic-live[hidden] { display: none; }
.mic-live::before { content: ""; flex: none; width: 10px; height: 10px; border-radius: 50%; background: #fff; animation: mic-pulse 1s ease-in-out infinite; }
@keyframes mic-pulse { 50% { opacity: .45; } }
@media (max-width: 640px) { .btn.small.mic { min-width: 44px; min-height: 44px; } }
@media (max-width: 640px) { .mic { min-width: 44px; } .mic-foot > .mic { min-height: 44px; } }
@media (prefers-reduced-motion: reduce) { .mic[aria-pressed="true"], .mic-live::before { animation: none; } }
.palette-list { max-height: 55vh; margin: 0; padding: 6px; overflow: auto; list-style: none; }
.palette-list li { display: flex; align-items: center; gap: 10px; padding: 8px 10px; border-radius: 8px; cursor: pointer; }
@@ -407,7 +422,8 @@ textarea + .mic-auto { display: flex; margin: 4px 0 0 auto; }
.wt { display: flex; flex-wrap: wrap; align-items: center; gap: 6px 12px; padding: 7px 10px; border-radius: 8px; background: var(--sunken); font-size: var(--fs-sm); }
.wt code { overflow-wrap: anywhere; }
.rule-row { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; padding: 8px 10px; border: 1px solid var(--line); border-radius: 10px; }
.rule-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; align-items: end; }
.rule-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 10px; align-items: start; }
.rule-form > label.check, .rule-form > button { align-self: end; }
.rule-form label, .sound-row label { display: grid; gap: 4px; color: var(--muted); font-size: var(--fs-sm); }
.sound-row { display: grid; grid-template-columns: minmax(0, 1fr) auto minmax(120px, 220px) auto; align-items: center; gap: var(--sp-3); padding: var(--sp-2) 0; border-bottom: 1px solid var(--line); }
.settings { display: grid; gap: var(--sp-5); }
@@ -550,6 +566,10 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "glossary.js" %}
{% include "settings-files.js" %}
{% include "answers.js" %}
{% include "ancestry.js" %}
{% include "popup.js" %}
@@ -676,11 +696,14 @@ pre.notes { margin: 0; padding: 8px 10px; background: var(--sunken); border-radi
{% include "page-mic.js" %}
{% include "page-slash.js" %}
{% include "page-bubbles.js" %}
{% include "page-alerts.js" %}
{% include "page-resources.js" %}
{% include "page-accounts.js" %}
{% include "page-rates.js" %}
+139
View File
@@ -0,0 +1,139 @@
const ACCOUNT_DAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
const ACCOUNT_COLUMNS = ["Provider", "Email", "Renewal", "Next reset", "Resubscribe", "Autorenew", "Since reset", "Today", "Total", "Remaining", ""];
const accountsView = {data: null, busy: false, body: null};
const momentText = (moment) => `${ACCOUNT_DAYS[moment.day]} ${moment.time}`;
function accountsPanel() {
const body = h("div", {class: "acc-body"});
accountsView.body = body;
const add = iconBtn("bi-plus-lg", "Add account", "btn small soft", () => accountSheet(null), "Add account: provider, email, renewal and weekly reset; kept on this host only");
const panel = h("section", {class: "card res-panel res-accounts", "data-panel": "resources-accounts", "aria-label": "Accounts"},
h("div", {class: "res-head", "data-star-slot": ""}, h("span", {class: "res-title", title: "Accounts", "aria-label": "Accounts"}, icon("bi-person-badge")), h("span", {class: "acc-title"}, "Accounts"), h("span", {class: "spacer"}), add), body);
return {panel, body};
}
async function fetchAccounts() {
if (accountsView.busy) {
return;
}
accountsView.busy = true;
try {
const response = await fetch("/api/accounts", {cache: "no-store"});
if (response.ok) {
accountsView.data = await response.json();
}
} catch {
ui.offline = true;
}
accountsView.busy = false;
drawAccounts();
}
/**
* @param data - /api/accounts: {accounts, active, usage}.
* @param now - epoch milliseconds.
* @returns the table rows: each account with its next reset and usage, sorted by the next reset, then one
* unassigned row for the tokens of no stored account, when there are any.
*/
function accountRows(data, now) {
const empty = {total: 0, hours: []};
const rows = data.accounts.map((account) => ({account, next: Resources.nextMoment(account.reset, now), used: Resources.accountUsage(data.usage[account.email] || empty, account.reset, now)}));
rows.sort((a, b) => a.next - b.next || a.account.email.localeCompare(b.account.email));
const known = new Set(data.accounts.map((account) => account.email));
const rest = Object.entries(data.usage).filter(([email]) => !known.has(email)).map(([, entry]) => entry);
const unassigned = {total: rest.reduce((sum, entry) => sum + entry.total, 0), hours: rest.flatMap((entry) => entry.hours)};
return unassigned.total ? [...rows, {account: null, next: null, used: Resources.accountUsage(unassigned, null, now)}] : rows;
}
function accountRow(row, active) {
const count = (value) => (value === null ? "–" : Resources.compact(value));
if (row.account === null) {
return h("tr", {class: "acc-unassigned", "data-account": ""}, h("td", {colspan: 6}, "Unassigned: sessions the SessionStart hook mapped to no stored account"),
h("td", {}, "–"), h("td", {}, count(row.used.today)), h("td", {}, count(row.used.total)), h("td", {}, "–"), h("td", {}));
}
const {account} = row;
const remaining = account.limit === null ? null : Math.max(0, account.limit - row.used.since);
const isActive = account.email === active;
return h("tr", {"data-account": account.id, ...(isActive ? {"data-active": ""} : {})},
h("td", {}, account.provider), h("td", {}, account.email, isActive ? h("span", {class: "pill", "data-tone": "ok", title: "The account Claude Code logged in with at the last session start"}, "active") : null),
h("td", {}, momentText(account.renewal)), h("td", {title: momentText(account.reset)}, absolute.format(new Date(row.next))), h("td", {}, account.resubscribe || "–"),
h("td", {}, account.autorenew ? "yes" : "no"), h("td", {}, count(row.used.since)), h("td", {}, count(row.used.today)), h("td", {}, count(row.used.total)),
h("td", {title: account.limit === null ? "No weekly limit set" : `Limit ${account.limit} minus the tokens since the last reset`}, count(remaining)),
h("td", {}, iconBtn("bi-pencil", `Edit ${account.email}`, "btn small ghost", () => accountSheet(account), "Edit or remove this account")));
}
function accountsContent(data) {
if (data === null) {
return h("p", {class: "muted"}, "…");
}
const rows = accountRows(data, Date.now());
if (!rows.length) {
return h("p", {class: "muted"}, "No account yet. Add one: it stays on this host, in the hub's state only.");
}
return h("div", {class: "acc-scroll"}, h("table", {class: "acc-table"},
h("thead", {}, h("tr", {}, ACCOUNT_COLUMNS.map((name) => h("th", {scope: "col"}, name)))),
h("tbody", {}, rows.map((row) => accountRow(row, data.active)))));
}
function drawAccounts() {
const body = accountsView.body;
if (body && body.isConnected) {
body.replaceChildren(accountsContent(accountsView.data));
}
}
function homeAccounts() {
homeFetch("accounts", fetchAccounts);
return h("div", {class: "acc-body"}, accountsContent(accountsView.data));
}
function momentFields(label, moment) {
const day = h("select", {class: "field", "aria-label": `${label} weekday`}, ACCOUNT_DAYS.map((name, index) => h("option", {value: String(index), ...(moment && moment.day === index ? {selected: true} : {})}, name)));
const time = h("input", {type: "time", class: "field", "aria-label": `${label} time`, value: moment ? moment.time : "00:00"});
return {day, time, row: h("div", {class: "acc-field"}, h("span", {}, label), h("div", {class: "acc-pair"}, day, time))};
}
function accountSheet(account) {
const text = (label, type, value, extra) => h("input", {type, class: "field", "aria-label": label, value, ...extra});
const provider = text("Provider", "text", account ? account.provider : "", {maxlength: 40});
const email = text("Email", "email", account ? account.email : "", {});
const renewal = momentFields("Renewal", account && account.renewal);
const reset = momentFields("Weekly reset", account && account.reset);
const resubscribe = text("Resubscribe", "date", account ? account.resubscribe : "", {});
const autorenew = h("input", {type: "checkbox", "aria-label": "Autorenew", ...(account && account.autorenew ? {checked: true} : {})});
const limit = text("Weekly token limit", "number", account && account.limit !== null ? String(account.limit) : "", {min: 0, step: 1});
const note = text("Note", "text", account ? account.note : "", {maxlength: 200});
const labelled = (label, input) => h("label", {class: "acc-field"}, h("span", {}, label), input);
const save = h("button", {type: "button", class: "btn primary"}, icon("bi-check-lg"), "Save");
save.addEventListener("click", async () => {
const fields = {
provider: provider.value.trim(), email: email.value.trim(), renewal: {day: Number(renewal.day.value), time: renewal.time.value}, reset: {day: Number(reset.day.value), time: reset.time.value},
resubscribe: resubscribe.value, autorenew: autorenew.checked, limit: limit.value === "" ? null : Number(limit.value), note: note.value.trim(),
};
const result = await sendJson("/api/accounts", {id: account ? account.id : "", account: fields});
if (!result.ok) {
toast("Account: not saved", fail(result), false);
return;
}
closeSheet();
fetchAccounts();
});
const remove = account ? h("button", {type: "button", class: "btn danger"}, icon("bi-trash"), "Remove") : null;
if (remove) {
remove.addEventListener("click", async () => {
const result = await sendJson(`/api/accounts/${account.id}/delete`, {});
if (!result.ok) {
toast("Account: not removed", fail(result), false);
return;
}
closeSheet();
fetchAccounts();
});
}
openSheet(account ? `Account: ${account.email}` : "Add account", [
h("p", {class: "muted"}, "Kept on this host in the hub's state, mode 0600; never in git, the view store or the radio."),
h("div", {class: "acc-form"}, labelled("Provider", provider), labelled("Email", email), renewal.row, reset.row, labelled("Resubscribe", resubscribe),
labelled("Autorenew", autorenew), labelled("Weekly token limit", limit), labelled("Note", note)),
h("div", {class: "actions"}, remove, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), save)], false);
provider.focus();
}
+3 -3
View File
@@ -88,13 +88,13 @@
function openAgent(who, anchor, closed) {
const key = agentKey(who);
const name = nameOf(key);
const text = h("textarea", {"aria-label": `Message to ${name}`, placeholder: `Message to ${name} …`});
const text = h("textarea", {"aria-label": `Message to ${name}`, placeholder: `Message to ${name} …`, "data-skills": ""});
const file = h("input", {type: "file", class: "field", "aria-label": "Attach file"});
const button = h("button", {type: "submit", class: "btn primary icon-only", ...named("Send")}, icon("bi-send"));
const classes = choice("to-one", TO_ONE, "post");
const form = h("form", {class: "popup-form"}, text, file, classes,
const form = h("form", {class: "popup-form"}, micFrame(text, []), file, classes,
h("p", {class: "muted"}, "Post arrives at the end of the turn, Call at once with a read receipt; your passkey signs, verifiable with operator_message."),
h("div", {class: "actions"}, h("span", {class: "spacer"}), micButton(text, false), button));
h("div", {class: "actions"}, h("span", {class: "spacer"}), button));
form.addEventListener("submit", async (event) => {
event.preventDefault();
if (!text.value.trim()) {
+2 -2
View File
@@ -277,8 +277,8 @@
drawArtifacts();
fetchTree();
}, 0);
const controls = h("div", {class: "card controls"}, viewSwitch("artifacts"), view === "3d" ? layoutTools("artifacts") : view === "tree" ? null : picker,
h("div", {class: "toolbar", role: "toolbar", "aria-label": "Artifacts"}, search, reload, removeAll, apply), count);
const controls = boxHead("Artifacts", "", viewSwitch("artifacts"), view === "3d" ? layoutTools("artifacts") : view === "tree" ? null : picker,
h("div", {class: "toolbar"}, search, reload, removeAll, apply), count);
const body = view === "tree" ? h("div", {class: "tree-panel", "data-panel": "artifacts/tree"}, list) : h("div", {class: "card stage-card", "data-panel": `artifacts/${view}`}, stageBox, legendBox);
return h("div", {class: "graph"}, controls, body);
}
+7 -3
View File
@@ -17,11 +17,15 @@
.sort(([one, a], [two, b]) => a.localeCompare(b) || one.localeCompare(two));
async function confirmAct(action, agents) {
const [, label, question] = actionOf(action);
const [, , question] = actionOf(action);
const names = new Map(nightAgents());
if (!window.confirm(agents.length ? question.replace("all agents", agents.map((sid) => names.get(sid) || sid).join(", ")) : question)) {
return;
if (window.confirm(agents.length ? question.replace("all agents", agents.map((sid) => names.get(sid) || sid).join(", ")) : question)) {
await signedAct(action, agents);
}
}
async function signedAct(action, agents) {
const [, label] = actionOf(action);
const chosen = agents.length ? {agents} : {};
const signed = await signedProof("/api/board/sign", {action, ...chosen}, label);
if (signed) {
+1
View File
@@ -41,6 +41,7 @@
window.addEventListener("resize", placeStations);
skyPanel();
micWatch();
slashWatch();
radioSpot();
radio.element = radioElement();
drawSky();
+1 -1
View File
@@ -4,7 +4,7 @@
async function requestChoices(cls) {
const direct = TO_ONE.some(([id]) => id === cls);
const to = direct ? [...choiceAsk.to].sort((a, b) => a.localeCompare(b)) : ["*"];
if ((direct && !to.length) || (cls === "mayday" && !confirmMayday())) {
if ((direct && !to.length) || (cls === "mayday" && !window.confirm(MAYDAY_ASK))) {
return;
}
const label = `Choice request (${CLASSES[cls]}) to ${direct ? to.join(", ") : "all"}`;
+77 -24
View File
@@ -1,4 +1,4 @@
const CHANNELS = [...TO_ONE, ...TO_ALL];
const CHANNELS = [...TO_ONE, ...TO_ALL].filter(([id]) => id !== "mayday");
const CHANNEL_HINTS = {
post: "Post arrives at the end of the turn.",
call: "Call arrives at once, with a read receipt.",
@@ -6,14 +6,52 @@
broadcast: "Broadcast reaches all at once.",
"pan-pan": "PAN-PAN: urgent, to all, at once.",
security: "Sécurité: safety notice to all stations, now.",
mayday: "MAYDAY: all agents pause writing steps until you cancel it.",
};
const MAYDAY_ASK = "Send a mayday to all? All agents pause writing steps until you cancel it.";
const VOICE_POLL = 700;
const HOLD_MS = 350;
const composer = {live: null};
function confirmMayday() {
return window.confirm("Send a mayday to all? All agents pause writing steps until you cancel it.");
/**
* @param {boolean} silence whether a mayday holds the radio silent.
* @returns {Object} {pressed, label, hint}: the MAYDAY toggle's face: Cancel mayday while one is active.
*/
function maydayFace(silence) {
const [, cancel, , cancelHint] = actionOf("clear-mayday");
return silence ? {pressed: true, label: cancel, hint: cancelHint} : {pressed: false, label: "MAYDAY", hint: "MAYDAY: send the message as mayday to all; all agents pause writing steps until you cancel it"};
}
function drawMayday(button) {
const shown = maydayFace(Boolean(state.silence));
button.setAttribute("aria-pressed", String(shown.pressed));
button.title = shown.hint;
button.replaceChildren(icon("bi-life-preserver"), shown.label);
}
/**
* @param {Element} form the composer the question shows in, above its footer, its last child.
* @param {string} question what the operator confirms.
* @param {string} yes the confirming button's label.
* @returns {Promise<boolean>} true on yes, false on Cancel or Escape; nothing leaves the page before.
*/
function inlineConfirm(form, question, yes) {
form.querySelectorAll(".mayday-confirm").forEach((node) => node.remove());
return new Promise((resolve) => {
const done = (answer) => {
box.remove();
resolve(answer);
};
const accept = h("button", {type: "button", class: "btn small danger", on: {click: () => done(true)}}, yes);
const box = h("div", {class: "mayday-confirm", role: "alertdialog", "aria-label": question}, h("p", {}, question), h("div", {class: "actions"}, h("button", {type: "button", class: "btn small ghost", on: {click: () => done(false)}}, "Cancel"), accept));
box.addEventListener("keydown", (event) => {
if (event.key === "Escape") {
event.stopPropagation();
done(false);
}
});
form.lastElementChild.before(box);
accept.focus();
});
}
async function radioSend(message) {
@@ -169,12 +207,11 @@
}
function composerForm() {
const channel = h("select", {class: "field"}, CHANNELS.map(([id, label]) => h("option", {value: id}, label)));
const channel = h("select", {class: "field"}, CHANNELS.map(([id, label]) => h("option", {value: id, title: CHANNEL_HINTS[id]}, label)));
const recipient = h("select", {class: "field"});
const toField = h("label", {}, "To", recipient);
const text = h("textarea", {"aria-label": "Message", placeholder: "Message to the agents …", maxlength: 20000});
const text = h("textarea", {"aria-label": "Message", placeholder: "Message to the agents …", maxlength: 20000, "data-skills": ""});
const replay = h("div", {class: "voice-note", hidden: true});
const hint = h("span", {class: "muted composer-hint"});
const status = h("span", {class: "muted composer-status", "aria-live": "polite"});
const record = h("button", {type: "button", class: "btn small", "aria-pressed": "false", title: "Record: one click starts, another stops, you check the text before sending; hold it to talk, release to send"});
const submit = h("button", {type: "submit", class: "btn primary ptt", title: "PTT: push to transmit the message; your passkey signs it"}, icon("bi-broadcast-pin"), "PTT");
@@ -199,38 +236,54 @@
startRecording(parts);
}
});
const [, cancel, , cancelHint] = actionOf("clear-mayday");
const clear = h("button", {type: "button", class: "btn small danger radio-cancel", hidden: !state.silence, ...named(cancel, cancelHint), on: {click: () => confirmAct("clear-mayday", [])}}, icon("bi-life-preserver"), cancel);
const mayday = h("button", {type: "button", class: "btn small danger mayday-toggle", "aria-pressed": "false"});
drawMayday(mayday);
const sync = () => {
const direct = TO_ONE.some(([id]) => id === channel.value);
toField.hidden = !direct;
hint.textContent = `${CHANNEL_HINTS[channel.value]} Your passkey signs every message.`;
channel.title = hint.textContent;
toField.hidden = !TO_ONE.some(([id]) => id === channel.value);
channel.title = CHANNEL_HINTS[channel.value];
};
channel.addEventListener("change", sync);
sync();
const form = h("form", {class: "composer"}, h("div", {class: "composer-grid"}, h("label", {}, "Channel", channel), toField), text, replay,
h("div", {class: "actions"}, record, micButton(text, false), status, hint, clear, h("div", {class: "ptt-split", role: "group", "aria-label": "Send"}, submit, testMenu(text, channel))));
form.addEventListener("submit", async (event) => {
event.preventDefault();
const direct = TO_ONE.some(([id]) => id === channel.value);
const form = h("form", {class: "composer"}, h("div", {class: "composer-grid"}, h("label", {}, "Channel", channel), toField), micFrame(text, [record]), replay,
h("div", {class: "actions"}, status, h("div", {class: "ptt-split", role: "group", "aria-label": "Send"}, submit, testMenu(text, channel)), mayday));
const empty = () => {
if (!text.value.trim()) {
toast("Nothing to send", ["Write a text or record one; the transcript lands in the field for checking."], false);
return;
}
if ((direct && !recipient.value) || (channel.value === "mayday" && !confirmMayday())) {
return;
}
return !text.value.trim();
};
const send = async (to, cls) => {
submit.disabled = true;
if (await radioSend({to: direct ? recipient.value : "*", text: text.value, upload: "", cls: channel.value, voice: attach.checked ? parts.voice : ""})) {
mayday.disabled = true;
if (await radioSend({to, text: text.value, upload: "", cls, voice: attach.checked ? parts.voice : ""})) {
text.value = "";
status.textContent = "";
attachVoice(parts, "");
}
submit.disabled = false;
mayday.disabled = false;
};
mayday.addEventListener("click", async () => {
if (state.silence) {
if (await inlineConfirm(form, actionOf("clear-mayday")[2], maydayFace(true).label)) {
await signedAct("clear-mayday", []);
}
return;
}
if (!empty() && (await inlineConfirm(form, MAYDAY_ASK, "Send mayday"))) {
await send("*", "mayday");
}
});
form.addEventListener("submit", async (event) => {
event.preventDefault();
const direct = TO_ONE.some(([id]) => id === channel.value);
if (empty() || (direct && !recipient.value)) {
return;
}
await send(direct ? recipient.value : "*", channel.value);
});
attachVoice(parts, "");
return {form, recipient, text, channel, clear};
return {form, recipient, text, channel, mayday};
}
function holdToTalk(parts) {
+1 -1
View File
@@ -75,7 +75,7 @@
direct: [[740, 0, 0.2]],
radio: [[520, 0, 0.07]],
};
const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["Right-click", "Context menu: the element's commands, then the tab's, then the general ones"], ["Shift+right-click", "The browser's own context menu"], ["Menu key · Shift+F10", "Context menu of the focused element: ↑ / ↓ move, Enter runs, Esc closes"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Feedback on the selected lines of a diff or a command"], ["→ · ← · ↑", "Match: accept · reject with feedback · later"],["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / − · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]];
const KEYS = [["Ctrl+K", "Commands, views, agents and AI command"], ["Right-click", "Context menu: the element's commands, then the tab's, then the general ones"], ["Shift+right-click", "The browser's own context menu"], ["Menu key · Shift+F10", "Context menu of the focused element: ↑ / ↓ move, Enter runs, Esc closes"], ["1 · 2 · 3 · 4", "Stream · Agents · Artifacts · Tasks"], ["j / k", "Waits on Operator: next / previous entry"], ["x", "Waits on Operator: select entry"], ["a", "Waits on Operator: grant entry (3 s to undo)"], ["Enter", "Waits on Operator: open entry"], ["f", "Comment on the selected lines of a diff or a command: it goes with Deny as a call, or after Grant as a post"], ["→ · ← · ↑", "Match: accept · reject with feedback · later"],["/", "Search the stream"], ["h", "Look at the sky: drag turns the view, wheel or two fingers zoom, Esc ends"], ["Arrows · + / − · 0", "Sky (focused): turn · zoom · reset"], ["Drag · wheel", "3D: turn, right drag pans, wheel zooms"], ["+ / − · 0 · Ctrl+wheel", "Home tile (focused): zoom its content in · out · reset"],["🎙 hold", "Voice input into the agent field or the command line, never sent automatically"], ["?", "This help"], ["Esc", "Close"]];
const calm = window.matchMedia("(prefers-reduced-motion: reduce)");
const relative = new Intl.RelativeTimeFormat("en", {numeric: "auto"});
const absolute = new Intl.DateTimeFormat("en-GB", {dateStyle: "medium", timeStyle: "short"});
+12 -1
View File
@@ -37,7 +37,7 @@
}
function ctxPathItems(node, path) {
return [...feedbackItems(), ...(path === "-" ? [] : [ctxCopyItem("Copy path", path)])];
return [...feedbackItems(node), ...(path === "-" ? [] : [ctxCopyItem("Copy path", path)])];
}
function ctxEntryItems(node, ref) {
@@ -69,6 +69,15 @@
return [...opens, {label: pinned ? "Unpin from Home" : "Pin to Home", hint: entry.title, run: () => homePress(target.kind, target.id, entry.title, target.view)}];
}
function ctxTileItems(node, key) {
const hint = `${node.querySelector(".home-title").textContent}: zoom its content`;
return [
{label: "Zoom in", hint: `${hint} (+)`, run: () => homeZoomBy(key, 1)},
{label: "Zoom out", hint: `${hint} (-)`, run: () => homeZoomBy(key, -1)},
{label: `Reset zoom (${homeZoom(key)} %)`, hint: `${hint} (0)`, run: () => homeZoomBy(key, 0)},
];
}
const CTX_KINDS = [
{kind: "task", id: ctxAttr("data-task"), title: (id) => `Task ${id}`, items: ctxTaskItems},
{kind: "agent", id: ctxAgentOf, title: (key) => nameOf(key), items: ctxAgentItems},
@@ -78,6 +87,7 @@
{kind: "rule", id: ctxAttr("data-rule", "data-entry"), title: (id) => `Rule ${id}`, items: (node, id) => [ctxCopyItem("Copy rule", id)]},
{kind: "pick", id: ctxAttr("data-pick"), title: ctxPickTitle, items: ctxPickItems},
{kind: "pin", id: ctxPinOf, title: (target) => ctxPinEntry(target).title, items: ctxPinItems},
{kind: "tile", id: (node) => (node.matches(".home-tile[data-pin]") ? node.dataset.pin : null), title: (key) => `Tile ${key}`, items: ctxTileItems},
];
/**
@@ -175,6 +185,7 @@
function ctxOpen(target, at) {
closeMenus(null);
ctxMenu.back = document.activeElement;
diffView.hit = target;
ctxShow(ctxSections(target), at);
}
+39 -4
View File
@@ -9,8 +9,12 @@
* @param {string} reason the operator's reason, possibly empty.
* @param {string} to the agent a direct channel tells; a class to all keeps the item's requester.
*/
function denyNow(item, channel, reason, to) {
return submit([{...entryOf(item, "reject", ""), channel, reason, to: DIRECT_DENY.has(channel) ? to : item.to}], `Denial (${CLASSES[channel]}): ${short(item.title)}`);
async function denyNow(item, channel, reason, to) {
const denied = await submit([{...entryOf(item, "reject", ""), channel, reason, to: DIRECT_DENY.has(channel) ? to : item.to}], `Denial (${CLASSES[channel]}): ${short(item.title)}`);
if (denied && lineNotes(keyOf(item))) {
setLineMarks(keyOf(item), []);
}
return denied;
}
/**
@@ -57,7 +61,8 @@
h("span", {}, h("strong", {}, CLASSES[id]), small));
});
recipient.addEventListener("change", paintDeny);
const reason = h("textarea", {class: "field", maxlength: DENY_REASON, rows: 3, placeholder: "e.g. make the gate green first"});
const reason = h("textarea", {class: "field", maxlength: DENY_REASON, rows: 3, placeholder: "e.g. make the gate green first", "data-skills": item.repo || ""});
reason.value = lineNotes(keyOf(item)).slice(0, DENY_REASON);
confirm.addEventListener("click", () => {
const channel = picked().value;
closeSheet();
@@ -78,7 +83,7 @@
}
function denySplit(item) {
const main = iconBtn("bi-x-lg", "Deny", "btn small danger", () => denyNow(item, "post", "", item.to), item.to ? `Deny: by post to ${revealed(item.to)}, 3 s to undo` : "Deny: the card names no agent; pick one under Deny via …");
const main = iconBtn("bi-x-lg", "Deny", "btn small danger", () => (lineNotes(keyOf(item)) ? denySheet(item) : denyNow(item, "post", "", item.to)), item.to ? `Deny: by post to ${revealed(item.to)}, 3 s to undo; with line comments it opens Deny via … with them as the reason` : "Deny: the card names no agent; pick one under Deny via …");
main.disabled = !item.to;
const more = h("button", {type: "button", class: "btn small danger icon-only", "aria-haspopup": "dialog", ...named("Deny via …", "Deny via another channel or with a reason")}, caret());
more.addEventListener("click", (event) => {
@@ -87,3 +92,33 @@
});
return h("div", {class: "deny-split", role: "group", "aria-label": "Deny"}, main, more);
}
/**
* @param {Object} item a Yes/No choice or decision row.
* @param {string} no its No label.
* @param {Function} answer sends the label it is given.
*/
function declineSheet(item, no, answer) {
const words = h("textarea", {class: "field", rows: 4, maxlength: OTHER_LIMIT, "aria-label": "Comment", "data-skills": ""});
const confirm = h("button", {type: "button", class: "btn danger"}, icon("bi-x-lg"), revealed(no));
confirm.addEventListener("click", () => {
closeSheet();
answer(Answers.declined(no, words.value, OTHER_LIMIT));
});
openSheet(`${revealed(no)}: ${short(item.title)}`, [h("p", {class: "muted"}, `Optional: what to do instead; it goes with the answer ${revealed(no)} on one line.`), reasonChips(words), words,
h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), confirm)], false);
words.focus();
}
/**
* @param {Object} item a Yes/No choice or decision row.
* @param {Function} answer sends the label it is given: chooseOne() for a choice, answerPick() for a row.
* @returns {HTMLElement[]} the grant button answering Yes and the decline button answering No with an optional comment.
*/
function yesNoButtons(item, answer) {
const {yes, no} = Answers.pair(item);
return [
h("button", {type: "button", class: "btn small primary", disabled: ui.busy, ...named(revealed(yes), `${revealed(yes)}: answer ${short(item.title)}`), on: {click: () => answer(yes)}}, icon("bi-check-lg"), revealed(yes)),
h("button", {type: "button", class: "btn small danger", disabled: ui.busy, ...named(revealed(no), `${revealed(no)}: answer it, with an optional comment on what to do instead`), on: {click: () => declineSheet(item, no, answer)}}, icon("bi-x-lg"), revealed(no)),
];
}
+1 -1
View File
@@ -78,7 +78,7 @@
send.addEventListener("click", () => how.pick(item.options.filter((option) => how.toggled.has(option.label)).map((option) => option.label).join(PICKED), false));
}
const typed = chosen.length === 1 && !item.options.some((option) => option.label === chosen[0]) ? chosen[0] : null;
const input = h("input", {class: "field", type: "text", maxlength: OTHER_LIMIT, placeholder: how.other, "aria-label": `Other answer to ${item.id}`, value: typed || drafts.get(item.id) || null, disabled: how.locked});
const input = h("input", {class: "field", type: "text", maxlength: OTHER_LIMIT, placeholder: how.other, "aria-label": `Other answer to ${item.id}`, value: typed || drafts.get(item.id) || null, disabled: how.locked, "data-skills": item.repo || ""});
input.addEventListener("input", () => drafts.set(item.id, input.value));
const other = h("form", {class: "option other"}, input,
h("button", {type: "submit", class: "btn small", disabled: how.locked, ...named("Send", revealed(`Send this text: ${how.hint}`))}, icon("bi-send"), "Send"));
+115 -38
View File
@@ -1,8 +1,56 @@
const DIFF_TONES = {A: "ok", M: "info", D: "bad", R: "violet", B: "neutral"};
const HIDDEN_NOTES = new Set(["masked", "content withheld"]);
const diffView = {cache: new Map(), revealed: new Map(), version: 0, float: null, picked: null, timer: 0};
const LINE_NOTES_GO = "Your line comments go to the requesting agent with Deny as a call, or after Grant as a post.";
const LINE_JOIN = ";\n";
const diffView = {cache: new Map(), revealed: new Map(), marks: new Map(), version: 0, float: null, picked: null, timer: 0, hit: null};
const revealedOf = (item) => diffView.revealed.get(keyOf(item)) || new Map();
const hiddenFile = (item, file) => HIDDEN_NOTES.has(file.note) && !revealedOf(item).has(file.path);
const lineMarksOf = (ref) => diffView.marks.get(ref) || [];
const lineSpanOf = (mark) => `${mark.path}:${mark.from === mark.until ? mark.from : `${mark.from}-${mark.until}`}`;
/**
* @param {string} ref the keyOf() of an inbox item.
* @returns {string} its line comments as "path:line: comment" in the order they were set, joined by LINE_JOIN so they
* stay apart once a denial folds the lines into one; "" without one.
*/
const lineNotes = (ref) => lineMarksOf(ref).map((mark) => `${lineSpanOf(mark)}: ${mark.comment}`).join(LINE_JOIN);
/**
* @param {string} ref the keyOf() of an inbox item.
* @param {Object[]} marks its line comments [{path, from, until, comment}]; empty forgets them.
*/
function setLineMarks(ref, marks) {
if (marks.length) {
diffView.marks.set(ref, marks);
} else {
diffView.marks.delete(ref);
}
diffView.version += 1;
drawInbox();
drawStream();
repaintReview();
}
/**
* @param {string} ref the keyOf() of the item the rows belong to.
* @param {string} path the file the rows show.
* @param {HTMLElement[]} rows its table rows; a code row carries data-line.
* @returns {HTMLElement[]} the rows, each commented one marked and its comments shown after the last line they cover.
*/
function withLineMarks(ref, path, rows) {
const marks = lineMarksOf(ref).filter((mark) => mark.path === path);
const placed = new Set();
return rows.flatMap((row) => {
const line = Number(row.dataset.line);
if (!marks.some((mark) => line >= mark.from && line <= mark.until)) {
return [row];
}
row.setAttribute("class", `${row.getAttribute("class") || ""} marked`.trim());
const here = marks.filter((mark) => mark.until === line && !placed.has(mark));
here.forEach((mark) => placed.add(mark));
return [row, ...here.map((mark) => h("tr", {class: "match-mark", "data-line": line}, h("td", {colspan: row.children.length}, icon("bi-chat-square-text"), h("span", {class: "match-mark-text"}, revealed(mark.comment)))))];
});
}
function forgetRevealed() {
const waiting = new Set(state.inbox.map(keyOf));
@@ -105,7 +153,7 @@
if (file.status === "B" || !file.patch) {
return h("section", {class: "diff-file", "data-path": file.path, "data-status": file.status, "data-patch": "none", "data-hidden": shown}, h("div", {class: "diff-head"}, head));
}
const table = h("table", {class: "diff"}, h("tbody", {}, Diffs.rows(file.patch).map(patchRow)));
const table = h("table", {class: "diff"}, h("tbody", {}, withLineMarks(keyOf(item), file.path, Diffs.rows(file.patch).map(patchRow))));
return h("section", {class: "diff-file", "data-path": file.path, "data-status": file.status, "data-hidden": shown},
h("details", {open: !Diffs.collapsed(file)}, h("summary", {class: "diff-head"}, head), h("div", {class: "diff-scroll"}, table)));
}
@@ -126,7 +174,58 @@
function feedbackList(ref) {
const sent = Diffs.feedbackOf(state.messages, ref);
return sent.length ? h("ul", {class: "feedback-list", "aria-label": `Feedback: ${sent.length}`}, sent.map((message) => h("li", {}, icon("bi-chat-left-text"), h("span", {class: "text"}, message.text), when(message.created_ts)))) : null;
const marks = lineMarksOf(ref);
const marked = marks.map((mark, index) => h("li", {class: "line-mark"}, icon("bi-bookmark-fill"), h("code", {}, revealed(lineSpanOf(mark))), h("span", {class: "text"}, revealed(mark.comment)),
iconBtn("bi-x-lg", "Remove comment", "btn small ghost", () => setLineMarks(ref, marks.filter((_, at) => at !== index)), `Remove the comment on ${revealed(lineSpanOf(mark))}`)));
return sent.length || marks.length ? h("ul", {class: "feedback-list", "aria-label": `Feedback: ${sent.length + marks.length}`, title: marks.length ? LINE_NOTES_GO : null}, marked,
sent.map((message) => h("li", {}, icon("bi-chat-left-text"), h("span", {class: "text"}, message.text), when(message.created_ts)))) : null;
}
/**
* @param {HTMLElement} row a code row with data-line, as a right-click hits it.
* @returns {Object|null} the row as the lines a comment covers, like selectionFeedback(); null outside a [data-path] region of an item with a requester.
*/
function rowPick(row) {
const region = row.closest("[data-path]");
const card = region && region.closest("[data-ref]");
if (!card || !card.dataset.to || !row.dataset.line || row.classList.contains("match-mark") || row.closest(".match-card")) {
return null;
}
const line = Number(row.dataset.line);
return {ref: card.dataset.ref, to: card.dataset.to, path: region.dataset.path, from: line, until: line, anchor: row, inline: Boolean(region.closest("#sheet"))};
}
/**
* @param {Object} picked the lines to comment: {ref, to, path, from, until, anchor, inline}; inline puts the field
* under the anchor instead of a sheet of its own.
*/
function markLines(picked) {
hideFeedback();
const words = h("textarea", {class: "field", rows: 3, maxlength: OTHER_LIMIT, "aria-label": "Comment", placeholder: "Comment on these lines", "data-skills": ""});
const save = () => {
const comment = words.value.trim();
if (!comment) {
words.focus();
return false;
}
setLineMarks(picked.ref, [...lineMarksOf(picked.ref), {path: picked.path, from: picked.from, until: picked.until, comment}]);
rememberComment(comment);
return true;
};
const head = h("code", {}, revealed(lineSpanOf(picked)));
const chips = presetChips(words, savedComments(), "Recent comments");
const saveButton = (cls, done) => h("button", {type: "button", class: cls, ...named("Save comment", LINE_NOTES_GO), on: {click: () => save() && done()}}, icon("bi-bookmark-fill"), "Save");
if (picked.inline) {
const box = h("div", {class: "match-comment-box"}, head, chips, words);
const field = picked.anchor.tagName === "TR" ? h("tr", {class: "match-comment"}, h("td", {colspan: picked.anchor.children.length}, box)) : h("div", {class: "match-comment"}, box);
box.append(h("div", {class: "actions"}, btn("Cancel", "btn small ghost", () => field.remove()), saveButton("btn small primary", () => field.remove())));
document.querySelectorAll("#sheet .match-comment").forEach((open) => open.remove());
picked.anchor.after(field);
} else {
openSheet("Comment", [h("div", {class: "who"}, icon("bi-chat-left-text"), person(picked.to), head), h("p", {class: "muted"}, LINE_NOTES_GO), chips, words,
h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), saveButton("btn primary", closeSheet))], false);
}
words.focus();
}
function selectionFeedback() {
@@ -143,36 +242,12 @@
}
const quote = selection.toString();
const code = region.querySelector("code");
const lines = region.classList.contains("command") && code
? Diffs.lineSpan(code.textContent, quote)
: Diffs.span([...region.querySelectorAll("tr[data-line]")].filter((row) => range.intersectsNode(row)).map((row) => Number(row.dataset.line)));
const rows = [...region.querySelectorAll("tr[data-line]")].filter((row) => !row.classList.contains("match-mark") && range.intersectsNode(row));
const lines = region.classList.contains("command") && code ? Diffs.lineSpan(code.textContent, quote) : Diffs.span(rows.map((row) => Number(row.dataset.line)));
if (!lines) {
return null;
}
return {ref: card.dataset.ref, to: card.dataset.to, path: region.dataset.path, from: lines[0], until: lines[1], quote, rect: range.getBoundingClientRect()};
}
function feedbackSheet(picked) {
hideFeedback();
const words = h("textarea", {class: "field", rows: 4, "aria-label": "Feedback", title: "Feedback"});
const send = iconBtn("bi-send", "Send feedback", "btn primary", async () => {
if (!words.value.trim()) {
words.focus();
return;
}
send.disabled = true;
const sent = await radioSend({to: picked.to, text: Diffs.feedback(picked.ref, picked.path, picked.from, picked.until, picked.quote, words.value), upload: "", cls: "post", voice: ""});
send.disabled = false;
if (sent) {
closeSheet();
}
}, `Send feedback: a post to ${picked.to}`);
openSheet("Feedback", [
h("div", {class: "who"}, icon("bi-chat-left-text"), person(picked.to), h("code", {}, `${picked.path}:${picked.from}-${picked.until}`)),
h("pre", {class: "notes"}, Diffs.quoted(picked.quote)),
words,
h("div", {class: "actions"}, h("span", {class: "spacer"}), send)], false);
words.focus();
return {ref: card.dataset.ref, to: card.dataset.to, path: region.dataset.path, from: lines[0], until: lines[1], anchor: rows.length ? rows[rows.length - 1] : region, inline: Boolean(region.closest("#sheet")), rect: range.getBoundingClientRect()};
}
function hideFeedback() {
@@ -185,9 +260,9 @@
function showFeedback(picked, x, y) {
if (!diffView.float) {
diffView.float = h("div", {class: "feedback-float", role: "toolbar", hidden: true},
h("button", {type: "button", class: "btn small primary icon-only", ...named("Feedback", "Feedback (f): a post with the selected lines to the requesting agent"), on: {
h("button", {type: "button", class: "btn small primary icon-only", ...named("Comment", `Comment (f) on the selected lines. ${LINE_NOTES_GO}`), on: {
mousedown: (event) => event.preventDefault(),
click: () => diffView.picked && feedbackSheet(diffView.picked),
click: () => diffView.picked && markLines(diffView.picked),
}}, icon("bi-chat-left-text")));
document.body.append(diffView.float);
}
@@ -210,18 +285,20 @@
}
/**
* @returns the context menu items of a [data-path] region, a diff file or a command: Feedback while lines of one are
* selected.
* @param {HTMLElement} node the [data-path] region the menu is for.
* @returns the context menu items of a diff file or a command: Comment on the selected lines, else on the code row the
* right-click hit.
*/
function feedbackItems() {
const picked = selectionFeedback();
return picked ? [{label: "Feedback", hint: "f: a post with the selected lines to the requesting agent", run: () => feedbackSheet(picked)}] : [];
function feedbackItems(node) {
const row = diffView.hit && node.contains(diffView.hit) ? diffView.hit.closest("tr[data-line]") : null;
const picked = selectionFeedback() || (row ? rowPick(row) : null);
return picked ? [{label: "Comment", hint: `f: ${lineSpanOf(picked)}. ${LINE_NOTES_GO}`, run: () => markLines(picked)}] : [];
}
function feedbackKey() {
const picked = selectionFeedback();
if (picked) {
feedbackSheet(picked);
markLines(picked);
}
return Boolean(picked);
}
+1
View File
@@ -21,6 +21,7 @@
const caret = () => icon("bi-caret-down-fill", "caret");
const named = (label, hint) => ({title: hint || label, "aria-label": label});
const iconBtn = (name, label, cls, run, hint) => h("button", {type: "button", class: `${cls} icon-only`, ...named(label, hint), on: {click: run}}, icon(name));
const boxHead = (label, cls, ...children) => h("div", {class: cls ? `box-head ${cls}` : "box-head", role: children.flat(Infinity).some((child) => child instanceof Node && child.getAttribute("role") === "toolbar") ? "group" : "toolbar", "aria-label": label}, ...children);
const dash = (value) => (value === "" || value === "-" || value === null || value === undefined ? "–" : value);
const targetsOf = (row) => (row.to.length ? row.to.join(", ") : "all");
const fixed = (value) => value.toFixed(1);
+37 -11
View File
@@ -23,7 +23,7 @@
};
const SWITCH_TITLES = {enableArtifact: "Artifacts"};
const OTHER_OP = {add: "remove", remove: "add"};
const firewall = {data: null, busy: false, staged: {}, dom: null, targets: new Set(), picks: {}, shown: new Set(ROW_FILTERS.map(([id]) => id)), open: new Set(), tab: CONTROL_TABS[0][0]};
const firewall = {data: null, busy: false, staged: {}, dom: null, targets: new Set(), picks: {}, shown: new Set(ROW_FILTERS.map(([id]) => id)), open: new Set(), tab: CONTROL_TABS[0][0], missing: false};
const knownAgents = () => Object.keys(people()).filter((key) => key !== HUMAN && SESSION_KEY.test(key)).sort();
const firewallGroups = () => (firewall.data ? firewall.data.groups : []);
@@ -214,7 +214,7 @@
tabs[id] = h("button", {type: "button", role: "tab", id: `controls-tab-${id}`, "data-tab": id, "aria-controls": `controls-${id}`, "aria-selected": String(firewall.tab === id), on: {click: () => pick(id)}}, icon(glyph), label);
views[id] = h("div", {class: "stack", role: "tabpanel", id: `controls-${id}`, "aria-labelledby": `controls-tab-${id}`, hidden: firewall.tab !== id}, panels[id]);
}
return h("div", {class: "stack controls"}, h("h2", {class: "title"}, "Controls"), h("div", {class: "segmented", role: "tablist", "aria-label": "Controls"}, Object.values(tabs)), Object.values(views), bar);
return h("div", {class: "stack fw-controls"}, boxHead("Controls", "", h("h2", {class: "box-title"}, "Controls"), h("div", {class: "segmented", role: "tablist", "aria-label": "Controls"}, Object.values(tabs))), Object.values(views), bar);
}
async function firewallPost(path, payload, label) {
@@ -224,15 +224,28 @@
return result.ok;
}
/**
* @param {string} label the field's name, shown above the chips.
* @param {Array} items [value, text, leading node or null] per chip.
* @param {HTMLElement|null} empty what the field shows when items is empty.
* @returns {Object} {node, chosen}: the field and a reader of the checked values.
*/
function checkChips(label, items, empty) {
const boxes = items.map(([value, text, lead]) => ({value, box: h("input", {type: "checkbox", value}), text, lead}));
const node = h("div", {class: "fw-chips-field"}, h("span", {class: "fw-chips-label"}, label), items.length
? h("div", {class: "chips check-chips", role: "group", "aria-label": label}, boxes.map(({box, text, lead}) => h("label", {class: "chip check-chip"}, box, lead, h("span", {}, text))))
: empty);
return {node, chosen: () => boxes.filter(({box}) => box.checked).map(({value}) => value)};
}
function groupsCard() {
const name = h("input", {class: "field", type: "text", placeholder: "builders", "aria-label": "Group name"});
const members = h("select", {class: "field", multiple: true, size: Math.min(Math.max(knownAgents().length, 2), 6), "aria-label": "Members"}, knownAgents().map((key) => h("option", {value: key}, labelOf(key))));
const form = h("form", {class: "fw-form", "aria-label": "New agent group"}, h("label", {}, "Name", name), h("label", {}, "Members", members),
const members = checkChips("Members", knownAgents().map((key) => [key, labelOf(key), face(key, false)]), h("p", {class: "muted"}, "No agent known yet: agents appear once they post or claim work."));
const form = h("form", {class: "fw-form", "aria-label": "New agent group"}, h("label", {}, "Name", name), members.node,
h("button", {type: "submit", class: "btn soft", ...named("Add group", "Add group: name the chosen agents as one rule target")}, icon("bi-people"), "Add group"));
form.addEventListener("submit", async (event) => {
event.preventDefault();
const chosen = [...members.selectedOptions].map((option) => option.value).sort();
await firewallPost("/api/firewall/groups", {name: name.value.trim(), members: chosen}, "Group added");
await firewallPost("/api/firewall/groups", {name: name.value.trim(), members: members.chosen().sort()}, "Group added");
});
const rows = firewallGroups().map((group) => h("div", {class: "rule-row", "data-group": group.name}, h("strong", {}, revealed(group.name)), h("span", {class: "muted"}, revealed(group.members.map(labelOf).join(", "))), h("span", {class: "spacer"}),
iconBtn("bi-trash3", "Delete group", "btn small danger", () => firewallPost(`/api/firewall/groups/${encodeURIComponent(group.id)}/delete`, {}, "Group deleted"), revealed(`Delete group ${group.name}: rules signed for it keep their agents`))));
@@ -244,12 +257,13 @@
function setsCard() {
const name = h("input", {class: "field", type: "text", placeholder: "ci", "aria-label": "Set name"});
const days = h("input", {class: "field", type: "number", min: 1, max: 366, value: 7, "aria-label": "Days"});
const chosen = h("select", {class: "field", multiple: true, size: Math.min(Math.max(state.rules.length, 2), 6), "aria-label": "Rules"}, state.rules.map((rule) => h("option", {value: rule.id}, revealed(`${rule.kind} ${rule.tool} ${rule.pattern}`.replace(" ", " ")))));
const form = h("form", {class: "fw-form", "aria-label": "New rule set"}, h("label", {}, "Name", name), h("label", {}, "Days", days), h("label", {}, "Rules", chosen),
const chosen = checkChips("Rules", state.rules.map((rule) => [rule.id, revealed(`${rule.kind} ${rule.tool} ${rule.pattern}`.replace(" ", " ")), null]),
h("p", {class: "muted"}, "No rule yet: create one under Rules, New hub rule for automatic grants, then pick it here."));
const form = h("form", {class: "fw-form", "aria-label": "New rule set"}, h("label", {}, "Name", name), h("label", {}, "Days", days), chosen.node,
h("button", {type: "submit", class: "btn soft", ...named("Save set", "Save set: keep the chosen rules as one named rule set")}, icon("bi-collection"), "Save set"));
form.addEventListener("submit", async (event) => {
event.preventDefault();
await firewallPost("/api/firewall/sets", {name: name.value.trim(), days: Number(days.value), rules: [...chosen.selectedOptions].map((option) => option.value)}, "Rule set saved");
await firewallPost("/api/firewall/sets", {name: name.value.trim(), days: Number(days.value), rules: chosen.chosen()}, "Rule set saved");
});
const sets = firewall.data ? firewall.data.sets : [];
const rows = sets.map((set) => setRow(set));
@@ -339,7 +353,7 @@
const byAction = (one, two) => ACTION_ORDER.indexOf(one.filter) - ACTION_ORDER.indexOf(two.filter);
function sourceGroups() {
return [{id: HUB_SOURCE, label: "Hub rules", file: false, status: null, rows: signedRows()}, ...firewall.data.files.map((file) => ({id: file.path, label: file.path, file: true, status: fileStatus(file), rows: fileRows(file)}))];
return [{id: HUB_SOURCE, label: "Hub rules", file: false, status: null, rows: signedRows()}, ...SettingsFiles.listed(firewall.data.files, firewall.missing).shown.map((file) => ({id: file.path, label: file.path, file: true, status: fileStatus(file), rows: fileRows(file)}))];
}
function hitsCell(row) {
@@ -540,7 +554,19 @@
return h("section", {class: "card stack-tight fw-rules", "aria-label": "Firewall rules"}, h("h3", {}, "Firewall rules"),
h("p", {class: "muted"}, `Every rule in one table: the hub rules and the permissions and sandbox entries of the listed settings files as the host read them, one folded group per source. Hits count the asks of the last ${data.days} days a rule matches, with the matcher of the rule request dry run; allow, deny and sandbox entries never reach the ask ledger and show not seen. A settings change shows as a diff, is signed with your passkey and is written by the host, never by an agent.`),
data.error ? h("p", {class: "muted"}, data.error) : null,
filterChips(), ruleTable(), files.length ? addForm(files) : null);
h("div", {class: "row fw-filters"}, filterChips(), missingToggle(SettingsFiles.listed(files, false).missing)), ruleTable(), files.length ? addForm(files) : null);
}
function missingToggle(count) {
if (!count) {
return null;
}
const label = `${firewall.missing ? "hide" : "show"} ${count} missing`;
return h("button", {type: "button", class: "btn small ghost fw-missing", "aria-pressed": String(firewall.missing),
...named(label, `${label}: settings files whose folder does not exist on this host; a change cannot create them`), on: {click: () => {
firewall.missing = !firewall.missing;
drawFirewall();
}}}, icon(firewall.missing ? "bi-eye-slash" : "bi-eye"), label);
}
function diffLines(text) {
+1 -1
View File
@@ -186,5 +186,5 @@
const toolbar = agentsToolbar();
graphDom = {stage: stageBox, pulses: null, toolbar};
const body = view === "tree" ? spawnScreen() : view === "hierarchy" ? hierarchyScreen() : h("div", {class: "card stage-card", "data-panel": `agents/${view}`}, stageBox, view === "3d" ? null : legend());
return h("div", {class: "graph"}, h("div", {class: "card controls"}, viewSwitch("agents"), view === "3d" ? layoutTools("agents") : null, toolbar.bar), body);
return h("div", {class: "graph"}, boxHead("Agents", "", viewSwitch("agents"), view === "3d" ? layoutTools("agents") : null, toolbar.bar), body);
}
+44 -3
View File
@@ -1,4 +1,6 @@
const HOME_PATH = "home.pins";
const ZOOM_PATH = "home.zoom";
const ZOOM_KEYS = {"+": 1, "=": 1, "-": -1, "0": 0};
const HOME_FETCH = 3000;
const HOME_MESSAGE = 30000;
const HOME_MARKS = [['section[aria-label="Recently sent"]', "radio-log"]];
@@ -146,6 +148,12 @@
return row ? h("ol", {class: "task-list"}, taskItem(row, etaOf().get(row.task))) : null;
}
function homeBoard() {
const board = kanbanBoard(shownTasks());
homeView.heads.set("tasks/board", board.querySelector(".kanban-bar"));
return board;
}
function homeTaskList() {
const etas = etaOf();
return h("ol", {class: "task-list"}, Plan.sortRows(shownTasks(), taskView.sort, taskView.descending).map((row) => taskItem(row, etas.get(row.task))));
@@ -167,7 +175,7 @@
Panels.panel("artifacts/swimlane", "Artifacts: Swimlane", () => homeArt("swimlane"));
Panels.panel("artifacts/3d", "Artifacts: 3D", () => homeTree(() => home3d("artifacts")), "3d");
Panels.panel("tasks/list", "Tasks: list", homeTaskList);
Panels.panel("tasks/board", "Tasks: kanban", () => kanbanBoard(shownTasks()));
Panels.panel("tasks/board", "Tasks: kanban", homeBoard);
Panels.panel("tasks/rasci", "Tasks: RASCI", () => taskMatrix(shownTasks()));
Panels.panel("tasks/gantt", "Tasks: Gantt", () => ganttChart(shownTasks()));
Panels.panel("tasks/burn", "Tasks: burndown and burnup", () => burnChart(state.tasks, shownTasks()));
@@ -181,6 +189,7 @@
Panels.panel("agents/order", "Agents: priority", homeOrder);
Panels.panel("tasks/operator", "Tasks: Waits on Operator", homeInbox);
Panels.panel("tasks/match", "Tasks: Match", () => homeMatch(), "", [6, 8]);
Panels.panel("resources-accounts", "Resources: accounts", () => homeAccounts(), "", [12, 5]);
Panels.item("metric", (id, view) => metricTitle(view), (size, id, view) => homeMetric(id, view));
Panels.capture("resources-hardware", () => resourcePin("hardware"));
Panels.capture("resources-tokens", () => resourcePin("tokens"));
@@ -466,11 +475,40 @@
function homeKeys(event, key) {
const steps = {ArrowLeft: -1, ArrowUp: -1, ArrowRight: 1, ArrowDown: 1};
if (event.target !== event.currentTarget || !Object.hasOwn(steps, event.key) || event.altKey || event.ctrlKey || event.metaKey) {
if (event.target !== event.currentTarget || event.altKey || event.ctrlKey || event.metaKey) {
return;
}
if (Object.hasOwn(ZOOM_KEYS, event.key)) {
event.preventDefault();
event.stopPropagation();
homeZoomBy(key, ZOOM_KEYS[event.key]);
} else if (Object.hasOwn(steps, event.key)) {
event.preventDefault();
homeSave((pins) => Panels.moveKey(pins, key, steps[event.key]));
}
}
const homeZoom = (key) => ViewStore.get(ZOOM_PATH)[key] || Panels.ZOOM.base;
function homeZoomBy(key, step) {
ViewStore.update(ZOOM_PATH, (zooms) => Panels.zoomBy(zooms, key, step));
}
function homeWheel(event, key) {
if (!event.ctrlKey || !event.deltaY) {
return;
}
event.preventDefault();
homeSave((pins) => Panels.moveKey(pins, key, steps[event.key]));
homeZoomBy(key, event.deltaY < 0 ? 1 : -1);
}
function paintZoom(tile) {
const zoom = homeZoom(tile.dataset.pin);
const body = tile.querySelector(".home-body");
if (body.dataset.zoom !== String(zoom)) {
body.dataset.zoom = String(zoom);
body.style.setProperty("--zoom", String(zoom / 100));
}
}
function homeSizeKeys(event, key) {
@@ -501,6 +539,7 @@
grip.addEventListener("pointerdown", (event) => homeGrab(event, key, "move"));
handle.addEventListener("pointerdown", (event) => homeGrab(event, key, "size"));
handle.addEventListener("keydown", (event) => homeSizeKeys(event, key));
body.addEventListener("wheel", (event) => homeWheel(event, key), {passive: false});
homeView.tiles.set(key, tile);
return tile;
}
@@ -560,6 +599,7 @@
if (body.childNodes.length !== 1 || body.firstChild !== shown) {
body.replaceChildren(shown);
}
paintZoom(tile);
}
function drawHome() {
@@ -614,6 +654,7 @@
drawHome();
homeView.mark();
});
ViewStore.on(ZOOM_PATH, () => drawHome());
homeView.mark = Panels.decorate(document.body, {pinned: (kind, id) => Panels.has(homePins(), kind, id), press: homePress, marks: HOME_MARKS});
window.addEventListener("pointermove", homeDragMove);
window.addEventListener("pointerup", homeDragEnd);
+51 -9
View File
@@ -114,12 +114,32 @@
}
return submit([entryOf(item, "approve", item.recommended)], `Choice: ${shownPick(item.recommended)}`);
}
return submit([entryOf(item, "approve", "")], `${item.kind === "operator" ? "Run" : "Grant"}: ${short(item.title)}`);
return withGrantNotes(item, submit([entryOf(item, "approve", "")], `${item.kind === "operator" ? "Run" : "Grant"}: ${short(item.title)}`));
}
/**
* @param {Object} item the granted inbox item.
* @param {Promise<boolean>|boolean} granted whether its grant went through.
* @returns {Promise<boolean>} granted; once it holds, the item's line comments go to its requester as one post and
* are forgotten.
*/
async function withGrantNotes(item, granted) {
const done = await granted;
const notes = lineNotes(keyOf(item));
if (!done || !notes) {
return done;
}
if (!item.to) {
toast("Line comments kept", ["The card names no agent to post them to."], false);
} else if (await radioSend({to: item.to, text: `Granted: ${item.title}. Notes:\n${notes}`, upload: "", cls: "post", voice: ""})) {
setLineMarks(keyOf(item), []);
}
return done;
}
const chooseOne = (item, label) => (picking(item) ? collectPick(item, label) : submit([entryOf(item, "approve", label)], `Choice: ${shownPick(label)}`));
const answerPick = (item, label) => (picking(item) ? collectPick(item, label) : answerRow(item, label));
const grantSolo = (item) => (item.kind === "rule" ? acceptRule(item) : submit([entryOf(item, "approve", "")], `Grant: ${short(item.title)}`));
const grantSolo = (item) => (item.kind === "rule" ? acceptRule(item) : withGrantNotes(item, submit([entryOf(item, "approve", "")], `Grant: ${short(item.title)}`)));
const asked = (item) => item.kind === "operator" && item.check === "decision";
async function answerRow(item, answer) {
@@ -139,14 +159,18 @@
* @param {string} answer the picked label, or the typed text.
* @param {boolean} typed whether answer is typed text, which always denies with it as the reason.
*/
const answerAsk = (item, answer, typed) => (!typed && answer === ALLOW ? approveOne(item) : denyNow(item, "post", typed ? answer : "", item.to));
const answerAsk = (item, answer, typed) => (!typed && answer === ALLOW ? approveOne(item) : denyNow(item, lineNotes(keyOf(item)) ? "call" : "post", withNotes(item, typed ? answer : ""), item.to));
/**
* @param {Object} item an inbox item.
* @param {Function} after called before a picked answer is sent.
* @returns {HTMLElement|Array|null} the choiceDialog() of a decision, a decision row or a permission ask, with its recipient line for a row; null for every other item.
* @returns {HTMLElement|Array|null} the choiceDialog() of a decision or a decision row with named options, with its recipient line for a row; only
* that line for a Yes/No row and null for a permission ask or a Yes/No decision, which booleanActions() answers; null for every other item.
*/
const choiceOf = (item, after) => {
if (Answers.boolean(item)) {
return asked(item) ? answerTo(item) : null;
}
if (item.kind === "decision") {
return choiceDialog(item, {pick: (label) => { after(); chooseOne(item, label); }, toggled: new Set(), chosen: ui.selected.has(keyOf(item)) ? grantLabel(item) : "", locked: item.held, hint: signsFor(item), group: "", other: OTHER_PROMPT});
}
@@ -165,7 +189,8 @@
const answerTo = (item) => h("p", {class: "muted answer-to"}, item.agent ? ["Your answer goes to ", h("strong", {}, revealed(item.agent)), " as a passkey-signed call that wakes it at once, with the row id and your answer only."] : UNASSIGNED);
const deniable = (item) => item.deniable || item.kind === "review";
const denialOf = (item, reason) => ({...entryOf(item, "reject", ""), channel: "post", reason, to: item.to});
const withNotes = (item, reason) => [reason, lineNotes(keyOf(item))].filter(Boolean).join(LINE_JOIN).slice(0, DENY_REASON);
const denialOf = (item, reason) => ({...entryOf(item, "reject", ""), channel: lineNotes(keyOf(item)) ? "call" : "post", reason: withNotes(item, reason), to: item.to});
const pickable = (item) => !item.held && (collectable(item) || deniable(item));
const unsettled = (item) => item.reviews.filter((review) => review.status !== "approved");
@@ -203,7 +228,7 @@
item.kind === "operator" ? h("span", {class: "muted"}, revealed(`in ${item.directory}`)) : null,
item.kind === "ask" ? h("div", {class: "command"}, h("code", {}, revealed(item.command))) : null));
const confirm = h("button", {type: "button", class: deny ? "btn danger" : "btn primary"}, `${deny ? "Deny" : "Grant"} ${usable.length + alone.length}`);
const reason = deny ? h("textarea", {class: "field", maxlength: DENY_REASON, rows: 3, placeholder: "e.g. make the gate green first"}) : null;
const reason = deny ? h("textarea", {class: "field", maxlength: DENY_REASON, rows: 3, placeholder: "e.g. make the gate green first", "data-skills": ""}) : null;
confirm.addEventListener("click", async () => {
closeSheet();
for (const item of alone) {
@@ -211,8 +236,14 @@
return;
}
}
if (usable.length) {
await submit(usable.map((item) => (deny ? denialOf(item, reason.value) : entryOf(item, "approve", labels.get(keyOf(item))))), `${label}: ${usable.length} entries`);
if (usable.length && (await submit(usable.map((item) => (deny ? denialOf(item, reason.value) : entryOf(item, "approve", labels.get(keyOf(item))))), `${label}: ${usable.length} entries`))) {
for (const item of usable) {
if (deny && lineNotes(keyOf(item))) {
setLineMarks(keyOf(item), []);
} else if (!deny) {
await withGrantNotes(item, true);
}
}
}
});
openSheet(label, [h("p", {class: "muted"}, deny ? DENY_NOTE : grantNote(alone.length, usable.length)), h("ul", {class: "mini"}, rows), ...(deny ? [reasonChips(reason), h("label", {class: "deny-reason"}, "Reason (optional, every requester reads it)", reason)] : []),
@@ -286,6 +317,8 @@
return h("button", {type: "button", class: "btn small primary", ...named(`Approve ${waiting.length} and run`, why), disabled: stuck || ui.busy, on: {click: () => (collecting(item) ? collect(item) : bulk(withReviews([item]), "Approve and run", false))}}, icon("bi-play-fill"), `Approve ${waiting.length} and run`);
}
const blockedButton = (glyph, word, reason) => h("button", {type: "button", class: "btn small", disabled: true, "data-blocked": "", ...named(word, `${word}: not possible now. ${reason}`)}, icon(glyph), word);
function actionsFor(item) {
if (item.held) {
return [h("span", {class: "muted"}, "takes effect …")];
@@ -295,15 +328,23 @@
if (item.kind === "review") {
grant(iconBtn("bi-check-lg", "Grant", "btn small primary", () => approveOne(item)));
buttons.push(denySplit(item));
} else if (item.kind === "ask") {
grant(iconBtn("bi-check-lg", "Grant", "btn small primary", () => approveOne(item), "Grant: allow this one call"));
} else if (Answers.pair(item)) {
buttons.push(...yesNoButtons(item, (label) => (asked(item) ? answerPick(item, label) : chooseOne(item, label))));
} else if (item.kind === "decision" && item.recommended) {
grant(h("button", {type: "button", class: "btn small primary", ...named(revealed(`Recommendation: ${shownPick(item.recommended)}`)), on: {click: () => approveOne(item)}}, icon("bi-check-lg"), revealed(shownPick(item.recommended))));
} else if (item.kind === "operator" && item.runnable) {
grant(runButton(item));
} else if (item.kind === "operator" && item.blocked) {
buttons.push(blockedButton("bi-play-fill", "Run", item.blocked));
} else if (item.kind === "rule") {
grant(h("button", {type: "button", class: "btn small primary", ...named("Accept", "Accept: the passkey signs exactly this rule, then it applies"), on: {click: () => approveOne(item)}}, icon("bi-shield-check"), "Accept"));
}
if (item.deniable) {
buttons.push(denySplit(item));
} else if (item.kind === "operator" && item.blocked) {
buttons.push(blockedButton("bi-x-lg", "Deny", item.blocked));
}
if (item.job && !jobOpen(item.job)) {
buttons.push(iconBtn("bi-x-circle", "Close", "btn small ghost", () => dismissJob(item.job), "Close: hide the console; a done row disappears with it"));
@@ -341,7 +382,7 @@
const wait = waitOf(item);
const classes = ["item", "entry", `k-${item.kind}`, "waiting", isGreen(item) ? "green" : "", red ? "red" : "", item.held ? "held" : "", wait ? "pending" : "", index === ui.cursor ? "cursor" : ""].filter(Boolean).join(" ");
const box = h("input", {type: "checkbox", "aria-label": `Select ${item.title}`, checked: ui.selected.has(keyOf(item)), disabled: !pickable(item), on: {change: () => toggle(item, true)}});
return h("li", {class: classes, "data-index": index, "data-ref": keyOf(item), "data-to": item.to || null, "aria-busy": wait ? "true" : null, title: wait || null},
return h("li", {class: classes, "data-index": index, "data-ref": keyOf(item), "data-to": item.to || null, "data-blocked": item.blocked ? "" : null, "aria-busy": wait ? "true" : null, title: item.blocked || wait || null},
box,
h("div", {class: "msg-meta"},
when(item.ts),
@@ -361,6 +402,7 @@
commanded ? h("span", {class: "muted"}, revealed(`in ${dash(item.directory)}`)) : null,
asked(item) ? h("p", {class: "text question"}, revealed(item.title)) : null,
item.kind === "operator" && item.detail && item.detail !== "-" ? h("p", {class: "text reason"}, revealed(item.detail)) : null,
item.blocked ? h("p", {class: "item-blocked"}, icon("bi-slash-circle"), item.blocked) : null,
diffBlocks(item),
item.job ? consoleOf(item.job) : null,
item.kind === "rule" ? ruleRequestBody(item) : null,
+50 -30
View File
@@ -47,7 +47,7 @@
function matchOrder(cards) {
const ids = new Set(cards.map((card) => card.id));
const kept = matchView.order.filter((id) => ids.has(id));
const fresh = cards.filter((card) => !kept.includes(card.id)).sort((a, b) => Number(a.stale) - Number(b.stale) || (a.created_ts || 0) - (b.created_ts || 0));
const fresh = cards.filter((card) => !kept.includes(card.id)).sort((a, b) => Number(Boolean(a.blocked)) - Number(Boolean(b.blocked)) || Number(a.stale) - Number(b.stale) || (a.created_ts || 0) - (b.created_ts || 0));
matchView.order = [...kept, ...fresh.map((card) => card.id)];
const byId = new Map(cards.map((card) => [card.id, card]));
return matchView.order.map((id) => byId.get(id));
@@ -98,8 +98,10 @@
}
const patched = (card) => card.kind === "commit" || card.kind === "ask" || Boolean(card.merge);
const pickOnly = (card) => card.kind === "decision" && card.entry === "decision";
const flies = (card) => !card.stale && card.kind !== "rule" && (card.kind !== "decision" || Boolean(card.recommended));
const pickOnly = (card) => card.kind === "decision" && card.entry === "decision" && !Answers.pair(card);
const needsPick = (card) => card.kind === "decision" && !card.recommended && !Answers.pair(card);
const acceptLabel = (card) => (card.kind !== "decision" ? "" : Answers.pair(card) ? Answers.pair(card).yes : card.recommended);
const flies = (card) => !card.blocked && !card.stale && card.kind !== "rule" && !needsPick(card);
function matchFileRows(card, file) {
const diffed = patched(card);
@@ -162,7 +164,7 @@
const article = row.closest(".match-card");
closeComment(article);
const file = row.closest(".match-file");
const words = h("textarea", {class: "field", rows: 2, "aria-label": "Comment", placeholder: "Comment on this line"});
const words = h("textarea", {class: "field", rows: 2, "aria-label": "Comment", placeholder: "Comment on this line", "data-skills": card.repo || ""});
const save = h("button", {type: "button", class: "btn small primary match-save", ...named("Save mark"), on: {click: () => {
if (!words.value.trim()) {
words.focus();
@@ -290,27 +292,16 @@
return choiceDialog({...card, id: card.ref}, {pick, toggled, chosen: kept ? kept.label : "", locked: false, hint: `picked now, sent to ${card.agent || "its agent"} at the release`, group: "match-options", other: OTHER_PROMPT});
}
/**
* @param {Object} card a permission ask card.
* @returns {HTMLElement} its choiceDialog(): Yes accepts, No rejects, typed text rejects with it as the feedback; all sent at the release.
*/
function matchAsk(card) {
const kept = matchView.decisions.get(cardKey(card));
const chosen = !kept ? "" : kept.verdict === "accept" ? ALLOW : kept.feedback || "No";
const pick = (answer, typed) => (!typed && answer === ALLOW ? acceptCard(card) : decide(card, "reject", typed ? answer : "", ""));
return choiceDialog(askDialog(card.ref), {pick, toggled: new Set(), chosen, locked: false, hint: `picked now, sent to ${card.agent || "its session"} at the release`, group: "match-options", other: TELL});
}
function matchPayload(card) {
if (card.kind === "decision") {
return h("section", {class: "match-payload"}, card.reason && card.reason !== "-" ? h("p", {class: "match-reason"}, revealed(card.reason)) : null, matchOptions(card));
return h("section", {class: "match-payload"}, card.reason && card.reason !== "-" ? h("p", {class: "match-reason"}, revealed(card.reason)) : null, Answers.pair(card) ? null : matchOptions(card));
}
if (card.kind === "rule") {
return h("section", {class: "match-payload"}, ruleRequestBody({...card, detail: card.reason}));
}
if (card.kind === "ask") {
return h("section", {class: "match-payload"}, h("pre", {class: "match-command"}, h("code", {}, revealed(card.command))), h("p", {class: "match-directory"}, revealed(card.directory)),
card.warnings.length ? h("p", {class: "match-warnings"}, card.warnings.map((warning) => pill(warning, "bad"))) : null, matchAsk(card));
card.warnings.length ? h("p", {class: "match-warnings"}, card.warnings.map((warning) => pill(warning, "bad"))) : null);
}
if (card.kind !== "command") {
return null;
@@ -339,11 +330,11 @@
function matchCard(card) {
const files = card.files || [];
const none = card.kind === "commit" ? "No diff shipped with this stage." : card.kind === "ask" ? "Its tool call changes no file." : card.merge ? (card.merge.error ? "No diff to show." : "The merge brings no change.") : "Its command names no file.";
const none = card.kind === "commit" ? (card.diff_error ? `No diff shipped with this stage. ${card.diff_error}` : "No diff shipped with this stage.") : card.kind === "ask" ? "Its tool call changes no file." : card.merge ? (card.merge.error ? "No diff to show." : "The merge brings no change.") : "Its command names no file.";
const list = files.length ? h("ol", {class: "match-files", "aria-label": `Files: ${files.length}`}, files.map((file, index) => fileBlock(card, file, index))) : card.kind === "decision" || card.kind === "rule" ? null : h("p", {class: "muted"}, none);
const body = h("div", {class: "match-body"}, matchPayload(card), list);
const body = h("div", {class: "match-body"}, card.blocked ? h("p", {class: "match-blocked"}, icon("bi-hourglass-split"), revealed(card.blocked)) : null, matchPayload(card), list);
body.addEventListener("scroll", () => openOnScroll(body, ".match-file"), {passive: true});
const article = h("article", {class: "card match-card front", "data-card": card.id, "data-kind": card.kind, "data-stale": String(Boolean(card.stale)), "aria-label": `${card.kind} card of ${card.agent || "an agent"}`},
const article = h("article", {class: "card match-card front", "data-card": card.id, "data-kind": card.kind, "data-stale": String(Boolean(card.stale)), ...(card.blocked ? {"data-blocked": "", title: card.blocked} : {}), "aria-label": `${card.kind} card of ${card.agent || "an agent"}`},
matchHead(card), body);
article.style.setProperty("--agent-hue", String(Faces.hash(card.agent) % 360));
paint(article, card.id);
@@ -354,7 +345,7 @@
function peekTab(card) {
const [kindName, kindTone] = MATCH_KINDS[card.kind] || [card.kind, "neutral"];
return h("button", {type: "button", class: "match-peek", "data-card": card.id, "data-stale": String(Boolean(card.stale)), ...named(`Show ${kindName.toLowerCase()} card: ${card.title}`), on: {click: () => {
return h("button", {type: "button", class: "match-peek", "data-card": card.id, "data-stale": String(Boolean(card.stale)), ...(card.blocked ? {"data-blocked": ""} : {}), ...named(`Show ${kindName.toLowerCase()} card: ${card.title}`, card.blocked ? `${card.title}: ${card.blocked}` : undefined), on: {click: () => {
matchView.order = [card.id, ...matchView.order.filter((id) => id !== card.id)];
drawMatch(true);
}}}, face(card.agent || "-", false), h("span", {class: "pill", "data-tone": kindTone}, kindName), card.stale ? h("span", {class: "pill", "data-tone": "bad"}, "stale") : null, h("span", {class: "match-peek-title"}, revealed(card.title)));
@@ -421,7 +412,20 @@
}));
}
/**
* @returns {boolean} whether the card can not act here; the toast then names its reason under the verdict.
*/
function refusedHere(card, verdict) {
if (card.blocked) {
toast(`${verdict}: not possible now`, [card.blocked], false);
}
return Boolean(card.blocked);
}
function acceptCard(card) {
if (refusedHere(card, "Accept")) {
return;
}
if (card.stale) {
toast("Accept: refused", [`The card is stale: ${card.stale_reason}. Add it again to decide it.`], false);
return;
@@ -435,25 +439,29 @@
}
return;
}
if (card.kind === "decision" && !card.recommended) {
if (needsPick(card)) {
toast("Accept: pick one of its options", ["The decision recommends none, so the card waits for your pick."], false);
return;
}
decide(card, "accept", "", card.kind === "decision" ? card.recommended : "");
decide(card, "accept", "", acceptLabel(card));
}
function rejectCard(card) {
if (refusedHere(card, "Reject")) {
return;
}
if (pickOnly(card)) {
toast("Reject: not possible", ["A choice is answered with one of its options."], false);
return;
}
const kept = matchView.decisions.get(cardKey(card));
const words = h("textarea", {class: "field match-feedback", rows: 6, maxlength: FEEDBACK_LIMIT, "aria-label": "Feedback"});
const words = h("textarea", {class: "field match-feedback", rows: 6, maxlength: FEEDBACK_LIMIT, "aria-label": "Feedback", "data-skills": card.repo || ""});
words.value = (kept && kept.verdict === "reject" ? kept.feedback : feedbackOf(card)).slice(0, FEEDBACK_LIMIT);
const confirm = h("button", {type: "button", class: "btn danger match-feedback-reject"}, icon("bi-x-lg"), "Reject");
const pair = card.kind === "decision" ? Answers.pair(card) : null;
confirm.addEventListener("click", () => {
closeSheet();
decide(card, "reject", words.value.trim(), "");
decide(card, "reject", words.value.trim(), pair ? Answers.declined(pair.no, words.value, OTHER_LIMIT) : "");
});
const note = `${card.agent || "The agent"} gets this text by radio call at the release; nothing is sent before.`;
openSheet(`Reject: ${card.title}`, [h("p", {class: "muted"}, note), reasonChips(words), words, h("div", {class: "actions"}, h("span", {class: "spacer"}), btn("Cancel", "btn ghost", closeSheet), confirm)], false);
@@ -542,6 +550,9 @@
function matchEntry(card, decision) {
const kind = card.entry || (card.kind === "commit" ? "review" : "operator");
const entry = {kind, id: card.ref, verb: decision.verdict === "accept" ? "approve" : "reject", label: decision.verdict === "accept" ? decision.label || "" : "", sha256: kind === "operator" ? card.sha256 || "" : ""};
if (card.kind === "decision" && Answers.pair(card)) {
return {...entry, verb: "approve", label: decision.label};
}
if (decision.verdict === "reject") {
return {...entry, channel: "call", reason: decision.feedback, to: card.to || ""};
}
@@ -563,6 +574,13 @@
matchView.overview = false;
drawMatch(true);
await fetchMatch();
for (const [card, decision] of picked) {
const notes = decision.verdict === "accept" ? feedbackOf(card) : "";
if (notes && card.to) {
await radioSend({to: card.to, text: `Granted: ${card.title}. Notes:\n${notes}`, upload: "", cls: "post", voice: ""});
}
matchView.marks.delete(cardKey(card));
}
}
}
@@ -631,7 +649,7 @@
if (matchView.drag) {
matchView.drag.end();
}
const bar = h("div", {class: "card controls task-toolbar", role: "toolbar", "aria-label": "Match"}, h("strong", {}, icon("bi-stack"), "Match"), count, h("span", {class: "spacer"}), decisions, peeks,
const bar = boxHead("Match", "task-toolbar", h("strong", {class: "box-title"}, icon("bi-stack"), "Match"), count, h("span", {class: "spacer"}), decisions, peeks,
iconBtn("bi-list-check", "Tasks", "btn small soft", () => go("tasks", null), "Tasks: back to the task list"), h("span", {"data-star-slot": ""}));
fetchMatch();
return h("div", {class: "graph tasks match", "data-panel": "tasks/match"}, bar, stack);
@@ -706,9 +724,11 @@
matchView.front = front;
const act = (cls, iconName, word, hint, disabled, run) => h("button", {type: "button", class: `match-act ${cls}`, disabled, ...named(word, hint), on: {click: run}},
h("span", {class: "match-act-face", "aria-hidden": "true"}, icon(iconName)), h("span", {class: "match-act-label"}, word));
const hint = front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : front.kind === "rule" ? "Accept: opens its row, where the passkey signs exactly this rule" : front.kind === "decision" ? (front.recommended ? `Accept: ${shownPick(front.recommended)} (right arrow, swipe right)` : "Accept: pick one of its options") : "Accept (right arrow, swipe right)";
const accept = act("match-accept", "bi-check-lg", "Accept", revealed(hint), Boolean(front.stale) || (front.kind === "decision" && !front.recommended), () => acceptCard(front));
const reject = act("match-reject", "bi-x-lg", "Reject", pickOnly(front) ? "Reject: a choice is answered with one of its options" : "Reject with feedback (left arrow, swipe left)", pickOnly(front), () => rejectCard(front));
const hint = front.blocked ? `Accept: not possible now. ${front.blocked}` : front.stale ? `Accept: refused while the card is stale (${front.stale_reason})` : front.kind === "rule" ? "Accept: opens its row, where the passkey signs exactly this rule" : front.kind === "decision" ? (needsPick(front) ? "Accept: pick one of its options" : `Accept: ${shownPick(acceptLabel(front))} (right arrow, swipe right)`) : "Accept (right arrow, swipe right)";
const accept = act("match-accept", "bi-check-lg", "Accept", revealed(hint), Boolean(front.blocked || front.stale) || needsPick(front), () => acceptCard(front));
const declining = front.kind === "decision" && Answers.pair(front) ? `Reject: ${shownPick(Answers.pair(front).no)}, with an optional comment on what to do instead (left arrow, swipe left)` : "Reject with feedback (left arrow, swipe left)";
const rejectHint = front.blocked ? `Reject: not possible now. ${front.blocked}` : pickOnly(front) ? "Reject: a choice is answered with one of its options" : declining;
const reject = act("match-reject", "bi-x-lg", "Reject", revealed(rejectHint), Boolean(front.blocked) || pickOnly(front), () => rejectCard(front));
const later = act("match-later", "bi-arrow-up", "Later", "Later: to the back of the stack (up arrow, swipe up)", !rest.length, () => laterCard(front));
const peeks = rest.length && peeksShown() ? h("div", {class: "match-peeks", role: "group", "aria-label": `${rest.length} more cards`}, rest.map(peekTab)) : null;
const behind = rest.slice(0, MATCH_PEEKS).map((card, index) => {
@@ -721,6 +741,6 @@
const shown = matchCard(front);
shown.dataset.fresh = String(!before || before.dataset.card !== front.id);
draggable(shown, front);
keepTyping(dom.stack, () => dom.stack.replaceChildren(h("div", {class: "match-deck"}, behind, shown), h("div", {class: "match-actions"}, reject, later, accept), peeks));
keepTyping(dom.stack, () => dom.stack.replaceChildren(h("div", {class: "match-deck"}, behind, shown), h("div", {class: "match-actions"}, reject, later, accept), ...(peeks ? [peeks] : [])));
shown.querySelector(".match-body").scrollTop = scrolled;
}
+40 -15
View File
@@ -34,15 +34,18 @@
/**
* @param {HTMLInputElement|HTMLTextAreaElement} field the text field the transcript lands in.
* @param {boolean} auto whether the shared component placed the button right after the field and keeps it there.
* @returns {HTMLButtonElement} the microphone button of the field.
* @returns {HTMLButtonElement} the microphone button of the field, made once and kept.
*/
function micButton(field, auto) {
function micButton(field) {
const kept = micButtons.get(field);
if (kept) {
return kept;
}
if (!field.id) {
micCount += 1;
field.id = `mic-field-${micCount}`;
}
const button = h("button", {type: "button", class: auto ? "btn small ghost icon-only mic mic-auto" : "btn small ghost icon-only mic", "aria-controls": field.id}, icon("bi-mic"));
const button = h("button", {type: "button", class: "mic", "aria-controls": field.id}, icon("bi-mic"));
micButtons.set(field, button);
micFields.set(button, field);
field.dataset.mic = "on";
@@ -51,21 +54,43 @@
return button;
}
const micFramed = (field) => Boolean(field.parentElement && field.parentElement.classList.contains("mic-frame"));
/**
* @param {HTMLInputElement|HTMLTextAreaElement} field the text field; it moves into the frame.
* @param {Node[]} extras what belongs to a textarea besides its mic, on the footer's left (Record, a count); [] for none.
* @returns {HTMLElement} one frame around field and mic: for a one-line field the mic as the field's last segment, for a
* textarea a footer row below it whose last child is the mic.
*/
function micFrame(field, extras) {
const button = micButton(field);
if (field.tagName === "TEXTAREA") {
return h("div", {class: "mic-frame mic-area"}, field, h("div", {class: "mic-foot"}, extras, h("span", {class: "spacer"}), button));
}
return h("span", {class: "mic-frame mic-line"}, field, button);
}
function micWrap(field) {
const focused = document.activeElement === field;
const [start, end] = [field.selectionStart, field.selectionEnd];
const [parent, next] = [field.parentNode, field.nextSibling];
parent.insertBefore(micFrame(field, []), next);
if (focused) {
field.focus({preventScroll: true});
field.setSelectionRange(start, end);
}
}
function micSweep() {
for (const field of document.querySelectorAll(Voice.FIELDS)) {
const button = micButtons.get(field);
if (field.readOnly || (button && !button.classList.contains("mic-auto"))) {
continue;
}
if (!button) {
field.after(micButton(field, true));
} else if (button.previousElementSibling !== field) {
field.after(button);
if (!field.readOnly && !micFramed(field) && field.parentNode) {
micWrap(field);
}
}
for (const button of document.querySelectorAll("button.mic-auto")) {
if (!micFields.get(button).isConnected) {
button.remove();
for (const frame of document.querySelectorAll(".mic-frame")) {
const button = frame.querySelector(":scope > button.mic, :scope > .mic-foot > button.mic");
if (!button || micFields.get(button).parentElement !== frame) {
frame.remove();
}
}
}
+1 -1
View File
@@ -146,7 +146,7 @@
runPalette(palette.index);
}
});
box.replaceChildren(h("div", {class: "palette-box", role: "dialog", "aria-label": "Commands"}, h("div", {class: "palette-row"}, palette.input, micButton(palette.input, false)), palette.list));
box.replaceChildren(h("div", {class: "palette-box", role: "dialog", "aria-label": "Commands"}, h("div", {class: "palette-row"}, micFrame(palette.input, [])), palette.list));
box.hidden = false;
drawPalette();
palette.input.focus();
+3 -3
View File
@@ -296,8 +296,8 @@
}
function speakCard() {
const {form, recipient, text, channel, clear} = composerForm();
const part = {recipient, text, channel, clear, names: ""};
const {form, recipient, text, channel, mayday} = composerForm();
const part = {recipient, text, channel, mayday, names: ""};
part.root = h("section", {class: "radio-card radio-speak", "data-panel": "radio-speak", "aria-label": "Speak"}, cardHead("Speak"), form);
radioParts.speaks.push(part);
return part;
@@ -307,7 +307,7 @@
const names = agentNames();
const sig = JSON.stringify(names);
for (const part of liveParts("speaks")) {
part.clear.hidden = !state.silence;
drawMayday(part.mayday);
if (sig !== part.names) {
part.names = sig;
const chosen = part.recipient.value;
+33 -11
View File
@@ -9,6 +9,7 @@
unknown: ["#bi-question-circle", (mark) => `${mark.name} unknown: no reading`, 0],
};
const RESOURCE_BURN = {done: "Done", scope: "Scope"};
const RESOURCE_PICKS = [["hardware", "Hardware"], ["tokens", "Tokens"], ["combined", "Combined"], ["accounts", "Accounts"]];
const resourceView = {data: null, dom: null, busy: false, key: "", at: 0, timer: 0, series: {}};
const resourceKey = () => JSON.stringify([ui.preset, ui.asOf]);
const resourcesStale = () => resourceKey() !== resourceView.key || nowSeconds() - resourceView.at >= RESOURCE.stale;
@@ -21,12 +22,22 @@
return h("button", {type: "button", class: "btn small soft res-switch", "data-switch": key, "aria-pressed": "false", ...named(label, hint), on: {click: () => ViewStore.set(path, next(ViewStore.get(path)))}}, icon(name), h("span", {}, label));
}
function resourcePicks() {
const boxes = RESOURCE_PICKS.map(([kind, label]) => {
const box = h("input", {type: "checkbox", "data-pick": kind, "aria-label": label, on: {change: () => ViewStore.update("resources.panels", (list) => [...list.filter((name) => name !== kind), ...(box.checked ? [kind] : [])])}});
return {kind, box, row: h("label", {class: "menu-item res-pick"}, box, h("span", {}, label))};
});
const menu = h("details", {class: "menu res-panels-menu"}, h("summary", {...named("Panels", "Panels: choose which panels Resources shows; the last one stays on")}, icon("bi-grid"), h("span", {}, "Panels"), caret()),
h("div", {class: "menu-box end", role: "group", "aria-label": "Panels"}, boxes.map((entry) => entry.row)));
return {menu, boxes};
}
function resourcesScreen() {
const count = h("span", {class: "count", title: "Samples", "aria-label": "Samples"}, "0");
const switches = {
tokens: resourceSwitch("tokens", (mode) => (mode === "accumulated" ? "interval" : "accumulated"), "bi-graph-up-arrow", "Accumulated", "Accumulated: per-agent running sums of the tokens instead of the tokens per hour"),
combined: resourceSwitch("combined", (on) => !on, "bi-layers", "Combined", "Combined: hardware in %, tokens and the burnup in one chart"),
};
const picks = resourcePicks();
const panels = RESOURCE_PANELS.map(([kind, name, label]) => {
const legend = h("div", {class: "res-legend"});
const plot = h("div", {class: "res-plot"});
@@ -34,7 +45,8 @@
h("div", {class: "res-head", "data-star-slot": ""}, h("span", {class: "res-title", title: label, "aria-label": label}, icon(name)), legend), plot);
return {kind, label, legend, plot, panel};
});
resourceView.dom = {count, switches, panels};
const accounts = accountsPanel();
resourceView.dom = {count, switches, picks, panels, accounts};
if (!resourceView.timer) {
resourceView.timer = window.setInterval(pollResources, RESOURCE.poll);
window.addEventListener("resize", drawResources);
@@ -43,11 +55,15 @@
window.setTimeout(() => {
drawResources();
fetchResources();
fetchAccounts();
}, 0);
const reload = iconBtn("bi-arrow-clockwise", "Reload", "btn small soft", fetchResources, "Reload: read the sampler files again");
const reload = iconBtn("bi-arrow-clockwise", "Reload", "btn small soft", () => {
fetchResources();
fetchAccounts();
}, "Reload: read the sampler files and the accounts again");
return h("div", {class: "graph resources"},
h("div", {class: "card controls"}, h("div", {class: "toolbar", role: "toolbar", "aria-label": "Resources"}, reload, switches.tokens, switches.combined, count)),
h("div", {class: "res-panels"}, panels.map((entry) => entry.panel)));
boxHead("Resources", "", h("div", {class: "toolbar"}, reload, switches.tokens, picks.menu, count)),
h("div", {class: "res-panels"}, panels.map((entry) => entry.panel), accounts.panel));
}
function pollResources() {
@@ -305,7 +321,7 @@
function metricParts(data, view) {
const span = {from: data.since, to: Math.max(data.until, data.since + 60)};
const parts = resourceParts(data, {tokens: view.tokens, hidden: [], combinedHidden: [], combined: view.chart === "combined"}, span);
const parts = resourceParts(data, {tokens: view.tokens, hidden: [], combinedHidden: [], panels: [view.chart]}, span);
const series = RESOURCE_SERIES[view.chart](parts);
return {span, parts, series, hidden: new Set(view.shown === null ? [] : series.map((line) => line.id).filter((id) => !view.shown.includes(id)))};
}
@@ -321,7 +337,7 @@
const {series, hidden} = metricParts(resourceView.data, view);
const ids = new Set(series.map((line) => line.id));
ViewStore.update(view.chart === "combined" ? "resources.combinedHidden" : "resources.hidden", (list) => [...list.filter((id) => !ids.has(id)), ...hidden]);
ViewStore.set("resources.combined", view.chart === "combined");
ViewStore.update("resources.panels", (list) => (list.includes(view.chart) ? list : [...list, view.chart]));
if (view.chart !== "hardware") {
ViewStore.set("resources.tokens", view.tokens);
}
@@ -336,7 +352,7 @@
mode: view.tokens,
hidden: new Set(view.hidden),
combinedHidden: new Set(view.combinedHidden),
burn: view.combined ? burnSeries(span) : [],
burn: view.panels.includes("combined") ? burnSeries(span) : [],
marks: [
...Resources.waits(data.samples).map((mark) => ({...mark, kind: "wait"})),
...Resources.blocked(data.samples).map((mark) => ({...mark, kind: "blocked"})),
@@ -354,10 +370,16 @@
}
const view = ViewStore.get("resources");
dom.switches.tokens.setAttribute("aria-pressed", String(view.tokens === "accumulated"));
dom.switches.combined.setAttribute("aria-pressed", String(view.combined));
for (const entry of dom.panels) {
entry.panel.hidden = (entry.kind === "combined") !== view.combined;
for (const {kind, box} of dom.picks.boxes) {
box.checked = view.panels.includes(kind);
box.disabled = box.checked && view.panels.length === 1;
box.title = box.disabled ? "The last panel stays on" : "";
}
for (const entry of dom.panels) {
entry.panel.hidden = !view.panels.includes(entry.kind);
}
dom.accounts.panel.hidden = !view.panels.includes("accounts");
drawAccounts();
if (data === null) {
return;
}
+35 -9
View File
@@ -39,14 +39,17 @@
return;
}
const item = state.inbox.find((entry) => entry.kind === "review" && entry.id === review.id);
const ref = item ? keyOf(item) : null;
const list = fileList(review.id);
const treeNav = h("nav", {class: "card tree", "aria-label": "Changed files"}, treePane(list));
const diff = h("section", {class: "card diff-pane", "aria-label": "Diff"}, diffPane(list));
const diff = h("section", {class: "card diff-pane", "aria-label": "Diff"}, diffPane(list, ref));
const notes = h("div", {class: "review-notes"}, ref ? feedbackList(ref) : null);
const id = ui.review;
const head = h("article", {class: "card"},
h("div", {class: "card-head"}, h("div", {}, h("p", {class: "muted"}, "submitted ", when(review.created_ts))), h("div", {class: "who"}, status(review.status || "pending"), review.gate ? pill(review.gate === "pass" ? "Gate green" : "Gate red", review.gate === "pass" ? "ok" : "bad") : null)),
meta([["Repo", review.worktree], ["Branch", review.branch], ["Tree", (review.tree || "").slice(0, 12), review.tree], ["Score", review.score]]),
review.notes ? h("pre", {class: "notes"}, revealedLines(review.notes)) : null,
notes,
h("div", {class: "actions"},
h("a", {class: "btn ghost icon-only", href: `/reviews/${encodeURIComponent(review.id)}/page`, target: "_blank", rel: "noopener noreferrer", ...named("Open full page", "Open full page (new tab)")}, icon("bi-box-arrow-up-right")),
h("span", {class: "spacer"}),
@@ -54,9 +57,26 @@
node.addEventListener("click", closeSheet);
return node;
}) : null));
openSheet(review.title, [head, h("div", {class: "split"}, treeNav, diff)], true);
openSheet(review.title, [head, h("div", {class: "split", "data-ref": ref, "data-to": item && item.to ? item.to : null}, treeNav, diff)], true);
ui.review = id;
reviewDom = {tree: treeNav, diff};
reviewDom = {tree: treeNav, diff, notes, ref};
}
function repaintReview() {
const stack = reviewDom && reviewDom.ref ? reviewDom.diff.querySelector(".review-stack") : null;
const list = stack ? files.get(ui.review) : null;
if (!Array.isArray(list)) {
return;
}
const top = stack.scrollTop;
const opened = [...stack.querySelectorAll(REVIEW_FILE)].map((file) => file.open);
stack.replaceChildren(...list.map((file, index) => {
const node = reviewFile(file, index, reviewDom.ref);
node.open = opened[index];
return node;
}));
stack.scrollTop = top;
reviewDom.notes.replaceChildren(...[feedbackList(reviewDom.ref)].filter(Boolean));
}
function nest(entries) {
@@ -149,21 +169,27 @@
if (line.kind === "hunk" || line.kind === "more") {
return h("tr", {class: line.kind}, h("td", {colspan: 3}), h("td", {class: "code"}, line.text));
}
return h("tr", {class: line.kind}, h("td", {class: "num"}, line.old), h("td", {class: "num"}, line.new), h("td", {class: "sign"}, SIGNS[line.kind] || " "), h("td", {class: "code"}, line.text));
return h("tr", {class: line.kind, "data-line": line.new || line.old || null}, h("td", {class: "num"}, line.old), h("td", {class: "num"}, line.new), h("td", {class: "sign"}, SIGNS[line.kind] || " "), h("td", {class: "code"}, line.text));
}
function diffPane(list) {
function diffPane(list, ref) {
if (!Array.isArray(list) || !list.length) {
return h("p", {class: "muted pad"}, list === "loading" ? "Loading changes …" : "No diff available.");
}
const stack = h("div", {class: "review-stack"}, list.map((file, index) => reviewFile(file, index)));
const stack = h("div", {class: "review-stack"}, list.map((file, index) => reviewFile(file, index, ref)));
stack.addEventListener("scroll", () => followScroll(stack), {passive: true});
return stack;
}
function reviewFile(file, index) {
/**
* @param {Object} file a file of the review's file list.
* @param {number} index its place in that list.
* @param {string|null} ref the keyOf() of the review's inbox item, whose line comments its rows show; null when it
* waits on nobody.
*/
function reviewFile(file, index, ref) {
const [letter, tone] = FILE_STATUS[file.status] || ["?", "neutral"];
return h("details", {class: "review-file", "data-index": index, open: index === ui.file},
return h("details", {class: "review-file", "data-index": index, "data-path": ref ? file.path : null, open: index === ui.file},
h("summary", {class: "diff-head"},
h("span", {class: "letter", "data-tone": tone}, letter),
h("code", {class: "path"}, file.old ? `${file.old} → ${file.path}` : file.path),
@@ -171,5 +197,5 @@
h("span", {class: "spacer"}),
stat(file)),
file.detail ? h("p", {class: "muted pad"}, file.detail) : null,
file.lines.length ? h("div", {class: "diff-wide"}, h("table", {class: "diff"}, h("tbody", {}, file.lines.map(diffRow)))) : null);
file.lines.length ? h("div", {class: "diff-wide"}, h("table", {class: "diff"}, h("tbody", {}, ref ? withLineMarks(ref, file.path, file.lines.map(diffRow)) : file.lines.map(diffRow)))) : null);
}
+142
View File
@@ -0,0 +1,142 @@
const SLASH_LIMIT = 8;
const SLASH_FRESH = 60000;
const SLASH_FIELDS = "textarea[data-skills], input[data-skills]";
const SLASH_TOKEN = /(^|\s)\/([A-Za-z0-9:_.-]*)$/;
const slash = {skills: [], fetched: 0, loading: null, bound: new WeakSet(), box: null, field: null, shown: [], active: 0, token: null};
/**
* @param {Array<{name: string, description: string, source: string}>} skills the rows /api/skills serves.
* @param {string} prefix what follows the "/", case ignored.
* @param {string} repo the repository the field's agent or card works in, "" for none.
* @returns {Array} at most SLASH_LIMIT rows, one per name: names that start with prefix before names that hold it,
* then the repository's own skills, then by name.
*/
function slashRank(skills, prefix, repo) {
const typed = prefix.toLowerCase();
const hits = skills.map((skill) => ({skill, at: skill.name.toLowerCase().indexOf(typed)})).filter((hit) => hit.at >= 0);
hits.sort((a, b) => Number(a.at !== 0) - Number(b.at !== 0) || Number(b.skill.source === repo) - Number(a.skill.source === repo) || a.skill.name.localeCompare(b.skill.name));
const seen = new Set();
return hits.map((hit) => hit.skill).filter((skill) => !seen.has(skill.name) && Boolean(seen.add(skill.name))).slice(0, SLASH_LIMIT);
}
/**
* @param {string} text the field's value.
* @param {number} caret where the caret stands.
* @returns {Object|null} {start, prefix}: the "/" word the caret ends: a "/" at the start or after
* whitespace, then skill name characters only; null inside a word or a path.
*/
function slashToken(text, caret) {
const found = SLASH_TOKEN.exec(text.slice(0, caret));
return found ? {start: caret - found[2].length - 1, prefix: found[2]} : null;
}
/**
* @returns {Object} {value, caret}: text with the token up to caret replaced by "/<name> ".
*/
function slashInsert(text, token, caret, name) {
const head = `${text.slice(0, token.start)}/${name} `;
return {value: head + text.slice(caret), caret: head.length};
}
function slashLoad() {
if (!slash.loading && Date.now() - slash.fetched > SLASH_FRESH) {
slash.loading = fetch("/api/skills", {cache: "no-store"}).then((response) => (response.ok ? response.json() : {skills: []})).then((data) => {
slash.skills = Array.isArray(data.skills) ? data.skills : [];
slash.fetched = Date.now();
}).catch(() => null).finally(() => {
slash.loading = null;
if (slash.field) {
slashShow(slash.field);
}
});
}
}
function slashClose() {
if (slash.box) {
slash.box.remove();
}
Object.assign(slash, {box: null, field: null, shown: [], active: 0, token: null});
}
function slashPick(field, skill) {
const next = slashInsert(field.value, slash.token, field.selectionStart, skill.name);
field.value = next.value;
field.setSelectionRange(next.caret, next.caret);
field.dispatchEvent(new Event("input", {bubbles: true}));
slashClose();
field.focus();
}
function slashPaint() {
slash.box.replaceChildren(...slash.shown.map((skill, index) => {
const option = h("div", {role: "option", class: "slash-option", id: `slash-option-${index}`, "aria-selected": String(index === slash.active), title: skill.source},
h("strong", {}, `/${skill.name}`), h("span", {class: "muted"}, skill.description));
option.addEventListener("pointerdown", (event) => {
event.preventDefault();
slashPick(slash.field, skill);
});
return option;
}));
slash.field.setAttribute("aria-activedescendant", `slash-option-${slash.active}`);
}
function slashShow(field) {
const token = field.selectionStart === field.selectionEnd ? slashToken(field.value, field.selectionStart) : null;
slashLoad();
const shown = token ? slashRank(slash.skills, token.prefix, field.dataset.skills) : [];
if (!shown.length) {
slashClose();
slash.field = token && slash.loading ? field : null;
return;
}
if (!slash.box || slash.field !== field) {
slashClose();
slash.box = h("div", {class: "slash-list", role: "listbox", "aria-label": "Skills"});
document.body.append(slash.box);
}
const box = field.getBoundingClientRect();
Object.assign(slash, {field, shown, token, active: Math.min(slash.active, shown.length - 1)});
slash.box.style.left = `${Math.max(8, Math.min(box.left, window.innerWidth - 8 - Math.min(448, window.innerWidth - 16)))}px`;
slash.box.style.top = `${box.bottom + 4}px`;
slashPaint();
}
function slashKeys(event, field) {
if (!slash.box || slash.field !== field) {
return;
}
const moves = {ArrowDown: 1, ArrowUp: -1};
if (Object.hasOwn(moves, event.key)) {
slash.active = (slash.active + moves[event.key] + slash.shown.length) % slash.shown.length;
slashPaint();
} else if (event.key === "Enter" || event.key === "Tab") {
slashPick(field, slash.shown[slash.active]);
} else if (event.key === "Escape") {
slashClose();
} else {
return;
}
event.preventDefault();
event.stopPropagation();
}
/**
* @param {HTMLElement} field a text field whose text reaches an agent; data-skills names the repository of its agent or card.
*/
function slashBind(field) {
if (slash.bound.has(field)) {
return;
}
slash.bound.add(field);
field.setAttribute("aria-autocomplete", "list");
field.addEventListener("input", () => slashShow(field));
field.addEventListener("keydown", (event) => slashKeys(event, field));
field.addEventListener("blur", () => window.setTimeout(() => slash.field === field && slashClose(), 0));
}
function slashWatch() {
const sweep = () => document.querySelectorAll(SLASH_FIELDS).forEach(slashBind);
sweep();
new MutationObserver(sweep).observe(document.body, {childList: true, subtree: true});
}
+5 -1
View File
@@ -141,12 +141,16 @@
const renamed = entry.now && entry.now !== entry.agent ? h("span", {title: `now: ${entry.now}`}, person(entry.agent)) : person(entry.agent);
const who = entry.agent ? [face(entry.agent, false), renamed] : entry.session ? h("strong", {title: entry.session}, entry.session.slice(0, 8)) : null;
const headline = entry.kind === "transcript" || entry.kind === "ask" || entry.kind === "operator" ? null : h("span", {class: "headline"}, Receipts.headline(entry));
return h("li", {class: `entry k-${entry.kind}${entry.waiting ? " waiting" : ""}${alarm ? " alarm" : ""}`, "data-ref": item ? keyOf(item) : null, "data-item": `message:${entry.ts}/${entry.id}`, "data-to": item && item.to ? item.to : null},
const blocked = (item && item.blocked) || (entry.kind === "operator" && entry.ref.blocked) || "";
return h("li", {class: `entry k-${entry.kind}${entry.waiting ? " waiting" : ""}${alarm ? " alarm" : ""}`, "data-ref": item ? keyOf(item) : null, "data-item": `message:${entry.ts}/${entry.id}`, "data-to": item && item.to ? item.to : null,
"data-blocked": blocked ? "" : null, title: blocked || null},
h("div", {class: "msg-meta"}, when(entry.ts), kindPill(entry), extras(entry)),
h("div", {},
h("div", {class: "route", "data-star-slot": ""}, who, entry.sub ? h("button", {type: "button", class: "linkish muted", on: {click: () => focusSub(entry.session, entry.sub)}}, `› Subagent ${entry.sub.slice(0, 12)}`) : null, entry.kind === "ask" ? h("strong", {}, entry.title) : null, headline),
entry.kind === "decision" && choice ? choice : [body(entry), choice],
entry.kind === "radio" ? readerRow(entry.ref) : null,
blocked ? h("p", {class: "item-blocked"}, icon("bi-slash-circle"), blocked) : null,
item && item.job ? consoleOf(item.job) : null,
item ? diffBlocks(item) : null,
item ? feedbackList(keyOf(item)) : null,
item ? h("div", {class: "line-actions"}, actionsFor(item)) : null));
+25 -4
View File
@@ -167,14 +167,33 @@
}}});
const stage = !inbox && view === "3d" ? h("div", {class: "stage"}) : null;
const body = inbox ? inboxScreen() : stage ? h("div", {class: "card stage-card tasks-body", "data-panel": "tasks/3d"}, layoutTools("tasks"), stage) : h("div", {class: "tasks-body", "data-panel": `tasks/${view}`});
taskView.dom = {chips, count, body, inbox, view, stage};
const slot = h("span", {class: "box-slot"});
taskView.dom = {chips, count, body, inbox, view, stage, slot};
taskView.sig = "";
taskView.plan = null;
taskView.bulk = null;
const bar = h("div", {class: "card controls task-toolbar", role: "toolbar", "aria-label": "Tasks"}, taskViewSwitch(inbox), search, count, inbox ? null : planTools(view), choiceMenu());
const bar = boxHead("Tasks", "task-toolbar", taskViewSwitch(inbox), search, count, inbox ? null : planTools(view), slot, choiceMenu());
return h("div", {class: "graph tasks"}, bar, chips, body);
}
const operatorItems = () => state.inbox.filter((item) => item.kind === "operator" && !item.settled);
/**
* @returns {HTMLElement|null} the open operator rows, greyed: the list and board only show them, Waits on Operator,
* Match and the Stream run, answer or deny them; null without any.
*/
function operatorSection() {
const items = operatorItems();
if (!items.length) {
return null;
}
const why = (item) => `Only shown here: Waits on Operator, Match and the Stream act on it.${item.blocked ? ` ${item.blocked}` : ""}`;
return h("section", {class: "operator-rows", "aria-label": "Waits on Operator"},
h("h3", {class: "group-title"}, "Waits on Operator", counter(items.length), h("span", {class: "spacer"}), btn("Open", "btn small ghost", () => chooseTaskFilter("operator"))),
h("ol", {class: "operator-list"}, items.map((item) => h("li", {"data-operator": item.id, "data-blocked": "", "aria-disabled": "true", title: why(item)},
pill(item.check === "decision" ? "Decision" : ITEM_LABELS.operator, item.check === "decision" ? KIND_TONES.decision : KIND_TONES.operator), h("code", {}, revealed(item.title)), h("span", {class: "muted"}, revealed(item.id))))));
}
function shownTasks() {
const q = taskView.q.trim().toLowerCase();
const [, , , test] = TASK_FILTERS.find(([id]) => id === taskView.filter);
@@ -191,7 +210,7 @@
stage3d("tasks", dom.stage);
}
const q = taskView.q.trim().toLowerCase();
const sig = JSON.stringify([state.tasks, state.jobs, state.task_edges, state.queue_line, Kanban.queueSig(state.queue_jobs), settings.estimation, settings.trend, taskView.filter, taskView.sort, taskView.descending, taskView.forecast, taskView.scope, q, waitingCount(), Math.floor(nowSeconds() / 60)]);
const sig = JSON.stringify([state.tasks, operatorItems().map((item) => [item.id, item.title, item.blocked]), state.jobs, state.task_edges, state.queue_line, Kanban.queueSig(state.queue_jobs), settings.estimation, settings.trend, taskView.filter, taskView.sort, taskView.descending, taskView.forecast, taskView.scope, q, waitingCount(), Math.floor(nowSeconds() / 60)]);
if (sig === taskView.sig) {
return;
}
@@ -224,5 +243,7 @@
gantt: ganttChart,
burn: (found) => burnChart(rows, found),
};
dom.body.replaceChildren(shown.length || dom.view === "burn" ? views[dom.view](shown) : emptyState("No task", "No entry matches this filter."));
dom.body.replaceChildren(shown.length || dom.view === "burn" ? views[dom.view](shown) : emptyState("No task", "No entry matches this filter."), ...(dom.view === "list" || dom.view === "board" ? [operatorSection()].filter(Boolean) : []));
const bar = dom.body.querySelector(".kanban-bar");
dom.slot.replaceChildren(...(bar ? [bar] : []));
}
+15 -1
View File
@@ -9,6 +9,7 @@ const Panels = (() => {
const ESCAPED = /_([0-9a-f]+)_/g;
const PANEL = "panel";
const SIZES = {panel: [6, 4], item: [4, 3]};
const ZOOM = {min: 50, max: 200, step: 10, base: 100};
const HOSTS = "[data-panel], [data-item]";
const TOO_LONG = "the id runs past 200 characters";
const XHTML = "http://www.w3.org/1999/xhtml";
@@ -172,6 +173,19 @@ const Panels = (() => {
const moveKey = (pins, key, step) => move(pins, indexOf(pins, key), step);
const resizeKey = (pins, key, w, h) => resize(pins, indexOf(pins, key), w, h);
/**
* @param zooms - the view store's home.zoom: pin key to percent; a pin without one shows at ZOOM.base.
* @param key - the tile's pin key.
* @param step - +1 zooms in, -1 out, 0 resets.
* @returns the new map: the tile at ZOOM.step percent more or less, held in ZOOM.min to ZOOM.max, left out at the base.
*/
function zoomBy(zooms, key, step) {
const now = Object.hasOwn(zooms, key) ? zooms[key] : ZOOM.base;
const next = step === 0 ? ZOOM.base : Math.min(ZOOM.max, Math.max(ZOOM.min, now + step * ZOOM.step));
const rest = Object.fromEntries(Object.entries(zooms).filter(([name]) => name !== key));
return next === ZOOM.base ? rest : {...rest, [key]: next};
}
function resizeBy(pins, key, dw, dh) {
const pin = pins[indexOf(pins, key)];
return pin ? resize(pins, indexOf(pins, key), pin.w + dw, pin.h + dh) : pins;
@@ -363,7 +377,7 @@ const Panels = (() => {
return {
MAX, SPAN, PANEL, ID, HOSTS, keyOf, token, raw, digest, valid, validLayout, clean, panel, item, capture, lookup, targetOf, has, add, remove, firstOfGroup,
place, move, resize, placeKey, moveKey, resizeKey, resizeBy, stretch, memory, store, decorate, keepFocus,
place, move, resize, placeKey, moveKey, resizeKey, resizeBy, stretch, ZOOM, zoomBy, memory, store, decorate, keepFocus,
};
})();
if (typeof module === "object" && module.exports) {
+38 -1
View File
@@ -258,7 +258,44 @@ const Resources = (() => {
return unit ? `${(value / unit[0]).toFixed(1)}${unit[1]}` : String(Math.round(value));
}
return {IDLE, SATURATED, CALM, BLOCKED, GAP, HOUR, COUNTS, ZONES, lines, hardware, segments, spans, waits, blocked, hung, asleep, unknown, stack, accumulate, burnup, compact};
/**
* @param moment - {day, time}: day 0 for Sunday to 6 for Saturday, time HH:MM, both local.
* @param now - epoch milliseconds.
* @returns the epoch milliseconds of the latest local moment at or before now; days step by the calendar, so a DST
* change keeps the wall clock time.
*/
function lastMoment(moment, now) {
const [hours, minutes] = moment.time.split(":").map(Number);
const at = new Date(now);
at.setHours(hours, minutes, 0, 0);
at.setDate(at.getDate() - ((at.getDay() - moment.day + 7) % 7));
if (at.getTime() > now) {
at.setDate(at.getDate() - 7);
}
return at.getTime();
}
function nextMoment(moment, now) {
const at = new Date(lastMoment(moment, now));
at.setDate(at.getDate() + 7);
return at.getTime();
}
/**
* @param entry - one account's usage from /api/accounts: {total, hours: [[t, tokens]]}, t in epoch seconds.
* @param reset - the account's weekly reset {day, time}, or null for the unassigned tokens.
* @param now - epoch milliseconds.
* @returns {since, today, total}: tokens of the hours from the last reset (null without a reset), from local
* midnight, and of all rows; an hour counts once its start is at or after the bound.
*/
function accountUsage(entry, reset, now) {
const midnight = new Date(now);
midnight.setHours(0, 0, 0, 0);
const from = (bound) => entry.hours.filter(([t]) => t * 1000 >= bound).reduce((sum, [, tokens]) => sum + tokens, 0);
return {since: reset ? from(lastMoment(reset, now)) : null, today: from(midnight.getTime()), total: entry.total};
}
return {IDLE, SATURATED, CALM, BLOCKED, GAP, HOUR, COUNTS, ZONES, lines, hardware, segments, spans, waits, blocked, hung, asleep, unknown, stack, accumulate, burnup, compact, lastMoment, nextMoment, accountUsage};
})();
if (typeof module === "object" && module.exports) {
module.exports = Resources;
+21
View File
@@ -0,0 +1,21 @@
const SettingsFiles = (() => {
const rank = (file) => (file.folder === false ? 2 : file.error ? 0 : 1);
/**
* @param files - /api/firewall files: path, folder and error each.
* @param showMissing - true lists the files whose folder is missing too.
* @returns {shown, missing}: shown the files to list, those with an error first, then by path, files without their folder
* last; missing the count of files without their folder.
*/
function listed(files, showMissing) {
const shown = files.filter((file) => showMissing || file.folder !== false);
shown.sort((a, b) => rank(a) - rank(b) || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
return {shown, missing: files.filter((file) => file.folder === false).length};
}
return {listed};
})();
if (typeof module === "object" && module.exports) {
module.exports = SettingsFiles;
}
+1
View File
@@ -26,4 +26,5 @@
.feedback-list { display: grid; gap: 4px; margin: var(--sp-1) 0 0; padding: 0; list-style: none; }
.feedback-list li { display: flex; align-items: baseline; gap: 6px; padding: 4px 8px; border-radius: 8px; background: var(--info-soft); font-size: var(--fs-sm); }
.feedback-list .text { flex: 1; min-width: 0; overflow-wrap: anywhere; white-space: pre-wrap; }
.feedback-list li.line-mark { align-items: center; background: var(--accent-soft); }
.feedback-float { position: fixed; z-index: 40; padding: 2px; border-radius: 10px; background: var(--glass-card); box-shadow: var(--shadow); }
+17 -5
View File
@@ -1,6 +1,17 @@
.stack-tight { display: grid; gap: 10px; min-width: 0; }
.fw-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 200px), 1fr)); gap: 10px; align-items: end; }
.fw-form label { display: grid; gap: 4px; min-width: 0; color: var(--muted); font-size: var(--fs-sm); }
.fw-form { display: grid; grid-template-columns: repeat(auto-fill, minmax(min(100%, 200px), 1fr)); gap: 10px; align-items: start; }
.fw-form > button { align-self: end; justify-self: start; }
.fw-form label, .fw-chips-field { display: grid; gap: 4px; min-width: 0; color: var(--muted); font-size: var(--fs-sm); }
.fw-chips-field { grid-column: 1 / -1; }
.fw-chips-field > p { margin: 0; }
.check-chips { margin: 0; }
.fw-form label.check-chip { display: inline-flex; color: var(--text); font-size: var(--fs-sm); }
.check-chip input { margin: 0; accent-color: var(--accent); }
.check-chip .avatar { width: 20px; height: 20px; }
.check-chip:has(input:checked) { border-color: transparent; background: var(--accent-soft); color: var(--accent); }
.check-chip:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 2px; }
.fw-filters { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; }
.fw-filters > .chips { margin-bottom: 0; }
.fw-form .field { width: 100%; min-width: 0; }
.fw-path { overflow-wrap: anywhere; }
.fw-patterns code { overflow-wrap: anywhere; }
@@ -20,9 +31,10 @@
.fw-diff .add { color: var(--ok); }
.fw-diff .del { color: var(--bad); }
.rule-row select.field { width: auto; max-width: 100%; min-width: 0; }
.controls > .segmented { justify-self: start; max-width: 100%; }
.controls > .segmented button { display: inline-flex; align-items: center; gap: 6px; }
.controls [role="tabpanel"][hidden], .apply-bar[hidden] { display: none; }
.fw-controls .box-head > .segmented { max-width: 100%; }
.fw-controls .box-head > .segmented button { display: inline-flex; align-items: center; gap: 6px; }
.fw-controls [role="tabpanel"][hidden], .apply-bar[hidden] { display: none; }
.fw-controls [role="tabpanel"] { grid-template-columns: minmax(0, 1fr); }
.tool-groups { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 280px), 1fr)); gap: 12px; align-items: start; }
.tool-group { display: grid; gap: 6px; min-width: 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 12px; background: var(--sunken); }
.tool-group h4 { margin: 0; }
+2
View File
@@ -11,12 +11,14 @@
.home-head { display: flex; flex: none; align-items: center; gap: 6px; padding: 4px 6px 4px 4px; border-bottom: 1px solid var(--line); }
.home-title { flex: 1; min-width: 0; margin: 0; overflow: hidden; font-size: var(--fs-sm); text-overflow: ellipsis; white-space: nowrap; }
.home-body { flex: 1; min-height: 0; padding: var(--sp-2); overflow: auto; }
.home-body > * { zoom: var(--zoom, 1); }
.home-body svg.chart { display: block; width: 100%; height: auto; max-height: 100%; }
.home-body .stage, .home-body .graph3d { height: 100%; min-height: 0; }
.home-grip { cursor: grab; touch-action: none; }
.home-open[hidden] { display: none; }
.home-slot { display: flex; flex: none; align-items: center; gap: 6px; min-width: 0; font-size: var(--fs-sm); }
.home-slot > .muted { white-space: nowrap; }
.home-slot.kanban-bar { flex: 0 1 auto; flex-wrap: nowrap; overflow-x: auto; }
.home-tile[data-w="1"] .home-head { gap: 2px; padding-inline: 2px; }
.home-tile[data-w="1"] .home-head .icon-only { min-width: 24px; padding-inline: 4px; }
.home-resize { position: absolute; right: 2px; bottom: 2px; z-index: 3; cursor: nwse-resize; touch-action: none; }
+7 -6
View File
@@ -6,12 +6,13 @@
.match-peeks { display: flex; flex-wrap: wrap; gap: var(--sp-1); min-width: 0; }
.match-peek { display: inline-flex; align-items: center; gap: 6px; max-width: 100%; min-width: 0; padding: 4px 10px 4px 4px; border: 1px solid var(--line); border-radius: 999px; background: var(--panel); color: inherit; font: inherit; font-size: var(--fs-sm); cursor: pointer; }
.match-peek[data-stale="true"] { border-color: var(--bad); }
.match-peek[data-blocked], .match-card.front[data-blocked] { filter: grayscale(1); opacity: 0.62; }
.match-blocked { display: flex; align-items: center; gap: 6px; margin: 0 0 var(--sp-2); color: var(--muted); font-size: var(--fs-sm); }
.match-peek .match-peek-title { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; min-width: 0; }
.match-deck { position: relative; display: grid; grid-template-rows: minmax(0, 1fr); min-height: 0; padding-top: 14px; overflow-x: clip; }
.match-behind { position: absolute; inset: calc(14px - var(--depth) * 7px) calc(var(--depth) * 12px) auto; height: 40px; border: 1px solid var(--line); border-radius: 22px; background: var(--panel); opacity: calc(1 - var(--depth) * 0.3); transform: rotate(calc((var(--depth) * 2 - 3) * 1deg)); }
.match-card.front { position: relative; display: grid; grid-template-rows: auto minmax(min(50%, 12rem), 1fr); min-height: 0; padding: 0; overflow: hidden auto; border-radius: 22px; box-shadow: 0 14px 34px -16px rgb(0 0 0 / 0.45); }
.match-card.front::before { content: ""; position: absolute; inset: 0 0 auto; z-index: 1; height: 6px; background: linear-gradient(90deg, hsl(var(--card-hue, 210) 75% 58%), hsl(var(--card-hue-2, 280) 75% 58%)); }
.match-card[data-stale="true"]::before { background: var(--bad); }
.match-card.front { --bar: linear-gradient(90deg, hsl(var(--card-hue, 210) 75% 58%), hsl(var(--card-hue-2, 280) 75% 58%)); position: relative; display: grid; grid-template-rows: auto minmax(min(50%, 12rem), 1fr); min-height: 0; padding: 0; overflow: hidden auto; border-top-width: 0; border-radius: 22px; background: var(--bar) top / 100% 6px no-repeat, var(--glass-card); box-shadow: 0 14px 34px -16px rgb(0 0 0 / 0.45); }
.match-card[data-stale="true"] { --bar: linear-gradient(var(--bad), var(--bad)); }
.match-card.front[data-fresh="true"] { animation: match-in 0.32s cubic-bezier(0.34, 1.56, 0.64, 1); }
.match-card.front[data-fresh="true"] .match-who .avatar { animation: match-pop 0.5s cubic-bezier(0.34, 1.56, 0.64, 1); }
.match-card.front[data-fly="accept"] { animation: match-fly-right 0.26s ease-in forwards; }
@@ -29,7 +30,7 @@
.match-head { position: relative; isolation: isolate; display: grid; justify-items: center; gap: 6px; padding: var(--sp-3); border-bottom: 1px solid var(--line); text-align: center;
--ink: hsl(var(--card-hue, 210) 55% 48% / 0.16);
background: radial-gradient(120% 90% at 0% 0%, hsl(var(--card-hue, 210) 85% 62% / 0.3), transparent 60%), radial-gradient(110% 90% at 100% 10%, hsl(var(--card-hue-2, 280) 85% 62% / 0.26), transparent 62%), linear-gradient(180deg, hsl(var(--card-hue, 210) 80% 60% / 0.1), transparent 85%); }
.match-head::before { content: ""; position: absolute; inset: 0; z-index: -1; pointer-events: none; mask-image: linear-gradient(180deg, #000 15%, transparent 95%); }
.match-head::before { content: ""; position: absolute; inset: 0; z-index: -1; pointer-events: none; mask-image: linear-gradient(180deg, transparent 6px, #000 6px, #000 15%, transparent 95%); }
.match-card[data-pattern="dots"] .match-head::before { background: radial-gradient(var(--ink) 1.2px, transparent 1.7px) 0 0 / 14px 14px; }
.match-card[data-pattern="stripes"] .match-head::before { background: repeating-linear-gradient(135deg, var(--ink) 0 2px, transparent 2px 12px); }
.match-card[data-pattern="waves"] .match-head::before { background: radial-gradient(circle at 50% 100%, transparent 7px, var(--ink) 7.5px 9px, transparent 9.5px) 0 0 / 24px 12px; }
@@ -63,8 +64,8 @@
.match-file .diff-scroll { max-height: none; overflow: auto hidden; }
.match-file .diff-head .note { display: inline-flex; align-items: center; gap: 4px; color: var(--warn); font-size: var(--fs-xs); }
.match-marks { min-width: 20px; padding: 0 6px; border-radius: 999px; background: var(--accent); color: var(--on-accent); font-size: var(--fs-xs); text-align: center; }
.match-file tr.marked td.code { box-shadow: inset 3px 0 0 var(--accent); }
.match-file tr.match-mark td, .match-file tr.match-comment td { padding: 4px 10px; background: var(--info-soft); font-family: var(--sans); white-space: normal; }
table.diff tr.marked td.code { box-shadow: inset 3px 0 0 var(--accent); }
table.diff tr.match-mark td, table.diff tr.match-comment td { padding: 4px 10px; background: var(--info-soft); font-family: var(--sans); white-space: normal; }
.match-mark-text { margin-left: 6px; }
.match-comment-box { display: grid; gap: 6px; }
.match-comment-box .actions { display: flex; justify-content: flex-end; gap: 6px; }
@@ -6,6 +6,24 @@ body.fit .graph.resources > .res-panels { flex: 1; }
.res-title { display: inline-flex; color: var(--text); font-size: var(--fs-md); }
.res-legend { display: flex; flex: 1; min-width: 0; font-variant-numeric: tabular-nums; }
.res-switch[aria-pressed="true"] { background: var(--accent-soft); color: var(--accent); }
.res-panels-menu { position: relative; }
.res-panels-menu > summary { padding: 4px 10px; }
.res-panels-menu .menu-box { gap: 2px; min-width: 11rem; padding: 6px; }
.res-pick { display: flex; align-items: center; gap: 8px; padding: 4px 6px; border-radius: 8px; cursor: pointer; }
.res-pick:has(input:disabled) { cursor: not-allowed; opacity: 0.7; }
.res-accounts { flex: 0 1 auto; min-height: 0; overflow: visible; }
.acc-title { color: var(--text); font-size: var(--fs-sm); font-weight: 620; }
.acc-scroll { max-width: 100%; overflow-x: auto; }
.acc-table { width: 100%; border-collapse: collapse; font-size: var(--fs-sm); font-variant-numeric: tabular-nums; }
.acc-table th, .acc-table td { padding: 4px 8px; border-bottom: 1px solid var(--line); text-align: left; white-space: nowrap; }
.acc-table th { color: var(--muted); font-size: var(--fs-xs); font-weight: 650; }
.acc-table tr[data-active] td { background: var(--accent-soft); }
.acc-table .pill { margin-left: 6px; }
.acc-unassigned td { color: var(--muted); }
.acc-form { display: grid; grid-template-columns: repeat(auto-fit, minmax(14rem, 1fr)); gap: var(--sp-2) var(--sp-3); }
.acc-field { display: grid; gap: 4px; font-size: var(--fs-sm); }
.acc-pair { display: flex; gap: 6px; }
.acc-pair > * { flex: 1; min-width: 0; }
.res-plot { position: relative; flex: 1; min-height: 0; }
.res-plot > svg { position: absolute; inset: 0; width: 100%; height: 100%; }
svg .band.idle { fill: var(--ok-soft); }
+7
View File
@@ -97,3 +97,10 @@ svg .forecast-label { fill: var(--ok); font-size: var(--fs-2xs); font-weight: 65
.burn-forecast { display: inline-flex; align-items: center; gap: 6px; }
svg .node.a-worktree.open circle { stroke: var(--warn); stroke-width: 2.6; stroke-dasharray: 3 2; }
svg .edge.flow { stroke-dasharray: 2 5; }
.inbox-list > li[data-blocked], .feed > li[data-blocked], .operator-list > li { filter: grayscale(1); opacity: 0.72; }
.item-blocked { display: flex; align-items: flex-start; gap: 6px; margin: 4px 0 0; color: var(--muted); font-size: var(--fs-sm); }
.operator-rows { display: grid; gap: 6px; margin-top: var(--sp-3); }
.operator-rows > h3 { display: flex; align-items: center; gap: 8px; margin: 0; }
.operator-list { display: grid; gap: 4px; margin: 0; padding: 0; list-style: none; }
.operator-list > li { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; min-width: 0; padding: 6px 10px; border: 1px solid var(--line); border-radius: 10px; cursor: not-allowed; }
.operator-list code { min-width: 0; overflow-wrap: anywhere; }
+29 -16
View File
@@ -73,19 +73,28 @@ body.fit .spot-host { flex: none; }
.radio-card-head { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); min-width: 0; min-height: 30px; }
.radio-card-head .group-title { margin-inline-end: var(--sp-2); }
.composer { display: grid; gap: var(--sp-2); min-width: 0; }
.composer-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 180px), 1fr)); gap: var(--sp-2) var(--sp-3); }
.composer-grid label { display: grid; grid-template-columns: 4.5em minmax(0, 1fr); align-items: center; gap: var(--sp-2); min-width: 0; color: var(--muted); font-size: var(--fs-sm); }
.composer-grid .field { width: 100%; min-width: 0; }
.composer textarea { min-height: 64px; }
.radio-card.radio-speak { border-radius: 14px; }
.composer-grid { display: flex; min-width: 0; overflow: hidden; border: 1px solid var(--line); border-radius: 10px; background: var(--glass-card); }
.composer-grid label { display: flex; flex: 1 1 0; align-items: center; gap: 6px; min-width: 0; padding-inline-start: 12px; color: var(--muted); font-size: var(--fs-sm); }
.composer-grid label + label { border-inline-start: 1px solid var(--line); }
.composer-grid .field { flex: 1 1 auto; width: 100%; min-width: 0; border: 0; border-radius: 0; background: transparent; }
.composer textarea { min-height: 64px; border-radius: 10px; }
.composer [hidden] { display: none; }
.composer .actions { flex-wrap: wrap; align-items: center; margin-top: 0; }
.composer-hint { flex: 1 1 14em; min-width: 0; margin: 0; font-size: var(--fs-xs); }
.composer .actions { flex-wrap: wrap; align-items: center; gap: 6px; margin-top: 0; }
.composer .mayday-toggle { border-radius: 999px; }
.composer .mayday-toggle[aria-pressed="true"] { background: var(--bad); color: #fff; }
.composer .ptt-split { display: inline-flex; margin-inline-start: auto; }
.ptt-split > .ptt { border-start-end-radius: 0; border-end-end-radius: 0; }
.ptt-menu > summary.ptt-more { height: 100%; padding-inline: 6px; border-inline-start: 1px solid color-mix(in srgb, currentColor 30%, transparent); border-start-start-radius: 0; border-end-start-radius: 0; list-style: none; }
.ptt-split > .ptt { border-start-start-radius: 999px; border-end-start-radius: 999px; border-start-end-radius: 0; border-end-end-radius: 0; }
.ptt-menu > summary.ptt-more { height: 100%; padding-inline: 6px; border-inline-start: 1px solid color-mix(in srgb, currentColor 30%, transparent); border-start-start-radius: 0; border-end-start-radius: 0; border-start-end-radius: 999px; border-end-end-radius: 999px; list-style: none; }
.ptt-menu > summary.ptt-more::-webkit-details-marker { display: none; }
.radio-cancel[hidden] { display: none; }
.mayday-confirm { display: flex; flex-wrap: wrap; align-items: center; gap: 6px var(--sp-2); padding: 6px 10px; border-radius: 10px; background: color-mix(in srgb, var(--bad) 14%, transparent); }
.mayday-confirm > p { flex: 1 1 14em; margin: 0; font-size: var(--fs-sm); }
.mayday-confirm > .actions { margin: 0 0 0 auto; }
.composer-status { min-width: 0; overflow-wrap: anywhere; }
.slash-list { position: fixed; z-index: 80; display: grid; width: min(28rem, 100vw - 16px); max-height: 18rem; overflow: auto; padding: 4px; border: 1px solid var(--line); border-radius: 10px; background: var(--glass-card); box-shadow: var(--shadow); }
.slash-option { display: grid; gap: 2px; padding: 6px 8px; border-radius: 8px; cursor: pointer; }
.slash-option[aria-selected="true"] { background: color-mix(in srgb, var(--accent) 18%, transparent); }
.slash-option > .muted { overflow: hidden; font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
.voice-note { display: flex; flex-wrap: wrap; align-items: center; gap: var(--sp-2); }
.voice-replay { max-width: 100%; height: 34px; }
.voice-note .voice-play { display: none; }
@@ -139,7 +148,8 @@ body.fit .spot-host { flex: none; }
.chip-select { min-width: 0; }
.chip-select .field { max-width: 160px; padding: 3px 8px; border-radius: 999px; font-size: var(--fs-sm); }
.chip-select[data-active="true"] .field { border-color: transparent; background: var(--accent-soft); color: var(--accent); }
.radio-logbox input[type="search"] { flex: 1 1 0; min-width: 5rem; padding: 4px 10px; border: 1px solid var(--line-strong); border-radius: 10px; background: var(--panel); }
.radio-logbox > .radio-card-head > .mic-line { flex: 1 1 0; width: auto; min-width: 5rem; }
.radio-logbox input[type="search"] { padding: 4px 10px; }
.radio-logbox { flex: 1 1 auto; min-height: 0; container: history / inline-size; }
.radio-log { display: grid; flex: 1 1 0; align-content: start; gap: 4px; height: 0; min-height: clamp(6.5rem, 30vh - 7rem, 24rem); margin: 0; padding: 0 2px 0 0; overflow: hidden auto; overscroll-behavior: contain; list-style: none; scrollbar-width: thin; scroll-margin-top: var(--head); }
.radio-log, .radio-device, .radio-speak, .shell > main { scrollbar-color: color-mix(in srgb, var(--muted) 45%, transparent) transparent; }
@@ -211,10 +221,11 @@ body.fit .spot-host { flex: none; }
.radio-spot .radio-column { grid-area: 2 / 2; gap: var(--sp-2); }
.radio-spot .radio-speak { flex: none; }
.radio-spot .radio-log { min-height: 4.25rem; }
.radio-spot .composer { grid-template-columns: auto minmax(0, 1fr); }
.radio-spot .composer { grid-template-columns: minmax(0, 1fr) fit-content(50%); }
.radio-spot .composer > * { grid-column: 1 / -1; }
.radio-spot .composer > .voice-note:not([hidden]) { grid-column: 1; }
.radio-spot .composer > .voice-note:not([hidden]) + .actions { grid-column: 2; }
.radio-spot .composer > .mic-area { grid-area: 2 / 1 / 4 / 2; }
.radio-spot .composer > .voice-note:not([hidden]) { grid-area: 2 / 2; align-self: start; }
.radio-spot .composer > .actions { grid-area: 3 / 2; align-self: end; }
.radio-spot .radio-face { grid-template-columns: auto minmax(0, max-content) minmax(0, 1fr) auto; }
.radio-spot .radio-display { display: grid; grid-template-columns: subgrid; }
.radio-spot .radio-caption { z-index: 1; grid-area: 1 / 2 / 2 / 4; gap: 4px; min-height: 0; padding: 0 4px; background-color: var(--sunken); background-image: linear-gradient(var(--ok-soft), var(--ok-soft)); }
@@ -225,7 +236,7 @@ body.fit .spot-host { flex: none; }
}
@media (min-width: 80rem) and (45rem <= height <= 66rem), (min-width: 61rem) and (46.5rem <= height <= 66rem), (min-width: 48rem) and (61rem <= height <= 66rem), (min-width: 48rem) and (width < 56rem) and (min-height: 61rem) {
body.fit .shell:has(> .spot-host > .radio-spot:not([hidden])) { padding-bottom: var(--sp-4); }
body.fit .spot-host:has(> .radio-spot:not([hidden])) + main { padding-block: var(--sp-3); }
body.fit .spot-host:has(> .radio-spot:not([hidden])) + main { --main-top: var(--sp-3); padding-block: var(--sp-3); }
.radio-spot:not([hidden]) { gap: 4px var(--sp-3); margin-bottom: 4px; padding-block: 4px; }
.radio-spot .radio-column { gap: 4px; }
.radio-spot .radio-card { gap: 4px; padding: 4px var(--sp-2); }
@@ -250,7 +261,9 @@ body.fit .spot-host { flex: none; }
.radio-spot .radio-speak .composer-grid { order: 1; flex: 1 1 0; }
.radio-spot .radio-speak .composer-grid .field { padding-block: 2px; }
.radio-spot .radio-speak .star { margin-inline-start: 0; }
.radio-spot .radio-speak textarea { order: 4; flex: 1 1 7rem; height: 32px; min-height: 32px; }
.radio-spot .radio-speak .mic-area { order: 4; flex: 1 1 7rem; }
.radio-spot .radio-speak .mic-area > textarea { height: 32px; min-height: 32px; }
.radio-spot .radio-speak .mic-foot { min-height: 0; padding-block: 0; }
.radio-spot .radio-speak .composer-hint { display: none; }
.radio-spot .radio-speak .actions > * { order: 5; }
.radio-spot .radio-speak .composer-status { flex: 1 1 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -272,4 +285,4 @@ body.fit .spot-host { flex: none; }
.ctx-item:is(:hover, :focus) { background: var(--accent-soft); color: var(--accent); outline: none; }
.ctx-item .ctx-label { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.ctx-item .muted { flex: 0 1 auto; max-width: 45%; overflow: hidden; font-size: var(--fs-xs); text-overflow: ellipsis; white-space: nowrap; }
.controls > .toolbar { justify-content: flex-end; margin-inline-start: auto; }
.box-head > .toolbar { justify-content: flex-end; margin-inline-start: auto; }
+2 -1
View File
@@ -129,6 +129,7 @@ const SCRIPT_HOOKS = [
["kvb-org-perform/scripts/log.py", "PreToolUse", "Agent|Task", "spawn", {}],
["kvb-org-perform/scripts/log.py", "PostToolUse", "Bash", "persist", {}],
["kvb-agent-optimize/scripts/graph.py", "PreToolUse", null, "hook", { timeout: 30 }],
["kvb-org-organize/scripts/account.py", "SessionStart", null, "hook", {}],
];
// Trip-wire: python3 recompiles the script it is started with on every call and caches only imported modules; loading it as __main__ by file path reuses its __pycache__.
const AS_MAIN = `'import importlib.util as u,sys;s=u.spec_from_file_location("__main__",sys.argv[1]);m=u.module_from_spec(s);sys.argv=sys.argv[1:];sys.modules["__main__"]=m;s.loader.exec_module(m)'`;
@@ -149,4 +150,4 @@ for (const [script, event, matcher, sub, extra] of SCRIPT_HOOKS) {
}
fs.writeFileSync(settingsPath, JSON.stringify(data, null, 2) + "\n");
console.log(`skills: enabled the caveman and ponytail plugins (plugin skill copies dropped from this .claude), the ${REMINDERS.join(" + ")} reminders, the kvb-org-organize claim gate and resource watch, the kvb-org-radio hooks, the kvb-org-queue gate, the kvb-org-perform log, and the kvb-agent-optimize code graph hook in ${settingsPath}`);
console.log(`skills: enabled the caveman and ponytail plugins (plugin skill copies dropped from this .claude), the ${REMINDERS.join(" + ")} reminders, the kvb-org-organize claim gate, resource watch and session account hook, the kvb-org-radio hooks, the kvb-org-queue gate, the kvb-org-perform log, and the kvb-agent-optimize code graph hook in ${settingsPath}`);
+1 -1
View File
@@ -179,7 +179,7 @@ install_hub() {
cp -a "${REPO_ROOT}/orchestrator/." "${HUB}/"
# Python loads a cached .pyc whose header matches the source mtime and size, and cp -a keeps the mtime: one planted in the sandbox-writable tree would run on the host
find -H "${HUB}" \( -name __pycache__ -o -name '*.py[co]' \) -prune -exec rm -rf {} +
chmod +x "${HUB}/client/permission_hook.py" "${HUB}/client/runner.py" "${HUB}/client/approval.py" "${HUB}/client/cleanup.py" "${HUB}/client/offices.py" "${HUB}/client/sessions.py" "${HUB}/client/resources.py" "${HUB}/client/settings_writer.py"
chmod +x "${HUB}/client/permission_hook.py" "${HUB}/client/runner.py" "${HUB}/client/approval.py" "${HUB}/client/cleanup.py" "${HUB}/client/offices.py" "${HUB}/client/sessions.py" "${HUB}/client/resources.py" "${HUB}/client/settings_writer.py" "${HUB}/client/skills_index.py"
log "skills: the PermissionRequest hook client is ${HUB}/client/permission_hook.py"
log "skills: approvals need a pinned passkey: settings, 'Passkey registrieren', then 'make orchestrator-pin CREDENTIAL=<blob>'; until then every executor refuses"
printf 'KVB_ORCHESTRATOR_USER=%s:%s\nKVB_ORCHESTRATOR_STATE=%s\nKVB_ORCHESTRATOR_COUNCIL=%s\nKVB_ORCHESTRATOR_SKILLS=%s\nKVB_ORCHESTRATOR_PROJECTS=%s\nKVB_ORCHESTRATOR_TREE=%s\nKVB_ORCHESTRATOR_TIMERS=%s\nKVB_ORCHESTRATOR_APPROVERS=%s\nKVB_ORCHESTRATOR_KEPT=%s\n' \
+3 -1
View File
@@ -9,6 +9,8 @@
},
"extras": {
"value": {"emoji": "💰", "label": "Value", "former": []},
"gate": {"emoji": "🚦", "label": "Gate", "former": []}
"gate": {"emoji": "🚦", "label": "Gate", "former": []},
"legal": {"emoji": "⚖️", "label": "Legal", "former": [], "before": "score"},
"architecture": {"emoji": "🏛️", "label": "Architecture", "former": [], "before": "score"}
}
}
+107
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
"""Record which account each session works on, for the Agent Orchestrator.
Usage:
account.py hook: the SessionStart hook; reads the hook payload on stdin.
Environment:
AGENTS_COUNCIL_ROOT, XDG_STATE_HOME, HOME: the council directory
councilroot.py resolves.
HOME: ~/.claude.json, whose oauthAccount.emailAddress is the only field
read.
Returns:
Appends {"session", "email"} to <council>/session-accounts.jsonl, mode
0600, unless the session's last line there already names that email;
a subagent, a payload without session_id or a ~/.claude.json without
the field writes nothing. The exit code is 0, so a session never fails
to start on it.
"""
from __future__ import annotations
import importlib.util
import json
import os
import re
import sys
from pathlib import Path
from types import ModuleType
SESSION_ACCOUNTS = "session-accounts.jsonl"
MODE = 0o600
PROFILE_LIMIT = 32 << 20
EMAIL = re.compile(r"[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9-]{1,63}(?:\.[A-Za-z0-9-]{1,63})*\.[A-Za-z]{2,24}")
def sibling(name: str) -> ModuleType:
spec = importlib.util.spec_from_file_location(f"kvb_account_{name}", Path(__file__).resolve().parent / f"{name}.py")
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)
return module
def email_of(profile: Path) -> str | None:
try:
with profile.open("rb") as handle:
raw = handle.read(PROFILE_LIMIT + 1)
data = json.loads(raw) if len(raw) <= PROFILE_LIMIT else None
except (OSError, ValueError, RecursionError):
return None
account = data.get("oauthAccount") if isinstance(data, dict) else None
email = account.get("emailAddress") if isinstance(account, dict) else None
return email if isinstance(email, str) and EMAIL.fullmatch(email) else None
def recorded(nofollow: ModuleType, root: Path, path: Path, session: str) -> str | None:
try:
text = nofollow.read_text(root, path)
except OSError:
return None
last = None
for line in text.splitlines():
try:
row = json.loads(line)
except ValueError:
continue
if isinstance(row, dict) and row.get("session") == session:
last = row.get("email")
return last
def record(root: Path, payload: object, profile: Path) -> bool:
"""Returns:
True when a mapping line was appended.
"""
if not isinstance(payload, dict) or payload.get("agent_id") or not isinstance(payload.get("session_id"), str) or not payload["session_id"]:
return False
email = email_of(profile)
if email is None:
return False
nofollow = sibling("nofollow")
path = root / SESSION_ACCOUNTS
session = payload["session_id"]
if recorded(nofollow, root, path, session) == email:
return False
root.mkdir(parents=True, exist_ok=True)
nofollow.append(root, path, json.dumps({"session": session, "email": email}) + "\n", MODE)
return True
def main() -> int:
if sys.argv[1:] != ["hook"]:
print("usage: account.py hook", file=sys.stderr)
return 2
try:
payload = json.load(sys.stdin)
except ValueError:
return 0
try:
record(sibling("councilroot").root(), payload, Path(os.environ.get("HOME", str(Path.home()))) / ".claude.json")
except OSError as error:
print(f"account: {error}", file=sys.stderr)
return 0
if __name__ == "__main__":
sys.exit(main())
+1 -1
View File
@@ -79,7 +79,7 @@ try {
if (plan.authenticator) {
await page("WebAuthn.enable", {enableUI: false});
const {authenticatorId} = await page("WebAuthn.addVirtualAuthenticator", {options: {protocol: "ctap2", transport: "internal", hasResidentKey: true, hasUserVerification: true, isUserVerified: true, automaticPresenceSimulation: true}});
await page("WebAuthn.addCredential", {authenticatorId, credential: {...plan.authenticator, isResidentCredential: false, signCount: 0}});
await page("WebAuthn.addCredential", {authenticatorId, credential: {signCount: 0, ...plan.authenticator, isResidentCredential: false}});
}
for (const step of plan.steps) {
await page("Emulation.setDeviceMetricsOverride", {width: step.width, height: step.height, deviceScaleFactor: 1, mobile: false});
+17 -13
View File
@@ -214,11 +214,6 @@ COMPOSE_SEND = """(async () => {@HELPERS@
})()""".replace("@HELPERS@", HELPERS)
CLEAR_MAYDAY = """(async () => {@HELPERS@
const questions = [];
let accept = false;
window.confirm = (question) => {
questions.push(question);
return accept;
};
const posted = [];
const send = window.fetch.bind(window);
window.fetch = (path, init) => {
@@ -229,19 +224,28 @@ CLEAR_MAYDAY = """(async () => {@HELPERS@
};
await until(() => document.querySelector('#main [role="toolbar"]'), 8000);
const toolbar = all('#main [role="toolbar"] button, #main [role="toolbar"] summary').map(name);@SPOT_OPEN@
const button = await until(() => spot && all("form.composer .radio-cancel", spot).find((node) => name(node) === "Cancel mayday" && !node.hidden), 8000);
const button = await until(() => spot && all("form.composer .mayday-toggle", spot).find((node) => name(node) === "Cancel mayday" && node.getAttribute("aria-pressed") === "true"), 8000);
if (!button) {
return {error: "no shown Cancel mayday button next to PTT", toolbar};
return {error: "no pressed Cancel mayday toggle next to PTT", toolbar};
}
const [title, shownLabel, next] = [button.title, text(button), Boolean(button.previousElementSibling && button.previousElementSibling.matches(".ptt-split"))];
const answer = async (yes) => {
button.click();
const box = await until(() => spot.querySelector("form.composer .mayday-confirm"), 4000);
if (box) {
questions.push(text(box.querySelector("p")));
all("button", box).find((node) => text(node) === (yes ? "Cancel mayday" : "Cancel")).click();
}
};
const shown = new Set(all("#toasts .toast"));
const fresh = () => all("#toasts .toast").filter((node) => !shown.has(node)).map(text);
button.click();
await answer(false);
await sleep(800);
const declined = {question: questions.slice(), posted: posted.slice(), toasts: fresh()};
accept = true;
button.click();
await answer(true);
const done = await until(() => fresh().find((toast) => toast.startsWith("Cancel mayday")), 15000);
return {toolbar, title: button.title, shown: text(button), declined, accepted: {question: questions.slice(declined.question.length), posted: posted.slice(declined.posted.length)}, done};
await sleep(600);
return {toolbar, title, shown: shownLabel, next, declined, accepted: {question: questions.slice(declined.question.length), posted: posted.slice(declined.posted.length)}, done, after: [text(button), button.getAttribute("aria-pressed")]};
})()""".replace("@HELPERS@", HELPERS).replace("@SPOT_OPEN@", SPOT_OPEN)
SPOT_SEND = """(async () => {@HELPERS@
const questions = [];
@@ -265,10 +269,10 @@ SPOT_SEND = """(async () => {@HELPERS@
inline: [getComputedStyle(spot).position, spot.getBoundingClientRect().bottom <= main.getBoundingClientRect().top, spot.parentElement.nextElementSibling === main],
toolbar: all('#main [role="toolbar"] > *').map((node) => name(node.tagName === "DETAILS" ? node.querySelector("summary") : node)),
channels: all("option", channel).map((option) => option.value),
record: all("button", form).filter((button) => button.hasAttribute("aria-pressed") && !button.classList.contains("mic")).map(text),
record: all("button", form).filter((button) => button.hasAttribute("aria-pressed") && !button.matches(".mic, .mayday-toggle")).map(text),
heads: all(".spot-head button", spot).length,
send: all(".ptt-split :is(button, summary)", form).filter((node) => !node.closest(".menu-box")).map((node) => [name(node), node.title]),
cancel: form.querySelector(".radio-cancel").hidden,
mayday: [text(form.querySelector(".mayday-toggle")), form.querySelector(".mayday-toggle").getAttribute("aria-pressed"), form.querySelector(".mayday-toggle").previousElementSibling.matches(".ptt-split")],
@FITS@,
};
await until(() => [...recipient.options].some((option) => option.value === "Stage"), 8000);
+6 -5
View File
@@ -301,15 +301,16 @@ REPLY_HOME = """(async () => {@HELPERS@@PROBES@
};
const sent = await sendFrom(tile("radio"), "reply from the Home radio");
const questions = [];
window.confirm = (question) => {
questions.push(question);
return true;
};
const clear = all("form.composer button.radio-cancel", tile("radio")).find((button) => button.getAttribute("aria-label") === "Cancel mayday");
const clear = all("form.composer button.mayday-toggle", tile("radio")).find((button) => text(button) === "Cancel mayday" && button.getAttribute("aria-pressed") === "true");
const enabled = clear ? !clear.disabled : null;
const shownBefore = new Set(all("#toasts .toast"));
if (clear) {
clear.click();
const ask = await until(() => tile("radio").querySelector("form.composer .mayday-confirm"), 4000);
if (ask) {
questions.push(text(ask.querySelector("p")));
all("button", ask).find((button) => text(button) === "Cancel mayday").click();
}
}
const lifted = await until(() => all("#toasts .toast").filter((node) => !shownBefore.has(node)).map(text).find((entry) => entry.startsWith("Cancel mayday")), 15000);
document.getElementById("toasts").replaceChildren();
+5 -4
View File
@@ -154,10 +154,10 @@ HOME = """(async () => {@HELPERS@@PROBES@
await sleep(200);
}
const menu = whole.querySelector(".radio-mode-menu:not([hidden])");
const cancel = whole.querySelector("form.composer .radio-cancel");
const cancel = whole.querySelector("form.composer .mayday-toggle");
const tools = {
menu: opens ? [active.getAttribute("aria-expanded"), Boolean(menu), menu ? box(menu).bottom <= box(whole).bottom + 1 : null] : null,
cancel: cancel ? [cancel.hidden, cancel.title] : null,
cancel: cancel ? [cancel.getAttribute("aria-pressed"), cancel.title] : null,
};
if (opens) {
active.click();
@@ -244,8 +244,9 @@ SPOT = """(async () => {@HELPERS@@PROBES@@SPEAKING@
const edge = box(node);
const [x, y] = [edge.left + edge.width / 2, edge.top + edge.height / 2];
const hit = document.elementFromPoint(x, y);
if (!(list.contains(node) && (y < box(list).top || y > box(list).bottom)) && !(hit === node || node.contains(hit) || (layer && hit && layer.contains(hit) && !layer.contains(node)))) {
found.push(`${named(node)} <- ${hit ? `${hit.tagName}.${hit.getAttribute("class")}#${hit.id}` : "null"}`);
if (!(list.contains(node) && (y <= box(list).top || y >= box(list).bottom)) &&!(hit === node || node.contains(hit) || (layer && hit && layer.contains(hit) && !layer.contains(node)))) {
const under = document.elementsFromPoint(x, y).slice(0, 4).map((item) => `${item.tagName}.${item.getAttribute("class")}`).join(" > ");
found.push(`${named(node)} <- ${hit ? `${hit.tagName}.${hit.getAttribute("class")}#${hit.id}` : "null"} at ${Math.round(x)},${Math.round(y)} list ${Math.round(box(list).top)}-${Math.round(box(list).bottom)} stack ${under}`);
}
}
window.scrollTo(0, 0);
+1 -1
View File
@@ -153,7 +153,7 @@ FACE = """(async () => {@HELPERS@@RADIO@
await sleep(150);
const menuFits = fits();
await modeMenu("auto", false);
const send = [name(spot.querySelector("form.composer .ptt-more")), spot.querySelector("form.composer .radio-cancel").hidden];
const send = [name(spot.querySelector("form.composer .ptt-more")), spot.querySelector("form.composer .mayday-toggle").getAttribute("aria-pressed")];
const stationsHead = text(spot.querySelector(".radio-station .group-title"));
const ptt = spot.querySelector('form.composer button[type="submit"]');
const pageFits = fits();
+1 -1
View File
@@ -17,7 +17,7 @@ OUT = Path(os.environ.get("E2E_OUT", "/tmp/agents-controls-shots"))
VIEWS = (*base.VIEWS, "hierarchy")
READ = """
const rect = (node) => node.getBoundingClientRect();
const card = () => document.querySelector("#main .graph > .card.controls");
const card = () => document.querySelector("#main .graph > .box-head");
const bar = () => card() && card().querySelector(':scope > [role="toolbar"]');
const menuOf = (label) => all("details.menu", bar()).find((node) => name(node.querySelector("summary")) === label);
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
+191
View File
@@ -0,0 +1,191 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
import test_home_bookmarks_e2e as bm
import test_home_dashboard_e2e as dash
import test_match_review_e2e as matched
import test_workbench_w4_e2e as w4
from hub_case import HubCase
OUT = Path(os.environ.get("E2E_OUT", "/tmp/box-heads-shots"))
VIEWS = {
"tasks/match": "Match",
"tasks/list": "Tasks",
"tasks/board": "Tasks",
"resources": "Resources",
"agents/orbit": "Agents",
"artifacts/orbit": "Artifacts",
"stream/rules": "Controls",
}
PINNED = ["tasks/match", "tasks/list", "tasks/board", "agents/orbit", "artifacts/orbit"]
PATTERNS = ["dots", "stripes", "waves", "grid", "rings"]
BUTTON = """
const buttonHeight = (root, selector) => {
const found = all(selector, root).find((node) => node.getClientRects().length);
return found ? Math.round(found.getBoundingClientRect().height) : null;
};
"""
BAND = """(async () => {@HELPERS@@BUTTON@
if (!(await screenShown(8000))) {
return {error: "no screen"};
}
const main = document.getElementById("main");
const head = await until(() => main.querySelector(".box-head"), 8000);
if (!head) {
return {error: text(main).slice(0, 300)};
}
await sleep(400);
let first = true;
for (let node = head; node !== main; node = node.parentElement) {
first = first && node.parentElement.firstElementChild === node;
}
const style = getComputedStyle(main);
const outer = main.getBoundingClientRect();
const box = head.getBoundingClientRect();
const tops = [...head.querySelectorAll(":scope > *, :scope > .box-slot > *")].filter((node) => node.getClientRects().length).map((node) => Math.round(node.getBoundingClientRect().top));
return {
label: head.getAttribute("aria-label"), count: all(".box-head", main).length, cards: all(".card.controls", main).length, first,
edges: [box.top - outer.top - parseFloat(style.borderTopWidth), box.left - outer.left - parseFloat(style.borderLeftWidth), outer.right - parseFloat(style.borderRightWidth) - box.right].map((value) => Math.round(value * 10) / 10),
height: Math.round(box.height), rows: new Set(tops).size, button: buttonHeight(head, "button.btn.small, button.btn"),
wide: document.documentElement.scrollWidth > innerWidth + 1, violations: window.e2eViolations || null,
};
})()"""
SEED = """(async () => {@HELPERS@
await ViewStore.update("home.pins", () => @PINNED@.map((id) => ({kind: "panel", id, w: innerWidth > 640 ? 6 : 4, h: 5})));
return true;
})()"""
TILES = """(async () => {@HELPERS@@HOME@@BUTTON@
await go("home");
await until(() => all("#main .home-tile").length === @COUNT@, 8000);
await sleep(1200);
const head = document.querySelector("#main .home-tile .home-head");
return {
head: head ? Math.round(head.getBoundingClientRect().height) : null, button: head ? buttonHeight(head, ".home-unpin") : null,
tiles: all("#main .home-tile").map((tile) => ({
key: tile.dataset.pin, heads: all(".home-body .box-head", tile).length, kanban: Boolean(tile.querySelector(".home-head .kanban-bar")),
})),
wide: document.documentElement.scrollWidth > innerWidth + 1, violations: window.e2eViolations || null,
};
})()"""
EDGE = """(async () => {@HELPERS@
if (!(await screenShown(8000))) {
return {error: "no screen"};
}
const card = await until(() => document.querySelector("#main .match-card.front"), 8000);
if (!card) {
return {error: text(document.getElementById("main")).slice(0, 300)};
}
const head = card.querySelector(".match-head");
const kept = card.dataset.pattern;
const found = {};
for (const pattern of @PATTERNS@) {
card.dataset.pattern = pattern;
await sleep(60);
const shown = getComputedStyle(card);
const after = getComputedStyle(head, "::before");
found[pattern] = {
border: shown.borderTopWidth, bar: shown.backgroundImage.startsWith("linear-gradient"), size: shown.backgroundSize.split(",")[0].trim(),
flush: Math.round(head.getBoundingClientRect().top - card.getBoundingClientRect().top), top: after.top,
mask: (after.maskImage || after.webkitMaskImage || "").replace(/\\s+/g, " "), hatch: after.backgroundImage !== "none",
};
}
card.dataset.pattern = kept;
return {found};
})()"""
def probe(template: str, **names: str) -> str:
fills = {"@HELPERS@": base.HELPERS, "@HOME@": dash.HOME, "@BUTTON@": BUTTON, "@PINNED@": json.dumps(PINNED), "@COUNT@": str(len(PINNED)), "@PATTERNS@": json.dumps(PATTERNS)}
fills.update({f"@{key.upper()}@": value for key, value in names.items()})
for key, value in fills.items():
template = template.replace(key, value)
return template
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestBoxHeads(HubCase):
seed = base.OrchestratorE2ECase.seed
subagents = base.OrchestratorE2ECase.subagents
drive = base.OrchestratorE2ECase.drive
cards = matched.TestMatchReview.cards
review = matched.TestMatchReview.review
payload = matched.TestMatchReview.payload
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.seed()
self.cards()
def steps(self, browser: str) -> list[dict]:
steps = []
for width, height in base.WIDTHS:
at = {"width": width, "height": height}
shot = OUT / f"{browser}-{width}"
steps += [{**at, "url": f"{self.base}?{width}-{view.replace('/', '-')}#{view}", "wait": 1500, "probe": probe(BAND), "shot": f"{shot}-{view.replace('/', '-')}.png"} for view in VIEWS]
steps += [
{**at, "url": f"{self.base}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
{**at, "url": f"{self.base}?{width}-seed#stream", "wait": 800, "probe": probe(SEED), "shot": None},
{**at, "url": f"{self.base}?{width}-home#home", "wait": 1500, "probe": probe(TILES), "shot": f"{shot}-home-tiles.png"},
{**at, "url": f"{self.base}?{width}-edge#tasks/match", "wait": 1500, "probe": probe(EDGE), "shot": f"{shot}-match-edge.png"},
]
return steps
def check_band(self, row: dict, view: str, width: int, home: dict) -> None:
self.assertNotIn("error", row, row)
self.assertEqual((row["label"], row["count"], row["cards"], row["first"]), (VIEWS[view], 1, 0, True), row)
self.assertEqual(row["edges"], [0, 0, 0], row)
self.assertEqual((row["wide"], w4.quiet(row["violations"])), (False, []), row)
if width == 1920 and row["rows"] == 1:
self.assertLessEqual(abs(row["height"] - home["head"]), 1, (row, home["head"]))
self.assertLessEqual(abs(row["button"] - home["button"]), 1, (row, home["button"]))
else:
self.assertLessEqual(row["height"], row["rows"] * (home["head"] + 6) + 1, (row, home["head"]))
def check(self, data: dict, browser: str) -> None:
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
bands = {view: next(results) for view in VIEWS}
next(results)
next(results)
home = next(results)
edge = next(results)
with self.subTest(browser=browser, width=width, step="tiles"):
self.assertEqual(sorted(tile["key"] for tile in home["tiles"]), sorted(f"panel:{view}" for view in PINNED), home)
self.assertEqual([tile["key"] for tile in home["tiles"] if tile["heads"]], [], home)
self.assertEqual([tile["key"] for tile in home["tiles"] if tile["kanban"]], ["panel:tasks/board"], home)
self.assertEqual((home["wide"], w4.quiet(home["violations"])), (False, []), home)
for view, row in bands.items():
with self.subTest(browser=browser, width=width, view=view):
self.check_band(row, view, width, home)
with self.subTest(browser=browser, width=width, step="edge"):
self.assertNotIn("error", edge, edge)
for pattern, found in edge["found"].items():
self.assertEqual((found["border"], found["bar"], found["size"], found["flush"], found["top"], found["hatch"]), ("0px", True, "100% 6px", 0, "0px", True), (pattern, found))
self.assertTrue(found["mask"].startswith("linear-gradient(rgba(0, 0, 0, 0) 6px"), (pattern, found))
def test_chromium_puts_one_flush_band_on_every_box_and_keeps_the_card_bar_on_the_edge(self):
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
(OUT / "chromium-box-heads.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data, "chromium")
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
def test_firefox_puts_one_flush_band_on_every_box_and_keeps_the_card_bar_on_the_edge(self):
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
(OUT / "firefox-box-heads.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data, "firefox")
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -250,7 +250,7 @@ class TestBulkGrant(base.OrchestratorE2ECase):
self.assertEqual(collect["restored"], selecting, collect)
self.assertEqual(collect["pale"], [True, True], collect)
self.assertEqual(collect["counts"], ["1 selected", "2 selected", "1 selected", "2 selected", "3 selected"], collect)
self.assertEqual((collect["pressed"], collect["posted"]), ([["true", True], ["true", False], ["true", True]], []), collect)
self.assertEqual((collect["pressed"], collect["posted"]), ([["true", True], ["true", True], ["true", True]], []), collect)
self.assertEqual((collect["labels"][0], collect["labels"][-1]), ("Grant selection (3)", "Direct"), collect)
self.assertEqual(sum(label.startswith("Remove ") for label in collect["labels"]), 3, collect)
self.assertEqual((sheet["label"], len(sheet["listed"])), ("Grant 3", 3), sheet)
+141
View File
@@ -0,0 +1,141 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
import hub_support
from hub_case import HubCase
from hub_support import verifier
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-029-shots"))
TEMPLATES = hub_support.HUB / "templates"
PRESENT = [f"/srv/p{index:02d}/.claude/settings.json" for index in range(10)]
ABSENT = [f"/srv/a{index:02d}/.claude/settings.json" for index in range(30)]
BROKEN = {PRESENT[3], PRESENT[7]}
READ = """
const box = () => document.querySelector("#main .fw-controls");
const tab = (id) => document.getElementById(`controls-tab-${id}`);
const flush = () => {
const head = box().querySelector(":scope > .box-head");
const main = document.getElementById("main");
return Boolean(head && head.querySelector('[role="tablist"]')) && Math.abs(head.getBoundingClientRect().top - main.getBoundingClientRect().top - parseFloat(getComputedStyle(main).borderTopWidth)) <= 1;
};
const width = (label) => {
const node = document.querySelector(`#main section[aria-label="${label}"]`);
return node && node.getClientRects().length ? node.getBoundingClientRect().width : null;
};
const misaligned = (form) => {
const boxes = all("label", form).filter((label) => label.querySelector(".field") && label.getClientRects().length).map((label) => label.getBoundingClientRect());
return boxes.filter((one, index) => boxes.slice(index + 1).some((two) => Math.min(one.bottom, two.bottom) - Math.max(one.top, two.top) > 0 && Math.abs(one.top - two.top) > 1)).length;
};
const forms = () => all("#main form").filter((form) => form.getClientRects().length).map((form) => [form.getAttribute("aria-label") || form.className, misaligned(form)]);
const sources = () => all("#main tbody[data-source]").map((body) => body.dataset.source).filter((source) => source !== "hub");
const toggle = () => document.querySelector("#main .fw-missing");
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
"""
RULES = """(async () => {@HELPERS@@READ@
if (!(await until(() => box() && sources().length === 10 && toggle(), 15000))) {
return {error: text(document.getElementById("main")), sources: sources()};
}
tab("rules").click();
const folded = {sources: sources(), toggle: text(toggle()), pressed: toggle().getAttribute("aria-pressed")};
toggle().click();
await until(() => sources().length === 40, 4000);
const opened = {count: sources().length, last: sources().slice(-1)[0], toggle: text(toggle()), pressed: toggle().getAttribute("aria-pressed")};
toggle().click();
await until(() => sources().length === 10, 4000);
return {folded, opened, flush: flush(), rules: width("Firewall rules"), forms: forms(), multiple: all("#main select[multiple]").length, wide: wide()};
})()"""
GROUPS = """(async () => {@HELPERS@@READ@
tab("groups").click();
const form = await until(() => width("Agent groups") && document.querySelector('#main form[aria-label="New agent group"]'), 4000);
const chips = all('[aria-label="Members"] label.check-chip', form);
const faces = chips.filter((chip) => chip.querySelector(".avatar svg")).length;
form.querySelector('input[aria-label="Group name"]').value = "@NAME@";
for (const chip of chips) {
chip.querySelector("input").checked = ["Skills", "Stage"].includes(text(chip));
}
const lit = chips.filter((chip) => getComputedStyle(chip).backgroundColor !== getComputedStyle(chips.find((other) => !other.querySelector("input").checked)).backgroundColor).map(text);
form.requestSubmit();
const row = await until(() => document.querySelector('#main [data-group="@NAME@"]'), 8000);
return {
flush: flush(), groups: width("Agent groups"), sets: width("Rule sets"), chips: chips.map(text), faces, lit, row: row ? text(row.querySelector(".muted")) : null,
emptyRules: text(document.querySelector('#main form[aria-label="New rule set"] .fw-chips-field p')), forms: forms(), multiple: all("#main select[multiple]").length, wide: wide(),
};
})()"""
def probe(template: str, name: str) -> str:
for key, value in {"@HELPERS@": base.HELPERS, "@READ@": READ, "@NAME@": name}.items():
template = template.replace(key, value)
return template
def view_files() -> list[dict]:
present = [{"path": path, "exists": True, "folder": True, "sha256": "", "error": "unreadable: ValueError" if path in BROKEN else "", "settings": {}} for path in PRESENT]
absent = [{"path": path, "exists": False, "folder": False, "sha256": "", "error": "no directory: create it first", "settings": {}} for path in ABSENT]
return [*absent[:15], *reversed(present), *absent[15:]]
class TestControlsSource(unittest.TestCase):
def test_no_controls_form_uses_a_multi_select(self):
for name in ("page-rules.js", "page-firewall.js"):
with self.subTest(name=name):
self.assertNotIn("multiple", (TEMPLATES / name).read_text(encoding="utf-8"))
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestControlsLayout(HubCase):
drive = base.OrchestratorE2ECase.drive
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.claim("s1", "Skills")
self.claim("s2", "Stage")
self.claim("s3", "Store")
self.snapshot()
verifier.write_private(self.state / "firewall" / "view.json", {"written": 0, "files": view_files()})
self.page_url = f"http://localhost:{self.port}/"
def test_chromium_lays_out_rules_and_groups_folds_missing_files_and_names_a_group_by_chips_at_three_widths(self):
steps = []
for width, height in base.WIDTHS:
shot = OUT / f"chromium-{width}"
steps += [
{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream/rules", "wait": 1500, "probe": probe(RULES, ""), "shot": f"{shot}-rules.png"},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(GROUPS, f"pair{width}"), "shot": f"{shot}-groups.png"},
]
data = self.drive(steps, None)
(OUT / "chromium-controls-layout.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
results = iter(data["results"])
errors_first = [PRESENT[3], PRESENT[7], *[path for path in PRESENT if path not in BROKEN]]
for width, _ in base.WIDTHS:
rules, groups = next(results), next(results)
with self.subTest(width=width):
self.assertNotIn("error", rules, rules)
self.assertEqual(rules["folded"], {"sources": errors_first, "toggle": "show 30 missing", "pressed": "false"})
self.assertEqual(rules["opened"], {"count": 40, "last": ABSENT[-1], "toggle": "hide 30 missing", "pressed": "true"})
self.assertTrue(rules["flush"], rules)
self.assertTrue(groups["flush"], groups)
self.assertAlmostEqual(groups["groups"], rules["rules"], delta=1)
self.assertAlmostEqual(groups["sets"], rules["rules"], delta=1)
self.assertEqual([count for _, count in rules["forms"] + groups["forms"]], [0] * (len(rules["forms"]) + len(groups["forms"])), (rules["forms"], groups["forms"]))
self.assertEqual((rules["multiple"], groups["multiple"], rules["wide"], groups["wide"]), (0, 0, False, False))
self.assertEqual((groups["chips"], groups["faces"], sorted(groups["lit"])), (["Skills", "Stage", "Store"], 3, ["Skills", "Stage"]))
self.assertEqual(groups["row"], "Skills, Stage")
self.assertTrue(groups["emptyRules"].startswith("No rule yet: create one under Rules"), groups["emptyRules"])
self.assertEqual(sorted((group["name"], group["members"]) for group in self.httpd.hub.groups.listed()), sorted((f"pair{width}", ["s1", "s2"]) for width, _ in base.WIDTHS))
if __name__ == "__main__":
unittest.main()
+8 -8
View File
@@ -47,7 +47,7 @@ SHOW = """(async () => {@HELPERS@
wrap.scrollIntoView({block: "start"});
await sleep(100);
return {
title: text(document.querySelector("#main h2.title")),
title: text(document.querySelector("#main .box-head h2.box-title")),
tabs: {first, picked: tabs()},
subs: all("#tabs .subtabs button").map(name),
sources,
@@ -162,8 +162,8 @@ GROUP_RULE = """(async () => {@HELPERS@
(await until(() => document.querySelector('#main tbody[data-source="hub"] .fw-fold'), 10000)).click();
const group = document.querySelector('#main form[aria-label="New agent group"]');
group.querySelector('input[aria-label="Group name"]').value = "builders";
for (const option of group.querySelector('select[aria-label="Members"]').options) {
option.selected = true;
for (const box of group.querySelectorAll('[aria-label="Members"] input[type="checkbox"]')) {
box.checked = true;
}
group.requestSubmit();
const row = await until(() => document.querySelector('#main [data-group="builders"]'), 8000);
@@ -182,8 +182,8 @@ GROUP_RULE = """(async () => {@HELPERS@
const found = {group: text(row.querySelector("strong")), members: text(row.querySelector(".muted")), pills: all("#main tr[data-rule] [data-agents]").map(text), found: Boolean(pill), hits, toasts: all("#toasts .toast").map(text)};
const sets = document.querySelector('#main form[aria-label="New rule set"]');
sets.querySelector('input[aria-label="Set name"]').value = "ci";
for (const option of sets.querySelector('select[aria-label="Rules"]').options) {
option.selected = option.textContent.includes("make e2e");
for (const box of sets.querySelectorAll('[aria-label="Rules"] input[type="checkbox"]')) {
box.checked = box.closest("label").textContent.includes("make e2e");
}
sets.requestSubmit();
if (!await until(setRow, 8000)) {
@@ -291,9 +291,9 @@ class TestFirewallE2E(HubCase):
self.assertNotIn("error", shown, shown)
self.assertEqual((shown["title"], shown["subs"]), ("Controls", base.SUBS))
self.assertEqual(shown["tabs"], {"first": [["tools", "true", False], ["rules", "false", True], ["groups", "false", True]], "picked": [["tools", "false", True], ["rules", "true", False], ["groups", "false", True]]})
self.assertEqual(shown["sources"], ["hub", str(self.settings), str(self.outside / "demo" / ".claude" / "settings.json")])
self.assertEqual(shown["folded"], {"expanded": ["false"] * 3, "rows": 0})
self.assertEqual(shown["opened"], ["true"] * 3)
self.assertEqual(shown["sources"], ["hub", str(self.settings)])
self.assertEqual(shown["folded"], {"expanded": ["false"] * 2, "rows": 0})
self.assertEqual(shown["opened"], ["true"] * 2)
self.assertEqual(shown["heads"], ["Action", "Tool", "Pattern", "Scope", "Source", "Hits (7 days)", ""])
self.assertEqual(shown["chips"], [[chip, "true"] for chip in ("allow", "ask", "deny", "sandbox", "signed")])
rows = shown["rows"]
+8 -4
View File
@@ -62,7 +62,7 @@ KIT = """
CLEAR = """(async () => {
sessionStorage.clear();
await Promise.all([ViewStore.update("home.pins", () => []), ViewStore.update("resources.hidden", () => []), ViewStore.update("resources.combinedHidden", () => []),
ViewStore.set("resources.combined", false), ViewStore.set("resources.tokens", "interval")]);
ViewStore.update("resources.panels", () => ["hardware", "tokens", "accounts"]), ViewStore.set("resources.tokens", "interval")]);
return true;
})()"""
LOADED = """(async () => {@HELPERS@@READ@
@@ -112,7 +112,9 @@ METRIC = """(async () => {@HELPERS@@HOME@@READ@@KIT@
const back = Boolean(await until(() => lineIds(document.querySelector(panel("hardware"))).length === @COUNT@, 5000));
await sleep(200);
const allState = [starOf(panel("hardware")).getAttribute("aria-pressed"), starOf(panel("hardware")).getAttribute("title")];
switched("combined").click();
await pickPanel("combined", true);
await pickPanel("hardware", false);
await pickPanel("tokens", false);
const combinedOn = Boolean(await until(() => charts().join() === "combined" && burn().length === 2, 5000));
const combined = await press(panel("combined"));
return {cpuOnly, hardware, cpuTitle, tokens, back, allState, combinedOn, combined, axisOverlaps, stored: (ViewStore.get("home.pins") || []).map((pin) => [pin.kind, pin.id, pin.view || null])};
@@ -120,7 +122,9 @@ METRIC = """(async () => {@HELPERS@@HOME@@READ@@KIT@
COMBINED_OFF = """(async () => {@HELPERS@@HOME@@READ@@KIT@
await go("resources");
await until(() => charts().join() === "combined", 8000);
switched("combined").click();
await pickPanel("hardware", true);
await pickPanel("tokens", true);
await pickPanel("combined", false);
const off = Boolean(await until(() => charts().length === 2 && lines().length === @COUNT@, 8000));
await sleep(300);
return {off, hardware: [starOf(panel("hardware")).getAttribute("aria-pressed"), starOf(panel("hardware")).getAttribute("title")]};
@@ -384,7 +388,7 @@ class TestHomeBookmarks(HubCase):
loaded = next(results)
self.assertTrue(loaded["drawn"], loaded)
found = next(results)
self.assertEqual((found["charts"], found["chips"], found["inHead"]), ([True, True, True], 0, True), found)
self.assertEqual((found["charts"], found["chips"], found["inHead"]), ([True] * 4, 0, True), found)
self.assertEqual(found["tree"], [True], found)
self.assertTrue(found["rows"]["repo"] and all(found["rows"]["repo"]), found)
self.assertTrue(found["rows"]["branch"] and all(found["rows"]["branch"]), found)
+1 -1
View File
@@ -151,10 +151,10 @@ class TestHubInbox(base.OrchestratorE2ECase):
stops = []
with mock.patch.object(batches, "UNDO", 0.3):
data = self.drive(steps, self.authenticator() if signs else None, driver, binary)
(OUT / f"{browser}-inbox-deny-selection.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
if signs:
self.settle(lambda: len([call for call in self.scripts.calls if call[0] == skill_scripts.RASCI]) >= 2 * len(WIDTHS))
stops = [args for script, args in self.scripts.calls if script == skill_scripts.RASCI]
(OUT / f"{browser}-inbox-deny-selection.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], [])
denied = []
for found, (width, _) in zip(data["results"], WIDTHS, strict=True):
+14 -14
View File
@@ -46,6 +46,8 @@ from hub_e2e_radio import (
from hub_support import HOST_STATE
from kvb_orchestrator import skill_scripts
SPEAK_CHANNELS = [channel for channel in CHOICE_CHANNELS if channel != "mayday"]
PRESSED = ["Cancel mayday", "true", True]
SEND_GROUP = [["PTT", "PTT: push to transmit the message; your passkey signs it"], ["More send options", "More: send a test message only you hear"]]
@@ -231,7 +233,7 @@ class TestHubRadio(base.OrchestratorE2ECase):
self.assertEqual(data["errors"], [])
composed, plain, again, sent = data["results"]
self.assertNotIn("error", composed)
self.assertEqual(composed["channels"], ["post", "call", "newsletter", "broadcast", "pan-pan", "security", "mayday"])
self.assertEqual(composed["channels"], SPEAK_CHANNELS)
self.assertIn("Stage", composed["recipients"])
self.assertEqual(composed["recording"], "true")
self.assertEqual(composed["text"], "hello from the mic second line", composed)
@@ -262,7 +264,7 @@ class TestHubRadio(base.OrchestratorE2ECase):
with self.subTest(width=width):
self.assertNotIn("error", result)
self.assertEqual(result["toolbar"], ["Priority", "Day/Night", "Drain", "Suspend", "Resume", "Status"])
self.assertEqual((result["title"], result["shown"]), ("Cancel mayday: lift the radio silence so the agents write again; your passkey signs it", "Cancel mayday"))
self.assertEqual((result["title"], result["shown"], result["next"]), ("Cancel mayday: lift the radio silence so the agents write again; your passkey signs it", "Cancel mayday", True))
self.assertEqual(result["declined"], {"question": [question], "posted": [], "toasts": []})
self.assertEqual(result["accepted"], {"question": [question], "posted": ["/api/board/sign", "/api/board/clear-mayday"]})
self.assertTrue((result["done"] or "").startswith("Cancel mayday: done"), result)
@@ -284,7 +286,6 @@ class TestHubRadio(base.OrchestratorE2ECase):
(OUT / "chromium-radio-spot.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
labels = dict(zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True))
mayday = "Send a mayday to all? All agents pause writing steps until you cancel it."
jumps, walked = data["results"][: len(WIDTHS)], data["results"][len(WIDTHS) :]
for jump, (width, _) in zip(jumps, WIDTHS, strict=True):
with self.subTest(width=width, part="radio spot on every tab"):
@@ -297,13 +298,13 @@ class TestHubRadio(base.OrchestratorE2ECase):
self.assertNotIn("error", probe)
self.assertEqual((sent["closed"], sent["open"]), ([True, "false"], [False, "true", True]))
self.assertEqual(sent["inline"], ["static", True, True])
self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"]))
self.assertEqual((sent["heads"], sent["send"], sent["cancel"]), (0, SEND_GROUP, False))
self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], SPEAK_CHANNELS, ["Record"]))
self.assertEqual((sent["heads"], sent["send"], sent["mayday"]), (0, SEND_GROUP, PRESSED))
self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False))
self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS)
self.assertEqual([run["cls"] for run in sent["runs"]], SPEAK_CHANNELS)
for run in sent["runs"]:
direct = run["cls"] in ("post", "call")
self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], ""), run)
self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [], ""), run)
self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: sent"), run)
self.assertEqual(saved["clashes"], [{"found": [], "outside": []}])
self.assertEqual(saved["tones"], ["MAYDAY / PAN-PAN", "Reviews, asks, decisions", "Post and calls to you", "All radio", "Squelch", "speak while CPU < 50 %"])
@@ -314,7 +315,7 @@ class TestHubRadio(base.OrchestratorE2ECase):
self.assertEqual(read, {"squelch": float(squelch), "radio": radio_bell, "post": post, "tall": width == 390, "wide": False})
heads = {"post": ["post", "--to", "Stage"], "call": ["send", "call", "--to", "Stage"], "newsletter": ["post"]}
radio = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO]
sends = [(width, cls) for width, _ in WIDTHS for cls in CHOICE_CHANNELS]
sends = [(width, cls) for width, _ in WIDTHS for cls in SPEAK_CHANNELS]
self.assertEqual([args[:-1] for args in radio], [[*heads.get(cls, ["send", cls]), "--session", "Operator"] for _, cls in sends])
for args, (width, cls) in zip(radio, sends, strict=True):
with self.subTest(width=width, cls=cls):
@@ -337,7 +338,6 @@ class TestHubRadio(base.OrchestratorE2ECase):
(OUT / "firefox-radio-spot.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], [])
labels = dict(zip(CHOICE_CHANNELS, ["Post", "Call", "Newsletter", "Broadcast", "Pan-Pan", "Sécurité", "Mayday"], strict=True))
mayday = "Send a mayday to all? All agents pause writing steps until you cancel it."
question = "Lift the radio silence of the active mayday?"
hint = "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"
results = iter(data["results"])
@@ -348,19 +348,19 @@ class TestHubRadio(base.OrchestratorE2ECase):
with self.subTest(browser="firefox", width=width, part="every class unsigned"):
self.assertNotIn("error", sent, sent)
self.assertEqual((sent["closed"], sent["open"], sent["inline"]), ([True, "false"], [False, "true", True], ["static", True, True]))
self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], CHOICE_CHANNELS, ["Record"]))
self.assertEqual((sent["heads"], sent["send"], sent["cancel"]), (0, SEND_GROUP, False))
self.assertEqual((sent["toolbar"], sent["channels"], sent["record"]), (["Priority", "Day/Night", "Status"], SPEAK_CHANNELS, ["Record"]))
self.assertEqual((sent["heads"], sent["send"], sent["mayday"]), (0, SEND_GROUP, PRESSED))
self.assertEqual((sent["tall"], sent["wide"]), (width == 390, False))
self.assertEqual([run["cls"] for run in sent["runs"]], CHOICE_CHANNELS)
self.assertEqual([run["cls"] for run in sent["runs"]], SPEAK_CHANNELS)
for run in sent["runs"]:
direct = run["cls"] in ("post", "call")
self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [mayday] if run["cls"] == "mayday" else [], f"spot {width} {run['cls']}"), run)
self.assertEqual((run["direct"], run["question"], run["left"]), (direct, [], f"spot {width} {run['cls']}"), run)
self.assertTrue((run["toast"] or "").startswith(f"{labels[run['cls']]} to {'Stage' if direct else 'all'}: not signed"), run)
self.assertIn("NotAllowedError", run["toast"], run)
with self.subTest(browser="firefox", width=width, part="cancel mayday next to PTT unsigned"):
self.assertNotIn("error", cleared, cleared)
self.assertEqual(cleared["toolbar"], ["Priority", "Day/Night", "Drain", "Suspend", "Resume", "Status"])
self.assertEqual((cleared["title"], cleared["shown"]), (hint, "Cancel mayday"))
self.assertEqual((cleared["title"], cleared["shown"], cleared["next"], cleared["after"]), (hint, "Cancel mayday", True, ["Cancel mayday", "true"]))
self.assertEqual(cleared["declined"], {"question": [question], "posted": [], "toasts": []})
self.assertEqual(cleared["accepted"], {"question": [question], "posted": ["/api/board/sign"]})
self.assertTrue((cleared["done"] or "").startswith("Cancel mayday: not signed"), cleared)
+173
View File
@@ -0,0 +1,173 @@
from __future__ import annotations
import html
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
from unittest import mock
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
from hub_support import ASK
from kvb_orchestrator import batches, skill_scripts
COMMAND = "git commit -m 'line comments'"
TITLE = "feat: overlay comments"
DIFF = [{"path": "a.txt", "status": "M", "mode": "100644", "additions": 2, "deletions": 1, "patch": "@@ -1,2 +1,3 @@\n keep\n-old\n+new\n+more", "note": ""}]
FILES = ("src/app.py", "src/view.js")
CAPTURE = """
navigator.credentials.get = @SIGNS@ ? navigator.credentials.get.bind(navigator.credentials) : () => Promise.reject(new DOMException("The operator canceled.", "NotAllowedError"));
const posted = [];
const send = window.fetch.bind(window);
window.fetch = (path, init) => {
if (["/api/sign", "/api/inbox/approve", "/api/messages/sign", "/api/messages"].includes(String(path))) {
const body = JSON.parse(init.body);
posted.push([String(path), body.text || null, (body.items || []).map((entry) => [entry.kind, entry.verb, entry.channel || "", entry.reason || ""])]);
}
return send(path, init);
};
const rightClick = async (cell) => {
const box = cell.getBoundingClientRect();
cell.dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, clientX: box.left + 4, clientY: box.top + 4}));
await sleep(200);
const first = document.querySelector('.ctx-menu:not([hidden]) [role="menuitem"]');
const label = first ? text(first.querySelector(".ctx-label")) : null;
if (first) {
first.click();
}
return label;
};
const listed = (root) => (root ? all(".feedback-list li.line-mark", root).map(text) : null);
"""
STREAM = """(async () => {@HELPERS@@UNLABELLED@@CAPTURE@
const rowOf = () => all("#main .feed > li.k-ask").find((li) => li.textContent.includes(@COMMAND@) && li.querySelector("tr[data-line]"));
if (!(await until(rowOf, 10000))) {
return {error: text(document.getElementById("main"))};
}
const item = await rightClick(all("tr[data-line]", rowOf())[1].querySelector("td.code"));
const field = await until(() => document.querySelector(".sheet-box textarea"), 4000);
if (!field) {
return {error: "no comment sheet", item};
}
const sheet = {title: text(document.querySelector(".sheet-head .panel-title")), range: text(document.querySelector(".sheet-box .who code")), unlabelled: unlabelled(document.querySelector("#sheet .sheet-box"))};
field.value = "stream note";
all(".sheet-box button").find((button) => name(button) === "Save comment").click();
await until(() => rowOf() && rowOf().querySelector("tr.match-mark"), 4000);
const marked = {rows: all("tr.marked", rowOf()).map((row) => row.dataset.line), notes: all("tr.match-mark", rowOf()).map(text), list: listed(rowOf()), open: !document.getElementById("sheet").hidden};
all(".deny-split button", rowOf()).find((button) => name(button) === "Deny").click();
const reason = await until(() => document.querySelector(".sheet-box .deny-reason textarea"), 4000);
const deny = {reason: reason ? reason.value : null, channel: (document.querySelector(".sheet-box .deny-channels input:checked") || {}).value || null, to: (document.querySelector(".sheet-box .deny-recipient select") || {}).value || null};
all(".sheet-box .actions button").find((button) => text(button) === "Deny").click();
await until(() => posted.some(([path]) => path === (@SIGNS@ ? "/api/inbox/approve" : "/api/sign")), 8000);
await sleep(1200);
return {item, sheet, marked, deny, posted, kept: listed(rowOf()), wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
OVERLAY = """(async () => {@HELPERS@@UNLABELLED@@CAPTURE@
const row = () => document.querySelector('#main .inbox-list > li[data-ref="@REVIEW@"]');
if (!(await until(row, 8000))) {
return {error: text(document.getElementById("main"))};
}
row().querySelector(".headline").click();
const lines = () => all("#sheet .review-file[data-path='src/app.py'] tr[data-line]");
if (!(await until(() => lines().length, 8000))) {
return {error: text(document.getElementById("sheet"))};
}
const target = lines()[2];
const item = await rightClick(target.querySelector("td.code"));
const field = await until(() => document.querySelector("#sheet tr.match-comment textarea"), 4000);
if (!field) {
return {error: "no inline comment field", item};
}
const inline = {after: field.closest("tr").previousElementSibling === target, unlabelled: unlabelled(field.closest("tr"))};
field.value = "overlay note";
all("#sheet tr.match-comment button").find((button) => name(button) === "Save comment").click();
await until(() => document.querySelector("#sheet tr.match-mark"), 4000);
const marked = {rows: all("#sheet tr.marked").map((tr) => tr.dataset.line), notes: all("#sheet tr.match-mark").map(text), list: all("#sheet .review-notes li.line-mark").map(text), field: Boolean(document.querySelector("#sheet tr.match-comment")), open: !document.getElementById("sheet").hidden};
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "Escape", bubbles: true}));
await until(() => document.getElementById("sheet").hidden, 4000);
const card = listed(row());
row().querySelector(".item-actions button.primary").click();
await until(() => posted.some(([path]) => path === (@SIGNS@ ? "/api/messages" : "/api/sign")), 10000);
await sleep(1200);
return {item, inline, marked, card, posted, kept: listed(row()), wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
def review_page() -> str:
sections = []
for path in FILES:
rows = "".join(f'<tr class="add"><td class="num"></td><td class="num">{line}</td><td class="sign">+</td><td class="code">{html.escape(path)} line {line}</td></tr>' for line in range(1, 6))
sections.append(f'<details class="file" data-path="{path}"><summary><span class="badge added" title="added">A</span><span class="path">{path}</span>'
f'<span class="stat"><span class="add">+5</span><span class="del">&minus;0</span></span></summary><table class="diff"><tbody>{rows}</tbody></table></details>')
return f'<!DOCTYPE html><html><body><section class="group" id="staged" data-files="2">{"".join(sections)}</section></body></html>'
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestLineComments(base.OrchestratorE2ECase):
def setUp(self):
super().setUp()
self.ask = self.create_ask({**ASK, "command": COMMAND, "timeout": 3600, "diff": DIFF})
arguments = {**self.arguments(TITLE, "", self.page("overlay.html", review_page())), "worktree": "/repo/.worktrees/feature/overlay", "branch": "feature/overlay", "agent": "Skills session"}
result = self.tool("review_request", arguments)
self.assertFalse(result["isError"], result)
self.review = result["structuredContent"]["id"]
def probe(self, template: str, signs: bool) -> str:
values = {"@HELPERS@": base.HELPERS, "@UNLABELLED@": base.UNLABELLED, "@CAPTURE@": CAPTURE, "@SIGNS@": "true" if signs else "false", "@COMMAND@": json.dumps(COMMAND), "@REVIEW@": f"review:{self.review}"}
for key, value in values.items():
template = template.replace(key, value)
return template
def steps(self, browser: str, signs: bool) -> list[dict]:
local = f"http://localhost:{self.port}/"
return [
{"width": 1366, "height": 768, "url": f"{local}?stream#stream", "wait": 1500, "probe": self.probe(STREAM, signs), "shot": self.shot(f"{browser}-1366-line-comments-stream")},
{"width": 1366, "height": 768, "url": f"{local}?overlay#stream/inbox", "wait": 1200, "probe": self.probe(OVERLAY, signs), "shot": self.shot(f"{browser}-1366-line-comments-overlay")},
]
def check(self, data: dict, signs: bool) -> None:
self.assertEqual([error for error in data["errors"] if "(style-src-elem)" not in error and "/favicon.ico" not in error], [])
stream, overlay = data["results"]
self.assertNotIn("error", stream, stream)
self.assertEqual((stream["item"], stream["sheet"]), ("Comment", {"title": "Comment", "range": "a.txt:2", "unlabelled": []}))
self.assertEqual(stream["marked"], {"rows": ["2", "2"], "notes": ["stream note"], "list": ["a.txt:2stream note"], "open": False})
self.assertEqual(stream["deny"], {"reason": "a.txt:2: stream note", "channel": "call", "to": "Skills session"})
denial = [["ask", "reject", "call", "a.txt:2: stream note"]]
self.assertEqual(stream["posted"], [["/api/sign", None, denial], *([["/api/inbox/approve", None, denial]] if signs else [])])
self.assertNotIn("error", overlay, overlay)
self.assertEqual((overlay["item"], overlay["inline"]), ("Comment", {"after": True, "unlabelled": []}))
self.assertEqual(overlay["marked"], {"rows": ["3"], "notes": ["overlay note"], "list": ["src/app.py:3overlay note"], "field": False, "open": True})
self.assertEqual(overlay["card"], ["src/app.py:3overlay note"])
grant = [["review", "approve", "", ""]]
notes = f"Granted: {TITLE}. Notes:\nsrc/app.py:3: overlay note"
self.assertEqual(overlay["posted"], [["/api/sign", None, grant], ["/api/inbox/approve", None, grant], ["/api/messages/sign", notes, []], ["/api/messages", notes, []]] if signs else [["/api/sign", None, grant]])
if not signs:
self.assertEqual((stream["kept"], overlay["kept"]), (["a.txt:2stream note"], ["src/app.py:3overlay note"]))
self.assertFalse(stream["wide"] or overlay["wide"])
def test_chromium_line_comments_reach_the_requester_in_the_deny_call_and_after_the_grant_as_one_post(self):
with mock.patch.object(batches, "UNDO", 0.3):
data = self.drive(self.steps("chromium", True), self.authenticator())
self.settle(lambda: self.status(self.review) == "approved" and any(ask["status"] == "denied" for ask in self.httpd.hub.asks.listed() if ask["command"] == COMMAND))
(base.OUT / "chromium-line-comments.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data, True)
asks = [(ask["status"], ask.get("channel", ""), ask.get("reason", "")) for ask in self.httpd.hub.asks.listed() if ask["command"] == COMMAND]
self.assertEqual(asks, [("denied", "call", "a.txt:2: stream note")])
radio = [" ".join(args) for script, args in self.scripts.calls if script == skill_scripts.RADIO]
self.assertEqual(len([entry for entry in radio if entry.startswith("send post --to Skills session ") and f"Granted: {TITLE}. Notes:" in entry and "src/app.py:3: overlay note" in entry]), 1, radio)
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
def test_firefox_keeps_line_comments_when_the_deny_and_the_grant_go_unsigned(self):
data = self.drive(self.steps("firefox", False), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
(base.OUT / "firefox-line-comments.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data, False)
self.assertEqual(self.status(self.review), "pending")
if __name__ == "__main__":
unittest.main()
+124
View File
@@ -0,0 +1,124 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
import test_home_bookmarks_e2e as bm
import test_home_dashboard_e2e as dash
import test_match_review_e2e as matched
import test_workbench_w4_e2e as w4
from hub_case import HubCase
from test_hub_match import git, merge_repo
OUT = Path(os.environ.get("E2E_OUT", "/tmp/match-content-shots"))
SCAN = """
const stray = (root) => {
const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
const found = [];
for (let node = walker.nextNode(); node; node = walker.nextNode()) {
if (["null", "undefined"].includes(node.nodeValue.trim())) {
found.push(node.parentElement ? node.parentElement.className || node.parentElement.tagName : "-");
}
}
return found;
};
"""
MERGE = """(async () => {@HELPERS@@CARD@@SCAN@
await screenShown(8000);
await until(card, 8000);
const shown = await pick("@MERGE@");
await sleep(400);
const files = shown ? all(".match-file", shown).map((file) => file.dataset.path) : null;
const added = shown ? all(".match-file tr", shown).some((row) => text(row).includes("added = 2")) : false;
const visited = [];
for (const tab of all("#main .match-peek")) {
tab.click();
await sleep(250);
visited.push(stray(document.getElementById("main")));
}
return {files, added, none: text(shown && shown.querySelector(".match-body > p.muted")), stray: stray(document.getElementById("main")), visited: visited.flat(),
reasons: all("#main .match-reason").filter((node) => ["", "-"].includes(text(node).trim())).length, wide: document.documentElement.scrollWidth > innerWidth + 1};
})()"""
SEED = """(async () => {@HELPERS@
await ViewStore.update("home.pins", () => [{kind: "panel", id: "tasks/match", w: innerWidth > 640 ? 6 : 4, h: 6}]);
return true;
})()"""
TILE = """(async () => {@HELPERS@@HOME@@SCAN@
await go("home");
const pinned = await until(() => tile("panel:tasks/match")?.querySelector(".match-card"), 8000);
await sleep(600);
return {found: Boolean(pinned), stray: stray(document.getElementById("main"))};
})()"""
def probe(template: str, **names: str) -> str:
fills = {"@HELPERS@": base.HELPERS, "@HOME@": dash.HOME, "@CARD@": matched.CARD, "@SCAN@": SCAN}
fills.update({f"@{key.upper()}@": value for key, value in names.items()})
for key, value in fills.items():
template = template.replace(key, value)
return template
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestMatchContent(HubCase):
drive = base.OrchestratorE2ECase.drive
cards = matched.TestMatchReview.cards
review = matched.TestMatchReview.review
payload = matched.TestMatchReview.payload
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.cards()
repo, target = merge_repo(self.work)
git(repo, "merge", "--no-commit", "--no-ff", "-q", target)
arguments = {**self.arguments("Merge feature into main", "", self.page("merge.html", "<!doctype html><title>m</title>")), "repo": str(repo / ".git"), "worktree": str(repo), "branch": "main", "tree": git(repo, "write-tree").strip()}
self.merge = self.tool("review_request", arguments)["structuredContent"]["id"]
self.run_runner(register=False)
def steps(self, browser: str) -> list[dict]:
steps = []
for width, height in base.WIDTHS:
at = {"width": width, "height": height}
shot = OUT / f"{browser}-{width}"
steps += [
{**at, "url": f"{self.base}?{width}-merge#tasks/match", "wait": 1500, "probe": probe(MERGE, merge=f"review:{self.merge}"), "shot": f"{shot}-merge-diff.png"},
{**at, "url": f"{self.base}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
{**at, "url": f"{self.base}?{width}-seed#stream", "wait": 800, "probe": probe(SEED), "shot": None},
{**at, "url": f"{self.base}?{width}-home#home", "wait": 1500, "probe": probe(TILE), "shot": f"{shot}-home-match.png"},
]
return steps
def check(self, data: dict, browser: str) -> None:
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
merge, _, _, tile = (next(results) for _ in range(4))
with self.subTest(browser=browser, width=width, step="merge"):
self.assertEqual((merge["files"], merge["added"], merge["none"]), (["app.py"], True, None), merge)
self.assertEqual((merge["stray"], merge["visited"], merge["reasons"], merge["wide"]), ([], [], 0, False), merge)
with self.subTest(browser=browser, width=width, step="tile"):
self.assertEqual((tile["found"], tile["stray"]), (True, []), tile)
def test_chromium_shows_the_merge_diff_and_no_stray_text(self):
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
(OUT / "chromium-match-content.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data, "chromium")
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
def test_firefox_shows_the_merge_diff_and_no_stray_text(self):
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
(OUT / "firefox-match-content.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data, "firefox")
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -158,7 +158,7 @@ class TestMatchWaiting(HubCase):
self.assertEqual(sorted(seen), sorted([PICK, ask, choice, rule]), found)
self.assertEqual({card_id: entry["kind"] for card_id, entry in seen.items()}, {PICK: "decision", ask: "ask", choice: "decision", rule: "rule"})
self.assertEqual(seen[ask]["chips"], ["fix=95 %", "break=2 %", "score=93", "value=1:4"], found)
self.assertEqual((seen[ask]["command"], seen[ask]["options"]), (SCORED, ["Yes", "No"]), found)
self.assertEqual((seen[ask]["command"], seen[ask]["options"]), (SCORED, []), found)
self.assertEqual((seen[PICK]["options"], seen[PICK]["acts"]["Accept"], seen[PICK]["acts"]["Reject"]), (["Merge now", "Wait"], False, False), found)
self.assertEqual((seen[choice]["acts"]["Accept"], seen[choice]["acts"]["Reject"], seen[choice]["refused"]), (True, True, True), found)
self.assertEqual((seen[rule]["rule"], seen[rule]["sheet"], seen[rule]["stayed"]), (True, True, True), found)
+128
View File
@@ -0,0 +1,128 @@
from __future__ import annotations
import json
import os
import re
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
import hub_support
from hub_case import HubCase
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-031-shots"))
TEMPLATES = hub_support.HUB / "templates"
SCAN = """
const shown = (node) => Boolean(node && node.getClientRects().length);
const scan = () => all("button.mic").filter(shown).map((button) => {
const field = document.getElementById(button.getAttribute("aria-controls"));
const frame = button.closest(".mic-frame");
if (!field || !frame || field.parentElement !== frame) {
return {id: button.getAttribute("aria-controls"), framed: false};
}
const line = frame.classList.contains("mic-line");
const [outer, mic, text] = [frame.getBoundingClientRect(), button.getBoundingClientRect(), field.getBoundingClientRect()];
const foot = line ? null : frame.querySelector(":scope > .mic-foot");
return {
id: field.id, framed: true, line,
last: line ? frame.lastElementChild === button : Boolean(foot) && foot.lastElementChild === button && field.nextElementSibling === foot,
fits: line ? Math.abs(mic.top - outer.top - 1) <= 1 && Math.abs(outer.bottom - 1 - mic.bottom) <= 1 && Math.abs(outer.right - 1 - mic.right) <= 1 : mic.bottom <= outer.bottom && mic.top >= text.bottom - 1,
divider: line ? getComputedStyle(button).borderLeftWidth : getComputedStyle(foot).borderTopWidth,
clear: line ? text.right <= mic.left + 0.5 : true,
};
});
const ring = (field) => {
field.focus();
const frame = field.closest(".mic-frame");
return [getComputedStyle(frame).outlineStyle, getComputedStyle(field).outlineStyle];
};
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
"""
STREAM = """(async () => {@HELPERS@@SCAN@
const field = await until(() => document.querySelector('#main input[type="search"]'), 15000);
await until(() => field.closest(".mic-frame"), 4000);
return {mics: scan(), ring: ring(field), wide: wide()};
})()"""
RULES = """(async () => {@HELPERS@@SCAN@
(await until(() => document.getElementById("controls-tab-rules"), 15000)).click();
await until(() => document.querySelector("#main .rule-form .mic-frame"), 4000);
return {mics: scan(), wide: wide()};
})()"""
RADIO = """(async () => {@HELPERS@@SCAN@
const area = await until(() => document.querySelector("#radio-spot form.composer textarea"), 15000);
await until(() => area.closest(".mic-frame"), 4000);
const foot = area.closest(".mic-frame").querySelector(".mic-foot");
const first = foot.firstElementChild;
const idle = getComputedStyle(foot.lastElementChild).backgroundColor;
foot.lastElementChild.setAttribute("aria-pressed", "true");
const recording = getComputedStyle(foot.lastElementChild).backgroundColor;
foot.lastElementChild.setAttribute("aria-pressed", "false");
area.style.height = "260px";
await sleep(100);
const after = scan().find((entry) => entry.id === area.id);
return {mics: scan(), record: first.textContent.trim() || first.getAttribute("aria-label"), looks: idle !== recording, resized: after, ring: ring(area), wide: wide()};
})()"""
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@SCAN@", SCAN)
class TestMicSource(unittest.TestCase):
def test_no_page_module_but_the_mic_helper_inserts_a_mic_button(self):
callers = [path.name for path in TEMPLATES.glob("*.js") if path.name != "page-mic.js" and re.search(r"micButton\(", path.read_text(encoding="utf-8"))]
self.assertEqual(callers, [])
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestMicFrames(HubCase):
drive = base.OrchestratorE2ECase.drive
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.claim("s1", "Skills")
self.snapshot()
self.page_url = f"http://localhost:{self.port}/"
def check_mics(self, mics: list[dict]) -> None:
self.assertTrue(mics)
for entry in mics:
with self.subTest(field=entry["id"]):
self.assertTrue(entry["framed"], entry)
self.assertEqual((entry["last"], entry["fits"], entry["divider"], entry["clear"]), (True, True, "1px", True), entry)
def test_chromium_joins_every_mic_into_its_field_frame_at_three_widths(self):
steps = []
for width, height in base.WIDTHS:
shot = OUT / f"chromium-{width}"
steps += [
{"width": width, "height": height, "url": f"{self.page_url}?{width}#stream", "wait": 1200, "probe": probe(STREAM), "shot": f"{shot}-stream.png"},
{"width": width, "height": height, "url": f"{self.page_url}?{width}-rules#stream/rules", "wait": 1200, "probe": probe(RULES), "shot": f"{shot}-rules.png"},
{"width": width, "height": height, "url": f"{self.page_url}?{width}-radio#stream/radio", "wait": 1200, "probe": probe(RADIO), "shot": f"{shot}-radio.png"},
]
data = self.drive(steps, None)
(OUT / "chromium-mic-frames.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
stream, rules, radio = next(results), next(results), next(results)
with self.subTest(width=width):
for found in (stream, rules, radio):
self.assertNotIn("error", found, found)
self.check_mics(found["mics"])
self.assertFalse(found["wide"])
self.assertEqual(stream["ring"], ["solid", "none"])
self.assertEqual(radio["ring"], ["solid", "none"])
self.assertEqual(radio["record"], "Record")
self.assertTrue(radio["looks"])
self.assertEqual((radio["resized"]["last"], radio["resized"]["fits"]), (True, True), radio["resized"])
if __name__ == "__main__":
unittest.main()
+1 -1
View File
@@ -164,7 +164,7 @@ class TestOrchestratorE2E(base.OrchestratorE2ECase):
self.assertRegex(by_hash[f"#{tab}/3d"]["note"], r"^\d+ nodes · \d+ edges · Force$")
agents = by_hash["#agents/orbit"]
self.assertEqual(agents["toolbar"], ["Priority", "Day/Night", "Status"])
self.assertEqual(agents["spot"], {"hidden": True, "channels": CHOICE_CHANNELS})
self.assertEqual(agents["spot"], {"hidden": True, "channels": [channel for channel in CHOICE_CHANNELS if channel != "mayday"]})
hierarchy = by_hash["#agents/hierarchy"]
self.assertEqual([office for office, _ in hierarchy["org"]], ["chair", "identity/oidc", "work/s1", "work/s2"])
self.assertEqual(hierarchy["toggles"], [["Collapse: Operator", "true"], ["Collapse: Chair", "true"], ["Collapse: identity", "true"], ["Collapse: Presidents", "true"]])
+1 -1
View File
@@ -115,7 +115,7 @@ class TestRadioLayout(kit.RadioLayoutCase):
self.assertTrue(found["inside"], home[moment])
self.assertTrue(found["filled"], home[moment])
self.assertEqual(home["tools"]["menu"], ["true", True, True], home)
self.assertEqual(home["tools"]["cancel"], [True, "Cancel mayday: lift the radio silence so the agents write again; your passkey signs it"], home)
self.assertEqual(home["tools"]["cancel"], ["false", "MAYDAY: send the message as mayday to all; all agents pause writing steps until you cancel it"], home)
content = home["content"]
self.assertEqual(content["tiles"], [f"panel:{part}" for part in PARTS], home)
self.assertEqual(content["radio"], [True, True, True], home)
+1 -1
View File
@@ -152,7 +152,7 @@ class TestRadioSet(HubCase):
self.assertTrue(label["whole"] or width == 390, label)
self.assertEqual(face["bells"], [["MAYDAY / PAN-PAN tone", "speak"], ["Reviews, asks, decisions tone", "tone"], ["Post and calls to you tone", "tone"], ["All radio tone", "off"]])
self.assertEqual((face["caret"], list(face["groups"]), face["menuFits"]), (["auto"], ["Fallback"], {"page": True, "panel": True}))
self.assertEqual(face["send"], ["More send options", True])
self.assertEqual(face["send"], ["More send options", "false"])
self.assertEqual(face["stationsHead"], "Internet radio")
self.assertEqual(face["ptt"][0], "PTT")
self.assertEqual([section for section in face["sections"] if section in ("Internet radio", "Tones", "Read radio aloud", "Radio")], [])
+156
View File
@@ -0,0 +1,156 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
import test_resources_view_e2e as res
import test_workbench_w4_e2e as w4
from hub_case import HubCase
from kvb_orchestrator import accounts
from kvb_orchestrator.viewstore import VIEW
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-028-shots"))
EMAIL = "one@example.org"
KIT = """
const box = () => document.querySelector("#main .res-accounts");
const rows = () => all("#main .res-accounts tbody tr").map((row) => [row.dataset.account === "" ? "" : "account", all("td", row).map((cell) => text(cell))]);
const sheet = () => document.getElementById("sheet");
const field = (label) => sheet().querySelector(`[aria-label="${label}"]`);
const button = (root, label) => all("button", root).find((node) => name(node) === label || text(node) === label);
const wide = () => ({wide: document.documentElement.scrollWidth > innerWidth + 1});
"""
ADD = """(async () => {@HELPERS@@READ@@KIT@
if (!(await until(() => box() && rows().length === 1, 15000))) {
return {error: text(box()) || text(document.getElementById("main"))};
}
const before = rows();
button(box(), "Add account").click();
await until(() => !sheet().hidden && field("Provider"), 4000);
field("Provider").value = "Anthropic";
field("Email").value = "@EMAIL@";
field("Renewal weekday").value = "1";
field("Renewal time").value = "09:00";
field("Weekly reset weekday").value = "4";
field("Weekly reset time").value = "18:30";
field("Autorenew").checked = true;
field("Weekly token limit").value = "1000";
button(sheet(), "Save").click();
const added = Boolean(await until(() => sheet().hidden && rows().length === 2, 5000));
const afterAdd = rows();
button(box(), "Edit @EMAIL@").click();
await until(() => !sheet().hidden && field("Weekly token limit"), 4000);
const prefilled = [field("Provider").value, field("Email").value, field("Weekly token limit").value, field("Autorenew").checked];
field("Weekly token limit").value = "";
button(sheet(), "Save").click();
const edited = Boolean(await until(() => sheet().hidden && rows()[0] && rows()[0][1][9] === "–", 5000));
const afterEdit = rows();
await pickPanel("accounts", false);
const off = {panels: panelsShown(), picks: picks()};
await pickPanel("accounts", true);
await until(() => rows().length === 2, 4000);
const on = {panels: panelsShown(), picks: picks()};
return {before, added, afterAdd, prefilled, edited, afterEdit, off, on, page: wide(), violations: window.e2eViolations || null};
})()"""
REMOVE = """(async () => {@HELPERS@@READ@@KIT@
button(box(), "Edit @EMAIL@").click();
await until(() => !sheet().hidden && button(sheet(), "Remove"), 4000);
button(sheet(), "Remove").click();
const removed = Boolean(await until(() => sheet().hidden && rows().length === 1, 5000));
return {removed, after: rows(), page: wide(), violations: window.e2eViolations || null};
})()"""
def probe(template: str) -> str:
names = {"@HELPERS@": base.HELPERS, "@READ@": res.READ, "@KIT@": KIT, "@EMAIL@": EMAIL}
for key, value in names.items():
template = template.replace(key, value)
return template
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestResourcesAccounts(HubCase):
drive = base.OrchestratorE2ECase.drive
sample = w4.TestWorkbenchResources.sample
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
now = int(time.time())
self.start = now - now % 60 - w4.ROWS * 60
folder = self.kept / "resources"
folder.mkdir()
(folder / "samples.jsonl").write_text(self.jsonl([self.sample(index) for index in range(w4.ROWS)]), encoding="utf-8")
tokens = [
{"t": now - 60, "agent": "Skills", "model": "claude-opus-5-5", "input": 40, "output": 2, "cache_read": 0, "cache_write": 0, "account": EMAIL},
{"t": now - 60, "agent": "Stage", "model": "claude-haiku-4-5", "input": 3, "output": 0, "cache_read": 0, "cache_write": 0},
]
(folder / "tokens.jsonl").write_text(self.jsonl(tokens), encoding="utf-8")
self.council.mkdir(parents=True, exist_ok=True)
(self.council / accounts.SESSION_ACCOUNTS).write_text(json.dumps({"session": "s1", "email": EMAIL}) + "\n", encoding="utf-8")
self.base = f"http://{self.host}/"
def steps(self, browser: str) -> list[dict]:
steps = []
for width, height in base.WIDTHS:
shot = OUT / f"{browser}-{width}"
steps += [
{"width": width, "height": height, "url": f"{self.base}?{width}#resources", "wait": 1200, "probe": probe(ADD), "shot": f"{shot}-accounts.png"},
{"width": width, "height": height, "url": None, "wait": 0, "probe": probe(REMOVE), "shot": f"{shot}-accounts-removed.png"},
]
return steps
def check(self, data: dict, browser: str) -> None:
results = iter(data["results"])
shown = [["resources-hardware", False], ["resources-tokens", False], ["resources-combined", True]]
for width, _ in base.WIDTHS:
add, remove = next(results), next(results)
with self.subTest(browser=browser, width=width):
self.assertNotIn("error", add, add)
self.assertEqual([(kind, cells[-3]) for kind, cells in add["before"]], [("", "45")])
self.assertTrue(add["added"], add)
(kind, cells), (rest, other) = add["afterAdd"]
self.assertEqual((kind, rest), ("account", ""))
self.assertEqual(cells[0], "Anthropic")
self.assertTrue(cells[1].startswith(EMAIL) and cells[1].endswith("active"), cells[1])
self.assertEqual((cells[2], cells[5], cells[6], cells[7], cells[8], cells[9]), ("Mon 09:00", "yes", "42", "42", "42", "958"))
self.assertEqual(other[-3], "3")
self.assertEqual(add["prefilled"], ["Anthropic", EMAIL, "1000", True])
self.assertTrue(add["edited"], add)
self.assertEqual(add["afterEdit"][0][1][9], "–")
self.assertEqual(add["off"]["panels"], [*shown, ["resources-accounts", True]])
self.assertEqual(add["off"]["picks"][-1], ["accounts", False, False])
self.assertEqual(add["on"]["panels"], [*shown, ["resources-accounts", False]])
self.assertEqual(add["page"], {"wide": False})
self.assertEqual(w4.quiet(add["violations"]), [])
self.assertTrue(remove["removed"], remove)
self.assertEqual([(kind, cells[-3]) for kind, cells in remove["after"]], [("", "45")])
self.assertEqual(remove["page"], {"wide": False})
self.assertEqual(w4.quiet(remove["violations"]), [])
self.assertEqual(self.httpd.hub.view_store.get(), VIEW)
self.assertEqual(self.httpd.hub.accounts.ledger.listed(), [])
def test_chromium_adds_edits_and_removes_an_account_and_picks_the_panel_at_three_widths(self):
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
(OUT / "chromium-resources-accounts.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
self.check(data, "chromium")
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
def test_firefox_adds_edits_and_removes_an_account_and_picks_the_panel_at_three_widths(self):
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
(OUT / "firefox-resources-accounts.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
self.check(data, "firefox")
if __name__ == "__main__":
unittest.main()
+24 -8
View File
@@ -44,14 +44,26 @@ READ = """
}
return null;
};
const legendFits = () => all("#main .res-panel:not([hidden])").every((panel) => panel.querySelector(".res-plot").getBoundingClientRect().height > 40);
const legendFits = () => all("#main .res-panel:not([hidden]) .res-plot").every((plot) => plot.getBoundingClientRect().height > 40);
const panelsShown = () => all("#main .res-panel").map((panel) => [panel.dataset.panel, panel.hidden]);
const picks = () => all("#main input[data-pick]").map((box) => [box.dataset.pick, box.checked, box.disabled]);
const pickPanel = async (kind, on) => {
const menu = document.querySelector("#main .res-panels-menu");
menu.open = true;
const box = menu.querySelector(`input[data-pick="${kind}"]`);
if (box.checked !== on) {
box.click();
}
await sleep(200);
menu.open = false;
};
const page = () => ({tall: document.documentElement.scrollHeight > innerHeight, wide: document.documentElement.scrollWidth > innerWidth + 1, fits: legendFits()});
"""
TOGGLE = """(async () => {@HELPERS@@READ@
if (!(await until(() => charts().length === 2 && chip("@CPU@") && chip("@STAGE@") && agents().length === 2, 15000))) {
return {error: text(document.getElementById("main")), charts: charts()};
}
const before = {charts: charts(), lines: lines(), agents: agents(), pressed: pressed(), panels: all("#main .res-panel").map((panel) => [panel.dataset.panel, panel.hidden])};
const before = {charts: charts(), lines: lines(), agents: agents(), pressed: pressed(), panels: panelsShown(), picks: picks()};
chip("@CPU@").click();
await until(() => chip("@STAGE@") && !lines().includes("@CPU@"), 4000);
chip("@STAGE@").click();
@@ -67,9 +79,11 @@ COMBINE = """(async () => {@HELPERS@@READ@
switched("tokens").click();
const accumulated = Boolean(await until(() => sums().length === 1 && !agents().length, 4000));
const sumsAt = {sums: sums(), rising: rising(), pressed: switched("tokens").getAttribute("aria-pressed")};
switched("combined").click();
await pickPanel("combined", true);
await pickPanel("hardware", false);
await pickPanel("tokens", false);
const combinedOn = Boolean(await until(() => charts().join() === "combined" && burn().length === 2, 4000));
const combined = {charts: charts(), lines: lines(), sums: sums(), burn: burn(), right: all('#main text[data-axis="right"]').length, pressed: pressed(), panels: all("#main .res-panel").map((panel) => [panel.dataset.panel, panel.hidden]), switch: switched("combined").getAttribute("aria-pressed")};
const combined = {charts: charts(), lines: lines(), sums: sums(), burn: burn(), right: all('#main text[data-axis="right"]').length, pressed: pressed(), panels: panelsShown(), picks: picks()};
return {kept, accumulated, sumsAt, combinedOn, combined, page: page(), violations: window.e2eViolations || null};
})()"""
DESELECT = """(async () => {@HELPERS@@READ@
@@ -135,7 +149,8 @@ class TestResourcesView(HubCase):
self.assertNotIn("error", toggle, toggle)
before = toggle["before"]
self.assertEqual(before["charts"], ["hardware", "tokens"])
self.assertEqual(before["panels"], [["resources-hardware", False], ["resources-tokens", False], ["resources-combined", True]])
self.assertEqual(before["panels"], [["resources-hardware", False], ["resources-tokens", False], ["resources-combined", True], ["resources-accounts", False]])
self.assertEqual(before["picks"], [["hardware", True, False], ["tokens", True, False], ["combined", False, False], ["accounts", True, False]])
self.assertEqual((before["lines"], before["agents"]), (hardware, ["Skills", "Stage"]))
self.assertEqual(set(before["pressed"].values()), {"true"})
self.assertEqual(set(before["pressed"]), {*hardware, "agent:Skills", STAGE})
@@ -153,15 +168,16 @@ class TestResourcesView(HubCase):
self.assertTrue(combine["combinedOn"], combine)
combined = combine["combined"]
self.assertEqual((combined["charts"], combined["lines"], combined["sums"], combined["burn"]), (["combined"], hardware, ["Skills", "Stage"], ["done", "scope"]))
self.assertEqual((combined["right"], combined["switch"]), (2, "true"))
self.assertEqual(combined["panels"], [["resources-hardware", True], ["resources-tokens", True], ["resources-combined", False]])
self.assertEqual(combined["right"], 2)
self.assertEqual(combined["panels"], [["resources-hardware", True], ["resources-tokens", True], ["resources-combined", False], ["resources-accounts", False]])
self.assertEqual(combined["picks"], [["hardware", False, False], ["tokens", False, False], ["combined", True, False], ["accounts", True, False]])
self.assertEqual(set(combined["pressed"].values()), {"true"})
self.assertEqual(set(combined["pressed"]), {*hardware, "agent:Skills", STAGE, "burn:done", SCOPE})
self.assertEqual(combine["page"], {"tall": False, "wide": False, "fits": True})
self.assertEqual(w4.quiet(combine["violations"]), [])
self.assertTrue(deselect["deselected"], deselect)
self.assertEqual((deselect["burn"], deselect["lines"]), (["done"], [line for line in hardware if line != UTIL]))
self.assertEqual(deselect["saved"], {"hidden": [CPU, STAGE], "tokens": "accumulated", "combined": True, "combinedHidden": [SCOPE, UTIL]})
self.assertEqual(deselect["saved"], {"hidden": [CPU, STAGE], "tokens": "accumulated", "panels": ["accounts", "combined"], "combinedHidden": [SCOPE, UTIL]})
self.assertEqual(deselect["reset"], 200)
self.assertEqual(w4.quiet(deselect["violations"]), [])
self.assertEqual(self.httpd.hub.view_store.get(), VIEW)
+147
View File
@@ -0,0 +1,147 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
import test_match_review_e2e as matched
import test_workbench_w4_e2e as w4
from hub_case import HubCase
from kvb_orchestrator.skillindex import SKILLS_INDEX
OUT = Path(os.environ.get("E2E_OUT", "/tmp/slash-skills-shots"))
SKILLS = [
{"name": "kvb-org-radio", "description": "Default channel to other agents", "source": "~/.claude/skills"},
{"name": "kvb-org-rasci", "description": "Register of tasks", "source": "~/.claude/skills"},
{"name": "kvb-org-robot", "description": "Work autonomously", "source": "~/.agents/skills"},
{"name": "i8-alpha", "description": "Global one", "source": "~/.claude/skills"},
{"name": "i8-zeta", "description": "Core one", "source": "/repo"},
]
KIT = """
const shown = () => all(".slash-list .slash-option strong").map(text);
const type = async (field, value) => {
field.focus();
field.value = value;
field.setSelectionRange(value.length, value.length);
field.dispatchEvent(new Event("input", {bubbles: true}));
await until(() => shown().length, 2500);
await sleep(150);
return shown();
};
const key = (field, name) => field.dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true, cancelable: true}));
const flow = async (field, prefix) => {
const listed = await type(field, `/${prefix}`);
const box = document.querySelector(".slash-list");
const inside = box ? box.getBoundingClientRect().right <= innerWidth + 1 && box.getBoundingClientRect().left >= -1 : null;
key(field, "Enter");
await sleep(150);
const picked = field.value;
const word = await type(field, "a/b");
const kept = await type(field, "keep /kvb");
key(field, "Escape");
await sleep(150);
return {listed, inside, picked, word, kept: kept.length > 0, closed: !document.querySelector(".slash-list"), text: field.value};
};
"""
COMPOSER = """(async () => {@HELPERS@@KIT@
await screenShown(8000);
const field = await until(() => document.querySelector("#radio-spot:not([hidden]) .radio-speak textarea[data-skills]"), 8000);
if (!field) {
return {error: text(document.getElementById("main"))};
}
return flow(field, "kvb-org-r");
})()"""
FEEDBACK = """(async () => {@HELPERS@@KIT@
await screenShown(8000);
const reject = await until(() => document.querySelector("#main .match-actions .match-reject:not([disabled])"), 8000);
if (!reject) {
return {error: text(document.getElementById("main"))};
}
reject.click();
const field = await until(() => document.querySelector("#sheet:not([hidden]) textarea.match-feedback[data-skills]"), 4000);
if (!field) {
return {error: "no feedback field"};
}
const core = await type(field, "/i8-");
const result = {repo: field.dataset.skills, core, ...(await flow(field, "kvb-org-r"))};
key(field, "Escape");
await until(() => document.getElementById("sheet").hidden, 3000);
return result;
})()"""
INJECTED = """(async () => {@HELPERS@@KIT@
const field = document.createElement("textarea");
field.dataset.skills = "";
document.getElementById("main").append(field);
await sleep(200);
const result = await flow(field, "kvb-org-r");
field.remove();
return result;
})()"""
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@KIT@", KIT)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestSlashSkills(HubCase):
drive = base.OrchestratorE2ECase.drive
cards = matched.TestMatchReview.cards
review = matched.TestMatchReview.review
payload = matched.TestMatchReview.payload
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
self.cards()
self.tree_file.with_name(SKILLS_INDEX).write_text(json.dumps({"written": 1, "skills": SKILLS}), encoding="utf-8")
def steps(self, browser: str) -> list[dict]:
steps = []
for width, height in base.WIDTHS:
at = {"width": width, "height": height}
shot = OUT / f"{browser}-{width}"
steps += [
{**at, "url": f"{self.base}?{width}-composer#stream/radio", "wait": 1200, "probe": probe(COMPOSER), "shot": f"{shot}-composer.png"},
{**at, "url": f"{self.base}?{width}-feedback#tasks/match", "wait": 1500, "probe": probe(FEEDBACK), "shot": f"{shot}-feedback.png"},
{**at, "url": None, "wait": 0, "probe": probe(INJECTED), "shot": None},
]
return steps
def check_flow(self, found: dict) -> None:
self.assertNotIn("error", found, found)
self.assertEqual(found["listed"][0], "/kvb-org-radio", found)
self.assertEqual((found["inside"], found["picked"], found["word"], found["kept"], found["closed"], found["text"]), (True, "/kvb-org-radio ", [], True, True, "keep /kvb"), found)
def check(self, data: dict, browser: str) -> None:
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
for field in ("composer", "feedback", "injected"):
found = next(results)
with self.subTest(browser=browser, width=width, field=field):
self.check_flow(found)
if field == "feedback":
self.assertEqual((found["repo"], found["core"]), ("/repo", ["/i8-zeta", "/i8-alpha"]), found)
def test_chromium_suggests_skills_after_a_slash_in_every_agent_field(self):
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
(OUT / "chromium-slash.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data, "chromium")
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
def test_firefox_suggests_skills_after_a_slash_in_every_agent_field(self):
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
(OUT / "firefox-slash.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data, "firefox")
if __name__ == "__main__":
unittest.main()
+147
View File
@@ -0,0 +1,147 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
import test_workbench_w4_e2e as w4
from kvb_orchestrator import skill_scripts
OUT = Path(os.environ.get("E2E_OUT", "/tmp/speak-card-shots"))
HINTS = ("Post arrives at the end of the turn.", "Your passkey signs every message.")
CARD = """
const card = () => document.querySelector("#radio-spot .radio-speak");
const form = () => card().querySelector("form.composer");
const toggle = () => form().querySelector(".mayday-toggle");
const answer = async (yes) => {
toggle().click();
const box = await until(() => form().querySelector(".mayday-confirm"), 4000);
if (!box) {
return null;
}
const question = text(box.querySelector("p"));
all("button", box).find((node) => text(node) === (yes ? yes : "Cancel")).click();
return question;
};
const posted = [];
const send = window.fetch.bind(window);
window.fetch = (path, init) => {
if (/^\\/api\\/(board|messages)/.test(String(path))) {
posted.push(String(path));
}
return send(path, init);
};
"""
RAISE = """(async () => {@HELPERS@@CARD@
if (!(await screenShown(8000)) || !(await until(card, 8000))) {
return {error: text(document.getElementById("main"))};
}
await sleep(400);
const foot = toggle().parentElement;
const radius = (node) => getComputedStyle(node).borderTopLeftRadius;
const layout = {
hints: @HINTS@.filter((line) => text(card()).includes(line)),
channels: all("select option", form()).slice(0, 6).map((option) => [option.value, Boolean(option.title)]),
mayday: all("select option", form()).some((option) => option.value === "mayday"),
next: Boolean(toggle().previousElementSibling && toggle().previousElementSibling.matches(".ptt-split")),
face: [text(toggle()), toggle().getAttribute("aria-pressed")],
cards: all(".card", card()).length,
radius: [radius(card()), radius(form().querySelector(".composer-grid")), radius(form().querySelector("textarea").closest(".mic-frame"))],
fits: foot.scrollWidth <= foot.clientWidth + 1 && foot.getBoundingClientRect().right <= card().getBoundingClientRect().right + 1,
wide: document.documentElement.scrollWidth > innerWidth + 1,
};
const field = form().querySelector("textarea");
field.value = "disk full @WIDTH@";
field.dispatchEvent(new Event("input", {bubbles: true}));
const shown = new Set(all("#toasts .toast"));
const declined = await answer(false);
await sleep(600);
const quiet = posted.slice();
const asked = await answer("Send mayday");
const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((line) => line.includes(" to all")), 15000);
return {layout, declined, quiet, asked, toast, left: field.value, violations: window.e2eViolations || null};
})()"""
CANCEL = """(async () => {@HELPERS@@CARD@
if (!(await screenShown(8000)) || !(await until(() => card() && toggle().getAttribute("aria-pressed") === "true", 8000))) {
return {error: text(document.getElementById("main"))};
}
const face = [text(toggle()), toggle().getAttribute("aria-pressed"), toggle().title];
const shown = new Set(all("#toasts .toast"));
const asked = await answer("Cancel mayday");
const toast = await until(() => all("#toasts .toast").filter((node) => !shown.has(node)).map(text).find((line) => line.startsWith("Cancel mayday")), 15000);
return {face, asked, toast, posted};
})()"""
IDLE = """(async () => {@HELPERS@@CARD@
await screenShown(8000);
await until(card, 8000);
return {face: [text(toggle()), toggle().getAttribute("aria-pressed")]};
})()"""
def probe(template: str, **names: str) -> str:
fills = {"@HELPERS@": base.HELPERS, "@CARD@": CARD, "@HINTS@": json.dumps(HINTS)}
fills.update({f"@{key.upper()}@": value for key, value in names.items()})
for key, value in fills.items():
template = template.replace(key, value)
return template
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestSpeakCard(base.OrchestratorE2ECase):
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
(self.council / "radio-silence.json").unlink()
self.local = f"http://localhost:{self.port}/"
def steps(self, template: str, name: str) -> list[dict]:
return [{"width": width, "height": height, "url": f"{self.local}?{width}-{name}#stream/radio", "wait": 1200, "probe": probe(template, width=str(width)), "shot": self.shot(f"{width}-speak-{name}")} for width, height in base.WIDTHS]
def test_chromium_raises_and_cancels_a_mayday_from_the_toggle_beside_ptt(self):
raised = self.drive(self.steps(RAISE, "raise"), self.authenticator(), init=w4.GUARD)
(OUT / "chromium-raise.json").write_text(json.dumps(raised, indent=1), encoding="utf-8")
self.assertEqual(raised["errors"], [])
ask = "Send a mayday to all? All agents pause writing steps until you cancel it."
for result, (width, _) in zip(raised["results"], base.WIDTHS, strict=True):
with self.subTest(step="raise", width=width):
self.assertNotIn("error", result, result)
layout = result["layout"]
self.assertEqual((layout["hints"], layout["mayday"], layout["next"], layout["face"], layout["cards"]), ([], False, True, ["MAYDAY", "false"], 0), layout)
self.assertEqual([value for value, _ in layout["channels"]], ["post", "call", "newsletter", "broadcast", "pan-pan", "security"], layout)
self.assertTrue(all(titled for _, titled in layout["channels"]), layout)
self.assertEqual(layout["radius"], ["14px", "10px", "10px"], layout)
self.assertEqual((layout["fits"], layout["wide"]), (True, False), layout)
self.assertEqual((result["declined"], result["quiet"], result["asked"]), (ask, [], ask), result)
self.assertTrue((result["toast"] or "").startswith("Mayday to all: sent$ radio.py send mayday"), result)
self.assertEqual((result["left"], w4.quiet(result["violations"])), ("", []), result)
sent = [args for script, args in self.scripts.calls if script == skill_scripts.RADIO]
self.assertEqual([args[:2] for args in sent], [["send", "mayday"]] * len(base.WIDTHS))
for args, (width, _) in zip(sent, base.WIDTHS, strict=True):
self.assertTrue(args[-1].endswith(f"disk full {width}"), args)
self.scripts.calls.clear()
(self.council / "radio-silence.json").write_text(json.dumps({"since": time.time() - 30, "until": time.time() + 3600, "by": "Operator", "text": "disk full"}), encoding="utf-8")
cancelled = self.drive(self.steps(CANCEL, "cancel"), {**self.authenticator(), "signCount": len(base.WIDTHS)}, init=w4.GUARD)
(OUT / "chromium-cancel.json").write_text(json.dumps(cancelled, indent=1), encoding="utf-8")
self.assertEqual(cancelled["errors"], [])
for result, (width, _) in zip(cancelled["results"], base.WIDTHS, strict=True):
with self.subTest(step="cancel", width=width):
self.assertNotIn("error", result, result)
self.assertEqual(result["face"][:2], ["Cancel mayday", "true"], result)
self.assertEqual((result["asked"], result["posted"]), ("Lift the radio silence of the active mayday?", ["/api/board/sign", "/api/board/clear-mayday"]), result)
self.assertTrue((result["toast"] or "").startswith("Cancel mayday: done"), result)
self.assertEqual(self.scripts.calls, [(skill_scripts.RADIO, ["clear", "--force", "--session", "Operator"])] * len(base.WIDTHS))
(self.council / "radio-silence.json").unlink()
idle = self.drive(self.steps(IDLE, "idle"), None, init=w4.GUARD)
self.assertEqual([result["face"] for result in idle["results"]], [["MAYDAY", "false"]] * len(base.WIDTHS))
if __name__ == "__main__":
unittest.main()
+164
View File
@@ -0,0 +1,164 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
import test_home_bookmarks_e2e as bm
import test_home_dashboard_e2e as dash
import test_workbench_w4_e2e as w4
OUT = Path(os.environ.get("E2E_OUT", "/tmp/widget-zoom-shots"))
KEY = "panel:tasks/board"
TILE = """
const pinned = () => tile("@KEY@");
const body = () => pinned().querySelector(".home-body");
const zoom = () => Number(body().dataset.zoom);
const key = async (name, times) => {
for (let index = 0; index < times; index += 1) {
const before = zoom();
pinned().focus();
pinned().dispatchEvent(new KeyboardEvent("keydown", {key: name, bubbles: true, cancelable: true}));
await until(() => zoom() !== before, 1500);
}
await sleep(200);
return zoom();
};
const wheel = async (ctrlKey, deltaY) => {
const before = zoom();
const event = new WheelEvent("wheel", {deltaY, ctrlKey, bubbles: true, cancelable: true});
body().dispatchEvent(event);
await until(() => zoom() !== before, 1500);
await sleep(200);
return {zoom: zoom(), prevented: event.defaultPrevented};
};
const fit = () => {
const style = getComputedStyle(body());
const inner = body().clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight);
return Math.abs(body().firstElementChild.offsetWidth * zoom() / 100 - inner) <= 2;
};
"""
SEED = """(async () => {@HELPERS@
await ViewStore.update("home.pins", () => [{kind: "panel", id: "tasks/board", w: innerWidth > 640 ? 6 : 4, h: 5}]);
await ViewStore.update("home.zoom", () => ({}));
return true;
})()"""
KEYS = """(async () => {@HELPERS@@HOME@@TILE@
await go("home");
if (!(await until(() => pinned() && body().dataset.zoom, 8000))) {
return {error: text(document.getElementById("main"))};
}
await sleep(600);
const head = pinned().querySelector(".home-head").getBoundingClientRect().height;
const three = await key("+", 3);
const kept = Math.abs(pinned().querySelector(".home-head").getBoundingClientRect().height - head) <= 0.5;
const fits = fit();
const scrolls = body().scrollHeight > body().clientHeight || body().scrollWidth > body().clientWidth;
const reset = await key("0", 1);
const floor = await key("-", 7);
const ceiling = await key("+", 16);
await key("0", 1);
const up = await wheel(true, -100);
const plain = await wheel(false, 100);
await key("+", 2);
const saved = await ViewStore.update("home.zoom", (zooms) => zooms);
return {three, kept, fits, scrolls, reset, floor, ceiling, up, plain, stored: saved ? ViewStore.get("home.zoom")["@KEY@"] : null};
})()"""
MENU = """(async () => {@HELPERS@@HOME@@TILE@
await until(() => pinned() && body().dataset.zoom, 8000);
const box = pinned().querySelector(".home-title").getBoundingClientRect();
const open = () => pinned().querySelector(".home-title").dispatchEvent(new MouseEvent("contextmenu", {bubbles: true, cancelable: true, button: 2, clientX: box.left + 4, clientY: box.top + 4}));
open();
const menu = await until(() => document.querySelector(".ctx-menu:not([hidden])"), 4000);
const labels = menu ? all('.ctx-group[data-scope="element"] .ctx-item .ctx-label', menu).map(text) : [];
const item = (label) => all(".ctx-item", document.querySelector(".ctx-menu:not([hidden])")).find((node) => text(node.querySelector(".ctx-label")) === label);
const before = zoom();
item("Zoom out").click();
await until(() => zoom() !== before, 1500);
const out = zoom();
open();
await until(() => document.querySelector(".ctx-menu:not([hidden])"), 4000);
item("Zoom in").click();
await until(() => zoom() !== out, 1500);
const back = zoom();
open();
await until(() => document.querySelector(".ctx-menu:not([hidden])"), 4000);
item(`Reset zoom (${back} %)`).click();
await until(() => zoom() === 100, 1500);
return {labels: labels.filter((label) => label.includes("oom")), out, back, reset: zoom()};
})()"""
KEPT = """(async () => {@HELPERS@@HOME@@TILE@
await go("home");
await until(() => pinned() && body().dataset.zoom, 8000);
return {zoom: zoom()};
})()"""
HELP = """(async () => {@HELPERS@
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "?", bubbles: true}));
const sheet = await until(() => document.querySelector("#sheet:not([hidden]) dl.keys"), 4000);
return {keys: sheet ? all("dt", sheet).map(text) : []};
})()"""
def probe(template: str) -> str:
for key, value in (("@HELPERS@", base.HELPERS), ("@HOME@", dash.HOME), ("@TILE@", TILE), ("@KEY@", KEY)):
template = template.replace(key, value)
return template
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestWidgetZoom(base.OrchestratorE2ECase):
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
def steps(self, browser: str) -> list[dict]:
steps = []
for width, height in base.WIDTHS:
at = {"width": width, "height": height}
shot = OUT / f"{browser}-{width}"
steps += [
{**at, "url": f"{self.base}?{width}-clear#stream", "wait": 600, "probe": bm.CLEAR, "shot": None},
{**at, "url": f"{self.base}?{width}-seed#stream", "wait": 800, "probe": probe(SEED), "shot": None},
{**at, "url": f"{self.base}?{width}-keys#home", "wait": 1500, "probe": probe(KEYS), "shot": f"{shot}-zoomed.png"},
{**at, "url": f"{self.base}?{width}-kept#home", "wait": 1500, "probe": probe(KEPT), "shot": None},
{**at, "url": None, "wait": 0, "probe": probe(MENU), "shot": f"{shot}-menu.png"},
{**at, "url": None, "wait": 0, "probe": probe(HELP), "shot": None},
]
return steps
def check(self, data: dict, browser: str) -> None:
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
results = iter(data["results"])
for width, _ in base.WIDTHS:
_, _, keys, kept, menu, shown = (next(results) for _ in range(6))
with self.subTest(browser=browser, width=width):
self.assertNotIn("error", keys, keys)
self.assertEqual((keys["three"], keys["kept"], keys["fits"], keys["scrolls"]), (130, True, True, True), keys)
self.assertEqual((keys["reset"], keys["floor"], keys["ceiling"]), (100, 50, 200), keys)
self.assertEqual((keys["up"], keys["plain"]), ({"zoom": 110, "prevented": True}, {"zoom": 110, "prevented": False}), keys)
self.assertEqual((keys["stored"], kept["zoom"]), (130, 130), (keys, kept))
self.assertEqual(menu["labels"], ["Zoom in", "Zoom out", "Reset zoom (130 %)"], menu)
self.assertEqual((menu["out"], menu["back"], menu["reset"]), (120, 130, 100), menu)
self.assertIn("+ / − · 0 · Ctrl+wheel", shown["keys"], shown)
def test_chromium_zooms_a_tile_by_keys_wheel_and_menu_and_keeps_it(self):
data = self.drive(self.steps("chromium"), None, init=w4.GUARD)
(OUT / "chromium-zoom.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data, "chromium")
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
def test_firefox_zooms_a_tile_by_keys_wheel_and_menu_and_keeps_it(self):
data = self.drive(self.steps("firefox"), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"), init=w4.GUARD)
(OUT / "firefox-zoom.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.check(data, "firefox")
if __name__ == "__main__":
unittest.main()
+47 -28
View File
@@ -76,6 +76,7 @@ OPERATOR = """(async () => {@HELPERS@@UNLABELLED@
return found;
})()"""
FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@
const mine = (words) => all("#main .inbox-list > li").find((li) => li.textContent.includes(words));
const card = await until(() => all("#main .inbox-list > li").find((li) => li.textContent.includes("@TAG@ second") && li.querySelector(".diff-file tr.add")), 10000);
if (!card) {
return {error: text(document.getElementById("main"))};
@@ -92,8 +93,9 @@ FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@
window.e2eFeedback = [];
const send = window.fetch.bind(window);
window.fetch = (path, init) => {
if (String(path).startsWith("/api/messages")) {
window.e2eFeedback.push([String(path), JSON.parse(init.body).text]);
if (String(path).startsWith("/api/") && init && init.method === "POST" && !String(path).startsWith("/api/inbox/undo")) {
const body = JSON.parse(init.body);
window.e2eFeedback.push([String(path), body.text || null, (body.items || []).map((entry) => [entry.kind, entry.verb, entry.channel || "", entry.reason || ""])]);
}
return send(path, init);
};
@@ -117,25 +119,36 @@ FEEDBACK = """(async () => {@HELPERS@@UNLABELLED@
const title = text(document.querySelector(".sheet-head .panel-title"));
const range = text(document.querySelector(".sheet-box .who code"));
sheet.value = "right-click note";
all(".sheet-box button").find((button) => name(button) === "Send feedback").click();
await until(() => window.e2eFeedback.length >= (@SIGNS@ ? 2 : 1), 8000);
await sleep(600);
const fresh = () => all("#main .inbox-list > li").find((li) => li.textContent.includes("@TAG@ second"));
const shown = @SIGNS@ ? await until(() => fresh() && all(".feedback-list li", fresh()).map(text).find((entry) => entry.includes("right-click note")), 15000) : null;
const close = document.querySelector(".sheet-head button");
if (close) {
close.click();
}
const ask = all("#main .inbox-list > li").find((li) => li.textContent.includes("@TAG@ keyed"));
const code = ask.querySelector(".command code");
all(".sheet-box button").find((button) => name(button) === "Save comment").click();
const fresh = () => mine("@TAG@ second");
await until(() => fresh() && fresh().querySelector("tr.match-mark"), 4000);
const marked = {
rows: all("tr.marked", fresh()).map((row) => row.dataset.line),
notes: all("tr.match-mark", fresh()).map(text),
list: all(".feedback-list li.line-mark", fresh()).map(text),
open: !document.getElementById("sheet").hidden,
};
const ask = () => mine("@TAG@ keyed");
const code = ask().querySelector(".command code");
select(code, code);
document.body.dispatchEvent(new KeyboardEvent("keydown", {key: "f", bubbles: true, cancelable: true}));
const keyed = await until(() => document.querySelector(".sheet-box textarea"), 4000);
const keyRange = text(document.querySelector(".sheet-box .who code"));
keyed.value = "key f note";
all(".sheet-box button").find((button) => name(button) === "Send feedback").click();
all(".sheet-box button").find((button) => name(button) === "Save comment").click();
const askList = await until(() => ask() && all(".feedback-list li.line-mark", ask()).map(text).join("|"), 4000);
const before = window.e2eFeedback.length;
all(".deny-split button", ask()).find((button) => name(button) === "Deny").click();
const reason = await until(() => document.querySelector(".sheet-box .deny-reason textarea"), 4000);
const deny = {reason: reason ? reason.value : null, channel: (document.querySelector(".sheet-box .deny-channels input:checked") || {}).value || null, to: (document.querySelector(".sheet-box .deny-recipient select") || {}).value || null};
all(".sheet-box .actions button").find((button) => text(button) === "Deny").click();
await until(() => window.e2eFeedback.length > before && (!@SIGNS@ || window.e2eFeedback.some(([path]) => path === "/api/inbox/approve")), 8000);
await sleep(1200);
all(".item-actions button", fresh()).find((button) => name(button) === "Grant").click();
await until(() => window.e2eFeedback.some(([path]) => path === (@SIGNS@ ? "/api/messages" : "/api/sign")) && window.e2eFeedback.filter(([path]) => path === "/api/sign").length >= 2, 10000);
await sleep(1500);
return {nearby, menu, item, title, range, keyRange, labels, shown: shown || "", posted: window.e2eFeedback, wide: document.documentElement.scrollWidth > window.innerWidth + 1};
const kept = {review: fresh() ? all(".feedback-list li.line-mark", fresh()).map(text) : null, ask: ask() ? all(".feedback-list li.line-mark", ask()).map(text) : null};
return {nearby, menu, item, title, range, keyRange, labels, marked, askList, deny, kept, posted: window.e2eFeedback, wide: document.documentElement.scrollWidth > window.innerWidth + 1};
})()"""
@@ -205,29 +218,35 @@ class TestWorkbenchOperatorTasks(HubCase):
self.assertEqual(tasks["posted"], [["/api/sign", kinds], *([["/api/inbox/approve", kinds]] if signs else [])])
self.assertFalse(tasks["wide"])
self.assertNotIn("error", feedback, feedback)
self.assertEqual((feedback["nearby"], feedback["menu"], feedback["item"], feedback["title"]), (True, "menu", "Feedback", "Feedback"))
self.assertEqual((feedback["range"], feedback["keyRange"]), ("src/app.py:2-2", "/repo:1-1"))
ref = f"review:{self.reviews[(tag, 'second')]}"
texts = [text for path, text in feedback["posted"] if path == "/api/messages/sign"]
self.assertEqual(texts[0].split(": ", 1)[0], f"Feedback on {ref} src/app.py:2-2")
self.assertTrue(texts[0].endswith(" right-click note"), texts)
if signs:
self.assertIn("right-click note", feedback["shown"])
self.assertTrue(any(text and text.endswith(" key f note") for _, text in feedback["posted"]), feedback["posted"])
self.assertEqual((feedback["nearby"], feedback["menu"], feedback["item"], feedback["title"]), (True, "menu", "Comment", "Comment"))
self.assertEqual((feedback["range"], feedback["keyRange"]), ("src/app.py:2", "/repo:1"))
self.assertEqual(feedback["marked"], {"rows": ["2", "2"], "notes": ["right-click note"], "list": ["src/app.py:2right-click note"], "open": False})
self.assertEqual(feedback["askList"], "/repo:1key f note")
self.assertEqual(feedback["deny"], {"reason": "/repo:1: key f note", "channel": "call", "to": "Skills"})
denial = [["ask", "reject", "call", "/repo:1: key f note"]]
grant = [["review", "approve", "", ""]]
notes = f"Granted: feat: {tag} second. Notes:\nsrc/app.py:2: right-click note"
expected = [["/api/sign", None, denial], ["/api/inbox/approve", None, denial], ["/api/sign", None, grant], ["/api/inbox/approve", None, grant], ["/api/messages/sign", notes, []], ["/api/messages", notes, []]]
self.assertEqual(feedback["posted"], expected if signs else [["/api/sign", None, denial], ["/api/sign", None, grant]])
if not signs:
self.assertEqual(feedback["kept"], {"review": ["src/app.py:2right-click note"], "ask": ["/repo:1key f note"]})
self.assertFalse(feedback["wide"])
radio = [" ".join(args) for script, args in self.scripts.calls if script == skill_scripts.RADIO]
reached = [entry for entry in radio if "] Feedback on review:" in entry or "] Feedback on ask:" in entry]
self.assertEqual(len(reached), 2 * len(base.WIDTHS) if signs else 0, radio)
granted = [entry for entry in radio if entry.startswith("send post --to Skills ") and "Granted: feat: w" in entry and "Notes:" in entry and "right-click note" in entry]
self.assertEqual(len(granted), len(base.WIDTHS) if signs else 0, radio)
asks = {ask["command"]: (ask["status"], ask.get("channel", ""), ask.get("reason", "")) for ask in self.httpd.hub.asks.listed() if "keyed" in ask["command"]}
self.assertEqual(asks, {f"git commit -m 'w{width} keyed'": ("denied", "call", "/repo:1: key f note") if signs else ("pending", "", "") for width, _ in base.WIDTHS})
def test_chromium_shows_operator_tasks_with_a_badge_diffs_bulk_grants_and_sends_feedback_at_three_widths(self):
def test_chromium_shows_operator_tasks_with_a_badge_diffs_bulk_grants_and_line_comments_in_the_deny_call_and_grant_post_at_three_widths(self):
with mock.patch.object(batches, "UNDO", 0.3):
data = self.drive(self.steps("chromium", True), self.authenticator())
self.settle(lambda: all(ask["status"] == "denied" for ask in self.httpd.hub.asks.listed() if "keyed" in ask["command"]))
(OUT / "chromium-operator.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
self.check(data, "chromium", True)
@unittest.skipUnless(shutil.which(os.environ.get("FIREFOX", "firefox")), "no Firefox")
def test_firefox_shows_operator_tasks_with_a_badge_diffs_and_feedback_without_signing_at_three_widths(self):
def test_firefox_shows_operator_tasks_with_a_badge_diffs_and_keeps_line_comments_without_signing_at_three_widths(self):
data = self.drive(self.steps("firefox", False), None, "bidi.mjs", os.environ.get("FIREFOX", "firefox"))
(OUT / "firefox-operator.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual([error for error in data["errors"] if "/favicon.ico" not in error], [])
+2 -2
View File
@@ -20,7 +20,7 @@ ROWS = 360
WAITED = (120, 180)
ASLEEP = 180
UNREAD = (300, 320)
PANELS = {"resources-hardware": "Hardware: disks, CPU, RAM, swap, GPU and VRAM", "resources-tokens": "Tokens per agent"}
PANELS = {"resources-hardware": "Hardware: disks, CPU, RAM, swap, GPU and VRAM", "resources-tokens": "Tokens per agent", "resources-accounts": "Accounts"}
GUARD = """() => {
window.e2eViolations = [];
document.addEventListener("securitypolicyviolation", (event) => window.e2eViolations.push(`${event.violatedDirective} ${event.blockedURI}`));
@@ -128,7 +128,7 @@ class TestWorkbenchResources(HubCase):
self.assertEqual(found["unknown"], [[self.start + UNREAD[0] * 60, self.start + UNREAD[1] * 60]])
self.assertEqual((found["agents"], found["bottoms"], found["stacked"]), (["Skills", "Stage"], ["Skills"], True))
self.assertEqual(found["legend"], ["CPU 60 %", "RAM 55 %", "Swap 5 %"])
self.assertEqual(found["labels"], {"tab": ["Resources (key 6)", "Resources"], "reload": ["Reload: read the sampler files again", "Reload"], "titles": [[name, name] for name in PANELS.values()]})
self.assertEqual(found["labels"], {"tab": ["Resources (key 6)", "Resources"], "reload": ["Reload: read the sampler files and the accounts again", "Reload"], "titles": [[name, name] for name in PANELS.values()]})
self.assertEqual((found["unlabelled"], found["plots"]), (0, [True] * 2))
self.assertEqual((found["tall"], found["wide"]), (False, False), "the page scrolls")
self.assertEqual(quiet(found["violations"]), [])
+125
View File
@@ -0,0 +1,125 @@
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import unittest
from pathlib import Path
HERE = Path(__file__).resolve().parent
sys.path[:0] = [str(HERE.parent), str(HERE)]
import hub_e2e_kit as base
from hub_case import HubCase
from kvb_orchestrator.jobs import UNRUNNABLE
OUT = Path(os.environ.get("E2E_OUT", "/tmp/hub-030-shots"))
ROWS = ["operator/free", "operator/loose", "operator/pick", "operator/runs", "operator/waits"]
READ = """
const blockedTitles = (selector) => Object.fromEntries(all(selector).filter((node) => node.hasAttribute("data-blocked")).map((node) => [node.dataset.card || node.dataset.ref || node.dataset.operator, node.getAttribute("title") || ""]));
const wide = () => document.documentElement.scrollWidth > innerWidth + 1;
"""
MATCH = """(async () => {@HELPERS@@READ@
if (!(await until(() => document.querySelector("#main .match-card.front"), 15000))) {
return {error: text(document.getElementById("main"))};
}
const toggle = document.querySelector("#main .match-peeks-toggle");
if (toggle && toggle.getAttribute("aria-pressed") !== "true") {
toggle.click();
}
await until(() => all("#main .match-peek").length === 4, 4000);
const front = document.querySelector("#main .match-card.front");
const accept = document.querySelector("#main .match-accept");
const reject = document.querySelector("#main .match-reject");
return {
front: front.dataset.card, forms: all(".choice", front).length, accept: [accept.disabled, accept.getAttribute("title")], reject: [reject.disabled, reject.getAttribute("title")],
peeks: all("#main .match-peek").map((peek) => peek.dataset.card), blocked: blockedTitles("#main .match-peek"), wide: wide(),
};
})()"""
STREAM = """(async () => {@HELPERS@@READ@
const rows = () => all("#main .feed > li.k-operator");
if (!(await until(() => rows().length === 5, 15000))) {
return {error: text(document.getElementById("main")), rows: rows().length};
}
const pick = rows().find((row) => row.dataset.ref === "operator:operator/pick");
const buttons = (row) => all(".line-actions button", row).map((button) => [name(button), button.disabled]);
const runs = rows().find((row) => row.dataset.ref === "operator:operator/runs");
return {refs: rows().map((row) => row.dataset.ref).sort(), blocked: blockedTitles("#main .feed > li.k-operator"), pickForms: pick ? all(".choice", pick).length : null, pickButtons: pick ? buttons(pick) : null, runsButtons: runs ? buttons(runs) : null, wide: wide()};
})()"""
TASKS = """(async () => {@HELPERS@@READ@
if (!(await until(() => all("#main .operator-list > li").length === 5, 15000))) {
return {error: text(document.getElementById("main"))};
}
return {rows: all("#main .operator-list > li").map((row) => row.dataset.operator).sort(), blocked: Object.keys(blockedTitles("#main .operator-list > li")).length, runs: document.querySelector('#main .operator-list > li[data-operator="operator/runs"]').getAttribute("title"), wide: wide()};
})()"""
def probe(template: str) -> str:
return template.replace("@HELPERS@", base.HELPERS).replace("@READ@", READ)
@unittest.skipUnless(shutil.which(os.environ.get("CHROMIUM", "chromium")), "no Chromium")
class TestYesNoAnswers(HubCase):
drive = base.OrchestratorE2ECase.drive
def setUp(self):
super().setUp()
OUT.mkdir(parents=True, exist_ok=True)
work = self.outside / "work"
work.mkdir()
row = {"title": "true", "workdir": str(work), "description": "ship the release notes", "check": "done", "roles": {"Skills": "A", "Operator": "R"}}
yes_no = [{"label": "Yes", "description": "merge it"}, {"label": "No", "description": "leave it"}]
register = {task: row for task in ("operator/free", "operator/runs", "operator/waits")}
register |= {"operator/loose": {**row, "workdir": "relative/dir"}, "operator/pick": {**row, "title": "Merge the hub now?", "check": "decision", "options": yes_no}}
self.write_council({"rasci.json": register})
now = time.time()
job = {"command": "true", "directory": str(work), "sha256": "0" * 64, "proof": None, "output": "", "finished": None, "dismissed": False, "code": None}
self.httpd.hub.jobs.add({**job, "task": "operator/runs", "status": "running", "created_ts": now - 1800, "started": now - 1800})
self.httpd.hub.jobs.add({**job, "task": "operator/waits", "status": "queued", "created_ts": now - 600, "started": None})
self.page_url = f"http://localhost:{self.port}/"
def test_chromium_shows_every_open_row_in_match_the_stream_and_tasks_greying_the_blocked_ones_at_three_widths(self):
steps = []
for width, height in base.WIDTHS:
shot = OUT / f"chromium-{width}"
steps += [
{"width": width, "height": height, "url": f"{self.page_url}?{width}#tasks/match", "wait": 1500, "probe": probe(MATCH), "shot": f"{shot}-match.png"},
{"width": width, "height": height, "url": f"{self.page_url}?{width}-stream#stream", "wait": 1500, "probe": probe(STREAM), "shot": f"{shot}-stream.png"},
{"width": width, "height": height, "url": f"{self.page_url}?{width}-tasks#tasks/list", "wait": 1500, "probe": probe(TASKS), "shot": f"{shot}-tasks.png"},
]
data = self.drive(steps, None)
(OUT / "chromium-yes-no.json").write_text(json.dumps(data, indent=1), encoding="utf-8")
self.assertEqual(data["errors"], [])
results = iter(data["results"])
blocked = {"operator/loose": UNRUNNABLE, "operator/runs": "The hub runner runs it for 30 min", "operator/waits": "Queued in the hub runner for 10 min behind operator/runs"}
for width, _ in base.WIDTHS:
match, stream, tasks = next(results), next(results), next(results)
with self.subTest(width=width):
self.assertNotIn("error", match, match)
self.assertEqual(sorted([match["front"], *match["peeks"]]), sorted(f"operator:{task}" for task in ROWS))
self.assertEqual(sorted(match["blocked"]), sorted(f"operator:{task}" for task in blocked))
for task, reason in blocked.items():
self.assertIn(reason, match["blocked"][f"operator:{task}"])
if match["front"] == "operator:operator/pick":
self.assertEqual(match["forms"], 0)
self.assertEqual(match["accept"][0], False)
self.assertTrue(match["accept"][1].startswith("Accept: Yes"), match["accept"])
self.assertTrue(match["reject"][1].startswith("Reject: No"), match["reject"])
self.assertNotIn("error", stream, stream)
self.assertEqual(stream["refs"], sorted(f"operator:{task}" for task in ROWS))
self.assertEqual(sorted(stream["blocked"]), sorted(f"operator:{task}" for task in blocked))
for task, reason in blocked.items():
self.assertIn(reason, stream["blocked"][f"operator:{task}"])
self.assertEqual(stream["pickForms"], 0)
self.assertEqual(stream["pickButtons"][:2], [["Yes", False], ["No", False]])
self.assertIn(["Run", True], stream["runsButtons"])
self.assertNotIn("error", tasks, tasks)
self.assertEqual((tasks["rows"], tasks["blocked"]), (ROWS, 5))
self.assertIn(blocked["operator/runs"], tasks["runs"])
self.assertEqual((match["wide"], stream["wide"], tasks["wide"]), (False, False, False))
if __name__ == "__main__":
unittest.main()
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more