diff --git a/docs/chief.md b/docs/chief.md index 3c7ba0d36..143a9d914 100644 --- a/docs/chief.md +++ b/docs/chief.md @@ -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. @@ -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=`) +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:`), and one `audit_log` row (`fleet..`) 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=` (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. diff --git a/e2e/tests/chief-fleet-proposals.spec.ts b/e2e/tests/chief-fleet-proposals.spec.ts index 7342c0828..c2e32d96e 100644 --- a/e2e/tests/chief-fleet-proposals.spec.ts +++ b/e2e/tests/chief-fleet-proposals.spec.ts @@ -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 @@ -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; +const ARRIVE = { p: arrivalsOf('p', 60), d: arrivalsOf('d', 70) }; +const ARRIVE_CLASS: Record = { old: 'continue', gone: 'handoff', fresh: 'stop_note' }; const APP_ID = '515151'; const APP_ACCOUNT = { login: 'e2e-quill', id: 5151, type: 'User' }; @@ -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.')); @@ -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. @@ -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) => (vp.phone ? loc.tap() : loc.click()); + await rig.login(page); + const set = ARRIVE[vp.key as 'p' | 'd']; + const ids = {} as Record; + 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) {} }); + }); }); } diff --git a/internal/api/attention.go b/internal/api/attention.go index 6f0c30544..2a7c2e8ce 100644 --- a/internal/api/attention.go +++ b/internal/api/attention.go @@ -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 diff --git a/internal/api/attention_notice.go b/internal/api/attention_notice.go index 33f711610..acf2e9fc7 100644 --- a/internal/api/attention_notice.go +++ b/internal/api/attention_notice.go @@ -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 } diff --git a/internal/api/attention_push_target.go b/internal/api/attention_push_target.go index 77f070498..c6fa5877f 100644 --- a/internal/api/attention_push_target.go +++ b/internal/api/attention_push_target.go @@ -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) } diff --git a/internal/api/fleet_actions.go b/internal/api/fleet_actions.go index 9e412761d..05043db60 100644 --- a/internal/api/fleet_actions.go +++ b/internal/api/fleet_actions.go @@ -8,6 +8,7 @@ import ( "strconv" "strings" "time" + "unicode" "github.com/ZacxDev/muster/internal/agents" "github.com/ZacxDev/muster/internal/attention" @@ -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) { @@ -1211,9 +1212,10 @@ 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 { @@ -1221,7 +1223,7 @@ func (s *Server) fleetPushWaiting(octx context.Context, owner int64) { 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) } @@ -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{} } diff --git a/internal/api/fleet_actions_pg_test.go b/internal/api/fleet_actions_pg_test.go index 87c5c51c2..e84802c5a 100644 --- a/internal/api/fleet_actions_pg_test.go +++ b/internal/api/fleet_actions_pg_test.go @@ -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) } } diff --git a/internal/api/fleet_cards.go b/internal/api/fleet_cards.go index 2211d756e..32dc3a4cb 100644 --- a/internal/api/fleet_cards.go +++ b/internal/api/fleet_cards.go @@ -265,7 +265,8 @@ func (s *Server) fleetProposalViews(ctx context.Context, subs map[string]fleetSu } p := ui.FleetProposalView{ID: a.ID, Subject: a.Evidence.SubjectID, Session: firstNonBlank(a.Evidence.Label, firstNonBlank(a.Evidence.SubjectID, a.SubjectKey)), Verb: fleet.ClassVerb[a.Class], Reason: a.Reason, Text: fleet.Body(owner, now, a.Text), EditText: a.Text, - Age: fleetAge(now.Sub(a.CreatedAt)), Editable: fleetEditable(a)} + Age: fleetAge(now.Sub(a.CreatedAt)), Editable: fleetEditable(a), + ExpiresIn: fleetExpiresIn(fleet.ExpiresAt(a.CreatedAt).Sub(now)), ExpiresAt: fleet.ExpiresAt(a.CreatedAt)} if a.Class == fleet.ClassReassign { p.Text = "1. Route task #" + strconv.FormatInt(a.TaskID, 10) + " to " + a.ToSubject + " (as route_to_session does).\n2. Then send:\n" + p.Text } @@ -280,12 +281,16 @@ func (s *Server) fleetProposalViews(ctx context.Context, subs map[string]fleetSu return out } +// fleetTTLOutcome is the outcome of a proposal expired by its 12 h +// (fleet.Expired): fleetGone says it expired at fleet.ExpiresAt by it. +const fleetTTLOutcome = "12 h passed" + // fleetExpire expires proposal a when its 12 h passed or its stop moved on // (the stop ended, a new message, a new pull-request head): true when it is // no longer a proposal. A state that cannot be read keeps it. func (s *Server) fleetExpire(ctx context.Context, a fleet.Action) bool { - 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 true } if s.fleetStillOn(ctx, a).movedOn() { @@ -295,6 +300,91 @@ func (s *Server) fleetExpire(ctx context.Context, a fleet.Action) bool { return false } +// fleetExpiresIn is d, the time left before a proposal expires, as its card +// says it: "in 3h", "in 45m", "in under a minute". +func fleetExpiresIn(d time.Duration) string { + switch { + case d < time.Minute: + return "in under a minute" + case d < time.Hour: + return "in " + strconv.Itoa(int(d.Minutes())) + "m" + } + return "in " + strconv.Itoa(int(d.Hours())) + "h" +} + +// --- a fleet link's arrival (ui.FleetProposalsURL) ------------------------------ + +// The lines a fleet link's card draws when the proposal it named no longer +// waits (ui.FleetGroupView.Gone; " at ." follows when it says when). +const ( + FleetGoneExpired = "That proposal expired" + FleetGoneApproved = "That proposal was already approved" + FleetGoneRejected = "That proposal was already rejected" + FleetGoneMovedOn = "That proposal was not sent: its session moved on" + FleetGoneUnknown = "That proposal is no longer waiting" + // FleetNoneWaiting: the link named no proposal (the Attention notice's) + // and none waits now. + FleetNoneWaiting = "No proposal is waiting now" +) + +// fleetFocus is v as a fleet link asked for it (?fleet=proposed&proposal=id): +// its Proposed group open (on a phone, its sheet), and the proposal id +// highlighted — or, when id no longer waits, the line saying so and the newest +// waiting one highlighted. id 0 highlights the newest. A card with no +// Proposed group (fleet proposals off, no digest) is left as it is. +func (s *Server) fleetFocus(ctx context.Context, v *ui.FleetDigestView, id int64) { + for i := range v.Groups { + gr := &v.Groups[i] + if gr.Key != ui.FleetGroupProposed { + continue + } + v.OpenGroup = ui.FleetGroupProposed + at := -1 + for j, p := range gr.Proposals { + if id > 0 && p.ID == id { + at = j + } + } + if at < 0 && id > 0 { + gr.Gone, gr.GoneAt = s.fleetGone(ctx, id) + } + // The cards are oldest first: the newest is the last. + if at < 0 && len(gr.Proposals) > 0 { + at = len(gr.Proposals) - 1 + } + if at >= 0 { + gr.Proposals[at].Highlight = true + } else if gr.Gone == "" { + gr.Gone = FleetNoneWaiting + } + return + } +} + +// fleetGone is why proposal id, not drawn as waiting, no longer waits, and +// when (zero when the row cannot be read as the principal's). +func (s *Server) fleetGone(ctx context.Context, id int64) (string, time.Time) { + a, err := s.ext.FleetActions.GetAction(ctx, id) + if err != nil || a.Owner != requestOwner(ctx) { + return FleetGoneUnknown, time.Time{} + } + switch { + case a.State == fleet.StateExpired && a.Outcome == fleetTTLOutcome: + // Its 12 h passed: then, not when a draw next noticed and marked it. + return FleetGoneExpired, fleet.ExpiresAt(a.CreatedAt) + case a.State == fleet.StateExpired: + // Its session moved on: noticed (and marked) by a draw or the pass. + return FleetGoneExpired, a.FinishedAt + case a.State == fleet.StateRejected: + return FleetGoneRejected, a.DecidedAt + case a.State == fleet.StateApproved || a.State == fleet.StateQueued || a.State == fleet.StateSent || a.State == fleet.StateFailed: + return FleetGoneApproved, a.DecidedAt + case a.State == fleet.Suppressed(fleet.GuardMovedOn): + return FleetGoneMovedOn, a.FinishedAt + } + return FleetGoneUnknown, time.Time{} +} + // fleetLabel is a proposal's session as a short line (for logs and notes). func fleetLabel(a fleet.Action) string { return strings.TrimSpace(firstNonBlank(a.Evidence.Label, firstNonBlank(a.Evidence.SubjectID, a.SubjectKey))) diff --git a/internal/api/fleet_digest.go b/internal/api/fleet_digest.go index baefac227..f8fc4cbaa 100644 --- a/internal/api/fleet_digest.go +++ b/internal/api/fleet_digest.go @@ -22,7 +22,9 @@ import ( // THE FLEET DIGEST CARD's routes (internal/ui fleet_digest.go; docs/chief.md // "Fleet digest"): // -// GET /ui/chief/fleet the card (?look=1: the panel was opened on it) +// GET /ui/chief/fleet the card (?look=1: the panel was opened on it; +// ?fleet=proposed[&proposal=]: a fleet link's +// arrival, fleetFocus) // GET /ui/chief/fleet/session one session's drill-in (?id=) // POST /ui/chief/fleet/chat the Fleet side chat, with a draft (about=) // @@ -127,6 +129,12 @@ func (s *Server) handleFleetDigest(w http.ResponseWriter, r *http.Request) { } } v := s.fleetDigestViewFor(ctx, baseline) + // A fleet link's arrival (ui.FleetProposalsURL, passed on by the panel + // script): the Proposed group open on the proposal it named. + if q := r.URL.Query(); q.Get(ui.FleetFocusParam) == ui.FleetGroupProposed { + id, _ := strconv.ParseInt(q.Get(ui.FleetProposalParam), 10, 64) + s.fleetFocus(ctx, &v, max(id, 0)) + } if err := ui.RenderFleetDigest(w, v); err != nil { s.logger.Printf("fleet digest: render: %v", err) } diff --git a/internal/api/fleet_push_body_test.go b/internal/api/fleet_push_body_test.go new file mode 100644 index 000000000..272c0ebd4 --- /dev/null +++ b/internal/api/fleet_push_body_test.go @@ -0,0 +1,57 @@ +package api + +import ( + "strings" + "testing" + + "github.com/ZacxDev/muster/internal/fleet" +) + +// TestThePushNamesEveryClass: every class a proposal can have (fleet.ClassVerb's) +// has the push's own question, naming the session once — none falls back to +// the generic line. +func TestThePushNamesEveryClass(t *testing.T) { + if len(fleetPushAsks) != len(fleet.ClassVerb) { + t.Errorf("%d push questions for %d classes", len(fleetPushAsks), len(fleet.ClassVerb)) + } + for class := range fleet.ClassVerb { + ask, ok := fleetPushAsks[class] + if !ok || strings.Count(ask, "%s") != 1 { + t.Errorf("class %q: push question %q", class, ask) + } + } +} + +// TestThePushBodyLiterals pins the push's words for the shapes the pg test +// does not drive: a wrap and a composed answer, the generic line when the +// newest could not be read (and its url naming no proposal), and a name with +// control and format characters. +func TestThePushBodyLiterals(t *testing.T) { + wrap := fleet.Action{ID: 41, Class: fleet.ClassWrap, Text: "Write your handoff (what is done, what is left, where), then stop.", + Reason: "its pull request merged", Evidence: fleet.Evidence{Label: "muster-asks-ux", SubjectID: "mirror:k-1"}} + cases := []struct { + n int + a fleet.Action + body, link string + }{ + {1, wrap, "Wrap 'muster-asks-ux'? Nothing is sent until you approve it.", "/tasks?chief=open&fleet=proposed&proposal=41"}, + {4, fleet.Action{ID: 7, Class: fleet.ClassAnswerComposed, Text: "Keep the old flag.", Evidence: fleet.Evidence{Label: "ledger-cleanup"}}, + "Answer 'ledger-cleanup'? +3 more. Nothing is sent until you approve them.", "/tasks?chief=open&fleet=proposed&proposal=7"}, + {2, fleet.Action{}, "Your chief proposed what to send your sessions. Nothing is sent until you approve it in the fleet digest.", + "/tasks?chief=open&fleet=proposed"}, + {1, fleet.Action{ID: 9, Class: fleet.ClassClose, Evidence: fleet.Evidence{Label: "a\x1b[2Jb​c\n d"}}, + "Close 'a [2Jb c d'? Nothing is sent until you approve it.", "/tasks?chief=open&fleet=proposed&proposal=9"}, + // No label: the card's own fallback, the session's fleet id. + {1, fleet.Action{ID: 3, Class: fleet.ClassContinue, SubjectKey: "k-3", Evidence: fleet.Evidence{SubjectID: "mirror:k-3"}}, + "Continue 'mirror:k-3'? Nothing is sent until you approve it.", "/tasks?chief=open&fleet=proposed&proposal=3"}, + } + for _, tc := range cases { + n := fleetPushNotification(tc.n, tc.a) + if n.Body != tc.body || n.Data["url"] != tc.link || len(n.Data) != 1 || n.AskActions || n.Tag != "fleet-proposals" { + t.Errorf("push(%d, %+v):\n body %q\n want %q\n data %v (want url %q)", tc.n, tc.a, n.Body, tc.body, n.Data, tc.link) + } + if tc.a.Text != "" && strings.Contains(n.Body, tc.a.Text) || tc.a.Reason != "" && strings.Contains(n.Body, tc.a.Reason) { + t.Errorf("the body carries the proposal's text or reason: %q", n.Body) + } + } +} diff --git a/internal/api/fleet_push_link_pg_test.go b/internal/api/fleet_push_link_pg_test.go new file mode 100644 index 000000000..40572d788 --- /dev/null +++ b/internal/api/fleet_push_link_pg_test.go @@ -0,0 +1,271 @@ +package api + +import ( + "net/http" + "net/http/httptest" + "regexp" + "strconv" + "strings" + "testing" + "time" + + "github.com/ZacxDev/muster/internal/attention" + "github.com/ZacxDev/muster/internal/fleet" + "github.com/ZacxDev/muster/internal/focus" + "github.com/ZacxDev/muster/internal/push" +) + +// THE FLEET PUSH'S TAP, AND WHAT IT SAYS (docs/chief.md "Fleet proposals"). +// +// Before: the batched push said "Your chief proposed what to send your +// sessions…" (no proposal, no session) and opened `/?chief=open` — which home +// redirected to the chief's own chat page, dropping the parameter, so the +// panel and its digest never opened; 18 of 19 proposals expired undecided. +// Its Attention notice linked nowhere. Every name below is invented. + +// pushesTo waits for owner's n-th push and returns them all. +func pushesTo(t *testing.T, cp *morningPush, owner int64, n int) []push.Payload { + t.Helper() + deadline := time.Now().Add(5 * time.Second) + for { + got := cp.to(owner) + if len(got) >= n { + return got + } + if time.Now().After(deadline) { + t.Fatalf("waited for push %d; got %d: %+v", n, len(got), got) + } + time.Sleep(10 * time.Millisecond) + } +} + +// TestTheFleetPushNamesTheNewestProposalAndOpensIt: the push names what the +// newest proposal is and the session it is for (its name as the digest card +// shows it, capped, with no straight quote and no control character), "+N +// more." for the others — never a message's text or its reason — and its tap +// opens the digest's Proposed group on that proposal. No action, the tag that +// replaces it. +// +// Red at origin/main: the body was the generic sentence and the url +// "/?chief=open". +func TestTheFleetPushNamesTheNewestProposalAndOpensIt(t *testing.T) { + f := newProposeFixture(t) + cp := &morningPush{} + f.srv.ext.Push = cp + s1, k1, _ := f.stopped(t, f.owner) + if _, err := f.focus.SetManualName(f.asOwner, focus.MirrorSubject(k1), "Billing migration"); err != nil { + t.Fatal(err) + } + first := f.propose(t, s1, fleet.ClassContinue) + f.pass() + p := pushesTo(t, cp, f.owner, 1)[0] + if p.Title != "1 proposal waiting" || p.Tag != "fleet-proposals" || p.AskActions || p.Ask != nil { + t.Fatalf("the push: %+v", p) + } + if want := "Continue 'Billing migration'? Nothing is sent until you approve it."; p.Body != want { + t.Errorf("the body: %q\nwant %q", p.Body, want) + } + if want := "/tasks?chief=open&fleet=proposed&proposal=" + strconv.FormatInt(first, 10); p.Data["url"] != want || len(p.Data) != 1 { + t.Errorf("the url: %v, want only url=%q", p.Data, want) + } + + // A second, on a session whose name is long and has a quote and a tab: + // the newest is named, cut to 40 runes, and the first is "+1 more". + s2, k2, _ := f.stopped(t, f.owner) + if _, err := f.focus.SetManualName(f.asOwner, focus.MirrorSubject(k2), "Bob's ledger\treconciliation for the quarterly close"); err != nil { + t.Fatal(err) + } + second := f.propose(t, s2, fleet.ClassStopNote) + dateBackPush(t, f, 31*time.Minute) + f.pass() + p = pushesTo(t, cp, f.owner, 2)[1] + if p.Title != "2 proposals waiting" { + t.Errorf("the title: %q", p.Title) + } + if want := "Stop 'Bob’s ledger reconciliation for the qua…' after this step? +1 more. Nothing is sent until you approve them."; p.Body != want { + t.Errorf("the body: %q\nwant %q", p.Body, want) + } + if want := "/tasks?chief=open&fleet=proposed&proposal=" + strconv.FormatInt(second, 10); p.Data["url"] != want { + t.Errorf("the url: %q, want %q", p.Data["url"], want) + } + // No session content: neither proposal's text nor its reason. + for _, id := range []int64{first, second} { + a := f.action(t, id) + if strings.Contains(p.Body, a.Text) || strings.Contains(p.Body, a.Reason) { + t.Errorf("the body carries proposal %d's text or reason: %q", id, p.Body) + } + } +} + +// TestAChiefOpenLinkReachesThePanel: `/?chief=open…` (a push already on a +// phone) goes to the board with its query — whose shell draws the chief +// panel — not to the chief's own chat page, which has none; a plain `/` is +// still the chief's chat. +// +// Red at origin/main: 302 to the chief's chat page, the query dropped. +func TestAChiefOpenLinkReachesThePanel(t *testing.T) { + withChief := &homeAgents{rows: homeRows(true), latest: map[int64]int64{homeChiefID: homeChiefSess, homeWorkerID: 55}} + s, h := homeServer(t, withChief) + for path, want := range map[string]string{ + "/?chief=open": "/tasks?chief=open", + "/?chief=open&fleet=proposed&proposal=9": "/tasks?chief=open&fleet=proposed&proposal=9", + "/": chiefHref, + } { + rec := homeGet(s, h, path, nil) + if rec.Code != http.StatusFound || rec.Header().Get("Location") != want { + t.Errorf("GET %s = %d → %q, want 302 → %q", path, rec.Code, rec.Header().Get("Location"), want) + } + } + // Where it lands draws the panel (the chief's chat page does not). + rec := homeGet(s, h, "/tasks?chief=open&fleet=proposed&proposal=9", nil) + if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `id="chief-panel"`) || !strings.Contains(rec.Body.String(), `id="panel-tasks"`) { + t.Errorf("GET the push's landing = %d; want 200, the board with the chief panel", rec.Code) + } +} + +// TestTheFleetNoticeLinksTheDigest: the "N proposals waiting" Attention +// item's link (its card's head) and its tap open the digest's Proposed group. +// +// Red at origin/main: no link at all, and the tap opened the notice's own page. +func TestTheFleetNoticeLinksTheDigest(t *testing.T) { + f := newProposeFixture(t) + s1, _, _ := f.stopped(t, f.owner) + f.propose(t, s1, fleet.ClassContinue) + f.pass() + open, err := f.srv.ext.Attention.Open(f.asOwner) + if err != nil { + t.Fatal(err) + } + var notice attention.Ask + for _, a := range open { + if a.Kind == attention.KindNotice && a.Asker.Label == "Fleet proposals" { + notice = a + } + } + if notice.ID == 0 { + t.Fatalf("no fleet notice among %+v", open) + } + const want = "/tasks?chief=open&fleet=proposed" + items := []attentionItem{f.srv.askItemNow(f.asOwner, notice)} + f.srv.withAskBoxes(f.asOwner, items, true) + if items[0].sessionLink != want { + t.Errorf("the notice's link: %q, want %q", items[0].sessionLink, want) + } + if got := f.srv.openTarget(f.asOwner, attentionAskKey(notice.ID)); got != want { + t.Errorf("the notice's tap: %q, want %q", got, want) + } +} + +// fleetCardFor is the digest card GET'd with query, as the owner. +func (f *proposeFixture) fleetCardFor(t *testing.T, query string) string { + t.Helper() + req := httptest.NewRequest(http.MethodGet, "/ui/chief/fleet"+query, nil) + rec := httptest.NewRecorder() + f.srv.handleFleetDigest(rec, req.WithContext(f.asOwner)) + if rec.Code != http.StatusOK { + t.Fatalf("GET the card%s: %d %s", query, rec.Code, rec.Body.String()) + } + return rec.Body.String() +} + +var ( + proposedDetails = regexp.MustCompile(`
]*>`) + proposedSheet = regexp.MustCompile(`
]*>`) + highlightedCards = regexp.MustCompile(`
  • ]*data-fleet-highlight[^>]*>`) + goneLine = regexp.MustCompile(`

    ]*>([^<]*)(?:)?([^<]*)

    `) +) + +// TestAFleetLinkOpensTheProposedGroupOnItsProposal: the card asked for with +// ?fleet=proposed&proposal= draws the Proposed group open (the desktop's +//
    , the phone's sheet) and that proposal highlighted; one that no +// longer waits draws the line saying so — rejected, expired at its 12 h — with +// the newest waiting one highlighted, or none. Without the parameter, nothing +// is open or highlighted. Each card says when it expires. +// +// Red at origin/main: the parameter was ignored (the group drawn closed). +func TestAFleetLinkOpensTheProposedGroupOnItsProposal(t *testing.T) { + f := newProposeFixture(t) + s1, _, _ := f.stopped(t, f.owner) + s2, _, _ := f.stopped(t, f.owner) + s3, _, _ := f.stopped(t, f.owner) + older := f.propose(t, s1, fleet.ClassContinue) + f.at = f.at.Add(time.Minute) + middle := f.propose(t, s2, fleet.ClassHandoff) + f.at = f.at.Add(time.Minute) + newest := f.propose(t, s3, fleet.ClassStopNote) + id := func(n int64) string { return strconv.FormatInt(n, 10) } + highlighted := func(card string) []string { + var out []string + for _, m := range highlightedCards.FindAllStringSubmatch(card, -1) { + out = append(out, m[1]) + } + return out + } + open := func(t *testing.T, card string) { + t.Helper() + d, s := proposedDetails.FindString(card), proposedSheet.FindString(card) + if !strings.Contains(d, ` open=""`) || s == "" || strings.Contains(s, ` hidden=""`) { + t.Errorf("the Proposed group is not open: details %q, sheet %q", d, s) + } + } + + // Control: no parameter, nothing open or highlighted. + card := f.fleetCardFor(t, "") + if d := proposedDetails.FindString(card); strings.Contains(d, ` open=""`) || len(highlighted(card)) != 0 || goneLine.MatchString(card) { + t.Fatalf("a plain card: details %q, highlighted %v", d, highlighted(card)) + } + // Each card says when it expires: 12 h after it was made, the clock in UTC + // until the panel script draws the reader's. + if !strings.Contains(card, `expires in 11h (