Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 23 additions & 6 deletions docs/chief.md
Original file line number Diff line number Diff line change
Expand Up @@ -1757,7 +1757,8 @@ the minder either way.)

**The cards.** The digest's **Proposed** group, after Needs you, lists each
open proposal: the session, the class as a verb ("Continue", "Write handoff,
then close"), the one-line reason, and **exactly what will be sent**, in full.
then close"), when it expires ("expires in 3h (10:07 PM)", the time in your
own clock), the one-line reason, and **exactly what will be sent**, in full.

- **Approve** sends it. It needs a sign-in from the last `MUSTER_STEPUP_WINDOW`
(usually free); on a stale one muster asks "Confirm it's you" and taps again.
Expand Down Expand Up @@ -1795,17 +1796,33 @@ proposals leave the group.
| a dispatched agent | a turn, as the chief's nudges start one |

**The push.** At most every 30 minutes, and only when a new proposal arrived,
one push: "N proposals waiting". Tapping it opens the chief panel. Beside it,
**one** Attention item says the same: each push replaces it with the new count
(never a second one), and it is withdrawn once no proposal waits. The per-stop
pushes are unchanged.
one push, titled "N proposals waiting". Its text names the newest proposal and
its session, by the name its card shows (at most 40 characters), and counts
the rest: "Wrap 'muster-asks-ux'? +2 more. Nothing is sent until you approve
them." It never carries a message's text, and it has no buttons. Each push
replaces the last on the phone.

Tapping it opens the board (`/tasks?chief=open&fleet=proposed&proposal=<id>`)
with the chief panel open on the digest's **Proposed group** (on a phone, its
sheet), scrolled to that proposal and outlined, with its Approve, Edit and
Reject on screen. If it no longer waits when you get there, a line says so:
"That proposal expired at 10:07 PM.", "That proposal was already approved at
…", "…rejected at …", or "That proposal was not sent: its session moved on".
The newest one still waiting is outlined instead, or the group says "None.".
An older push's `/?chief=open` opens the board with the panel open too.

Beside the push, **one** Attention item says the same: each push replaces it
with the new count (never a second one), and it is withdrawn once no proposal
waits. Tapping it opens the Proposed group the same way, on the newest
proposal. The per-stop pushes are unchanged.

**The action log**, `fleet_actions` ([schema.md](schema.md)), is append-only:
one row per proposal with its state (`proposed`, `approved`, `rejected`,
`expired`, `queued`, `sent`, `failed`, `suppressed:<why>`), and one
`audit_log` row (`fleet.<class>.<state>`) per change, carrying ids only.

