From 3e267d486390c870df44559df5011c38f9dea987 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:21:44 +0000 Subject: [PATCH 01/19] Chat: never drop a Claude turn's lifecycle frames; end a runner turn whose end was lost emit now waits (bounded) for a full watcher to accept step and resync frames instead of dropping them. The turn runner also ends its turn once a harness that tracks its turn state has reported idle for the settle period and its probe confirms, asking clients to resync. Co-Authored-By: Claude Opus 5.5 --- internal/claude/claude.go | 25 +++++++ internal/claude/emit_lifecycle_test.go | 61 +++++++++++++++++ internal/server/chat_lost_end_test.go | 90 +++++++++++++++++++++++++ internal/server/chat_manager.go | 14 ++++ internal/server/chat_queue.go | 16 +++++ internal/server/chat_room.go | 92 +++++++++++++++++++++++++- 6 files changed, 295 insertions(+), 3 deletions(-) create mode 100644 internal/claude/emit_lifecycle_test.go create mode 100644 internal/server/chat_lost_end_test.go diff --git a/internal/claude/claude.go b/internal/claude/claude.go index 6ef01238..59b66db1 100644 --- a/internal/claude/claude.go +++ b/internal/claude/claude.go @@ -474,14 +474,39 @@ func (s *session) emit(frame protocol.ChatEventFrame) { targets = append(targets, ch) } s.mu.Unlock() + lifecycle := frameIsLifecycle(frame) for _, ch := range targets { select { case ch <- frame: + continue default: } + if !lifecycle { + continue + } + // A full watcher may lose a delta (the hub repairs text from + // history), but never a step start or end: a lost end leaves the + // turn "working" forever. Wait, bounded, for the watcher to drain. + timer := time.NewTimer(lifecycleDeliveryTimeout) + select { + case ch <- frame: + case <-timer.C: + log.Printf("claude session %s: a watcher did not accept the %s frame within %s; it was dropped", s.id, frame.Kind, lifecycleDeliveryTimeout) + } + timer.Stop() } } +// lifecycleDeliveryTimeout bounds how long emit waits for a full watcher to +// accept a turn lifecycle frame before it gives up on that watcher. +var lifecycleDeliveryTimeout = 5 * time.Second + +// frameIsLifecycle reports whether a frame changes the turn's state, so it +// must reach every watcher even when that watcher's buffer is full. +func frameIsLifecycle(frame protocol.ChatEventFrame) bool { + return frame.Kind == protocol.ChatEventStep || frame.Kind == protocol.ChatEventResync +} + func (s *session) subscribe() chan protocol.ChatEventFrame { ch := make(chan protocol.ChatEventFrame, 256) s.mu.Lock() diff --git a/internal/claude/emit_lifecycle_test.go b/internal/claude/emit_lifecycle_test.go new file mode 100644 index 00000000..6577e5c3 --- /dev/null +++ b/internal/claude/emit_lifecycle_test.go @@ -0,0 +1,61 @@ +package claude + +import ( + "context" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// A watcher whose buffer is full of streamed text may lose a delta, but never +// the turn's end: a lost end left the chat "working" forever. +func TestEmitDeliversTheTurnEndToAFullWatcher(t *testing.T) { + c := newChat(context.Background()) + t.Cleanup(c.cancel) + s := c.sessionFor("ses_full", t.TempDir()) + ch := s.subscribe() + defer s.unsubscribe(ch) + for len(ch) < cap(ch) { + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}}) + } + emitted := make(chan struct{}) + go func() { + defer close(emitted) + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}}) + }() + // The watcher is slow, not gone: it drains only after the end was emitted. + time.Sleep(100 * time.Millisecond) + deadline := time.After(3 * time.Second) + for { + select { + case frame := <-ch: + if frame.Kind == protocol.ChatEventStep && frame.Step != nil && frame.Step.Status == protocol.ChatStepEnded { + <-emitted + return + } + case <-deadline: + t.Fatal("the turn end never reached the full watcher") + } + } +} + +// A watcher that never drains does not hold the CLI reader forever. +func TestEmitGivesUpOnAStuckWatcher(t *testing.T) { + prior := lifecycleDeliveryTimeout + lifecycleDeliveryTimeout = 50 * time.Millisecond + t.Cleanup(func() { lifecycleDeliveryTimeout = prior }) + c := newChat(context.Background()) + t.Cleanup(c.cancel) + s := c.sessionFor("ses_stuck", t.TempDir()) + ch := s.subscribe() + defer s.unsubscribe(ch) + for len(ch) < cap(ch) { + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventText, Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "p", Text: "x"}}) + } + start := time.Now() + s.emit(protocol.ChatEventFrame{Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_1"}}) + if waited := time.Since(start); waited > 2*time.Second { + t.Fatalf("emit blocked %s on a stuck watcher", waited) + } +} diff --git a/internal/server/chat_lost_end_test.go b/internal/server/chat_lost_end_test.go new file mode 100644 index 00000000..99db772e --- /dev/null +++ b/internal/server/chat_lost_end_test.go @@ -0,0 +1,90 @@ +package server + +import ( + "context" + "path/filepath" + "sync" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// reportingChat is an observedChat that also reports its turn state without +// I/O, as Claude Code does. +type reportingChat struct { + *observedChat + rmu sync.Mutex + running bool +} + +func (c *reportingChat) TurnRunning(string) bool { + c.rmu.Lock() + defer c.rmu.Unlock() + return c.running +} + +// Prompt starts a turn, as Claude Code's does before it returns. +func (c *reportingChat) Prompt(ctx context.Context, sessionID, text string) error { + if err := c.observedChat.Prompt(ctx, sessionID, text); err != nil { + return err + } + c.setRunning(true) + return nil +} + +func (c *reportingChat) setRunning(running bool) { + c.rmu.Lock() + c.running = running + c.rmu.Unlock() +} + +// The live incident: a Claude turn's end frame was dropped on the way (a full +// watcher buffer), so the room's own turn stayed "working" forever and every +// later prompt queued behind it. Once the harness reports itself idle for the +// settle period and its probe agrees, the turn is ended, the client told to +// resync, and the queued prompt delivered. While it reports running, it waits. +func TestChatRunnerEndsItsTurnWhoseEndFrameWasLost(t *testing.T) { + fastUnattended(t) + fastStaleTurnSettle(t) + t.Setenv("PIPELINES_NTFY_URL", "") + store := openQueueStore(t, filepath.Join(t.TempDir(), "queue.db")) + broker := &reportingChat{observedChat: newObservedChat()} + server := startQueueServer(t, broker, store) + conn := dialChatConn(t, server.ctx, server.srv) + broker.setProbe(true) + sendPrompt(t, server.ctx, conn, "p1", "build it", "op-1") + waitFor(t, "first prompt", func() bool { return broker.promptCount() == 1 }) + broker.push(stepFrameFor(protocol.ChatStepStarted, "turn_1")) + waitStepFrame(t, server.ctx, conn, protocol.ChatStepStarted, "turn_1") + if ack := sendPrompt(t, server.ctx, conn, "p2", "continue", "op-2"); !ack.ChatQueued { + t.Fatalf("second prompt was not queued behind the running turn: %+v", ack) + } + time.Sleep(4 * chatQueueStaleTurnSettle) + if n := broker.promptCount(); n != 1 { + t.Fatalf("prompt delivered while the harness reports its turn running: %v", broker.promptTexts()) + } + // The turn ends in the harness, but its end frame never arrives. + broker.setRunning(false) + broker.setProbe(false) + sawResync := false + for { + message := readChatMessage(t, server.ctx, conn) + if message.Type != protocol.ChatEvent || message.ChatEvent == nil { + continue + } + if message.ChatEvent.Kind == protocol.ChatEventResync { + sawResync = true + } + if step := message.ChatEvent.Step; step != nil && step.Status == protocol.ChatStepEnded && step.TurnID == "turn_1" { + break + } + } + if !sawResync { + t.Fatal("the client was not told to resync after the lost end") + } + waitFor(t, "queued prompt delivered after the lost end", func() bool { return broker.promptCount() == 2 }) + if texts := broker.promptTexts(); texts[1] != "continue" { + t.Fatalf("delivered = %v", texts) + } +} diff --git a/internal/server/chat_manager.go b/internal/server/chat_manager.go index 533d5d9a..d5340735 100644 --- a/internal/server/chat_manager.go +++ b/internal/server/chat_manager.go @@ -834,6 +834,20 @@ func (m *chatManager) TurnRunning(sessionID string) bool { return ok && reporter.TurnRunning(sessionID) } +// TracksTurnState reports whether the routed harness reports its own turn +// state through TurnRunning (Claude Code does; OpenCode and Codex are probed). +func (m *chatManager) TracksTurnState(sessionID string) bool { + m.mu.Lock() + backend := m.cache[sessionID] + m.mu.Unlock() + adapter := m.opencode + if backend != "" && backend != "opencode" { + adapter = m.attached(backend) + } + _, ok := adapter.(chatTurnReporter) + return ok +} + // ProbeTurn asks the session's own harness whether a turn is in flight. It is // the server-start probe (chat_unattended.go): a harness that can be asked // (OpenCode, Codex) is asked; otherwise its in-memory state is used, which for diff --git a/internal/server/chat_queue.go b/internal/server/chat_queue.go index 2f5d26a6..1a266e7c 100644 --- a/internal/server/chat_queue.go +++ b/internal/server/chat_queue.go @@ -190,6 +190,22 @@ func errChatQueueFull(sessionID string) error { return errors.New("session " + sessionID + " already has the maximum number of prompts queued") } +// chatTurnTracker is implemented by a broker that routes to several harnesses +// and knows whether the one serving a session reports its own turn state. +type chatTurnTracker interface { + TracksTurnState(sessionID string) bool +} + +// brokerTracksTurns reports whether brokerTurnRunning's answer for sessionID +// comes from a harness that tracks its turn, rather than a constant false. +func brokerTracksTurns(broker chatBroker, sessionID string) bool { + if tracker, ok := broker.(chatTurnTracker); ok { + return tracker.TracksTurnState(sessionID) + } + _, ok := broker.(chatTurnReporter) + return ok +} + // brokerTurnRunning asks a harness that knows its own turn state without I/O. func brokerTurnRunning(broker chatBroker, sessionID string) bool { reporter, ok := broker.(chatTurnReporter) diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index 85a69615..a6459c59 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -925,10 +925,96 @@ func (h *chatHub) runTurn(room *chatRoom, p *chatQueuedPrompt, done chan struct{ // Start the approval poller once, after the first ack, so a pending request // is surfaced after the prompt is acknowledged and shared with every client. h.startRoomPoller(room, broker) - select { - case <-done: - case <-room.ctx.Done(): + h.awaitTurnEnd(room, broker, done) +} + +// awaitTurnEnd waits for the turn runner's turn to end. Its end normally +// arrives as a step frame; the safety net covers an end that was lost on the +// way (a full watcher buffer, a stream that reconnected): once a harness that +// tracks its own turn state has reported itself idle for the settle period +// (chatQueueStaleTurnSettle) and its own probe confirms no turn is in flight, +// the turn is ended here and attached clients re-read the history. A harness +// that cannot report or be probed is never second-guessed. +func (h *chatHub) awaitTurnEnd(room *chatRoom, broker chatBroker, done chan struct{}) { + prober, probes := broker.(chatTurnProber) + if !probes || !brokerTracksTurns(broker, room.sessionID) { + select { + case <-done: + case <-room.ctx.Done(): + } + return } + settle := h.unattended.staleTurn + if settle <= 0 { + settle = 10 * time.Second + } + ticker := time.NewTicker(min(chatQueueBusyPoll, settle/4)) + defer ticker.Stop() + var idleSince time.Time + for { + select { + case <-done: + return + case <-room.ctx.Done(): + return + case <-ticker.C: + } + if brokerTurnRunning(broker, room.sessionID) { + idleSince = time.Time{} + continue + } + now := h.clock() + if idleSince.IsZero() { + idleSince = now + } + if now.Sub(idleSince) < settle { + continue + } + probeCtx, cancel := context.WithTimeout(room.ctx, 5*time.Second) + busy, err := prober.ProbeTurn(probeCtx, room.sessionID) + cancel() + if err != nil || busy { + // Look again only after another settle period. + idleSince = h.clock() + continue + } + if h.endLostTurn(room, done, now.Sub(idleSince)) { + return + } + } +} + +// endLostTurn ends the runner's turn whose end frame never arrived, exactly +// as that frame would have, and asks attached clients to resync. It reports +// false when the turn already ended (or the room was released) meanwhile. +func (h *chatHub) endLostTurn(room *chatRoom, done chan struct{}, idle time.Duration) bool { + h.mu.Lock() + if h.rooms[room.sessionID] != room || room.ctx.Err() != nil || room.turnDone != done { + h.mu.Unlock() + return true + } + log.Printf("chat session %s: the harness reports no turn running for %s but the turn %q never reported its end; ending it", + room.sessionID, idle.Round(time.Second), room.nativeTurnID) + end := protocol.ChatEventFrame{SessionID: room.sessionID, NativeTurnID: room.nativeTurnID, Kind: protocol.ChatEventStep, + Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: room.nativeTurnID}} + priorStep := h.turnLocked(room.sessionID).step + h.applyLocked(end) + h.noteTurnDiffLocked(room, end) + h.noteReplyAttentionLocked(priorStep, end) + h.finishTurnLocked(room) + resync := protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventResync} + var slow []*chatSub + for _, sub := range room.subs { + if !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) || + !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end}) { + slow = append(slow, sub) + } + } + h.mu.Unlock() + for _, sub := range slow { + sub.close() + } + return true } // endRoomTurn releases the turn slot after a prompt that never entered flight, From e649eced105c052485721d82385c54b2dccae1dc Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:23:39 +0000 Subject: [PATCH 02/19] Runs: one uninterruptible stage session no longer disables the runner Start-up recovery used to fail the whole runner when any previously active stage session could not be confirmed stopped. That run alone is now marked interrupted with a diagnostic naming the session and error. A Pi owner whose process and process group are gone counts as stopped without its quiescence receipt (it crashed), as the Claude stage path already did. Co-Authored-By: Claude Opus 5.5 --- internal/server/run_reattach_test.go | 34 ++++++++++++++++++++++++++++ internal/server/runner.go | 10 +++++++- internal/stage/pi.go | 14 ++++++++++-- internal/stage/pi_cleanup_test.go | 28 +++++++++++++++++++++++ 4 files changed, 83 insertions(+), 3 deletions(-) diff --git a/internal/server/run_reattach_test.go b/internal/server/run_reattach_test.go index 047170ca..1f330347 100644 --- a/internal/server/run_reattach_test.go +++ b/internal/server/run_reattach_test.go @@ -194,6 +194,40 @@ func TestStageRunWithHarnessGoneFallsBackWithReason(t *testing.T) { } } +// TestUninterruptibleStageSessionInterruptsOnlyItsRun: one stage session that +// start-up cannot confirm stopped (a crashed Pi owner, a missing Claude +// evidence directory) used to fail the whole runner, disabling every run. +// Now only its run is interrupted, naming why, and the runner starts. +func TestUninterruptibleStageSessionInterruptsOnlyItsRun(t *testing.T) { + seamRestartRecovery(t, nil) + interruptRecoveredSession = func(context.Context, pipeline.SessionOwner) error { + return fmt.Errorf("retained Pi owner: %w", stage.ErrStageCleanup) + } + f := stopMidStage(t, func(ctx context.Context, s *pipeline.Store, id int64) (stage.Result, error) { + if err := s.RunSession(context.Background(), id, 1, "ses_pi", true, "pi", "/nonexistent/pi-ref"); err != nil { + return stage.Result{}, err + } + <-ctx.Done() + return stage.Result{}, stage.ErrDetached + }) + r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) { + t.Error("an interrupted run executed again") + return stage.Result{}, nil + }) + r.reattachRuns() + r.wg.Wait() + d, err := s.GetRun(context.Background(), f.runID) + if err != nil { + t.Fatal(err) + } + if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "could not be confirmed stopped") || !strings.Contains(d.Diagnostic, "ses_pi") { + t.Fatalf("uninterruptible session's run lacks a clear reason: status=%s run=%q", d.Status, d.Diagnostic) + } + if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 { + t.Fatalf("the interrupted run's session still blocks recovery at the next start: %+v", owners) + } +} + // TestStageNotYetAdmittedStartsAgainAfterRestart: a visit the stopped server // had begun but not handed to any session is started again, nothing replayed. func TestStageNotYetAdmittedStartsAgainAfterRestart(t *testing.T) { diff --git a/internal/server/runner.go b/internal/server/runner.go index 6ea8e8e1..914560c8 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -152,7 +152,15 @@ func newRunnerReattaching(ctx context.Context, s *pipeline.Store, artifactsRoot cancel() } if err != nil { - return nil, fmt.Errorf("cannot interrupt previously active agent %s: %w", owner.ID, err) + // One session that cannot be confirmed stopped must not disable + // every run: interrupt only its run, saying why, and go on. + reason := fmt.Sprintf("its previous %s stage agent (session %s) could not be confirmed stopped (%v); check for a leftover agent process before reusing the workspace", owner.Backend, owner.ID, err) + if prior := reasons[owner.RunID]; prior != "" { + reason = prior + "; " + reason + } + reasons[owner.RunID] = reason + log.Printf("run %d: cannot interrupt previously active agent %s: %v; the run is marked interrupted", owner.RunID, owner.ID, err) + continue } if err := s.ConfirmRecoveredSession(ctx, owner); err != nil { return nil, err diff --git a/internal/stage/pi.go b/internal/stage/pi.go index 7f05b3e8..4adc94dd 100644 --- a/internal/stage/pi.go +++ b/internal/stage/pi.go @@ -608,7 +608,9 @@ func piResult(data []byte) (string, error) { } // InterruptPi expires the retained lease. The explicit extension aborts tools and -// marks quiescence before shutting down; without that receipt recovery fails closed. +// marks quiescence before shutting down. An owner whose process and process +// group are both gone (a crash, a reboot) has nothing left to stop, so it +// counts as interrupted without that receipt; otherwise recovery fails closed. func InterruptPi(ctx context.Context, reference string) error { if !filepath.IsAbs(reference) { return fmt.Errorf("invalid retained Pi reference") @@ -623,6 +625,12 @@ func InterruptPi(ctx context.Context, reference string) error { if json.Unmarshal(data, &owner) != nil || owner.PID <= 1 { return errors.Join(fmt.Errorf("invalid retained Pi owner"), ErrStageCleanup) } + gone := func() bool { + return errors.Is(syscall.Kill(owner.PID, 0), syscall.ESRCH) && errors.Is(syscall.Kill(-owner.PID, 0), syscall.ESRCH) + } + if gone() { + return nil + } old := time.Unix(0, 0) if err := os.Chtimes(filepath.Join(reference, "lease"), old, old); err != nil { return err @@ -630,7 +638,9 @@ func InterruptPi(ctx context.Context, reference string) error { ticker := time.NewTicker(100 * time.Millisecond) defer ticker.Stop() for { - if data, err := os.ReadFile(filepath.Join(reference, "quiescent")); err == nil && string(data) == "quiescent" && errors.Is(syscall.Kill(owner.PID, 0), syscall.ESRCH) && errors.Is(syscall.Kill(-owner.PID, 0), syscall.ESRCH) { + // The receipt is written just before a clean exit; a process that + // died without it is still gone. + if gone() { return nil } select { diff --git a/internal/stage/pi_cleanup_test.go b/internal/stage/pi_cleanup_test.go index 9f22cc59..e9ec181d 100644 --- a/internal/stage/pi_cleanup_test.go +++ b/internal/stage/pi_cleanup_test.go @@ -42,3 +42,31 @@ func TestPiReceiptRequiresProcessExit(t *testing.T) { t.Fatal("confirmed process exit not accepted", err) } } + +// A Pi owner that crashed never wrote its quiescence receipt; with its process +// and process group gone there is nothing left to stop, so recovery must not +// wait out its timeout and fail. +func TestPiOwnerGoneWithoutReceiptCountsAsInterrupted(t *testing.T) { + cmd := exec.Command("sleep", "5") + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + pid := cmd.Process.Pid + if err := cmd.Process.Kill(); err != nil { + t.Fatal(err) + } + cmd.Wait() + dir := t.TempDir() + owner, _ := json.Marshal(map[string]any{"pid": pid}) + for name, data := range map[string][]byte{"owner.json": owner, "lease": []byte("lease")} { + if err := os.WriteFile(filepath.Join(dir, name), data, 0600); err != nil { + t.Fatal(err) + } + } + ctx, cancel := context.WithTimeout(context.Background(), time.Second) + defer cancel() + if err := InterruptPi(ctx, dir); err != nil { + t.Fatal("a crashed owner was not accepted as gone:", err) + } +} From 32c9c6b1dfc3b2b5f4e6797679c82d946b40f06d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:25:09 +0000 Subject: [PATCH 03/19] Server: chat:-scoped find-in-chat search returning every occurrence, paged A kind=chat search with scope chat: returns one hit per text-part occurrence (message id, part, UTF-16 offset/length), newest message first, paged by cursor (a reply's next_cursor or a chat_messages next_cursor), with optional case-sensitive matching. Scoped and global chat searches no longer cancel each other on one connection. Co-Authored-By: Claude Opus 5.5 --- internal/protocol/search.go | 26 +++ internal/server/search_chat_scoped.go | 208 +++++++++++++++++++++ internal/server/search_chat_scoped_test.go | 147 +++++++++++++++ internal/server/search_chats.go | 7 + internal/server/websocket.go | 14 +- 5 files changed, 399 insertions(+), 3 deletions(-) create mode 100644 internal/server/search_chat_scoped.go create mode 100644 internal/server/search_chat_scoped_test.go diff --git a/internal/protocol/search.go b/internal/protocol/search.go index 9dae88e8..6724bdd6 100644 --- a/internal/protocol/search.go +++ b/internal/protocol/search.go @@ -84,8 +84,22 @@ type SearchRequest struct { // and private/ scratch, see ClassifyArtifacts). Off by default: artifact // search surfaces only deliverables. IncludeDebug bool `json:"include_debug,omitempty"` + // Scope narrows a kind=chat search to one chat ("chat:"). + // A scoped search returns every text-part occurrence of Query in that + // chat's messages, newest message first, one result per occurrence with + // its message id, part index and offset, paged by Cursor/NextCursor. + Scope string `json:"scope,omitempty"` + // Cursor continues a scoped chat search: a previous reply's NextCursor, + // or a chat_messages next_cursor to start just before the messages a + // client already holds. Empty starts at the newest message. + Cursor string `json:"cursor,omitempty"` + // CaseSensitive makes a scoped chat search match case exactly. + CaseSensitive bool `json:"case_sensitive,omitempty"` } +// SearchChatScope is a scoped chat search's Scope for one session. +func SearchChatScope(sessionID string) string { return "chat:" + sessionID } + // SearchResponse is the bounded set of matches. Results are ordered by recency // descending (a chat's last use for kind chat), numeric entity/visit IDs // descending, then target ascending, before the cap applies; Score records the @@ -105,6 +119,11 @@ type SearchResponse struct { // ScannedChats is how many chat transcripts a chat search read message // text from (kind chat only); additive, so older peers ignore it. ScannedChats int `json:"scanned_chats,omitempty"` + // NextCursor continues a scoped chat search that stopped before the + // chat's oldest message (result cap or scan budget); empty when done. + NextCursor string `json:"next_cursor,omitempty"` + // ScannedMessages is how many messages a scoped chat search read. + ScannedMessages int `json:"scanned_messages,omitempty"` } // SearchResult is one typed, navigable match. Kind selects which payload is @@ -202,6 +221,13 @@ type SearchChat struct { MessageID string `json:"message_id,omitempty"` Role string `json:"role,omitempty"` Snippet string `json:"snippet,omitempty"` + // Part and Offset locate one occurrence in a scoped chat search: the + // index of the text part in the message's parts and the match's start + // in that part's text, in UTF-16 code units (as a browser or Dart string + // counts). Length is the match's length in the same units. + Part int `json:"part,omitempty"` + Offset int `json:"offset,omitempty"` + Length int `json:"length,omitempty"` } // SearchChatTarget is a chat hit's target token. diff --git a/internal/server/search_chat_scoped.go b/internal/server/search_chat_scoped.go new file mode 100644 index 00000000..8ed0e7a8 --- /dev/null +++ b/internal/server/search_chat_scoped.go @@ -0,0 +1,208 @@ +package server + +import ( + "context" + "errors" + "strconv" + "strings" + "time" + "unicode" + "unicode/utf16" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// Scoped chat search ("find in chat"): every occurrence of a query in one +// chat's message text, newest message first, paged. A client uses it to count +// and reach matches in history it has not loaded yet. +const ( + // scopedChatPageMessages is how many messages one broker read returns. + scopedChatPageMessages = 200 + // scopedChatMaxMessages bounds the messages one scoped request reads; + // a longer history continues through NextCursor. + scopedChatMaxMessages = 2000 +) + +// scopedChatBudget bounds how long one scoped request reads history before it +// replies with what it found and a cursor. A variable so a test can shorten it. +var scopedChatBudget = 2 * time.Second + +// scopedChatSession returns the session id a chat search's Scope names, or "" +// when the request is not scoped. +func scopedChatSession(req protocol.SearchRequest) string { + scope := strings.TrimSpace(req.Scope) + if scope == "" { + return "" + } + return strings.TrimPrefix(scope, "chat:") +} + +// scopedCursor is where a scoped search resumes: the broker's history cursor +// for a page (empty for the newest) and how many of that page's newest +// messages were already searched. It travels as "|"; a +// cursor without the separator is a chat_messages next_cursor. +type scopedCursor struct { + history string + skip int +} + +func parseScopedCursor(value string) scopedCursor { + skip, history, found := strings.Cut(value, "|") + if !found { + return scopedCursor{history: value} + } + n, err := strconv.Atoi(skip) + if err != nil || n < 0 { + return scopedCursor{history: history} + } + return scopedCursor{history: history, skip: n} +} + +func (c scopedCursor) String() string { return strconv.Itoa(c.skip) + "|" + c.history } + +// searchChatScoped answers a scoped chat search. Results hold one hit per +// occurrence; a message's occurrences are never split across replies, so a +// reply may exceed the cap by one message's worth. +func searchChatScoped(ctx context.Context, req protocol.SearchRequest, broker chatBroker) (*protocol.SearchResponse, error) { + sessionID := scopedChatSession(req) + if !validChatSessionID(sessionID) { + return nil, errors.New("a valid chat session id is required in scope chat:") + } + if broker == nil { + return nil, errors.New("chat is not configured on this server") + } + response := &protocol.SearchResponse{ + Query: req.Query, + Kind: protocol.SearchKindChat, + Results: []protocol.SearchResult{}, + Cap: chatSearchLimit(req.Limit), + ScanBoundBytes: protocol.SearchMaxScanBytes, + } + query := []rune(strings.TrimSpace(req.Query)) + if len(query) == 0 { + return response, nil + } + ctx, cancel := context.WithTimeout(ctx, scopedChatBudget) + defer cancel() + cursor := parseScopedCursor(req.Cursor) + for { + page, err := broker.Messages(ctx, sessionID, scopedChatPageMessages, cursor.history) + if err != nil { + if ctx.Err() != nil && response.ScannedMessages > 0 { + // Out of time: what was found stands; the client continues. + response.Truncated = true + response.NextCursor = cursor.String() + return response, nil + } + return nil, err + } + messages := page.Messages + for index := len(messages) - 1 - cursor.skip; index >= 0; index-- { + message := messages[index] + response.Results = append(response.Results, scopedMessageHits(sessionID, message, query, req.CaseSensitive)...) + response.ScannedMessages++ + cursor.skip++ + done := index == 0 && (!page.HasMore || page.NextCursor == "") + if done { + return response, nil + } + if len(response.Results) >= response.Cap || + response.ScannedMessages >= scopedChatMaxMessages || ctx.Err() != nil { + response.Truncated = true + if index == 0 { + cursor = scopedCursor{history: page.NextCursor} + } + response.NextCursor = cursor.String() + return response, nil + } + } + if !page.HasMore || page.NextCursor == "" { + return response, nil + } + cursor = scopedCursor{history: page.NextCursor} + } +} + +// scopedMessageHits is one hit per occurrence of query in message's text parts. +func scopedMessageHits(sessionID string, message protocol.ChatMessage, query []rune, caseSensitive bool) []protocol.SearchResult { + var hits []protocol.SearchResult + for partIndex, part := range message.Parts { + if part.Type != protocol.ChatPartText || part.Text == "" { + continue + } + for _, match := range runeMatches([]rune(part.Text), query, caseSensitive) { + hits = append(hits, protocol.SearchResult{ + Kind: protocol.SearchKindChat, + Target: protocol.SearchChatTarget(sessionID), + Score: chatScoreMessage, + MatchedField: "message", + Chat: &protocol.SearchChat{ + SessionID: sessionID, + MessageID: message.ID, + Role: message.Role, + Snippet: protocol.SearchSnippet(part.Text, string(query)), + Part: partIndex, + Offset: match.offset, + Length: match.length, + }, + }) + } + } + return hits +} + +type runeMatch struct{ offset, length int } + +// runeMatches finds the non-overlapping occurrences of query in text, folding +// case unless caseSensitive, and reports each in UTF-16 code units. +func runeMatches(text, query []rune, caseSensitive bool) []runeMatch { + if len(query) == 0 || len(query) > len(text) { + return nil + } + var matches []runeMatch + units := 0 // UTF-16 units before text[i] + for i := 0; i <= len(text)-len(query); { + if runesEqual(text[i:i+len(query)], query, caseSensitive) { + length := utf16Len(text[i : i+len(query)]) + matches = append(matches, runeMatch{offset: units, length: length}) + units += length + i += len(query) + continue + } + units += utf16.RuneLen(text[i]) + i++ + } + return matches +} + +func runesEqual(a, b []rune, caseSensitive bool) bool { + for i := range a { + if a[i] == b[i] { + continue + } + if caseSensitive || !foldEqual(a[i], b[i]) { + return false + } + } + return true +} + +func foldEqual(a, b rune) bool { + if unicode.ToLower(a) == unicode.ToLower(b) { + return true + } + for folded := unicode.SimpleFold(a); folded != a; folded = unicode.SimpleFold(folded) { + if folded == b { + return true + } + } + return false +} + +func utf16Len(runes []rune) int { + n := 0 + for _, r := range runes { + n += utf16.RuneLen(r) + } + return n +} diff --git a/internal/server/search_chat_scoped_test.go b/internal/server/search_chat_scoped_test.go new file mode 100644 index 00000000..987b9f22 --- /dev/null +++ b/internal/server/search_chat_scoped_test.go @@ -0,0 +1,147 @@ +package server + +import ( + "context" + "fmt" + "strconv" + "testing" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// scopedHistoryChat serves one session's history oldest first in pages of the +// requested size; a cursor is the index one past the page's oldest message. +type scopedHistoryChat struct { + *fakeChat + messages []protocol.ChatMessage +} + +func (c *scopedHistoryChat) Messages(_ context.Context, _ string, limit int, cursor string) (protocol.ChatHistoryPage, error) { + end := len(c.messages) + if cursor != "" { + n, err := strconv.Atoi(cursor) + if err != nil { + return protocol.ChatHistoryPage{}, err + } + end = n + } + start := max(end-limit, 0) + page := protocol.ChatHistoryPage{Messages: c.messages[start:end]} + if start > 0 { + page.HasMore = true + page.NextCursor = strconv.Itoa(start) + } + return page, nil +} + +func pagedHistory(n int) []protocol.ChatMessage { + messages := make([]protocol.ChatMessage, n) + for i := range messages { + text := fmt.Sprintf("message %d", i) + if i%10 == 0 { + text = fmt.Sprintf("Needle %d and needle again", i) + } + messages[i] = chatText(fmt.Sprintf("m%d", i), protocol.ChatRoleAssistant, text) + } + return messages +} + +func TestScopedChatSearchReturnsEveryOccurrenceNewestFirst(t *testing.T) { + broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)} + response, err := searchChatScoped(context.Background(), protocol.SearchRequest{ + Query: "needle", Kind: protocol.SearchKindChat, Scope: protocol.SearchChatScope("ses_a"), Limit: 200, + }, broker) + if err != nil { + t.Fatal(err) + } + if len(response.Results) != 90 || response.NextCursor != "" || response.Truncated { + t.Fatalf("results=%d cursor=%q truncated=%v", len(response.Results), response.NextCursor, response.Truncated) + } + first := response.Results[0].Chat + if first.MessageID != "m440" || first.Offset != 0 || first.Length != 6 { + t.Fatalf("first hit = %+v", first) + } + second := response.Results[1].Chat + if second.MessageID != "m440" || second.Offset != len("Needle 440 and ") { + t.Fatalf("second hit = %+v", second) + } + if last := response.Results[89].Chat; last.MessageID != "m0" { + t.Fatalf("last hit = %+v", last) + } +} + +func TestScopedChatSearchPagesThroughCursor(t *testing.T) { + broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)} + request := protocol.SearchRequest{Query: "needle", Kind: protocol.SearchKindChat, Scope: "chat:ses_a", Limit: 7} + var ids []string + for pages := 0; ; pages++ { + if pages > 50 { + t.Fatal("cursor never ended") + } + response, err := searchChatScoped(context.Background(), request, broker) + if err != nil { + t.Fatal(err) + } + for _, hit := range response.Results { + ids = append(ids, hit.Chat.MessageID) + } + if response.NextCursor == "" { + break + } + request.Cursor = response.NextCursor + } + if len(ids) != 90 { + t.Fatalf("hits across pages = %d", len(ids)) + } + seen := map[string]int{} + for _, id := range ids { + seen[id]++ + } + if len(seen) != 45 || seen["m0"] != 2 || seen["m440"] != 2 { + t.Fatalf("each needle message twice, got %v", seen) + } +} + +func TestScopedChatSearchStartsAtHistoryCursorAndMatchesCase(t *testing.T) { + broker := &scopedHistoryChat{fakeChat: scriptedChat(), messages: pagedHistory(450)} + response, err := searchChatScoped(context.Background(), protocol.SearchRequest{ + Query: "Needle", Kind: protocol.SearchKindChat, Scope: "chat:ses_a", Cursor: "250", CaseSensitive: true, + }, broker) + if err != nil { + t.Fatal(err) + } + if len(response.Results) != 25 || response.Results[0].Chat.MessageID != "m240" { + t.Fatalf("results=%d first=%+v", len(response.Results), response.Results[0].Chat) + } +} + +func TestScopedChatSearchCountsUTF16Offsets(t *testing.T) { + matches := runeMatches([]rune("😀 Ünïcode ünïcode"), []rune("ÜNÏ"), false) + if len(matches) != 2 || matches[0].offset != 3 || matches[1].offset != 11 || matches[0].length != 3 { + t.Fatalf("matches = %+v", matches) + } + if got := runeMatches([]rune("aaaa"), []rune("aa"), true); len(got) != 2 { + t.Fatalf("overlapping matches counted: %+v", got) + } +} + +func TestScopedChatSearchRejectsAnInvalidScope(t *testing.T) { + broker := &scopedHistoryChat{fakeChat: scriptedChat()} + if _, err := searchChatScoped(context.Background(), protocol.SearchRequest{Query: "x", Scope: "chat:../etc"}, broker); err == nil { + t.Fatal("invalid scope accepted") + } +} + +func TestScopedChatSearchOverTheSocket(t *testing.T) { + broker := &transcriptChat{fakeChat: scriptedChat(), pages: map[string][]protocol.ChatMessage{}} + ctx, conn := chatSearchFixture(t, broker) + writeChat(t, ctx, conn, protocol.Message{Type: protocol.Search, ID: "scoped", Search: &protocol.SearchRequest{ + Query: "flaky", Kind: protocol.SearchKindChat, Scope: "chat:ses_text", + }}) + reply := readReply(t, ctx, conn, "scoped") + // transcriptChat refuses any page size but the global search's, so the + // scoped search's own read comes back as an error reply. + if reply.Type != protocol.Error { + t.Fatalf("reply = %+v", reply) + } +} diff --git a/internal/server/search_chats.go b/internal/server/search_chats.go index 95e150d5..cb957989 100644 --- a/internal/server/search_chats.go +++ b/internal/server/search_chats.go @@ -40,6 +40,13 @@ func isChatSearch(request protocol.Message) bool { // chatSearchReply answers one kind=chat search request. func chatSearchReply(ctx context.Context, request protocol.Message, broker chatBroker, registry operatorRegistry) protocol.Message { + if scopedChatSession(*request.Search) != "" { + response, err := searchChatScoped(ctx, *request.Search, broker) + if err != nil { + return protocol.Message{Type: protocol.Error, ID: request.ID, Error: err.Error()} + } + return protocol.Message{Type: protocol.SearchResults, ID: request.ID, SearchResults: response} + } if registry == nil { return protocol.Message{Type: protocol.Error, ID: request.ID, Error: "chat search unavailable: operator session registry is not configured on this server"} } diff --git a/internal/server/websocket.go b/internal/server/websocket.go index b44124b5..1a2f3591 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -285,8 +285,11 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // A chat search runs beside the read loop so its transcript readback // never delays the run search sent with it; a newer one cancels the // previous, whose reply the client would discard as stale anyway. + // A newer chat search replaces an older one of the same mode: the + // chat list's search and a find-in-chat search never cancel each other. cancelChatSearch := func() {} - defer func() { cancelChatSearch() }() + cancelScopedChatSearch := func() {} + defer func() { cancelChatSearch(); cancelScopedChatSearch() }() // Keystrokes and sizes take their own lane (terminal_lane.go), so // they never wait behind a slow request read before them. The lane // is drained before the deferred detaches above run. @@ -312,9 +315,14 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin continue } if isChatSearch(request) { - cancelChatSearch() searchCtx, cancel := context.WithCancel(connCtx) - cancelChatSearch = cancel + if scopedChatSession(*request.Search) != "" { + cancelScopedChatSearch() + cancelScopedChatSearch = cancel + } else { + cancelChatSearch() + cancelChatSearch = cancel + } go func(request protocol.Message) { defer cancel() _ = write(chatSearchReply(searchCtx, request, options.Chat, registry)) From 9f13c93be62f7cf1900849b715ce7577cf1bd832 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:26:46 +0000 Subject: [PATCH 04/19] Chat reliability: durable ntfy outbox, queue recovery retries, unattended cap - Chat phone pushes (attention items, auto-switch notices) go through a durable chat_notifications outbox with leases, bounded attempts and backoff, retried by a worker; pushes cleared in the app first are never published, and a publication racing a clear is cleared again. - Queued/scheduled chat prompts are deleted on recovery only when they can never be rebuilt; transient failures keep the rows and retry with backoff. - Unattended chats with live work always keep notifying; the idle cap rises from 16 to 64. Co-Authored-By: Claude Opus 5.5 --- internal/pipeline/chat_notifications.go | 115 +++++++++++++++++ internal/pipeline/chat_notifications_test.go | 76 +++++++++++ internal/pipeline/store.go | 4 + internal/server/chat_attention.go | 10 +- internal/server/chat_auto_switch.go | 10 +- internal/server/chat_hub.go | 3 + internal/server/chat_ntfy_outbox.go | 128 +++++++++++++++++++ internal/server/chat_ntfy_outbox_test.go | 61 +++++++++ internal/server/chat_queue.go | 124 ++++++++++++------ internal/server/chat_queue_recovery_test.go | 74 +++++++++++ internal/server/chat_unattended.go | 19 ++- internal/server/chat_unattended_test.go | 42 +++++- internal/server/websocket.go | 1 + 13 files changed, 609 insertions(+), 58 deletions(-) create mode 100644 internal/pipeline/chat_notifications.go create mode 100644 internal/pipeline/chat_notifications_test.go create mode 100644 internal/server/chat_ntfy_outbox.go create mode 100644 internal/server/chat_ntfy_outbox_test.go create mode 100644 internal/server/chat_queue_recovery_test.go diff --git a/internal/pipeline/chat_notifications.go b/internal/pipeline/chat_notifications.go new file mode 100644 index 00000000..02e37544 --- /dev/null +++ b/internal/pipeline/chat_notifications.go @@ -0,0 +1,115 @@ +package pipeline + +import ( + "context" + "database/sql" + "errors" + "time" +) + +// ChatNotification is one chat phone push (ntfy) in the durable outbox. It +// follows the run notification outbox (run_notifications.go): a row is leased +// for a bounded attempt, a crash during a lease is recovered when the lease +// expires, and attempts are bounded. ID is the chat's app notification id, so +// an enqueue is idempotent and a notification the operator already cleared in +// the app is never published late. +type ChatNotification struct { + ID, SessionID, Title, Body, Click string + // SequenceID is the ntfy sequence id the push is published with (so a later + // clear dismisses it on the phone); "" publishes without one. + SequenceID string + Priority int + Attempts int +} + +// ChatNotificationAttempts bounds publication attempts per chat push. +const ChatNotificationAttempts = 5 + +// chatNotificationLease is how long one claimed attempt owns its row. +const chatNotificationLease = 60 + +// chatNotificationRetention bounds how long settled rows are kept. +const chatNotificationRetention = 7 * 24 * time.Hour + +func (s *Store) initChatNotifications() error { + _, err := s.db.Exec(`CREATE TABLE IF NOT EXISTS chat_notifications ( +id TEXT PRIMARY KEY, session_id TEXT NOT NULL, title TEXT NOT NULL, body TEXT NOT NULL, click TEXT NOT NULL, +sequence_id TEXT NOT NULL DEFAULT '', priority INTEGER NOT NULL DEFAULT 0, +status TEXT NOT NULL DEFAULT 'pending', attempts INTEGER NOT NULL DEFAULT 0, +next_attempt INTEGER NOT NULL DEFAULT 0, diagnostic TEXT NOT NULL DEFAULT '', message_id TEXT NOT NULL DEFAULT '', +created_at INTEGER NOT NULL); +CREATE INDEX IF NOT EXISTS chat_notifications_due ON chat_notifications(status,next_attempt);`) + return err +} + +// EnqueueChatNotification records one chat push once (by id) and prunes +// settled rows past retention. +func (s *Store) EnqueueChatNotification(ctx context.Context, n ChatNotification, now time.Time) error { + if _, err := s.db.ExecContext(ctx, `DELETE FROM chat_notifications WHERE created_at0)`, now); err != nil { + return nil, err + } + if _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status='failed',diagnostic='publisher acknowledgement unknown after final lease expired' +WHERE status='sending' AND attempts>=? AND next_attempt<=?`, ChatNotificationAttempts, now); err != nil { + return nil, err + } + n := new(ChatNotification) + err := s.db.QueryRowContext(ctx, `UPDATE chat_notifications SET status='sending',attempts=attempts+1,next_attempt=? +WHERE rowid=(SELECT rowid FROM chat_notifications WHERE status IN ('pending','sending') AND attempts= ChatNotificationAttempts { + status = "failed" + } + } + _, err := s.db.ExecContext(ctx, `UPDATE chat_notifications SET status=?,diagnostic=?,message_id=?,next_attempt=? +WHERE id=? AND status='sending' AND attempts=?`, status, diagnostic, messageID, next, n.ID, n.Attempts) + return err +} + +// ChatNotificationStatus reports one push's outbox status ("" when absent) +// and attempts. +func (s *Store) ChatNotificationStatus(ctx context.Context, id string) (string, int, error) { + var status string + var attempts int + err := s.db.QueryRowContext(ctx, `SELECT status,attempts FROM chat_notifications WHERE id=?`, id).Scan(&status, &attempts) + if errors.Is(err, sql.ErrNoRows) { + return "", 0, nil + } + return status, attempts, err +} + +// ChatNotificationCleared reports whether id's app notification has been +// cleared; a publication that raced a clear then clears the phone too. +func (s *Store) ChatNotificationCleared(ctx context.Context, id string) (bool, error) { + var cleared bool + err := s.db.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM app_notifications WHERE id=? AND cleared_at<>0)`, id).Scan(&cleared) + return cleared, err +} diff --git a/internal/pipeline/chat_notifications_test.go b/internal/pipeline/chat_notifications_test.go new file mode 100644 index 00000000..bef69429 --- /dev/null +++ b/internal/pipeline/chat_notifications_test.go @@ -0,0 +1,76 @@ +package pipeline + +import ( + "context" + "errors" + "path/filepath" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +func TestChatNotificationOutboxRetriesAndSkipsCleared(t *testing.T) { + ctx := context.Background() + s, err := Open(filepath.Join(t.TempDir(), "chat-outbox.db")) + if err != nil { + t.Fatal(err) + } + defer s.Close() + now := time.Unix(1000, 0) + n := ChatNotification{ID: "chat:ses_a:form:q1", SessionID: "ses_a", Title: "T", Body: "B", Click: "pipelines://chat/ses_a", SequenceID: "pl-1"} + for range 2 { // idempotent by id + if err := s.EnqueueChatNotification(ctx, n, now); err != nil { + t.Fatal(err) + } + } + first, err := s.ClaimChatNotification(ctx, 1000) + if err != nil || first == nil || first.Attempts != 1 || first.SequenceID != "pl-1" { + t.Fatalf("claim = %+v %v", first, err) + } + if again, err := s.ClaimChatNotification(ctx, 1000); err != nil || again != nil { + t.Fatalf("leased row claimed twice: %+v %v", again, err) + } + if err := s.FinishChatNotification(ctx, *first, 1000, "", errors.New("ntfy down")); err != nil { + t.Fatal(err) + } + if early, _ := s.ClaimChatNotification(ctx, 1004); early != nil { + t.Fatalf("retried before backoff: %+v", early) + } + second, err := s.ClaimChatNotification(ctx, 1005) + if err != nil || second == nil || second.Attempts != 2 { + t.Fatalf("retry claim = %+v %v", second, err) + } + if err := s.FinishChatNotification(ctx, *second, 1005, "m1", nil); err != nil { + t.Fatal(err) + } + if status, attempts, _ := s.ChatNotificationStatus(ctx, n.ID); status != "sent" || attempts != 2 { + t.Fatalf("status = %s/%d", status, attempts) + } + // A lease lost to a crash is reclaimed after it expires. + crashed := ChatNotification{ID: "chat:ses_a:form:q2", SessionID: "ses_a", Title: "T", Body: "B"} + _ = s.EnqueueChatNotification(ctx, crashed, now) + if c, _ := s.ClaimChatNotification(ctx, 2000); c == nil { + t.Fatal("no claim") + } + if c, _ := s.ClaimChatNotification(ctx, 2061); c == nil || c.Attempts != 2 { + t.Fatalf("expired lease not reclaimed: %+v", c) + } else if err := s.FinishChatNotification(ctx, *c, 2061, "m2", nil); err != nil { + t.Fatal(err) + } + // A push whose app notification was cleared first is never published. + cleared := ChatNotification{ID: "chat:ses_b:form:q3", SessionID: "ses_b", Title: "T", Body: "B"} + if _, _, err := s.RecordAppNotification(ctx, AppNotificationRecord{AppNotification: protocol.AppNotification{ID: cleared.ID, Kind: protocol.NotificationChatQuestion, Title: "T"}, SessionID: "ses_b"}, now); err != nil { + t.Fatal(err) + } + if _, err := s.ClearAppNotifications(ctx, []string{cleared.ID}, now); err != nil { + t.Fatal(err) + } + _ = s.EnqueueChatNotification(ctx, cleared, now) + if c, _ := s.ClaimChatNotification(ctx, 3000); c != nil { + t.Fatalf("cleared push claimed: %+v", c) + } + if status, _, _ := s.ChatNotificationStatus(ctx, cleared.ID); status != "cleared" { + t.Fatalf("cleared push status = %q", status) + } +} diff --git a/internal/pipeline/store.go b/internal/pipeline/store.go index e258892b..ae16e913 100644 --- a/internal/pipeline/store.go +++ b/internal/pipeline/store.go @@ -77,6 +77,10 @@ CREATE TABLE IF NOT EXISTS submissions (id INTEGER PRIMARY KEY, name TEXT NOT NU db.Close() return nil, err } + if err := s.initChatNotifications(); err != nil { + db.Close() + return nil, err + } if err := s.initSchedules(); err != nil { db.Close() return nil, err diff --git a/internal/server/chat_attention.go b/internal/server/chat_attention.go index 22c5d058..b7e58d88 100644 --- a/internal/server/chat_attention.go +++ b/internal/server/chat_attention.go @@ -2,7 +2,6 @@ package server import ( "context" - "log" "net/url" "os" "strings" @@ -147,7 +146,8 @@ func (h *chatHub) clearChatAttention(sessionID, id string) { } // startChatAttention publishes asynchronously within the 30-second notification -// budget. It never blocks or fails chat handling; failures are only logged. +// budget. It never blocks or fails chat handling; the phone push goes through +// the durable outbox, which retries a failed attempt. func (h *chatHub) startChatAttention(a chatAttention) { base := h.baseCtx if base == nil { @@ -176,7 +176,7 @@ func (h *chatHub) startChatAttention(a chatAttention) { if a.reply { title, body = chatReplyText(name, a.body) } - click, views := chatAttentionLinks(a.sessionID) + click, _ := chatAttentionLinks(a.sessionID) kind := protocol.NotificationChatQuestion if a.reply { kind = protocol.NotificationChatReply @@ -192,9 +192,7 @@ func (h *chatHub) startChatAttention(a chatAttention) { return } // ntfy takes a single-line message of at most 2048 bytes. - if _, err := chatAttentionPublish(stage.WithNtfySequenceID(ctx, chatNtfySequence(a.id)), "system", title, truncateUTF8(singleLine(body), 2000), "", nil, click, views...); err != nil { - log.Printf("chat attention notification session=%s: %v", a.sessionID, err) - } + h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: a.id, SessionID: a.sessionID, Title: title, Body: truncateUTF8(singleLine(body), 2000), Click: click, SequenceID: chatNtfySequence(a.id)}) }() } diff --git a/internal/server/chat_auto_switch.go b/internal/server/chat_auto_switch.go index fea5d75a..53b4ba9e 100644 --- a/internal/server/chat_auto_switch.go +++ b/internal/server/chat_auto_switch.go @@ -11,7 +11,6 @@ import ( "git.a-wan.net/alan/pipelines/internal/claude" "git.a-wan.net/alan/pipelines/internal/pipeline" "git.a-wan.net/alan/pipelines/internal/protocol" - "git.a-wan.net/alan/pipelines/internal/stage" ) // When Claude Code refuses an operator chat's turn because the account ran @@ -281,10 +280,11 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us } title := truncateUTF8("Switched "+name+" to "+singleLine(email)+" and continued", 256) message := "Claude usage ran out, so Pipelines switched the account and asked the agent to check it is on track before continuing." - click, views := chatAttentionLinks(refusal.SessionID) + click, _ := chatAttentionLinks(refusal.SessionID) + id := "chat:" + refusal.SessionID + ":auto-switch:" + refusalKey(refusal) if h.notes != nil { h.notes.record(ctx, pipeline.AppNotificationRecord{ - AppNotification: protocol.AppNotification{ID: "chat:" + refusal.SessionID + ":auto-switch:" + refusalKey(refusal), Kind: protocol.NotificationChatReply, + AppNotification: protocol.AppNotification{ID: id, Kind: protocol.NotificationChatReply, Title: title, Message: message, Click: click, Priority: chatAutoSwitchPriority, Tags: []string{}, Group: "chat:" + refusal.SessionID}, SessionID: refusal.SessionID, }) @@ -292,7 +292,5 @@ func (h *chatHub) publishAutoSwitchNotice(ctx context.Context, refusal claude.Us if !chatAttentionConfigured() || !chatNotificationSettings(ctx, h.settings).NtfyEnabled { return } - if _, err := chatAttentionPublish(stage.WithNtfyPriority(ctx, chatAutoSwitchPriority), "system", title, message, "", nil, click, views...); err != nil { - log.Printf("claude auto-switch notification session=%s: %v", refusal.SessionID, err) - } + h.pushChatNtfy(ctx, pipeline.ChatNotification{ID: id, SessionID: refusal.SessionID, Title: title, Body: message, Click: click, Priority: chatAutoSwitchPriority}) } diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index 25a35787..5858a218 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -51,6 +51,9 @@ type chatHub struct { attentionSeen map[string]struct{} attentionOrder []string attentionWG sync.WaitGroup + // outbox makes chat phone pushes durable and retried (chat_ntfy_outbox.go); + // nil publishes each push once, directly. + outbox chatNotificationOutbox // notifiedTurns holds the chats whose current turn already sent an agent // notify, so that turn's end is not announced again (one turn, one ping). notifiedTurns map[string]struct{} diff --git a/internal/server/chat_ntfy_outbox.go b/internal/server/chat_ntfy_outbox.go new file mode 100644 index 00000000..32746049 --- /dev/null +++ b/internal/server/chat_ntfy_outbox.go @@ -0,0 +1,128 @@ +package server + +import ( + "context" + "log" + "sync/atomic" + "time" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +// Chat phone pushes (attention items and Claude auto-switch notices) go +// through a durable outbox like run notifications: the push is recorded first, +// one attempt is made at once, and a background worker retries a failed or +// interrupted attempt with backoff, also after a restart. A push whose app +// notification the operator already cleared is never published late, and a +// publication that raced a clear is cleared on the phone again, so the ntfy +// sequence-id/clear behaviour (chat_ntfy_clear.go) holds. + +// chatNotificationOutbox is the durable chat push outbox; *pipeline.Store +// implements it. +type chatNotificationOutbox interface { + EnqueueChatNotification(ctx context.Context, n pipeline.ChatNotification, now time.Time) error + ClaimChatNotification(ctx context.Context, now int64) (*pipeline.ChatNotification, error) + FinishChatNotification(ctx context.Context, n pipeline.ChatNotification, now int64, messageID string, failure error) error + ChatNotificationCleared(ctx context.Context, id string) (bool, error) + Done() <-chan struct{} +} + +// chatOutboxInterval is how often the worker looks for due retries. +var chatOutboxInterval = time.Second + +// chatOutboxSkew shifts the outbox clock; tests move it past a backoff. +var chatOutboxSkew atomic.Int64 + +func chatOutboxNow() time.Time { return time.Now().Add(time.Duration(chatOutboxSkew.Load())) } + +// startChatNotificationOutbox wires the durable outbox and starts its retry +// worker for the life of ctx. +func (h *chatHub) startChatNotificationOutbox(ctx context.Context, outbox chatNotificationOutbox) { + h.outbox = outbox + go func() { + ticker := time.NewTicker(chatOutboxInterval) + defer ticker.Stop() + for { + select { + case <-ctx.Done(): + return + case <-outbox.Done(): + return + case <-ticker.C: + h.deliverChatNotifications(ctx, 16) + } + } + }() +} + +// pushChatNtfy publishes one chat phone push. With an outbox it is recorded +// durably and attempted at once; without one (a store-less hub) it is a single +// direct attempt, as before. +func (h *chatHub) pushChatNtfy(ctx context.Context, n pipeline.ChatNotification) { + if h.outbox != nil { + err := h.outbox.EnqueueChatNotification(ctx, n, chatOutboxNow()) + if err == nil { + h.deliverChatNotifications(ctx, 1) + return + } + log.Printf("enqueue chat notification %s: %v; publishing directly", n.ID, err) + } + if _, err := chatAttentionPublish(chatNtfyContext(ctx, n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(n)...); err != nil { + log.Printf("chat notification session=%s: %v", n.SessionID, err) + } +} + +func chatNtfyContext(ctx context.Context, n pipeline.ChatNotification) context.Context { + if n.SequenceID != "" { + ctx = stage.WithNtfySequenceID(ctx, n.SequenceID) + } + if n.Priority > 0 { + ctx = stage.WithNtfyPriority(ctx, n.Priority) + } + return ctx +} + +// chatNtfyViews derives the push's actions at delivery, so a changed web +// origin applies to a retried push. +func chatNtfyViews(n pipeline.ChatNotification) []stage.NtfyView { + _, views := chatAttentionLinks(n.SessionID) + return views +} + +// deliverChatNotifications attempts up to limit due pushes. +func (h *chatHub) deliverChatNotifications(ctx context.Context, limit int) { + outbox := h.outbox + if outbox == nil { + return + } + for i := 0; i < limit && ctx.Err() == nil; i++ { + n, err := outbox.ClaimChatNotification(ctx, chatOutboxNow().Unix()) + if err != nil { + log.Printf("claim chat notification: %v", err) + return + } + if n == nil { + return + } + publish, cancel := context.WithTimeout(ctx, 30*time.Second) + result, publishErr := chatAttentionPublish(chatNtfyContext(publish, *n), "system", n.Title, n.Body, "", nil, n.Click, chatNtfyViews(*n)...) + cancel() + if publishErr != nil { + log.Printf("chat notification session=%s attempt=%d: %v", n.SessionID, n.Attempts, publishErr) + } + messageID, _ := result["message_id"].(string) + save, done := context.WithTimeout(context.WithoutCancel(ctx), 5*time.Second) + if err := outbox.FinishChatNotification(save, *n, chatOutboxNow().Unix(), messageID, publishErr); err != nil { + log.Printf("save chat notification %s: %v", n.ID, err) + } + // The operator may have cleared it in the app while it was being + // published, after the clear went to ntfy: clear it there again. + if publishErr == nil && n.SequenceID != "" { + if cleared, err := outbox.ChatNotificationCleared(save, n.ID); err == nil && cleared { + clearChatNtfy([]string{n.ID}) + } + } + done() + } +} diff --git a/internal/server/chat_ntfy_outbox_test.go b/internal/server/chat_ntfy_outbox_test.go new file mode 100644 index 00000000..12c9a89d --- /dev/null +++ b/internal/server/chat_ntfy_outbox_test.go @@ -0,0 +1,61 @@ +package server + +import ( + "context" + "errors" + "sync" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +// A chat attention push that ntfy refuses is kept in the durable outbox and +// retried by the worker with its sequence id, not lost after one attempt. +func TestChatAttentionPushIsRetriedFromTheOutbox(t *testing.T) { + t.Setenv("PIPELINES_NTFY_URL", "http://ntfy.invalid/pipelines") + t.Setenv("PIPELINES_WEB_PUBLIC_URL", "") + interval := chatOutboxInterval + chatOutboxInterval = 20 * time.Millisecond + defer func() { chatOutboxInterval = interval }() + var mu sync.Mutex + var sequences []string + original := chatAttentionPublish + chatAttentionPublish = func(ctx context.Context, _, _, _, _ string, _ []byte, _ string, _ ...stage.NtfyView) (stage.Values, error) { + mu.Lock() + defer mu.Unlock() + sequences = append(sequences, stage.NtfySequence(ctx)) + if len(sequences) == 1 { + return nil, errors.New("ntfy unavailable") + } + return stage.Values{"message_id": "m1"}, nil + } + defer func() { chatAttentionPublish = original }() + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() + store := newOperatorStore(t) + h := chatAttentionHub(t, "ses_a") + h.settings = store + h.notes = newAppNotifier(store) + h.startChatNotificationOutbox(ctx, store) + form := protocol.ChatForm{ID: "que_1", SessionID: "ses_a", Kind: "question", Title: "Ship it?"} + h.emit(protocol.ChatEventFrame{SessionID: "ses_a", Kind: protocol.ChatEventForm, Form: &form}) + h.attentionWG.Wait() + id := "chat:ses_a:form:que_1" + if status, attempts, err := store.ChatNotificationStatus(ctx, id); err != nil || status != "pending" || attempts != 1 { + t.Fatalf("after a refused attempt: %s/%d %v", status, attempts, err) + } + // The first backoff is 5 s; move the outbox clock past it. + chatOutboxSkew.Store(int64(10 * time.Second)) + defer chatOutboxSkew.Store(0) + waitFor(t, "retried push sent", func() bool { + status, _, _ := store.ChatNotificationStatus(ctx, id) + return status == "sent" + }) + mu.Lock() + defer mu.Unlock() + if len(sequences) != 2 || sequences[0] != chatNtfySequence(id) || sequences[1] != sequences[0] { + t.Fatalf("sequence ids = %v", sequences) + } +} diff --git a/internal/server/chat_queue.go b/internal/server/chat_queue.go index 2f5d26a6..1fba9743 100644 --- a/internal/server/chat_queue.go +++ b/internal/server/chat_queue.go @@ -221,9 +221,24 @@ func chatQueueRow(sessionID string, p *chatQueuedPrompt) pipeline.ChatQueuedProm } } +// errChatQueuedPromptInvalid marks a stored prompt that can never be rebuilt +// (unreadable attachment list, an attachment outside the store). Only such a +// row is dropped; any other promptFromRow failure (the attachment directory +// cannot be resolved right now) keeps the row for a later retry. +var errChatQueuedPromptInvalid = errors.New("queued prompt is invalid") + +// chatQueueRecoveryRetry is the first delay before a session whose queued +// prompts could not be restored is tried again; it doubles up to +// chatQueueRecoveryRetryMax. +var ( + chatQueueRecoveryRetry = 30 * time.Second + chatQueueRecoveryRetryMax = 10 * time.Minute +) + // promptFromRow rebuilds a queued prompt read back from the store. Its files // must still name the server's own attachment directory; they are leased again -// so retention cannot collect them before delivery. +// so retention cannot collect them before delivery. A permanent failure wraps +// errChatQueuedPromptInvalid. func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) { p := &chatQueuedPrompt{ text: row.Text, @@ -239,7 +254,7 @@ func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) { _ = json.Unmarshal([]byte(row.PartsJSON), &p.parts) var stored []chatStoredFile if err := json.Unmarshal([]byte(row.FilesJSON), &stored); err != nil { - return p, fmt.Errorf("queued prompt attachments are unreadable") + return p, fmt.Errorf("%w: queued prompt attachments are unreadable", errChatQueuedPromptInvalid) } if len(stored) == 0 { return p, nil @@ -253,7 +268,7 @@ func promptFromRow(row pipeline.ChatQueuedPrompt) (*chatQueuedPrompt, error) { for _, file := range stored { u, err := url.Parse(file.URI) if err != nil || u.Scheme != "file" || filepath.Dir(u.Path) != dir { - return p, fmt.Errorf("queued prompt attachment %q is outside the attachment store", file.Name) + return p, fmt.Errorf("%w: queued prompt attachment %q is outside the attachment store", errChatQueuedPromptInvalid, file.Name) } chatAttachmentStore.leased[u.Path] = true p.files = append(p.files, opencode.NewPreparedPromptFile(file.URI, file.Name)) @@ -411,49 +426,80 @@ func (h *chatHub) resumeQueued(ctx context.Context, broker chatBroker) { return } for _, sessionID := range sessions { - rows, err := h.queueStore.ChatQueuedPrompts(ctx, sessionID) - if err != nil { - log.Printf("chat queue recovery session=%s: %v", sessionID, err) + h.resumeQueuedSession(ctx, broker, sessionID, chatQueueRecoveryRetry) + } +} + +// resumeQueuedSession restores one session's durable queue. A prompt that can +// never be rebuilt is dropped; a transient failure (the store or the +// attachment directory unavailable) keeps every row, restores nothing for the +// session (so FIFO order is kept) and tries again after retry, backing off. +// A row whose operation the live hub already knows (a retry racing a client +// that queued or delivered it meanwhile) is left to the hub. +func (h *chatHub) resumeQueuedSession(ctx context.Context, broker chatBroker, sessionID string, retry time.Duration) { + if ctx.Err() != nil { + return + } + later := func(err error) { + log.Printf("chat queue recovery session=%s: %v; retrying in %s", sessionID, err, retry) + next := min(2*retry, chatQueueRecoveryRetryMax) + time.AfterFunc(retry, func() { h.resumeQueuedSession(ctx, broker, sessionID, next) }) + } + rows, err := h.queueStore.ChatQueuedPrompts(ctx, sessionID) + if err != nil { + later(err) + return + } + var prompts []*chatQueuedPrompt + for _, row := range rows { + h.mu.Lock() + _, known := h.recentOps[sessionID+"\x00"+row.OperationID] + h.mu.Unlock() + if known && row.OperationID != "" { continue } - var prompts []*chatQueuedPrompt - for _, row := range rows { - p, err := promptFromRow(row) - if err != nil { - releaseChatAttachments(p.files) - log.Printf("chat queue recovery session=%s: %v", sessionID, err) - _, _ = h.queueStore.DeleteChatQueuedPrompt(ctx, sessionID, row.OperationID) - continue - } + p, err := promptFromRow(row) + if err == nil { prompts = append(prompts, p) - } - if len(prompts) == 0 { continue } + releaseChatAttachments(p.files) + if !errors.Is(err, errChatQueuedPromptInvalid) { + for _, kept := range prompts { + releaseChatAttachments(kept.files) + } + later(err) + return + } + log.Printf("chat queue recovery session=%s: dropping %s: %v", sessionID, row.OperationID, err) + _, _ = h.queueStore.DeleteChatQueuedPrompt(ctx, sessionID, row.OperationID) + } + if len(prompts) == 0 { + return + } + h.mu.Lock() + room := h.roomLocked(sessionID) + if room.broker == nil { + room.broker = broker + } + room.notBefore = time.Now().Add(chatQueueRecoverySettle) + for _, p := range prompts { + if !room.holdsOp(p.operationID) { + room.queue = append(room.queue, p) + h.rememberOpLocked(sessionID, p.operationID) + } + } + h.mu.Unlock() + go func(room *chatRoom) { + // Attach the stream first so a turn the harness is still running is + // observed before the settle window lets the runner deliver. + if err := h.ensureObserving(room, broker); err != nil && room.ctx.Err() == nil { + log.Printf("chat queue recovery observe session=%s: %v", room.sessionID, err) + } h.mu.Lock() - room := h.roomLocked(sessionID) - if room.broker == nil { - room.broker = broker - } - room.notBefore = time.Now().Add(chatQueueRecoverySettle) - for _, p := range prompts { - if !room.holdsOp(p.operationID) { - room.queue = append(room.queue, p) - h.rememberOpLocked(sessionID, p.operationID) - } - } + signalWake(room.wake) h.mu.Unlock() - go func(room *chatRoom) { - // Attach the stream first so a turn the harness is still running is - // observed before the settle window lets the runner deliver. - if err := h.ensureObserving(room, broker); err != nil && room.ctx.Err() == nil { - log.Printf("chat queue recovery observe session=%s: %v", room.sessionID, err) - } - h.mu.Lock() - signalWake(room.wake) - h.mu.Unlock() - }(room) - } + }(room) } func (r *chatRoom) holdsOp(operationID string) bool { diff --git a/internal/server/chat_queue_recovery_test.go b/internal/server/chat_queue_recovery_test.go new file mode 100644 index 00000000..6440f2d1 --- /dev/null +++ b/internal/server/chat_queue_recovery_test.go @@ -0,0 +1,74 @@ +package server + +import ( + "context" + "encoding/json" + "net/url" + "path/filepath" + "slices" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/pipeline" +) + +func fastQueueRecovery(t *testing.T) { + t.Helper() + settle, retry, retryMax := chatQueueRecoverySettle, chatQueueRecoveryRetry, chatQueueRecoveryRetryMax + chatQueueRecoverySettle, chatQueueRecoveryRetry, chatQueueRecoveryRetryMax = 10*time.Millisecond, 50*time.Millisecond, 100*time.Millisecond + t.Cleanup(func() { + chatQueueRecoverySettle, chatQueueRecoveryRetry, chatQueueRecoveryRetryMax = settle, retry, retryMax + }) +} + +func queuedPromptWithFile(t *testing.T, store *pipeline.Store, op, text, path string) { + t.Helper() + files, err := json.Marshal([]chatStoredFile{{URI: (&url.URL{Scheme: "file", Path: path}).String(), Name: filepath.Base(path)}}) + if err != nil { + t.Fatal(err) + } + if _, _, err := store.EnqueueChatPrompt(context.Background(), pipeline.ChatQueuedPrompt{SessionID: "ses_1", OperationID: op, MessageID: "msg_" + op, Text: text, FilesJSON: string(files)}, 0); err != nil { + t.Fatal(err) + } +} + +// A queued prompt whose attachment directory cannot be resolved at restart is +// kept and restored on a later retry, not deleted. +func TestChatQueuedPromptKeptOnTransientAttachmentFailure(t *testing.T) { + fastQueueRecovery(t) + dir := t.TempDir() + path := filepath.Join(t.TempDir(), "queue.db") + store := openQueueStore(t, path) + queuedPromptWithFile(t, store, "op-1", "with file", filepath.Join(dir, "a.txt")) + t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", "relative/dir") // unresolvable for now + broker := newChannelChat() + startQueueServer(t, broker, store) + time.Sleep(200 * time.Millisecond) + if ops := queuedOps(t, store); !slices.Equal(ops, []string{"op-1"}) { + t.Fatalf("queued prompt dropped on a transient failure: %v", ops) + } + if texts := broker.promptTexts(); len(texts) != 0 { + t.Fatalf("prompt delivered while unrestorable: %v", texts) + } + t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", dir) + waitFor(t, "prompt restored on retry", func() bool { return slices.Equal(broker.promptTexts(), []string{"with file"}) }) + waitFor(t, "delivered row deleted", func() bool { return len(queuedOps(t, store)) == 0 }) +} + +// A queued prompt that can never be rebuilt is still dropped, and the rest of +// the session's queue is delivered. +func TestChatQueuedPromptDroppedOnPermanentFailure(t *testing.T) { + fastQueueRecovery(t) + dir := t.TempDir() + t.Setenv("PIPELINES_CHAT_ATTACHMENT_DIR", dir) + path := filepath.Join(t.TempDir(), "queue.db") + store := openQueueStore(t, path) + queuedPromptWithFile(t, store, "op-1", "outside", filepath.Join(t.TempDir(), "elsewhere.txt")) + if _, _, err := store.EnqueueChatPrompt(context.Background(), pipeline.ChatQueuedPrompt{SessionID: "ses_1", OperationID: "op-2", MessageID: "msg_op-2", Text: "plain"}, 0); err != nil { + t.Fatal(err) + } + broker := newChannelChat() + startQueueServer(t, broker, store) + waitFor(t, "valid prompt delivered", func() bool { return slices.Equal(broker.promptTexts(), []string{"plain"}) }) + waitFor(t, "rows cleared", func() bool { return len(queuedOps(t, store)) == 0 }) +} diff --git a/internal/server/chat_unattended.go b/internal/server/chat_unattended.go index 3819ad09..3e5895c1 100644 --- a/internal/server/chat_unattended.go +++ b/internal/server/chat_unattended.go @@ -23,9 +23,11 @@ import ( // is not an idle lease: it remains attached until actual completion or explicit // stop. Its durable journal is independent of bounded replay/room retention. -// chatUnattendedLimit bounds the rooms kept observing with no client attached -// and no queued prompt. -const chatUnattendedLimit = 16 +// chatUnattendedLimit bounds the rooms kept observing with no client attached, +// no queued prompt and no live work of this server's own (see liveWorkLocked): +// a turn this server started, a pending approval or question, or background +// tasks always keep notifying, however many chats are unattended. +const chatUnattendedLimit = 64 // chatRecoverSessionLimit bounds how many recently used open sessions are // probed for a running turn at server start. @@ -84,6 +86,15 @@ func (h *chatHub) keepUnattendedLocked(room *chatRoom, busy, hold bool) bool { return hold && h.clock().Before(room.holdUntil) } +// liveWorkLocked reports whether a room holds work this server knows is real +// and will notify: its own turn in flight, an unanswered approval or question, +// or running background tasks. Such a room is never refused by the idle cap, +// which only bounds observers kept on weaker evidence (a stream-announced or +// harness-reported turn, the start-up settle window). Callers hold h.mu. +func (h *chatHub) liveWorkLocked(room *chatRoom) bool { + return room.running || len(room.pending) > 0 || len(room.forms) > 0 || h.backgroundTasksLocked(room.sessionID) > 0 +} + // unattendedCountLocked counts the rooms kept observing with no client and no // queued prompt, other than except. Callers hold h.mu. func (h *chatHub) unattendedCountLocked(except *chatRoom) int { @@ -109,7 +120,7 @@ func (h *chatHub) leaveUnattendedLocked(room *chatRoom) { h.releaseRoomLocked(room) return } - if !room.watching && h.backgroundTasksLocked(room.sessionID) == 0 && h.unattendedCountLocked(room) >= chatUnattendedLimit { + if !room.watching && !h.liveWorkLocked(room) && h.unattendedCountLocked(room) >= chatUnattendedLimit { log.Printf("chat session %s: %d chats already observed with no client; not keeping this one", room.sessionID, chatUnattendedLimit) h.releaseRoomLocked(room) return diff --git a/internal/server/chat_unattended_test.go b/internal/server/chat_unattended_test.go index d6d2e23d..c2c103f0 100644 --- a/internal/server/chat_unattended_test.go +++ b/internal/server/chat_unattended_test.go @@ -2,6 +2,7 @@ package server import ( "context" + "fmt" "path/filepath" "sync" "testing" @@ -320,7 +321,42 @@ func TestChatStuckUnattendedTurnIsReleased(t *testing.T) { waitFor(t, "stuck observer released", func() bool { active, _ := broker.streams(); return active == 0 }) } -// At most chatUnattendedLimit chats are kept observing with no client. +// A turn this server started keeps notifying however many chats are already +// observed unattended: the idle cap never drops live work. +func TestChatUnattendedRunningTurnsIgnoreTheCap(t *testing.T) { + fastUnattended(t) + h := newChatHub() + defer func() { + h.mu.Lock() + for _, room := range h.rooms { + room.cancel() + } + h.mu.Unlock() + }() + count := chatUnattendedLimit + 3 + kept := 0 + for i := 0; i < count; i++ { + id := fmt.Sprintf("ses_run_%03d", i) + h.mu.Lock() + room := h.roomLocked(id) + room.running = true + sub := &chatSub{hub: h, room: room, clientID: "c", ch: make(chan protocol.Message, 1), done: make(chan struct{})} + room.subs["c"] = sub + h.mu.Unlock() + h.detach(id, sub) + h.mu.Lock() + if h.rooms[id] == room { + kept++ + } + h.mu.Unlock() + } + if kept != count { + t.Fatalf("kept %d unattended running rooms, want all %d", kept, count) + } +} + +// At most chatUnattendedLimit chats are kept observing with no client on +// weaker evidence than live work (a stream-announced turn). func TestChatUnattendedRoomsAreBounded(t *testing.T) { fastUnattended(t) h := newChatHub() @@ -333,10 +369,10 @@ func TestChatUnattendedRoomsAreBounded(t *testing.T) { }() kept := 0 for i := 0; i < chatUnattendedLimit+3; i++ { - id := "ses_" + string(rune('a'+i)) + id := fmt.Sprintf("ses_obs_%03d", i) h.mu.Lock() room := h.roomLocked(id) - room.running = true + room.observedTurn = true sub := &chatSub{hub: h, room: room, clientID: "c", ch: make(chan protocol.Message, 1), done: make(chan struct{})} room.subs["c"] = sub h.mu.Unlock() diff --git a/internal/server/websocket.go b/internal/server/websocket.go index b44124b5..366970c5 100644 --- a/internal/server/websocket.go +++ b/internal/server/websocket.go @@ -145,6 +145,7 @@ func HandlerWithOptions(ctx context.Context, options Options, stores ...*pipelin // Prompts queued behind a running turn are durable and owned by their // session; resume delivering any a previous process left queued. hub.queueStore = stores[0] + hub.startChatNotificationOutbox(ctx, stores[0]) hub.liveStore = stores[0] hub.turnDiffStore = stores[0] } From 56dd1a77b0e4bccc6aed877ed34d41aaf22656b7 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:28:49 +0000 Subject: [PATCH 05/19] Changes: file list beside the selected diff on wide desktop panes At a window of at least 1000 px with a pane of at least 720 px, the run Changes surface (final changes and visit pages) lists the files on the left (name over folder, line counts, selected row highlighted) and shows the selected file's diff on the right. j/k or ArrowDown/ArrowUp move between files while the list has focus; Enter opens the file's full diff page. Phones and narrow panes keep one row per file. Co-Authored-By: Claude Opus 5.5 --- .../changes/widgets/capture_section.dart | 57 ++-- .../changes/widgets/changes_split_view.dart | 248 ++++++++++++++++++ .../changes/widgets/changes_viewer.dart | 49 +++- .../changes/changes_split_view_test.dart | 148 +++++++++++ 4 files changed, 475 insertions(+), 27 deletions(-) create mode 100644 app/lib/features/changes/widgets/changes_split_view.dart create mode 100644 app/test/features/changes/changes_split_view_test.dart diff --git a/app/lib/features/changes/widgets/capture_section.dart b/app/lib/features/changes/widgets/capture_section.dart index 5b577d96..b973b425 100644 --- a/app/lib/features/changes/widgets/capture_section.dart +++ b/app/lib/features/changes/widgets/capture_section.dart @@ -32,33 +32,10 @@ class StageCaptureSection extends StatelessWidget { final status = stage.stepStatus.trim().toLowerCase(); final pending = capture == null && (status == 'running' || status == 'waiting'); - final meta = [ - 'Visit ${stage.visit}', - if (stage.stepStatus.isNotEmpty) stage.stepStatus, - ].join(' · '); return Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ - Padding( - padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), - child: Column( - crossAxisAlignment: CrossAxisAlignment.start, - children: [ - Text(meta, style: Theme.of(context).textTheme.bodySmall), - if (capture != null) ...[ - Text( - fileChangesSummary(capture), - style: Theme.of(context).textTheme.bodySmall, - ), - if (capture.scope.isNotEmpty) - Text( - 'Scope: ${capture.scope}', - style: Theme.of(context).textTheme.bodySmall, - ), - ], - ], - ), - ), + StageCaptureHeading(stage: stage), const Divider(height: 1), if (capture == null) _CaptureNote( @@ -99,6 +76,38 @@ class StageCaptureSection extends StatelessWidget { } } +/// A stage/visit capture's heading: the visit and step status, the capture's +/// summary and its scope. +class StageCaptureHeading extends StatelessWidget { + const StageCaptureHeading({super.key, required this.stage}); + + final StageCapture stage; + + @override + Widget build(BuildContext context) { + final capture = stage.capture; + final small = Theme.of(context).textTheme.bodySmall; + final meta = [ + 'Visit ${stage.visit}', + if (stage.stepStatus.isNotEmpty) stage.stepStatus, + ].join(' · '); + return Padding( + padding: const EdgeInsets.fromLTRB(16, 16, 16, 8), + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text(meta, style: small), + if (capture != null) ...[ + Text(fileChangesSummary(capture), style: small), + if (capture.scope.isNotEmpty) + Text('Scope: ${capture.scope}', style: small), + ], + ], + ), + ); + } +} + /// One changed file: its kind, path and line counts; tapping opens its diff. /// [dense] draws it on one compact line (the path, then the counts), for a /// card that lists many files in little space. diff --git a/app/lib/features/changes/widgets/changes_split_view.dart b/app/lib/features/changes/widgets/changes_split_view.dart new file mode 100644 index 00000000..a6cba454 --- /dev/null +++ b/app/lib/features/changes/widgets/changes_split_view.dart @@ -0,0 +1,248 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../domain/file_change.dart'; +import '../domain/unified_patch.dart'; +import '../domain/change_kind.dart'; +import '../domain/change_wording.dart'; +import 'capture_section.dart' show changeKindIcon; +import 'change_style.dart'; +import 'file_diff_viewer.dart'; + +/// The window width from which the Changes surface shows its files beside +/// the selected file's diff instead of one row per file. +const double changesSplitMinWidth = 1000; + +/// The narrowest pane that still fits the file list beside a readable diff; +/// a desktop window's detail pane beside the run list is usually narrower +/// than the window threshold. +const double changesSplitMinPaneWidth = 720; + +/// Whether a Changes pane [paneWidth] wide splits into list and diff. +bool changesSplitFits(BuildContext context, double paneWidth) => + MediaQuery.sizeOf(context).width >= changesSplitMinWidth && + paneWidth >= changesSplitMinPaneWidth; + +/// A desktop review layout: the changed files as a compact list on the left +/// and the selected file's diff on the right, like a code review tool. +/// +/// While the view has focus, `j`/ArrowDown select the next file and +/// `k`/ArrowUp the previous one; Enter opens the selected file on its own +/// page. Keys typed into a text field are never taken. +class ChangesSplitView extends StatefulWidget { + const ChangesSplitView({super.key, required this.files, this.heading}); + + /// The files to review, in list order. Must not be empty. + final List files; + + /// Shown above the file list (a visit's heading). + final Widget? heading; + + @override + State createState() => _ChangesSplitViewState(); +} + +class _ChangesSplitViewState extends State { + final _focus = FocusNode(debugLabel: 'changes split'); + final _listScroll = ScrollController(); + List _rowKeys = const []; + int _index = 0; + + @override + void initState() { + super.initState(); + _rowKeys = _keysFor(widget.files); + } + + @override + void didUpdateWidget(ChangesSplitView oldWidget) { + super.didUpdateWidget(oldWidget); + if (identical(oldWidget.files, widget.files)) return; + // Keep the same file selected across a refreshed reply when it is still + // listed; otherwise stay at the same position. + final path = oldWidget.files.isEmpty + ? null + : oldWidget.files[_index.clamp(0, oldWidget.files.length - 1)].path; + final kept = widget.files.indexWhere((file) => file.path == path); + _index = kept >= 0 + ? kept + : _index.clamp(0, widget.files.isEmpty ? 0 : widget.files.length - 1); + _rowKeys = _keysFor(widget.files); + } + + static List _keysFor(List files) => [ + for (final file in files) GlobalKey(debugLabel: 'change row ${file.path}'), + ]; + + @override + void dispose() { + _focus.dispose(); + _listScroll.dispose(); + super.dispose(); + } + + void _select(int index, {bool focus = false}) { + if (focus) _focus.requestFocus(); + if (index < 0 || index >= widget.files.length) return; + final forward = index > _index; + if (index != _index) setState(() => _index = index); + // Keep the selected row in view once it is laid out at its new state. + WidgetsBinding.instance.addPostFrameCallback((_) { + final row = _rowKeys[index].currentContext; + if (row == null || !row.mounted) return; + Scrollable.ensureVisible( + row, + alignmentPolicy: forward + ? ScrollPositionAlignmentPolicy.keepVisibleAtEnd + : ScrollPositionAlignmentPolicy.keepVisibleAtStart, + ); + }); + } + + void _step(int delta) => + _select((_index + delta).clamp(0, widget.files.length - 1)); + + KeyEventResult _handle(FocusNode node, KeyEvent event) { + if (event is KeyUpEvent) return KeyEventResult.ignored; + final primary = FocusManager.instance.primaryFocus; + final focused = primary?.context; + if (primary != node && + focused != null && + (focused.widget is EditableText || + focused.findAncestorWidgetOfExactType() != null)) { + return KeyEventResult.ignored; + } + final keyboard = HardwareKeyboard.instance; + if (keyboard.isControlPressed || + keyboard.isMetaPressed || + keyboard.isAltPressed) { + return KeyEventResult.ignored; + } + final key = event.logicalKey; + if (key == LogicalKeyboardKey.arrowDown || key == LogicalKeyboardKey.keyJ) { + _step(1); + } else if (key == LogicalKeyboardKey.arrowUp || + key == LogicalKeyboardKey.keyK) { + _step(-1); + } else if (event is KeyDownEvent && + (key == LogicalKeyboardKey.enter || + key == LogicalKeyboardKey.numpadEnter)) { + _openPage(); + } else { + return KeyEventResult.ignored; + } + return KeyEventResult.handled; + } + + void _openPage() => + showFileDiffViewer(context, widget.files[_index], files: widget.files); + + @override + Widget build(BuildContext context) { + final files = widget.files; + final index = _index.clamp(0, files.length - 1); + final file = files[index]; + return LayoutBuilder( + builder: (context, constraints) { + final listWidth = (constraints.maxWidth * 0.28).clamp(260.0, 380.0); + return Focus( + focusNode: _focus, + onKeyEvent: _handle, + child: Row( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + SizedBox( + width: listWidth, + child: Semantics( + container: true, + identifier: 'changes-file-list', + label: 'Changed files', + explicitChildNodes: true, + child: SingleChildScrollView( + key: const ValueKey('changes-split-list'), + controller: _listScroll, + padding: const EdgeInsets.only(bottom: 16), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + ?widget.heading, + for (var i = 0; i < files.length; i++) + _SplitFileRow( + key: _rowKeys[i], + file: files[i], + selected: i == index, + onTap: () => _select(i, focus: true), + ), + ], + ), + ), + ), + ), + const VerticalDivider(width: 1), + Expanded( + child: FileDiffViewer( + key: ValueKey('changes-split-diff-${file.path}'), + file: file, + ), + ), + ], + ), + ); + }, + ); + } +} + +/// One file in the split list: its name with its folder below, so a long +/// path never hides the file name, and its line counts. +class _SplitFileRow extends StatelessWidget { + const _SplitFileRow({ + super.key, + required this.file, + required this.selected, + required this.onTap, + }); + + final FileChange file; + final bool selected; + final VoidCallback onTap; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + final mono = nativeDiffText(DefaultTextStyle.of(context).style); + final slash = file.path.lastIndexOf('/'); + final name = slash < 0 ? file.path : file.path.substring(slash + 1); + final folder = slash < 0 ? '' : file.path.substring(0, slash); + return Semantics( + container: true, + button: true, + selected: selected, + label: + 'Show diff for ${file.path}. ' + '${changeKindTitle(file.kind)} · ${changeFileMeta(file)}', + excludeSemantics: true, + onTap: onTap, + child: ListTile( + dense: true, + visualDensity: VisualDensity.compact, + minLeadingWidth: 20, + selected: selected, + selectedTileColor: theme.colorScheme.secondaryContainer, + selectedColor: theme.colorScheme.onSecondaryContainer, + leading: Icon(changeKindIcon(file.kind), size: 20), + title: Text( + name, + style: mono, + maxLines: 1, + overflow: TextOverflow.ellipsis, + ), + subtitle: folder.isEmpty + ? null + : Text(folder, maxLines: 1, overflow: TextOverflow.ellipsis), + trailing: ChangeStatText(changeStat(file.added, file.removed)), + onTap: onTap, + ), + ); + } +} diff --git a/app/lib/features/changes/widgets/changes_viewer.dart b/app/lib/features/changes/widgets/changes_viewer.dart index 6247e356..d93b4ce3 100644 --- a/app/lib/features/changes/widgets/changes_viewer.dart +++ b/app/lib/features/changes/widgets/changes_viewer.dart @@ -6,6 +6,7 @@ import '../domain/change_wording.dart'; import '../domain/file_change.dart'; import '../domain/run_changes.dart'; import 'capture_section.dart'; +import 'changes_split_view.dart'; import 'change_style.dart'; import 'file_diff_viewer.dart'; import 'visit_pager.dart'; @@ -97,7 +98,14 @@ class _ChangesViewerState extends State { static const _query = ''; @override - Widget build(BuildContext context) { + Widget build(BuildContext context) => LayoutBuilder( + builder: (context, constraints) => + _build(context, split: changesSplitFits(context, constraints.maxWidth)), + ); + + /// [split] shows the files beside the selected file's diff (a wide pane) + /// rather than one row per file opening its own page. + Widget _build(BuildContext context, {required bool split}) { final run = _run; final captures = _captures; final showSummary = widget.showSummary; @@ -106,6 +114,7 @@ class _ChangesViewerState extends State { ); final note = showSummary ? runChangesNote(run) : ''; final visit = captures.isEmpty ? null : captures[_visitIndex]; + final visitFiles = visit?.capture?.files ?? const []; final hasVisitPager = !widget.finalOnly && captures.length > 1; final pager = hasVisitPager ? ChangesVisitPager( @@ -158,7 +167,17 @@ class _ChangesViewerState extends State { ), if (showSummary) const Divider(height: 1), // The run's final changes: every changed path once, as it ended. - if (widget.finalOnly) + if (widget.finalOnly && split && run.files.isNotEmpty) + Expanded( + child: Padding( + padding: withBarClearance(context, EdgeInsets.zero), + child: ChangesSplitView( + key: const ValueKey('changes-final-split'), + files: run.files, + ), + ), + ) + else if (widget.finalOnly) Expanded( child: run.files.isEmpty ? SingleChildScrollView( @@ -184,7 +203,31 @@ class _ChangesViewerState extends State { ], ), ), - if (!widget.finalOnly) + if (!widget.finalOnly && + split && + visit != null && + visitFiles.isNotEmpty) + Expanded( + child: Padding( + padding: hasVisitPager + ? withBarClearance(context, EdgeInsets.zero) + : withTopBarClearance(context, EdgeInsets.zero), + child: ChangesSplitView( + key: ValueKey( + 'changes-visit-split-${visit.stage}-${visit.sequence}', + ), + files: visitFiles, + heading: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + StageCaptureHeading(stage: visit), + const Divider(height: 1), + ], + ), + ), + ), + ) + else if (!widget.finalOnly) Expanded( child: visit == null ? SingleChildScrollView( diff --git a/app/test/features/changes/changes_split_view_test.dart b/app/test/features/changes/changes_split_view_test.dart new file mode 100644 index 00000000..18fe4cbb --- /dev/null +++ b/app/test/features/changes/changes_split_view_test.dart @@ -0,0 +1,148 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/changes/changes.dart'; + +import 'fixtures.dart'; +import 'widget_hosts.dart'; + +String _patch(String path, String line) => + '--- "a/$path"\n' + '+++ "b/$path"\n' + '@@ -1,1 +1,1 @@\n' + '-old $line\n' + '+new $line\n'; + +List _steps() => [ + stepFixture( + fileChanges: captureFixture( + files: [ + fileChangeFixture(path: 'lib/a.dart', patch: _patch('lib/a.dart', 'A')), + fileChangeFixture(path: 'lib/b.dart', patch: _patch('lib/b.dart', 'B')), + fileChangeFixture(path: 'lib/c.dart', patch: _patch('lib/c.dart', 'C')), + ], + ), + ), +]; + +Future _pumpAt( + WidgetTester tester, + Size size, { + bool finalOnly = true, +}) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + await tester.pumpWidget( + materialHost(ChangesViewer(steps: _steps(), finalOnly: finalOnly)), + ); + await tester.pumpAndSettle(); +} + +bool _shows(String text) => + find.textContaining(text, findRichText: true).evaluate().isNotEmpty; + +void main() { + testWidgets('a wide pane lists the files beside the first file\'s diff', ( + tester, + ) async { + await _pumpAt(tester, const Size(1400, 900)); + expect(find.byKey(const ValueKey('changes-final-split')), findsOneWidget); + expect(find.byType(FileDiffViewer), findsOneWidget); + expect( + find.byKey(const ValueKey('changes-split-diff-lib/a.dart')), + findsOneWidget, + ); + expect(_shows('new A'), isTrue); + expect(_shows('new B'), isFalse); + }); + + testWidgets('tapping a file shows its diff without leaving the pane', ( + tester, + ) async { + await _pumpAt(tester, const Size(1400, 900)); + await tester.tap(find.bySemanticsLabel(RegExp('^Show diff for lib/c'))); + await tester.pumpAndSettle(); + expect(find.byType(FileDiffPage), findsNothing); + expect( + find.byKey(const ValueKey('changes-split-diff-lib/c.dart')), + findsOneWidget, + ); + expect(_shows('new C'), isTrue); + }); + + testWidgets('j/k and the arrows move between files once focused', ( + tester, + ) async { + await _pumpAt(tester, const Size(1400, 900)); + await tester.tap(find.bySemanticsLabel(RegExp('^Show diff for lib/a'))); + await tester.pumpAndSettle(); + Future press(LogicalKeyboardKey key) async { + await tester.sendKeyEvent(key); + await tester.pumpAndSettle(); + } + + await press(LogicalKeyboardKey.keyJ); + expect(_shows('new B'), isTrue); + await press(LogicalKeyboardKey.arrowDown); + expect(_shows('new C'), isTrue); + // The last file stays selected rather than wrapping. + await press(LogicalKeyboardKey.keyJ); + expect(_shows('new C'), isTrue); + await press(LogicalKeyboardKey.keyK); + expect(_shows('new B'), isTrue); + await press(LogicalKeyboardKey.arrowUp); + expect(_shows('new A'), isTrue); + // Enter opens the selected file on its own page. + await press(LogicalKeyboardKey.enter); + expect(find.byType(FileDiffPage), findsOneWidget); + }); + + testWidgets('a visit page splits too, under the visit heading', ( + tester, + ) async { + await _pumpAt(tester, const Size(1400, 900), finalOnly: false); + expect( + find.byKey(const ValueKey('changes-visit-split-implementer-1')), + findsOneWidget, + ); + expect(find.textContaining('Visit 1'), findsOneWidget); + expect(_shows('new A'), isTrue); + }); + + testWidgets('a phone keeps one row per file opening its own page', ( + tester, + ) async { + await _pumpAt(tester, const Size(560, 1000)); + expect(find.byKey(const ValueKey('changes-final-split')), findsNothing); + expect(find.byType(FileDiffViewer), findsNothing); + await tester.tap(find.bySemanticsLabel(RegExp('^Open diff for lib/b'))); + await tester.pumpAndSettle(); + expect(find.byType(FileDiffPage), findsOneWidget); + }); + + testWidgets( + 'a detail pane beside a list splits from 720 px in a wide window', + (tester) async { + tester.view.physicalSize = const Size(1440, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + Widget pane(double width) => materialHost( + Align( + alignment: Alignment.topRight, + child: SizedBox( + width: width, + child: ChangesViewer(steps: _steps(), finalOnly: true), + ), + ), + ); + await tester.pumpWidget(pane(900)); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('changes-final-split')), findsOneWidget); + await tester.pumpWidget(pane(600)); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('changes-final-split')), findsNothing); + }, + ); +} From 072db8f749af36406df07a5f710e50d8fc4e7697 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:32:57 +0000 Subject: [PATCH 06/19] Runs: failure banner actions, immediate run menu; pipeline rows get Run MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - "Why it failed" banner offers Retry (the retry prompt), Run again… (New run form pre-filled; now allowed for failed runs from the banner) and Open in chat (the run's existing send-to-chat flow). - The run ⋮ menu shows while the detail loads: items listed from the run's list row, disabled until get_run answers (the loading placeholder had no actions, so the menu waited for the full detail). - Pipelines list rows: Run… in the row menu (not for archived pipelines) and a trailing Run button when the list sits beside its detail. Co-Authored-By: Claude Opus 5.5 --- app/lib/features/pipelines/screen.dart | 17 ++ .../pipelines/ui/run_pipeline_from_list.dart | 41 +++++ .../widgets/pipeline_list_panel.dart | 51 ++++-- .../widgets/pipeline_row_actions.dart | 73 ++++++++ .../runs/actions/retry_eligibility.dart | 11 +- app/lib/features/runs/ui/run_again_flow.dart | 2 +- .../features/runs/ui/run_detail_material.dart | 2 + .../runs/ui/run_detail_tab_bodies.dart | 5 +- app/lib/features/runs/ui/run_detail_tabs.dart | 6 + app/lib/features/runs/ui/run_detail_view.dart | 36 ++++ .../features/runs/ui/run_failure_actions.dart | 95 +++++++++++ .../features/runs/ui/run_failure_banner.dart | 11 +- app/lib/features/runs/ui/run_more_menu.dart | 6 + .../pipelines/ui/pipeline_row_run_test.dart | 88 ++++++++++ .../runs/ui/run_failure_actions_test.dart | 156 ++++++++++++++++++ 15 files changed, 578 insertions(+), 22 deletions(-) create mode 100644 app/lib/features/pipelines/ui/run_pipeline_from_list.dart create mode 100644 app/lib/features/pipelines/widgets/pipeline_row_actions.dart create mode 100644 app/lib/features/runs/ui/run_failure_actions.dart create mode 100644 app/test/features/pipelines/ui/pipeline_row_run_test.dart create mode 100644 app/test/features/runs/ui/run_failure_actions_test.dart diff --git a/app/lib/features/pipelines/screen.dart b/app/lib/features/pipelines/screen.dart index 523ae975..e60eebe6 100644 --- a/app/lib/features/pipelines/screen.dart +++ b/app/lib/features/pipelines/screen.dart @@ -1,3 +1,5 @@ +import 'dart:async'; + import '../../ui/adaptive/segmented_bar.dart'; import '../../shell/destination.dart'; import '../../shell/detail_page.dart'; @@ -15,6 +17,7 @@ import 'pending_run_store.dart'; import 'widgets/pipeline_bar_buttons.dart'; import 'widgets/pipeline_detail_panel.dart'; import 'widgets/pipeline_list_panel.dart'; +import 'ui/run_pipeline_from_list.dart'; export 'pipeline_models.dart' show PipelineDetail, PipelineVersion; @@ -223,6 +226,18 @@ class _PipelinesScreenState extends State { return _isRoutePin(detail) ? key : null; } + /// A list row's Run: the same start flow as the detail's Run button. + void _runFromList(BuildContext context, PipelineSummary pipeline) => + unawaited( + startPipelineRunFromList( + context: context, + pipeline: pipeline, + controller: _controller, + gateway: widget.gateway, + onRunStarted: widget.onRunStarted, + ), + ); + @override Widget build(BuildContext context) { return AnimatedBuilder( @@ -262,6 +277,7 @@ class _PipelinesScreenState extends State { child: PipelineListPanel( controller: _controller, onOpenInChat: widget.onOpenPipelineInChat, + onRun: _runFromList, ), ); } @@ -270,6 +286,7 @@ class _PipelinesScreenState extends State { child: PipelineListPanel( controller: _controller, onOpenInChat: widget.onOpenPipelineInChat, + onRun: _runFromList, ), ), detailIdentity: _controller.selectedId, diff --git a/app/lib/features/pipelines/ui/run_pipeline_from_list.dart b/app/lib/features/pipelines/ui/run_pipeline_from_list.dart new file mode 100644 index 00000000..76046f72 --- /dev/null +++ b/app/lib/features/pipelines/ui/run_pipeline_from_list.dart @@ -0,0 +1,41 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../pipeline_models.dart'; +import '../pipeline_repository.dart'; +import '../pipelines_controller.dart'; +import 'run_pipeline_flow.dart'; +import 'run_pipeline_wording.dart'; + +/// A list row's Run: reads the row's pipeline at its listed version, then +/// opens the same start flow as the detail's Run button. Nothing starts until +/// the form's own confirm; a refused read is shown, never a guessed form. +Future startPipelineRunFromList({ + required BuildContext context, + required PipelineSummary pipeline, + required PipelinesController controller, + required ApiGateway gateway, + ValueChanged? onRunStarted, +}) async { + if (pipeline.archived) return; + final PipelineDetail detail; + try { + detail = await PipelinesRepository( + gateway, + ).getPipeline(pipeline.id, pipeline.version); + } catch (error) { + if (!context.mounted) return; + ScaffoldMessenger.maybeOf( + context, + )?.showSnackBar(SnackBar(content: Text(describeRunPipelineError(error)))); + return; + } + if (!context.mounted) return; + await openRunPipelineFlow( + context: context, + controller: controller, + detail: detail, + gateway: gateway, + onRunStarted: onRunStarted, + ); +} diff --git a/app/lib/features/pipelines/widgets/pipeline_list_panel.dart b/app/lib/features/pipelines/widgets/pipeline_list_panel.dart index 7e958e32..a04f44d7 100644 --- a/app/lib/features/pipelines/widgets/pipeline_list_panel.dart +++ b/app/lib/features/pipelines/widgets/pipeline_list_panel.dart @@ -14,7 +14,8 @@ import '../pipelines_controller.dart'; import 'pipeline_controls.dart'; import 'pipeline_filter_page.dart'; import 'pipeline_scope_control.dart'; -import '../../../ui/layout/app_overflow_menu.dart'; +import '../../../shell/list_detail_policy.dart'; +import 'pipeline_row_actions.dart'; /// The list's horizontal rhythm, matching the web's toolbar and row inset /// (`var(--space-s)`: 12px). The detail pane keeps its own content padding. @@ -26,12 +27,17 @@ class PipelineListPanel extends StatelessWidget { super.key, required this.controller, this.onOpenInChat, + this.onRun, }); final PipelinesController controller; final Future Function(BuildContext, PipelineSummary, PipelineRun?)? onOpenInChat; + /// Opens the New run form for a row's pipeline (its menu's Run…, and its + /// trailing Run button on a wide list); null offers neither. + final void Function(BuildContext, PipelineSummary)? onRun; + @override Widget build(BuildContext context) { final filters = controller.filters; @@ -230,6 +236,23 @@ class PipelineListPanel extends StatelessWidget { final now = DateTime.now(); // The default padding is the media padding: the controls start below the // top bar and the last row clears the floating tab bar. + return LayoutBuilder( + builder: (context, constraints) => + _rows(context, header, items, now, constraints.maxWidth), + ); + } + + Widget _rows( + BuildContext context, + List header, + List items, + DateTime now, + double width, + ) { + // A wide layout's list, beside its detail and wide enough, gives each row + // its own Run button beside its menu; a phone keeps Run in the menu. + final wide = + showsListBesideDetail(context) && width >= kPipelineRowRunButtonWidth; return ListView.builder( key: const Key('pipeline-list'), itemCount: header.length + items.length, @@ -271,22 +294,16 @@ class PipelineListPanel extends StatelessWidget { : Text( ServerContext.metadata(context, runStateLabel(badge.state)), ), - menu: onOpenInChat == null - ? null - : AppOverflowMenu( - key: Key('pipeline-row-more-menu-${pipeline.id}'), - label: 'Pipeline actions', - sheetTitle: pipeline.displayName, - actions: const [ - AppMenuAction( - value: true, - label: 'Send to chat…', - icon: Icons.chat_bubble_outline, - ), - ], - onSelected: (context, _) => - onOpenInChat!(context, pipeline, run), - ), + menu: pipelineRowActions( + pipeline: pipeline, + wide: wide, + onRun: onRun == null + ? null + : (context) => onRun!(context, pipeline), + onOpenInChat: onOpenInChat == null + ? null + : (context) => onOpenInChat!(context, pipeline, run), + ), ); }, ); diff --git a/app/lib/features/pipelines/widgets/pipeline_row_actions.dart b/app/lib/features/pipelines/widgets/pipeline_row_actions.dart new file mode 100644 index 00000000..20ea3963 --- /dev/null +++ b/app/lib/features/pipelines/widgets/pipeline_row_actions.dart @@ -0,0 +1,73 @@ +import 'package:flutter/material.dart'; + +import '../../../ui/layout/app_overflow_menu.dart'; +import '../pipeline_models.dart'; +import '../ui/run_pipeline_wording.dart'; + +/// The pipeline list's width from which each row shows its own Run button +/// beside its menu; a narrower list keeps Run in the menu only. +const double kPipelineRowRunButtonWidth = 360; + +const pipelineRowRunLabel = 'Run…'; + +Key pipelineRowRunKey(int id) => ValueKey('pipeline-row-run-$id'); +Key pipelineRowRunMenuKey(int id) => ValueKey('pipeline-row-run-menu-$id'); +Key pipelineRowMenuKey(int id) => ValueKey('pipeline-row-more-menu-$id'); + +enum _PipelineRowAction { run, sendToChat } + +/// A pipeline row's trailing actions: its menu (Run…, Send to chat…) and, on +/// a [wide] list, a Run button before it. Run is not offered for an archived +/// pipeline, as its detail offers none. Null when there is nothing to offer. +Widget? pipelineRowActions({ + required PipelineSummary pipeline, + required bool wide, + void Function(BuildContext)? onRun, + void Function(BuildContext)? onOpenInChat, +}) { + final run = pipeline.archived ? null : onRun; + final actions = [ + if (run != null) + AppMenuAction( + key: pipelineRowRunMenuKey(pipeline.id), + value: _PipelineRowAction.run, + label: pipelineRowRunLabel, + icon: Icons.play_arrow_rounded, + ), + if (onOpenInChat != null) + const AppMenuAction( + value: _PipelineRowAction.sendToChat, + label: 'Send to chat…', + icon: Icons.chat_bubble_outline, + ), + ]; + if (actions.isEmpty) return null; + final menu = AppOverflowMenu<_PipelineRowAction>( + key: pipelineRowMenuKey(pipeline.id), + label: 'Pipeline actions', + sheetTitle: pipeline.displayName, + actions: actions, + onSelected: (context, action) => switch (action) { + _PipelineRowAction.run => run!(context), + _PipelineRowAction.sendToChat => onOpenInChat!(context), + }, + ); + if (!wide || run == null) return menu; + return Row( + mainAxisSize: MainAxisSize.min, + children: [ + Builder( + builder: (context) => TextButton.icon( + key: pipelineRowRunKey(pipeline.id), + onPressed: () => run(context), + icon: const Icon(Icons.play_arrow_rounded), + label: Text( + runPipelineActionLabel, + semanticsLabel: 'Run ${pipeline.displayName}', + ), + ), + ), + menu, + ], + ); +} diff --git a/app/lib/features/runs/actions/retry_eligibility.dart b/app/lib/features/runs/actions/retry_eligibility.dart index 0af6b64d..82f7809b 100644 --- a/app/lib/features/runs/actions/retry_eligibility.dart +++ b/app/lib/features/runs/actions/retry_eligibility.dart @@ -11,12 +11,19 @@ bool canRetryRun(JsonMap? run) { /// Whether [run] can be started again with its inputs: a finished run that /// succeeded, was canceled or was interrupted, and names its pipeline. A -/// failed run has Retry instead. -bool canRunAgain(JsonMap? run) { +/// failed run has Retry instead in menus (see [canStartRunAgain]). +bool canRunAgain(JsonMap? run) => + canStartRunAgain(run) && run!['status'] != 'failed'; + +/// Whether the New run form can be pre-filled from [run]: any finished run, +/// failed included, that names its pipeline. A failed run's banner offers it +/// beside Retry. +bool canStartRunAgain(JsonMap? run) { if (run == null || run['executing'] == true) return false; final pipeline = run['pipeline_id']; return const { 'succeeded', + 'failed', 'canceled', 'interrupted', }.contains(run['status']) && diff --git a/app/lib/features/runs/ui/run_again_flow.dart b/app/lib/features/runs/ui/run_again_flow.dart index d83eb0c1..8e7709bb 100644 --- a/app/lib/features/runs/ui/run_again_flow.dart +++ b/app/lib/features/runs/ui/run_again_flow.dart @@ -38,7 +38,7 @@ Future startRunAgainFlow({ required ApiGateway gateway, ValueChanged? onRunStarted, }) async { - if (!canRunAgain(run)) return; + if (!canStartRunAgain(run)) return; final pipelineId = (run['pipeline_id'] as num).toInt(); final JsonMap full; final PipelineDetail detail; diff --git a/app/lib/features/runs/ui/run_detail_material.dart b/app/lib/features/runs/ui/run_detail_material.dart index d9553682..0793e257 100644 --- a/app/lib/features/runs/ui/run_detail_material.dart +++ b/app/lib/features/runs/ui/run_detail_material.dart @@ -26,9 +26,11 @@ Widget buildMaterialRunDetail({ String? initialStageKey, int? initialVisit, void Function(String draft)? onSendToChat, + Widget? failureActions, }) { return RunDetailTabs( run: run, + failureActions: failureActions, copying: copying, copyStatus: copyStatus, onCopy: onCopy, diff --git a/app/lib/features/runs/ui/run_detail_tab_bodies.dart b/app/lib/features/runs/ui/run_detail_tab_bodies.dart index 40d8a73e..d898c106 100644 --- a/app/lib/features/runs/ui/run_detail_tab_bodies.dart +++ b/app/lib/features/runs/ui/run_detail_tab_bodies.dart @@ -30,6 +30,7 @@ Widget runDetailSummaryTab({ ExpansibleController? inputController, ExpansibleController? outputController, Widget? graphPreview, + Widget? failureActions, }) { final rows = detailSummaryRows(run); final identity = detailSummaryIdentity(run); @@ -61,7 +62,9 @@ Widget runDetailSummaryTab({ ), ), ), - SliverToBoxAdapter(child: RunFailureBanner(run: run)), + SliverToBoxAdapter( + child: RunFailureBanner(run: run, actions: failureActions), + ), SliverToBoxAdapter( child: WarningsSection(messages: warningMessages(run['warnings'])), ), diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index 0ee737dc..b0e1ba27 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -56,10 +56,15 @@ class RunDetailTabs extends StatefulWidget { this.initialStageKey, this.initialVisit, this.onSendToChat, + this.failureActions, }); final JsonMap run; + /// What a failed run's "Why it failed" banner offers (Retry, Run again…, + /// Open in chat); null offers none. + final Widget? failureActions; + /// The host's own header: status, the run actions and notices. It floats /// outside the tab body, so switching tabs never drops an action. final Widget header; @@ -458,6 +463,7 @@ class _RunDetailTabsState extends State { onCopy: widget.onCopy, inputController: _inputSection, outputController: _outputSection, + failureActions: widget.failureActions, graphPreview: RunGraphPreview( graph: detailGraph(widget.run), run: widget.run, diff --git a/app/lib/features/runs/ui/run_detail_view.dart b/app/lib/features/runs/ui/run_detail_view.dart index 7d724f81..eb57496b 100644 --- a/app/lib/features/runs/ui/run_detail_view.dart +++ b/app/lib/features/runs/ui/run_detail_view.dart @@ -12,6 +12,7 @@ import 'run_more_menu.dart'; import 'run_pipeline_link.dart'; import 'run_detail_content.dart'; import 'run_detail_material.dart'; +import 'run_failure_actions.dart'; import 'runs_controller.dart'; import '../../../core/error_advice.dart'; import '../../../ui/status/error_notice.dart'; @@ -96,6 +97,14 @@ class _RunDetailViewState extends State { onSendToChat: widget.onSendToChat == null ? null : (draft) => widget.onSendToChat!(context, run, draft), + failureActions: RunFailureActions( + run: run, + gateway: widget.gateway, + onRunChanged: widget.controller.acceptRunDetail, + onRunOpened: widget.onRunOpened, + onRunAgain: widget.onRunAgain, + onOpenInChat: widget.onOpenInChat, + ), ); // The top bar becomes the run's: Back to the list, its title over its // number, pipeline and version (a link to that pipeline when the host @@ -181,14 +190,41 @@ class _RunDetailViewState extends State { : widget.controller.error ?? 'Run details unavailable.'; // Back stays available while the detail is pending as well as after a // failure, so a slow or refused request can never trap the destination. + // The more menu is there from the first frame: while the detail loads its + // items are listed from the run's list row, disabled until the detail + // they act on arrives. + final pending = _pendingRun(); return ShellBar( title: 'Run', onBack: widget.onBack, hideNavigation: true, + actions: [ + if (loading && pending != null) + RunMoreMenu( + run: pending, + gateway: widget.gateway, + onRunChanged: widget.controller.acceptRunDetail, + onDeleted: widget.controller.applyDeletion, + onOpenInChat: widget.onOpenInChat, + onRunAgain: widget.onRunAgain, + pending: true, + ), + ], child: _placeholderBody(loading, message), ); } + /// The selected run as its list row knows it, else only its id; null when + /// no run is selected. + JsonMap? _pendingRun() { + final id = widget.controller.selectedRunId; + if (id == null) return null; + for (final run in widget.controller.runs) { + if (run['id'] == id) return run; + } + return {'id': id}; + } + Widget _placeholderBody(bool loading, String message) { return Center( child: Column( diff --git a/app/lib/features/runs/ui/run_failure_actions.dart b/app/lib/features/runs/ui/run_failure_actions.dart new file mode 100644 index 00000000..12420f01 --- /dev/null +++ b/app/lib/features/runs/ui/run_failure_actions.dart @@ -0,0 +1,95 @@ +import 'package:flutter/material.dart'; + +import '../../../core/api_gateway.dart'; +import '../actions/retry_action.dart'; +import '../actions/retry_eligibility.dart'; +import '../actions/retry_wording.dart'; +import 'run_again_flow.dart'; + +const runFailureRetryKey = ValueKey('run-failure-retry'); +const runFailureRunAgainKey = ValueKey('run-failure-run-again'); +const runFailureOpenInChatKey = ValueKey('run-failure-open-in-chat'); +const runFailureOpenInChatLabel = 'Open in chat'; + +/// What a failed run's "Why it failed" banner offers: Retry (the server's +/// retry, as the more menu's), Run again… (the New run form pre-filled from +/// the run) and Open in chat (the run's send-to-chat flow, with its context). +/// +/// Each is the existing action; one the host cannot apply is omitted. It stays +/// mounted while a picked flow runs, so a retry's result reaches the run. +class RunFailureActions extends StatefulWidget { + const RunFailureActions({ + super.key, + required this.run, + required this.gateway, + required this.onRunChanged, + this.onRunOpened, + this.onRunAgain, + this.onOpenInChat, + }); + + final JsonMap run; + final ApiGateway gateway; + final ValueChanged onRunChanged; + final ValueChanged? onRunOpened; + final ValueChanged? onRunAgain; + final Future Function(BuildContext, JsonMap)? onOpenInChat; + + @override + State createState() => _RunFailureActionsState(); +} + +class _RunFailureActionsState extends State { + void _retry() => openRetryRunPrompt( + context, + run: widget.run, + gateway: widget.gateway, + onRunChanged: widget.onRunChanged, + onRunOpened: widget.onRunOpened, + owns: (owned) => mounted && retryRunId(widget.run) == owned, + ); + + @override + Widget build(BuildContext context) { + final run = widget.run; + final scheme = Theme.of(context).colorScheme; + final onBanner = TextButton.styleFrom( + foregroundColor: scheme.onErrorContainer, + ); + final runAgain = widget.onRunAgain; + final openInChat = widget.onOpenInChat; + return Wrap( + spacing: 8, + runSpacing: 4, + children: [ + if (retryRunId(run) != null && canRetryRun(run)) + FilledButton.icon( + key: runFailureRetryKey, + style: FilledButton.styleFrom( + backgroundColor: scheme.error, + foregroundColor: scheme.onError, + ), + onPressed: _retry, + icon: const Icon(Icons.replay), + label: const Text(retryActionLabel), + ), + if (runAgain != null && canStartRunAgain(run)) + TextButton.icon( + key: runFailureRunAgainKey, + style: onBanner, + onPressed: () => runAgain(run), + icon: const Icon(Icons.edit_note), + label: const Text(runAgainActionLabel), + ), + if (openInChat != null) + TextButton.icon( + key: runFailureOpenInChatKey, + style: onBanner, + onPressed: () => openInChat(context, run), + icon: const Icon(Icons.chat_bubble_outline), + label: const Text(runFailureOpenInChatLabel), + ), + ], + ); + } +} diff --git a/app/lib/features/runs/ui/run_failure_banner.dart b/app/lib/features/runs/ui/run_failure_banner.dart index c4ff16b5..034d14e8 100644 --- a/app/lib/features/runs/ui/run_failure_banner.dart +++ b/app/lib/features/runs/ui/run_failure_banner.dart @@ -6,10 +6,15 @@ import '../domain/run_outcome_line.dart'; /// The run Summary's prominent "Why it failed" note: a failed run's recorded /// failure reason (else its diagnostic), selectable, at the top of the /// Summary so the reason is read before the facts. Nothing for other runs. +/// +/// [actions] (the run's Retry, Run again… and Open in chat; see +/// `RunFailureActions`) sit under the reason, so what to do next is beside +/// why it failed. class RunFailureBanner extends StatelessWidget { - const RunFailureBanner({super.key, required this.run}); + const RunFailureBanner({super.key, required this.run, this.actions}); final JsonMap run; + final Widget? actions; @override Widget build(BuildContext context) { @@ -53,6 +58,10 @@ class RunFailureBanner extends StatelessWidget { color: scheme.onErrorContainer, ), ), + if (actions case final actions?) ...[ + const SizedBox(height: 8), + actions, + ], ], ), ), diff --git a/app/lib/features/runs/ui/run_more_menu.dart b/app/lib/features/runs/ui/run_more_menu.dart index 4c026d7f..a5a77027 100644 --- a/app/lib/features/runs/ui/run_more_menu.dart +++ b/app/lib/features/runs/ui/run_more_menu.dart @@ -72,8 +72,13 @@ class RunMoreMenu extends StatefulWidget { this.onOpenInChat, this.onRunAgain, this.menuKey = runMoreMenuKey, + this.pending = false, }); + /// The run's detail is still loading: [run] is its list row (or only its + /// id), so the items are listed but disabled until the detail arrives. + final bool pending; + /// Opens the New run form pre-filled from this run (finished runs that /// did not fail); without it the menu offers no Run again. final ValueChanged? onRunAgain; @@ -168,6 +173,7 @@ class _RunMoreMenuState extends State { _RunMoreItem.openInChat => Icons.chat_bubble_outline, }, destructive: item == _RunMoreItem.delete, + enabled: !widget.pending, ), ], onSelected: _pick, diff --git a/app/test/features/pipelines/ui/pipeline_row_run_test.dart b/app/test/features/pipelines/ui/pipeline_row_run_test.dart new file mode 100644 index 00000000..27b77cdc --- /dev/null +++ b/app/test/features/pipelines/ui/pipeline_row_run_test.dart @@ -0,0 +1,88 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:pipelines_app/features/pipelines/screen.dart'; +import 'package:pipelines_app/features/pipelines/ui/run_pipeline_wording.dart'; +import 'package:pipelines_app/features/pipelines/widgets/pipeline_row_actions.dart'; + +import 'package:pipelines_app/features/pipelines/pipeline_models.dart'; +import 'package:pipelines_app/ui/layout/app_overflow_menu.dart'; + +import '../fixtures.dart'; +import 'run_pipeline_launch_test.dart' show acceptedRun, launchGateway; + +Future _pump(WidgetTester tester, Size size, FakeGateway gateway) async { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget(MaterialApp(home: PipelinesScreen(gateway: gateway))); + await tester.pumpAndSettle(); +} + +void main() { + SharedPreferences.setMockInitialValues({}); + + testWidgets('a wide list row has its own Run button opening the form', ( + tester, + ) async { + final fixture = PipelineFixture(); + final gateway = launchGateway(fixture, onLaunch: (_) => acceptedRun(9)); + await _pump(tester, const Size(1440, 900), gateway); + + expect(find.byKey(pipelineRowRunKey(1)), findsOneWidget); + await tester.tap(find.byKey(pipelineRowRunKey(1))); + await tester.pumpAndSettle(); + + // The same New run form as the detail's Run, for the row's pipeline at + // its listed version; opening it starts nothing. + expect(find.byKey(runPipelinePromptKey), findsOneWidget); + expect(gateway.callsOf('get_pipeline').last.fields, { + 'pipeline_id': 1, + 'version': 2, + }); + expect(gateway.callsOf('run_pipeline'), isEmpty); + // The row did not open the pipeline. + expect(find.byKey(const Key('pipeline-detail')), findsNothing); + }); + + testWidgets('a phone row offers Run… in its menu and no button', ( + tester, + ) async { + final fixture = PipelineFixture(); + final gateway = launchGateway(fixture, onLaunch: (_) => acceptedRun(9)); + await _pump(tester, const Size(560, 900), gateway); + + expect(find.byKey(pipelineRowRunKey(2)), findsNothing); + await tester.tap(find.byKey(pipelineRowMenuKey(2))); + await tester.pumpAndSettle(); + await tester.tap(find.text(pipelineRowRunLabel)); + await tester.pumpAndSettle(); + + expect(find.byKey(runPipelinePromptKey), findsOneWidget); + expect(gateway.callsOf('get_pipeline').last.fields['pipeline_id'], 2); + }); + + test('an archived pipeline offers no Run, as its detail offers none', () { + final archived = PipelineSummary.fromJson({ + ...pipelineSummary(id: 4, name: 'Old'), + 'archived_at': '2026-10-01T00:00:00Z', + }); + void run(BuildContext _) {} + + expect( + pipelineRowActions(pipeline: archived, wide: true, onRun: run), + isNull, + ); + // Send to chat stays; only Run is withheld. + expect( + pipelineRowActions( + pipeline: archived, + wide: true, + onRun: run, + onOpenInChat: run, + ), + isA>(), + ); + }); +} diff --git a/app/test/features/runs/ui/run_failure_actions_test.dart b/app/test/features/runs/ui/run_failure_actions_test.dart new file mode 100644 index 00000000..efeebc99 --- /dev/null +++ b/app/test/features/runs/ui/run_failure_actions_test.dart @@ -0,0 +1,156 @@ +import 'dart:async'; + +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/runs/actions/retry_wording.dart'; +import 'package:pipelines_app/features/runs/actions/title_wording.dart'; +import 'package:pipelines_app/features/runs/screen.dart'; +import 'package:pipelines_app/features/runs/ui/run_failure_actions.dart'; +import 'package:pipelines_app/features/runs/ui/run_more_menu.dart'; + +import 'run_retry_wiring_support.dart'; + +Future _mount( + WidgetTester tester, + ApiGateway gateway, { + Future Function(BuildContext, JsonMap)? onOpenInChat, + bool settle = true, +}) async { + tester.view.physicalSize = const Size(1200, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunsScreen( + gateway: gateway, + initialRunId: 7, + onOpenInChat: onOpenInChat, + ), + ), + ), + ); + if (settle) await tester.pumpAndSettle(); +} + +/// A gateway that lists run 7 but never answers its detail. +class _SlowDetailGateway implements ApiGateway { + final pending = Completer(); + + @override + Stream get frames => const Stream.empty(); + + @override + Future call(String type, [JsonMap fields = const {}]) => + switch (type) { + 'list_runs' => Future.value({ + 'runs': [ + {'id': 7, 'title': 'Slow run', 'status': 'failed', 'name': 'p'}, + ], + }), + 'get_run' => pending.future, + _ => Future.error(UnsupportedError(type)), + }; +} + +void main() { + testWidgets('the failure banner offers Retry, Run again… and Open in chat', ( + tester, + ) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + gateway.details[7] = { + ...retryFailedDetail(), + 'pipeline_id': 3, + 'version': 2, + 'failure_reason': 'The build stage exited with status 2.', + }; + final opened = []; + await _mount( + tester, + gateway, + onOpenInChat: (context, run) async => opened.add(run), + ); + + expect(find.text('The build stage exited with status 2.'), findsOneWidget); + expect(find.byKey(runFailureRetryKey), findsOneWidget); + expect(find.byKey(runFailureRunAgainKey), findsOneWidget); + expect(find.byKey(runFailureOpenInChatKey), findsOneWidget); + + // Retry is the menu's retry prompt; nothing is sent until its confirm. + await tester.tap(find.byKey(runFailureRetryKey)); + await tester.pumpAndSettle(); + expect(find.text(retryDialogTitle(7)), findsOneWidget); + await tester.tap(find.byKey(retryKeepKey)); + await tester.pumpAndSettle(); + expect(gateway.retryCalls, isEmpty); + + // Open in chat hands the run to the host's send-to-chat flow. + await tester.tap(find.byKey(runFailureOpenInChatKey)); + await tester.pumpAndSettle(); + expect(opened.single['id'], 7); + + // Run again reads the run's pipeline for the pre-filled New run form. + await tester.tap(find.byKey(runFailureRunAgainKey)); + await tester.pumpAndSettle(); + expect(gateway.calls.map((call) => call.type), contains('get_pipeline')); + }); + + testWidgets('a failed run without a pipeline offers no Run again', ( + tester, + ) async { + final gateway = RetryWiringGateway(); + addTearDown(gateway.framesController.close); + gateway.details[7] = {...retryFailedDetail(), 'failure_reason': 'Boom.'}; + await _mount(tester, gateway); + + expect(find.byKey(runFailureRetryKey), findsOneWidget); + expect(find.byKey(runFailureRunAgainKey), findsNothing); + expect(find.byKey(runFailureOpenInChatKey), findsNothing); + }); + + testWidgets('the more menu shows while the detail loads, items disabled', ( + tester, + ) async { + final gateway = _SlowDetailGateway(); + await _mount(tester, gateway, settle: false); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 50)); + + expect(find.text('Loading run details…'), findsOneWidget); + expect(find.byKey(runMoreMenuKey), findsOneWidget); + await tester.tap(find.byKey(runMoreMenuKey)); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 400)); + final rename = tester.widget>( + find.ancestor( + of: find.text(runTitleActionLabel), + matching: find.byWidgetPredicate((w) => w is PopupMenuItem), + ), + ); + expect(rename.enabled, isFalse); + + gateway.pending.complete({ + 'run_detail': { + 'id': 7, + 'title': 'Slow run', + 'status': 'failed', + 'name': 'p', + 'steps': const [], + }, + }); + await tester.tapAt(const Offset(2, 2)); + await tester.pumpAndSettle(); + await tester.tap(find.byKey(runMoreMenuKey)); + await tester.pumpAndSettle(); + final loaded = tester.widget>( + find.ancestor( + of: find.text(runTitleActionLabel), + matching: find.byWidgetPredicate((w) => w is PopupMenuItem), + ), + ); + expect(loaded.enabled, isTrue); + }); +} From fbc09528ec891848ec871825c5c4ce23d98c90b9 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:34:16 +0000 Subject: [PATCH 07/19] Chat list: order chat_session_changed pushes by a registry revision operator_sessions gains a revision bumped by a trigger on every update; the wire row carries it, and the app ignores a push (or a list read) older than the row it holds. Co-Authored-By: Claude Opus 5.5 --- .../ui/sessions/chat_sessions_controller.dart | 58 ++++++++++++++++++- .../chat/ui/sessions/chat_color_test.dart | 39 +++++++++++++ internal/pipeline/operator_sessions.go | 26 +++++++-- internal/pipeline/operator_sessions_test.go | 42 ++++++++++++++ internal/protocol/chat.go | 4 ++ internal/server/chat_close.go | 1 + 6 files changed, 163 insertions(+), 7 deletions(-) diff --git a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart index 39b4bb54..8f375f96 100644 --- a/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart +++ b/app/lib/features/chat/ui/sessions/chat_sessions_controller.dart @@ -143,6 +143,10 @@ class ChatSessionsController extends ChangeNotifier { /// Another device changed a chat's shared colour, star or title: the row /// takes the server's values at once, with no re-list. Each field the /// registry row omits is cleared, since omitted means unset on the wire. + /// The server sends these pushes concurrently, so they can arrive out of + /// order: one whose `revision` is older than the row held here is stale and + /// ignored (a row or push without a revision, from an older server, is + /// always applied). /// /// A row naming `previous_id` is a chat another device moved to a fresh /// session (`/new`): it replaces that row in place and [onSessionReplaced] @@ -165,8 +169,14 @@ class ChatSessionsController extends ChangeNotifier { if ('${row['id'] ?? ''}' == id) () { found = true; + if (chatSessionPushIsStale(row, changed)) return row; final next = {...row}; - for (final key in const ['color', 'starred', 'starred_at']) { + for (final key in const [ + 'color', + 'starred', + 'starred_at', + 'revision', + ]) { if (changed.containsKey(key)) { next[key] = changed[key]; } else { @@ -404,8 +414,14 @@ class ChatSessionsController extends ChangeNotifier { final runningRevision = _runningRevision; final sessions = await repository.sessions(); if (generation != _generation) return; + // A push applied while this list was read can be newer than its row. + final held = {for (final row in _sessions) '${row['id'] ?? ''}': row}; _sessions = [ - for (final row in sessions) _withActivity(row, runningRevision), + for (final row in sessions) + _withActivity( + newerChatSessionMetadata(row, held['${row['id'] ?? ''}']), + runningRevision, + ), ]; _seedLocal(); _loading = false; @@ -644,3 +660,41 @@ class ChatSessionsController extends ChangeNotifier { super.dispose(); } } + +/// The registry revision a chat list row or push carries; 0 when absent. +int chatSessionRevision(Map row) { + final value = row['revision']; + return value is num ? value.toInt() : 0; +} + +/// Whether [pushed] is older than [held]: both carry a revision and the +/// push's is lower. A push is never stale against a row with no revision. +bool chatSessionPushIsStale( + Map held, + Map pushed, +) { + final incoming = chatSessionRevision(pushed); + return incoming > 0 && incoming < chatSessionRevision(held); +} + +/// [fetched] with the shared metadata (colour, star, title, revision) of +/// [held] when [held] is newer: a list read that started before a push was +/// applied must not revert it. +JsonMap newerChatSessionMetadata(JsonMap fetched, JsonMap? held) { + if (held == null || !chatSessionPushIsStale(held, fetched)) return fetched; + final next = {...fetched}; + for (final key in const [ + 'color', + 'starred', + 'starred_at', + 'title', + 'revision', + ]) { + if (held.containsKey(key)) { + next[key] = held[key]; + } else { + next.remove(key); + } + } + return next; +} diff --git a/app/test/features/chat/ui/sessions/chat_color_test.dart b/app/test/features/chat/ui/sessions/chat_color_test.dart index d82fdd40..f5647c48 100644 --- a/app/test/features/chat/ui/sessions/chat_color_test.dart +++ b/app/test/features/chat/ui/sessions/chat_color_test.dart @@ -266,6 +266,45 @@ void main() { expect(gateway.count('chat_sessions'), lists); }); + test('a push older than the row held is ignored', () async { + JsonMap push(int revision, String color) => { + 'type': 'chat_session_changed', + 'chat_session': { + 'id': 's2', + 'title': 'Plain chat', + 'color': color, + 'revision': revision, + }, + }; + // The server sends pushes concurrently: revision 7 lands before 6. + gateway.pushed.add(push(7, 'pink')); + gateway.pushed.add(push(6, 'blue')); + await pumpEventQueue(); + expect(row('s2')['color'], 'pink'); + expect(row('s2')['revision'], 7); + gateway.pushed.add(push(8, 'amber')); + await pumpEventQueue(); + expect(row('s2')['color'], 'amber'); + // A list read older than the applied push does not revert it. + var listed = { + 'id': 's2', + 'title': 'Plain chat', + 'directory': '/w', + 'revision': 5, + }; + gateway.sessionsHandler = () async => { + 'chat_sessions': [listed], + }; + await controller.refresh(); + expect(row('s2')['color'], 'amber'); + expect(row('s2')['revision'], 8); + // A newer list row wins. + listed = {...listed, 'color': 'teal', 'revision': 9}; + await controller.refresh(); + expect(row('s2')['color'], 'teal'); + expect(row('s2')['revision'], 9); + }); + test('a refused colour is undone and the reason shown', () async { gateway.failures['chat_color'] = 'unknown chat colour'; await controller.setColor('s2', 'blue'); diff --git a/internal/pipeline/operator_sessions.go b/internal/pipeline/operator_sessions.go index b9d1469e..10d545b1 100644 --- a/internal/pipeline/operator_sessions.go +++ b/internal/pipeline/operator_sessions.go @@ -41,6 +41,9 @@ type OperatorSession struct { // protocol.ChatColors by name, or "" for none. The name, not a shade, is // stored so every client renders its own theme-tuned colour. Color string + // Revision increases with every change to the row (a trigger bumps it), so + // a client receiving list metadata pushes out of order keeps the newest. + Revision int64 } // ChatCreateBootstrap is the durable progress record for one chat_create @@ -175,7 +178,20 @@ func (s *Store) migrateOperatorSessions() error { // replaced_by names the native session a chat moved to when the operator // started a fresh session (/new). The replaced row is kept, unlisted, so the // old id still resolves; existing rows default to '' (current). - return s.addColumnIfMissing("operator_sessions", "replaced_by", "TEXT NOT NULL DEFAULT ''") + if err := s.addColumnIfMissing("operator_sessions", "replaced_by", "TEXT NOT NULL DEFAULT ''"); err != nil { + return err + } + // revision orders a row's states: every update that does not set it bumps + // it, so the chat_session_changed pushes (sent concurrently) can be ordered + // by the client. SQLite does not re-fire a trigger from its own update. + if err := s.addColumnIfMissing("operator_sessions", "revision", "INTEGER NOT NULL DEFAULT 0"); err != nil { + return err + } + _, err := s.db.Exec(`CREATE TRIGGER IF NOT EXISTS operator_sessions_revision AFTER UPDATE ON operator_sessions +FOR EACH ROW WHEN NEW.revision = OLD.revision BEGIN +UPDATE operator_sessions SET revision = OLD.revision + 1 WHERE session_id = NEW.session_id; +END`) + return err } // ErrOperatorSessionReplaced reports that a chat was already moved to another @@ -409,9 +425,9 @@ func (s *Store) SetOperatorSessionColor(ctx context.Context, sessionID, color st // returned). It is one indexed lookup and never mutates the row. func (s *Store) OperatorSession(ctx context.Context, sessionID string) (OperatorSession, bool, error) { var session OperatorSession - row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color + row := s.db.QueryRowContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color,revision FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID) - if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color); err != nil { + if err := row.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color, &session.Revision); err != nil { if errors.Is(err, sql.ErrNoRows) { return OperatorSession{}, false, nil } @@ -430,7 +446,7 @@ FROM operator_sessions WHERE session_id=? AND tag <> ''`, sessionID) // operator can still see and reopen what they finished. It is one bounded // statement; recency is never mutated here. func (s *Store) OperatorSessions(ctx context.Context) ([]OperatorSession, error) { - rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color + rows, err := s.db.QueryContext(ctx, `SELECT session_id,directory,title,tag,backend,created_at,last_used_at,closed_at,starred_at,color,revision FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 AND replaced_by = '' ORDER BY last_used_at DESC, session_id LIMIT ?`, operatorSessionListLimit) if err != nil { return nil, err @@ -439,7 +455,7 @@ FROM operator_sessions WHERE tag <> '' AND ephemeral = 0 AND replaced_by = '' OR sessions := []OperatorSession{} for rows.Next() { var session OperatorSession - if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color); err != nil { + if err := rows.Scan(&session.ID, &session.Directory, &session.Title, &session.Tag, &session.Backend, &session.CreatedAt, &session.UpdatedAt, &session.ClosedAt, &session.StarredAt, &session.Color, &session.Revision); err != nil { return nil, err } sessions = append(sessions, session) diff --git a/internal/pipeline/operator_sessions_test.go b/internal/pipeline/operator_sessions_test.go index 06140a79..ca5b98d6 100644 --- a/internal/pipeline/operator_sessions_test.go +++ b/internal/pipeline/operator_sessions_test.go @@ -320,3 +320,45 @@ func TestOperatorSessionsMigrationAddsEphemeral(t *testing.T) { t.Fatalf("verification session listed after migration: %+v err=%v", listed, err) } } + +// Every change to an operator session bumps its revision, so clients can order +// concurrent chat_session_changed pushes. +func TestOperatorSessionRevisionIncreasesOnEveryChange(t *testing.T) { + ctx := context.Background() + store, err := Open(filepath.Join(t.TempDir(), "revision.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + if err := store.RecordOperatorSession(ctx, "ses_a", "/work/a", "A", "operator"); err != nil { + t.Fatal(err) + } + revision := func() int64 { + t.Helper() + session, found, err := store.OperatorSession(ctx, "ses_a") + if err != nil || !found { + t.Fatalf("read: %v %v", found, err) + } + return session.Revision + } + last := revision() + for i, change := range []func() error{ + func() error { return store.SetOperatorSessionColor(ctx, "ses_a", "red") }, + func() error { return store.SetOperatorSessionStar(ctx, "ses_a", true) }, + func() error { return store.SetOperatorSessionTitle(ctx, "ses_a", "Renamed") }, + func() error { return store.SetOperatorSessionColor(ctx, "ses_a", "") }, + } { + if err := change(); err != nil { + t.Fatal(err) + } + next := revision() + if next != last+1 { + t.Fatalf("change %d: revision %d after %d", i, next, last) + } + last = next + } + sessions, err := store.OperatorSessions(ctx) + if err != nil || len(sessions) != 1 || sessions[0].Revision != last { + t.Fatalf("listed %+v %v, want revision %d", sessions, err, last) + } +} diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index e5433ea3..04bedcfc 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -357,6 +357,10 @@ type ChatSession struct { Tag string `json:"tag,omitempty"` CreatedAt int64 `json:"created_at,omitempty"` UpdatedAt int64 `json:"updated_at,omitempty"` + // Revision increases with every change to the chat's registry row. The + // chat_session_changed pushes may arrive out of order; a client ignores one + // older than the row it holds. 0 (older servers) is unordered. + Revision int64 `json:"revision,omitempty"` // Busy is retained for wire compatibility only: it is never set by this // server. A session is never read-only, any number of clients may watch and // write it, and only a turn is serialised (a waiting prompt is acknowledged diff --git a/internal/server/chat_close.go b/internal/server/chat_close.go index d5eb98c6..a97e9e7a 100644 --- a/internal/server/chat_close.go +++ b/internal/server/chat_close.go @@ -156,6 +156,7 @@ func chatSessionFromOperator(session pipeline.OperatorSession) protocol.ChatSess CreatedAt: session.CreatedAt, UpdatedAt: session.UpdatedAt, Backend: session.Backend, + Revision: session.Revision, } if session.ClosedAt > 0 { out.Closed = true From ab6b2bb63262cc069212fce25834a7caa49178d7 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:37:50 +0000 Subject: [PATCH 08/19] Scheduler: skip unreadable schedules, admit claimed runs asynchronously A schedule that cannot be parsed or claimed is logged and skipped instead of aborting the tick for every schedule. Claimed runs are admitted on their own goroutines, so a slow start (worktree creation) no longer makes the next due schedule look missed; lateness is measured at claim time. An invalid interval no longer divides by zero. Co-Authored-By: Claude Opus 5.5 --- .../server/legacy_schedule_workspace_test.go | 1 + internal/server/runner.go | 3 + internal/server/schedule_scope_test.go | 2 + internal/server/scheduler.go | 126 +++++++++++------- internal/server/scheduler_reliability_test.go | 100 ++++++++++++++ internal/server/scheduler_test.go | 15 ++- internal/server/tools_test.go | 1 + 7 files changed, 198 insertions(+), 50 deletions(-) create mode 100644 internal/server/scheduler_reliability_test.go diff --git a/internal/server/legacy_schedule_workspace_test.go b/internal/server/legacy_schedule_workspace_test.go index db8d701a..145008c9 100644 --- a/internal/server/legacy_schedule_workspace_test.go +++ b/internal/server/legacy_schedule_workspace_test.go @@ -120,6 +120,7 @@ func TestLegacyScheduleBindsExecutionDefaultNotOfflineOpenDirectory(t *testing.T if err = r.scheduleTick(due, false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() r.wg.Wait() runs, err := store.ListRuns(ctx) if err != nil || len(runs) != 1 || runs[0].Workspace != resolvedB || !runs[0].Scheduled || runs[0].ScheduleID != original.ID { diff --git a/internal/server/runner.go b/internal/server/runner.go index 6ea8e8e1..9626cecb 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -78,6 +78,9 @@ type runner struct { verifyTarget stage.VerificationRunner wg sync.WaitGroup schedulerWG sync.WaitGroup + // scheduleAdmissions tracks schedule-claimed runs still being admitted + // (scheduler.go); the scheduler loop waits for them before it exits. + scheduleAdmissions sync.WaitGroup // attentionMu guards attentionSent, the per-run set of run-attention events // already delivered — by a stage's own notify policy or by the run-level // default — so neither republishes the same genuine event. diff --git a/internal/server/schedule_scope_test.go b/internal/server/schedule_scope_test.go index fb53033e..5e501900 100644 --- a/internal/server/schedule_scope_test.go +++ b/internal/server/schedule_scope_test.go @@ -73,6 +73,7 @@ func TestScheduledRunPreservesWriteScopeAndWorkflowPermissions(t *testing.T) { if err = r.scheduleTick(dueOf(t, entry), false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() r.wg.Wait() runs, err := s.ListRuns(ctx) if err != nil || len(runs) != 1 || runs[0].Status != "succeeded" || calls != 1 { @@ -111,6 +112,7 @@ func TestScheduleRechecksWriteScopeBeforeTitleOrExecution(t *testing.T) { if err = r.scheduleTick(dueOf(t, entry), false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() r.wg.Wait() // The exact same shared policy rejects manual admission as well. if _, err = r.start(protocol.Message{PipelineID: pid, Version: 1, Workspace: workspace, Input: spec.Input, WritePaths: spec.WritePaths, AllowTools: true, RequestKey: "manual-unsafe"}); err == nil { diff --git a/internal/server/scheduler.go b/internal/server/scheduler.go index bdcfc14c..d2165955 100644 --- a/internal/server/scheduler.go +++ b/internal/server/scheduler.go @@ -11,6 +11,8 @@ import ( func (r *runner) scheduleLoop() { defer r.schedulerWG.Done() + // Admissions run beside the loop; shutdown waits for the ones it started. + defer r.scheduleAdmissions.Wait() if err := r.scheduleTick(time.Now(), true); err != nil { log.Printf("scheduler startup: %v", err) } @@ -22,14 +24,21 @@ func (r *runner) scheduleLoop() { return case <-r.store.Done(): return - case now := <-ticker.C: - if err := r.scheduleTick(now, false); err != nil { + case <-ticker.C: + // Lateness is measured against the time of the claim, not the + // (possibly delayed) tick. + if err := r.scheduleTick(time.Now(), false); err != nil { log.Printf("scheduler: %v", err) } } } } +// scheduleTick claims every enabled schedule due at now. A schedule that +// cannot be read or claimed is logged and skipped, never stopping the others. +// A claimed run is admitted on its own goroutine (scheduleAdmissions): run +// admission can take up to a minute (git worktree creation), and an inline +// start would make the next due schedule look missed by the time it is seen. func (r *runner) scheduleTick(now time.Time, recovery bool) error { items, err := r.store.ListSchedules(r.ctx, 0) if err != nil { @@ -39,54 +48,73 @@ func (r *runner) scheduleTick(now time.Time, recovery bool) error { if !item.Enabled { continue } - due, err := time.Parse(time.RFC3339Nano, item.NextDue) - if err != nil { - return err + if err := r.claimSchedule(item, now, recovery); err != nil { + log.Printf("schedule id=%d pipeline=%d: %v", item.ID, item.PipelineID, err) } - if due.After(now) { - continue - } - next, err := pipeline.NextSchedule(item.Rule, now) - if err != nil { - return err - } - if item.Rule.Every != "" { - interval, _ := time.ParseDuration(item.Rule.Every) - next = due.Add((now.Sub(due)/interval + 1) * interval) - } - status := "claimed" - if recovery || now.Sub(due) > 5*time.Second { - status = "skipped_missed" - } - loc, err := pipeline.ScheduleLocation(item.Rule) - if err != nil { - return err - } - if !pipeline.ScheduleDay(item.Rule, due.In(loc)) { - status = "skipped_day" - } - claimed, err := r.store.ClaimSavedSchedule(r.ctx, item, due, next, status) - if err != nil { - return err - } - if !claimed || status != "claimed" { - continue - } - request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat} - run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name}) - diagnostic := "" - status = "started" - var runID int64 - if err != nil { - status = "skipped" - diagnostic = err.Error() - } else { - runID = run.ID - } - if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, status, diagnostic); err != nil { - return err - } - log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic) } return nil } + +func (r *runner) claimSchedule(item protocol.SavedSchedule, now time.Time, recovery bool) error { + due, err := time.Parse(time.RFC3339Nano, item.NextDue) + if err != nil { + return fmt.Errorf("next due %q: %w", item.NextDue, err) + } + if due.After(now) { + return nil + } + next, err := pipeline.NextSchedule(item.Rule, now) + if err != nil { + return err + } + if item.Rule.Every != "" { + interval, err := time.ParseDuration(item.Rule.Every) + if err != nil || interval <= 0 { + return fmt.Errorf("interval %q is invalid", item.Rule.Every) + } + next = due.Add((now.Sub(due)/interval + 1) * interval) + } + status := "claimed" + if recovery || now.Sub(due) > 5*time.Second { + status = "skipped_missed" + } + loc, err := pipeline.ScheduleLocation(item.Rule) + if err != nil { + return err + } + if !pipeline.ScheduleDay(item.Rule, due.In(loc)) { + status = "skipped_day" + } + claimed, err := r.store.ClaimSavedSchedule(r.ctx, item, due, next, status) + if err != nil { + return err + } + if !claimed || status != "claimed" { + return nil + } + r.scheduleAdmissions.Add(1) + go func() { + defer r.scheduleAdmissions.Done() + r.admitScheduled(item, due) + }() + return nil +} + +// admitScheduled starts one claimed schedule's run and records the outcome. +func (r *runner) admitScheduled(item protocol.SavedSchedule, due time.Time) { + request := protocol.Message{PipelineID: item.PipelineID, Version: item.Version, RequestKey: fmt.Sprintf("saved-schedule:%d:%d", item.ID, due.UnixNano()), Input: item.Input, Workspace: item.Workspace, WritePaths: item.WritePaths, AllowTools: item.AllowTools, Model: item.Model, StageModels: item.StageModels, NotifyMode: item.NotifyMode, Title: item.Title, OutputFormat: item.OutputFormat} + run, err := r.startWithSchedule(request, &pipeline.ScheduleAdmission{ID: item.ID, Revision: item.Revision, Due: due, Name: item.Name}) + diagnostic := "" + status := "started" + var runID int64 + if err != nil { + status = "skipped" + diagnostic = err.Error() + } else if run != nil { + runID = run.ID + } + if err := r.store.FinishSavedSchedule(r.ctx, item.ID, due, status, diagnostic); err != nil { + log.Printf("schedule id=%d record admission: %v", item.ID, err) + } + log.Printf("schedule id=%d pipeline=%d version=%d due=%s status=%s run=%d %s", item.ID, item.PipelineID, item.Version, due.Format(time.RFC3339), status, runID, diagnostic) +} diff --git a/internal/server/scheduler_reliability_test.go b/internal/server/scheduler_reliability_test.go new file mode 100644 index 00000000..bd9c7620 --- /dev/null +++ b/internal/server/scheduler_reliability_test.go @@ -0,0 +1,100 @@ +package server + +import ( + "context" + "database/sql" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" + "git.a-wan.net/alan/pipelines/internal/summarise" +) + +// One schedule whose stored due time cannot be parsed is logged and skipped; +// every other due schedule still runs on the same tick. +func TestScheduleTickSkipsAnUnreadableScheduleAndRunsTheRest(t *testing.T) { + ctx, s, r, pid := scheduleFixture(t) + now := time.Now() + broken := saveTestSchedule(t, ctx, s, pid, "broken", t.TempDir(), "1m", now) + good := saveTestSchedule(t, ctx, s, pid, "good", t.TempDir(), "1m", now) + db, err := sql.Open("sqlite", s.DatabasePath()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err := db.ExecContext(ctx, `UPDATE saved_schedules SET next_due='not a time' WHERE id=?`, broken.ID); err != nil { + t.Fatal(err) + } + r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) { + return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil + } + if err := r.scheduleTick(dueOf(t, good), false); err != nil { + t.Fatal(err) + } + r.scheduleAdmissions.Wait() + r.wg.Wait() + runs, err := s.ListRuns(ctx) + if err != nil || len(runs) != 1 || runs[0].ScheduleID != good.ID { + t.Fatalf("runs = %+v %v", runs, err) + } +} + +// A slow admission (title generation, worktree creation) no longer holds the +// scheduler: the tick returns at once and a schedule due a moment later is +// claimed and started, not recorded as missed. +func TestSlowScheduledAdmissionDoesNotMissTheNextSchedule(t *testing.T) { + ctx, s, r, pid := scheduleFixture(t) + now := time.Now() + save := func(prompt string) *protocol.SavedSchedule { + item, err := s.SaveSchedule(ctx, protocol.SavedSchedule{Name: prompt, PipelineID: pid, Version: 1, Enabled: true, Workspace: t.TempDir(), Input: map[string]any{"prompt": prompt}, Rule: protocol.Schedule{Every: "1m"}, NotifyMode: "off"}, now) + if err != nil { + t.Fatal(err) + } + return item + } + a, b := save("first"), save("second") + release := make(chan struct{}) + titling := make(chan string, 2) + r.title = func(_ context.Context, prompt string) summarise.Title { + titling <- prompt + if prompt == "first" { + <-release + } + return summarise.Title{Text: prompt} + } + r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) { + return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil + } + at := dueOf(t, a) + if dueB := dueOf(t, b); dueB.After(at) { + at = dueB + } + // Both are due on this tick; the first one's admission blocks. + returned := make(chan error, 1) + go func() { returned <- r.scheduleTick(at, false) }() + select { + case err := <-returned: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("scheduler tick blocked on a slow admission") + } + seen := map[string]bool{} + for len(seen) < 2 { + select { + case got := <-titling: + seen[got] = true + case <-time.After(5 * time.Second): + t.Fatalf("second schedule not admitted while the first was slow: %v", seen) + } + } + close(release) + r.scheduleAdmissions.Wait() + r.wg.Wait() + runs, err := s.ListRuns(ctx) + if err != nil || len(runs) != 2 { + t.Fatalf("runs = %+v %v", runs, err) + } +} diff --git a/internal/server/scheduler_test.go b/internal/server/scheduler_test.go index 3a9e5b28..9a7b5703 100644 --- a/internal/server/scheduler_test.go +++ b/internal/server/scheduler_test.go @@ -82,6 +82,7 @@ func TestIndependentScheduledRunsAndProvenance(t *testing.T) { if err := r.scheduleTick(dueOf(t, item), false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() r.wg.Wait() } runs, err := s.ListRuns(ctx) @@ -183,6 +184,7 @@ func TestScheduleDeletionDoesNotCancelAdmittedRun(t *testing.T) { if err := r.scheduleTick(dueOf(t, item), false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() <-entered if err := s.DeleteSchedule(ctx, item.ID, item.Revision); err != nil { t.Fatal(err) @@ -190,6 +192,7 @@ func TestScheduleDeletionDoesNotCancelAdmittedRun(t *testing.T) { if err := r.scheduleTick(dueOf(t, item).Add(time.Minute), false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() close(release) r.wg.Wait() runs, err := s.ListRuns(ctx) @@ -211,21 +214,26 @@ func TestSavedScheduleRecoveryAndOverlap(t *testing.T) { if err := r.scheduleTick(due, false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() <-entered if err := r.scheduleTick(due.Add(time.Minute), false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() close(release) r.wg.Wait() if err := r.scheduleTick(due.Add(time.Minute), false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() if err := r.scheduleTick(due.Add(time.Hour), true); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() if err := r.scheduleTick(due.Add(time.Hour), false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() runs, err := s.ListRuns(ctx) if err != nil || len(runs) != 1 { t.Fatal("replayed or overlapping work", runs, err) @@ -242,6 +250,7 @@ func TestSavedScheduleRecoveryAndOverlap(t *testing.T) { if err = r.scheduleTick(dueOf(t, item), false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() runs, _ = s.ListRuns(ctx) if len(runs) != 1 { t.Fatal("excluded day dispatched", runs) @@ -259,7 +268,10 @@ func TestScheduleEditBetweenClaimAndAdmission(t *testing.T) { if err != nil { t.Fatal(err) } + due := dueOf(t, item) r.title = func(context.Context, string) summarise.Title { + // Admission runs on its own goroutine: keep its error local. + var err error if operation == "delete" { err = s.DeleteSchedule(ctx, item.ID, item.Revision) } else { @@ -279,9 +291,10 @@ func TestScheduleEditBetweenClaimAndAdmission(t *testing.T) { t.Error("invalidated occurrence executed") return stage.Result{}, nil } - if err = r.scheduleTick(dueOf(t, item), false); err != nil { + if err = r.scheduleTick(due, false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() r.wg.Wait() runs, _ := s.ListRuns(ctx) if len(runs) != 0 { diff --git a/internal/server/tools_test.go b/internal/server/tools_test.go index 2c200e26..e7678c07 100644 --- a/internal/server/tools_test.go +++ b/internal/server/tools_test.go @@ -57,6 +57,7 @@ func TestWebStagesCanRunWithoutMutationApproval(t *testing.T) { if err := r.scheduleTick(due, false); err != nil { t.Fatal(err) } + r.scheduleAdmissions.Wait() r.wg.Wait() runs, _ := store.ListRuns(ctx) if len(runs) != 2 { From c316bc9bc806396ee0faac3567cb623b7fc6680d Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:39:38 +0000 Subject: [PATCH 09/19] Chat and runs: tell a slow client to resync instead of dropping it silently; join queued deltas A chat subscriber whose queue fills is detached and its writer ends the stream with a resync frame (the app re-attaches and re-reads history); a run subscriber gets a final runs_resync and the app subscribes again and re-reads the Runs list and open detail. Consecutive text/reasoning deltas of one part are joined in a chat subscriber's queue; joined numbered frames carry seq_from and delta_lens so the app trims exactly the prefix a history page already holds. Co-Authored-By: Claude Opus 5.5 --- app/lib/application/app_session.dart | 13 ++ app/lib/application/runs_destination.dart | 2 +- .../conversation/chat_thread_controller.dart | 5 +- .../chat/domain/chat_live_frames.dart | 56 ++++- app/test/application/app_session_test.dart | 31 +++ .../chat/domain/chat_live_frames_test.dart | 67 ++++++ docs/cli.md | 10 + internal/protocol/chat.go | 7 + internal/protocol/runevents.go | 4 + internal/server/chat_activity_test.go | 2 +- internal/server/chat_compaction.go | 8 +- internal/server/chat_compaction_test.go | 32 +-- internal/server/chat_detach.go | 7 +- internal/server/chat_hub.go | 2 +- internal/server/chat_room.go | 212 +++++++++++++++--- internal/server/chat_sub_overflow_test.go | 125 +++++++++++ internal/server/chat_unattended_test.go | 2 +- internal/server/chat_usage_test.go | 14 +- internal/server/runevents.go | 37 ++- internal/server/runevents_overflow_test.go | 47 ++++ 20 files changed, 603 insertions(+), 80 deletions(-) create mode 100644 app/test/features/chat/domain/chat_live_frames_test.dart create mode 100644 internal/server/chat_sub_overflow_test.go create mode 100644 internal/server/runevents_overflow_test.go diff --git a/app/lib/application/app_session.dart b/app/lib/application/app_session.dart index eae45388..5edbde6e 100644 --- a/app/lib/application/app_session.dart +++ b/app/lib/application/app_session.dart @@ -53,6 +53,7 @@ class AppSession extends ChangeNotifier { bool _subscribed = false, _disposed = false; bool _everConnected; int _connectionEpoch = 0; + int _runsResyncs = 0; RunSubscriptionState _subscription = RunSubscriptionState.pending; String _subscriptionError = ''; String? _subscribeRequest; @@ -79,6 +80,11 @@ class AppSession extends ChangeNotifier { /// detail without remounting the screen or losing its selection. int get connectionEpoch => _connectionEpoch; + /// Advances on every connected transition and whenever the server detached + /// this connection's run watch for falling behind (`runs_resync`). The Runs + /// screen keys its re-read with this: frames were discarded either way. + int get runsEpoch => _connectionEpoch + _runsResyncs; + /// Connects the shared socket. A missing endpoint is a configuration state, /// so this is a no-op rather than a guessed endpoint. Future start() async { @@ -140,6 +146,13 @@ class AppSession extends ChangeNotifier { void _onFrame(JsonMap frame) { if (_disposed) return; + if (frame['type'] == 'runs_resync') { + // The server dropped this watch because the connection fell behind and + // discarded the frames it still held: watch again and re-read the runs. + _runsResyncs++; + resubscribe(); + return; + } final id = frame['id']; if (id is! String || id != _subscribeRequest) return; switch (frame['type']) { diff --git a/app/lib/application/runs_destination.dart b/app/lib/application/runs_destination.dart index 6dffbe39..8f56fc4b 100644 --- a/app/lib/application/runs_destination.dart +++ b/app/lib/application/runs_destination.dart @@ -103,7 +103,7 @@ class RunsDestination extends StatelessWidget { initialStageKey: initialStageKey, initialVisit: initialVisit, initialDecide: initialDecide, - syncToken: session.connectionEpoch, + syncToken: session.runsEpoch, listRefreshToken: listRefreshToken, notifications: notifications, attention: attention, diff --git a/app/lib/features/chat/conversation/chat_thread_controller.dart b/app/lib/features/chat/conversation/chat_thread_controller.dart index b4a6d6c9..7b002faa 100644 --- a/app/lib/features/chat/conversation/chat_thread_controller.dart +++ b/app/lib/features/chat/conversation/chat_thread_controller.dart @@ -439,9 +439,10 @@ class ChatThreadController extends ChangeNotifier { return; } // A delta a history page already included is not added again. - if (!_live.admit(body)) return; + final admitted = _live.admit(body); + if (admitted == null) return; final current = _thread; - final next = applyChatEvent(current, body); + final next = applyChatEvent(current, admitted); if (identical(next, current)) return; // A frame for a cached message is fresh state the next read must not drop. final changed = body['message_id']; diff --git a/app/lib/features/chat/domain/chat_live_frames.dart b/app/lib/features/chat/domain/chat_live_frames.dart index d62aa7b1..6212f34d 100644 --- a/app/lib/features/chat/domain/chat_live_frames.dart +++ b/app/lib/features/chat/domain/chat_live_frames.dart @@ -28,17 +28,21 @@ class ChatLiveFrames { /// Stops recording for a read that will not be applied. void abandon(List frames) => _reads.remove(frames); - /// Whether [frame] should be folded into the held transcript, recording it - /// for every read in flight. A frame with no number is always folded. - bool admit(JsonMap frame) { + /// The part of [frame] to fold into the held transcript, recording it for + /// every read in flight, or null when a page already included all of it. A + /// frame with no number is always folded whole; a joined frame whose first + /// deltas were already included is trimmed to the rest. + JsonMap? admit(JsonMap frame) { final seq = frame['seq']; - if (seq is! int) return true; - if (seq <= _included) return false; + if (seq is! int) return frame; + if (seq <= _included) return null; + final admitted = chatDeltasAfter(frame, _included); + if (admitted == null) return null; _included = seq; for (final read in _reads) { - read.add(frame); + read.add(admitted); } - return true; + return admitted; } /// [messages] after applying [page]: frames recorded during the read that @@ -65,9 +69,11 @@ class ChatLiveFrames { }; } var thread = {'messages': messages}; - for (final frame in frames) { - final seq = frame['seq']; + for (final recorded in frames) { + final seq = recorded['seq']; if (seq is! int || seq <= liveSeq) continue; + final frame = chatDeltasAfter(recorded, liveSeq); + if (frame == null) continue; final messageId = frame['message_id']; if (!replaced(messageId)) continue; final part = frame['part']; @@ -82,3 +88,35 @@ class ChatLiveFrames { return chatMessageList(thread['messages']); } } + +/// [frame] without the numbered deltas up to [included]. +/// +/// A server joins consecutive deltas of one part while a slow client's queue +/// is backed up: the joined frame's `seq_from`..`seq` names the deltas it holds +/// and `delta_lens` each one's length in UTF-16 code units. When a history page +/// already holds a prefix of them, only the rest is new. A plain frame (or one +/// wholly past [included]) is returned unchanged; null means nothing in it is +/// new. +JsonMap? chatDeltasAfter(JsonMap frame, int included) { + final seq = frame['seq']; + if (seq is! int) return frame; + if (seq <= included) return null; + final from = frame['seq_from']; + final lens = frame['delta_lens']; + if (from is! int || from > included || lens is! List) return frame; + final delta = frame['delta']; + if (delta is! String || lens.length != seq - from + 1) return frame; + var cut = 0; + for (var i = 0; i <= included - from; i++) { + final length = lens[i]; + if (length is! int || length < 0) return frame; + cut += length; + } + if (cut >= delta.length) return null; + return { + ...frame, + 'delta': delta.substring(cut), + 'seq_from': included + 1, + 'delta_lens': lens.sublist(included - from + 1), + }; +} diff --git a/app/test/application/app_session_test.dart b/app/test/application/app_session_test.dart index 28233da0..a6c7dd00 100644 --- a/app/test/application/app_session_test.dart +++ b/app/test/application/app_session_test.dart @@ -140,6 +140,37 @@ void main() { expect(session.subscriptionError, contains('too many run subscriptions')); }); + test('runs_resync watches again and advances the runs epoch', () async { + // The server detached this connection's run watch because it fell behind + // and discarded the frames it held; without a new subscribe the Runs + // list and detail froze until the next reconnect. + final channel = FakeChannel()..readyCompleter.complete(); + final client = PipelinesClient(channelFactory: (_) => channel); + final session = AppSession( + endpoint: Uri.parse('ws://example.test/connect'), + client: client, + ); + addTearDown(session.dispose); + + await session.start(); + await flush(); + final subscribe = + jsonDecode(channel.outgoing.single as String) as Map; + channel.incoming.add( + jsonEncode({'id': subscribe['id'], 'type': 'subscribe'}), + ); + await flush(); + final epoch = session.runsEpoch; + final connection = session.connectionEpoch; + + channel.incoming.add(jsonEncode({'type': 'runs_resync'})); + await flush(); + expect(types(channel), ['subscribe', 'subscribe']); + expect(session.runsEpoch, greaterThan(epoch)); + expect(session.connectionEpoch, connection); + expect(session.subscription, RunSubscriptionState.pending); + }); + test('dispose drops the watch and releases the client', () async { final channel = FakeChannel()..readyCompleter.complete(); final client = PipelinesClient(channelFactory: (_) => channel); diff --git a/app/test/features/chat/domain/chat_live_frames_test.dart b/app/test/features/chat/domain/chat_live_frames_test.dart new file mode 100644 index 00000000..00dfd674 --- /dev/null +++ b/app/test/features/chat/domain/chat_live_frames_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/domain/chat_live_frames.dart'; + +/// A frame the server joined from deltas 10..12 ("héllo ", "wörld ", "😀!") +/// while this client's queue was backed up. +Map joined() => { + 'session_id': 's', + 'message_id': 'm', + 'kind': 'text', + 'part': {'type': 'text', 'id': 'm-text-0'}, + 'delta': 'héllo wörld 😀!', + 'seq_from': 10, + 'seq': 12, + 'delta_lens': [6, 6, 3], +}; + +void main() { + test('a joined frame drops exactly the deltas a page already holds', () { + expect(chatDeltasAfter(joined(), 9)?['delta'], 'héllo wörld 😀!'); + final rest = chatDeltasAfter(joined(), 10)!; + expect(rest['delta'], 'wörld 😀!'); + expect(rest['seq_from'], 11); + expect(rest['delta_lens'], [6, 3]); + expect(chatDeltasAfter(joined(), 11)?['delta'], '😀!'); + expect(chatDeltasAfter(joined(), 12), isNull); + }); + + test('a plain numbered delta is folded whole or not at all', () { + final plain = {'kind': 'text', 'delta': 'x', 'seq': 5}; + expect(chatDeltasAfter(plain, 4), same(plain)); + expect(chatDeltasAfter(plain, 5), isNull); + }); + + test('admit trims a joined frame overlapping what was included', () { + final live = ChatLiveFrames(); + final first = {'kind': 'text', 'delta': 'héllo ', 'seq': 10}; + expect(live.admit(first), same(first)); + // The rest arrives joined with the delta already shown. + expect(live.admit(joined())?['delta'], 'wörld 😀!'); + expect(live.admit(joined()), isNull); + }); + + test('settle folds back only the part of a joined frame past the page', () { + final live = ChatLiveFrames(); + final read = live.beginRead(); + live.admit(joined()); + final page = { + 'liveSeq': 11, + 'liveParts': ['m-text-0'], + 'messages': [ + { + 'id': 'm', + 'role': 'assistant', + 'parts': [ + {'type': 'text', 'id': 'm-text-0', 'text': 'héllo wörld '}, + ], + }, + ], + }; + final messages = live.settle(read, page, [ + for (final message in page['messages'] as List) + Map.from(message as Map), + ], replaced: (_) => true); + final parts = messages.single['parts'] as List; + expect((parts.single as Map)['text'], 'héllo wörld 😀!'); + }); +} diff --git a/docs/cli.md b/docs/cli.md index 0bab3de4..c413128d 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -480,6 +480,16 @@ history refresh without inventing text deltas or ending a queued prompt. Native step markers may include `step.turn_id`; a terminal marker for an older turn must not clear a newer turn's Stop control or release its queue slot. +A client that falls too far behind its chat stream (64 queued frames) is +detached; its last frame is `chat_event.kind="resync"`, so it must send +`chat_subscribe` again before re-reading history. Consecutive text or reasoning +deltas of one part are joined while queued: a joined numbered frame carries +`seq` (its last delta), `seq_from` (its first) and `delta_lens` (each delta's +length in UTF-16 code units), so a client whose history page's `liveSeq` +falls inside the range drops exactly the prefix the page already holds. A run +subscriber that falls behind likewise receives a final `{"type":"runs_resync"}` +and must send `subscribe` again for a fresh snapshot. + Native context compaction is reported as `chat_event.kind="compaction"`, with `compaction: {status: "running" | "completed" | "failed", id?: string}`. Optional `native_turn_id` scopes the activity to its real harness turn; ignore diff --git a/internal/protocol/chat.go b/internal/protocol/chat.go index e5433ea3..f8252115 100644 --- a/internal/protocol/chat.go +++ b/internal/protocol/chat.go @@ -758,6 +758,13 @@ type ChatEventFrame struct { // Seq numbers a text or reasoning delta within its session, increasing; // see ChatHistoryPage.LiveSeq. Zero when the harness does not number them. Seq int64 `json:"seq,omitempty"` + // SeqFrom and DeltaLens are set on a frame joining consecutive numbered + // deltas of one part (a slow client's queue coalesced them, see + // chatSub): SeqFrom is the first joined delta's Seq (Seq the last), and + // DeltaLens each joined delta's length in UTF-16 code units, so a client + // whose history page already holds a prefix (LiveSeq) drops exactly it. + SeqFrom int64 `json:"seq_from,omitempty"` + DeltaLens []int `json:"delta_lens,omitempty"` } // ChatCompaction is session activity, never a transcript message or tool. diff --git a/internal/protocol/runevents.go b/internal/protocol/runevents.go index d5915216..9689e3e1 100644 --- a/internal/protocol/runevents.go +++ b/internal/protocol/runevents.go @@ -11,6 +11,10 @@ const ( Subscribe = "subscribe" Unsubscribe = "unsubscribe" RunEvent = "run_event" + // RunsResync is the last frame of a subscription the server detached + // because its client fell too far behind: the client must send subscribe + // again and re-read the runs it shows, since frames were discarded. + RunsResync = "runs_resync" ) // RunEventFrame is the server-pushed run_event delta. It carries only the values diff --git a/internal/server/chat_activity_test.go b/internal/server/chat_activity_test.go index 5fa6f2d2..44b7445f 100644 --- a/internal/server/chat_activity_test.go +++ b/internal/server/chat_activity_test.go @@ -173,7 +173,7 @@ func TestChatBackgroundTasksKeepUnattendedRoom(t *testing.T) { if tasks > 0 { h.turnLocked(id).applyShell(&protocol.ChatShell{ID: "sh_1", Status: protocol.ChatShellRunning}) } - sub := &chatSub{hub: h, room: room, clientID: "c", ch: make(chan protocol.Message, 1), done: make(chan struct{})} + sub := &chatSub{hub: h, room: room, clientID: "c", limit: 1, done: make(chan struct{})} room.subs["c"] = sub h.mu.Unlock() h.detach(id, sub) diff --git a/internal/server/chat_compaction.go b/internal/server/chat_compaction.go index 6b16a9b0..3079c7b3 100644 --- a/internal/server/chat_compaction.go +++ b/internal/server/chat_compaction.go @@ -35,7 +35,7 @@ func (h *chatHub) replayCompaction(sub *chatSub) { } h.mu.Unlock() if slow { - sub.close() + sub.overflow() } } @@ -56,9 +56,9 @@ func (h *chatHub) clearCompactionLocked(room *chatRoom) { } for _, sub := range room.subs { if !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}) { - // close detaches under h.mu; never block the folding lock. A full - // queue must reconnect rather than silently miss terminal cleanup. - go sub.close() + // overflow detaches under h.mu; never block the folding lock. A + // full queue must resync rather than silently miss terminal cleanup. + go sub.overflow() } } } diff --git a/internal/server/chat_compaction_test.go b/internal/server/chat_compaction_test.go index 63ddcab7..64943e87 100644 --- a/internal/server/chat_compaction_test.go +++ b/internal/server/chat_compaction_test.go @@ -14,63 +14,63 @@ func TestCompactionRetainedReplayIsolationAndTerminalClear(t *testing.T) { room.running, room.nativeTurnID = true, "turn_new" room.turnDone = make(chan struct{}) h.rooms[room.sessionID] = room - sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 32), done: make(chan struct{})} + sub := &chatSub{hub: h, room: room, clientID: "watcher", limit: 32, done: make(chan struct{})} room.subs[sub.clientID] = sub emit := func(id, status, nativeID string) { h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, NativeTurnID: nativeID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{ID: id, Status: status}}) } emit("old", "running", "turn_old") - if len(sub.ch) != 0 { + if sub.queued() != 0 { t.Fatal("old native turn surfaced") } emit("first", "running", "turn_new") - <-sub.ch + sub.take() if got := h.snapshot(room.sessionID); len(got) != 0 { t.Fatalf("fake message: %+v", got) } h.replayCompaction(sub) - if f := (<-sub.ch).ChatEvent; f == nil || f.Compaction.ID != "first" || f.MessageID != "" { + if f := (sub.take()).ChatEvent; f == nil || f.Compaction.ID != "first" || f.MessageID != "" { t.Fatalf("replay without assistant: %+v", f) } other := newChatRoom(context.Background(), "ses_other") defer other.cancel() h.rooms[other.sessionID] = other - otherSub := &chatSub{hub: h, room: other, clientID: "other", ch: make(chan protocol.Message, 4), done: make(chan struct{})} + otherSub := &chatSub{hub: h, room: other, clientID: "other", limit: 4, done: make(chan struct{})} other.subs[otherSub.clientID] = otherSub h.replayCompaction(otherSub) - if len(otherSub.ch) != 0 { + if otherSub.queued() != 0 { t.Fatal("foreign-session replay") } resetOld := h.compactionReset(room.sessionID) emit("second", "running", "turn_new") - <-sub.ch + sub.take() resetOld() emit("first", "completed", "turn_new") - if len(sub.ch) != 0 || h.turns[room.sessionID].compaction.ID != "second" { + if sub.queued() != 0 || h.turns[room.sessionID].compaction.ID != "second" { t.Fatal("old lifecycle cleared newer compaction") } h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, Intermediate: true}}) - <-sub.ch + sub.take() if h.turns[room.sessionID].compaction == nil || !room.running { t.Fatal("provider step settled compaction or turn") } emit("second", "completed", "turn_new") - <-sub.ch + sub.take() if !room.running { t.Fatal("compaction completion released turn queue") } emit("third", "running", "turn_new") - <-sub.ch + sub.take() h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded, TurnID: "turn_new"}}) - if f := (<-sub.ch).ChatEvent; f.Compaction == nil || f.Compaction.Status != "failed" { + if f := (sub.take()).ChatEvent; f.Compaction == nil || f.Compaction.Status != "failed" { t.Fatalf("terminal cleanup: %+v", f) } - <-sub.ch // authoritative step completion + sub.take() // authoritative step completion if room.running || h.turns[room.sessionID].compaction != nil { t.Fatal("terminal state stuck") } emit("third", "running", "turn_new") - if len(sub.ch) != 0 { + if sub.queued() != 0 { t.Fatal("late old-turn activity revived label") } } @@ -83,10 +83,10 @@ func TestCompactionTransportLossAndInterruptClearDoNotReleaseTurn(t *testing.T) defer room.cancel() h.rooms[room.sessionID] = room room.running = true - sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 8), done: make(chan struct{})} + sub := &chatSub{hub: h, room: room, clientID: "watcher", limit: 8, done: make(chan struct{})} room.subs[sub.clientID] = sub h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "running", ID: "compact"}}) - <-sub.ch + sub.take() switch mode { case "interrupt": h.compactionReset(room.sessionID)() diff --git a/internal/server/chat_detach.go b/internal/server/chat_detach.go index f6ea4e47..5dc0f852 100644 --- a/internal/server/chat_detach.go +++ b/internal/server/chat_detach.go @@ -294,8 +294,11 @@ func (h *chatHub) endObservedTurnLocked(room *chatRoom) { h.finishTurnLocked(room) resync := protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventResync} for _, sub := range room.subs { - enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) - enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end}) + if !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) || + !enqueueChatLocked(sub, protocol.Message{Type: protocol.ChatEvent, ChatEvent: &end}) { + // overflow detaches under h.mu: never from inside the fold lock. + go sub.overflow() + } } } diff --git a/internal/server/chat_hub.go b/internal/server/chat_hub.go index 25a35787..cb83841b 100644 --- a/internal/server/chat_hub.go +++ b/internal/server/chat_hub.go @@ -388,7 +388,7 @@ func (h *chatHub) replayUsage(sub *chatSub) { } h.mu.Unlock() if slow { - sub.close() + sub.overflow() } } diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index a6459c59..9e518d21 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -46,17 +46,29 @@ const ( // chatSub is one client's attachment to a session's shared stream. Frames reach // it through a dedicated writer goroutine so a slow or broken client never stalls -// the turn or the other subscribers; the buffered channel bounds how far behind -// it may fall. +// the turn or the other subscribers; the bounded queue limits how far behind it +// may fall. Consecutive text or reasoning deltas of one part are joined in the +// queue, so a streaming burst takes one slot. A client that still falls behind +// is detached, and its writer ends the stream with a resync frame so the client +// re-attaches and re-reads the authoritative history instead of silently +// missing frames. type chatSub struct { hub *chatHub room *chatRoom clientID string label string - ch chan protocol.Message done chan struct{} once sync.Once write func(protocol.Message) error + + // qmu guards the queue. It is taken under h.mu (enqueue) and never + // takes h.mu itself. + qmu sync.Mutex + queue []protocol.Message + limit int // 0 means chatRoomSubscriberBuffer + ready chan struct{} // signalled when the queue gains a frame + overflowed bool + overOnce sync.Once } func (s *chatSub) run() { @@ -64,28 +76,118 @@ func (s *chatSub) run() { select { case <-s.done: return - case msg := <-s.ch: - if err := s.write(msg); err != nil { - s.close() + default: + } + msg, ok, overflowed := s.next() + if overflowed { + // The terminal frame: everything still queued was discarded, so + // the client must re-attach and re-read the history. + resync := protocol.ChatEventFrame{SessionID: s.room.sessionID, Kind: protocol.ChatEventResync} + _ = s.write(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &resync}) + s.close() + return + } + if !ok { + select { + case <-s.done: return + case <-s.ready: } + continue + } + if err := s.write(msg); err != nil { + s.close() + return } } } -func (s *chatSub) send(msg protocol.Message) { +// next pops the oldest queued frame, or reports that the subscription +// overflowed. +func (s *chatSub) next() (protocol.Message, bool, bool) { + s.qmu.Lock() + defer s.qmu.Unlock() + if s.overflowed { + return protocol.Message{}, false, true + } + if len(s.queue) == 0 { + return protocol.Message{}, false, false + } + msg := s.queue[0] + s.queue[0] = protocol.Message{} + s.queue = s.queue[1:] + return msg, true, false +} + +// queued is the number of frames waiting for the writer. +func (s *chatSub) queued() int { + s.qmu.Lock() + defer s.qmu.Unlock() + return len(s.queue) +} + +// enqueue queues msg without blocking, joining it to the previous delta of the +// same part. It reports false when the queue is full; the caller must then +// call overflow, outside h.mu. It never detaches, so it may run under h.mu. +func (s *chatSub) enqueue(msg protocol.Message) bool { select { case <-s.done: - return + return true default: } - select { - case s.ch <- msg: - default: - // The client is not draining: drop it rather than block the fan-out. Its - // next attach re-syncs from history. - s.close() + s.qmu.Lock() + defer s.qmu.Unlock() + if s.overflowed { + return true // discarded: the client is told to resync } + if n := len(s.queue); n > 0 { + if joined, ok := joinChatDeltas(s.queue[n-1], msg); ok { + s.queue[n-1] = joined + return true + } + } + limit := s.limit + if limit <= 0 { + limit = chatRoomSubscriberBuffer + } + if len(s.queue) >= limit { + return false + } + s.queue = append(s.queue, msg) + if s.ready != nil { + select { + case s.ready <- struct{}{}: + default: + } + } + return true +} + +func (s *chatSub) send(msg protocol.Message) { + if !s.enqueue(msg) { + // The client is not draining: detach it rather than block the + // fan-out. Its writer tells it to resync. + s.overflow() + } +} + +// overflow detaches a subscription whose client fell too far behind and lets +// its writer end the stream with a resync frame. Callers must not hold h.mu. +func (s *chatSub) overflow() { + s.overOnce.Do(func() { + s.qmu.Lock() + s.overflowed = true + s.queue = nil + if s.ready != nil { + select { + case s.ready <- struct{}{}: + default: + } + } + s.qmu.Unlock() + log.Printf("chat session %s: client %s fell %d frames behind; it is told to resync", s.room.sessionID, s.clientID, chatRoomSubscriberBuffer) + s.hub.detach(s.room.sessionID, s) + }) } // close detaches the subscription and stops its writer goroutine exactly once. @@ -96,6 +198,61 @@ func (s *chatSub) close() { }) } +// joinChatDeltas joins next onto last when both are plain text or reasoning +// deltas of the same part, so a burst takes one queue slot. Numbered deltas +// join only when consecutive; the joined frame names its first delta +// (SeqFrom) and each delta's length, so a client whose history page already +// holds a prefix can drop exactly that prefix. +func joinChatDeltas(last, next protocol.Message) (protocol.Message, bool) { + a, b := last.ChatEvent, next.ChatEvent + if last.Type != protocol.ChatEvent || next.Type != protocol.ChatEvent || a == nil || b == nil || last.ID != "" || next.ID != "" { + return last, false + } + if !plainChatDelta(a) || !plainChatDelta(b) || a.Kind != b.Kind || a.SessionID != b.SessionID || a.MessageID != b.MessageID || + a.NativeTurnID != b.NativeTurnID || a.MessageKind != b.MessageKind || a.Part.ID != b.Part.ID || a.Part.Type != b.Part.Type { + return last, false + } + if (a.Seq == 0) != (b.Seq == 0) || (a.Seq != 0 && b.Seq != a.Seq+1) { + return last, false + } + joined := *a + part := *a.Part + joined.Part = &part + joined.Delta = a.Delta + b.Delta + if a.Seq != 0 { + lens := a.DeltaLens + if a.SeqFrom == 0 { + joined.SeqFrom = a.Seq + lens = []int{utf16Len(a.Delta)} + } + joined.DeltaLens = append(slices.Clip(lens), utf16Len(b.Delta)) + joined.Seq = b.Seq + } + last.ChatEvent = &joined + return last, true +} + +// plainChatDelta reports whether f carries only a text or reasoning delta. +func plainChatDelta(f *protocol.ChatEventFrame) bool { + return (f.Kind == protocol.ChatEventText || f.Kind == protocol.ChatEventReasoning) && f.Delta != "" && f.Part != nil && + f.Part.Text == "" && f.Step == nil && f.Usage == nil && f.Shell == nil && f.Form == nil && f.Compaction == nil && + len(f.Attachments) == 0 && f.Client == "" && f.OperationID == "" +} + +// utf16Len is the length of s in UTF-16 code units, the unit a Dart client +// indexes strings by. +func utf16Len(s string) int { + n := 0 + for _, r := range s { + if r >= 0x10000 { + n += 2 + } else { + n++ + } + } + return n +} + // chatQueuedPrompt is one prompt waiting for the session's in-flight turn to // finish. acked marks a prompt the handler already acknowledged as queued, so the // turn runner does not send a second (success) acknowledgement for the same @@ -316,7 +473,7 @@ func (h *chatHub) attach(sessionID, clientID, label string, broker chatBroker, w room: room, clientID: clientID, label: label, - ch: make(chan protocol.Message, chatRoomSubscriberBuffer), + ready: make(chan struct{}, 1), done: make(chan struct{}), write: write, } @@ -396,7 +553,7 @@ func (h *chatHub) roomBacklog(sessionID string) int { most := 0 if room := h.rooms[sessionID]; room != nil { for _, sub := range room.subs { - most = max(most, len(sub.ch)) + most = max(most, sub.queued()) } } return most @@ -529,7 +686,7 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) { } h.mu.Unlock() for _, sub := range slow { - sub.close() + sub.overflow() } return } @@ -543,19 +700,10 @@ func (h *chatHub) emitRoom(source *chatRoom, frame protocol.ChatEventFrame) { } } -// enqueueChatLocked never blocks or calls detach under the hub mutex. +// enqueueChatLocked never blocks or calls detach under the hub mutex. A false +// result means the client overflowed: call sub.overflow once h.mu is released. func enqueueChatLocked(sub *chatSub, msg protocol.Message) bool { - select { - case <-sub.done: - return true - default: - } - select { - case sub.ch <- msg: - return true - default: - return false - } + return sub.enqueue(msg) } func (h *chatHub) replayShells(sub *chatSub) { @@ -574,7 +722,7 @@ func (h *chatHub) replayShells(sub *chatSub) { } h.mu.Unlock() if slow { - sub.close() + sub.overflow() } } @@ -661,7 +809,7 @@ func (h *chatHub) flushBuffered(sessionID string) { } h.mu.Unlock() for _, sub := range slow { - sub.close() + sub.overflow() } } @@ -1012,7 +1160,7 @@ func (h *chatHub) endLostTurn(room *chatRoom, done chan struct{}, idle time.Dura } h.mu.Unlock() for _, sub := range slow { - sub.close() + sub.overflow() } return true } diff --git a/internal/server/chat_sub_overflow_test.go b/internal/server/chat_sub_overflow_test.go new file mode 100644 index 00000000..8e515ab7 --- /dev/null +++ b/internal/server/chat_sub_overflow_test.go @@ -0,0 +1,125 @@ +package server + +import ( + "strings" + "sync" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// take pops the oldest queued frame (the zero Message when none is queued). +func (s *chatSub) take() protocol.Message { + msg, _, _ := s.next() + return msg +} + +func deltaMessage(seq int64, delta string) protocol.Message { + frame := protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventText, Delta: delta, Seq: seq, + Part: &protocol.ChatPart{Type: protocol.ChatPartText, ID: "msg_1-text-0"}} + return protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame} +} + +// A streaming burst must not overflow a client that is merely a little slow: +// consecutive deltas of one part take one queue slot, and the joined frame +// says which numbered deltas it holds and how long each one is. +func TestChatSubJoinsConsecutiveDeltasOfOnePart(t *testing.T) { + sub := &chatSub{limit: 2, done: make(chan struct{})} + pieces := []string{"héllo ", "wörld ", "😀!"} + for i, piece := range pieces { + if !sub.enqueue(deltaMessage(int64(10+i), piece)) { + t.Fatalf("delta %d overflowed a two-slot queue", i) + } + } + if sub.queued() != 1 { + t.Fatalf("queued = %d, want the burst joined into one frame", sub.queued()) + } + // A frame of another kind is never joined. + step := protocol.ChatEventFrame{SessionID: "ses_1", Kind: protocol.ChatEventStep, Step: &protocol.ChatStep{Status: protocol.ChatStepEnded}} + if !sub.enqueue(protocol.Message{Type: protocol.ChatEvent, ChatEvent: &step}) { + t.Fatal("step frame refused") + } + if sub.enqueue(deltaMessage(13, "late")) { + t.Fatal("a delta after the step joined across it") + } + joined := sub.take().ChatEvent + if joined.Delta != strings.Join(pieces, "") || joined.SeqFrom != 10 || joined.Seq != 12 { + t.Fatalf("joined = %+v", joined) + } + if want := []int{6, 6, 3}; len(joined.DeltaLens) != 3 || joined.DeltaLens[0] != want[0] || joined.DeltaLens[1] != want[1] || joined.DeltaLens[2] != want[2] { + t.Fatalf("delta lengths = %v, want %v (UTF-16 units)", joined.DeltaLens, want) + } + // A gap in the numbering is never joined over. + sub2 := &chatSub{limit: 4, done: make(chan struct{})} + sub2.enqueue(deltaMessage(1, "a")) + sub2.enqueue(deltaMessage(3, "c")) + if sub2.queued() != 2 { + t.Fatal("deltas with a numbering gap were joined") + } +} + +// The frame a delta came from is shared by every subscriber, so joining for +// one slow client must not change what another client is sent. +func TestChatSubJoinDoesNotMutateSharedFrames(t *testing.T) { + sub := &chatSub{limit: 4, done: make(chan struct{})} + first := deltaMessage(1, "a") + sub.enqueue(first) + sub.enqueue(deltaMessage(2, "b")) + if first.ChatEvent.Delta != "a" || first.ChatEvent.Seq != 1 || first.ChatEvent.SeqFrom != 0 { + t.Fatalf("shared frame mutated: %+v", first.ChatEvent) + } +} + +// The live incident: a slow client's 64-frame buffer filled and the server +// silently dropped its subscription, so the app kept showing a frozen +// transcript until the next reconnect. Now the client's last frame is a +// resync, which makes the app re-attach and re-read the history. +func TestChatSubOverflowEndsWithAResyncFrame(t *testing.T) { + h := newChatHub() + h.mu.Lock() + room := h.roomLocked("ses_1") + h.mu.Unlock() + defer room.cancel() + release := make(chan struct{}) + var mu sync.Mutex + var written []protocol.Message + write := func(msg protocol.Message) error { + <-release // the client does not read until the burst is over + mu.Lock() + written = append(written, msg) + mu.Unlock() + return nil + } + sub := h.attach("ses_1", "slow", "Phone", nil, write) + for i := range chatRoomSubscriberBuffer + 8 { + // Tool frames never join, so the queue fills. + frame := protocol.ChatEventFrame{SessionID: "ses_1", MessageID: "msg_1", Kind: protocol.ChatEventTool, + Part: &protocol.ChatPart{Type: protocol.ChatPartTool, ID: "tool", Name: strings.Repeat("x", i%3+1)}} + h.fanout("ses_1", protocol.Message{Type: protocol.ChatEvent, ChatEvent: &frame}, "") + } + h.mu.Lock() + attached := room.subs["slow"] == sub + h.mu.Unlock() + if attached { + t.Fatal("an overflowed client stayed attached") + } + close(release) + select { + case <-sub.done: + case <-time.After(5 * time.Second): + t.Fatal("the overflowed subscription never closed") + } + mu.Lock() + defer mu.Unlock() + last := written[len(written)-1] + if last.Type != protocol.ChatEvent || last.ChatEvent == nil || last.ChatEvent.Kind != protocol.ChatEventResync || last.ChatEvent.SessionID != "ses_1" { + t.Fatalf("the overflowed client's last frame was %+v, want a resync", last) + } + // The client re-attaches with its own subscribe: a fresh subscription. + again := h.attach("ses_1", "slow", "Phone", nil, func(protocol.Message) error { return nil }) + if again == nil || again == sub { + t.Fatal("re-attaching after an overflow did not create a fresh subscription") + } + again.close() +} diff --git a/internal/server/chat_unattended_test.go b/internal/server/chat_unattended_test.go index d6d2e23d..0c5f1fbc 100644 --- a/internal/server/chat_unattended_test.go +++ b/internal/server/chat_unattended_test.go @@ -337,7 +337,7 @@ func TestChatUnattendedRoomsAreBounded(t *testing.T) { h.mu.Lock() room := h.roomLocked(id) room.running = true - sub := &chatSub{hub: h, room: room, clientID: "c", ch: make(chan protocol.Message, 1), done: make(chan struct{})} + sub := &chatSub{hub: h, room: room, clientID: "c", limit: 1, done: make(chan struct{})} room.subs["c"] = sub h.mu.Unlock() h.detach(id, sub) diff --git a/internal/server/chat_usage_test.go b/internal/server/chat_usage_test.go index b72105f2..31d99707 100644 --- a/internal/server/chat_usage_test.go +++ b/internal/server/chat_usage_test.go @@ -15,20 +15,20 @@ func TestUsageRetainedWithoutMessageReplayResetAndAdmissionIsolation(t *testing. room.nativeTurnID = "turn_keep" room.turnDone = make(chan struct{}) h.rooms[room.sessionID] = room - sub := &chatSub{hub: h, room: room, clientID: "watcher", ch: make(chan protocol.Message, 32), done: make(chan struct{})} + sub := &chatSub{hub: h, room: room, clientID: "watcher", limit: 32, done: make(chan struct{})} room.subs[sub.clientID] = sub h.apply(protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventCompaction, Compaction: &protocol.ChatCompaction{Status: "running"}}) for _, n := range []int64{123, 123, 0, 5} { total := n u := &protocol.ChatUsage{Scope: "session", TotalTokens: &total} h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: u}) - live := (<-sub.ch).ChatEvent + live := (sub.take()).ChatEvent if live.MessageID != "" || *live.Usage.TotalTokens != n { t.Fatalf("live=%+v", live) } total = 999 // producer-owned data must not mutate retained state h.replayUsage(sub) - frame := (<-sub.ch).ChatEvent + frame := (sub.take()).ChatEvent if frame == nil || frame.Kind != protocol.ChatEventUsage || frame.MessageID != "" || frame.Usage.TotalTokens == nil || *frame.Usage.TotalTokens != n { t.Fatalf("replay=%+v", frame) } @@ -47,18 +47,18 @@ func TestUsageRetainedWithoutMessageReplayResetAndAdmissionIsolation(t *testing. } // A full snapshot may legitimately reset every unknown field to nil. h.emitRoom(room, protocol.ChatEventFrame{SessionID: room.sessionID, Kind: protocol.ChatEventUsage, Usage: &protocol.ChatUsage{Scope: "session"}}) - <-sub.ch + sub.take() h.replayUsage(sub) - if f := (<-sub.ch).ChatEvent; f.Usage.TotalTokens != nil { + if f := (sub.take()).ChatEvent; f.Usage.TotalTokens != nil { t.Fatal("unknown snapshot accumulated old counter") } other := newChatRoom(context.Background(), "ses_other") defer other.cancel() h.rooms[other.sessionID] = other - otherSub := &chatSub{hub: h, room: other, clientID: "other", ch: make(chan protocol.Message, 4), done: make(chan struct{})} + otherSub := &chatSub{hub: h, room: other, clientID: "other", limit: 4, done: make(chan struct{})} other.subs[otherSub.clientID] = otherSub h.replayUsage(otherSub) - if len(otherSub.ch) != 0 { + if otherSub.queued() != 0 { t.Fatal("foreign usage replayed") } } diff --git a/internal/server/runevents.go b/internal/server/runevents.go index ddf8bfd8..bd4e4e3c 100644 --- a/internal/server/runevents.go +++ b/internal/server/runevents.go @@ -1,6 +1,7 @@ package server import ( + "log" "sync" "time" @@ -90,6 +91,11 @@ type runSubscription struct { mu sync.Mutex snapshotting bool pending []protocol.Message + + // overflowed is closed once the subscriber fell too far behind: it is + // already detached, and its writer ends the stream with runs_resync. + overflowed chan struct{} + overOnce sync.Once } func newRunEventHub() *runEventHub { @@ -129,6 +135,7 @@ func (h *runEventHub) subscribe(clientID, workspace string, runIDs []int64, writ workspace: workspace, ch: make(chan protocol.Message, runEventSubscriberBuffer), done: make(chan struct{}), + overflowed: make(chan struct{}), write: write, snapshotting: true, } @@ -378,9 +385,19 @@ func (s *runSubscription) matches(workspace string, runID int64) bool { func (s *runSubscription) run() { for { + select { + case <-s.overflowed: + // The terminal frame: the frames still queued are discarded, so + // the client must subscribe again and re-read the runs. + _ = s.write(protocol.Message{Type: protocol.RunsResync}) + s.close() + return + default: + } select { case <-s.done: return + case <-s.overflowed: case msg := <-s.ch: if err := s.write(msg); err != nil { s.close() @@ -450,7 +467,7 @@ func (s *runSubscription) sendMessage(msg protocol.Message) { // the snapshot and the ack are written directly by the subscriber. if len(s.pending) >= runEventSubscriberBuffer { s.mu.Unlock() - s.close() + s.overflow() return } s.pending = append(s.pending, msg) @@ -461,12 +478,24 @@ func (s *runSubscription) sendMessage(msg protocol.Message) { select { case s.ch <- msg: default: - // The subscriber is not draining: drop it rather than block the - // producer. Its next subscribe re-syncs from a fresh snapshot. - s.close() + // The subscriber is not draining: detach it rather than block the + // producer. Its writer tells it to subscribe again for a fresh + // snapshot. + s.overflow() } } +// overflow detaches a subscriber that fell too far behind and lets its writer +// (started by ready, if the snapshot is still being written) end the stream +// with runs_resync. +func (s *runSubscription) overflow() { + s.overOnce.Do(func() { + close(s.overflowed) + log.Printf("run events: client %s fell %d frames behind; it is told to resync", s.clientID, runEventSubscriberBuffer) + s.hub.remove(s) + }) +} + // close unregisters the subscription and stops its writer goroutine exactly // once. It is safe to call from the writer goroutine, from unsubscribe and from // the disconnect path. diff --git a/internal/server/runevents_overflow_test.go b/internal/server/runevents_overflow_test.go new file mode 100644 index 00000000..2b65e2b8 --- /dev/null +++ b/internal/server/runevents_overflow_test.go @@ -0,0 +1,47 @@ +package server + +import ( + "sync" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/protocol" +) + +// A run subscriber that falls behind used to be dropped silently: the app's +// run list and open detail froze until the next reconnect. Now it is detached +// and its last frame is runs_resync, which makes the app subscribe again. +func TestRunSubscriptionOverflowEndsWithRunsResync(t *testing.T) { + h := newRunEventHub() + release := make(chan struct{}) + var mu sync.Mutex + var written []protocol.Message + sub := h.subscribe("conn", "", nil, func(msg protocol.Message) error { + <-release + mu.Lock() + written = append(written, msg) + mu.Unlock() + return nil + }) + sub.ready() + for i := range runEventSubscriberBuffer + 4 { + sub.send(protocol.RunEventFrame{RunID: int64(i + 1), Status: protocol.RunStatusRunning}) + } + h.mu.Lock() + _, attached := h.subs[sub] + h.mu.Unlock() + if attached { + t.Fatal("an overflowed run subscriber stayed attached") + } + close(release) + select { + case <-sub.done: + case <-time.After(5 * time.Second): + t.Fatal("the overflowed subscription never closed") + } + mu.Lock() + defer mu.Unlock() + if last := written[len(written)-1]; last.Type != protocol.RunsResync { + t.Fatalf("the overflowed client's last frame was %q, want %q", last.Type, protocol.RunsResync) + } +} From 8bd219e636ed1bd5db4fb0df389a05c68d7a0691 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:41:39 +0000 Subject: [PATCH 10/19] Chat: find in chat (Ctrl+F / Cmd+F) A find bar over the transcript: query, Match case, n of N (counted from the newest), Enter for an older match and Shift+Enter for a newer one. Matches are painted over the rendered text, code blocks included, without restyling it; the current match is scrolled into view. Matches in history not loaded yet come from the server's chat:-scoped search and are reached by loading older pages. Esc closes and returns to the composer. The key is the pane's, so a focused terminal keeps Ctrl+F. Fixture answers scoped searches for captures; cheatsheet lists the key. The scoped search matches the query as typed, spaces included, like the client. Co-Authored-By: Claude Opus 5.5 --- .../chat/conversation/chat_find_bar.dart | 140 +++++++++ .../conversation/chat_find_controller.dart | 261 ++++++++++++++++ .../chat/conversation/chat_find_host.dart | 221 ++++++++++++++ .../chat/conversation/chat_thread_view.dart | 281 ++++++++++-------- app/lib/features/chat/domain/chat_find.dart | 146 +++++++++ .../ui/transcript/chat_find_highlight.dart | 278 +++++++++++++++++ .../chat/ui/transcript/chat_link_text.dart | 14 +- .../ui/transcript/chat_markdown_view.dart | 33 +- .../settings/keyboard_shortcuts_registry.dart | 7 + .../chat/conversation/chat_find_test.dart | 184 ++++++++++++ .../features/chat/domain/chat_find_test.dart | 78 +++++ app/tool/perf/chat_scroll_fixture.dart | 39 +++ app/tool/search_selection_probe_entry.dart | 19 ++ internal/server/search_chat_scoped.go | 6 +- 14 files changed, 1581 insertions(+), 126 deletions(-) create mode 100644 app/lib/features/chat/conversation/chat_find_bar.dart create mode 100644 app/lib/features/chat/conversation/chat_find_controller.dart create mode 100644 app/lib/features/chat/conversation/chat_find_host.dart create mode 100644 app/lib/features/chat/domain/chat_find.dart create mode 100644 app/lib/features/chat/ui/transcript/chat_find_highlight.dart create mode 100644 app/test/features/chat/conversation/chat_find_test.dart create mode 100644 app/test/features/chat/domain/chat_find_test.dart diff --git a/app/lib/features/chat/conversation/chat_find_bar.dart b/app/lib/features/chat/conversation/chat_find_bar.dart new file mode 100644 index 00000000..4fbf3461 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_find_bar.dart @@ -0,0 +1,140 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import 'chat_find_controller.dart'; + +/// The chat's find bar, like the terminal's: the query field, the match +/// count, Match case, the older/newer and close buttons. Matches count from +/// the newest; Enter moves to an older match and Shift+Enter to a newer one; +/// Esc closes. [onStep] moves and reveals; [onClose] closes the bar and +/// returns the keyboard to the composer. +class ChatFindBar extends StatefulWidget { + const ChatFindBar({ + super.key, + required this.find, + required this.focus, + required this.onStep, + required this.onClose, + }); + + final ChatFindController find; + final FocusNode focus; + final ValueChanged onStep; + final VoidCallback onClose; + + @override + State createState() => _ChatFindBarState(); +} + +class _ChatFindBarState extends State { + late final TextEditingController _text = TextEditingController( + text: widget.find.query, + ); + + @override + void dispose() { + _text.dispose(); + super.dispose(); + } + + KeyEventResult _key(FocusNode node, KeyEvent event) { + if (event is KeyUpEvent) return KeyEventResult.ignored; + if (event.logicalKey == LogicalKeyboardKey.escape) { + widget.onClose(); + return KeyEventResult.handled; + } + if (event.logicalKey == LogicalKeyboardKey.enter || + event.logicalKey == LogicalKeyboardKey.numpadEnter) { + widget.onStep(HardwareKeyboard.instance.isShiftPressed ? -1 : 1); + return KeyEventResult.handled; + } + return KeyEventResult.ignored; + } + + String _count(ChatFindController find) { + if (find.query.isEmpty) return ''; + if (find.count == 0) return find.capped ? 'Searching…' : 'No results'; + final total = find.capped ? '${find.count}+' : '${find.count}'; + return '${find.index + 1} of $total'; + } + + @override + Widget build(BuildContext context) { + final find = widget.find; + final scheme = Theme.of(context).colorScheme; + // The buttons count as part of the field, so clicking one keeps the + // keyboard in it (Enter steps on from there). + return TextFieldTapRegion( + child: Material( + elevation: 3, + color: scheme.surfaceContainerHigh, + borderRadius: BorderRadius.circular(8), + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 12, end: 4), + child: ListenableBuilder( + listenable: find, + builder: (context, _) => Row( + mainAxisSize: MainAxisSize.min, + children: [ + Flexible( + child: ConstrainedBox( + constraints: const BoxConstraints(maxWidth: 240), + child: Focus( + onKeyEvent: _key, + skipTraversal: true, + child: TextField( + key: const ValueKey('chat-find-field'), + controller: _text, + focusNode: widget.focus, + autofocus: true, + decoration: const InputDecoration( + hintText: 'Find in chat', + border: InputBorder.none, + isDense: true, + ), + onChanged: (value) => find.query = value, + ), + ), + ), + ), + Semantics( + liveRegion: true, + child: Text( + _count(find), + key: const ValueKey('chat-find-count'), + style: Theme.of(context).textTheme.bodySmall, + ), + ), + IconButton( + key: const ValueKey('chat-find-case'), + tooltip: 'Match case', + isSelected: find.caseSensitive, + onPressed: find.toggleCase, + icon: const Text('Aa'), + ), + IconButton( + key: const ValueKey('chat-find-older'), + tooltip: 'Older match (Enter)', + onPressed: find.count == 0 ? null : () => widget.onStep(1), + icon: const Icon(Icons.keyboard_arrow_up), + ), + IconButton( + key: const ValueKey('chat-find-newer'), + tooltip: 'Newer match (Shift+Enter)', + onPressed: find.count == 0 ? null : () => widget.onStep(-1), + icon: const Icon(Icons.keyboard_arrow_down), + ), + IconButton( + key: const ValueKey('chat-find-close'), + tooltip: 'Close find (Esc)', + onPressed: widget.onClose, + icon: const Icon(Icons.close), + ), + ], + ), + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/conversation/chat_find_controller.dart b/app/lib/features/chat/conversation/chat_find_controller.dart new file mode 100644 index 00000000..38701818 --- /dev/null +++ b/app/lib/features/chat/conversation/chat_find_controller.dart @@ -0,0 +1,261 @@ +import 'dart:async'; + +import 'package:flutter/widgets.dart'; + +import '../../../core/api_gateway.dart'; +import '../domain/chat_find.dart'; + +/// A highlighted range in one rendered text, and whether it is the current +/// match. +typedef ChatFindHighlight = ({int start, int end, bool current}); + +/// Find in one chat: the query, whether case matters, the matches in the +/// loaded transcript and, through the server's scoped search, those in older +/// history not loaded yet. +/// +/// Matches are numbered from the newest: "1 of N" is the newest match and +/// stepping on (Enter) goes back in time, so finding never starts by jumping +/// to the start of a long history. The loaded matches come first; the +/// server's hits in unloaded messages, all older, follow in its order, so a +/// match keeps its number when the page holding it loads. +class ChatFindController extends ChangeNotifier { + ChatFindController({ + required this.gateway, + required this.sessionId, + required this.history, + this.debounce = const Duration(milliseconds: 250), + }); + + final ApiGateway gateway; + final String sessionId; + final Duration debounce; + + /// Whether the transcript has older history it has not loaded, and the + /// cursor its next older page would be read with. + final ({bool hasMore, String cursor}) Function() history; + + String _query = ''; + bool _caseSensitive = false; + List _units = const []; + Set _loadedIds = const {}; + + /// Loaded matches, newest first. + List _local = const []; + List _remoteAll = const []; + List _remote = const []; + bool _remoteMore = false; + bool _searching = false; + int _index = -1; + ChatFindMatch? _currentLocal; + int _generation = 0; + Timer? _timer; + Map>> _byRow = const {}; + bool _disposed = false; + + String get query => _query; + bool get caseSensitive => _caseSensitive; + + /// How many matches are known: loaded ones and the server's in history + /// that is not loaded. + int get count => _local.length + _remote.length; + + /// Whether there may be more matches than [count] (the server's search + /// stopped at its cap, or is still running). + bool get capped => + _remoteMore || _searching || _local.length >= chatFindLocalCap; + + /// The current match's number from the newest (0-based), -1 with none. + int get index => _index; + + /// The current match when it is in the loaded transcript. + ChatFindMatch? get current => + _index >= 0 && _index < _local.length ? _local[_index] : null; + + /// The current match when it is in history not loaded yet. + ChatFindRemoteHit? get currentRemote { + final at = _index - _local.length; + return at >= 0 && at < _remote.length ? _remote[at] : null; + } + + /// Bumped whenever the current match moves, so the view reveals it once. + int get revealToken => _revealToken; + int _revealToken = 0; + + /// The highlights in [text] of row [rowKey]. + List highlightsFor(String rowKey, String text) => + _byRow[rowKey]?[text] ?? const []; + + set query(String value) { + if (value == _query) return; + _query = value; + _restart(); + } + + void toggleCase() { + _caseSensitive = !_caseSensitive; + _restart(); + } + + /// Moves to an older match ([step] 1) or a newer one (-1), wrapping. + void step(int step) { + if (count == 0) return; + _select((_index + step) % count); + } + + /// Takes the transcript as it is now. The current loaded match stays + /// current; otherwise the current number does. Listeners hear of a change + /// after this frame, since the transcript calls this while it builds. + void updateTranscript( + List rows, + List keys, + Iterable loadedMessageIds, + ) { + final units = chatFindUnits(rows, keys); + _loadedIds = {...loadedMessageIds}; + final sameUnits = _sameUnits(units); + _units = units; + if (sameUnits && _remote.length == _filterRemote().length) return; + _recompute(keepCurrent: true); + WidgetsBinding.instance.addPostFrameCallback((_) => _notify()); + } + + bool _sameUnits(List units) { + if (units.length != _units.length) return false; + for (var i = 0; i < units.length; i++) { + if (units[i].rowKey != _units[i].rowKey || + !identical(units[i].text, _units[i].text) && + units[i].text != _units[i].text) { + return false; + } + } + return true; + } + + List _filterRemote() => [ + for (final hit in _remoteAll) + if (!_loadedIds.contains(hit.messageId)) hit, + ]; + + void _restart() { + _generation++; + _timer?.cancel(); + _remoteAll = const []; + _remote = const []; + _remoteMore = false; + _searching = false; + _currentLocal = null; + _index = -1; + _recompute(keepCurrent: false); + _searchHistory(); + _notify(); + } + + void _recompute({required bool keepCurrent}) { + final previous = keepCurrent ? _currentLocal : null; + final previousIndex = _index; + _local = _query.isEmpty + ? const [] + : chatFindMatches( + _units, + _query, + caseSensitive: _caseSensitive, + ).reversed.toList(); + _remote = _filterRemote(); + var index = -1; + if (previous != null) { + index = _local.indexWhere(previous.sameAs); + } + if (index < 0 && keepCurrent && previousIndex >= 0 && count > 0) { + index = previousIndex.clamp(0, count - 1); + } + if (index < 0 && count > 0) index = 0; + _setIndex(index, reveal: !keepCurrent || index != previousIndex); + _rebuildHighlights(); + } + + void _select(int index) { + _setIndex(index, reveal: true); + _rebuildHighlights(); + _notify(); + } + + void _setIndex(int index, {required bool reveal}) { + _index = index; + _currentLocal = current; + if (reveal && index >= 0) _revealToken++; + } + + void _rebuildHighlights() { + final byRow = >>{}; + final now = current; + for (final match in _local) { + byRow + .putIfAbsent(match.rowKey, () => {}) + .putIfAbsent(match.unit.text, () => []) + .add(( + start: match.start, + end: match.end, + current: identical(match, now), + )); + } + _byRow = byRow; + } + + /// Asks the server for matches in the history before the transcript's + /// loaded pages, after a short pause in typing. Without older history + /// there is nothing to ask. + void _searchHistory() { + final older = history(); + if (_query.isEmpty || !older.hasMore) return; + final generation = _generation; + _searching = true; + _timer = Timer(debounce, () { + unawaited(_fetch(generation, '0|${older.cursor}')); + }); + } + + Future _fetch(int generation, String cursor) async { + var next = cursor; + final hits = []; + try { + while (true) { + final reply = await gateway.call('search', { + 'search': { + 'query': _query, + 'kind': 'chat', + 'scope': 'chat:$sessionId', + 'cursor': next, + 'case_sensitive': _caseSensitive, + 'limit': 200, + }, + }); + if (_disposed || generation != _generation) return; + hits.addAll(ChatFindRemoteHit.fromReply(reply)); + final results = reply['search_results']; + next = results is Map ? '${results['next_cursor'] ?? ''}' : ''; + _remoteAll = List.unmodifiable(hits); + _remoteMore = next.isNotEmpty && hits.length >= chatFindRemoteCap; + _recompute(keepCurrent: true); + _notify(); + if (next.isEmpty || hits.length >= chatFindRemoteCap) break; + } + } catch (_) { + // An older server without scoped search, or a dropped socket: the + // loaded transcript's matches still stand. + if (_disposed || generation != _generation) return; + } + _searching = false; + _notify(); + } + + void _notify() { + if (!_disposed) notifyListeners(); + } + + @override + void dispose() { + _disposed = true; + _timer?.cancel(); + super.dispose(); + } +} diff --git a/app/lib/features/chat/conversation/chat_find_host.dart b/app/lib/features/chat/conversation/chat_find_host.dart new file mode 100644 index 00000000..73504e2c --- /dev/null +++ b/app/lib/features/chat/conversation/chat_find_host.dart @@ -0,0 +1,221 @@ +import 'dart:async'; +import 'dart:math' as math; + +import 'package:flutter/foundation.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; +import 'package:flutter/services.dart'; + +import '../../../core/api_gateway.dart'; +import '../../../ui/input/keyboard_owner.dart'; +import '../shell/chat_shell_terminal_find_bar.dart'; +import '../ui/transcript/chat_find_highlight.dart'; +import 'chat_find_bar.dart'; +import 'chat_find_controller.dart'; +import 'chat_thread_controller.dart'; +import 'chat_thread_view.dart'; +import 'composer_focus_request.dart'; + +/// Whether [event] is find's key: Cmd+F on Apple platforms, Ctrl+F +/// elsewhere, without Shift or Alt. +bool chatFindShortcut(KeyEvent event, HardwareKeyboard keyboard) { + if (event is! KeyDownEvent || event.logicalKey != LogicalKeyboardKey.keyF) { + return false; + } + final apple = + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS; + final ctrl = keyboard.isControlPressed; + final meta = keyboard.isMetaPressed; + if (keyboard.isAltPressed || keyboard.isShiftPressed) return false; + return apple ? meta && !ctrl : ctrl && !meta; +} + +/// Find in one open chat: Ctrl+F (Cmd+F) opens the bar over the transcript, +/// matches are highlighted, the current one is scrolled into view (reading +/// older pages until it is loaded), and Esc closes the bar and returns the +/// keyboard to the composer. +mixin ChatFindHost on State { + ScrollController get findScroll; + ChatThreadController get findThread; + + /// Stops the transcript following its end while find moves it. + void findReleaseFollow(); + + /// Lets the transcript decide again whether it follows its end. + void findSettleFollow(); + + final findTargets = ChatFindTargets(); + final FocusNode _findFocus = FocusNode(debugLabel: 'chat-find'); + ChatFindController? _find; + int _revealed = 0; + Map _rowIndex = const {}; + + ChatFindController? get find => _find; + + void disposeFind() { + _find?.dispose(); + _findFocus.dispose(); + } + + /// The pane's key handler: find's shortcut from anywhere in this chat, + /// except a terminal (where Ctrl+F is the shell's) and its own find bar. + KeyEventResult findKey(FocusNode node, KeyEvent event) { + if (!chatFindShortcut(event, HardwareKeyboard.instance)) { + return KeyEventResult.ignored; + } + if (primaryFocusIsTypingSurface()) return KeyEventResult.ignored; + final focused = FocusManager.instance.primaryFocus?.context; + if (focused?.findAncestorWidgetOfExactType() != + null) { + return KeyEventResult.ignored; + } + openFind(); + return KeyEventResult.handled; + } + + /// Opens the find bar, or focuses its field when it is open. + void openFind() { + if (_find == null) { + final find = ChatFindController( + gateway: widget.gateway, + sessionId: widget.sessionId, + history: () => (hasMore: findThread.hasMore, cursor: findThread.cursor), + )..addListener(_findChanged); + setState(() => _find = find); + } + // The field's autofocus would not take the keyboard from the composer, + // which holds it in the same scope. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted && _find != null) _findFocus.requestFocus(); + }); + } + + void closeFind() { + final find = _find; + if (find == null) return; + setState(() => _find = null); + find.dispose(); + findSettleFollow(); + ChatComposerFocusScope.maybeOf(context)?.requests.request(widget.sessionId); + } + + void _findChanged() { + final find = _find; + if (find == null || find.revealToken == _revealed) return; + _revealed = find.revealToken; + unawaited(_reveal(find, _revealed)); + } + + /// Hands the transcript as built to an open find. + void findTranscript(List rows, List keys) { + final find = _find; + if (find == null) return; + _rowIndex = {for (var i = 0; i < keys.length; i++) keys[i]: i}; + find.updateTranscript(rows, keys, [ + for (final message in findThread.messages) + if ('${message['id'] ?? ''}'.isNotEmpty) '${message['id']}', + ]); + } + + /// [transcript] inside find's scope. + Widget findScope(Widget transcript) => + ChatFindScope(controller: _find, targets: findTargets, child: transcript); + + /// The bar over the transcript's top end while find is open. + Widget? findBar({required double top, required double end}) { + final find = _find; + if (find == null) return null; + return PositionedDirectional( + top: top, + start: 8, + end: end, + child: Align( + alignment: AlignmentDirectional.topEnd, + child: ChatFindBar( + find: find, + focus: _findFocus, + onStep: find.step, + onClose: closeFind, + ), + ), + ); + } + + /// Brings find's current match into view: reads older pages until it is + /// loaded, scrolls toward its row until the row is built, then centres the + /// match. A newer move ([token]) abandons this one. + Future _reveal(ChatFindController find, int token) async { + bool stale() => !mounted || _find != find || find.revealToken != token; + findReleaseFollow(); + for (var attempt = 0; attempt < 120; attempt++) { + if (stale()) return; + if (find.currentRemote != null) { + if (!findThread.hasMore) return; + if (!findThread.loading) await findThread.loadOlder(); + await WidgetsBinding.instance.endOfFrame; + continue; + } + final match = find.current; + if (match == null || !findScroll.hasClients) return; + final rects = findTargets.textFor(match.rowKey, match.unit.text); + final row = findTargets.rows[match.rowKey]; + if (rects != null && row != null && row.mounted) { + if (_centre(row, rects, match.start, match.end)) break; + } else if (!_stepToward(match.unit.rowIndex)) { + return; + } + await WidgetsBinding.instance.endOfFrame; + } + if (!stale()) findSettleFollow(); + } + + /// Scrolls so the match is in the middle of the viewport when it is not + /// already comfortably in view; true once it is placed. + bool _centre(BuildContext row, ChatFindRects rects, int start, int end) { + final object = row.findRenderObject(); + if (object == null || !object.attached) return false; + final viewport = RenderAbstractViewport.maybeOf(object); + if (viewport is! RenderBox || !(viewport as RenderBox).hasSize) { + return false; + } + final box = viewport as RenderBox; + final boxes = rects(start, end, box); + if (boxes.isEmpty) { + unawaited(Scrollable.ensureVisible(row, alignment: 0.5)); + return false; + } + final match = boxes.reduce((a, b) => a.expandToInclude(b)); + final height = box.size.height; + final margin = math.min(64.0, height / 4); + if (match.top >= margin && match.bottom <= height - margin) return true; + final position = findScroll.position; + final target = (position.pixels + match.center.dy - height / 2).clamp( + position.minScrollExtent, + position.maxScrollExtent, + ); + if ((target - position.pixels).abs() < 1) return true; + position.jumpTo(target); + return false; + } + + /// Moves the transcript a screen toward row [index] when it is not built; + /// false when it cannot move further. + bool _stepToward(int index) { + final built = [ + for (final entry in findTargets.rows.entries) + if (entry.value.mounted && _rowIndex[entry.key] != null) + _rowIndex[entry.key]!, + ]; + final position = findScroll.position; + final older = built.isEmpty || index < built.reduce(math.min); + final distance = position.viewportDimension * 0.8; + final target = (position.pixels + (older ? -distance : distance)).clamp( + position.minScrollExtent, + position.maxScrollExtent, + ); + if ((target - position.pixels).abs() < 1) return false; + position.jumpTo(target); + return true; + } +} diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 270c9f41..0d09896b 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -27,6 +27,7 @@ import '../ui/sessions/chat_color_picker.dart'; import '../ui/sessions/session_actions.dart'; import '../ui/sessions/session_row_content.dart'; import '../ui/sessions/chat_adaptive.dart'; +import '../ui/transcript/chat_find_highlight.dart'; import '../ui/transcript/chat_markdown_view.dart'; import '../ui/transcript/chat_message_bubble.dart'; import '../ui/transcript/chat_message_view.dart'; @@ -50,6 +51,7 @@ import 'chat_session_section.dart'; import 'chat_background_tasks.dart'; import 'chat_command_actions.dart'; import 'chat_composer_bar.dart'; +import 'chat_find_host.dart'; import 'chat_composer_controller.dart'; import 'chat_escape_stop.dart'; import 'chat_delivery_indicator.dart'; @@ -241,7 +243,26 @@ class ChatThreadView extends StatefulWidget { State createState() => _ChatThreadViewState(); } -class _ChatThreadViewState extends State { +class _ChatThreadViewState extends State with ChatFindHost { + @override + ScrollController get findScroll => _scroll; + @override + ChatThreadController get findThread => _controller; + + @override + void findReleaseFollow() { + if (!_following) return; + setState(() { + _following = false; + _newestAtRelease = _newestMessageId(); + }); + } + + @override + void findSettleFollow() { + if (_scroll.hasClients) _updateFollow(_scroll.position); + } + late ChatThreadController _controller = _attach(); late ChatComposerController _composer = _attachComposer(); @@ -831,6 +852,7 @@ class _ChatThreadViewState extends State { _saveTranscript(widget.transcripts, widget.sessionId); widget.paneCommands?.removeListener(_takeCommands); widget.paneCommands?.setFinished(widget.sessionId, false); + disposeFind(); _scroll.dispose(); widget.onComposerDisposed?.call(_composer); _composer.dispose(); @@ -1247,6 +1269,7 @@ class _ChatThreadViewState extends State { // across paging and streaming. final keys = _rowKeys.forRows(rows); final split = _splitFor(rows); + findTranscript(rows, keys); final initialLoad = !_controller.loaded && _controller.loading; final historyNotice = _noticeOf( notices, @@ -1344,32 +1367,35 @@ class _ChatThreadViewState extends State { // Slivers mount only visible rows. Defer constructing // their chips and checking cached widgets until then, // rather than visiting the entire history per delta. - child: ChatDayDivided( - day: days[index], - // An answer row starts at the gutter; the divider - // keeps to the reading column. - inset: rows[index]['kind'] == 'assistant' - ? gutter - : 0, - child: ChatTranscriptRowSelection( - child: ChatCopyGutter( - width: rows[index]['kind'] == 'assistant' - ? gutter - : 0, - child: Builder( - builder: (_) => _entering( - rows[index], - _transcriptRow( + child: ChatFindRow( + rowKey: keys[index], + child: ChatDayDivided( + day: days[index], + // An answer row starts at the gutter; the divider + // keeps to the reading column. + inset: rows[index]['kind'] == 'assistant' + ? gutter + : 0, + child: ChatTranscriptRowSelection( + child: ChatCopyGutter( + width: rows[index]['kind'] == 'assistant' + ? gutter + : 0, + child: Builder( + builder: (_) => _entering( rows[index], - keys[index], - onDismissCompaction: - compactionNotice != null && - chatNoticeActivityCondition( - rows[index], - ) == - compactionNotice.condition - ? () => _dismiss(compactionNotice) - : null, + _transcriptRow( + rows[index], + keys[index], + onDismissCompaction: + compactionNotice != null && + chatNoticeActivityCondition( + rows[index], + ) == + compactionNotice.condition + ? () => _dismiss(compactionNotice) + : null, + ), ), ), ), @@ -1385,108 +1411,114 @@ class _ChatThreadViewState extends State { // the viewport itself ends above the composer. // Bottom-anchored at the split row, the newest rows are // laid out first and older ones only when scrolled to. - ChatTranscriptSelectionArea( - child: ChatTranscriptScrollView( - key: ValueKey( - 'chat-thread-${widget.sessionId}', - ), - controller: _scroll, - splitAfter: split < 0 - ? null - : ValueKey(keys[split]), - padding: EdgeInsets.fromLTRB( - side - gutter, - media.top + 8, - side, - 8, - ), - children: chatCopyGutterInset(gutter, transcript, [ - if (initialLoad) - Padding( - key: const Key('chat-thread-loading'), - padding: const EdgeInsets.all(16), - child: const Center(child: AppSpinner()), - ), - if (_controller.hasMore) - Padding( - key: const Key('chat-load-older'), - padding: const EdgeInsets.symmetric( - horizontal: 16, + findScope( + ChatTranscriptSelectionArea( + child: ChatTranscriptScrollView( + key: ValueKey( + 'chat-thread-${widget.sessionId}', + ), + controller: _scroll, + splitAfter: split < 0 + ? null + : ValueKey(keys[split]), + padding: EdgeInsets.fromLTRB( + side - gutter, + media.top + 8, + side, + 8, + ), + children: chatCopyGutterInset(gutter, transcript, [ + if (initialLoad) + Padding( + key: const Key('chat-thread-loading'), + padding: const EdgeInsets.all(16), + child: const Center(child: AppSpinner()), ), - child: Align( - alignment: AlignmentDirectional.centerStart, - child: TextButton( - onPressed: _controller.loading - ? null - : _controller.loadOlder, - child: const Text('Load older'), + if (_controller.hasMore) + Padding( + key: const Key('chat-load-older'), + padding: const EdgeInsets.symmetric( + horizontal: 16, + ), + child: Align( + alignment: + AlignmentDirectional.centerStart, + child: TextButton( + onPressed: _controller.loading + ? null + : _controller.loadOlder, + child: const Text('Load older'), + ), ), ), - ), - if (historyNotice != null) - _ChatNoticeLine( - key: const Key('chat-history-error'), - notice: historyNotice, - onDismiss: _dismiss, - onRetry: _controller.load, - ), - if (liveNotice != null) - _ChatNoticeLine( - key: const Key('chat-live-error'), - notice: liveNotice, - onDismiss: _dismiss, - onRetry: _controller.resync, - ), - if (_controller.loaded && - allRows.isEmpty && - allNotices.isEmpty && - _commandNotices.isEmpty && - _controller.error == null) - const Padding( - key: Key('chat-thread-empty'), - padding: EdgeInsets.all(16), - child: Text('No messages in this chat yet.'), - ), - ...transcript, - // Messages the server holds queued (one sent before - // a reload, or from another device) follow the - // transcript: none has reached the harness yet. - for (final prompt - in _controller.queuedOutsideTranscript) - Padding( - key: ValueKey( - 'chat-queued-${prompt['operation_id']}', + if (historyNotice != null) + _ChatNoticeLine( + key: const Key('chat-history-error'), + notice: historyNotice, + onDismiss: _dismiss, + onRetry: _controller.load, ), - padding: const EdgeInsets.symmetric( - horizontal: 16, + if (liveNotice != null) + _ChatNoticeLine( + key: const Key('chat-live-error'), + notice: liveNotice, + onDismiss: _dismiss, + onRetry: _controller.resync, ), - child: _queuedRow(prompt), - ), - // Messages the server has not accepted follow the - // transcript until they are retried or edited. - for (final send in _composer.deliveries.unsent) - Padding( - key: ValueKey( - 'chat-unsent-${send.operationId}', + if (_controller.loaded && + allRows.isEmpty && + allNotices.isEmpty && + _commandNotices.isEmpty && + _controller.error == null) + const Padding( + key: Key('chat-thread-empty'), + padding: EdgeInsets.all(16), + child: Text( + 'No messages in this chat yet.', + ), ), - padding: const EdgeInsets.symmetric( - horizontal: 16, + ...transcript, + // Messages the server holds queued (one sent before + // a reload, or from another device) follow the + // transcript: none has reached the harness yet. + for (final prompt + in _controller.queuedOutsideTranscript) + Padding( + key: ValueKey( + 'chat-queued-${prompt['operation_id']}', + ), + padding: const EdgeInsets.symmetric( + horizontal: 16, + ), + child: _queuedRow(prompt), ), - child: _unsentRow(send), - ), - // The conversation's own command lines sit after the - // turns, as on the web; they are never bubbles. - for (final notice in _commandNotices) - _ChatNoticeLine( - key: ValueKey( - 'chat-command-notice-${notice.condition}', + // Messages the server has not accepted follow the + // transcript until they are retried or edited. + for (final send in _composer.deliveries.unsent) + Padding( + key: ValueKey( + 'chat-unsent-${send.operationId}', + ), + padding: const EdgeInsets.symmetric( + horizontal: 16, + ), + child: _unsentRow(send), ), - notice: notice, - onDismiss: _dismiss, - ), - ]), + // The conversation's own command lines sit after the + // turns, as on the web; they are never bubbles. + for (final notice in _commandNotices) + _ChatNoticeLine( + key: ValueKey( + 'chat-command-notice-${notice.condition}', + ), + notice: notice, + onDismiss: _dismiss, + ), + ]), + ), ), ), + ?findBar(top: media.top + 8, end: side + 8), if (showJump) PositionedDirectional( end: side + 16, @@ -1511,10 +1543,15 @@ class _ChatThreadViewState extends State { // scrolls under fixed bars. // Two Escape presses stop a running turn while the conversation has // the keyboard; the wheel over the page still scrolls it. - final column = ChatEscapeStop( - running: _controller.running, - onStop: _stopTurn, - child: VerticalWheelForwarder(controller: _scroll, child: page), + final column = Focus( + canRequestFocus: false, + skipTraversal: true, + onKeyEvent: findKey, + child: ChatEscapeStop( + running: _controller.running, + onStop: _stopTurn, + child: VerticalWheelForwarder(controller: _scroll, child: page), + ), ); final wideFiles = _filesVisible && MediaQuery.sizeOf(context).width >= 700; diff --git a/app/lib/features/chat/domain/chat_find.dart b/app/lib/features/chat/domain/chat_find.dart new file mode 100644 index 00000000..e9054d67 --- /dev/null +++ b/app/lib/features/chat/domain/chat_find.dart @@ -0,0 +1,146 @@ +import '../../../core/api_gateway.dart'; + +/// One piece of transcript text find searches, as the transcript shows it: +/// a user turn's text (its text parts joined by line breaks, as its bubble +/// draws them) or one text part of an answer. [rowKey] is the transcript +/// row's stable key; [text] is exactly the string the row renders. +class ChatFindUnit { + const ChatFindUnit(this.rowIndex, this.rowKey, this.text, this.messageIds); + + final int rowIndex; + final String rowKey; + final String text; + + /// The stored messages the row holds. + final List messageIds; +} + +/// A match's character range in its unit's text. +typedef ChatFindRange = ({int start, int end}); + +/// One match in the loaded transcript. +class ChatFindMatch { + const ChatFindMatch(this.unit, this.start, this.end, this.ordinal); + + final ChatFindUnit unit; + final int start; + final int end; + + /// Which occurrence in [unit] this is, from its start. + final int ordinal; + + String get rowKey => unit.rowKey; + + /// Whether [other] is the same occurrence in the same text. + bool sameAs(ChatFindMatch other) => + other.rowKey == rowKey && + other.unit.text == unit.text && + other.ordinal == ordinal; +} + +/// A match the server found in a message the transcript has not loaded yet. +class ChatFindRemoteHit { + const ChatFindRemoteHit(this.messageId, this.part, this.offset); + + final String messageId; + final int part; + final int offset; + + /// The hits of a scoped chat search reply, newest message first. + static List fromReply(JsonMap reply) { + final results = reply['search_results']; + final list = results is Map ? results['results'] : null; + if (list is! List) return const []; + return [ + for (final result in list) + if (result is Map && result['chat'] is Map) + ChatFindRemoteHit( + '${(result['chat'] as Map)['message_id'] ?? ''}', + _int((result['chat'] as Map)['part']), + _int((result['chat'] as Map)['offset']), + ), + ]; + } + + static int _int(Object? value) => value is num ? value.toInt() : 0; +} + +/// The text units of transcript [rows] (keyed by [keys]), in display order. +/// Only what reads as conversation is searched: user turns and the text of +/// answers, not activity, cards or notices. +List chatFindUnits(List rows, List keys) { + final units = []; + for (var index = 0; index < rows.length && index < keys.length; index++) { + final row = rows[index]; + final kind = row['kind']; + if (kind == 'user') { + final message = row['message'] is Map ? row['message'] as Map : row; + final text = _textParts(message).join('\n'); + if (text.trim().isEmpty) continue; + final id = '${row['key'] ?? message['id'] ?? ''}'; + units.add(ChatFindUnit(index, keys[index], text, [id])); + } else if (kind == 'assistant') { + final ids = [ + for (final id in row['messageIds'] as List? ?? const []) '$id', + ]; + for (final text in _textParts(row)) { + if (text.trim().isEmpty) continue; + units.add(ChatFindUnit(index, keys[index], text, ids)); + } + } + } + return units; +} + +List _textParts(Map source) { + final parts = source['parts']; + if (parts is! List) return const []; + return [ + for (final part in parts) + if (part is Map && + (part['type'] == null || part['type'] == 'text') && + part['text'] is String) + part['text'] as String, + ]; +} + +/// The non-overlapping occurrences of [query] in [text]. +List chatFindRanges( + String text, + String query, { + required bool caseSensitive, +}) { + if (query.isEmpty || text.length < query.length) return const []; + final pattern = RegExp(RegExp.escape(query), caseSensitive: caseSensitive); + return [ + for (final match in pattern.allMatches(text)) + (start: match.start, end: match.end), + ]; +} + +/// Every match of [query] in [units], in display order (oldest first). +List chatFindMatches( + List units, + String query, { + required bool caseSensitive, + int cap = chatFindLocalCap, +}) { + final matches = []; + for (final unit in units) { + var ordinal = 0; + for (final range in chatFindRanges( + unit.text, + query, + caseSensitive: caseSensitive, + )) { + matches.add(ChatFindMatch(unit, range.start, range.end, ordinal++)); + if (matches.length >= cap) return matches; + } + } + return matches; +} + +/// How many matches find counts in the loaded transcript, and in history +/// it has not loaded, before it reports "N+". +const chatFindLocalCap = 2000; +const chatFindRemoteCap = 1000; diff --git a/app/lib/features/chat/ui/transcript/chat_find_highlight.dart b/app/lib/features/chat/ui/transcript/chat_find_highlight.dart new file mode 100644 index 00000000..d4219007 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/chat_find_highlight.dart @@ -0,0 +1,278 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/rendering.dart'; + +import '../../conversation/chat_find_controller.dart'; +import '../../shell/chat_shell_terminal_theme.dart'; + +/// The boxes, in [ancestor]'s coordinates, of a character range of a +/// rendered text; empty when it is not laid out. +typedef ChatFindRects = + List Function(int start, int end, RenderBox ancestor); + +/// Where find's matches are drawn: the open find (null while it is closed) +/// and the rendered texts and rows the transcript has built, so the current +/// match can be scrolled into view. +class ChatFindTargets { + final rows = {}; + final texts = >{}; + + ChatFindRects? textFor(String rowKey, String text) => texts[rowKey]?[text]; +} + +class ChatFindScope extends InheritedWidget { + const ChatFindScope({ + super.key, + required this.controller, + required this.targets, + required super.child, + }); + + final ChatFindController? controller; + final ChatFindTargets targets; + + static ChatFindScope? maybeOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType(); + + @override + bool updateShouldNotify(ChatFindScope oldWidget) => + controller != oldWidget.controller || targets != oldWidget.targets; +} + +/// Marks one transcript row for find: the texts in it highlight their +/// matches under [rowKey], and the row registers itself while built. +class ChatFindRow extends StatefulWidget { + const ChatFindRow({super.key, required this.rowKey, required this.child}); + + final String rowKey; + final Widget child; + + static String? keyOf(BuildContext context) => + context.dependOnInheritedWidgetOfExactType<_ChatFindRowKey>()?.rowKey; + + @override + State createState() => _ChatFindRowState(); +} + +class _ChatFindRowState extends State { + ChatFindTargets? _targets; + String? _registered; + + @override + void didChangeDependencies() { + super.didChangeDependencies(); + _register(); + } + + @override + void didUpdateWidget(ChatFindRow oldWidget) { + super.didUpdateWidget(oldWidget); + _register(); + } + + void _register() { + _unregister(); + final targets = ChatFindScope.maybeOf(context)?.targets; + if (targets == null) return; + targets.rows[widget.rowKey] = context; + _targets = targets; + _registered = widget.rowKey; + } + + void _unregister() { + final targets = _targets; + final key = _registered; + if (targets != null && key != null && targets.rows[key] == context) { + targets.rows.remove(key); + } + _targets = null; + _registered = null; + } + + @override + void dispose() { + _unregister(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => + _ChatFindRowKey(rowKey: widget.rowKey, child: widget.child); +} + +class _ChatFindRowKey extends InheritedWidget { + const _ChatFindRowKey({required this.rowKey, required super.child}); + + final String rowKey; + + @override + bool updateShouldNotify(_ChatFindRowKey oldWidget) => + rowKey != oldWidget.rowKey; +} + +/// Paints find's matches in one rendered [text], the current one stronger, +/// like the terminal's find. The text itself is never restyled, so nothing +/// shifts or rewraps as the current match moves. The translucent marks go +/// over the text, since a code block's own fill would hide them behind it. +class ChatFindHighlight extends StatefulWidget { + const ChatFindHighlight({ + super.key, + required this.text, + required this.rects, + required this.child, + }); + + final String text; + final ChatFindRects rects; + final Widget child; + + @override + State createState() => _ChatFindHighlightState(); +} + +class _ChatFindHighlightState extends State { + final _anchor = GlobalKey(); + ChatFindTargets? _targets; + (String, String)? _registered; + + @override + void dispose() { + _unregister(); + super.dispose(); + } + + void _register(ChatFindTargets? targets, String? rowKey) { + final next = rowKey == null ? null : (rowKey, widget.text); + if (identical(targets, _targets) && next == _registered) { + if (next != null) targets!.texts[next.$1]![next.$2] = widget.rects; + return; + } + _unregister(); + if (targets == null || next == null) return; + targets.texts.putIfAbsent(next.$1, () => {})[next.$2] = widget.rects; + _targets = targets; + _registered = next; + } + + void _unregister() { + final targets = _targets; + final key = _registered; + if (targets != null && key != null) { + final texts = targets.texts[key.$1]; + texts?.remove(key.$2); + if (texts != null && texts.isEmpty) targets.texts.remove(key.$1); + } + _targets = null; + _registered = null; + } + + @override + Widget build(BuildContext context) { + final scope = ChatFindScope.maybeOf(context); + final rowKey = ChatFindRow.keyOf(context); + _register(scope?.targets, rowKey); + final controller = scope?.controller; + if (controller == null || rowKey == null) { + return KeyedSubtree(key: _anchor, child: widget.child); + } + final colours = chatShellTerminalMatchColours(context); + return CustomPaint( + key: _anchor, + foregroundPainter: _ChatFindPainter( + controller: controller, + rowKey: rowKey, + text: widget.text, + rects: widget.rects, + anchor: _anchor, + hit: colours.hit, + current: colours.current, + ), + child: widget.child, + ); + } +} + +class _ChatFindPainter extends CustomPainter { + _ChatFindPainter({ + required this.controller, + required this.rowKey, + required this.text, + required this.rects, + required this.anchor, + required this.hit, + required this.current, + }) : super(repaint: controller); + + final ChatFindController controller; + final String rowKey; + final String text; + final ChatFindRects rects; + final GlobalKey anchor; + final Color hit; + final Color current; + + @override + void paint(Canvas canvas, Size size) { + final highlights = controller.highlightsFor(rowKey, text); + if (highlights.isEmpty) return; + final box = anchor.currentContext?.findRenderObject(); + if (box is! RenderBox || !box.attached) return; + for (final highlight in highlights) { + final fill = Paint()..color = highlight.current ? current : hit; + for (final rect in rects(highlight.start, highlight.end, box)) { + canvas.drawRRect( + RRect.fromRectAndRadius(rect.inflate(1), const Radius.circular(3)), + fill, + ); + } + } + } + + @override + bool shouldRepaint(_ChatFindPainter oldDelegate) => + oldDelegate.controller != controller || + oldDelegate.rowKey != rowKey || + oldDelegate.text != text || + oldDelegate.hit != hit || + oldDelegate.current != current; +} + +/// The boxes of characters [start]..[end] of the first paragraph (or +/// editable) under [context], for a text rendered verbatim. +List chatFindPlainRects( + BuildContext? context, + int start, + int end, + RenderBox ancestor, +) { + final paragraph = chatFindTextRenderer(context); + if (paragraph == null || !paragraph.attached || !paragraph.hasSize) { + return const []; + } + final selection = TextSelection(baseOffset: start, extentOffset: end); + final boxes = switch (paragraph) { + RenderParagraph() => paragraph.getBoxesForSelection(selection), + RenderEditable() => paragraph.getBoxesForSelection(selection), + _ => const [], + }; + final transform = paragraph.getTransformTo(ancestor); + return [ + for (final box in boxes) MatrixUtils.transformRect(transform, box.toRect()), + ]; +} + +/// The first [RenderParagraph] or [RenderEditable] under [context]. +RenderBox? chatFindTextRenderer(BuildContext? context) { + RenderBox? found; + void visit(RenderObject object) { + if (found != null) return; + if (object is RenderParagraph || object is RenderEditable) { + found = object as RenderBox; + } else { + object.visitChildren(visit); + } + } + + final root = context?.findRenderObject(); + if (root != null) visit(root); + return found; +} diff --git a/app/lib/features/chat/ui/transcript/chat_link_text.dart b/app/lib/features/chat/ui/transcript/chat_link_text.dart index 6a56a242..71a98c71 100644 --- a/app/lib/features/chat/ui/transcript/chat_link_text.dart +++ b/app/lib/features/chat/ui/transcript/chat_link_text.dart @@ -2,6 +2,7 @@ import 'dart:async'; import 'package:flutter/material.dart'; +import 'chat_find_highlight.dart'; import 'chat_link_launcher.dart'; import 'chat_link_spans.dart'; import 'chat_links.dart'; @@ -38,8 +39,19 @@ class _ChatLinkTextState extends State { super.dispose(); } + final _textKey = GlobalKey(); + + /// The text with find's matches painted behind it; it renders verbatim, + /// so a match's offsets are the rendered characters'. @override - Widget build(BuildContext context) { + Widget build(BuildContext context) => ChatFindHighlight( + text: widget.text, + rects: (start, end, box) => + chatFindPlainRects(_textKey.currentContext, start, end, box), + child: KeyedSubtree(key: _textKey, child: _text(context)), + ); + + Widget _text(BuildContext context) { final text = widget.text; if (_found.isEmpty) { return ChatTranscriptSelectionScope.maybeOf(context) == null diff --git a/app/lib/features/chat/ui/transcript/chat_markdown_view.dart b/app/lib/features/chat/ui/transcript/chat_markdown_view.dart index d0d51dca..387e6508 100644 --- a/app/lib/features/chat/ui/transcript/chat_markdown_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_markdown_view.dart @@ -5,6 +5,7 @@ import 'package:flutter/rendering.dart'; import 'chat_transcript_selection.dart'; import 'chat_code_hover.dart'; +import 'chat_find_highlight.dart'; import '../../../../ui/text/monospace.dart'; import 'chat_link_launcher.dart'; import 'chat_link_spans.dart'; @@ -110,7 +111,7 @@ class _ChatMarkdownViewState extends State { // The text is built once and never restyled while speaking; the // spoken word is painted behind it, so nothing shifts or rewraps. final rendered = _rendered ??= _buildRendered(context); - return CustomPaint( + final spoken = CustomPaint( key: _paintKey, painter: SpokenWordPainter( anchor: _paintKey, @@ -121,6 +122,13 @@ class _ChatMarkdownViewState extends State { ), child: rendered, ); + // Find's matches are painted the same way, behind the text. + return ChatFindHighlight( + text: widget.text, + rects: (start, end, box) => + spokenWordRects(_segments, (start: start, end: end), box), + child: spoken, + ); }, ); } @@ -252,6 +260,7 @@ class _ChatMarkdownViewState extends State { ], ); case MarkdownCode(language: final language, code: final code): + final codeKey = _codeSegment(code); _skipCodeBlock(code); final labelStyle = _roleStyle( context, @@ -267,6 +276,7 @@ class _ChatMarkdownViewState extends State { child: ChatTranscriptHorizontalScrollView( label: 'code block', child: Text.rich( + key: codeKey, TextSpan( children: _linked( context, @@ -283,6 +293,27 @@ class _ChatMarkdownViewState extends State { } } + /// Records where a code block's text renders, character for character + /// from its place in the source, so find can highlight matches in it. + GlobalKey _codeSegment(String code) { + if (_textCount == _textKeys.length) _textKeys.add(GlobalKey()); + final key = _textKeys[_textCount++]; + final start = code.isEmpty ? -1 : widget.text.indexOf(code, _sourceCursor); + if (start >= 0) { + _segments.add( + MarkdownSpokenSegment( + key, + start, + start + code.length, + 0, + code.length, + List.generate(code.length, (index) => start + index), + ), + ); + } + return key; + } + void _skipCodeBlock(String code) { _sourceCursor = fencedCodeSpan( widget.text, diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 41ec8006..9a7984a4 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -134,6 +134,13 @@ class KeyboardShortcutRegistry { caveat: 'While the slash command list is open above the composer. Esc dismisses it.', ), + KeyboardShortcutEntry( + group: KeyboardShortcutGroup.chat, + action: 'Find in chat', + keys: _apple ? 'Cmd+F' : 'Ctrl+F', + caveat: + 'Enter moves to an older match, Shift+Enter to a newer one; Esc closes and returns to the composer. Older history is searched on the server and loaded as needed. In the terminal the key goes to the terminal.', + ), KeyboardShortcutEntry( group: KeyboardShortcutGroup.chat, action: 'Toggle Files', diff --git a/app/test/features/chat/conversation/chat_find_test.dart b/app/test/features/chat/conversation/chat_find_test.dart new file mode 100644 index 00000000..82cf9422 --- /dev/null +++ b/app/test/features/chat/conversation/chat_find_test.dart @@ -0,0 +1,184 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_draft_store.dart'; +import 'package:pipelines_app/features/chat/conversation/chat_thread_view.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_find_highlight.dart'; + +import 'chat_thread_fixtures.dart'; + +JsonMap _text(String text) => {'type': 'text', 'text': text}; + +/// Answers scoped searches with [searchHits] for history older than the +/// loaded page. +class _FindGateway extends FakeChatGateway { + final searches = []; + List searchHits = const []; + + @override + Future call(String type, [JsonMap fields = const {}]) async { + if (type == 'search') { + searches.add(Map.from(fields['search'] as Map)); + return { + 'type': 'search_results', + 'search_results': {'results': searchHits}, + }; + } + return super.call(type, fields); + } +} + +final _newest = [ + for (var i = 0; i < 30; i++) + chatMessage( + 'n$i', + i.isEven ? 'user' : 'assistant', + parts: [ + _text(i == 2 || i == 27 ? 'Needle at $i, and needle' : 'filler $i'), + ], + ), +]; + +final _older = [ + chatMessage('o1', 'user', parts: [_text('an old needle')]), + chatMessage('o2', 'assistant', parts: [_text('nothing')]), +]; + +Future<_FindGateway> _host(WidgetTester tester, {bool older = false}) async { + tester.view.physicalSize = const Size(1000, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.reset); + final gateway = _FindGateway() + ..history = (fields) async { + final query = fields['chat_query'] as Map; + if (query['cursor'] == 'c1') return chatPage(_older); + return chatPage(_newest, cursor: older ? 'c1' : '', hasMore: older); + }; + addTearDown(gateway.close); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: ChatThreadView( + gateway: gateway, + sessionId: 's', + onBack: () {}, + drafts: MemoryChatDraftStore(), + newOperationId: () => 'op', + ), + ), + ), + ); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 100)); + await tester.pump(); + return gateway; +} + +Future _ctrlF(WidgetTester tester) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyF); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + await tester.pump(); +} + +String _count(WidgetTester tester) => + tester.widget(find.byKey(const ValueKey('chat-find-count'))).data!; + +void main() { + testWidgets('Ctrl+F finds in the chat, steps older with Enter and Esc ' + 'returns to the composer', (tester) async { + await _host(tester); + await tester.tap(find.byType(EditableText).last); + await tester.pump(); + await _ctrlF(tester); + expect(find.byKey(const ValueKey('chat-find-field')), findsOneWidget); + + await tester.enterText( + find.byKey(const ValueKey('chat-find-field')), + 'needle', + ); + await tester.pumpAndSettle(); + expect(_count(tester), '1 of 4'); + // Each built text with a match registers where it draws. + final scope = tester.widget(find.byType(ChatFindScope)); + expect(scope.controller, isNotNull); + expect(scope.targets.texts, isNotEmpty); + + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(_count(tester), '2 of 4'); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(_count(tester), '3 of 4'); + // The match in message n2 is near the top of history: it is built now. + expect( + find.textContaining('Needle at 2', findRichText: true), + findsWidgets, + ); + + await tester.sendKeyDownEvent(LogicalKeyboardKey.shiftLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.sendKeyUpEvent(LogicalKeyboardKey.shiftLeft); + await tester.pumpAndSettle(); + expect(_count(tester), '2 of 4'); + + await tester.tap(find.byKey(const ValueKey('chat-find-case'))); + await tester.pumpAndSettle(); + expect(_count(tester), '1 of 2'); + + await tester.sendKeyEvent(LogicalKeyboardKey.escape); + await tester.pumpAndSettle(); + expect(find.byKey(const ValueKey('chat-find-field')), findsNothing); + }); + + testWidgets('matches in unloaded history are counted from the server and ' + 'reached by loading older pages', (tester) async { + final gateway = await _host(tester, older: true); + gateway.searchHits = [ + { + 'chat': {'message_id': 'o1', 'part': 0, 'offset': 7}, + }, + ]; + await tester.tap(find.byType(EditableText).last); + await tester.pump(); + await _ctrlF(tester); + await tester.enterText( + find.byKey(const ValueKey('chat-find-field')), + 'needle', + ); + await tester.pump(const Duration(milliseconds: 300)); + await tester.pumpAndSettle(); + expect(gateway.searches.single['scope'], 'chat:s'); + expect(gateway.searches.single['cursor'], '0|c1'); + expect(_count(tester), '1 of 5'); + + // Step to the oldest: it is only on the server, so the older page loads. + for (var i = 0; i < 4; i++) { + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + } + expect(_count(tester), '5 of 5'); + expect( + gateway.calls.where( + (call) => + call.type == 'chat_messages' && + (call.fields['chat_query'] as Map)['cursor'] == 'c1', + ), + isNotEmpty, + ); + expect( + find.textContaining('an old needle', findRichText: true), + findsWidgets, + ); + }); + + testWidgets('Ctrl+F with no focus in the chat opens nothing', (tester) async { + await _host(tester); + expect(find.byKey(const ValueKey('chat-find-field')), findsNothing); + // No focus in the chat at all: the pane's handler never sees the key. + await _ctrlF(tester); + expect(find.byKey(const ValueKey('chat-find-field')), findsNothing); + }); +} diff --git a/app/test/features/chat/domain/chat_find_test.dart b/app/test/features/chat/domain/chat_find_test.dart new file mode 100644 index 00000000..89a242bf --- /dev/null +++ b/app/test/features/chat/domain/chat_find_test.dart @@ -0,0 +1,78 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/domain/chat_find.dart'; + +void main() { + final rows = [ + { + 'kind': 'user', + 'key': 'u1', + 'message': { + 'id': 'u1', + 'parts': [ + {'type': 'text', 'text': 'Find the Needle'}, + {'type': 'text', 'text': 'and another needle'}, + ], + }, + }, + {'kind': 'activity', 'key': 'x', 'label': 'needle in activity'}, + { + 'kind': 'assistant', + 'key': 'a1', + 'messageIds': ['a1', 'a2'], + 'parts': [ + {'type': 'reasoning', 'text': 'needle thoughts'}, + {'type': 'text', 'text': 'A **needle** here, needle there'}, + {'type': 'text', 'text': ' '}, + ], + }, + ]; + + test('units are user turns and answer text parts as rendered', () { + final units = chatFindUnits(rows, ['k0', 'k1', 'k2']); + expect(units.map((u) => u.text), [ + 'Find the Needle\nand another needle', + 'A **needle** here, needle there', + ]); + expect(units.map((u) => u.rowKey), ['k0', 'k2']); + expect(units.first.messageIds, ['u1']); + expect(units.last.messageIds, ['a1', 'a2']); + }); + + test('matches fold case unless asked, in display order', () { + final units = chatFindUnits(rows, ['k0', 'k1', 'k2']); + final folded = chatFindMatches(units, 'needle', caseSensitive: false); + expect(folded.length, 4); + expect(folded.first.start, 'Find the '.length); + expect(folded.map((m) => m.ordinal), [0, 1, 0, 1]); + final exact = chatFindMatches(units, 'Needle', caseSensitive: true); + expect(exact.length, 1); + }); + + test('regex characters in the query are literal', () { + expect(chatFindRanges('a.b axb (c)', '.', caseSensitive: false), [ + (start: 1, end: 2), + ]); + expect(chatFindRanges('a.b axb (c)', '(c)', caseSensitive: false), [ + (start: 8, end: 11), + ]); + }); + + test('server hits parse from a scoped reply', () { + final hits = ChatFindRemoteHit.fromReply({ + 'search_results': { + 'results': [ + { + 'chat': {'message_id': 'm9', 'part': 1, 'offset': 4}, + }, + { + 'chat': {'message_id': 'm8'}, + }, + ], + }, + }); + expect(hits.map((h) => (h.messageId, h.part, h.offset)), [ + ('m9', 1, 4), + ('m8', 0, 0), + ]); + }); +} diff --git a/app/tool/perf/chat_scroll_fixture.dart b/app/tool/perf/chat_scroll_fixture.dart index 955b4473..1df0ea92 100644 --- a/app/tool/perf/chat_scroll_fixture.dart +++ b/app/tool/perf/chat_scroll_fixture.dart @@ -310,3 +310,42 @@ void chatScrollStream(String sessionId, void Function(JsonMap frame) emit) { }); }); } + +/// A scoped find-in-chat search (`scope: chat:`) the way +/// `internal/server/search_chat_scoped.go` answers it: every occurrence in +/// the text parts of the history before [cursor] ("0|older" for the page +/// `?older=1` holds back), newest message first. +List chatScrollScopedHits( + String sessionId, + String cursor, + String query, + bool caseSensitive, +) { + if (!_older || !cursor.endsWith('|older') || query.trim().isEmpty) { + return const []; + } + final pattern = RegExp(RegExp.escape(query), caseSensitive: caseSensitive); + final hits = []; + for (var i = -1; i >= -20; i--) { + final message = _message(sessionId, i); + final parts = message['parts'] as List; + for (var part = 0; part < parts.length; part++) { + final body = parts[part] as Map; + if (body['type'] != 'text') continue; + for (final match in pattern.allMatches('${body['text']}')) { + hits.add({ + 'kind': 'chat', + 'target': 'chat:$sessionId', + 'chat': { + 'session_id': sessionId, + 'message_id': message['id'], + 'part': part, + 'offset': match.start, + 'length': match.end - match.start, + }, + }); + } + } + } + return hits; +} diff --git a/app/tool/search_selection_probe_entry.dart b/app/tool/search_selection_probe_entry.dart index d49313b0..0b3add4b 100644 --- a/app/tool/search_selection_probe_entry.dart +++ b/app/tool/search_selection_probe_entry.dart @@ -709,6 +709,25 @@ JsonMap? probeReply(JsonMap request) { // The app must send exactly the browser's SearchRequest body; anything // else is answered with a visible refusal so the capture cannot pass. final search = request['search']; + if (search is Map && search['scope'] is String) { + // Find in chat: every occurrence in history not loaded yet. + final session = '${search['scope']}'.replaceFirst('chat:', ''); + return { + 'id': id, + 'type': 'search_results', + 'search_results': { + 'query': search['query'], + 'kind': 'chat', + 'results': chatScrollScopedHits( + session, + '${search['cursor'] ?? ''}', + '${search['query'] ?? ''}', + search['case_sensitive'] == true, + ), + 'cap': 200, + }, + }; + } if (search is! Map || search.length != 3 || search['query'] is! String || diff --git a/internal/server/search_chat_scoped.go b/internal/server/search_chat_scoped.go index 8ed0e7a8..7e4973db 100644 --- a/internal/server/search_chat_scoped.go +++ b/internal/server/search_chat_scoped.go @@ -78,8 +78,10 @@ func searchChatScoped(ctx context.Context, req protocol.SearchRequest, broker ch Cap: chatSearchLimit(req.Limit), ScanBoundBytes: protocol.SearchMaxScanBytes, } - query := []rune(strings.TrimSpace(req.Query)) - if len(query) == 0 { + // Find matches the query as typed, spaces included, like the client's + // own matching of the loaded transcript. + query := []rune(req.Query) + if strings.TrimSpace(req.Query) == "" { return response, nil } ctx, cancel := context.WithTimeout(ctx, scopedChatBudget) From c7e0b8b84e93ab9570d308fac0f5359ea2bea37f Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:41:48 +0000 Subject: [PATCH 11/19] Chat tests: accept text deltas joined in a subscriber's queue Co-Authored-By: Claude Opus 5.5 --- internal/server/chat_multiclient_test.go | 3 ++- internal/server/chat_test.go | 11 +++++++---- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/internal/server/chat_multiclient_test.go b/internal/server/chat_multiclient_test.go index 53890952..3bf6fd6b 100644 --- a/internal/server/chat_multiclient_test.go +++ b/internal/server/chat_multiclient_test.go @@ -313,8 +313,9 @@ func TestChatFanoutToSeveralClients(t *testing.T) { name string conn *websocket.Conn }{{"phone", phone}, {"tablet", tablet}} { + // Deltas still queued for a client may arrive joined into one frame. var text strings.Builder - for i := 0; i < 2; i++ { + for i := 0; text.Len() < len("hello"); i++ { frame := nextEvent(t, ctx, client.conn) if frame.Kind != protocol.ChatEventText { t.Fatalf("%s frame %d = %+v, want text", client.name, i, frame) diff --git a/internal/server/chat_test.go b/internal/server/chat_test.go index 5b6513c4..3a03d262 100644 --- a/internal/server/chat_test.go +++ b/internal/server/chat_test.go @@ -549,10 +549,12 @@ func TestChatPromptStreamsEvents(t *testing.T) { t.Fatalf("ack = %+v", ack) } frames := readChatTurn(t, ctx, conn) - if len(frames) != 4 { - t.Fatalf("got %d frames, want 4", len(frames)) + // The two text deltas may arrive joined into one frame. + if len(frames) != 4 && len(frames) != 3 { + t.Fatalf("got %d frames, want 4 (or 3 with the deltas joined)", len(frames)) } sawText, sawStep := false, false + var text strings.Builder for _, frame := range frames { if frame.SessionID != "ses_1" || frame.MessageID != "msg_1" { t.Fatalf("frame missing stable ids: %+v", frame) @@ -560,6 +562,7 @@ func TestChatPromptStreamsEvents(t *testing.T) { switch frame.Kind { case protocol.ChatEventText: sawText = true + text.WriteString(frame.Delta) case protocol.ChatEventStep: sawStep = true if frame.Step == nil || frame.Step.Status != protocol.ChatStepEnded { @@ -567,8 +570,8 @@ func TestChatPromptStreamsEvents(t *testing.T) { } } } - if !sawText || !sawStep { - t.Fatalf("missing text or step frame: %+v", frames) + if !sawText || !sawStep || text.String() != "hello world" { + t.Fatalf("missing text or step frame (text %q): %+v", text.String(), frames) } if prompts, _, _ := broker.counts(); prompts != 1 { t.Fatalf("prompt forwarded %d times, want 1", prompts) From 2ea7eb9db06cd4cb34fa9d167fb2dccb7b1c9028 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:42:25 +0000 Subject: [PATCH 12/19] Runner: no I/O under the runner lock; retry run settlement - Run worktree creation happens outside r.mu; the source tree is protected from storage maintenance meanwhile and the reservation is re-checked under the lock before the run is recorded (a refused tree is discarded). - getRun/listRuns read the store without r.mu; listRuns finds failed runs with an active cleanup agent in one query (partial index) instead of a detail read per failed run. - finishRunState writes the deliverable and walks the run size without the lock; FinishRun retries transient failures with backoff (a refused transition is final). - Launch teardown retries a failed read with backoff instead of keeping the reservation forever; a kept run that cannot be read at reattach is retried and then marked interrupted (stopping its adopted session first). Co-Authored-By: Claude Opus 5.5 --- internal/pipeline/runs_mutate.go | 7 +- internal/pipeline/runs_schema.go | 1 + internal/pipeline/runs_sessions.go | 19 ++ internal/server/run_reattach.go | 62 ++++- internal/server/runner.go | 271 +++++++++++++++----- internal/server/runner_reliability_test.go | 274 +++++++++++++++++++++ internal/server/storage_cleanup.go | 3 + 7 files changed, 567 insertions(+), 70 deletions(-) create mode 100644 internal/server/runner_reliability_test.go diff --git a/internal/pipeline/runs_mutate.go b/internal/pipeline/runs_mutate.go index cefe4e2d..e1ad0efb 100644 --- a/internal/pipeline/runs_mutate.go +++ b/internal/pipeline/runs_mutate.go @@ -4,6 +4,7 @@ import ( "context" "database/sql" "encoding/json" + "errors" "fmt" "strings" @@ -20,6 +21,10 @@ func (s *Store) SaveNotifications(ctx context.Context, id int64, sequence int, r return err } +// ErrInvalidRunTransition reports a conditional run update that matched no row: +// the run is not in a state the transition applies to. Retrying cannot help. +var ErrInvalidRunTransition = errors.New("invalid run state transition") + func affected(result sql.Result, err error) error { if err != nil { return err @@ -29,7 +34,7 @@ func affected(result sql.Result, err error) error { return err } if n != 1 { - return fmt.Errorf("invalid run state transition") + return ErrInvalidRunTransition } return nil } diff --git a/internal/pipeline/runs_schema.go b/internal/pipeline/runs_schema.go index 900ad830..9766bc96 100644 --- a/internal/pipeline/runs_schema.go +++ b/internal/pipeline/runs_schema.go @@ -26,6 +26,7 @@ session_id TEXT NOT NULL DEFAULT '', agent_active INTEGER NOT NULL DEFAULT 0, tr started_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP, finished_at TEXT, PRIMARY KEY(run_id,sequence)); CREATE INDEX IF NOT EXISTS run_latest ON pipeline_runs(id DESC); CREATE INDEX IF NOT EXISTS run_steps_session ON run_steps(session_id); +CREATE INDEX IF NOT EXISTS run_steps_agent_active ON run_steps(run_id) WHERE agent_active<>0; CREATE TABLE IF NOT EXISTS step_notifications ( run_id INTEGER NOT NULL, sequence INTEGER NOT NULL, receipts_json TEXT NOT NULL, PRIMARY KEY(run_id,sequence), FOREIGN KEY(run_id,sequence) REFERENCES run_steps(run_id,sequence)); diff --git a/internal/pipeline/runs_sessions.go b/internal/pipeline/runs_sessions.go index f566416f..5b83b96f 100644 --- a/internal/pipeline/runs_sessions.go +++ b/internal/pipeline/runs_sessions.go @@ -143,3 +143,22 @@ func (s *Store) ActiveAgentSessionsForRun(ctx context.Context, runID int64) ([]s } return ids, rows.Err() } + +// RunsWithActiveAgents reports every run with a step whose agent is still +// active, in one query. +func (s *Store) RunsWithActiveAgents(ctx context.Context) (map[int64]bool, error) { + rows, err := s.db.QueryContext(ctx, "SELECT DISTINCT run_id FROM run_steps WHERE agent_active<>0") + if err != nil { + return nil, err + } + defer rows.Close() + runs := map[int64]bool{} + for rows.Next() { + var id int64 + if err := rows.Scan(&id); err != nil { + return nil, err + } + runs[id] = true + } + return runs, rows.Err() +} diff --git a/internal/server/run_reattach.go b/internal/server/run_reattach.go index f58832f0..33781068 100644 --- a/internal/server/run_reattach.go +++ b/internal/server/run_reattach.go @@ -172,9 +172,10 @@ func (r *runner) reattachRun(plan reattachPlan) { log.Printf("run %d: restart stage %s after server restart: %v", id, plan.step.Stage, err) } } - detail, err := r.store.GetRun(ctx, id) + detail, err := r.readForReattach(ctx, id) if err != nil { - log.Printf("run %d: read for reattach: %v", id, err) + log.Printf("run %d: read for reattach: %v; marking it interrupted", id, err) + r.abandonReattach(plan, err) return } r.rememberRunIdentity(id, identityOfRunSummary(detail.RunSummary)) @@ -199,6 +200,63 @@ func (r *runner) reattachRun(plan reattachPlan) { } } +// reattachReadBackoff bounds the retries of a reattach read; reattach runs +// before requests are served, so it stays short. +var reattachReadBackoff = []time.Duration{100 * time.Millisecond, 500 * time.Millisecond, 2 * time.Second} + +// readForReattach reads a kept run, retrying a transient failure. +func (r *runner) readForReattach(ctx context.Context, id int64) (*protocol.RunDetail, error) { + for attempt := 0; ; attempt++ { + detail, err := runSettleRead(r, ctx, id) + if err == nil && detail != nil { + return detail, nil + } + if err == nil { + err = fmt.Errorf("run %d not found", id) + } + if attempt >= len(reattachReadBackoff) || ctx.Err() != nil { + return nil, err + } + if !r.sleepSettle(reattachReadBackoff[attempt]) { + return nil, err + } + } +} + +// abandonReattach settles a kept run that cannot be continued, instead of +// leaving it "running" with nothing executing it: an adopted session is +// stopped first, then the run is marked interrupted. If the session cannot be +// stopped, the run keeps its workspace reserved as cleanup-unconfirmed, as +// start-up recovery does. +func (r *runner) abandonReattach(plan reattachPlan, cause error) { + id := plan.runID + if plan.kind == reattachAdopt { + stop, cancel := context.WithTimeout(r.ctx, 20*time.Second) + err := interruptRecoveredSession(stop, plan.owner) + if err == nil { + err = r.store.ConfirmRecoveredSession(stop, plan.owner) + } + cancel() + if err != nil { + log.Printf("run %d: stop session %s after a failed reattach: %v; workspace stays reserved", id, plan.owner.ID, err) + mark, done := context.WithTimeout(context.Background(), 10*time.Second) + if markErr := r.store.MarkCleanupUnconfirmed(mark, id); markErr != nil { + log.Printf("run %d: mark cleanup unconfirmed: %v", id, markErr) + } + done() + r.mu.Lock() + if _, ok := r.active[id]; !ok { + r.active[id] = activeRun{cancel: func() {}, workspace: plan.owner.Directory} + } + r.mu.Unlock() + return + } + } + r.finishRunWithRetry(id, "interrupted", "", "Server restarted; the run could not be reattached: "+cause.Error(), stage.Values{}) + r.forgetAttention(id) + r.forgetNotifyMode(id) +} + // rebuildAdoptState restores the loop state at the planned visit: memory and // visit counts from every other persisted step, the handoff input from the // visit before it, and (for an adopted visit) the session to re-adopt. diff --git a/internal/server/runner.go b/internal/server/runner.go index 9626cecb..522e1bc0 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -41,6 +41,9 @@ type runner struct { artifactsRoot string mu sync.Mutex active map[int64]activeRun + // admitting counts admissions creating a run worktree from each source + // workspace outside r.mu; storage maintenance keeps those trees. + admitting map[string]int execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error) // dirEnv resolves the run workspace's own environment (direnv/mise) at // run start; nil uses workenv.Default. @@ -178,7 +181,7 @@ func newRunnerReattaching(ctx context.Context, s *pipeline.Store, artifactsRoot active[row.ID] = activeRun{cancel: func() {}, workspace: row.Workspace} } } - r := &runner{ctx: ctx, store: s, artifactsRoot: root, active: active, idents: map[int64]runIdentity{}, attentionSent: map[int64]map[string]bool{}, notifyModes: map[int64]string{}, exportSession: stage.ExportSession, detach: detach, reattach: plans} + r := &runner{ctx: ctx, store: s, artifactsRoot: root, active: active, admitting: map[string]int{}, idents: map[int64]runIdentity{}, attentionSent: map[int64]map[string]bool{}, notifyModes: map[int64]string{}, exportSession: stage.ExportSession, detach: detach, reattach: plans} if err := r.startSessionExportJobs(); err != nil { return nil, err } @@ -329,38 +332,57 @@ func (r *runner) startWithSchedule(request protocol.Message, origin *pipeline.Sc } r.mu.Lock() - defer r.mu.Unlock() // Another run may have reserved this workspace while the title was // generated, so re-check before reserving it; a race on the request key is // handled by the store's idempotent insert. - if existing == 0 { - if err := r.checkWorkspaceFree(workspace); err != nil { - return nil, err - } - } - // Storage maintenance may have removed a clean inactive tree while an - // admission was generating its title. Refuse that vanished workspace under - // the same lock used by removal instead of launching into a missing tree. - if info, err := os.Stat(workspace); err != nil || !info.IsDir() { - return nil, fmt.Errorf("run workspace is no longer available: %s", workspace) + if err := r.checkAdmissionWorkspace(workspace, existing); err != nil { + r.mu.Unlock() + return nil, err } // A fresh run started from a repository's main checkout gets its own // worktree and branch, so runs never share a tree with each other or with - // the operator's uncommitted work. A retry keeps its run's tree. + // the operator's uncommitted work. A retry keeps its run's tree. Creating + // the worktree can take up to a minute, so it runs without r.mu (listings, + // details and cancellation must not stall behind it); storage maintenance + // keeps the source tree meanwhile (r.admitting), and the reservation is + // re-checked under the lock before the run is recorded. isolated := "" if existing == 0 && request.RetrySource == 0 { + source := workspace + if r.admitting == nil { + r.admitting = map[string]int{} + } + r.admitting[source]++ + r.mu.Unlock() isolateCtx, isolateCancel := context.WithTimeout(r.ctx, time.Minute) - tree, isolateErr := isolateRunWorkspace(isolateCtx, workspace, runTitle.Text) + tree, isolateErr := isolateRunWorkspace(isolateCtx, source, runTitle.Text) isolateCancel() + r.mu.Lock() + if r.admitting[source]--; r.admitting[source] <= 0 { + delete(r.admitting, source) + } if isolateErr != nil { + r.mu.Unlock() return nil, isolateErr } - if tree != workspace { + if tree != source { isolated = tree } workspace = tree request.Input["pwd"] = workspace + recheck := r.ctx.Err() + if recheck == nil { + recheck = r.checkAdmissionWorkspace(workspace, existing) + } + if recheck != nil { + r.mu.Unlock() + if isolated != "" { + discardRunWorktree(isolated) + } + return nil, recheck + } } + defer r.mu.Unlock() id, created, err := r.store.CreateRunTitled(r.ctx, d, request.RequestKey, workspace, request.AllowTools, request.WritePaths, request.Input, pipeline.RunOverrides{Schedule: origin, Model: request.Model, StageModels: request.StageModels, NotifyMode: request.NotifyMode, OutputFormat: request.OutputFormat, StageSkills: stageSkills}, runTitle, retryOf...) if isolated != "" && (err != nil || !created) { // The run was refused or an identical request won the race: the fresh @@ -431,42 +453,100 @@ func (r *runner) launch(id int64, workspace string, fn func(context.Context)) { go func() { defer r.wg.Done() defer cancel() - defer func() { - r.mu.Lock() - defer r.mu.Unlock() - if entry, ok := r.active[id]; !ok || entry.generation != generation { - return // A parked launch must not remove the resumed reservation. - } - check, done := context.WithTimeout(context.Background(), 10*time.Second) - defer done() - detail, err := r.store.GetRun(check, id) - if err != nil || detail.CleanupUnconfirmed { - return // Fail closed: execution/cleanup has not settled durably. - } - if detail.Status == protocol.RunStatusWaiting && detail.CancelRequested { - if err := r.store.CancelWaiting(check, id); err != nil { - return - } - r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true) - } - if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting { - delete(r.active, id) - } - // A landed (or change-free) successful run's own worktree is no - // longer needed; anything unlanded or uncommitted is kept. - if detail.Status == "succeeded" && detail.FinishedAt != "" { - workspace := detail.Workspace - go func() { - if removeLandedRunWorktree(workspace) { - log.Printf("run %d: removed its landed worktree %s", id, workspace) - } - }() - } - }() + defer r.settleLaunch(id, generation) fn(ctx) }() } +// settleLaunch releases a finished launch's reservation once its run has +// settled durably. A failed read is retried with backoff (the lock is not held +// while waiting); a run whose cleanup is unconfirmed, or that cannot be read +// even after the retries, keeps its reservation (fail closed). +func (r *runner) settleLaunch(id int64, generation *byte) { + for attempt := 0; ; attempt++ { + settled, err := r.settleLaunchOnce(id, generation) + if settled { + return + } + if attempt >= len(runSettleBackoff) { + log.Printf("run %d: launch teardown could not read the run; its workspace stays reserved: %v", id, err) + return + } + if !r.sleepSettle(runSettleBackoff[attempt]) { + return + } + } +} + +// settleLaunchOnce is one teardown attempt under r.mu. It reports false only +// when the run could not be read. +func (r *runner) settleLaunchOnce(id int64, generation *byte) (bool, error) { + r.mu.Lock() + defer r.mu.Unlock() + if entry, ok := r.active[id]; !ok || entry.generation != generation { + return true, nil // A parked launch must not remove the resumed reservation. + } + check, done := context.WithTimeout(context.Background(), 10*time.Second) + defer done() + detail, err := runSettleRead(r, check, id) + if err != nil || detail == nil { + return false, err + } + if detail.CleanupUnconfirmed { + return true, nil // Fail closed: execution/cleanup has not settled durably. + } + if detail.Status == protocol.RunStatusWaiting && detail.CancelRequested { + if err := r.store.CancelWaiting(check, id); err != nil { + // A refused transition fails closed; anything else is retried. + return errors.Is(err, pipeline.ErrInvalidRunTransition), err + } + r.emitRun(protocol.RunEventFrame{RunID: id, Workspace: detail.Workspace, Status: protocol.RunStatusCanceled, CancelRequested: true, CurrentStage: detail.CurrentStage, FinishedAt: time.Now().UTC().Format(time.RFC3339)}, true) + } + if detail.FinishedAt != "" || detail.Status == protocol.RunStatusWaiting { + delete(r.active, id) + } + // A landed (or change-free) successful run's own worktree is no longer + // needed; anything unlanded or uncommitted is kept. + if detail.Status == "succeeded" && detail.FinishedAt != "" { + workspace := detail.Workspace + go func() { + if removeLandedRunWorktree(workspace) { + log.Printf("run %d: removed its landed worktree %s", id, workspace) + } + }() + } + return true, nil +} + +// runFinishWrite persists a run's terminal state; tests replace it to inject +// transient store failures. +var runFinishWrite = func(r *runner, ctx context.Context, id int64, status, outcome, diagnostic string, input stage.Values) error { + return r.store.FinishRun(ctx, id, status, outcome, diagnostic, input) +} + +// runSettleRead reads a run for settlement; tests replace it to inject +// transient store failures. +var runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.RunDetail, error) { + return r.store.GetRun(ctx, id) +} + +// checkAdmissionWorkspace refuses admitting a fresh run (existing == 0) into a +// workspace another run reserves, and any admission into a vanished workspace: +// storage maintenance may have removed a clean inactive tree while an +// admission was generating its title, so it is checked under the same lock +// removal takes. Callers must hold r.mu. +func (r *runner) checkAdmissionWorkspace(workspace string, existing int64) error { + if existing == 0 { + if err := r.checkWorkspaceFree(workspace); err != nil { + return err + } + } + if info, err := os.Stat(workspace); err != nil || !info.IsDir() { + return fmt.Errorf("run workspace is no longer available: %s", workspace) + } + return nil +} + // checkWorkspaceFree refuses a run when an active or cleanup-unconfirmed run // reserves an overlapping resolved workspace. Callers must hold r.mu. func (r *runner) checkWorkspaceFree(workspace string) error { @@ -530,12 +610,15 @@ func repositoryRoot(dir string) string { } } +// getRun reads one run's detail. The store read runs without r.mu, so a +// detail never waits behind admission or settlement work; only the executing +// overlay reads the active set under the lock. func (r *runner) getRun(id int64) (*protocol.RunDetail, error) { - r.mu.Lock() - defer r.mu.Unlock() d, err := r.store.GetRun(r.ctx, id) if d != nil { + r.mu.Lock() _, d.Executing = r.active[id] + r.mu.Unlock() if d.ExportPendingSequence > 0 { d.Executing = false } @@ -579,28 +662,38 @@ func (r *runner) overlayEffectiveModels(d *protocol.RunDetail) { } } +// listRuns lists every run with its executing overlay. The store reads run +// without r.mu (a listing never waits behind admission or settlement), and a +// failed run whose cleanup agent is still active is found with one query +// rather than a detail read per failed run. func (r *runner) listRuns() ([]protocol.RunSummary, error) { - r.mu.Lock() - defer r.mu.Unlock() items, err := r.store.ListRuns(r.ctx) + if err != nil { + return items, err + } + var agents map[int64]bool + for _, item := range items { + if item.Status == "failed" { + if agents, err = r.store.RunsWithActiveAgents(r.ctx); err != nil { + return nil, err + } + break + } + } + r.mu.Lock() for i := range items { _, items[i].Executing = r.active[items[i].ID] + } + r.mu.Unlock() + for i := range items { if items[i].ExportPendingSequence > 0 { items[i].Executing = false } - if items[i].Status == "failed" && !items[i].Executing { - d, err := r.store.GetRun(r.ctx, items[i].ID) - if err != nil { - return nil, err - } - for _, step := range d.Steps { - if step.AgentActive { - items[i].Executing = true - } - } + if items[i].Status == "failed" && !items[i].Executing && agents[items[i].ID] { + items[i].Executing = true } } - return items, err + return items, nil } type retryCheckpoint struct { @@ -1503,23 +1596,26 @@ func (r *runner) emitRun(frame protocol.RunEventFrame, terminal bool) { } func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diagnostic string, completed, sequence int, currentStage string, input stage.Values) { - r.mu.Lock() + // The deliverable and the size walk touch files only: they run without r.mu, + // so listings and details do not stall behind a large run finishing. The + // run stays in r.active (its workspace reserved) until the launch teardown. c, cancel := context.WithTimeout(context.Background(), 10*time.Second) - defer cancel() if status == "succeeded" { if err := r.finalizeDeliverable(c, id, sequence, input); err != nil { status, outcome, diagnostic = "failed", "error", "deliverable contract: "+err.Error() } } + cancel() // Measure the run's footprint while it is still recorded as active: its // files are final, and measuring after the terminal status is written would // widen the window in which a client sees the run finished but still owned. // The status write re-marks the cache stale, so the background sizer then // records the exact value including the final output row. size := r.finishedSize(id) - if err := r.store.FinishRun(c, id, status, outcome, diagnostic, input); err != nil { - log.Printf("finish run %d: %v", id, err) - } + r.finishRunWithRetry(id, status, outcome, diagnostic, input) + r.mu.Lock() + c, cancel = context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() // The store atomically makes a stop request win over a late success. detail, getErr := r.store.GetRun(c, id) if getErr != nil || detail == nil { @@ -1555,6 +1651,47 @@ func (r *runner) finishRunState(id int64, name, workspace, status, outcome, diag r.forgetNotifyMode(id) } +// runSettleBackoff is the retry schedule for durable run settlement writes +// (finishing a run, reading it back at launch teardown). A transient store +// failure (a busy or briefly unavailable database) must not leave a run +// "running" with its workspace reserved until restart. +var runSettleBackoff = []time.Duration{250 * time.Millisecond, 500 * time.Millisecond, time.Second, 2 * time.Second, 4 * time.Second, 8 * time.Second, 15 * time.Second} + +// sleepSettle waits out one backoff step; false when the server is stopping. +func (r *runner) sleepSettle(delay time.Duration) bool { + select { + case <-r.ctx.Done(): + return false + case <-time.After(delay): + return true + } +} + +// finishRunWithRetry persists a run's terminal state, retrying a transient +// failure with backoff (each attempt under r.mu, the waits without it). A +// refused transition (an agent still active, cleanup unconfirmed, a run +// already settled) is final and not retried. +func (r *runner) finishRunWithRetry(id int64, status, outcome, diagnostic string, input stage.Values) { + for attempt := 0; ; attempt++ { + r.mu.Lock() + c, cancel := context.WithTimeout(context.Background(), 10*time.Second) + err := runFinishWrite(r, c, id, status, outcome, diagnostic, input) + cancel() + r.mu.Unlock() + if err == nil { + return + } + if errors.Is(err, pipeline.ErrInvalidRunTransition) || attempt >= len(runSettleBackoff) { + log.Printf("finish run %d: %v", id, err) + return + } + log.Printf("finish run %d (attempt %d, retrying): %v", id, attempt+1, err) + if !r.sleepSettle(runSettleBackoff[attempt]) { + return + } + } +} + // completedSteps counts the completed steps of a run detail; resume uses it to // seed the terminal delta without another store read. func completedSteps(steps []protocol.RunStep) int { diff --git a/internal/server/runner_reliability_test.go b/internal/server/runner_reliability_test.go new file mode 100644 index 00000000..4519d69f --- /dev/null +++ b/internal/server/runner_reliability_test.go @@ -0,0 +1,274 @@ +package server + +import ( + "context" + "database/sql" + "errors" + "os" + "os/exec" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "time" + + "git.a-wan.net/alan/pipelines/internal/pipeline" + "git.a-wan.net/alan/pipelines/internal/protocol" + "git.a-wan.net/alan/pipelines/internal/stage" +) + +func fastRunSettle(t *testing.T) { + t.Helper() + settle, reattach := runSettleBackoff, reattachReadBackoff + runSettleBackoff = []time.Duration{time.Millisecond, time.Millisecond, time.Millisecond} + reattachReadBackoff = []time.Duration{time.Millisecond, time.Millisecond} + t.Cleanup(func() { runSettleBackoff, reattachReadBackoff = settle, reattach }) +} + +func reliabilityRunner(t *testing.T) (context.Context, *pipeline.Store, *runner, int64) { + t.Helper() + ctx, cancel := context.WithCancel(context.Background()) + s, err := pipeline.Open(filepath.Join(t.TempDir(), "reliability.db")) + if err != nil { + t.Fatal(err) + } + if _, err := s.Submit(ctx, "workflow", pipeline.Template([]string{"one"}, true)); err != nil { + t.Fatal(err) + } + items, _ := s.List(ctx) + r, err := newRunner(ctx, s) + if err != nil { + t.Fatal(err) + } + r.execute = func(context.Context, stage.Definition, stage.Values) (stage.Result, error) { + return stage.Result{Outcome: "success", Output: stage.Values{"markdown": "# Done"}}, nil + } + t.Cleanup(func() { cancel(); r.wg.Wait(); r.schedulerWG.Wait(); s.Close() }) + return ctx, s, r, items[0].ID +} + +// A transient failure persisting a run's end is retried: the run settles and +// its workspace is released instead of staying "running" and reserved. +func TestFinishRunTransientFailureIsRetried(t *testing.T) { + fastRunSettle(t) + ctx, s, r, pid := reliabilityRunner(t) + var attempts atomic.Int32 + original := runFinishWrite + runFinishWrite = func(r *runner, ctx context.Context, id int64, status, outcome, diagnostic string, input stage.Values) error { + if attempts.Add(1) <= 2 { + return errors.New("database is locked") + } + return original(r, ctx, id, status, outcome, diagnostic, input) + } + t.Cleanup(func() { runFinishWrite = original }) + workspace := t.TempDir() + d, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "transient", Workspace: workspace, Input: map[string]any{"prompt": "task"}}) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + detail, err := s.GetRun(ctx, d.ID) + if err != nil || detail.Status != "succeeded" || detail.FinishedAt == "" { + t.Fatalf("run not settled after a transient failure: %+v %v", detail, err) + } + if attempts.Load() != 3 { + t.Fatalf("finish attempts = %d, want 3", attempts.Load()) + } + r.mu.Lock() + _, reserved := r.active[d.ID] + r.mu.Unlock() + if reserved { + t.Fatal("settled run still reserves its workspace") + } +} + +// A refused transition is final: it is not retried. +func TestFinishRunRefusedTransitionIsNotRetried(t *testing.T) { + fastRunSettle(t) + _, _, r, pid := reliabilityRunner(t) + var attempts atomic.Int32 + original := runFinishWrite + runFinishWrite = func(*runner, context.Context, int64, string, string, string, stage.Values) error { + attempts.Add(1) + return pipeline.ErrInvalidRunTransition + } + t.Cleanup(func() { runFinishWrite = original }) + if _, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "refused", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}}); err != nil { + t.Fatal(err) + } + r.wg.Wait() + if attempts.Load() != 1 { + t.Fatalf("refused transition attempted %d times", attempts.Load()) + } +} + +// The launch teardown retries a failed read instead of keeping the +// reservation forever. +func TestLaunchTeardownRetriesAFailedRead(t *testing.T) { + fastRunSettle(t) + _, _, r, pid := reliabilityRunner(t) + var reads atomic.Int32 + original := runSettleRead + runSettleRead = func(r *runner, ctx context.Context, id int64) (*protocol.RunDetail, error) { + if reads.Add(1) <= 2 { + return nil, errors.New("database is locked") + } + return original(r, ctx, id) + } + t.Cleanup(func() { runSettleRead = original }) + d, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "teardown", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}}) + if err != nil { + t.Fatal(err) + } + r.wg.Wait() + r.mu.Lock() + _, reserved := r.active[d.ID] + r.mu.Unlock() + if reserved || reads.Load() < 3 { + t.Fatalf("reservation kept after a transient teardown read failure (reads=%d)", reads.Load()) + } +} + +// A run kept for reattachment that cannot be read is not left "running": +// its adopted session is stopped and the run is marked interrupted. +func TestReattachReadFailureMarksTheRunInterrupted(t *testing.T) { + fastRunSettle(t) + interrupts := seamRestartRecovery(t, nil) + f := stopMidStage(t, ownedLiveStage) + r, s := f.restart(t, func(context.Context, *pipeline.Store, stage.Definition) (stage.Result, error) { + t.Error("an unreadable run executed") + return stage.Result{}, nil + }) + original := runSettleRead + runSettleRead = func(*runner, context.Context, int64) (*protocol.RunDetail, error) { + return nil, errors.New("database is unavailable") + } + t.Cleanup(func() { runSettleRead = original }) + r.reattachRuns() + r.wg.Wait() + runSettleRead = original + d, err := s.GetRun(context.Background(), f.runID) + if err != nil { + t.Fatal(err) + } + if d.Status != "interrupted" || !strings.Contains(d.Diagnostic, "could not be reattached") { + t.Fatalf("unreadable reattached run left as %s: %q", d.Status, d.Diagnostic) + } + if interrupts.Load() != 1 { + t.Fatalf("adopted session interrupted %d times, want 1", interrupts.Load()) + } + if owners, _ := s.ActiveSessionOwners(context.Background()); len(owners) != 0 { + t.Fatalf("session still recorded active: %+v", owners) + } +} + +// A failed run whose cleanup agent is still active is listed as executing, +// found with one query rather than a detail read per failed run. +func TestListRunsMarksFailedRunsWithActiveAgentsExecuting(t *testing.T) { + ctx, s, r, pid := reliabilityRunner(t) + d, _ := s.Get(ctx, pid, 1) + var ids []int64 + for _, key := range []string{"a", "b"} { + id, _, err := s.CreateRun(ctx, d, key, t.TempDir(), false, nil, map[string]any{"prompt": "task"}) + if err != nil { + t.Fatal(err) + } + if err := s.BeginStep(ctx, id, 1, "one", map[string]any{}); err != nil { + t.Fatal(err) + } + if err := s.FinishRun(ctx, id, "failed", "error", "boom", nil); err != nil { + t.Fatal(err) + } + ids = append(ids, id) + } + db, err := sql.Open("sqlite", s.DatabasePath()) + if err != nil { + t.Fatal(err) + } + defer db.Close() + if _, err := db.ExecContext(ctx, `UPDATE run_steps SET agent_active=1 WHERE run_id=?`, ids[0]); err != nil { + t.Fatal(err) + } + runs, err := r.listRuns() + if err != nil { + t.Fatal(err) + } + executing := map[int64]bool{} + for _, run := range runs { + executing[run.ID] = run.Executing + } + if !executing[ids[0]] || executing[ids[1]] { + t.Fatalf("executing = %v", executing) + } +} + +// Creating a run's worktree (a git hook can make it arbitrarily slow) no +// longer holds the runner lock: listings, details and another admission in a +// different workspace proceed meanwhile. +func TestRunWorktreeCreationDoesNotBlockListings(t *testing.T) { + if _, err := exec.LookPath("git"); err != nil { + t.Skip("git not installed") + } + _, _, r, pid := reliabilityRunner(t) + repo := filepath.Join(t.TempDir(), "repo") + git := func(args ...string) { + t.Helper() + cmd := exec.Command("git", append([]string{"-C", repo, "-c", "user.name=t", "-c", "user.email=t@example.invalid", "-c", "commit.gpgsign=false"}, args...)...) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v: %s", args, err, out) + } + } + if err := os.MkdirAll(repo, 0o755); err != nil { + t.Fatal(err) + } + git("init", "-q") + git("commit", "-q", "--allow-empty", "-m", "root") + started, release := filepath.Join(t.TempDir(), "started"), filepath.Join(t.TempDir(), "release") + hook := "#!/bin/sh\ntouch '" + started + "'\nfor i in $(seq 1 200); do [ -e '" + release + "' ] && exit 0; sleep 0.05; done\n" + if err := os.WriteFile(filepath.Join(repo, ".git", "hooks", "post-checkout"), []byte(hook), 0o755); err != nil { + t.Fatal(err) + } + admitted := make(chan error, 1) + go func() { + _, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "slow-tree", Title: "slow tree", Workspace: repo, Input: map[string]any{"prompt": "task"}}) + admitted <- err + }() + waitFor(t, "worktree hook running", func() bool { _, err := os.Stat(started); return err == nil }) + done := make(chan error, 1) + go func() { + if _, err := r.listRuns(); err != nil { + done <- err + return + } + _, err := r.start(protocol.Message{PipelineID: pid, Version: 1, RequestKey: "elsewhere", Title: "elsewhere", Workspace: t.TempDir(), Input: map[string]any{"prompt": "task"}}) + done <- err + }() + select { + case err := <-done: + if err != nil { + t.Fatal(err) + } + case <-time.After(5 * time.Second): + t.Fatal("listing or another admission blocked behind worktree creation") + } + if err := os.WriteFile(release, nil, 0o644); err != nil { + t.Fatal(err) + } + if err := <-admitted; err != nil { + t.Fatal(err) + } + r.wg.Wait() + runs, err := r.listRuns() + if err != nil || len(runs) != 2 { + t.Fatalf("runs = %+v %v", runs, err) + } + for _, run := range runs { + if run.Workspace == repo { + t.Fatalf("run used the main checkout instead of its own worktree: %+v", run) + } + } + t.Cleanup(func() { + // Remove the run worktree sibling the admission created. + os.RemoveAll(repo + runWorktreesDirSuffix) + }) +} diff --git a/internal/server/storage_cleanup.go b/internal/server/storage_cleanup.go index a82eb84f..4355ccbf 100644 --- a/internal/server/storage_cleanup.go +++ b/internal/server/storage_cleanup.go @@ -190,6 +190,9 @@ func (m *storageManager) apply(ctx context.Context, preview protocol.StorageClea for _, active := range m.runner.active { config.ProtectedWorkspaces = append(config.ProtectedWorkspaces, active.workspace) } + for source := range m.runner.admitting { + config.ProtectedWorkspaces = append(config.ProtectedWorkspaces, source) + } var tree storageWorktree found := false for _, known := range before.Worktrees { From 878012ad4c5ce624db58144353a90d8d036e07b3 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:42:27 +0000 Subject: [PATCH 13/19] Runner: gofmt Co-Authored-By: Claude Opus 5.5 --- internal/server/runner.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/internal/server/runner.go b/internal/server/runner.go index 522e1bc0..39d95ac0 100644 --- a/internal/server/runner.go +++ b/internal/server/runner.go @@ -44,7 +44,7 @@ type runner struct { // admitting counts admissions creating a run worktree from each source // workspace outside r.mu; storage maintenance keeps those trees. admitting map[string]int - execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error) + execute func(context.Context, stage.Definition, stage.Values) (stage.Result, error) // dirEnv resolves the run workspace's own environment (direnv/mise) at // run start; nil uses workenv.Default. dirEnv *workenv.Resolver From 393f06fa88dbd75812d97d2fb9bfab9b5e65c165 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:46:00 +0000 Subject: [PATCH 14/19] Chat find: re-register a highlight whose shared entry another text removed Co-Authored-By: Claude Opus 5.5 --- .../features/chat/ui/transcript/chat_find_highlight.dart | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/lib/features/chat/ui/transcript/chat_find_highlight.dart b/app/lib/features/chat/ui/transcript/chat_find_highlight.dart index d4219007..96dea40c 100644 --- a/app/lib/features/chat/ui/transcript/chat_find_highlight.dart +++ b/app/lib/features/chat/ui/transcript/chat_find_highlight.dart @@ -143,7 +143,11 @@ class _ChatFindHighlightState extends State { void _register(ChatFindTargets? targets, String? rowKey) { final next = rowKey == null ? null : (rowKey, widget.text); if (identical(targets, _targets) && next == _registered) { - if (next != null) targets!.texts[next.$1]![next.$2] = widget.rects; + // Another text with the same row and string may have unregistered + // the shared entry; put it back. + if (next != null) { + targets!.texts.putIfAbsent(next.$1, () => {})[next.$2] = widget.rects; + } return; } _unregister(); From 12c7642e35514e186f36c7cd4c7c07b7c1c454d3 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:49:36 +0000 Subject: [PATCH 15/19] Chat quick switcher MRU, Closed section and markers; Alt+N, Alt+J and run tab keys Ctrl+K lists open chats most recently used first (tracked on open and pane focus, persisted per server) and preselects the previous chat, so Ctrl+K, Enter returns to it. Rows mark needs you / working / unread; a query also lists matching closed chats under Closed, and choosing one reopens it. Alt+N (Option+N) starts a new chat and Alt+J (Option+J) opens the next chat waiting for you, unread or failed, cycling; the terminal keeps both. In run detail, bare 1-4 switch tabs when not typing. Cheatsheet entries added. Co-Authored-By: Claude Opus 5.5 --- app/lib/application/pipelines_app.dart | 24 +++- app/lib/features/chat/chat_runtime.dart | 20 ++- .../features/chat/chat_screen_attention.dart | 54 ++++++++ .../chat/chat_screen_quick_switch.dart | 39 +++++- .../features/chat/chat_screen_workspace.dart | 5 + .../chat_quick_switch_dialog.dart | 97 +++++++++++--- .../chat_quick_switch_requests.dart | 6 +- .../conversation/chat_quick_switch_row.dart | 86 +++++++++++-- app/lib/features/chat/data/chat_recency.dart | 101 +++++++++++++++ .../chat/domain/chat_attention_cycle.dart | 40 ++++++ .../chat/domain/chat_quick_switch_order.dart | 73 +++++++++++ app/lib/features/chat/screen.dart | 10 +- .../features/runs/ui/run_detail_tab_keys.dart | 40 ++++++ app/lib/features/runs/ui/run_detail_tabs.dart | 16 +++ .../settings/keyboard_shortcuts_registry.dart | 24 +++- app/lib/shell/adaptive_shell.dart | 31 ++++- .../shell/shell_chat_actions_shortcut.dart | 56 +++++++++ .../chat_quick_switch_shortcut_test.dart | 102 ++++++++++++++- .../chat_quick_switch_dialog_test.dart | 52 +++++++- .../features/chat/data/chat_recency_test.dart | 44 +++++++ .../domain/chat_quick_switch_order_test.dart | 113 +++++++++++++++++ .../runs/ui/run_detail_tab_keys_test.dart | 72 +++++++++++ .../shell_chat_actions_shortcut_test.dart | 119 ++++++++++++++++++ .../examples/chat-quick-switch-recent.json | 25 ++++ app/tool/perf/perf_fixture.dart | 20 +++ 25 files changed, 1223 insertions(+), 46 deletions(-) create mode 100644 app/lib/features/chat/chat_screen_attention.dart create mode 100644 app/lib/features/chat/data/chat_recency.dart create mode 100644 app/lib/features/chat/domain/chat_attention_cycle.dart create mode 100644 app/lib/features/chat/domain/chat_quick_switch_order.dart create mode 100644 app/lib/features/runs/ui/run_detail_tab_keys.dart create mode 100644 app/lib/shell/shell_chat_actions_shortcut.dart create mode 100644 app/test/features/chat/data/chat_recency_test.dart create mode 100644 app/test/features/chat/domain/chat_quick_switch_order_test.dart create mode 100644 app/test/features/runs/ui/run_detail_tab_keys_test.dart create mode 100644 app/test/shell/shell_chat_actions_shortcut_test.dart create mode 100644 app/tool/capture/examples/chat-quick-switch-recent.json diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 652ecb05..34e4f87f 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -15,6 +15,7 @@ import '../core/servers/server_scope.dart'; import '../core/transport/pipelines_client.dart'; import '../shell/adaptive_shell.dart'; import '../shell/destination.dart'; +import '../shell/shell_chat_actions_shortcut.dart'; import '../features/attention/notify/notification_controller.dart'; import '../features/attention/notify/notification_models.dart'; import '../features/attention/notify/chat_question_notices.dart'; @@ -55,6 +56,7 @@ import '../shell/windows/window_store.dart'; import 'app_terminals.dart'; import '../features/chat/chat_run_opener.dart'; import '../features/chat/chat_runtime.dart'; +import '../features/chat/data/chat_recency.dart'; import '../features/changes/windows/diff_windows.dart'; import '../features/chat/windows/chat_windows.dart'; import 'open_in_chat.dart'; @@ -359,7 +361,13 @@ class _PipelinesAppState extends State final chatScope = widget.chatPool != null ? 'all-saved-servers' : serverStorageScope(serverIdentity(chatGateway)); - _chatRuntime = ChatRuntime(gateway: chatGateway, serverKey: chatScope); + _chatRuntime = ChatRuntime( + gateway: chatGateway, + serverKey: chatScope, + recency: ChatRecency( + store: SharedPreferencesChatRecencyStore(serverScope: chatScope), + ), + ); _chatWindows = ChatWindows( manager: _windows, runtime: _chatRuntime, @@ -868,6 +876,19 @@ class _PipelinesAppState extends State if (!_chatRuntime.quickSwitch.toggle()) _focusOpenChatComposer(); } + /// Alt+N / Alt+J: the shell has shown Chat; once it has built (a first + /// visit mounts the chat screen), the chat screen acts. + void _chatAction(ShellChatAction action) { + final requests = switch (action) { + ShellChatAction.newChat => _chatRuntime.newChat, + ShellChatAction.nextAttention => _chatRuntime.nextAttention, + }; + WidgetsBinding.instance.addPostFrameCallback((_) { + if (mounted) requests.toggle(); + }); + WidgetsBinding.instance.ensureVisualUpdate(); + } + void _selectDestination(AppDestination destination) { // Settings is shown from its own nav item and has no Back, so its route // (filed under the Pipelines tab) must not trap the Pipelines item: that @@ -1130,6 +1151,7 @@ class _PipelinesAppState extends State onDestinationReselected: _reselectDestination, onOpenChat: _focusOpenChatComposer, onChatQuickSwitch: _toggleChatQuickSwitch, + onChatAction: _chatAction, destinationBodies: { AppDestination.pipelines: (_) => FirstRunWalkthroughGate( store: _walkthroughStore, diff --git a/app/lib/features/chat/chat_runtime.dart b/app/lib/features/chat/chat_runtime.dart index 611e39ae..f828de14 100644 --- a/app/lib/features/chat/chat_runtime.dart +++ b/app/lib/features/chat/chat_runtime.dart @@ -13,6 +13,7 @@ import 'conversation/chat_transcript_cache.dart'; import 'conversation/chat_composer_controller.dart'; import 'conversation/chat_quick_switch_requests.dart'; import 'conversation/composer_focus_request.dart'; +import 'data/chat_recency.dart'; import 'data/chat_repository.dart'; import 'ui/sessions/chat_sessions_body.dart'; import 'ui/sessions/chat_sessions_controller.dart'; @@ -24,9 +25,13 @@ import 'ui/sessions/chat_sessions_controller.dart'; /// /// It notifies when a row a conversation is drawn from changes. class ChatRuntime extends ChangeNotifier { - ChatRuntime({required ApiGateway gateway, this.serverKey = ''}) - : _gateway = gateway, - sessions = ChatSessionsController(ChatRepository(gateway)) { + ChatRuntime({ + required ApiGateway gateway, + this.serverKey = '', + ChatRecency? recency, + }) : _gateway = gateway, + recency = recency ?? ChatRecency(), + sessions = ChatSessionsController(ChatRepository(gateway)) { sessions.onSessionReplaced = (previousId, session) { for (final listener in _replaced.toList()) { listener(previousId, session); @@ -132,6 +137,15 @@ class ChatRuntime extends ChangeNotifier { /// The Chat destination's quick switcher, toggled by Ctrl+K / Alt+K there. final ChatQuickSwitchRequests quickSwitch = ChatQuickSwitchRequests(); + /// New chat (Alt+N) and the next chat needing the operator (Alt+J), asked + /// of the mounted Chat destination. + final ChatQuickSwitchRequests newChat = ChatQuickSwitchRequests(); + final ChatQuickSwitchRequests nextAttention = ChatQuickSwitchRequests(); + + /// The chats this device used, most recent first (the quick switcher's + /// order with no query). + final ChatRecency recency; + /// Mounted composers are registered so external actions can append without /// sending. A selection made before a pane mounts is queued here. final Map composers = {}; diff --git a/app/lib/features/chat/chat_screen_attention.dart b/app/lib/features/chat/chat_screen_attention.dart new file mode 100644 index 00000000..1ef3edca --- /dev/null +++ b/app/lib/features/chat/chat_screen_attention.dart @@ -0,0 +1,54 @@ +part of 'screen.dart'; + +/// The Chat destination's app-wide chat shortcuts, run through +/// [ChatRuntime.newChat] and [ChatRuntime.nextAttention] (the shell shows +/// Chat first): Alt+N starts a new chat with the list's own create dialog, +/// and Alt+J opens the next chat needing the operator (waiting for an answer, +/// unread, or a failed action), cycling in list order. Neither acts while a +/// popup or dialog over the chat keeps the keyboard. +mixin _ChatScreenAttention on State, _ChatScreenWorkspace { + ChatRuntime get _runtime; + + void _bindAttention() { + _runtime.newChat.attach(_startNewChat); + _runtime.nextAttention.attach(_openNextAttention); + } + + void _unbindAttention() { + _runtime.newChat.detach(_startNewChat); + _runtime.nextAttention.detach(_openNextAttention); + } + + void _startNewChat() { + if (!mounted || !_chatOwnsKeyboard()) return; + final state = _sessionsKey.currentState; + if (state != null) unawaited(state.newChat()); + } + + void _openNextAttention() { + if (!mounted || !_chatOwnsKeyboard()) return; + final sessions = _runtime.sessions; + final current = _workspaceVisible ? _workspace.activePane?.sessionId : null; + final next = chatNextNeedingAttention( + sessions.sessions, + current, + (row) => chatNeedsAttention( + row, + unread: sessions.isUnseen(row), + failed: sessions.errorFor('${row['id'] ?? ''}') != null, + ), + ); + if (next != null) { + _openByShortcut(next); + return; + } + ScaffoldMessenger.maybeOf(context) + ?..hideCurrentSnackBar() + ..showSnackBar( + const SnackBar( + key: Key('chat-no-attention'), + content: Text('No other chat needs you.'), + ), + ); + } +} diff --git a/app/lib/features/chat/chat_screen_quick_switch.dart b/app/lib/features/chat/chat_screen_quick_switch.dart index adad1006..6940c3a9 100644 --- a/app/lib/features/chat/chat_screen_quick_switch.dart +++ b/app/lib/features/chat/chat_screen_quick_switch.dart @@ -1,16 +1,21 @@ part of 'screen.dart'; /// The quick switcher Ctrl+K / Alt+K (Cmd+K on a Mac) shows when pressed on -/// the Chat destination: the open chats to jump to, filtered as the operator -/// types (see [showChatQuickSwitch]). Pressing the shortcut again closes it. -/// A chosen chat opens as a keyboard choice from the list does: its pane is -/// reused when it is already open, and its composer takes the keyboard. +/// the Chat destination: the open chats to jump to, most recently used first +/// with the one used before the current chat selected, filtered as the +/// operator types (see [showChatQuickSwitch]). Pressing the shortcut again +/// closes it. A chosen chat opens as a keyboard choice from the list does: +/// its pane is reused when it is already open, and its composer takes the +/// keyboard. A closed chat a query found is reopened first. mixin _ChatScreenQuickSwitch on State, _ChatScreenWorkspace { ChatRuntime get _runtime; ModalRoute? _quickSwitchRoute; - void _bindQuickSwitch() => _runtime.quickSwitch.attach(_toggleQuickSwitch); + void _bindQuickSwitch() { + _runtime.quickSwitch.attach(_toggleQuickSwitch); + unawaited(_runtime.recency.load()); + } void _unbindQuickSwitch() { _runtime.quickSwitch.detach(_toggleQuickSwitch); @@ -24,6 +29,12 @@ mixin _ChatScreenQuickSwitch on State, _ChatScreenWorkspace { } } + @override + void _touchActiveChat() { + final id = _workspaceVisible ? _workspace.activePane?.sessionId : null; + if (id != null) _runtime.recency.touch(id); + } + void _toggleQuickSwitch() { final open = _quickSwitchRoute; if (open != null && open.isActive) { @@ -36,9 +47,11 @@ mixin _ChatScreenQuickSwitch on State, _ChatScreenWorkspace { final route = showChatQuickSwitch( context, sessions: _runtime.sessions, + recent: () => _runtime.recency.ids, + currentId: _workspaceVisible ? _workspace.activePane?.sessionId : null, serverName: _quickSwitchServerName, onSelected: (row) { - if (mounted) _openByShortcut(row); + if (mounted) unawaited(_openSwitched(row)); }, ); _quickSwitchRoute = route; @@ -47,6 +60,20 @@ mixin _ChatScreenQuickSwitch on State, _ChatScreenWorkspace { }); } + /// Opens a chosen chat, reopening it first when it was closed. A refused + /// reopen leaves it closed, with the list row showing the server's words. + Future _openSwitched(JsonMap row) async { + if (chatQuickSwitchIsClosed(row)) { + final id = '${row['id'] ?? ''}'; + await _runtime.sessions.reopen(id); + if (!mounted || _runtime.sessions.errorFor(id) != null) return; + row = {...row} + ..remove('closed_at') + ..remove('closed'); + } + if (mounted) _openByShortcut(row); + } + /// The machine a federated row is on, as the list names it. String? _quickSwitchServerName(JsonMap row) { final id = '${row['_server_id'] ?? ''}'; diff --git a/app/lib/features/chat/chat_screen_workspace.dart b/app/lib/features/chat/chat_screen_workspace.dart index 36fb4e97..ea8d4415 100644 --- a/app/lib/features/chat/chat_screen_workspace.dart +++ b/app/lib/features/chat/chat_screen_workspace.dart @@ -365,6 +365,7 @@ mixin _ChatScreenWorkspace on State { if (_workspaceSignature == signature) return; _workspaceSignature = signature; _syncOpenWorkspace(); + _touchActiveChat(); void update() { if (!mounted) return; setState(() {}); @@ -379,6 +380,10 @@ mixin _ChatScreenWorkspace on State { } } + /// The active pane's chat, while shown, is the most recently used one (the + /// quick switcher's order). + void _touchActiveChat(); + void _publishWorkspaceRoute() { if (!mounted) return; final id = _workspace.activePane?.sessionId; diff --git a/app/lib/features/chat/conversation/chat_quick_switch_dialog.dart b/app/lib/features/chat/conversation/chat_quick_switch_dialog.dart index 73a317b0..306ffcc3 100644 --- a/app/lib/features/chat/conversation/chat_quick_switch_dialog.dart +++ b/app/lib/features/chat/conversation/chat_quick_switch_dialog.dart @@ -4,28 +4,39 @@ import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../../ui/adaptive/app_popups.dart'; import '../domain/chat_quick_switch.dart'; +import '../domain/chat_quick_switch_order.dart'; import '../ui/sessions/chat_sessions_controller.dart'; import 'chat_quick_switch_keys.dart'; import 'chat_quick_switch_row.dart'; /// Shows the chat quick switcher over the Chat destination: a search field /// with the keyboard in it above the open chats ([chatQuickSwitchCandidates]), -/// narrowed and ranked as the operator types ([chatQuickSwitchMatches]). The -/// first match is selected; Ctrl+N / Ctrl+P and Down / Up move the selection, -/// wrapping, and Enter or a click chooses it. Esc closes it. +/// most recently used first ([recent]), narrowed and ranked as the operator +/// types ([chatQuickSwitchMatches]). With no query the chat used before +/// [currentId] is selected, so the shortcut and then Enter go back to it; +/// with one, the best match. A query also lists the closed chats it matches +/// under "Closed", after the open ones. Ctrl+N / Ctrl+P and Down / Up move +/// the selection, wrapping, and Enter or a click chooses it. Esc closes it. /// /// A centred dialog on a wide app, a full-width bottom sheet on a phone, on /// the root navigator either way. Returns the route so a second press of the -/// shortcut can close it; [onSelected] gets the chosen row once it closed. +/// shortcut can close it; [onSelected] gets the chosen row once it closed (a +/// closed row is still closed: the caller reopens it). ModalRoute showChatQuickSwitch( BuildContext context, { required ChatSessionsController sessions, required ValueChanged onSelected, String? Function(JsonMap session)? serverName, + List Function()? recent, + String? currentId, }) { final navigator = Navigator.of(context, rootNavigator: true); - Widget content(BuildContext context) => - ChatQuickSwitch(sessions: sessions, serverName: serverName); + Widget content(BuildContext context) => ChatQuickSwitch( + sessions: sessions, + serverName: serverName, + recent: recent?.call() ?? const [], + currentId: currentId, + ); final ModalRoute route = usesDesktopPopups(context) ? DialogRoute( context: context, @@ -76,11 +87,23 @@ void closeChatQuickSwitch(ModalRoute route) { /// The switcher's content: the field and the matching chats. class ChatQuickSwitch extends StatefulWidget { - const ChatQuickSwitch({super.key, required this.sessions, this.serverName}); + const ChatQuickSwitch({ + super.key, + required this.sessions, + this.serverName, + this.recent = const [], + this.currentId, + }); final ChatSessionsController sessions; final String? Function(JsonMap session)? serverName; + /// The chats used on this device, most recent first. + final List recent; + + /// The chat shown when the switcher opened, if any. + final String? currentId; + @override State createState() => _ChatQuickSwitchState(); } @@ -88,16 +111,52 @@ class ChatQuickSwitch extends StatefulWidget { class _ChatQuickSwitchState extends State { final _query = TextEditingController(); final _rowKeys = {}; - int _selected = 0; + + /// The row the operator moved to; null keeps the initial selection + /// ([chatQuickSwitchInitialSelection]). + int? _moved; List _shown = const []; + /// How many of [_shown] are open chats; the closed ones follow. + int _openCount = 0; + @override void dispose() { _query.dispose(); super.dispose(); } - void _queryChanged(String _) => setState(() => _selected = 0); + void _queryChanged(String _) => setState(() => _moved = null); + + int get _selected => + _moved ?? + chatQuickSwitchInitialSelection( + _shown, + currentId: widget.currentId, + emptyQuery: _query.text.trim().isEmpty, + ); + + /// The open matches, then (with a query) the closed ones. + void _match() { + final query = _query.text; + final open = chatQuickSwitchMatches( + chatQuickSwitchByRecency( + chatQuickSwitchCandidates(widget.sessions.sessions), + widget.recent, + ), + query, + serverName: widget.serverName, + ); + final closed = query.trim().isEmpty + ? const [] + : chatQuickSwitchMatches( + chatQuickSwitchClosed(widget.sessions.sessions), + query, + serverName: widget.serverName, + ); + _openCount = open.length; + _shown = [...open, ...closed]; + } /// Moves the selection [step] rows, wrapping, and scrolls it into view at /// the edge it moved towards. @@ -105,7 +164,7 @@ class _ChatQuickSwitchState extends State { if (_shown.isEmpty) return; final from = _selected.clamp(0, _shown.length - 1); final index = (from + step) % _shown.length; - setState(() => _selected = index); + setState(() => _moved = index); final id = '${_shown[index]['id'] ?? ''}'; final policy = step < 0 ? ScrollPositionAlignmentPolicy.keepVisibleAtStart @@ -154,11 +213,7 @@ class _ChatQuickSwitchState extends State { final list = ListenableBuilder( listenable: widget.sessions, builder: (context, _) { - _shown = chatQuickSwitchMatches( - chatQuickSwitchCandidates(widget.sessions.sessions), - _query.text, - serverName: widget.serverName, - ); + _match(); if (_shown.isEmpty) { return Padding( padding: const EdgeInsets.all(24), @@ -181,7 +236,9 @@ class _ChatQuickSwitchState extends State { child: Column( mainAxisSize: MainAxisSize.min, children: [ - for (final (index, row) in _shown.indexed) + for (final (index, row) in _shown.indexed) ...[ + if (index == _openCount) + const ChatQuickSwitchSectionHeader(title: 'Closed'), ChatQuickSwitchRow( key: _rowKeys.putIfAbsent( '${row['id'] ?? ''}', @@ -190,8 +247,16 @@ class _ChatQuickSwitchState extends State { session: row, serverName: widget.serverName?.call(row), selected: index == selected, + closed: index >= _openCount, + markers: index >= _openCount + ? const [] + : chatQuickSwitchMarkers( + row, + unread: widget.sessions.isUnseen(row), + ), onTap: () => _choose(row), ), + ], ], ), ); diff --git a/app/lib/features/chat/conversation/chat_quick_switch_requests.dart b/app/lib/features/chat/conversation/chat_quick_switch_requests.dart index c0da63d8..2252d992 100644 --- a/app/lib/features/chat/conversation/chat_quick_switch_requests.dart +++ b/app/lib/features/chat/conversation/chat_quick_switch_requests.dart @@ -1,7 +1,9 @@ import 'package:flutter/foundation.dart'; -/// Where Ctrl+K / Alt+K pressed on the Chat destination goes: the mounted -/// chat screen attaches its quick switcher here, and the app toggles it. +/// Where an app-wide chat shortcut goes: Ctrl+K / Alt+K pressed on the Chat +/// destination (the quick switcher), Alt+N (New chat) and Alt+J (the next +/// chat needing the operator). The mounted chat screen attaches its action +/// here, and the app runs it. class ChatQuickSwitchRequests { VoidCallback? _toggle; diff --git a/app/lib/features/chat/conversation/chat_quick_switch_row.dart b/app/lib/features/chat/conversation/chat_quick_switch_row.dart index c8bd5232..3c32f132 100644 --- a/app/lib/features/chat/conversation/chat_quick_switch_row.dart +++ b/app/lib/features/chat/conversation/chat_quick_switch_row.dart @@ -2,14 +2,17 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../domain/chat_list_activity.dart'; +import '../domain/chat_quick_switch_order.dart'; import '../domain/chat_sessions.dart'; import '../ui/sessions/session_row_content.dart'; import '../ui/sessions/session_row_style.dart'; /// One chat in the quick switcher: the list's avatar (harness mark in the /// chat's colour, with its running or awaiting badge), the title, and the -/// folder with the machine it is on. The selected row takes the selection -/// fill; hover and click work as on any list tile. +/// folder with the machine it is on, then small [markers] (needs you, +/// working, unread) and the star. A [closed] chat (listed under "Closed", +/// reopened when chosen) shows no live state. The selected row takes the selection fill; hover +/// and click work as on any list tile. class ChatQuickSwitchRow extends StatelessWidget { const ChatQuickSwitchRow({ super.key, @@ -17,22 +20,31 @@ class ChatQuickSwitchRow extends StatelessWidget { required this.selected, required this.onTap, this.serverName, + this.markers = const [], + this.closed = false, }); final JsonMap session; final bool selected; final VoidCallback onTap; final String? serverName; + final List markers; + final bool closed; @override Widget build(BuildContext context) { final id = '${session['id'] ?? ''}'; final scheme = Theme.of(context).colorScheme; - final running = session['running'] == true; + final running = !closed && session['running'] == true; final subtitle = [ homeRelativePath('${session['directory'] ?? ''}'.trim()), ?serverName, ].where((part) => part.isNotEmpty).join(' · '); + final trailing = [ + for (final marker in markers) ChatQuickSwitchMarkerIcon(marker: marker), + if (session['starred'] == true) + Icon(Icons.star, color: scheme.primary, semanticLabel: 'Starred'), + ]; return ListTile( key: Key('chat-quick-switch-row-$id'), selected: selected, @@ -43,7 +55,7 @@ class ChatQuickSwitchRow extends StatelessWidget { session: session, running: running, backgroundTasks: running ? 0 : chatSessionBackgroundTasks(session), - awaitingOperator: chatSessionAwaitingOperator(session), + awaitingOperator: closed ? 0 : chatSessionAwaitingOperator(session), ), title: Text( chatSessionTitle(session), @@ -53,10 +65,70 @@ class ChatQuickSwitchRow extends StatelessWidget { subtitle: subtitle.isEmpty ? null : Text(subtitle, maxLines: 1, overflow: TextOverflow.ellipsis), - trailing: session['starred'] == true - ? Icon(Icons.star, color: scheme.primary, semanticLabel: 'Starred') - : null, + trailing: trailing.isEmpty + ? null + : Row(mainAxisSize: MainAxisSize.min, spacing: 6, children: trailing), onTap: onTap, ); } } + +/// One row marker: a small icon in the state's colour, named by its tooltip +/// and to assistive technology. +class ChatQuickSwitchMarkerIcon extends StatelessWidget { + const ChatQuickSwitchMarkerIcon({super.key, required this.marker}); + + final ChatQuickSwitchMarker marker; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + final (icon, color) = switch (marker) { + ChatQuickSwitchMarker.needsYou => ( + Icons.notifications_active, + scheme.error, + ), + ChatQuickSwitchMarker.working => ( + Icons.play_circle_outline, + scheme.onSurfaceVariant, + ), + ChatQuickSwitchMarker.unread => (Icons.circle, scheme.primary), + }; + return Tooltip( + message: marker.label, + child: Icon( + icon, + key: Key('chat-quick-switch-marker-${marker.name}'), + size: marker == ChatQuickSwitchMarker.unread ? 10 : 18, + color: color, + semanticLabel: marker.label, + ), + ); + } +} + +/// The heading over the switcher's closed chats. +class ChatQuickSwitchSectionHeader extends StatelessWidget { + const ChatQuickSwitchSectionHeader({super.key, required this.title}); + + final String title; + + @override + Widget build(BuildContext context) { + final theme = Theme.of(context); + return Container( + alignment: AlignmentDirectional.centerStart, + padding: const EdgeInsets.fromLTRB(16, 12, 16, 4), + child: Semantics( + header: true, + child: Text( + title, + key: const Key('chat-quick-switch-closed-header'), + style: theme.textTheme.labelLarge?.copyWith( + color: theme.colorScheme.onSurfaceVariant, + ), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/data/chat_recency.dart b/app/lib/features/chat/data/chat_recency.dart new file mode 100644 index 00000000..d9d95441 --- /dev/null +++ b/app/lib/features/chat/data/chat_recency.dart @@ -0,0 +1,101 @@ +import 'dart:async'; + +import 'package:shared_preferences/shared_preferences.dart'; + +import '../../../core/servers/server_scope.dart'; + +/// Where the chats' most-recently-used order is kept on this device. +abstract interface class ChatRecencyStore { + Future> read(); + + Future write(List ids); +} + +/// The chats this device used, most recent first, for the quick switcher's +/// order with no query. A chat counts as used when it is opened or its pane +/// takes focus ([touch]). The list is read once, lazily, and written back on +/// every change; a chat touched before the read finished stays in front. +class ChatRecency { + ChatRecency({ChatRecencyStore? store, this.limit = 200}) + : _store = store ?? MemoryChatRecencyStore(); + + final ChatRecencyStore _store; + + /// How many chats are remembered. + final int limit; + + List _ids = const []; + Future? _loading; + + /// The remembered chats, most recent first. + List get ids => _ids; + + /// Reads the stored order once; later calls return the same read. + Future load() => _loading ??= _read(); + + Future _read() async { + List stored; + try { + stored = await _store.read(); + } catch (_) { + stored = const []; + } + _ids = _merged(_ids, stored); + } + + /// [id] was opened or focused: it moves to the front. + void touch(String id) { + if (id.isEmpty || (_ids.isNotEmpty && _ids.first == id)) return; + _ids = _merged([id], _ids); + unawaited(load().then((_) => _write())); + } + + Future _write() async { + try { + await _store.write(_ids); + } catch (_) { + // The order is a convenience; the switcher still lists every chat. + } + } + + List _merged(List front, List rest) { + final seen = {}; + return [ + for (final id in [...front, ...rest]) + if (id.isNotEmpty && seen.add(id)) id, + ].take(limit).toList(growable: false); + } +} + +class SharedPreferencesChatRecencyStore implements ChatRecencyStore { + const SharedPreferencesChatRecencyStore({this.serverScope = ''}); + + final String serverScope; + + String get _key => scopedServerKey('pipelines.chat.recency.v1', serverScope); + + @override + Future> read() async { + final prefs = await SharedPreferences.getInstance(); + return prefs.getStringList(_key) ?? const []; + } + + @override + Future write(List ids) async { + final prefs = await SharedPreferences.getInstance(); + await prefs.setStringList(_key, ids); + } +} + +/// An in-memory store for tests and hosts without preferences. +class MemoryChatRecencyStore implements ChatRecencyStore { + MemoryChatRecencyStore([List? ids]) : ids = ids ?? []; + + List ids; + + @override + Future> read() async => List.of(ids); + + @override + Future write(List ids) async => this.ids = List.of(ids); +} diff --git a/app/lib/features/chat/domain/chat_attention_cycle.dart b/app/lib/features/chat/domain/chat_attention_cycle.dart new file mode 100644 index 00000000..e574810a --- /dev/null +++ b/app/lib/features/chat/domain/chat_attention_cycle.dart @@ -0,0 +1,40 @@ +import '../../../core/api_gateway.dart'; +import 'chat_list_activity.dart'; +import 'chat_sessions.dart'; + +/// Whether an open chat needs the operator: it waits on an approval or a +/// question, has replies not read yet ([unread]), or an action on it failed +/// ([failed]). +bool chatNeedsAttention( + JsonMap session, { + required bool unread, + required bool failed, +}) => chatSessionAwaitingOperator(session) > 0 || unread || failed; + +/// The chat Alt+J opens: the next open chat after [currentId], in the order +/// the list draws them (starred, then by directory; folded sections count), +/// that [needsAttention], wrapping around. With no current chat (or one not +/// among the open chats) the first such chat. Null when no other chat needs +/// the operator. +JsonMap? chatNextNeedingAttention( + List sessions, + String? currentId, + bool Function(JsonMap session) needsAttention, +) { + final open = chatSessionsInListOrder( + chatSessionSections( + sessions + .where((row) => row['closed_at'] == null && row['closed'] != true) + .toList(), + ), + isOpen: (_) => true, + ); + if (open.isEmpty) return null; + final at = open.indexWhere((row) => '${row['id'] ?? ''}' == currentId); + for (var step = 1; step <= open.length; step++) { + final row = open[(at + step) % open.length]; + if ('${row['id'] ?? ''}' == currentId) continue; + if (needsAttention(row)) return row; + } + return null; +} diff --git a/app/lib/features/chat/domain/chat_quick_switch_order.dart b/app/lib/features/chat/domain/chat_quick_switch_order.dart new file mode 100644 index 00000000..114ec611 --- /dev/null +++ b/app/lib/features/chat/domain/chat_quick_switch_order.dart @@ -0,0 +1,73 @@ +import '../../../core/api_gateway.dart'; +import 'chat_list_activity.dart'; + +/// [candidates] most recently used first: each chat in [recent] (most recent +/// first) by its place there, then the chats never used on this device in +/// [candidates]' own order. +List chatQuickSwitchByRecency( + List candidates, + List recent, +) { + final rank = {for (final (index, id) in recent.indexed) id: index}; + final indexed = candidates.indexed.toList() + ..sort((a, b) { + final ra = rank['${a.$2['id'] ?? ''}']; + final rb = rank['${b.$2['id'] ?? ''}']; + if (ra != null && rb != null) return ra - rb; + if (ra != null) return -1; + if (rb != null) return 1; + return a.$1 - b.$1; + }); + return [for (final (_, row) in indexed) row]; +} + +/// Whether [row] is a closed chat. +bool chatQuickSwitchIsClosed(JsonMap row) => + row['closed_at'] != null || row['closed'] == true; + +/// The closed chats the switcher offers under "Closed" once a query matches +/// them, most recently closed first. +List chatQuickSwitchClosed(List sessions) { + int closedAt(JsonMap row) { + final at = row['closed_at']; + return at is num ? at.toInt() : 0; + } + + return sessions.where(chatQuickSwitchIsClosed).toList() + ..sort((a, b) => closedAt(b) - closedAt(a)); +} + +/// The row the switcher selects first: with no query, the first chat that is +/// not [currentId] (the one used before it, so the shortcut and then Enter go +/// back there, as Alt+Tab does); with a query, the best match. +int chatQuickSwitchInitialSelection( + List shown, { + required String? currentId, + required bool emptyQuery, +}) { + if (!emptyQuery || currentId == null) return 0; + final index = shown.indexWhere((row) => '${row['id'] ?? ''}' != currentId); + return index < 0 ? 0 : index; +} + +/// What a switcher row marks about its chat, most urgent first. +enum ChatQuickSwitchMarker { + needsYou('Needs you'), + working('Working'), + unread('Unread'); + + const ChatQuickSwitchMarker(this.label); + + final String label; +} + +/// [session]'s markers: approvals or questions waiting on the operator, a +/// turn running, and replies not read yet ([unread], as the list reads it). +List chatQuickSwitchMarkers( + JsonMap session, { + required bool unread, +}) => [ + if (chatSessionAwaitingOperator(session) > 0) ChatQuickSwitchMarker.needsYou, + if (session['running'] == true) ChatQuickSwitchMarker.working, + if (unread) ChatQuickSwitchMarker.unread, +]; diff --git a/app/lib/features/chat/screen.dart b/app/lib/features/chat/screen.dart index 7286deab..694632ee 100644 --- a/app/lib/features/chat/screen.dart +++ b/app/lib/features/chat/screen.dart @@ -50,7 +50,9 @@ import 'ui/sessions/chat_adaptive.dart'; import 'conversation/composer_focus_request.dart'; import 'conversation/composer_selection_focus.dart'; import 'domain/chat_commands.dart'; +import 'domain/chat_attention_cycle.dart'; import 'domain/chat_cycle.dart'; +import 'domain/chat_quick_switch_order.dart'; import '../terminal/terminal_scope.dart'; import 'domain/chat_colors.dart'; import 'ui/sessions/chat_color_palette.dart'; @@ -59,6 +61,7 @@ import 'ui/sessions/chat_sessions_controller.dart'; import 'ui/sessions/chat_sessions_screen.dart'; import '../../ui/input/keyboard_owner.dart'; +part 'chat_screen_attention.dart'; part 'chat_screen_float.dart'; part 'chat_screen_pane_menu.dart'; part 'chat_screen_keys.dart'; @@ -121,7 +124,8 @@ class _ChatScreenState extends State _ChatScreenKeys, _ChatScreenFloat, _ChatScreenPaneMenu, - _ChatScreenQuickSwitch { + _ChatScreenQuickSwitch, + _ChatScreenAttention { /// The chats' shared state: the list, opened rows, accepted models, /// transcript positions and caches (see [ChatRuntime]). @override @@ -161,11 +165,13 @@ class _ChatScreenState extends State _runtime.addSessionReplacedListener(_replacedElsewhere); _bindWindows(); _bindQuickSwitch(); + _bindAttention(); final initial = widget.initialSessionId; if (initial != null && initial.isNotEmpty) { _workspace.open(initial); _workspaceVisible = true; _publishedWorkspaceSession = initial; + _runtime.recency.touch(initial); } _workspace.addListener(_workspaceChanged); _bindWorkspacePersistence(); @@ -256,6 +262,7 @@ class _ChatScreenState extends State _openedSessions[id] = session; _workspaceVisible = true; _workspace.open(id); + _runtime.recency.touch(id); // A docked chat chosen while chat windows float over the workspace would // open behind them: hide the windows so the chosen chat is seen. final windows = widget.windows; @@ -465,6 +472,7 @@ class _ChatScreenState extends State _openWorkspace?.dispose(); _unbindWindows(); _unbindQuickSwitch(); + _unbindAttention(); _workspace.removeListener(_workspaceChanged); _workspace.dispose(); _sessions.removeListener(_nextChanged); diff --git a/app/lib/features/runs/ui/run_detail_tab_keys.dart b/app/lib/features/runs/ui/run_detail_tab_keys.dart new file mode 100644 index 00000000..90aac032 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_tab_keys.dart @@ -0,0 +1,40 @@ +import 'package:flutter/services.dart'; +import 'package:flutter/widgets.dart'; + +import '../../../ui/input/keyboard_owner.dart'; + +const _digits = [ + LogicalKeyboardKey.digit1, + LogicalKeyboardKey.digit2, + LogicalKeyboardKey.digit3, + LogicalKeyboardKey.digit4, + LogicalKeyboardKey.numpad1, + LogicalKeyboardKey.numpad2, + LogicalKeyboardKey.numpad3, + LogicalKeyboardKey.numpad4, +]; + +/// The 0-based run-detail tab a bare 1…4 key press names, or null. Any +/// modifier (Ctrl+1…9 opens a chat list item) or a repeat is not the key. +int? runDetailTabDigit(KeyEvent event, HardwareKeyboard keyboard) { + if (event is! KeyDownEvent || + keyboard.isControlPressed || + keyboard.isMetaPressed || + keyboard.isAltPressed || + keyboard.isShiftPressed) { + return null; + } + final index = _digits.indexOf(event.logicalKey); + return index < 0 ? null : index % 4; +} + +/// Whether a digit pressed now is meant for the run detail at [context]: it +/// is on screen (not in a hidden destination or tab), no dialog, menu or +/// visit page is over it, and nothing that takes typing (a text field, the +/// terminal) has the keyboard. +bool runDetailOwnsDigits(BuildContext context) { + if (!TickerMode.valuesOf(context).enabled) return false; + final route = ModalRoute.of(context); + if (route != null && !route.isCurrent) return false; + return !primaryFocusTakesTyping(); +} diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index 0ee737dc..f7f9d4b4 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -7,6 +7,7 @@ import '../../../ui/motion/fade_through_stack.dart'; import 'dart:math' as math; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; import '../../../core/api_gateway.dart'; import '../../graph/widgets/run_graph_view.dart'; @@ -19,6 +20,7 @@ import 'run_detail_content.dart'; import 'run_graph_preview.dart'; import 'run_detail_tab.dart'; import 'run_detail_tab_bodies.dart'; +import 'run_detail_tab_keys.dart'; import 'run_detail_tab_strip.dart'; import 'run_detail_timeline.dart'; import 'run_detail_visit.dart'; @@ -120,6 +122,19 @@ class _RunDetailTabsState extends State { void initState() { super.initState(); _applyInitialVisit(); + HardwareKeyboard.instance.addHandler(_tabDigitKey); + } + + /// A bare 1…4 outside text fields selects that tab of the shown ones. + bool _tabDigitKey(KeyEvent event) { + final index = runDetailTabDigit(event, HardwareKeyboard.instance); + if (index == null || !mounted || !runDetailOwnsDigits(context)) { + return false; + } + final tabs = _tabsFor(widget.run); + if (index >= tabs.length) return false; + if (_tab != tabs[index]) setState(() => _tab = tabs[index]); + return true; } @override @@ -136,6 +151,7 @@ class _RunDetailTabsState extends State { @override void dispose() { + HardwareKeyboard.instance.removeHandler(_tabDigitKey); _inputSection.dispose(); _outputSection.dispose(); _liveRun.dispose(); diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 41ec8006..64ce90d7 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -4,6 +4,7 @@ import '../chat/workspace/chat_center_stage_controller.dart'; import '../chat/workspace/chat_float_shortcut.dart'; import '../terminal/terminal_shortcuts.dart'; import '../../shell/windows/window_shortcuts.dart'; +import '../../shell/shell_chat_actions_shortcut.dart'; import '../../shell/shell_chat_shortcut.dart'; import '../../shell/shell_cheatsheet_shortcut.dart'; import '../../shell/shell_runs_pipelines_shortcut.dart'; @@ -114,7 +115,21 @@ class KeyboardShortcutRegistry { action: 'Switch to another chat', keys: shellChatShortcutLabels(platform).join(', '), caveat: - 'On Chat: type to filter the open chats, Ctrl+N or Down and Ctrl+P or Up to move, Enter to open, Esc or the shortcut again to close.${web ? ' A browser tab keeps Ctrl+N (new window) for itself; use Down, or the installed app.' : ''}', + 'On Chat: the open chats, most recently used first, with the previous chat selected, so the shortcut then Enter goes back to it. Type to filter (matching closed chats are listed under Closed; Enter reopens one), Ctrl+N or Down and Ctrl+P or Up to move, Enter to open, Esc or the shortcut again to close.${web ? ' A browser tab keeps Ctrl+N (new window) for itself; use Down, or the installed app.' : ''}', + ), + KeyboardShortcutEntry( + group: KeyboardShortcutGroup.chat, + action: 'New chat', + keys: shellChatActionLabel(ShellChatAction.newChat, platform), + caveat: + 'From any destination. In the terminal the key goes to the terminal.', + ), + KeyboardShortcutEntry( + group: KeyboardShortcutGroup.chat, + action: 'Next chat needing you', + keys: shellChatActionLabel(ShellChatAction.nextAttention, platform), + caveat: + 'Opens the next chat waiting for you, with unread replies, or with a failed action, in list order; press again to cycle. In the terminal the key goes to the terminal.', ), KeyboardShortcutEntry( group: KeyboardShortcutGroup.chat, @@ -273,6 +288,13 @@ class KeyboardShortcutRegistry { caveat: 'Available when the Chat list is mounted; numbers select its visible item.', ), + const KeyboardShortcutEntry( + group: KeyboardShortcutGroup.lists, + action: 'Switch run detail tabs', + keys: '1, 2, 3, 4', + caveat: + 'In a run: Summary, Timeline, Artifacts, Changes, as the run offers them. Not while typing.', + ), const KeyboardShortcutEntry( group: KeyboardShortcutGroup.lists, action: 'Resize a list pane', diff --git a/app/lib/shell/adaptive_shell.dart b/app/lib/shell/adaptive_shell.dart index f5a2be80..8bef446f 100644 --- a/app/lib/shell/adaptive_shell.dart +++ b/app/lib/shell/adaptive_shell.dart @@ -12,6 +12,7 @@ import 'shell_navigation_bar.dart'; import 'shell_rail_scope.dart'; import 'list_pane_widths.dart'; import 'shell_bar.dart'; +import 'shell_chat_actions_shortcut.dart'; import 'shell_chat_shortcut.dart'; import 'shell_cheatsheet.dart'; import 'shell_cheatsheet_shortcut.dart'; @@ -33,6 +34,7 @@ class AdaptiveShell extends StatefulWidget { this.onSearch, this.onOpenChat, this.onChatQuickSwitch, + this.onChatAction, this.attentionCount = 0, this.runningRunCount, this.listPaneWidthStore = const SharedPreferencesListPaneWidthStore(), @@ -77,6 +79,11 @@ class AdaptiveShell extends StatefulWidget { /// the composer focus of [onOpenChat] there too. final VoidCallback? onChatQuickSwitch; + /// Runs after Alt+N or Alt+J (see [shellChatActionShortcut]) has shown the + /// Chat destination: the host starts a new chat or opens the next chat + /// needing the operator. Null leaves both chords unhandled. + final ValueChanged? onChatAction; + /// Runs needing the operator today, retained in the tab's accessible label. final int attentionCount; @@ -410,8 +417,20 @@ class _AdaptiveShellState extends State { } return true; } - // A terminal keeps its keys (Escape, Ctrl+/, Ctrl+digits). + // A terminal keeps its keys (Escape, Ctrl+/, Ctrl+digits, Alt+N, Alt+J). if (primaryFocusIsTypingSurface()) return false; + final chatAction = widget.onChatAction == null + ? null + : shellChatActionShortcut(event, keyboard); + if (chatAction != null) { + // A dialog or popup over the shell keeps its keys. + if (!_shellRouteHasKeyboard()) return false; + if (event is KeyDownEvent) { + if (_selected != AppDestination.chat) _select(AppDestination.chat); + widget.onChatAction!(chatAction); + } + return true; + } if (_selected == AppDestination.search && event is KeyDownEvent && event.logicalKey == LogicalKeyboardKey.escape && @@ -450,6 +469,16 @@ class _AdaptiveShellState extends State { widget.onOpenChat?.call(); } + /// Whether the keyboard is outside any dialog, sheet or menu (a page, such + /// as a phone's open chat, is fine). + bool _shellRouteHasKeyboard() { + final focusedContext = FocusManager.instance.primaryFocus?.context; + final focusedRoute = focusedContext == null + ? null + : ModalRoute.of(focusedContext); + return focusedRoute is! PopupRoute; + } + /// A popup or nested viewer owns Escape before the underlying Search tab. bool _searchEscape() { final route = ModalRoute.of(context); diff --git a/app/lib/shell/shell_chat_actions_shortcut.dart b/app/lib/shell/shell_chat_actions_shortcut.dart new file mode 100644 index 00000000..b3692be5 --- /dev/null +++ b/app/lib/shell/shell_chat_actions_shortcut.dart @@ -0,0 +1,56 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// The app-wide chat actions bound to a bare Alt chord (Option on a Mac). +enum ShellChatAction { + /// Alt+N: a new chat, with the Chat list's create dialog. + newChat, + + /// Alt+J: the next chat waiting for the operator, unread or failed. + nextAttention, +} + +/// The chat action [event] asks for, or null: Alt+N or Alt+J with no other +/// modifier. Option+N and Option+J yield a dead key or a symbol on a Mac, so +/// the key is matched by position as well. Repeats of a held chord match too, +/// so the caller can swallow them; only the first press acts. +/// +/// Neither chord is taken by Chromium, Firefox or Safari on Linux, Windows or +/// macOS, nor by the app's other shortcuts (Alt+K, Alt+T, Alt+Y, Alt+E, +/// Alt+`, Alt+/). The terminal keeps both for readline (Alt+N searches +/// history), so the caller leaves them to it while it has the keyboard. +ShellChatAction? shellChatActionShortcut( + KeyEvent event, + HardwareKeyboard keyboard, +) { + if (event is KeyUpEvent || + !keyboard.isAltPressed || + keyboard.isControlPressed || + keyboard.isMetaPressed || + keyboard.isShiftPressed) { + return null; + } + bool key(LogicalKeyboardKey logical, PhysicalKeyboardKey physical) => + event.logicalKey == logical || event.physicalKey == physical; + if (key(LogicalKeyboardKey.keyN, PhysicalKeyboardKey.keyN)) { + return ShellChatAction.newChat; + } + if (key(LogicalKeyboardKey.keyJ, PhysicalKeyboardKey.keyJ)) { + return ShellChatAction.nextAttention; + } + return null; +} + +/// [action]'s chord as it reads on [platform], for the help page. +String shellChatActionLabel( + ShellChatAction action, [ + TargetPlatform? platform, +]) { + final target = platform ?? defaultTargetPlatform; + final apple = target == TargetPlatform.macOS || target == TargetPlatform.iOS; + final letter = switch (action) { + ShellChatAction.newChat => 'N', + ShellChatAction.nextAttention => 'J', + }; + return '${apple ? 'Option' : 'Alt'}+$letter'; +} diff --git a/app/test/application/chat_quick_switch_shortcut_test.dart b/app/test/application/chat_quick_switch_shortcut_test.dart index 57482659..4ef9af04 100644 --- a/app/test/application/chat_quick_switch_shortcut_test.dart +++ b/app/test/application/chat_quick_switch_shortcut_test.dart @@ -13,7 +13,11 @@ import 'chat_registration_test.dart' final _field = find.byKey(const Key('chat-quick-switch-field')); -Future _replySessions(WidgetTester tester, FakeChannel channel) async { +Future _replySessions( + WidgetTester tester, + FakeChannel channel, { + bool awaiting = false, +}) async { final request = await waitForRequest(tester, channel, 'chat_sessions'); channel.incoming.add( jsonEncode({ @@ -22,7 +26,12 @@ Future _replySessions(WidgetTester tester, FakeChannel channel) async { 'chat_sessions': [ {'id': 's1', 'title': 'Wire chat', 'directory': '/workspace/demo'}, {'id': 's2', 'title': 'Second chat', 'directory': '/workspace/other'}, - {'id': 's3', 'title': 'Third chat', 'directory': '/workspace/demo'}, + { + 'id': 's3', + 'title': 'Third chat', + 'directory': '/workspace/demo', + if (awaiting) 'activity': {'awaiting_operator': 1, 'seq': 1}, + }, ], }), ); @@ -31,8 +40,9 @@ Future _replySessions(WidgetTester tester, FakeChannel channel) async { Future _mountOnChat( WidgetTester tester, - PlatformRouteInformationProvider provider, -) async { + PlatformRouteInformationProvider provider, { + bool awaiting = false, +}) async { tester.view.physicalSize = const Size(1200, 900); tester.view.devicePixelRatio = 1; addTearDown(tester.view.resetPhysicalSize); @@ -48,10 +58,15 @@ Future _mountOnChat( ), ); await tester.pump(); - await _replySessions(tester, channel); + await _replySessions(tester, channel, awaiting: awaiting); await replySubscribe(tester, channel); await replyHistory(tester, channel); - await tester.pumpAndSettle(); + // A chat waiting for the operator pulses its badge, so it never settles. + if (awaiting) { + await tester.pump(const Duration(seconds: 1)); + } else { + await tester.pumpAndSettle(); + } expect(find.byType(ChatThreadView), findsOneWidget); return channel; } @@ -149,6 +164,81 @@ void main() { await _teardown(tester); }); + testWidgets('the shortcut then Enter returns to the previous chat', ( + tester, + ) async { + final provider = _provider(); + final channel = await _mountOnChat(tester, provider); + await _chord(tester, LogicalKeyboardKey.controlLeft); + await tester.enterText(_field, 'second'); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pump(); + await replySubscribe(tester, channel, index: 1); + await replyHistory(tester, channel, index: 1); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat/s2'); + + await _chord(tester, LogicalKeyboardKey.controlLeft); + // Most recent first: the open chat, then the one before it, selected. + final rows = tester + .widgetList( + find.byWidgetPredicate( + (w) => + w is ListTile && '${w.key}'.contains('chat-quick-switch-row'), + ), + ) + .toList(); + expect( + rows.map((tile) => '${tile.key}'.split('row-').last.split("'").first), + ['s2', 's1', 's3'], + ); + expect(rows[1].selected, isTrue); + await tester.sendKeyEvent(LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(provider.value.uri.path, '/chat/s1'); + await _teardown(tester); + }); + + testWidgets('Alt+J opens the next chat waiting for you', (tester) async { + final provider = _provider(); + final channel = await _mountOnChat(tester, provider, awaiting: true); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyJ); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + await tester.pump(); + await replySubscribe(tester, channel, index: 1); + await replyHistory(tester, channel, index: 1); + await tester.pump(const Duration(seconds: 1)); + expect(provider.value.uri.path, '/chat/s3'); + + // Only the open chat needs you now: nothing else to go to. + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyJ); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + await tester.pump(); + expect(provider.value.uri.path, '/chat/s3'); + expect(find.text('No other chat needs you.'), findsOneWidget); + await _teardown(tester); + }); + + testWidgets('Alt+N from Runs opens New chat', (tester) async { + await _mountOnChat(tester, _provider()); + await tester.tap(find.byKey(const ValueKey('shell.destination.runs'))); + await tester.pump(const Duration(milliseconds: 600)); + FocusManager.instance.primaryFocus?.unfocus(); + await tester.pump(); + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.keyN); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); + await tester.pump(const Duration(milliseconds: 600)); + expect(find.byType(Dialog), findsOneWidget); + await _teardown(tester); + }); + testWidgets('elsewhere the shortcut still jumps to Chat', (tester) async { final provider = _provider(); await _mountOnChat(tester, provider); diff --git a/app/test/features/chat/conversation/chat_quick_switch_dialog_test.dart b/app/test/features/chat/conversation/chat_quick_switch_dialog_test.dart index 0bcdd428..1128f1ae 100644 --- a/app/test/features/chat/conversation/chat_quick_switch_dialog_test.dart +++ b/app/test/features/chat/conversation/chat_quick_switch_dialog_test.dart @@ -31,6 +31,8 @@ class _Switcher { Future<_Switcher> _open( WidgetTester tester, { Size size = const Size(900, 800), + List recent = const [], + String? currentId, }) async { tester.view.physicalSize = size; tester.view.devicePixelRatio = 1; @@ -54,6 +56,8 @@ Future<_Switcher> _open( onPressed: () => switcher.route = showChatQuickSwitch( context, sessions: controller, + recent: () => recent, + currentId: currentId, onSelected: (row) => switcher.chosen.add('${row['id']}'), ), child: const Text('Open'), @@ -162,8 +166,20 @@ void main() { 'build', ); await tester.pump(); - // The closed chat titled "Closed build" is not offered. - expect(_shown(tester), ['one']); + // The closed chat titled "Closed build" follows under Closed. + expect(_shown(tester), ['one', 'gone']); + expect( + find.byKey(const Key('chat-quick-switch-closed-header')), + findsOneWidget, + ); + expect( + tester.getTopLeft(find.text('Closed')).dy, + lessThan( + tester + .getTopLeft(find.byKey(const Key('chat-quick-switch-row-gone'))) + .dy, + ), + ); await tester.enterText( find.byKey(const Key('chat-quick-switch-field')), 'zzz', @@ -213,6 +229,38 @@ void main() { await tester.pump(); }); + testWidgets( + 'no query: most recent first, the previous chat selected; Enter goes back', + (tester) async { + final switcher = await _open( + tester, + recent: ['three', 'two'], + currentId: 'three', + ); + expect(_shown(tester), ['three', 'two', 'one']); + expect(_selected(tester), 'two'); + await _key(tester, LogicalKeyboardKey.enter); + await tester.pumpAndSettle(); + expect(switcher.chosen, ['two']); + }, + ); + + testWidgets('rows mark working, needs you and unread chats', (tester) async { + await _open(tester); + final two = find.byKey(const Key('chat-quick-switch-row-two')); + expect( + find.descendant( + of: two, + matching: find.byKey(const Key('chat-quick-switch-marker-working')), + ), + findsOneWidget, + ); + expect( + find.byKey(const Key('chat-quick-switch-marker-needsYou')), + findsNothing, + ); + }); + testWidgets('a phone shows it as a full-width bottom sheet', (tester) async { await _open(tester, size: const Size(400, 800)); expect(find.byType(Dialog), findsNothing); diff --git a/app/test/features/chat/data/chat_recency_test.dart b/app/test/features/chat/data/chat_recency_test.dart new file mode 100644 index 00000000..d0f3c970 --- /dev/null +++ b/app/test/features/chat/data/chat_recency_test.dart @@ -0,0 +1,44 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/chat/data/chat_recency.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + test('touch moves a chat to the front and persists the order', () async { + final store = MemoryChatRecencyStore(['b', 'a']); + final recency = ChatRecency(store: store); + await recency.load(); + expect(recency.ids, ['b', 'a']); + recency.touch('a'); + recency.touch('c'); + expect(recency.ids, ['c', 'a', 'b']); + await Future.delayed(Duration.zero); + expect(store.ids, ['c', 'a', 'b']); + }); + + test('a chat touched before the read stays in front', () async { + final recency = ChatRecency(store: MemoryChatRecencyStore(['b', 'a'])); + recency.touch('a'); + await recency.load(); + expect(recency.ids, ['a', 'b']); + }); + + test('keeps at most the limit', () async { + final recency = ChatRecency(limit: 2); + for (final id in ['a', 'b', 'c']) { + recency.touch(id); + } + expect(recency.ids, ['c', 'b']); + }); + + test('shared preferences keep the order per server', () async { + SharedPreferences.setMockInitialValues({}); + const one = SharedPreferencesChatRecencyStore(serverScope: 'one'); + const two = SharedPreferencesChatRecencyStore(serverScope: 'two'); + await one.write(['x', 'y']); + expect(await one.read(), ['x', 'y']); + expect(await two.read(), isEmpty); + final reloaded = ChatRecency(store: one); + await reloaded.load(); + expect(reloaded.ids, ['x', 'y']); + }); +} diff --git a/app/test/features/chat/domain/chat_quick_switch_order_test.dart b/app/test/features/chat/domain/chat_quick_switch_order_test.dart new file mode 100644 index 00000000..c0866394 --- /dev/null +++ b/app/test/features/chat/domain/chat_quick_switch_order_test.dart @@ -0,0 +1,113 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/domain/chat_attention_cycle.dart'; +import 'package:pipelines_app/features/chat/domain/chat_quick_switch_order.dart'; + +List ids(List rows) => [ + for (final row in rows) '${row['id']}', +]; + +void main() { + final rows = [ + {'id': 'a', 'title': 'A'}, + {'id': 'b', 'title': 'B'}, + {'id': 'c', 'title': 'C'}, + {'id': 'd', 'title': 'D'}, + ]; + + test('recently used chats lead, the rest keep their order', () { + expect(ids(chatQuickSwitchByRecency(rows, ['c', 'x', 'a'])), [ + 'c', + 'a', + 'b', + 'd', + ]); + expect(ids(chatQuickSwitchByRecency(rows, const [])), ['a', 'b', 'c', 'd']); + }); + + test('no query selects the chat used before the current one', () { + final shown = chatQuickSwitchByRecency(rows, ['c', 'a']); + expect( + chatQuickSwitchInitialSelection(shown, currentId: 'c', emptyQuery: true), + 1, + ); + // Not showing a chat: the most recent one. + expect( + chatQuickSwitchInitialSelection(shown, currentId: null, emptyQuery: true), + 0, + ); + // A query selects the best match, even the current chat. + expect( + chatQuickSwitchInitialSelection(shown, currentId: 'c', emptyQuery: false), + 0, + ); + expect( + chatQuickSwitchInitialSelection( + [rows.first], + currentId: 'a', + emptyQuery: true, + ), + 0, + ); + }); + + test('closed chats, most recently closed first', () { + expect( + ids( + chatQuickSwitchClosed([ + ...rows, + {'id': 'old', 'closed_at': 1}, + {'id': 'new', 'closed_at': 9}, + {'id': 'flag', 'closed': true}, + ]), + ), + ['new', 'old', 'flag'], + ); + }); + + test('markers: needs you, working, unread', () { + expect( + chatQuickSwitchMarkers({ + 'awaiting_operator': 2, + 'running': true, + }, unread: true), + [ + ChatQuickSwitchMarker.needsYou, + ChatQuickSwitchMarker.working, + ChatQuickSwitchMarker.unread, + ], + ); + expect(chatQuickSwitchMarkers({'id': 'a'}, unread: false), isEmpty); + }); + + group('next chat needing attention', () { + final sessions = [ + {'id': 'a', 'title': 'A', 'directory': '/x'}, + {'id': 'b', 'title': 'B', 'directory': '/x', 'awaiting_operator': 1}, + {'id': 'c', 'title': 'C', 'directory': '/x'}, + {'id': 'd', 'title': 'D', 'directory': '/x'}, + {'id': 'e', 'title': 'E', 'closed_at': 3, 'awaiting_operator': 1}, + ]; + const unread = {'d'}; + const failed = {'a'}; + bool needs(JsonMap row) => chatNeedsAttention( + row, + unread: unread.contains(row['id']), + failed: failed.contains(row['id']), + ); + + test('cycles in list order, wrapping, skipping closed chats', () { + expect(chatNextNeedingAttention(sessions, 'a', needs)?['id'], 'b'); + expect(chatNextNeedingAttention(sessions, 'b', needs)?['id'], 'd'); + expect(chatNextNeedingAttention(sessions, 'd', needs)?['id'], 'a'); + expect(chatNextNeedingAttention(sessions, 'c', needs)?['id'], 'd'); + expect(chatNextNeedingAttention(sessions, null, needs)?['id'], 'a'); + }); + + test('null when only the current chat needs the operator', () { + bool onlyB(JsonMap row) => row['id'] == 'b'; + expect(chatNextNeedingAttention(sessions, 'b', onlyB), isNull); + expect(chatNextNeedingAttention(sessions, 'a', onlyB)?['id'], 'b'); + }); + }); +} diff --git a/app/test/features/runs/ui/run_detail_tab_keys_test.dart b/app/test/features/runs/ui/run_detail_tab_keys_test.dart new file mode 100644 index 00000000..9a0da857 --- /dev/null +++ b/app/test/features/runs/ui/run_detail_tab_keys_test.dart @@ -0,0 +1,72 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart'; + +import 'run_detail_graph_support.dart'; + +int _current(WidgetTester tester) => tester + .widget( + find.descendant( + of: find.byKey(const Key('run-detail-tabs')), + matching: find.byType(FloatingDestinationBar), + ), + ) + .currentIndex; + +void main() { + testWidgets('bare 1-4 switch the run detail tabs', (tester) async { + await pumpRunDetail(tester, RunDetailTestPlatform.material); + expect(_current(tester), 0); + await tester.sendKeyEvent(LogicalKeyboardKey.digit2); + await tester.pump(); + expect(_current(tester), 1); + await tester.sendKeyEvent(LogicalKeyboardKey.numpad1); + await tester.pump(); + expect(_current(tester), 0); + }); + + testWidgets('a modifier or a focused text field keeps the digit', ( + tester, + ) async { + await pumpRunDetail(tester, RunDetailTestPlatform.material); + await tester.sendKeyDownEvent(LogicalKeyboardKey.controlLeft); + await tester.sendKeyEvent(LogicalKeyboardKey.digit2); + await tester.sendKeyUpEvent(LogicalKeyboardKey.controlLeft); + await tester.pump(); + expect(_current(tester), 0); + + // A text field over the detail (in an overlay of the same route) types. + final field = TextEditingController(); + addTearDown(field.dispose); + final overlay = OverlayEntry( + builder: (_) => Material( + child: TextField(key: const Key('probe-field'), controller: field), + ), + ); + Overlay.of( + tester.element(find.byKey(const Key('run-detail-tabs'))), + ).insert(overlay); + await tester.pump(); + await tester.tap(find.byKey(const Key('probe-field'))); + await tester.pump(); + await tester.sendKeyEvent(LogicalKeyboardKey.digit2); + await tester.pump(); + expect(_current(tester), 0); + overlay.remove(); + }); + + testWidgets('a dialog over the run keeps the digits', (tester) async { + await pumpRunDetail(tester, RunDetailTestPlatform.material); + showDialog( + context: tester.element(find.byKey(const Key('run-detail-tabs'))), + builder: (_) => const AlertDialog(content: Text('Over')), + ); + await tester.pumpAndSettle(); + await tester.sendKeyEvent(LogicalKeyboardKey.digit2); + await tester.pump(); + Navigator.of(tester.element(find.text('Over'))).pop(); + await tester.pumpAndSettle(); + expect(_current(tester), 0); + }); +} diff --git a/app/test/shell/shell_chat_actions_shortcut_test.dart b/app/test/shell/shell_chat_actions_shortcut_test.dart new file mode 100644 index 00000000..2468c609 --- /dev/null +++ b/app/test/shell/shell_chat_actions_shortcut_test.dart @@ -0,0 +1,119 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/shell/adaptive_shell.dart'; +import 'package:pipelines_app/shell/destination.dart'; +import 'package:pipelines_app/shell/shell_chat_actions_shortcut.dart'; +import 'package:pipelines_app/ui/input/keyboard_owner.dart'; + +KeyDownEvent _down(PhysicalKeyboardKey physical, LogicalKeyboardKey logical) => + KeyDownEvent( + physicalKey: physical, + logicalKey: logical, + timeStamp: Duration.zero, + ); + +final _n = _down(PhysicalKeyboardKey.keyN, LogicalKeyboardKey.keyN); +final _j = _down(PhysicalKeyboardKey.keyJ, LogicalKeyboardKey.keyJ); + +Future _alt(WidgetTester tester, LogicalKeyboardKey key) async { + await tester.sendKeyDownEvent(LogicalKeyboardKey.altLeft); + await tester.sendKeyEvent(key); + await tester.sendKeyUpEvent(LogicalKeyboardKey.altLeft); + await tester.pump(); +} + +void main() { + test('Alt+N is New chat and Alt+J the next chat needing you, alone', () { + ShellChatAction? chord(Set held, KeyEvent event) => + shellChatActionShortcut(event, _FakeKeyboard(held)); + const alt = LogicalKeyboardKey.altLeft; + expect(chord({alt}, _n), ShellChatAction.newChat); + expect(chord({alt}, _j), ShellChatAction.nextAttention); + expect(chord({}, _n), isNull); + expect(chord({alt, LogicalKeyboardKey.shiftLeft}, _n), isNull); + expect(chord({alt, LogicalKeyboardKey.controlLeft}, _j), isNull); + expect(chord({alt, LogicalKeyboardKey.metaLeft}, _j), isNull); + expect(chord({LogicalKeyboardKey.controlLeft}, _n), isNull); + // Option+N is a dead key (˜) on a Mac: matched by position. + final dead = _down( + PhysicalKeyboardKey.keyN, + const LogicalKeyboardKey(0x02dc), + ); + expect(chord({alt}, dead), ShellChatAction.newChat); + expect( + shellChatActionLabel(ShellChatAction.newChat, TargetPlatform.macOS), + 'Option+N', + ); + expect( + shellChatActionLabel(ShellChatAction.nextAttention, TargetPlatform.linux), + 'Alt+J', + ); + }); + + testWidgets('the chords show Chat and report the action; the terminal ' + 'keeps them', (tester) async { + final terminal = FocusNode(); + addTearDown(terminal.dispose); + final actions = []; + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + onChatAction: actions.add, + destinationBodies: { + AppDestination.pipelines: (_) => TypingSurface( + child: Focus(focusNode: terminal, child: const Text('terminal')), + ), + AppDestination.chat: (_) => const Text('chat body'), + }, + ), + ), + ); + terminal.requestFocus(); + await tester.pump(); + await _alt(tester, LogicalKeyboardKey.keyN); + expect(actions, isEmpty); + expect(find.text('chat body'), findsNothing); + + terminal.unfocus(); + await tester.pump(); + await _alt(tester, LogicalKeyboardKey.keyJ); + expect(actions, [ShellChatAction.nextAttention]); + expect(find.text('chat body'), isOnstage); + await _alt(tester, LogicalKeyboardKey.keyN); + expect(actions, [ShellChatAction.nextAttention, ShellChatAction.newChat]); + }); + + testWidgets('a dialog keeps the chords', (tester) async { + final actions = []; + await tester.pumpWidget( + MaterialApp( + home: AdaptiveShell( + onChatAction: actions.add, + destinationBodies: { + AppDestination.pipelines: (context) => TextButton( + onPressed: () => showDialog( + context: context, + builder: (_) => + const AlertDialog(content: TextField(autofocus: true)), + ), + child: const Text('dialog'), + ), + AppDestination.chat: (_) => const Text('chat body'), + }, + ), + ), + ); + await tester.tap(find.text('dialog')); + await tester.pumpAndSettle(); + await _alt(tester, LogicalKeyboardKey.keyN); + expect(actions, isEmpty); + }); +} + +class _FakeKeyboard extends HardwareKeyboard { + _FakeKeyboard(this.pressed); + final Set pressed; + @override + bool isLogicalKeyPressed(LogicalKeyboardKey key) => pressed.contains(key); +} diff --git a/app/tool/capture/examples/chat-quick-switch-recent.json b/app/tool/capture/examples/chat-quick-switch-recent.json new file mode 100644 index 00000000..88d08101 --- /dev/null +++ b/app/tool/capture/examples/chat-quick-switch-recent.json @@ -0,0 +1,25 @@ +{ + "size": "1440x1000", + "params": "chats=8&colors=1&activity=1&closed=2", + "steps": [ + { "open": "/chat/perf-chat-1" }, + { "wait": 1500 }, + { "press": "Alt+k", "wait": 800 }, + { "type": "billing", "wait": 500 }, + { "press": "Enter", "wait": 1200 }, + { "press": "Alt+k", "wait": 800 }, + { "shot": "recent-first-previous-selected" }, + { "press": "Enter", "wait": 1200 }, + { "shot": "back-to-previous" }, + { "press": "Alt+k", "wait": 800 }, + { "type": "s", "wait": 500 }, + { "shot": "closed-section" }, + { "type": "earch", "wait": 400 }, + { "press": "Enter", "wait": 1500 }, + { "shot": "closed-reopened" }, + { "press": "Alt+j", "wait": 1500 }, + { "shot": "alt-j-needs-you" }, + { "press": "Alt+n", "wait": 1200 }, + { "shot": "alt-n-new-chat" } + ] +} diff --git a/app/tool/perf/perf_fixture.dart b/app/tool/perf/perf_fixture.dart index ed38738f..62409f43 100644 --- a/app/tool/perf/perf_fixture.dart +++ b/app/tool/perf/perf_fixture.dart @@ -17,6 +17,8 @@ // them, and keeps colours picked with chat_color; // `?activity=1` (with `?chats=N`) lists a running chat, one with // background tasks and idle ones; +// `?closed=N` (with `?chats=N`) closes the last N chats (chat_reopen +// reopens one); // `?automations=N` reports N native automations for the selected chat; // `?msgs=`, `?rich=1`, `?older=1`, `?live=N` vary the chat transcripts for // scroll captures (tool/perf/chat_scroll_fixture.dart). @@ -91,8 +93,22 @@ const _colorNames = ['teal', 'purple', null, 'amber', 'red', null, 'blue']; final Map _pickedColors = {}; final _chatCatalog = ChatCatalogFixture(); +/// `?closed=N` (with `?chats=N`): the last N chats are closed until +/// chat_reopen reopens one. +int get _closedCount => int.tryParse(_params['closed'] ?? '') ?? 0; +final Set _reopened = {}; + JsonMap _chatRow(int i) { final id = perfChatId(i); + final closed = i >= _chats - _closedCount && !_reopened.contains(id); + return { + ..._openChatRow(i, id), + if (closed) + 'closed_at': DateTime.now().millisecondsSinceEpoch - (i + 1) * 60000, + }; +} + +JsonMap _openChatRow(int i, String id) { if (!_colors) { return { 'id': id, @@ -305,6 +321,10 @@ JsonMap? perfChatReply(JsonMap request) { 'type': 'chat_sessions', 'chat_sessions': [for (var i = 0; i < _chats; i++) _chatRow(i)], }; + case 'chat_reopen': + final query = request['chat_query']; + _reopened.add(query is Map ? '${query['session_id'] ?? ''}' : ''); + return {'id': id, 'type': 'chat_reopen'}; case 'chat_color': final query = request['chat_query']; final session = query is Map ? '${query['session_id'] ?? ''}' : ''; From a6db4ba20e5d5594ecb2463f18b0836470754c1a Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:55:50 +0000 Subject: [PATCH 16/19] App: run tabs under the header on wide layouts, stable Artifacts tab, spelled-out pipeline status, shared list selection, code block header and edge fades MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Run detail: on a wide window (>= 840, pane >= 600) the tabs are Material segments under the run header; phones keep the floating bottom bar. Artifacts is always a tab, badged with its count and disabled with 0 (its tooltip says why), so Changes never moves. - Pipelines list: 'Failed · last run 19 Oct' beside the status dot; facts on the next line; compact rows keep 'Failed · 19 Oct'. - Settings: Disconnect is outlined beside a tonal Reconnect. - Lists: one selection style (tonal fill plus one leading accent bar) for runs, pipelines and chats; chat's border, fill and pointer removed. - Transcript: overflowing blocks fade at the edge with a chevron instead of a 'Scroll horizontally' line (semantics hint kept); code blocks get a header strip with language and Copy; lighter light-mode code fill. - Runs list: rows under a day heading show only the time of day. - Artifact search reveal re-centres once the lazy list's extent settles. Co-Authored-By: Claude Opus 5.5 --- .../artifacts/ui/artifact_gallery_action.dart | 7 ++ .../artifacts/ui/artifact_visit_reveal.dart | 10 +- .../ui/sessions/chat_compact_sidebar.dart | 14 ++- .../ui/sessions/chat_visibility_marker.dart | 92 +++--------------- .../chat/ui/sessions/session_row_content.dart | 11 ++- .../chat/ui/transcript/chat_code_hover.dart | 97 +++++++++++-------- .../transcript/chat_horizontal_viewport.dart | 93 ++++++++++++------ .../ui/transcript/chat_markdown_view.dart | 25 +++-- .../features/pipelines/pipeline_query.dart | 10 ++ .../widgets/pipeline_list_panel.dart | 36 +++++-- app/lib/features/runs/domain/run_models.dart | 7 ++ .../runs/ui/run_detail_tab_strip.dart | 59 +++++++++-- app/lib/features/runs/ui/run_detail_tabs.dart | 75 +++++++++----- .../features/runs/ui/run_detail_top_tabs.dart | 82 ++++++++++++++++ .../runs/ui/run_detail_wide_chrome.dart | 88 +++++++---------- app/lib/features/runs/ui/run_list_row.dart | 7 ++ app/lib/features/runs/ui/runs_list.dart | 27 +++++- .../features/settings/settings_controls.dart | 49 +++++++--- .../features/settings/settings_sections.dart | 2 + .../ui/adaptive/floating_destination_bar.dart | 13 +++ .../adaptive/floating_destination_labels.dart | 11 ++- app/lib/ui/adaptive/floating_tab_button.dart | 18 +++- app/lib/ui/layout/app_list_row.dart | 36 ++++++- .../chat/chat_open_transition_test.dart | 4 +- .../sessions/chat_active_selection_test.dart | 14 ++- .../chat/ui/sessions/chat_color_test.dart | 18 ++-- .../sessions/chat_visibility_marker_test.dart | 42 ++++++-- .../ui/transcript/chat_code_hover_test.dart | 59 +++++------ .../chat_horizontal_viewport_test.dart | 24 +++-- .../chat_markdown_table_wrap_test.dart | 6 +- .../pipeline_list_composition_test.dart | 15 ++- .../runs/ui/run_artifacts_action_test.dart | 61 +++++++----- .../runs/ui/run_detail_flat_bodies_test.dart | 18 ++-- .../runs/ui/run_detail_tabs_test.dart | 32 +++--- .../features/runs/ui/run_list_row_test.dart | 26 +++++ .../settings/settings_actions_test.dart | 49 ++++++++++ app/test/ui/layout/app_list_row_test.dart | 10 ++ 37 files changed, 848 insertions(+), 399 deletions(-) create mode 100644 app/lib/features/runs/ui/run_detail_top_tabs.dart create mode 100644 app/test/features/settings/settings_actions_test.dart diff --git a/app/lib/features/artifacts/ui/artifact_gallery_action.dart b/app/lib/features/artifacts/ui/artifact_gallery_action.dart index 8e02ad41..e6bbe5fc 100644 --- a/app/lib/features/artifacts/ui/artifact_gallery_action.dart +++ b/app/lib/features/artifacts/ui/artifact_gallery_action.dart @@ -3,6 +3,7 @@ import 'package:flutter/material.dart'; import '../../../core/api_gateway.dart'; import '../../../core/transport/pipelines_client.dart'; import '../domain/artifact_chat_context.dart'; +import '../domain/artifact_groups.dart'; import 'artifact_external_open.dart'; import 'artifact_gallery_page.dart'; @@ -28,6 +29,12 @@ List runDetailArtifactSteps(JsonMap run) { bool showRunArtifactsAction(JsonMap run) => runDetailArtifactSteps(run).isNotEmpty; +/// How many recorded entries the run's gallery lists (stage files plus +/// recorded turn documents), as the gallery header counts them. +int runArtifactCount(JsonMap run) => galleryGroups( + runDetailArtifactSteps(run), +).fold(0, (sum, group) => sum + group.recordedCount); + /// Whether the run is still executing, so the page can say capture pending /// instead of claiming nothing was recorded. bool runDetailExecuting(JsonMap run) => _runExecuting(run); diff --git a/app/lib/features/artifacts/ui/artifact_visit_reveal.dart b/app/lib/features/artifacts/ui/artifact_visit_reveal.dart index 1d56e72d..3a6f910e 100644 --- a/app/lib/features/artifacts/ui/artifact_visit_reveal.dart +++ b/app/lib/features/artifacts/ui/artifact_visit_reveal.dart @@ -28,7 +28,15 @@ class ArtifactVisitReveal { final row = target.currentContext; if (row != null && row.mounted) { Scrollable.ensureVisible(row, alignment: 0.5); - onDone(); + // The lazy list's extent is an estimate until the rows past the + // target are laid out; a row near the end, clamped to that estimate, + // is centred again once the next frame has measured them. + WidgetsBinding.instance.addPostFrameCallback((_) { + if (generation != _generation) return; + if (row.mounted) Scrollable.ensureVisible(row, alignment: 0.5); + onDone(); + }); + WidgetsBinding.instance.scheduleFrame(); return; } final anchorContext = anchor.currentContext; diff --git a/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart b/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart index 1e60be0e..53b2b3d4 100644 --- a/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart +++ b/app/lib/features/chat/ui/sessions/chat_compact_sidebar.dart @@ -1,3 +1,4 @@ +import '../../../../ui/layout/app_list_row.dart'; import '../../../../core/servers/chat/federated_chat_gateway.dart'; import '../../../../core/servers/server_context.dart'; import 'dart:async'; @@ -127,7 +128,18 @@ class ChatCompactSidebar extends StatelessWidget { duration: MediaQuery.disableAnimationsOf(context) ? Duration.zero : const Duration(milliseconds: 200), - color: selected ? Colors.transparent : color.withValues(alpha: .07), + // The lists' shared open-row style: the tonal fill and one leading + // bar in the chat's colour. + color: selected + ? AppListRow.selectedColor(context) + : color.withValues(alpha: .07), + foregroundDecoration: selected + ? BoxDecoration( + border: BorderDirectional( + start: BorderSide(color: color, width: kAppListRowBarWidth), + ), + ) + : null, child: Draggable( // A mouse drags at once (a click still opens the chat); the chip // follows the pointer. diff --git a/app/lib/features/chat/ui/sessions/chat_visibility_marker.dart b/app/lib/features/chat/ui/sessions/chat_visibility_marker.dart index d7d4b895..3458f2f8 100644 --- a/app/lib/features/chat/ui/sessions/chat_visibility_marker.dart +++ b/app/lib/features/chat/ui/sessions/chat_visibility_marker.dart @@ -1,8 +1,10 @@ import 'package:flutter/material.dart'; -import 'chat_color_palette.dart'; /// A chat's colour identifies it; this animated edge identifies where it is -/// visible. The active chat has a stronger edge in both list presentations. +/// visible. A chat shown in another pane (visible, not the open one) keeps a +/// thin leading bar. The open chat is marked by the lists' shared selection +/// style on its row (`AppListRow.selected`: tonal fill and one leading bar), +/// the same in every list, so this adds nothing more to it. class ChatVisibilityMarker extends StatelessWidget { const ChatVisibilityMarker({ super.key, @@ -19,41 +21,24 @@ class ChatVisibilityMarker extends StatelessWidget { final bool active; final Widget child; + /// The thin bar of a chat visible in another pane. + static const double visibleBarWidth = 3; + @override Widget build(BuildContext context) { - final dark = chatColorDarkSurface(context); - // The open chat: selected and shown beside the list. - final open = active && visible; + final elsewhere = visible && !active; final row = AnimatedContainer( key: ValueKey('chat-visibility-$sessionId'), duration: MediaQuery.disableAnimationsOf(context) ? Duration.zero : const Duration(milliseconds: 220), curve: Curves.easeInOut, - // The open chat is unmistakable: a strong fill in its colour, a full - // outline, a thick leading bar and (below) a pointer toward the - // conversation shown beside the list. A chat visible elsewhere keeps a - // thin leading bar. - decoration: BoxDecoration( - color: open - ? color.withValues(alpha: dark ? .40 : .28) - : active - ? color.withValues(alpha: dark ? .30 : .22) - : null, - ), foregroundDecoration: BoxDecoration( - border: open - ? BorderDirectional( - start: BorderSide(color: color, width: 8), - top: BorderSide(color: color, width: 2), - end: BorderSide(color: color, width: 2), - bottom: BorderSide(color: color, width: 2), - ) - : BorderDirectional( - start: visible - ? BorderSide(color: color, width: 3) - : BorderSide.none, - ), + border: BorderDirectional( + start: elsewhere + ? BorderSide(color: color, width: visibleBarWidth) + : BorderSide.none, + ), ), child: child, ); @@ -64,56 +49,7 @@ class ChatVisibilityMarker extends StatelessWidget { ? 'Visible chat' : null, selected: active, - // Always a Stack, so selecting a chat never rebuilds its row. - child: Stack( - children: [ - row, - if (open) - PositionedDirectional( - end: 0, - top: 0, - bottom: 0, - child: IgnorePointer( - child: Center( - child: CustomPaint( - key: Key('chat-active-pointer-$sessionId'), - size: const Size(9, 18), - painter: _Pointer( - color: color, - rtl: Directionality.of(context) == TextDirection.rtl, - ), - ), - ), - ), - ), - ], - ), + child: row, ); } } - -/// A small triangle on the row's trailing edge, pointing toward the open -/// conversation beside the list. -class _Pointer extends CustomPainter { - const _Pointer({required this.color, required this.rtl}); - - final Color color; - final bool rtl; - - @override - void paint(Canvas canvas, Size size) { - final path = rtl - ? (Path() - ..moveTo(size.width, 0) - ..lineTo(0, size.height / 2) - ..lineTo(size.width, size.height)) - : (Path() - ..moveTo(0, 0) - ..lineTo(size.width, size.height / 2) - ..lineTo(0, size.height)); - canvas.drawPath(path..close(), Paint()..color = color); - } - - @override - bool shouldRepaint(_Pointer old) => old.color != color || old.rtl != rtl; -} diff --git a/app/lib/features/chat/ui/sessions/session_row_content.dart b/app/lib/features/chat/ui/sessions/session_row_content.dart index 0e15b405..be8aebb8 100644 --- a/app/lib/features/chat/ui/sessions/session_row_content.dart +++ b/app/lib/features/chat/ui/sessions/session_row_content.dart @@ -25,8 +25,9 @@ import 'chat_awaiting.dart'; /// An unread chat is emphasised (heavier title, accent time) with an accent /// dot ending its line; a starred chat shows a small star after its title; a /// running chat carries an activity badge on its avatar. A chat with a colour -/// wears a faint row tint and a coloured avatar. An animated leading edge -/// marks visible chats, growing wider for the active chat. The menu remains +/// wears a faint row tint and a coloured avatar. The open chat wears the +/// lists' shared selection (tonal fill and one leading bar); a thin animated +/// leading edge marks a chat visible elsewhere. The menu remains /// the row's way to its actions. class ChatSessionRow extends StatelessWidget { const ChatSessionRow({ @@ -80,7 +81,7 @@ class ChatSessionRow extends StatelessWidget { id: id, color: tint == null ? background : Color.alphaBlend(tint, background), marker: marker, - markerWidth: visible ? (selected ? 10 : 3) : 0, + markerWidth: selected ? kAppListRowBarWidth : (visible ? 3 : 0), child: draggable ? Draggable( // A mouse drags at once (a click still opens the chat); the chip @@ -130,7 +131,9 @@ class ChatSessionRow extends StatelessWidget { child: AppListRow( key: Key('chat-row-$id'), selected: selected, - selectedFill: Colors.transparent, + // The shared open-row style (tonal fill and one leading bar), the + // bar in the chat's own colour when it has one. + selectionAccent: marker, emphasized: unread, divider: divider, onTap: () => onOpen(session), diff --git a/app/lib/features/chat/ui/transcript/chat_code_hover.dart b/app/lib/features/chat/ui/transcript/chat_code_hover.dart index 18acc455..2d222433 100644 --- a/app/lib/features/chat/ui/transcript/chat_code_hover.dart +++ b/app/lib/features/chat/ui/transcript/chat_code_hover.dart @@ -116,9 +116,14 @@ class _CopyPosition extends SingleChildLayoutDelegate { anchor != oldDelegate.anchor; } -/// The copy slot always occupies the same space, so hover never shifts code. -/// Keyboard focus also reveals it; a touch on the code still selects normally. -class ChatCodeCopyRegion extends StatefulWidget { +/// A fenced code block as one framed piece: a header strip with the +/// language label and Copy, then the code on its own fill. +/// +/// Copy is always in the header (a touch screen has no hover to reveal it), +/// outside the selectable document, so selecting the code never takes the +/// button's label with it. Light mode keeps the code fill light, framed by a +/// hairline, so code text keeps its full contrast; dark mode lifts it a step. +class ChatCodeCopyRegion extends StatelessWidget { const ChatCodeCopyRegion({ super.key, required this.code, @@ -127,49 +132,57 @@ class ChatCodeCopyRegion extends StatefulWidget { }); final String code; final Widget label, child; - @override - State createState() => _ChatCodeCopyRegionState(); -} -class _ChatCodeCopyRegionState extends State { - bool _hover = false, _focus = false; + /// The block's corner radius. + static const double radius = 8; + + /// The code body's fill. + static Color fill(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return scheme.brightness == Brightness.light + ? scheme.surfaceContainerLow + : scheme.surfaceContainerHighest; + } + + /// The header strip's fill, one step from the body's. + static Color headerFill(BuildContext context) => + Theme.of(context).colorScheme.surfaceContainerHigh; + @override Widget build(BuildContext context) { - final visible = _hover || _focus; - return MouseRegion( - onEnter: (_) => setState(() => _hover = true), - onExit: (_) => setState(() => _hover = false), - child: Column( - crossAxisAlignment: CrossAxisAlignment.stretch, - mainAxisSize: MainAxisSize.min, - children: [ - Row( - children: [ - Expanded(child: widget.label), - Focus( - skipTraversal: true, - onFocusChange: (value) => setState(() => _focus = value), - child: ExcludeSemantics( - excluding: !visible, - child: IgnorePointer( - ignoring: !visible, - child: Opacity( - opacity: visible ? 1 : 0, - child: SelectionContainer.disabled( - child: ChatCopyButton( - text: widget.code, - showLabel: true, - ), - ), - ), - ), - ), - ), - ], + final scheme = Theme.of(context).colorScheme; + final header = ColoredBox( + key: const Key('chat-code-header'), + color: headerFill(context), + child: Padding( + padding: const EdgeInsetsDirectional.only(start: 12, end: 4), + child: Row( + children: [ + Expanded(child: label), + SelectionContainer.disabled( + child: ChatCopyButton(text: code, showLabel: true), + ), + ], + ), + ), + ); + return DecoratedBox( + position: DecorationPosition.foreground, + decoration: BoxDecoration( + border: Border.all(color: scheme.outlineVariant), + borderRadius: BorderRadius.circular(radius), + ), + child: ClipRRect( + borderRadius: BorderRadius.circular(radius), + child: ColoredBox( + key: const Key('chat-code-body'), + color: fill(context), + child: Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + mainAxisSize: MainAxisSize.min, + children: [header, child], ), - const SizedBox(height: 4), - widget.child, - ], + ), ), ); } diff --git a/app/lib/features/chat/ui/transcript/chat_horizontal_viewport.dart b/app/lib/features/chat/ui/transcript/chat_horizontal_viewport.dart index b477c458..0124ba24 100644 --- a/app/lib/features/chat/ui/transcript/chat_horizontal_viewport.dart +++ b/app/lib/features/chat/ui/transcript/chat_horizontal_viewport.dart @@ -2,8 +2,10 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import '../../../../ui/layout/wheel_scroll_forwarding.dart'; -/// Native, persistent overflow affordances for a code block or table. The -/// footer is outside the selectable document and never overlays its content. +/// Native, persistent overflow affordances for a code block or table: the +/// side with more content fades out under a small chevron, and the scrollbar +/// thumb stays visible. The chevrons are outside the selectable document and +/// take no taps; the semantics hint names the gestures and keys. class ChatHorizontalViewport extends StatefulWidget { const ChatHorizontalViewport({ super.key, @@ -89,20 +91,67 @@ class _ChatHorizontalViewportState extends State { super.dispose(); } + /// The width over which content fades out at a side with more to scroll. + static const double _fadeWidth = 32; + @override Widget build(BuildContext context) { final color = Theme.of(context).colorScheme.onSurfaceVariant; final focusColor = Theme.of(context).colorScheme.primary; - final view = Padding( - padding: EdgeInsets.only(bottom: _overflow ? 12 : 0), + Widget view = Padding( + padding: EdgeInsets.only(bottom: _overflow ? 10 : 0), child: HorizontalScrollView(controller: _controller, child: widget.child), ); + if (_left || _right) { + // The side with more content fades out, the usual sign that a row + // continues past the edge; content at rest is never covered. + view = ShaderMask( + key: const Key('chat-horizontal-fade'), + blendMode: BlendMode.dstIn, + shaderCallback: (bounds) { + final fade = bounds.width <= 0 + ? 0.0 + : (_fadeWidth / bounds.width).clamp(0.0, 0.5); + const shown = Colors.white; + const hidden = Color(0x00FFFFFF); + return LinearGradient( + colors: [ + _left ? hidden : shown, + shown, + shown, + _right ? hidden : shown, + ], + stops: [0, fade, 1 - fade, 1], + ).createShader(bounds); + }, + child: view, + ); + } final scrollbar = Scrollbar( controller: _controller, thumbVisibility: _overflow, - trackVisibility: _overflow, child: view, ); + Widget chevron(bool left) => Positioned( + left: left ? 0 : null, + right: left ? null : 0, + top: 0, + bottom: 10, + child: IgnorePointer( + child: Center( + child: Icon( + left ? Icons.chevron_left : Icons.chevron_right, + key: Key( + left ? 'chat-horizontal-more-left' : 'chat-horizontal-more-right', + ), + size: 18, + // Physical sides: the arrow points where the content continues. + textDirection: TextDirection.ltr, + color: color.withValues(alpha: .7), + ), + ), + ), + ); return NotificationListener( onNotification: (notification) { if (notification.metrics.axis == Axis.horizontal) _scheduleMetrics(); @@ -127,35 +176,17 @@ class _ChatHorizontalViewportState extends State { color: _focused ? focusColor : Colors.transparent, ), ), - child: Column( - mainAxisSize: MainAxisSize.min, - crossAxisAlignment: CrossAxisAlignment.start, + child: Stack( children: [ scrollbar, - if (_overflow) - SelectionContainer.disabled( - child: ExcludeSemantics( - child: Padding( - padding: const EdgeInsets.only(top: 4), - child: Row( + if (_left || _right) + Positioned.fill( + child: SelectionContainer.disabled( + child: ExcludeSemantics( + child: Stack( children: [ - Icon( - _left && _right - ? Icons.swap_horiz - : _left - ? Icons.arrow_back - : Icons.arrow_forward, - size: 16, - textDirection: TextDirection.ltr, - color: color, - ), - const SizedBox(width: 4), - Flexible( - child: Text( - 'Scroll horizontally', - style: TextStyle(color: color), - ), - ), + if (_left) chevron(true), + if (_right) chevron(false), ], ), ), diff --git a/app/lib/features/chat/ui/transcript/chat_markdown_view.dart b/app/lib/features/chat/ui/transcript/chat_markdown_view.dart index d0d51dca..bbe564b2 100644 --- a/app/lib/features/chat/ui/transcript/chat_markdown_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_markdown_view.dart @@ -260,22 +260,19 @@ class _ChatMarkdownViewState extends State { return ChatCodeCopyRegion( code: code, label: Text(markdownCodeLabel(language), style: labelStyle), - child: DecoratedBox( - decoration: BoxDecoration(color: _codeFill(context)), - child: Padding( - padding: const EdgeInsets.all(12), - child: ChatTranscriptHorizontalScrollView( - label: 'code block', - child: Text.rich( - TextSpan( - children: _linked( - context, - code, - (part) => TextSpan(text: part), - ), + child: Padding( + padding: const EdgeInsets.all(12), + child: ChatTranscriptHorizontalScrollView( + label: 'code block', + child: Text.rich( + TextSpan( + children: _linked( + context, + code, + (part) => TextSpan(text: part), ), - style: const TextStyle(fontFamily: appMonospaceFamily), ), + style: const TextStyle(fontFamily: appMonospaceFamily), ), ), ), diff --git a/app/lib/features/pipelines/pipeline_query.dart b/app/lib/features/pipelines/pipeline_query.dart index 56c0b1ee..13fd889a 100644 --- a/app/lib/features/pipelines/pipeline_query.dart +++ b/app/lib/features/pipelines/pipeline_query.dart @@ -28,6 +28,16 @@ class RunBadge { final String? ranAgo; final String? duration; + /// When the last run started, said as such for a list row: `last run + /// 19 Oct`, `last run 2h ago`, `last run just now`. Null without a time. + String? get lastRun { + final ago = ranAgo; + if (ago == null || ago.isEmpty) return null; + // `5m`, `2h`, `3d` are ages; a date or `just now` reads as it is. + final age = RegExp(r'^\d+[mhd]$').hasMatch(ago) ? '$ago ago' : ago; + return 'last run $age'; + } + /// `2h · 1m 5s · run 42`; missing fragments are omitted. String get metaLine => [ ranAgo, diff --git a/app/lib/features/pipelines/widgets/pipeline_list_panel.dart b/app/lib/features/pipelines/widgets/pipeline_list_panel.dart index 7e958e32..38f93297 100644 --- a/app/lib/features/pipelines/widgets/pipeline_list_panel.dart +++ b/app/lib/features/pipelines/widgets/pipeline_list_panel.dart @@ -248,7 +248,9 @@ class PipelineListPanel extends StatelessWidget { controller.openPipeline(pipeline.id, version: pipeline.version), leading: _pipelineIdentityIcon(context, pipeline), title: Text(pipeline.displayName), - time: badge?.ranAgo, + // The latest run's state is spelled out, not colour alone, with + // when it ran: `Failed · last run 19 Oct`. The pipeline's own + // facts (stages, schedules) follow on the next line. subtitleLeading: badge == null ? null : AppListStatusDot( @@ -260,16 +262,28 @@ class PipelineListPanel extends StatelessWidget { semanticLabel: runStateLabel(badge.state), ), subtitle: Text( - ServerContext.metadata(context, _rowMetadata(pipeline)), + badge == null + ? ServerContext.metadata(context, _rowMetadata(pipeline)) + : ServerContext.metadata( + context, + _statusLine(badge, badge.lastRun), + ), + key: Key('pipeline-status-text-${pipeline.id}'), ), - // A narrow pane keeps the latest state, the useful decision signal; - // stage counts, schedules and version live in the detail instead. - // Do not turn an in-flight or failed run-history read into a false - // no-runs claim: the line stays blank until history is known. + detail: badge == null ? null : Text(_rowMetadata(pipeline)), + compactDetail: false, + // A narrow pane keeps the latest state and its date, the useful + // decision signal; stage counts, schedules and version live in the + // detail instead. Do not turn an in-flight or failed run-history + // read into a false no-runs claim: the line stays blank until + // history is known. compactSubtitle: badge == null ? Text(ServerContext.metadata(context, '')) : Text( - ServerContext.metadata(context, runStateLabel(badge.state)), + ServerContext.metadata( + context, + _statusLine(badge, badge.ranAgo), + ), ), menu: onOpenInChat == null ? null @@ -292,7 +306,13 @@ class PipelineListPanel extends StatelessWidget { ); } - /// The row's one muted subtitle: stage count and schedules. + /// `Failed · last run 19 Oct`: the latest run's state and when it ran. + String _statusLine(RunBadge badge, String? when) => [ + runStateLabel(badge.state), + if (when != null && when.isNotEmpty) when, + ].join(' · '); + + /// The row's muted facts line: stage count and schedules. String _rowMetadata(PipelineSummary pipeline) { final schedules = switch (pipeline.scheduleState) { PipelineScheduleState.scheduled => pipeline.scheduleLabel, diff --git a/app/lib/features/runs/domain/run_models.dart b/app/lib/features/runs/domain/run_models.dart index 90bc23b7..f3502e5c 100644 --- a/app/lib/features/runs/domain/run_models.dart +++ b/app/lib/features/runs/domain/run_models.dart @@ -23,6 +23,13 @@ String localDayKey(DateTime date) { return '${local.year}-${two(local.month)}-${two(local.day)}'; } +/// The local time of day, `HH:mm`, for a run listed under its day heading. +String runTimeOfDay(DateTime instant) { + final local = instant.toLocal(); + String two(int value) => value.toString().padLeft(2, '0'); + return '${two(local.hour)}:${two(local.minute)}'; +} + String runDayLabel(String createdAt, DateTime today) { final created = DateTime.tryParse(createdAt)?.toLocal(); if (created == null) return 'Unknown date'; diff --git a/app/lib/features/runs/ui/run_detail_tab_strip.dart b/app/lib/features/runs/ui/run_detail_tab_strip.dart index 7a7adaa2..a82d2623 100644 --- a/app/lib/features/runs/ui/run_detail_tab_strip.dart +++ b/app/lib/features/runs/ui/run_detail_tab_strip.dart @@ -1,4 +1,4 @@ -import 'package:flutter/widgets.dart'; +import 'package:flutter/material.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; import '../../../ui/adaptive/floating_destination_bar.dart'; @@ -16,14 +16,41 @@ const List renderedRunDetailTabs = [ RunDetailTab.changes, ]; -/// The run detail's tabs: the app's floating glass tab bar, full width at the -/// bottom of a phone page; beside a list, sized to its tabs at the bottom of -/// the detail pane (the shell's own tab bar stays over the list pane). +/// The run's Artifacts count as a small badge: `0` on a run with none, so +/// the (disabled) tab still says why it cannot open. +class RunArtifactsCount extends StatelessWidget { + const RunArtifactsCount({super.key, required this.count, this.child}); + + final int count; + + /// The icon the badge sits on; null draws the badge on its own. + final Widget? child; + + @override + Widget build(BuildContext context) { + final scheme = Theme.of(context).colorScheme; + return Badge( + key: const ValueKey('run-detail-artifacts-count'), + label: Text('$count'), + backgroundColor: count == 0 + ? scheme.surfaceContainerHighest + : scheme.secondary, + textColor: count == 0 ? scheme.onSurfaceVariant : scheme.onSecondary, + child: child, + ); + } +} + +/// The run detail's tabs on a phone: the app's floating glass tab bar, full +/// width at the bottom of the page (a wide layout puts `RunDetailTopTabs` +/// under the run header instead). /// /// Float it over the tab body with `FloatingBarOverlay` at the same [edge]; /// every tab is always visible, so a tab selected by the Graph is shown -/// selected without scrolling. The whole bar is keyed `run-detail-tabs`, each -/// tab `run-detail-tab-`. +/// selected without scrolling. Artifacts is always a tab, disabled with a +/// `0` count on a run with none, so the tabs after it never move between +/// runs. The whole bar is keyed `run-detail-tabs`, each tab +/// `run-detail-tab-`. class RunDetailTabStrip extends StatelessWidget { const RunDetailTabStrip({ super.key, @@ -31,8 +58,14 @@ class RunDetailTabStrip extends StatelessWidget { required this.onSelected, this.tabs = renderedRunDetailTabs, this.edge = FloatingBarEdge.bottom, + this.artifactCount, + this.disabled = const {}, + this.disabledReasons = const {}, }); + /// Why a disabled tab cannot open, as its tooltip. + final Map disabledReasons; + final RunDetailTab selected; final ValueChanged onSelected; final FloatingBarEdge edge; @@ -40,9 +73,17 @@ class RunDetailTabStrip extends StatelessWidget { /// The tabs this run offers, in [renderedRunDetailTabs] order. final List tabs; + /// The run's recorded artifacts, badged on the Artifacts tab; null draws + /// no badge. + final int? artifactCount; + + /// Tabs shown greyed out that take no taps. + final Set disabled; + @override Widget build(BuildContext context) { final index = tabs.indexOf(selected); + final count = artifactCount; return KeyedSubtree( key: const Key('run-detail-tabs'), child: FloatingDestinationBar( @@ -56,8 +97,12 @@ class RunDetailTabStrip extends StatelessWidget { for (final tab in tabs) FloatingDestinationItem( key: ValueKey('run-detail-tab-${tab.name}'), - icon: Icon(tab.icon), + icon: tab == RunDetailTab.artifacts && count != null + ? RunArtifactsCount(count: count, child: Icon(tab.icon)) + : Icon(tab.icon), label: tab.label, + enabled: !disabled.contains(tab), + tooltip: disabled.contains(tab) ? disabledReasons[tab] : null, ), ], ), diff --git a/app/lib/features/runs/ui/run_detail_tabs.dart b/app/lib/features/runs/ui/run_detail_tabs.dart index 0ee737dc..64cf757d 100644 --- a/app/lib/features/runs/ui/run_detail_tabs.dart +++ b/app/lib/features/runs/ui/run_detail_tabs.dart @@ -13,6 +13,7 @@ import '../../graph/widgets/run_graph_view.dart'; import '../../artifacts/ui/artifact_gallery_action.dart'; import '../../artifacts/ui/artifact_gallery_page.dart'; import '../../artifacts/domain/artifact_chat_context.dart'; +import '../../artifacts/domain/artifact_summary.dart'; import '../../changes/changes.dart'; import 'run_changes_action.dart'; import 'run_detail_content.dart'; @@ -20,6 +21,7 @@ import 'run_graph_preview.dart'; import 'run_detail_tab.dart'; import 'run_detail_tab_bodies.dart'; import 'run_detail_tab_strip.dart'; +import 'run_detail_top_tabs.dart'; import 'run_detail_timeline.dart'; import 'run_detail_visit.dart'; import 'run_detail_wide_chrome.dart'; @@ -253,8 +255,8 @@ class _RunDetailTabsState extends State { case RunArtifactTarget(:final url): _selectedStage = null; _selectedVisit = null; - if (!_tabsFor(widget.run).contains(RunDetailTab.artifacts)) { - // A run with no recorded steps has no gallery to open it in. + if (_disabledTabs(widget.run).contains(RunDetailTab.artifacts)) { + // A run with no recorded artifacts has no gallery to open it in. _tab = RunDetailTab.summary; WidgetsBinding.instance.addPostFrameCallback( (_) => mounted ? _showSearchArtifactMissingNotice() : null, @@ -369,18 +371,19 @@ class _RunDetailTabsState extends State { }); } - /// Artifacts once the run has recorded steps; Changes once it has stopped - /// executing, since a snapshot would not follow live captures. + /// Every tab but Changes always, so a tab never moves between runs; + /// Changes (the last) once the run has stopped executing, since a snapshot + /// would not follow live captures. List _tabsFor(JsonMap run) => [ for (final tab in renderedRunDetailTabs) - if (switch (tab) { - RunDetailTab.artifacts => showRunArtifactsAction(run), - RunDetailTab.changes => showRunChangesAction(run), - _ => true, - }) - tab, + if (tab != RunDetailTab.changes || showRunChangesAction(run)) tab, ]; + /// Artifacts stays in place but disabled while the run recorded none. + Set _disabledTabs(JsonMap run) => { + if (runArtifactCount(run) == 0) RunDetailTab.artifacts, + }; + @override Widget build(BuildContext context) { // A selected visit opens on its own page; the tab keeps the list. @@ -388,8 +391,12 @@ class _RunDetailTabsState extends State { _syncVisitPage(); } final tabs = _tabsFor(widget.run); - // A tab the run no longer offers falls back to Summary. - final shown = tabs.contains(_tab) || !renderedRunDetailTabs.contains(_tab) + final disabled = _disabledTabs(widget.run); + final artifactCount = runArtifactCount(widget.run); + // A tab the run no longer offers (or cannot open) falls back to Summary. + final shown = + (tabs.contains(_tab) && !disabled.contains(_tab)) || + !renderedRunDetailTabs.contains(_tab) ? _tab : RunDetailTab.summary; final edge = PageTabsEdge.of(context); @@ -403,29 +410,49 @@ class _RunDetailTabsState extends State { child: widget.header, ), ); - final tabStrip = RunDetailTabStrip( - tabs: tabs, - edge: edge, - selected: shown, - onSelected: (tab) => setState(() => _tab = tab), - ); + void select(RunDetailTab tab) => setState(() => _tab = tab); final body = FadeThroughStack( key: ValueKey('run-detail-body-${widget.run['id']}'), index: tabs.indexOf(shown), lazy: true, children: [for (final tab in tabs) _body(tab)], ); - if (edge == FloatingBarEdge.top && - constraints.maxWidth >= kRunDetailWideChromeMinWidth) { - // Beside a list the tabs and the header share one row under the - // pane's bar, so only that row (not a header strip over a tabs - // strip) sits above the tab's content. + // Why a disabled Artifacts tab cannot open: none recorded, capture + // pending or unavailable. + final reasons = { + RunDetailTab.artifacts: artifactsHeader( + runDetailArtifactSteps(widget.run), + executing: runDetailExecuting(widget.run), + ), + }; + if (runDetailTabsOnTop(context, constraints.maxWidth)) { + // A wide layout puts the tabs right under the run header, at the + // top of the detail, in one strip with it. return FloatingBarOverlay( edge: FloatingBarEdge.top, - bar: RunDetailWideChrome(tabs: tabStrip, header: header), + bar: RunDetailWideChrome( + header: header, + tabs: RunDetailTopTabs( + tabs: tabs, + selected: shown, + onSelected: select, + artifactCount: artifactCount, + disabled: disabled, + disabledReasons: reasons, + ), + ), child: body, ); } + final tabStrip = RunDetailTabStrip( + tabs: tabs, + edge: edge, + selected: shown, + onSelected: select, + artifactCount: artifactCount, + disabled: disabled, + disabledReasons: reasons, + ); // The header (status, actions, notices) is a glass strip floating // just under the top bar, so every tab scrolls behind both and pads // its first item clear of them at rest. Below it, the tabs float over diff --git a/app/lib/features/runs/ui/run_detail_top_tabs.dart b/app/lib/features/runs/ui/run_detail_top_tabs.dart new file mode 100644 index 00000000..90e7db85 --- /dev/null +++ b/app/lib/features/runs/ui/run_detail_top_tabs.dart @@ -0,0 +1,82 @@ +import 'package:flutter/material.dart'; + +import 'run_detail_tab.dart'; +import 'run_detail_tab_strip.dart'; + +/// The run detail's tabs on a wide layout: a Material [SegmentedButton] of +/// icon-and-label segments under the run header, at the top of the detail +/// where the eye already is, with labels at the button text size. +/// +/// The segments keep their order and positions across runs: Artifacts is +/// always one, disabled with a `0` count when the run recorded none. Keys +/// match the phone bar's: the whole row `run-detail-tabs`, each label +/// `run-detail-tab-`. +class RunDetailTopTabs extends StatelessWidget { + const RunDetailTopTabs({ + super.key, + required this.tabs, + required this.selected, + required this.onSelected, + this.artifactCount, + this.disabled = const {}, + this.disabledReasons = const {}, + }); + + final List tabs; + final RunDetailTab selected; + final ValueChanged onSelected; + final int? artifactCount; + final Set disabled; + + /// Why a disabled tab cannot open, as its tooltip. + final Map disabledReasons; + + @override + Widget build(BuildContext context) { + final count = artifactCount; + final scheme = Theme.of(context).colorScheme; + return Align( + key: const Key('run-detail-tabs'), + alignment: AlignmentDirectional.centerStart, + child: SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: SegmentedButton( + showSelectedIcon: false, + // On the frosted strip the unselected segments take the surface, + // so the selected one's tonal fill stands out from the glass. + style: ButtonStyle( + backgroundColor: WidgetStateProperty.resolveWith( + (states) => states.contains(WidgetState.selected) + ? scheme.secondaryContainer + : scheme.surface, + ), + ), + segments: [ + for (final tab in tabs) + ButtonSegment( + value: tab, + enabled: !disabled.contains(tab), + tooltip: disabled.contains(tab) ? disabledReasons[tab] : null, + icon: Icon(tab.icon), + label: Row( + key: ValueKey('run-detail-tab-${tab.name}'), + mainAxisSize: MainAxisSize.min, + children: [ + Text(tab.label), + if (tab == RunDetailTab.artifacts && count != null) ...[ + const SizedBox(width: 6), + RunArtifactsCount(count: count), + ], + ], + ), + ), + ], + selected: {selected}, + onSelectionChanged: (value) { + if (value.isNotEmpty) onSelected(value.first); + }, + ), + ), + ); + } +} diff --git a/app/lib/features/runs/ui/run_detail_wide_chrome.dart b/app/lib/features/runs/ui/run_detail_wide_chrome.dart index 4f9b512f..592441d6 100644 --- a/app/lib/features/runs/ui/run_detail_wide_chrome.dart +++ b/app/lib/features/runs/ui/run_detail_wide_chrome.dart @@ -1,26 +1,31 @@ import 'package:flutter/widgets.dart'; import '../../../ui/adaptive/floating_bar_layout.dart'; -import '../../../ui/adaptive/floating_destination_bar.dart'; -import '../../../ui/adaptive/glass_pill.dart'; import '../../../ui/adaptive/top_glass_strip.dart'; -/// The narrowest detail pane that puts its tabs and header in one row; -/// narrower panes stack the header strip over the tabs. +/// The narrowest detail pane that puts its tabs under the run header. const double kRunDetailWideChromeMinWidth = kFloatingBarWideWidth; -/// The most of the row the tabs take, leaving the rest to the header. -const double kRunDetailWideTabsShare = 0.6; +/// The narrowest window whose run detail puts its tabs at the top: a wide +/// (desktop or tablet) window. Phones keep the floating bottom tab bar. +const double kRunDetailTopTabsMinWindowWidth = 840; -/// The run detail's controls beside a list (a wide split): its tabs and its -/// header (status, run actions, notices) share one row under the pane's top -/// bar, instead of stacking the header strip above a second tabs strip. +/// Whether the run detail at [context], [width] wide, shows its tabs under +/// the run header rather than as the floating bottom bar: on a wide window +/// with a wide enough detail pane, or where the host asks for top tabs. +bool runDetailTabsOnTop(BuildContext context, double width) { + if (width < kRunDetailWideChromeMinWidth) return false; + return PageTabsEdge.of(context) == FloatingBarEdge.top || + MediaQuery.sizeOf(context).width >= kRunDetailTopTabsMinWindowWidth; +} + +/// The run detail's controls on a wide layout: one frosted strip under the +/// pane's top bar holding the header (status, run actions, notices) and, +/// under it, the tabs, so the tabs sit right below the run's title instead +/// of floating at the far corner of a wide pane. /// -/// The tabs lead, in line with the bar's title; the header follows as a glass -/// piece as wide as its content, and wraps (or scrolls inside its height -/// limit) when the pane is narrow. Float the row with `FloatingBarOverlay` -/// at the top edge so the tab body pads past it at rest. The header keeps the -/// key `run-detail-header`. +/// Float it with `FloatingBarOverlay` at the top edge so the tab body pads +/// past it at rest. The strip keeps the key `run-detail-header`. class RunDetailWideChrome extends StatelessWidget { const RunDetailWideChrome({ super.key, @@ -28,7 +33,7 @@ class RunDetailWideChrome extends StatelessWidget { required this.header, }); - /// The tab strip at [FloatingBarEdge.top]; it brings its own 12px margins. + /// The tabs (`RunDetailTopTabs`). final Widget tabs; /// The header's content, already bounded in height. @@ -36,46 +41,19 @@ class RunDetailWideChrome extends StatelessWidget { @override Widget build(BuildContext context) { - final insets = MediaQuery.paddingOf(context); - return Padding( - padding: EdgeInsets.only(left: insets.left), - child: LayoutBuilder( - builder: (context, constraints) => Row( - crossAxisAlignment: CrossAxisAlignment.center, - children: [ - // The tabs keep at most 60% of the row, so the header always has - // room for its status and actions (scaled text included). - ConstrainedBox( - constraints: BoxConstraints( - maxWidth: constraints.maxWidth * kRunDetailWideTabsShare, - ), - child: tabs, - ), - Flexible( - child: Padding( - // The tabs' own trailing margin is the gap before the header. - padding: EdgeInsets.only( - right: FloatingDestinationBar.topMargin + insets.right, - bottom: 8, - ), - child: Align( - alignment: AlignmentDirectional.centerStart, - heightFactor: 1, - child: GlassPill( - key: const Key('run-detail-header'), - shape: RoundedRectangleBorder( - borderRadius: BorderRadius.circular(kTopGlassStripRadius), - ), - child: Padding( - padding: const EdgeInsets.symmetric(vertical: 4), - child: header, - ), - ), - ), - ), - ), - ], - ), + return TopGlassStrip( + key: const Key('run-detail-header'), + padding: const EdgeInsets.fromLTRB(0, 4, 0, 12), + child: Column( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + header, + Padding( + padding: const EdgeInsets.symmetric(horizontal: 12), + child: tabs, + ), + ], ), ); } diff --git a/app/lib/features/runs/ui/run_list_row.dart b/app/lib/features/runs/ui/run_list_row.dart index f636da29..eb6c5c32 100644 --- a/app/lib/features/runs/ui/run_list_row.dart +++ b/app/lib/features/runs/ui/run_list_row.dart @@ -38,8 +38,13 @@ class RunListRow extends StatelessWidget { this.onLongPress, this.onOpenInChat, this.onRunAgain, + this.timeOfDay = false, }); + /// The row sits under a day heading, so its time is the time of day + /// (`09:12`) rather than a date the heading already names. + final bool timeOfDay; + final ValueChanged? onRunAgain; final JsonMap run; @@ -137,6 +142,8 @@ class RunListRow extends StatelessWidget { title: Text(title), timeWidget: createdAt == null ? null + : timeOfDay + ? Text(runTimeOfDay(createdAt), key: ValueKey('run-row-time-$id')) : RelativeTimeLabel(instant: createdAt, now: now), subtitle: line(subtitle), compactSubtitle: line(compactSubtitle), diff --git a/app/lib/features/runs/ui/runs_list.dart b/app/lib/features/runs/ui/runs_list.dart index b132c00f..1504eac8 100644 --- a/app/lib/features/runs/ui/runs_list.dart +++ b/app/lib/features/runs/ui/runs_list.dart @@ -247,7 +247,12 @@ class RunsList extends StatelessWidget { final last = next >= entries.length || entries[next].run == null; return Arrival( id: '${entry.run!['id']}', - child: _runTile(context, entry.run!, divider: !last), + child: _runTile( + context, + entry.run!, + divider: !last, + timeOfDay: !flatRunSorts.contains(controller.sort), + ), ); }, ); @@ -310,7 +315,12 @@ class RunsList extends StatelessWidget { ), ); - Widget _runTile(BuildContext context, JsonMap run, {bool divider = true}) { + Widget _runTile( + BuildContext context, + JsonMap run, { + bool divider = true, + bool timeOfDay = false, + }) { final id = run['id']; final selection = controller.selection; final now = DateTime.now(); @@ -320,6 +330,7 @@ class RunsList extends StatelessWidget { memo: ( MemoMap(run), divider, + timeOfDay, selection.active, selection.contains(id), id == controller.selectedRunId, @@ -327,11 +338,18 @@ class RunsList extends StatelessWidget { onSelected, // An executing run's duration ticks inside the row, not from here. ), - builder: (context) => _runRow(run, id, now, divider: divider), + builder: (context) => + _runRow(run, id, now, divider: divider, timeOfDay: timeOfDay), ); } - Widget _runRow(JsonMap run, Object? id, DateTime now, {bool divider = true}) { + Widget _runRow( + JsonMap run, + Object? id, + DateTime now, { + bool divider = true, + bool timeOfDay = false, + }) { final selection = controller.selection; return RunListRow( selecting: selection.active, @@ -342,6 +360,7 @@ class RunsList extends StatelessWidget { onDeleted: controller.applyDeletion, run: run, divider: divider, + timeOfDay: timeOfDay, selected: id == controller.selectedRunId, now: now, onTap: id is num ? () => onSelected(id) : null, diff --git a/app/lib/features/settings/settings_controls.dart b/app/lib/features/settings/settings_controls.dart index 6473d59a..b60ada9c 100644 --- a/app/lib/features/settings/settings_controls.dart +++ b/app/lib/features/settings/settings_controls.dart @@ -93,8 +93,14 @@ class SettingsTextField extends StatelessWidget { } } -/// The filled primary and outlined secondary settings actions. Buttons wrap on -/// a narrow window (or with large text) instead of overflowing. +/// The settings actions: the emphasised one filled, the other outlined. +/// Buttons wrap on a narrow window (or with large text) instead of +/// overflowing. +/// +/// [primaryOutlined] turns the order of emphasis around for a primary action +/// that ends something (Disconnect): the secondary action leads as a tonal +/// button and the primary follows outlined, so the filled emphasis never sits +/// on the action that drops the connection. class SettingsActions extends StatelessWidget { const SettingsActions({ super.key, @@ -104,6 +110,7 @@ class SettingsActions extends StatelessWidget { required this.onSecondary, this.primaryKey, this.secondaryKey, + this.primaryOutlined = false, }); final String primaryLabel; @@ -112,24 +119,38 @@ class SettingsActions extends StatelessWidget { final VoidCallback onSecondary; final Key? primaryKey; final Key? secondaryKey; + final bool primaryOutlined; @override Widget build(BuildContext context) { + final primary = primaryOutlined + ? OutlinedButton( + key: primaryKey, + onPressed: onPrimary, + child: Text(primaryLabel), + ) + : FilledButton( + key: primaryKey, + onPressed: onPrimary, + child: Text(primaryLabel), + ); + final secondary = primaryOutlined + ? FilledButton.tonal( + key: secondaryKey, + onPressed: onSecondary, + child: Text(secondaryLabel), + ) + : OutlinedButton( + key: secondaryKey, + onPressed: onSecondary, + child: Text(secondaryLabel), + ); return Wrap( spacing: settingsControlGap, runSpacing: settingsControlGap, - children: [ - FilledButton( - key: primaryKey, - onPressed: onPrimary, - child: Text(primaryLabel), - ), - OutlinedButton( - key: secondaryKey, - onPressed: onSecondary, - child: Text(secondaryLabel), - ), - ], + children: primaryOutlined + ? [secondary, primary] + : [primary, secondary], ); } } diff --git a/app/lib/features/settings/settings_sections.dart b/app/lib/features/settings/settings_sections.dart index bcde5f62..3681c232 100644 --- a/app/lib/features/settings/settings_sections.dart +++ b/app/lib/features/settings/settings_sections.dart @@ -55,6 +55,8 @@ class SettingsConnectionSection extends StatelessWidget { SettingsActions( primaryLabel: controller.primaryActionLabel, secondaryLabel: controller.secondaryActionLabel, + // Disconnect is outlined beside a tonal Reconnect. + primaryOutlined: controller.connectionActive, primaryKey: controller.connectionActive ? SettingsKeys.disconnect : SettingsKeys.connect, diff --git a/app/lib/ui/adaptive/floating_destination_bar.dart b/app/lib/ui/adaptive/floating_destination_bar.dart index 70424084..4c4fd432 100644 --- a/app/lib/ui/adaptive/floating_destination_bar.dart +++ b/app/lib/ui/adaptive/floating_destination_bar.dart @@ -197,6 +197,7 @@ class _FloatingDestinationBarState extends State final labels = FloatingDestinationLabels( key: FloatingDestinationBar.rowKey, labels: [for (final item in items) item.label], + enabled: [for (final item in items) item.enabled], selected: currentIndex, buttonBuilder: (index) => _button(context, index), onTap: widget.onTap, @@ -267,6 +268,8 @@ class _FloatingDestinationBarState extends State iconSize: iconSize * size / _size, label: item.label, icon: selected ? item.selectedIcon ?? item.icon : item.icon, + enabled: item.enabled, + tooltip: item.tooltip, onTap: () => widget.onTap(index), ), ), @@ -281,8 +284,18 @@ class FloatingDestinationItem { required this.label, this.selectedIcon, this.key, + this.enabled = true, + this.tooltip, }); + /// The tab's tooltip (and accessibility hint) instead of its label, such + /// as why a disabled tab cannot open. + final String? tooltip; + + /// False shows the tab greyed out and takes no taps, so a tab that has + /// nothing to show keeps its place in the bar. + final bool enabled; + final Widget icon; /// The tab's accessible name (and Material tooltip); not drawn. diff --git a/app/lib/ui/adaptive/floating_destination_labels.dart b/app/lib/ui/adaptive/floating_destination_labels.dart index 10e33bc0..eac7bd5f 100644 --- a/app/lib/ui/adaptive/floating_destination_labels.dart +++ b/app/lib/ui/adaptive/floating_destination_labels.dart @@ -7,11 +7,16 @@ class FloatingDestinationLabels extends StatelessWidget { const FloatingDestinationLabels({ super.key, required this.labels, + this.enabled = const [], required this.selected, required this.buttonBuilder, required this.onTap, }); final List labels; + + /// Per label; a missing entry is enabled. + final List enabled; + bool _enabled(int index) => index >= enabled.length || enabled[index]; final int selected; final Widget Function(int) buttonBuilder; final ValueChanged onTap; @@ -36,7 +41,7 @@ class FloatingDestinationLabels extends StatelessWidget { GestureDetector( key: ValueKey('destination-label-${labels[index]}'), excludeFromSemantics: true, - onTap: () => onTap(index), + onTap: _enabled(index) ? () => onTap(index) : null, child: TextFieldTapRegion( child: Column( mainAxisSize: MainAxisSize.min, @@ -46,7 +51,9 @@ class FloatingDestinationLabels extends StatelessWidget { child: Text( labels[index], style: style.copyWith( - color: color, + color: _enabled(index) + ? color + : color.withValues(alpha: .38), fontWeight: index == selected ? FontWeight.w600 : style.fontWeight, diff --git a/app/lib/ui/adaptive/floating_tab_button.dart b/app/lib/ui/adaptive/floating_tab_button.dart index 9575e58a..b5fb15fc 100644 --- a/app/lib/ui/adaptive/floating_tab_button.dart +++ b/app/lib/ui/adaptive/floating_tab_button.dart @@ -33,8 +33,16 @@ class FloatingTabButton extends StatelessWidget { required this.label, required this.icon, required this.onTap, + this.enabled = true, + this.tooltip, }); + /// Shown (and given as the accessibility hint) instead of [label]. + final String? tooltip; + + /// False greys the tab out and ignores taps; it keeps its place. + final bool enabled; + final FloatingTabMotion motion; final int index; final int count; @@ -64,12 +72,14 @@ class FloatingTabButton extends StatelessWidget { child: Semantics( role: SemanticsRole.tab, selected: selected, + enabled: enabled, + hint: tooltip, button: true, label: kIsWeb ? label : '$label\n${_tabLabel(context)}', // Switching tabs does not unfocus a text field (the composer). child: TextFieldTapRegion( child: Tooltip( - message: label, + message: tooltip ?? label, excludeFromSemantics: true, child: button, ), @@ -87,7 +97,9 @@ class FloatingTabButton extends StatelessWidget { return ( tint: scheme.secondaryContainer, selectedIcon: scheme.onSecondaryContainer, - icon: scheme.onSurfaceVariant, + icon: enabled + ? scheme.onSurfaceVariant + : scheme.onSurface.withValues(alpha: .38), ); } @@ -105,7 +117,7 @@ class FloatingTabButton extends StatelessWidget { key: fillKey, decoration: decoration, child: InkResponse( - onTap: onTap, + onTap: enabled ? onTap : null, customBorder: const CircleBorder(), containedInkWell: true, highlightShape: BoxShape.circle, diff --git a/app/lib/ui/layout/app_list_row.dart b/app/lib/ui/layout/app_list_row.dart index a5e2f078..6f7500f3 100644 --- a/app/lib/ui/layout/app_list_row.dart +++ b/app/lib/ui/layout/app_list_row.dart @@ -28,6 +28,11 @@ const double _lineGap = 4; const appListRowSurfaceKey = ValueKey('app-list-row-surface'); const appListRowDividerKey = ValueKey('app-list-row-divider'); const appListRowAccentKey = ValueKey('app-list-row-accent'); +const appListRowSelectionKey = ValueKey('app-list-row-selection'); + +/// The width of a row's leading bar: the open row's accent, or an identity +/// colour's mark. +const double kAppListRowBarWidth = 4; /// The app's one list row (runs, pipelines, chats, search results, /// schedules). @@ -42,7 +47,9 @@ const appListRowAccentKey = ValueKey('app-list-row-accent'); /// under the text column separates rows. Nothing has a fixed height: the row /// grows with text scaling and every line ellipsises. /// -/// [selected] paints the open row (Material `secondaryContainer`); [emphasized] +/// [selected] paints the open row: Material `secondaryContainer` with one +/// [selectionAccent] bar on its leading edge, the one selection style every +/// list shares; [emphasized] /// marks unread/attention (a heavier title and an accent time). Rows ripple. class AppListRow extends StatelessWidget { const AppListRow({ @@ -54,6 +61,7 @@ class AppListRow extends StatelessWidget { this.subtitle, this.compactSubtitle, this.detail, + this.compactDetail = true, this.subtitleLeading, this.subtitleTrailing, this.menu, @@ -68,8 +76,14 @@ class AppListRow extends StatelessWidget { this.compactWidth = kAppListRowCompactWidth, this.accent, this.showAccentBorder = true, + this.selectionAccent, }); + /// The leading bar's colour on the open row; Material `primary` when null. + /// Every list marks its open row the same way: the tonal fill plus this + /// one bar. + final Color? selectionAccent; + /// The item's own colour (a chat's highlight): a bar on the row's leading /// edge and a faint tint under an unselected row. The selected fill still /// marks the open row, so the two never read as one another. @@ -93,6 +107,10 @@ class AppListRow extends StatelessWidget { /// An optional third line under the subtitle (a failed run's reason), one /// ellipsised line in the subtitle style unless the widget styles itself. final Widget? detail; + + /// Whether a compact row keeps [detail]; false leaves a narrow row its + /// title and [compactSubtitle] only. + final bool compactDetail; final Widget? subtitleLeading; final Widget? subtitleTrailing; final Widget? menu; @@ -184,14 +202,22 @@ class AppListRow extends StatelessWidget { // The colour bar runs the row's whole height, divider included, and // the tint fills the divider's inset too, so coloured rows read as // one band each. - Widget marked(Widget row) => accent == null || !showAccentBorder + // The open row's bar, else an identity colour's own bar. + final bar = selected + ? selectionAccent ?? + accent ?? + Theme.of(context).colorScheme.primary + : showAccentBorder + ? accent + : null; + Widget marked(Widget row) => bar == null ? row : DecoratedBox( - key: appListRowAccentKey, + key: selected ? appListRowSelectionKey : appListRowAccentKey, position: DecorationPosition.foreground, decoration: BoxDecoration( border: BorderDirectional( - start: BorderSide(color: accent!, width: 4), + start: BorderSide(color: bar, width: kAppListRowBarWidth), ), ), child: row, @@ -276,7 +302,7 @@ class AppListRow extends StatelessWidget { // A compact row has no room beside its title: the time takes a line of // its own under the subtitle. final timeLine = compact ? time : null; - final detailLine = detail == null + final detailLine = detail == null || (compact && !compactDetail) ? null : Padding( padding: const EdgeInsets.only(top: _lineGap), diff --git a/app/test/features/chat/chat_open_transition_test.dart b/app/test/features/chat/chat_open_transition_test.dart index 15068046..8b729ec8 100644 --- a/app/test/features/chat/chat_open_transition_test.dart +++ b/app/test/features/chat/chat_open_transition_test.dart @@ -1,5 +1,6 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/ui/layout/app_list_row.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/chat/screen.dart'; @@ -175,7 +176,8 @@ void main() { final background = appLightTheme().scaffoldBackgroundColor; expect(origin.color, isNot(background), reason: 'the chat colour tints it'); expect(origin.color.a, 1); - expect(origin.markerWidth, 10); + // The open row's one bar, as every list marks its open row. + expect(origin.markerWidth, kAppListRowBarWidth); expect(origin.marker, isNotNull); }); diff --git a/app/test/features/chat/ui/sessions/chat_active_selection_test.dart b/app/test/features/chat/ui/sessions/chat_active_selection_test.dart index 11e5ccad..04d17fce 100644 --- a/app/test/features/chat/ui/sessions/chat_active_selection_test.dart +++ b/app/test/features/chat/ui/sessions/chat_active_selection_test.dart @@ -58,13 +58,17 @@ void main() { of: row, matching: find.byKey(appListRowSurfaceKey), ); + // The lists' shared open-row style: the tonal fill and one bar. final color = tester.widget(surface).color; - expect(color, const Color(0x00000000)); - final highlight = tester.widget( - find.byKey(ValueKey('chat-visibility-$id')), + final context = tester.element(row); + expect(color == AppListRow.selectedColor(context), active); + expect( + find.descendant( + of: find.byKey(ValueKey('chat-visibility-$id')), + matching: find.byKey(appListRowSelectionKey), + ), + active ? findsOneWidget : findsNothing, ); - final fill = (highlight.decoration as BoxDecoration).color; - expect(fill != null && fill.a > 0, active); } expectRow('a', true); diff --git a/app/test/features/chat/ui/sessions/chat_color_test.dart b/app/test/features/chat/ui/sessions/chat_color_test.dart index d82fdd40..2c458222 100644 --- a/app/test/features/chat/ui/sessions/chat_color_test.dart +++ b/app/test/features/chat/ui/sessions/chat_color_test.dart @@ -210,16 +210,16 @@ void main() { ), ), ); - final surface = tester.widget(find.byKey(appListRowSurfaceKey)); - expect(surface.color, Colors.transparent); - final highlight = tester.widget( - find.byKey(const ValueKey('chat-visibility-s1')), - ); - // The selected row is filled in its own colour. - final fill = (highlight.decoration as BoxDecoration).color!; - expect(fill.a, greaterThan(0)); + // The shared open-row style: the tonal fill, and its one bar in the + // chat's own colour. final context = tester.element(find.byType(ChatSessionRow)); - expect(fill.withValues(alpha: 1), chatColorShade(context, 'amber')); + final surface = tester.widget(find.byKey(appListRowSurfaceKey)); + expect(surface.color, AppListRow.selectedColor(context)); + final bar = tester.widget(find.byKey(appListRowSelectionKey)); + final side = + ((bar.decoration as BoxDecoration).border as BorderDirectional).start; + expect(side.color, chatColorShade(context, 'amber')); + expect(side.width, kAppListRowBarWidth); expect(find.byKey(appListRowAccentKey), findsNothing); expect(find.byKey(const ValueKey('chat-visibility-s1')), findsOneWidget); }); diff --git a/app/test/features/chat/ui/sessions/chat_visibility_marker_test.dart b/app/test/features/chat/ui/sessions/chat_visibility_marker_test.dart index 8a7a86d2..8aa482f2 100644 --- a/app/test/features/chat/ui/sessions/chat_visibility_marker_test.dart +++ b/app/test/features/chat/ui/sessions/chat_visibility_marker_test.dart @@ -25,9 +25,20 @@ BorderSide edge(WidgetTester tester, String id) { return ((box.decoration as BoxDecoration).border as BorderDirectional).start; } +/// The shared open-row bar [AppListRow] draws on the selected row of [id]. +BorderSide? selectionBar(WidgetTester tester, String id) { + final bar = find.descendant( + of: find.byKey(ValueKey('chat-visibility-$id')), + matching: find.byKey(appListRowSelectionKey), + ); + if (bar.evaluate().isEmpty) return null; + final box = tester.widget(bar); + return ((box.decoration as BoxDecoration).border as BorderDirectional).start; +} + void main() { testWidgets( - 'only visible chats have an edge; active edge widens continuously', + 'visible chats have a thin edge; the open chat has the shared selection', (tester) async { tester.platformDispatcher.accessibilityFeaturesTestValue = const FakeAccessibilityFeatures(disableAnimations: false); @@ -72,19 +83,25 @@ void main() { ), ), ); + // A selected chat not shown in a pane wears only the shared selection. expect(edge(tester, 'off').style, BorderStyle.none); + expect(selectionBar(tester, 'off')!.width, kAppListRowBarWidth); + // A chat visible elsewhere keeps its thin edge. expect(edge(tester, 'on').width, 3); + expect(selectionBar(tester, 'on'), isNull); expect(find.byKey(appListRowAccentKey), findsNothing); update(() => active = true); - await tester.pump(); - await tester.pump(const Duration(milliseconds: 100)); - expect(edge(tester, 'on').width, greaterThan(3)); - expect(edge(tester, 'on').width, lessThan(8)); await tester.pumpAndSettle(); - expect(edge(tester, 'on').width, 8); + // Opened, it is marked exactly like any open row: one bar in the + // chat's colour over the tonal fill, and no second edge. + expect(edge(tester, 'on').style, BorderStyle.none); + final bar = selectionBar(tester, 'on')!; + expect(bar.width, kAppListRowBarWidth); + expect(bar.color, isNot(Colors.transparent)); update(() => active = false); await tester.pumpAndSettle(); expect(edge(tester, 'on').width, 3); + expect(selectionBar(tester, 'on'), isNull); }, ); testWidgets('compact chats keep identity colours and visible/active edges', ( @@ -128,7 +145,18 @@ void main() { await tester.tap(find.byTooltip('New chat')); expect(newChatPressed, isTrue); expect(find.byTooltip('Expand chat list'), findsOneWidget); - expect(edge(tester, 'a').width, 8); + // The open chat: no second edge, the shared fill and bar instead. + expect(edge(tester, 'a').style, BorderStyle.none); + final open = tester + .widgetList( + find.descendant( + of: find.byKey(const ValueKey('chat-visibility-a')), + matching: find.byType(AnimatedContainer), + ), + ) + .singleWhere((box) => box.foregroundDecoration != null); + final bar = (open.foregroundDecoration as BoxDecoration).border; + expect((bar as BorderDirectional).start.width, kAppListRowBarWidth); expect(edge(tester, 'b').width, 3); expect(edge(tester, 'c').style, BorderStyle.none); final avatars = tester diff --git a/app/test/features/chat/ui/transcript/chat_code_hover_test.dart b/app/test/features/chat/ui/transcript/chat_code_hover_test.dart index 1e913b2a..e1d9d689 100644 --- a/app/test/features/chat/ui/transcript/chat_code_hover_test.dart +++ b/app/test/features/chat/ui/transcript/chat_code_hover_test.dart @@ -48,31 +48,36 @@ void main() { .setMockMethodCallHandler(SystemChannels.platform, null), ); - testWidgets( - 'fenced code reveals Copy without shifting and copies exact whitespace', - (tester) async { - const code = ' final x = 1;\n\tkeep spaces '; - await tester.pumpWidget(_host('```dart\n$code\n```')); - await tester.pumpAndSettle(); - final before = tester.getTopLeft(find.text(code)); - expect(find.text('Copy').hitTestable(), findsNothing); - final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); - await mouse.addPointer(location: const Offset(1, 1)); - await mouse.moveTo(tester.getCenter(find.text(code))); - await tester.pump(); - expect(find.text('Copy').hitTestable(), findsOneWidget); - expect(tester.getTopLeft(find.text(code)), before); - await tester.tap(find.text('Copy').hitTestable()); - await tester.pump(); - expect(copied, code); - expect(find.text('Copied').hitTestable(), findsOneWidget); - await mouse.moveTo(const Offset(1, 1)); - await tester.pump(); - expect(find.text('Copied').hitTestable(), findsNothing); - await mouse.removePointer(); - await tester.pumpWidget(const SizedBox()); - }, - ); + testWidgets('fenced code has a header strip with its language and Copy', ( + tester, + ) async { + const code = ' final x = 1;\n\tkeep spaces '; + await tester.pumpWidget(_host('```dart\n$code\n```')); + await tester.pumpAndSettle(); + // One framed block: the header strip (label and Copy) sits on top of + // the code, inside the block, and Copy needs no hover (touch has none). + final header = tester.getRect(find.byKey(const Key('chat-code-header'))); + final block = tester.getRect(find.byKey(const Key('chat-code-body'))); + final label = tester.getRect(find.text('dart')); + final copy = tester.getRect(find.text('Copy').hitTestable()); + expect(header.top, block.top); + expect(header.contains(label.center), isTrue); + expect(header.contains(copy.center), isTrue); + expect(tester.getTopLeft(find.text(code)).dy, greaterThan(header.bottom)); + expect(block.contains(tester.getCenter(find.text(code))), isTrue); + final before = tester.getTopLeft(find.text(code)); + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + await mouse.addPointer(location: const Offset(1, 1)); + await mouse.moveTo(tester.getCenter(find.text(code))); + await tester.pump(); + expect(tester.getTopLeft(find.text(code)), before); + await tester.tap(find.text('Copy').hitTestable()); + await tester.pump(); + expect(copied, code); + expect(find.text('Copied').hitTestable(), findsOneWidget); + await mouse.removePointer(); + await tester.pumpWidget(const SizedBox()); + }); testWidgets( 'inline spans retain selection, hover transfer and copy the right raw snippet', @@ -168,11 +173,11 @@ void main() { await tester.pumpWidget(const SizedBox()); }); - testWidgets('keyboard focus exposes the reserved block action', ( + testWidgets('the block action is reachable from the keyboard', ( tester, ) async { await tester.pumpWidget(_host('```text\nraw\n```')); - expect(find.text('Copy').hitTestable(), findsNothing); + expect(find.text('Copy').hitTestable(), findsOneWidget); // The selectable transcript itself is the first focus stop. await tester.sendKeyEvent(LogicalKeyboardKey.tab); await tester.pump(); diff --git a/app/test/features/chat/ui/transcript/chat_horizontal_viewport_test.dart b/app/test/features/chat/ui/transcript/chat_horizontal_viewport_test.dart index 728e6d53..6ff57484 100644 --- a/app/test/features/chat/ui/transcript/chat_horizontal_viewport_test.dart +++ b/app/test/features/chat/ui/transcript/chat_horizontal_viewport_test.dart @@ -45,6 +45,9 @@ Widget _host({ ); } +/// The chevron over the faded side with more content. +Finder _more(String side) => find.byKey(Key('chat-horizontal-more-$side')); + ScrollController _controller(WidgetTester tester) => tester.widget(find.byType(Scrollbar)).controller!; @@ -55,14 +58,16 @@ void main() { (tester) async { await tester.pumpWidget(_host(brightness: brightness)); await tester.pumpAndSettle(); - expect(find.text('Scroll horizontally'), findsOneWidget); + expect(find.byKey(const Key('chat-horizontal-fade')), findsOneWidget); final controller = _controller(tester); expect(controller.position.maxScrollExtent, 640); expect( tester.widget(find.byType(Scrollbar)).thumbVisibility, isTrue, ); - expect(find.byIcon(Icons.arrow_forward), findsOneWidget); + // More content to the right: that side fades under a chevron. + expect(_more('right'), findsOneWidget); + expect(_more('left'), findsNothing); final focus = tester .widgetList(find.byType(Focus)) .firstWhere( @@ -73,15 +78,17 @@ void main() { await tester.sendKeyEvent(LogicalKeyboardKey.arrowRight); await tester.pumpAndSettle(); expect(controller.offset, 80); - expect(find.byIcon(Icons.swap_horiz), findsOneWidget); + expect(_more('left'), findsOneWidget); + expect(_more('right'), findsOneWidget); controller.jumpTo(controller.position.maxScrollExtent); await tester.pumpAndSettle(); - expect(find.byIcon(Icons.arrow_back), findsOneWidget); + expect(_more('left'), findsOneWidget); + expect(_more('right'), findsNothing); await tester.pumpWidget( _host(brightness: brightness, contentWidth: 120), ); await tester.pumpAndSettle(); - expect(find.text('Scroll horizontally'), findsNothing); + expect(find.byKey(const Key('chat-horizontal-fade')), findsNothing); expect(tester.takeException(), isNull); }, ); @@ -92,9 +99,10 @@ void main() { (tester) async { await tester.pumpWidget(_host(direction: TextDirection.rtl)); await tester.pumpAndSettle(); - expect(find.byIcon(Icons.arrow_back), findsOneWidget); + expect(_more('left'), findsOneWidget); + expect(_more('right'), findsNothing); expect( - tester.widget(find.byIcon(Icons.arrow_back)).textDirection, + tester.widget(_more('left')).textDirection, TextDirection.ltr, ); final controller = _controller(tester); @@ -169,7 +177,7 @@ void main() { find.bySemanticsLabel('Horizontally scrollable table'), findsNothing, ); - expect(find.text('Scroll horizontally'), findsOneWidget); + expect(find.byKey(const Key('chat-horizontal-fade')), findsOneWidget); final viewport = tester.getRect(find.byType(ChatMarkdownView)); expect( tester.getRect(find.byType(Table)).right, diff --git a/app/test/features/chat/ui/transcript/chat_markdown_table_wrap_test.dart b/app/test/features/chat/ui/transcript/chat_markdown_table_wrap_test.dart index fc363745..19443bf9 100644 --- a/app/test/features/chat/ui/transcript/chat_markdown_table_wrap_test.dart +++ b/app/test/features/chat/ui/transcript/chat_markdown_table_wrap_test.dart @@ -27,7 +27,7 @@ void main() { '| No | Text | Ok |\n| --- | --- | --- |\n' '| one | ${List.filled(30, 'word').join(' ')} | done |', ); - expect(find.text('Scroll horizontally'), findsNothing); + expect(find.byKey(const Key('chat-horizontal-fade')), findsNothing); expect(tableRect(tester).right, lessThanOrEqualTo(screenRight)); final description = tester.getSize(find.textContaining('word word')); final status = tester.getSize(find.text('done')); @@ -55,7 +55,7 @@ void main() { '| --- | --- | --- | --- | --- | --- | --- |\n' '| a b | c d | e f | g h | i j | k l | m n |', ); - expect(find.text('Scroll horizontally'), findsOneWidget); + expect(find.byKey(const Key('chat-horizontal-fade')), findsOneWidget); expect( find.bySemanticsLabel('Horizontally scrollable table'), findsOneWidget, @@ -76,7 +76,7 @@ void main() { '| Column | Notes |\n| --- | --- |\n' '| x | ${List.filled(40, 'note').join(' ')} |', ); - expect(find.text('Scroll horizontally'), findsNothing); + expect(find.byKey(const Key('chat-horizontal-fade')), findsNothing); expect(tableRect(tester).right, lessThanOrEqualTo(screenRight)); final header = tester.getSize(find.text('Column')).height; expect(header, tester.getSize(find.text('x')).height); diff --git a/app/test/features/pipelines/pipeline_list_composition_test.dart b/app/test/features/pipelines/pipeline_list_composition_test.dart index c35ae3f9..0ccefe56 100644 --- a/app/test/features/pipelines/pipeline_list_composition_test.dart +++ b/app/test/features/pipelines/pipeline_list_composition_test.dart @@ -55,6 +55,11 @@ void main() { expect(find.textContaining('v2 · #'), findsNothing); expect(find.text('2 stages · 1 schedule'), findsOneWidget); expect(find.byKey(const Key('pipeline-status-1')), findsOneWidget); + // The state is spelled out beside its dot, with when the run was. + expect( + tester.widget(find.byKey(const Key('pipeline-status-text-1'))).data, + matches(RegExp(r'^Succeeded · last run .+')), + ); expect(find.byKey(const Key('pipeline-status-2')), findsOneWidget); expect(find.text('no runs recorded'), findsNothing); }); @@ -142,7 +147,10 @@ void main() { findsOneWidget, ); expect( - find.descendant(of: firstRow, matching: find.text('Succeeded')), + find.descendant( + of: firstRow, + matching: find.textContaining(RegExp(r'^Succeeded( · .+)?$')), + ), findsOneWidget, ); expect( @@ -204,7 +212,10 @@ void main() { runs.complete(runListReply(fixture.runs)); await tester.pumpAndSettle(); expect( - find.descendant(of: firstRow, matching: find.text('Succeeded')), + find.descendant( + of: firstRow, + matching: find.textContaining(RegExp(r'^Succeeded( · .+)?$')), + ), findsOneWidget, ); expect(tester.takeException(), isNull); diff --git a/app/test/features/runs/ui/run_artifacts_action_test.dart b/app/test/features/runs/ui/run_artifacts_action_test.dart index fd1595a3..970ec49c 100644 --- a/app/test/features/runs/ui/run_artifacts_action_test.dart +++ b/app/test/features/runs/ui/run_artifacts_action_test.dart @@ -4,6 +4,7 @@ import 'package:pipelines_app/core/api_gateway.dart'; import 'package:pipelines_app/features/runs/data/runs_repository.dart'; import 'package:pipelines_app/features/runs/ui/run_detail_view.dart'; import 'package:pipelines_app/features/runs/ui/runs_controller.dart'; +import 'package:pipelines_app/ui/adaptive/floating_tab_button.dart'; import '../../artifacts/domain/artifact_fixtures.dart'; @@ -97,16 +98,44 @@ void main() { expect(find.text('reviewer · visit 1'), findsOneWidget); }); - testWidgets('the action is offered only when the detail has steps', ( + /// The Artifacts tab keeps its place on a run with none: disabled, badged + /// `0`, and its tooltip (and accessibility hint) says why. + Future expectDisabledArtifacts(WidgetTester tester, String why) async { + final tab = find.byKey(const ValueKey('run-detail-tab-artifacts')); + expect(tab, findsOneWidget); + final button = tester.widget(tab); + expect(button.enabled, isFalse); + expect(button.tooltip, why); + expect( + find.descendant( + of: tab, + matching: find.byKey(const ValueKey('run-detail-artifacts-count')), + ), + findsOneWidget, + ); + expect(find.descendant(of: tab, matching: find.text('0')), findsOneWidget); + // A tap does not open an empty gallery: Summary stays. + await tester.tap(tab, warnIfMissed: false); + await tester.pumpAndSettle(); + expect(find.text(why), findsNothing); + // Changes, after it, keeps its place. + final order = [ + for (final name in ['summary', 'timeline', 'artifacts', 'changes']) + tester.getCenter(find.byKey(ValueKey('run-detail-tab-$name'))).dx, + ]; + expect(order, orderedEquals([...order]..sort())); + } + + testWidgets('a run without steps keeps a disabled Artifacts tab', ( tester, ) async { final gateway = _FakeGateway(_run(steps: const [])); final controller = await _loaded(gateway); addTearDown(controller.dispose); await _pumpDetail(tester, controller, gateway); - expect( - find.byKey(const ValueKey('run-detail-tab-artifacts')), - findsNothing, + await expectDisabledArtifacts( + tester, + 'No artifacts recorded for this run.', ); }); @@ -121,16 +150,10 @@ void main() { final controller = await _loaded(gateway); addTearDown(controller.dispose); await _pumpDetail(tester, controller, gateway); - - await tester.ensureVisible( - find.byKey(const ValueKey('run-detail-tab-artifacts')), + await expectDisabledArtifacts( + tester, + 'No artifacts recorded for this run.', ); - - await tester.pumpAndSettle(); - - await tester.tap(find.byKey(const ValueKey('run-detail-tab-artifacts'))); - await tester.pumpAndSettle(); - expect(find.text('No artifacts recorded for this run.'), findsOneWidget); }); testWidgets('an unavailable capture is never reported as empty', ( @@ -142,16 +165,6 @@ void main() { final controller = await _loaded(gateway); addTearDown(controller.dispose); await _pumpDetail(tester, controller, gateway); - - await tester.ensureVisible( - find.byKey(const ValueKey('run-detail-tab-artifacts')), - ); - - await tester.pumpAndSettle(); - - await tester.tap(find.byKey(const ValueKey('run-detail-tab-artifacts'))); - await tester.pumpAndSettle(); - expect(find.text('Artifacts · capture unavailable'), findsOneWidget); - expect(find.text('No artifacts recorded for this run.'), findsNothing); + await expectDisabledArtifacts(tester, 'Artifacts · capture unavailable'); }); } diff --git a/app/test/features/runs/ui/run_detail_flat_bodies_test.dart b/app/test/features/runs/ui/run_detail_flat_bodies_test.dart index 1a48bff5..a8f7f3e5 100644 --- a/app/test/features/runs/ui/run_detail_flat_bodies_test.dart +++ b/app/test/features/runs/ui/run_detail_flat_bodies_test.dart @@ -10,8 +10,8 @@ import 'package:pipelines_app/ui/adaptive/floating_bar_layout.dart'; import 'run_detail_graph_support.dart'; import 'run_detail_visit_support.dart'; -/// The run and stage detail bodies are flat on the page, and beside a list one -/// row of tabs and header. +/// The run and stage detail bodies are flat on the page, and beside a list +/// the tabs sit under the header in one strip. void main() { testWidgets('Summary and Timeline show their bodies', (tester) async { await pumpRunDetail(tester, RunDetailTestPlatform.material); @@ -28,7 +28,7 @@ void main() { expect(tester.takeException(), isNull); }); - testWidgets('beside a list the tabs and the header share one row', ( + testWidgets('beside a list the tabs sit under the header at the top', ( tester, ) async { tester.view.physicalSize = const Size(720, 900); @@ -51,11 +51,13 @@ void main() { final tabs = tester.getRect(find.byKey(const Key('run-detail-tabs'))); final header = tester.getRect(find.byKey(const Key('run-detail-header'))); - // Side by side, not stacked: the header starts after the tabs and - // overlaps them vertically. - expect(header.left, greaterThanOrEqualTo(tabs.right - 12)); - expect(header.top, lessThan(tabs.bottom)); - expect(header.bottom, greaterThan(tabs.top)); + // One strip at the top: the tabs are inside it, at its foot, and the + // whole strip sits near the top of the 900px detail. + expect(tabs.top, greaterThan(header.top)); + expect(tabs.bottom, lessThanOrEqualTo(header.bottom)); + expect(tabs.left, greaterThanOrEqualTo(header.left)); + expect(header.top, lessThan(120)); + expect(tester.getRect(find.text('Summary')).top, greaterThan(header.top)); expect(tester.takeException(), isNull); }); } diff --git a/app/test/features/runs/ui/run_detail_tabs_test.dart b/app/test/features/runs/ui/run_detail_tabs_test.dart index 02a01658..b3a48af5 100644 --- a/app/test/features/runs/ui/run_detail_tabs_test.dart +++ b/app/test/features/runs/ui/run_detail_tabs_test.dart @@ -59,18 +59,21 @@ void main() { previous = center.dx; } expect(find.byKey(runMoreMenuKey), findsOneWidget); - // The tabs are the floating glass bar: on this 900px detail it is sized - // to its tabs at the right edge, above the bottom. - final pill = tester.getRect( + // On this wide 900px detail the tabs are Material segments under the + // run header, at the top of the detail, not a floating bottom bar. + final row = tester.getRect(strip); + final header = tester.getRect(find.byKey(const Key('run-detail-header'))); + expect(find.byType(SegmentedButton), findsOneWidget); + expect( find.descendant( of: strip, matching: find.byKey(FloatingDestinationBar.rowKey), ), + findsNothing, ); - expect(pill.right, 900 - 16); - expect(pill.bottom, 1000 - 16); - // (The test font draws every glyph a full em wide.) - expect(pill.width, lessThan(900 * 0.7)); + expect(row.top, greaterThan(header.top)); + expect(row.bottom, lessThanOrEqualTo(header.bottom)); + expect(row.top, lessThan(1000 / 3)); for (final tab in [ RunDetailTab.timeline, @@ -122,19 +125,24 @@ void main() { greaterThanOrEqualTo(844 - pill.top), ); + // Wide, the tabs move to the top under the header; the content still + // fills the pane and starts below them at rest. await pumpRunDetail(tester, platform, size: const Size(1000, 844)); - final widePill = tester.getRect( + final wideTabs = tester.getRect(strip); + expect(wideTabs.top, lessThan(844 / 3)); + expect( find.descendant( of: strip, matching: find.byKey(FloatingDestinationBar.rowKey), ), + findsNothing, ); - expect(widePill.right, 1000 - 16); - expect(widePill.bottom, 844 - 16); - expect(widePill.width, lessThan(1000 * 0.6)); - // Beside the bar the content takes taps: the body fills the pane. expect(tester.getRect(body).left, 0); expect(tester.getRect(body).width, 1000); + expect( + MediaQuery.paddingOf(tester.element(body)).top, + greaterThanOrEqualTo(wideTabs.bottom), + ); }); testWidgets('${platform.name} missing graph states the exact wording', ( diff --git a/app/test/features/runs/ui/run_list_row_test.dart b/app/test/features/runs/ui/run_list_row_test.dart index 40130ff9..cf3def37 100644 --- a/app/test/features/runs/ui/run_list_row_test.dart +++ b/app/test/features/runs/ui/run_list_row_test.dart @@ -187,4 +187,30 @@ void main() { expect(tester.takeException(), isNull); }); } + + testWidgets('under a day heading a row shows only its time of day', ( + tester, + ) async { + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + body: RunListRow( + run: _finished, + now: DateTime.utc(2026, 10, 22), + timeOfDay: true, + ), + ), + ), + ); + final created = DateTime.parse('${_finished['created_at']}'); + expect(find.byType(RelativeTimeLabel), findsNothing); + final time = tester.widget( + find.byKey(const ValueKey('run-row-time-42')), + ); + expect(time.data, runTimeOfDay(created)); + expect(time.data, matches(RegExp(r'^\d\d:\d\d$'))); + // The day the heading already names is not repeated on the row. + final local = created.toLocal(); + expect(find.textContaining('${local.day} Oct'), findsNothing); + }); } diff --git a/app/test/features/settings/settings_actions_test.dart b/app/test/features/settings/settings_actions_test.dart new file mode 100644 index 00000000..f6a3044c --- /dev/null +++ b/app/test/features/settings/settings_actions_test.dart @@ -0,0 +1,49 @@ +import 'package:flutter/material.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/features/settings/settings_controls.dart'; + +Widget _actions({required bool connected}) => MaterialApp( + home: Scaffold( + body: SettingsActions( + primaryLabel: connected ? 'Disconnect' : 'Connect', + secondaryLabel: 'Reconnect', + primaryKey: const Key('primary'), + secondaryKey: const Key('secondary'), + primaryOutlined: connected, + onPrimary: () {}, + onSecondary: () {}, + ), + ), +); + +void main() { + testWidgets('connected: Reconnect is tonal and leads, Disconnect outlined', ( + tester, + ) async { + await tester.pumpWidget(_actions(connected: true)); + final disconnect = find.byKey(const Key('primary')); + final reconnect = find.byKey(const Key('secondary')); + expect(tester.widget(disconnect), isA()); + expect(tester.widget(reconnect), isA()); + // Never the filled primary emphasis on the action that drops the link. + expect(find.byType(OutlinedButton), findsOneWidget); + expect( + tester.getTopLeft(reconnect).dx, + lessThan(tester.getTopLeft(disconnect).dx), + ); + }); + + testWidgets('disconnected: Connect is filled, Reconnect outlined', ( + tester, + ) async { + await tester.pumpWidget(_actions(connected: false)); + final connect = find.byKey(const Key('primary')); + final reconnect = find.byKey(const Key('secondary')); + expect(tester.widget(connect), isA()); + expect(tester.widget(reconnect), isA()); + expect( + tester.getTopLeft(connect).dx, + lessThan(tester.getTopLeft(reconnect).dx), + ); + }); +} diff --git a/app/test/ui/layout/app_list_row_test.dart b/app/test/ui/layout/app_list_row_test.dart index 3a771e19..40a923f0 100644 --- a/app/test/ui/layout/app_list_row_test.dart +++ b/app/test/ui/layout/app_list_row_test.dart @@ -147,11 +147,21 @@ void main() { AppListRow.selectedColor(context), ); final accent = Theme.of(context).colorScheme.primary; + // The one selection style every list shares: the tonal fill plus one + // leading bar in the accent. + final bar = tester.widget( + find.descendant(of: row, matching: find.byKey(appListRowSelectionKey)), + ); + final side = + ((bar.decoration as BoxDecoration).border as BorderDirectional).start; + expect(side.color, accent); + expect(side.width, kAppListRowBarWidth); expect(_paint(tester, 'Fixture run').fontWeight, FontWeight.w700); expect(_paint(tester, '9d ago').color, accent); await tester.pumpWidget(_host(_row())); expect(tester.widget(surface).color, const Color(0x00000000)); + expect(find.byKey(appListRowSelectionKey), findsNothing); expect(_paint(tester, '9d ago').color, isNot(accent)); }); From ff5d8595e4c44770be845b49716ce9aa3b8348d7 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 00:57:51 +0000 Subject: [PATCH 17/19] Cheatsheet: J/K and arrows move between changed files in the wide Changes view Co-Authored-By: Claude Opus 5.5 --- app/lib/features/settings/keyboard_shortcuts_registry.dart | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/app/lib/features/settings/keyboard_shortcuts_registry.dart b/app/lib/features/settings/keyboard_shortcuts_registry.dart index 310a5fd3..f3914a76 100644 --- a/app/lib/features/settings/keyboard_shortcuts_registry.dart +++ b/app/lib/features/settings/keyboard_shortcuts_registry.dart @@ -302,6 +302,13 @@ class KeyboardShortcutRegistry { caveat: 'In a run: Summary, Timeline, Artifacts, Changes, as the run offers them. Not while typing.', ), + const KeyboardShortcutEntry( + group: KeyboardShortcutGroup.lists, + action: 'Next or previous changed file', + keys: 'J, K, Down, Up', + caveat: + 'In Changes on a wide window, once the file list has focus; Enter opens the file on its own page. Not while typing.', + ), const KeyboardShortcutEntry( group: KeyboardShortcutGroup.lists, action: 'Resize a list pane', From bbeb90339baf38d11428f509e071d37f41f9caea Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 01:07:34 +0000 Subject: [PATCH 18/19] Run tab keys test: read the selected tab from the top segments on wide layouts Co-Authored-By: Claude Opus 5.5 --- .../runs/ui/run_detail_tab_keys_test.dart | 24 ++++++++++++------- 1 file changed, 16 insertions(+), 8 deletions(-) diff --git a/app/test/features/runs/ui/run_detail_tab_keys_test.dart b/app/test/features/runs/ui/run_detail_tab_keys_test.dart index 9a0da857..825a7f59 100644 --- a/app/test/features/runs/ui/run_detail_tab_keys_test.dart +++ b/app/test/features/runs/ui/run_detail_tab_keys_test.dart @@ -2,17 +2,25 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/ui/adaptive/floating_destination_bar.dart'; +import 'package:pipelines_app/features/runs/ui/run_detail_top_tabs.dart'; import 'run_detail_graph_support.dart'; -int _current(WidgetTester tester) => tester - .widget( - find.descendant( - of: find.byKey(const Key('run-detail-tabs')), - matching: find.byType(FloatingDestinationBar), - ), - ) - .currentIndex; +/// The selected tab's index, from the bottom bar (narrow) or the top +/// segments (wide), whichever the layout shows. +int _current(WidgetTester tester) { + final bar = find.descendant( + of: find.byKey(const Key('run-detail-tabs')), + matching: find.byType(FloatingDestinationBar), + ); + if (bar.evaluate().isNotEmpty) { + return tester.widget(bar).currentIndex; + } + final segments = tester.widget( + find.byType(RunDetailTopTabs), + ); + return segments.tabs.indexOf(segments.selected); +} void main() { testWidgets('bare 1-4 switch the run detail tabs', (tester) async { From c0b2bda474a285e9bc641a81e42415a5b07d81f1 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Thu, 3 Dec 2026 01:08:21 +0000 Subject: [PATCH 19/19] Server: rename the scoped search's rune-length helper so it doesn't clash Merging the reliability branch added another utf16Len; 66a12207 also records the merge of worktree-agent-a588aaf81441341cd. Co-Authored-By: Claude Opus 5.5 --- internal/server/search_chat_scoped.go | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/internal/server/search_chat_scoped.go b/internal/server/search_chat_scoped.go index 7e4973db..50d476d5 100644 --- a/internal/server/search_chat_scoped.go +++ b/internal/server/search_chat_scoped.go @@ -165,7 +165,7 @@ func runeMatches(text, query []rune, caseSensitive bool) []runeMatch { units := 0 // UTF-16 units before text[i] for i := 0; i <= len(text)-len(query); { if runesEqual(text[i:i+len(query)], query, caseSensitive) { - length := utf16Len(text[i : i+len(query)]) + length := utf16RunesLen(text[i : i+len(query)]) matches = append(matches, runeMatch{offset: units, length: length}) units += length i += len(query) @@ -201,7 +201,7 @@ func foldEqual(a, b rune) bool { return false } -func utf16Len(runes []rune) int { +func utf16RunesLen(runes []rune) int { n := 0 for _, r := range runes { n += utf16.RuneLen(r)