The routes: `POST /ui/chief/fleet/actions/{id}/approve`, `…/edit` (`text=`),
The routes: `GET /ui/chief/fleet?fleet=proposed&proposal=<id>` (the card as
the push's tap opens it), `POST /ui/chief/fleet/actions/{id}/approve`, `…/edit` (`text=`),
`…/reject`, `POST /ui/chief/fleet/bulk` (`op=approve|reject`, `id=` for each
card) and `GET /ui/chief/fleet/stepup` (the confirm dialog). Each answers 404
with the flag off.
Expand Down
90 changes: 87 additions & 3 deletions e2e/tests/chief-fleet-proposals.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ import { clsInit, readCls, resetCls, settle } from '../lib/cls';
// - Approve all, after a confirm listing every card, sends each that is
// still on its stop and skips one whose stop ended after it was drawn:
// "2 sent, 1 skipped (moved on).";
// - opening the panel on a card with a Proposed group shifts nothing.
// - opening the panel on a card with a Proposed group shifts nothing;
// - the batched push's tap (ui.FleetProposalsURL, the url
// TestTheFleetPushNamesTheNewestProposalAndOpensIt pins on the push) lands
// with the panel open on the Proposed group — on a phone its sheet —
// scrolled to the newest proposal, highlighted, its Approve in view, each
// card saying when it expires, and nothing shifted; a tap whose proposal
// no longer waits (decided, expired) says so.
//
// ⚠ WHAT IS PLAYED: tmux (the e2emirror host's windows file), GitHub (a fake
// App: one merged pull request), the model (a fake runtime that must hear
Expand Down Expand Up @@ -62,6 +68,14 @@ const DESK = windowsOf('d', 30);
// stopped: muster proposes ci_result (its stop is opened in that viewport's
// test, so the other's card is not in its bulk approve).
const CIW = { p: { sid: `${prefix}pci`, win: '@50' }, d: { sid: `${prefix}dci`, win: '@51' } };
// Three windows per viewport for the push's tap: proposed oldest to newest;
// the middle one's stop ends before a tap (it expires).
const ARRIVALS = ['old', 'gone', 'fresh'] as const;
type Arrival = (typeof ARRIVALS)[number];
const arrivalsOf = (vp: string, base: number) =>
Object.fromEntries(ARRIVALS.map((r, i) => [r, { sid: `${prefix}${vp}a${i}`, win: `@${base + i}` }])) as Record<Arrival, { sid: string; win: string }>;
const ARRIVE = { p: arrivalsOf('p', 60), d: arrivalsOf('d', 70) };
const ARRIVE_CLASS: Record<Arrival, string> = { old: 'continue', gone: 'handoff', fresh: 'stop_note' };

const APP_ID = '515151';
const APP_ACCOUNT = { login: 'e2e-quill', id: 5151, type: 'User' };
Expand Down Expand Up @@ -143,7 +157,7 @@ test.beforeAll(async ({ browser }) => {
const longAgo = Date.now() - 60 * 60 * 1000;
const lines: string[] = [];
let i = 0;
for (const w of [...Object.values(PHONE), ...Object.values(DESK), CIW.p, CIW.d]) {
for (const w of [...Object.values(PHONE), ...Object.values(DESK), CIW.p, CIW.d, ...Object.values(ARRIVE.p), ...Object.values(ARRIVE.d)]) {
i++;
const file = path.join(rig.dir, `${w.sid}.jsonl`);
fs.writeFileSync(file, cc.prompt('Fix ledger bug ' + i + '.') + cc.reply('Ledger fix ' + i + ' is merged.'));
Expand All @@ -161,7 +175,7 @@ test.beforeAll(async ({ browser }) => {
await ctx.close();
// Every window's stop, as the pass would open it; the pass then observes
// each (its idle streak), which a proposal is filed on.
const all = [...Object.values(PHONE), ...Object.values(DESK)];
const all = [...Object.values(PHONE), ...Object.values(DESK), ...Object.values(ARRIVE.p), ...Object.values(ARRIVE.d)];
for (const w of all) fix('episode', '1', w.sid, 'stalled', rig.host, w.win);
// The question each answer card answers: an open plain-text ask in the
// answer window's stop.
Expand Down Expand Up @@ -384,5 +398,75 @@ for (const vp of [
expect(r.total, JSON.stringify(r.shifts)).toBeLessThan(0.01);
await page.evaluate(() => { try { localStorage.removeItem('muster.chief.v1.open.chief-panel'); } catch (e) {} });
});

test("the push's tap opens the Proposed group on the newest proposal, and says when one no longer waits", async ({ page }) => {
test.setTimeout(120_000);
const tap = async (loc: ReturnType<Page['locator']>) => (vp.phone ? loc.tap() : loc.click());
await rig.login(page);
const set = ARRIVE[vp.key as 'p' | 'd'];
const ids = {} as Record<Arrival, number>;
for (const r of ARRIVALS) {
const out = await chiefCall('session_instruct', { subject: `mirror:${set[r].sid}`, class: ARRIVE_CLASS[r], reason: `the ${r} arrival` });
expect(out.state, `session_instruct ${r}: ${JSON.stringify(out)}`).toBe('proposed');
ids[r] = out.action_id as number;
}
const card = page.locator('#fleet-digest [data-fleet-digest]');
const group = () => (vp.phone ? page.locator('[data-fleet-sheet="proposed"]') : card.locator('details[data-fleet-group="proposed"]'));
const of = (r: Arrival) => group().locator(`[data-fleet-proposal-subject="mirror:${set[r].sid}"]`);
// The push's url for proposal id (ui.FleetProposalsURL; the Go tests pin
// the push and the Attention notice to it).
const arrive = async (id: number) => {
await page.goto(rig.origin + `/tasks?chief=open&fleet=proposed&proposal=${id}`);
await expect(page.locator('#chief-panel')).toHaveAttribute('data-chief-panel-open', '1', { timeout: 20_000 });
await expect(card).toHaveAttribute('data-fleet-state', 'ready');
await expect(group(), 'the Proposed group is open on arrival').toBeVisible();
};

await page.addInitScript(clsInit);
await arrive(ids.fresh);
// The parameters left the address bar: a reload does not reopen it.
await expect(page).toHaveURL(rig.origin + '/tasks');
if (vp.phone) {
await expect(card.locator('[data-fleet-chip="proposed"]')).toHaveAttribute('aria-expanded', 'true');
} else {
await expect(group()).toHaveAttribute('open', '');
}
// The newest, highlighted, scrolled into view, its Approve right there.
const hl = group().locator('[data-fleet-highlight]');
await expect(hl).toHaveCount(1);
await expect(hl).toHaveAttribute('data-fleet-proposal-subject', `mirror:${set.fresh.sid}`);
await expect(hl.locator('[data-fleet-verb]')).toHaveText('Stop and wait');
await expect(of('old')).toHaveCount(1);
await expect(hl.locator('[data-fleet-approve]')).toBeInViewport();
// Each card says when it expires, in the reader's own clock (with its
// date when that is not today: 12 h on can be tomorrow) — never the
// server's UTC fallback.
for (const r of ARRIVALS) {
await expect(of(r).locator('[data-fleet-expires]')).toHaveText(/^expires in 1[01]h \((?:[A-Z][a-z]{2} \d{1,2}, )?\d{1,2}:\d\d(\s?[AP]M)?\)$/);
}
await settle(page);
const shift = await readCls(page);
expect(shift.unsupported, 'the browser reports layout-shift entries').toBeUndefined();
console.log(`[cls ${vp.name}] arriving from the push: ${shift.total}`);
expect(shift.total, 'arriving from the push: ' + JSON.stringify(shift.shifts)).toBeLessThan(0.01);

// Approve is reachable and works; the oldest is rejected.
await tap(hl.locator('[data-fleet-approve]'));
await expect(card.locator('[data-fleet-note]')).toHaveText('Queued: it is pasted once the session is idle.');
await tap(of('old').locator('[data-fleet-reject]'));
await expect(card.locator('[data-fleet-note]')).toHaveText('Rejected.');

// A tap whose proposal expired (its stop ended): the line says so, and
// nothing waits.
fix('endepisode', '1', set.gone.sid);
await arrive(ids.gone);
await expect(group().locator('[data-fleet-gone]')).toHaveText(/^That proposal expired at \d{1,2}:\d\d(\s?[AP]M)?\.$/);
await expect(group().locator('[data-fleet-proposal]')).toHaveCount(0);
await expect(group()).toContainText('None.');
// The one already approved: decided, and said so.
await arrive(ids.fresh);
await expect(group().locator('[data-fleet-gone]')).toHaveText(/^That proposal was already approved at \d{1,2}:\d\d(\s?[AP]M)?\.$/);
await page.evaluate(() => { try { localStorage.removeItem('muster.chief.v1.open.chief-panel'); } catch (e) {} });
});
});
}
3 changes: 3 additions & 0 deletions internal/api/attention.go
Original file line number Diff line number Diff line change
Expand Up @@ -346,6 +346,9 @@ type attentionItem struct {
// withAskBoxes for the pages that draw them, never by askItem: the item is
// built where no server is in reach (a push, attention_list).
dictate, sessionLink string
// fleetNotice: the fleet's "N proposals waiting" notice (fleetNoticeSync),
// whose link is the digest's Proposed group (attentionSessionPathIn).
fleetNotice bool
// pageOpen is the owner's view of the page a share link's card asks about
// (Server.pageAskOpen), "" for every other ask: the card's "Open the
// page" button, so its question needs no address. Set by withAskBoxes and
Expand Down
3 changes: 2 additions & 1 deletion internal/api/attention_notice.go
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,8 @@ func (s *Server) noticeItemNow(ctx context.Context, a attention.Ask) attentionIt
func noticeItem(a attention.Ask, ds map[int64]chiefnudge.Decision, hosts []mirror.HostView) attentionItem {
key := attentionAskKey(a.ID)
it := attentionItem{Key: key, Kind: attentionKindNotice, Source: shownAskLabel(a), OfficerID: officerAskID(a), Text: a.Question, Since: a.CreatedAt,
Link: attentionPath + "#" + key, AskID: a.ID, systemAsk: true, owner: a.Owner, toChief: a.ToChief}
Link: attentionPath + "#" + key, AskID: a.ID, systemAsk: true, owner: a.Owner, toChief: a.ToChief,
fleetNotice: a.Asker.System && a.Asker.Label == fleetNoticeLabel}
if it.Source == "" {
it.Source = chiefNudgeAskLabel
}
Expand Down
5 changes: 5 additions & 0 deletions internal/api/attention_push_target.go
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,11 @@ func (s *Server) attentionSessionPathIn(ctx context.Context, owner int64, it att
}
return c.ref.ViewPath()
case attentionKindNotice:
// The fleet's "N proposals waiting": the proposals are in the
// digest, not in a session — its Proposed group, on the newest.
if it.fleetNotice {
return ui.FleetProposalsURL(0)
}
if it.AskID > 0 {
return s.nudgeSessionPathIn(ctx, owner, it.AskID, hosts)
}
Expand Down
107 changes: 96 additions & 11 deletions internal/api/fleet_actions.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"strconv"
"strings"
"time"
"unicode"

"github.com/ZacxDev/muster/internal/agents"
"github.com/ZacxDev/muster/internal/attention"
Expand Down Expand Up @@ -647,8 +648,8 @@ func (s *Server) fleetApprove(ctx context.Context, id int64, via string, edited
if edited != nil && !fleetEditable(a) {
return fleetApproveResult{note: FleetNotEditable}
}
if s.now().Sub(a.CreatedAt) >= fleet.ProposalTTL {
s.fleetMove(ctx, a, fleet.Move{State: fleet.StateExpired, Outcome: "12 h passed", Finish: true})
if fleet.Expired(a.CreatedAt, s.now()) {
s.fleetMove(ctx, a, fleet.Move{State: fleet.StateExpired, Outcome: fleetTTLOutcome, Finish: true})
return fleetApproveResult{note: FleetExpiredNote}
}
switch s.fleetStillOn(ctx, a) {
Expand Down Expand Up @@ -1211,17 +1212,18 @@ const fleetPushTag = "fleet-proposals"

// fleetPushWaiting pushes owner "N proposals waiting" when one is due
// (fleet.Actions.ClaimPush: at most every fleet.PushEvery, and only when a
// proposal arrived since the last). Its tap opens the chief panel; it carries
// NO action — 🔴 a phone's notification can never approve a proposal (the
// card's routes refuse a device principal too: fleetCardRefusal).
// proposal arrived since the last). It names the newest proposal, and its tap
// opens the digest's Proposed group on it; it carries NO action — 🔴 a
// phone's notification can never approve a proposal (the card's routes
// refuse a device principal too: fleetCardRefusal).
func (s *Server) fleetPushWaiting(octx context.Context, owner int64) {
n, due, err := s.ext.FleetActions.ClaimPush(octx, s.now())
if err != nil {
s.logger.Printf("fleet: owner %d: the batched push: %v", owner, err)
return
}
if due {
s.goNotify(owner, push.EventAttention, fleetPushNotification(n), nil)
s.goNotify(owner, push.EventAttention, fleetPushNotification(n, s.fleetNewestWaiting(octx)), nil)
}
s.fleetNoticeSync(octx, due, n)
}
Expand Down Expand Up @@ -1316,14 +1318,97 @@ func (s *Server) fleetNoticeWithdraw(octx context.Context) {
}
}

// fleetPushNotification is the batched push for n waiting proposals: muster's
// own words, no session text, and no actions.
func fleetPushNotification(n int) RouterNotification {
// fleetPushNotification is the batched push for n waiting proposals, newest
// the newest of them (its zero value when it could not be read): muster's own
// words naming what is proposed and on which session (fleetPushBody) — never
// a message's or an instruction's text — and no actions. Its tap opens the
// digest's Proposed group on newest (ui.FleetProposalsURL).
func fleetPushNotification(n int, newest fleet.Action) RouterNotification {
title := "1 proposal waiting"
if n != 1 {
title = strconv.Itoa(n) + " proposals waiting"
}
return RouterNotification{Type: attentionNotificationType, ID: fleetPushTag, Title: title,
Body: "Your chief proposed what to send your sessions. Nothing is sent until you approve it in the fleet digest.",
Tag: fleetPushTag, Data: map[string]string{"url": ui.ChiefOpenURL}}
Body: fleetPushBody(n, newest), Tag: fleetPushTag, Data: map[string]string{"url": ui.FleetProposalsURL(newest.ID)}}
}

// fleetPushGeneric is the push's body when the newest proposal could not be
// read.
const fleetPushGeneric = "Your chief proposed what to send your sessions. Nothing is sent until you approve it in the fleet digest."

// fleetPushAsks is each class as the push asks it, %s the session's name.
// TestThePushNamesEveryClass holds it to fleet.ClassVerb's classes.
var fleetPushAsks = map[string]string{
fleet.ClassContinue: "Continue '%s'?",
fleet.ClassHandoff: "Ask '%s' for its handoff?",
fleet.ClassStopNote: "Stop '%s' after this step?",
fleet.ClassCustom: "Send the chief's message to '%s'?",
fleet.ClassWrap: "Wrap '%s'?",
fleet.ClassReassign: "Move a task off '%s'?",
fleet.ClassAnswerRule: "Answer '%s'?",
fleet.ClassAnswerComposed: "Answer '%s'?",
fleet.ClassAnswerPick: "Pick an option for '%s'?",
fleet.ClassCIResult: "Tell '%s' its CI finished?",
fleet.ClassClose: "Close '%s'?",
}

// fleetPushNameRunes caps the session's name in the push.
const fleetPushNameRunes = 40

// fleetPushBody is the push's body: what the newest proposal is, on which
// session ("Wrap 'muster-asks-ux'?"), "+N more." for the others, and that
// nothing is sent until approved.
func fleetPushBody(n int, newest fleet.Action) string {
if newest.ID <= 0 {
return fleetPushGeneric
}
ask, ok := fleetPushAsks[newest.Class]
if !ok {
ask = "A proposal for '%s'."
}
body := strings.Replace(ask, "%s", fleetPushName(fleetLabel(newest)), 1)
if n > 1 {
return body + " +" + strconv.Itoa(n-1) + " more. Nothing is sent until you approve them."
}
return body + " Nothing is sent until you approve it."
}

// fleetPushName is a session's name as the push quotes it: the digest card's
// label on one line, with no control character and no straight quote (so the
// quoting stays unambiguous), cut to fleetPushNameRunes with "…".
func fleetPushName(label string) string {
label = strings.Map(func(r rune) rune {
switch {
case r == '\'':
return '’'
case unicode.IsControl(r) || unicode.Is(unicode.Cf, r):
return ' '
}
return r
}, label)
label = strings.Join(strings.Fields(label), " ")
if label == "" {
return "a session"
}
if r := []rune(label); len(r) > fleetPushNameRunes {
return strings.TrimSpace(string(r[:fleetPushNameRunes-1])) + "…"
}
return label
}

// fleetNewestWaiting is octx's owner's newest proposal still waiting for its
// tap; the zero Action when there is none or it could not be read.
func (s *Server) fleetNewestWaiting(octx context.Context) fleet.Action {
list, err := s.ext.FleetActions.OpenActions(octx)
if err != nil {
s.logger.Printf("fleet: the batched push's newest proposal: %v", err)
return fleet.Action{}
}
// Oldest first: the newest waiting is the last proposed.
for i := len(list) - 1; i >= 0; i-- {
if list[i].State == fleet.StateProposed {
return list[i]
}
}
return fleet.Action{}
}
4 changes: 2 additions & 2 deletions internal/api/fleet_actions_pg_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -255,8 +255,8 @@ func TestAPhoneNotificationActionCannotApprove(t *testing.T) {
if a := f.action(t, id); a.State != fleet.StateProposed || len(f.rows(t)) != 0 {
t.Fatalf("a phone's tap moved it: %+v rows %v", a, f.rows(t))
}
n := fleetPushNotification(3)
if n.AskActions || len(n.Data) != 1 || n.Data["url"] != "/?chief=open" || n.Title != "3 proposals waiting" {
n := fleetPushNotification(3, f.action(t, id))
if n.AskActions || len(n.Data) != 1 || n.Data["url"] != "/tasks?chief=open&fleet=proposed&proposal="+strconv.FormatInt(id, 10) || n.Title != "3 proposals waiting" {
t.Fatalf("the batched push: %+v", n)
}
}
Expand Down
Loading
Loading