From f2520a09b884d6f342a5aeb47180f3eed91ff54e Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 9 Nov 2026 23:29:25 +0000 Subject: [PATCH 1/2] Keep dismissed shell commands and restore them without a time limit A dismissed run keeps its command, status, times and output within the usual history bounds. chat_shell_runs lists dismissed runs apart (chat_shell_dismissed_runs), chat_shell_run_output still reads them, and the purge timer and startup purge are gone. Rows an older server purged are listed with purged set and cannot be restored. --- internal/pipeline/chat_shell_dismiss.go | 60 +++----- internal/pipeline/chat_shell_dismiss_test.go | 143 ++++++++++++------- internal/pipeline/chat_shell_runs.go | 26 +--- internal/protocol/chat_shell_dismiss.go | 26 ++-- internal/protocol/chat_shell_run.go | 6 + internal/protocol/message.go | 7 +- internal/server/chat_shell_dismiss.go | 55 +++---- internal/server/chat_shell_dismiss_test.go | 55 ++++--- internal/server/chat_shell_run_handlers.go | 5 +- internal/server/chat_shell_runner.go | 7 +- 10 files changed, 204 insertions(+), 186 deletions(-) diff --git a/internal/pipeline/chat_shell_dismiss.go b/internal/pipeline/chat_shell_dismiss.go index d329320d..ff265a46 100644 --- a/internal/pipeline/chat_shell_dismiss.go +++ b/internal/pipeline/chat_shell_dismiss.go @@ -8,10 +8,10 @@ import ( ) // initChatShellDismissals adds the dismissal columns of chat_shell_runs. A -// dismissed run (dismissed_at > 0) is left out of every readback; once its -// undo window has passed it is purged: its command, output and error are -// deleted and only a tombstone (id, session, status, times) remains, which -// tells a client that missed the dismissal to drop its card. +// dismissed run (dismissed_at > 0) leaves the transcript readback but keeps +// its command, output and error, so the operator can still read and restore +// it. purged marks a row an older server emptied after its undo window: only +// a tombstone (id, session, status, times) remains of it. func (s *Store) initChatShellDismissals() error { for _, column := range [][2]string{ {"dismissed_at", "INTEGER NOT NULL DEFAULT 0"}, @@ -48,9 +48,9 @@ WHERE session_id = ? AND id = ? AND status != ? AND dismissed_at = 0`, at, sessi } // RestoreChatShellRuns undoes the dismissal of the runs of sessionID among ids -// that were dismissed at or after since and not yet purged, and returns them, -// oldest first. -func (s *Store) RestoreChatShellRuns(ctx context.Context, sessionID string, ids []string, since int64) ([]protocol.ChatShellRunRecord, error) { +// that are dismissed and not purged, however long ago they were dismissed, +// and returns them, oldest first. +func (s *Store) RestoreChatShellRuns(ctx context.Context, sessionID string, ids []string) ([]protocol.ChatShellRunRecord, error) { tx, err := s.db.BeginTx(ctx, nil) if err != nil { return nil, err @@ -59,7 +59,7 @@ func (s *Store) RestoreChatShellRuns(ctx context.Context, sessionID string, ids var restored []string for _, id := range ids { result, err := tx.ExecContext(ctx, `UPDATE chat_shell_runs SET dismissed_at = 0 -WHERE session_id = ? AND id = ? AND dismissed_at > 0 AND dismissed_at >= ? AND purged = 0`, sessionID, id, since) +WHERE session_id = ? AND id = ? AND dismissed_at > 0 AND purged = 0`, sessionID, id) if err != nil { return nil, err } @@ -74,8 +74,19 @@ WHERE session_id = ? AND id = ? AND dismissed_at > 0 AND dismissed_at >= ? AND p for _, id := range restored { args = append(args, id) } - rows, err := s.db.QueryContext(ctx, chatShellRunSelect+` WHERE session_id = ? AND id IN (?`+ + return s.queryChatShellRuns(ctx, ` WHERE session_id = ? AND id IN (?`+ strings.Repeat(", ?", len(restored)-1)+`) ORDER BY started_at, id`, args...) +} + +// DismissedChatShellRuns lists sessionID's dismissed runs, oldest first, with +// their whole retained output. A purged one (an older server's tombstone) has +// no command or output. +func (s *Store) DismissedChatShellRuns(ctx context.Context, sessionID string) ([]protocol.ChatShellRunRecord, error) { + return s.queryChatShellRuns(ctx, ` WHERE session_id = ? AND dismissed_at > 0 ORDER BY started_at, id`, sessionID) +} + +func (s *Store) queryChatShellRuns(ctx context.Context, where string, args ...any) ([]protocol.ChatShellRunRecord, error) { + rows, err := s.db.QueryContext(ctx, chatShellRunSelect+where, args...) if err != nil { return nil, err } @@ -90,34 +101,3 @@ WHERE session_id = ? AND id = ? AND dismissed_at > 0 AND dismissed_at >= ? AND p } return runs, rows.Err() } - -// PurgeDismissedChatShellRuns deletes the command, output and error of every -// run dismissed before epoch millisecond before, leaving its tombstone. -func (s *Store) PurgeDismissedChatShellRuns(ctx context.Context, before int64) (int64, error) { - result, err := s.db.ExecContext(ctx, `UPDATE chat_shell_runs SET command = '', output = '', output_text = '', error = '', -output_start = 0, output_bytes = 0, purged = 1 WHERE dismissed_at > 0 AND dismissed_at < ? AND purged = 0`, before) - if err != nil { - return 0, err - } - return result.RowsAffected() -} - -// DismissedChatShellRuns lists the ids of sessionID's dismissed runs, oldest -// first: the tombstones a readback reports so clients drop those cards. -func (s *Store) DismissedChatShellRuns(ctx context.Context, sessionID string) ([]string, error) { - rows, err := s.db.QueryContext(ctx, `SELECT id FROM chat_shell_runs WHERE session_id = ? AND dismissed_at > 0 -ORDER BY started_at, id`, sessionID) - if err != nil { - return nil, err - } - defer rows.Close() - var ids []string - for rows.Next() { - var id string - if err := rows.Scan(&id); err != nil { - return nil, err - } - ids = append(ids, id) - } - return ids, rows.Err() -} diff --git a/internal/pipeline/chat_shell_dismiss_test.go b/internal/pipeline/chat_shell_dismiss_test.go index 009ca864..9160ad70 100644 --- a/internal/pipeline/chat_shell_dismiss_test.go +++ b/internal/pipeline/chat_shell_dismiss_test.go @@ -9,7 +9,19 @@ import ( "git.a-wan.net/alan/pipelines/internal/protocol" ) -func TestChatShellRunsDismissRestoreAndPurge(t *testing.T) { +func chatShellIDs(t *testing.T, runs []protocol.ChatShellRunRecord, err error) string { + t.Helper() + if err != nil { + t.Fatal(err) + } + var out []string + for _, run := range runs { + out = append(out, run.ID) + } + return fmt.Sprint(out) +} + +func TestChatShellRunsDismissKeepsOutputAndRestores(t *testing.T) { ctx := context.Background() store, err := Open(filepath.Join(t.TempDir(), "shell.db")) if err != nil { @@ -18,8 +30,10 @@ func TestChatShellRunsDismissRestoreAndPurge(t *testing.T) { defer store.Close() save := func(id, session, status string, started int64) { t.Helper() + code := 3 run := protocol.ChatShellRunRecord{ID: id, SessionID: session, Command: "echo " + id, Directory: "/w", Status: status, - StartedAt: started, Output: "out " + id, OutputBytes: 6, Text: "out " + id, Error: "err"} + ExitCode: &code, StartedAt: started, EndedAt: started + 5, DurationMS: 5, Output: "out " + id, OutputBytes: 6, + Text: "out " + id, Error: "err"} if err := store.SaveChatShellRun(ctx, run, 0); err != nil { t.Fatal(err) } @@ -28,17 +42,10 @@ func TestChatShellRunsDismissRestoreAndPurge(t *testing.T) { save("run_b", "ses_1", protocol.ChatShellRunFailed, 2) save("run_live", "ses_1", protocol.ChatShellRunRunning, 3) save("run_other", "ses_2", protocol.ChatShellRunExited, 4) - ids := func(session string) string { + listed := func(session string) string { t.Helper() runs, err := store.ChatShellRuns(ctx, session) - if err != nil { - t.Fatal(err) - } - var out []string - for _, run := range runs { - out = append(out, run.ID) - } - return fmt.Sprint(out) + return chatShellIDs(t, runs, err) } // Running, foreign and unknown runs are skipped. @@ -46,57 +53,93 @@ func TestChatShellRunsDismissRestoreAndPurge(t *testing.T) { if err != nil || fmt.Sprint(dismissed) != "[run_a]" { t.Fatalf("dismissed = %v, %v", dismissed, err) } - if got := ids("ses_1"); got != "[run_b run_live]" { + if got := listed("ses_1"); got != "[run_b run_live]" { t.Fatalf("readback after dismiss = %s", got) } - if _, found, _ := store.ChatShellRun(ctx, "ses_1", "run_a"); found { - t.Fatal("a dismissed run is still readable") - } if again, _ := store.DismissChatShellRuns(ctx, "ses_1", []string{"run_a"}, 1001); len(again) != 0 { t.Fatalf("dismissed twice: %v", again) } - if tombs, _ := store.DismissedChatShellRuns(ctx, "ses_1"); fmt.Sprint(tombs) != "[run_a]" { - t.Fatalf("tombstones = %v", tombs) + + // The dismissed run keeps its command, status, times and output. + held, err := store.DismissedChatShellRuns(ctx, "ses_1") + if err != nil || len(held) != 1 { + t.Fatalf("dismissed runs = %+v, %v", held, err) + } + if run := held[0]; run.ID != "run_a" || !run.Dismissed || run.DismissedAt != 1000 || run.Purged || + run.Command != "echo run_a" || run.Output != "out run_a" || run.Text != "out run_a" || + run.ExitCode == nil || *run.ExitCode != 3 || run.DurationMS != 5 || run.EndedAt != 6 { + t.Fatalf("dismissed run = %+v", run) + } + if run, found, err := store.ChatShellRun(ctx, "ses_1", "run_a"); err != nil || !found || !run.Dismissed || run.Output != "out run_a" { + t.Fatalf("reading a dismissed run = %+v, %v, %v", run, found, err) } - // Undo inside the window restores the whole record. - restored, err := store.RestoreChatShellRuns(ctx, "ses_1", []string{"run_a", "run_b"}, 900) - if err != nil || len(restored) != 1 || restored[0].ID != "run_a" || restored[0].Output != "out run_a" || restored[0].Text != "out run_a" { + // Restore has no time limit and brings the whole record back. + restored, err := store.RestoreChatShellRuns(ctx, "ses_1", []string{"run_a", "run_b"}) + if err != nil || len(restored) != 1 || restored[0].ID != "run_a" || restored[0].Dismissed || restored[0].Output != "out run_a" { t.Fatalf("restored = %+v, %v", restored, err) } - if got := ids("ses_1"); got != "[run_a run_b run_live]" { + if got := listed("ses_1"); got != "[run_a run_b run_live]" { t.Fatalf("readback after restore = %s", got) } - - // Past the window: no restore, and the purge keeps only a tombstone. - if _, err := store.DismissChatShellRuns(ctx, "ses_1", []string{"run_a", "run_b"}, 2000); err != nil { - t.Fatal(err) + if runs, err := store.DismissedChatShellRuns(ctx, "ses_1"); chatShellIDs(t, runs, err) != "[]" { + t.Fatalf("dismissed after restore = %+v", runs) } - if late, err := store.RestoreChatShellRuns(ctx, "ses_1", []string{"run_a"}, 2001); err != nil || len(late) != 0 { - t.Fatalf("late restore = %+v, %v", late, err) - } - if n, err := store.PurgeDismissedChatShellRuns(ctx, 2000); err != nil || n != 0 { - t.Fatalf("purged inside the window: %d, %v", n, err) - } - if n, err := store.PurgeDismissedChatShellRuns(ctx, 2001); err != nil || n != 2 { - t.Fatalf("purge = %d, %v", n, err) - } - if restoredPurged, _ := store.RestoreChatShellRuns(ctx, "ses_1", []string{"run_a"}, 0); len(restoredPurged) != 0 { - t.Fatalf("a purged run was restored: %+v", restoredPurged) - } - var command, output, text, errText string - var bytes int64 - if err := store.db.QueryRowContext(ctx, `SELECT command, output, output_text, error, output_bytes FROM chat_shell_runs WHERE id = 'run_a'`). - Scan(&command, &output, &text, &errText, &bytes); err != nil { - t.Fatal(err) - } - if command != "" || output != "" || text != "" || errText != "" || bytes != 0 { - t.Fatalf("purged row kept %q %q %q %q %d", command, output, text, errText, bytes) - } - if tombs, _ := store.DismissedChatShellRuns(ctx, "ses_1"); fmt.Sprint(tombs) != "[run_a run_b]" { - t.Fatalf("tombstones = %v", tombs) - } - if got := ids("ses_2"); got != "[run_other]" { + if got := listed("ses_2"); got != "[run_other]" { t.Fatalf("another session changed: %s", got) } } + +func TestChatShellRunsListOlderPurgedTombstones(t *testing.T) { + ctx := context.Background() + store, err := Open(filepath.Join(t.TempDir(), "shell.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + run := protocol.ChatShellRunRecord{ID: "run_old", SessionID: "ses_1", Directory: "/w", + Status: protocol.ChatShellRunExited, StartedAt: 10, EndedAt: 20, DurationMS: 10} + if err := store.SaveChatShellRun(ctx, run, 0); err != nil { + t.Fatal(err) + } + // An older server purged this dismissed row after its undo window. + if _, err := store.db.ExecContext(ctx, `UPDATE chat_shell_runs SET dismissed_at = 15, purged = 1 WHERE id = 'run_old'`); err != nil { + t.Fatal(err) + } + held, err := store.DismissedChatShellRuns(ctx, "ses_1") + if err != nil || len(held) != 1 || !held[0].Purged || !held[0].Dismissed || held[0].Command != "" || held[0].Output != "" { + t.Fatalf("tombstone = %+v, %v", held, err) + } + if restored, err := store.RestoreChatShellRuns(ctx, "ses_1", []string{"run_old"}); err != nil || len(restored) != 0 { + t.Fatalf("a purged run was restored: %+v, %v", restored, err) + } +} + +func TestChatShellRunsDismissedCountTowardHistory(t *testing.T) { + ctx := context.Background() + store, err := Open(filepath.Join(t.TempDir(), "shell.db")) + if err != nil { + t.Fatal(err) + } + defer store.Close() + for i := range 4 { + run := protocol.ChatShellRunRecord{ID: fmt.Sprintf("run_%d", i), SessionID: "ses_1", Command: "true", Directory: "/w", + Status: protocol.ChatShellRunExited, StartedAt: int64(i + 1)} + if err := store.SaveChatShellRun(ctx, run, 3); err != nil { + t.Fatal(err) + } + if i == 1 { + if _, err := store.DismissChatShellRuns(ctx, "ses_1", []string{"run_0", "run_1"}, 100); err != nil { + t.Fatal(err) + } + } + } + dismissed, err := store.DismissedChatShellRuns(ctx, "ses_1") + if got := chatShellIDs(t, dismissed, err); got != "[run_1]" { + t.Fatalf("dismissed kept = %s", got) + } + kept, err := store.ChatShellRuns(ctx, "ses_1") + if got := chatShellIDs(t, kept, err); got != "[run_2 run_3]" { + t.Fatalf("runs kept = %s", got) + } +} diff --git a/internal/pipeline/chat_shell_runs.go b/internal/pipeline/chat_shell_runs.go index cdabddc0..0de80c53 100644 --- a/internal/pipeline/chat_shell_runs.go +++ b/internal/pipeline/chat_shell_runs.go @@ -84,26 +84,13 @@ cols = excluded.cols, rows = excluded.rows, output_text = excluded.output_text`, // ChatShellRuns lists one session's runs, oldest first, leaving out dismissed // ones. func (s *Store) ChatShellRuns(ctx context.Context, sessionID string) ([]protocol.ChatShellRunRecord, error) { - rows, err := s.db.QueryContext(ctx, chatShellRunSelect+` WHERE session_id = ? AND dismissed_at = 0 ORDER BY started_at, id`, sessionID) - if err != nil { - return nil, err - } - defer rows.Close() - var runs []protocol.ChatShellRunRecord - for rows.Next() { - run, err := scanChatShellRun(rows) - if err != nil { - return nil, err - } - runs = append(runs, run) - } - return runs, rows.Err() + return s.queryChatShellRuns(ctx, ` WHERE session_id = ? AND dismissed_at = 0 ORDER BY started_at, id`, sessionID) } -// ChatShellRun returns one run of sessionID; found is false when that session -// has no undismissed run with this id. +// ChatShellRun returns one run of sessionID, dismissed or not (a dismissed +// one is flagged); found is false when that session has no run with this id. func (s *Store) ChatShellRun(ctx context.Context, sessionID, id string) (protocol.ChatShellRunRecord, bool, error) { - run, err := scanChatShellRun(s.db.QueryRowContext(ctx, chatShellRunSelect+` WHERE session_id = ? AND id = ? AND dismissed_at = 0`, sessionID, id)) + run, err := scanChatShellRun(s.db.QueryRowContext(ctx, chatShellRunSelect+` WHERE session_id = ? AND id = ?`, sessionID, id)) if errors.Is(err, sql.ErrNoRows) { return protocol.ChatShellRunRecord{}, false, nil } @@ -123,14 +110,14 @@ duration_ms = CASE WHEN ? > started_at THEN ? - started_at ELSE 0 END WHERE stat return result.RowsAffected() } -const chatShellRunSelect = `SELECT id, session_id, command, directory, status, exit_code, signal, error, started_at, ended_at, duration_ms, output, output_start, output_bytes, terminal, cols, rows, output_text FROM chat_shell_runs` +const chatShellRunSelect = `SELECT id, session_id, command, directory, status, exit_code, signal, error, started_at, ended_at, duration_ms, output, output_start, output_bytes, terminal, cols, rows, output_text, dismissed_at, purged FROM chat_shell_runs` func scanChatShellRun(row chatQueueScanner) (protocol.ChatShellRunRecord, error) { var run protocol.ChatShellRunRecord var exit sql.NullInt64 err := row.Scan(&run.ID, &run.SessionID, &run.Command, &run.Directory, &run.Status, &exit, &run.Signal, &run.Error, &run.StartedAt, &run.EndedAt, &run.DurationMS, &run.Output, &run.OutputStart, &run.OutputBytes, - &run.Terminal, &run.Cols, &run.Rows, &run.Text) + &run.Terminal, &run.Cols, &run.Rows, &run.Text, &run.DismissedAt, &run.Purged) if err != nil { return protocol.ChatShellRunRecord{}, err } @@ -139,5 +126,6 @@ func scanChatShellRun(row chatQueueScanner) (protocol.ChatShellRunRecord, error) run.ExitCode = &code } run.Truncated = run.OutputStart > 0 + run.Dismissed = run.DismissedAt > 0 return run, nil } diff --git a/internal/protocol/chat_shell_dismiss.go b/internal/protocol/chat_shell_dismiss.go index da3db3eb..042cb181 100644 --- a/internal/protocol/chat_shell_dismiss.go +++ b/internal/protocol/chat_shell_dismiss.go @@ -1,26 +1,26 @@ package protocol // Dismissing operator shell commands. Dismissal is per chat, for every client: -// a dismissed run leaves every chat_shell_runs readback and every watcher -// receives a chat_shell_run_event with Dismissed set. A running command cannot -// be dismissed. For ChatShellRunUndoWindow after a dismissal the run can be -// restored (chat_shell_restore); after that the server purges its command, -// output and error, keeping only a tombstone whose id chat_shell_runs reports -// in ChatShellDismissed so a client that missed the event drops the card. +// a dismissed run leaves the transcript (chat_shell_runs' ChatShellRuns) and +// every watcher receives a chat_shell_run_event with Dismissed set. A running +// command cannot be dismissed. A dismissed run is kept, command, status, times +// and output included, within the same history and output bounds as any other +// run: chat_shell_runs lists it in ChatShellDismissedRuns (flagged Dismissed) +// so clients can show it collapsed, chat_shell_run_output still reads it, and +// chat_shell_restore puts it back at any time. Runs dismissed by an older +// server had their command and output purged; they are listed with Purged set +// and cannot be restored. const ( // ChatShellDismiss dismisses the finished runs named in // ChatShellRunRequest.RunIDs; the reply lists those it dismissed in // ChatShellDismissed (running, unknown and already dismissed runs are // skipped). ChatShellDismiss = "chat_shell_dismiss" - // ChatShellRestore undoes a dismissal still inside its undo window; the - // reply carries the restored runs (with their list output tail) in - // ChatShellRuns, and every watcher receives their lifecycle frames. + // ChatShellRestore undoes a dismissal; the reply carries the restored runs + // (with their list output tail) in ChatShellRuns, and every watcher + // receives their lifecycle frames. There is no time limit; a purged run + // cannot be restored. ChatShellRestore = "chat_shell_restore" - // ChatShellRunUndoWindow is how long, in milliseconds, a dismissed run is - // kept restorable before its output is purged. It is longer than the - // clients' Undo notice so a late Undo still succeeds. - ChatShellRunUndoWindow = 30_000 // ChatShellDismissLimit bounds the run ids of one request. ChatShellDismissLimit = 200 ) diff --git a/internal/protocol/chat_shell_run.go b/internal/protocol/chat_shell_run.go index be1d9d35..90ae515d 100644 --- a/internal/protocol/chat_shell_run.go +++ b/internal/protocol/chat_shell_run.go @@ -114,6 +114,12 @@ type ChatShellRunRecord struct { // carriage-return redraws applied): what Copy output copies and Send to // agent shares. Only chat_shell_run_output carries it. Text string `json:"text,omitempty"` + // Dismissed is set on a run the operator dismissed (chat_shell_dismiss.go) + // and DismissedAt is when, in epoch milliseconds. Purged is set when an + // older server deleted its command and output: only the tombstone is left. + Dismissed bool `json:"dismissed,omitempty"` + DismissedAt int64 `json:"dismissed_at,omitempty"` + Purged bool `json:"purged,omitempty"` } // ChatShellRunEventFrame is one live change to a run. A lifecycle frame sets diff --git a/internal/protocol/message.go b/internal/protocol/message.go index 2394c6c2..a7f28b65 100644 --- a/internal/protocol/message.go +++ b/internal/protocol/message.go @@ -281,8 +281,11 @@ type Message struct { ChatShellRuns []ChatShellRunRecord `json:"chat_shell_runs,omitempty"` ChatShellRunEvent *ChatShellRunEventFrame `json:"chat_shell_run_event,omitempty"` // ChatShellDismissed lists dismissed run ids (chat_shell_dismiss's reply - // and chat_shell_runs' tombstones; chat_shell_dismiss.go). - ChatShellDismissed []string `json:"chat_shell_dismissed,omitempty"` + // and chat_shell_runs' dismissed ids; chat_shell_dismiss.go), and + // ChatShellDismissedRuns carries chat_shell_runs' dismissed runs, oldest + // first, with their list output tail. + ChatShellDismissed []string `json:"chat_shell_dismissed,omitempty"` + ChatShellDismissedRuns []ChatShellRunRecord `json:"chat_shell_dismissed_runs,omitempty"` // Machine terminals (terminal.go): the request body, one terminal, the // machine's terminals and the pushed change. TerminalRequest *TerminalRequest `json:"terminal_request,omitempty"` diff --git a/internal/server/chat_shell_dismiss.go b/internal/server/chat_shell_dismiss.go index b98aea94..052fe4e8 100644 --- a/internal/server/chat_shell_dismiss.go +++ b/internal/server/chat_shell_dismiss.go @@ -4,7 +4,6 @@ import ( "context" "errors" "fmt" - "time" "git.a-wan.net/alan/pipelines/internal/protocol" ) @@ -12,9 +11,8 @@ import ( // chatShellDismissStore persists dismissals; *pipeline.Store implements it. type chatShellDismissStore interface { DismissChatShellRuns(ctx context.Context, sessionID string, ids []string, at int64) ([]string, error) - RestoreChatShellRuns(ctx context.Context, sessionID string, ids []string, since int64) ([]protocol.ChatShellRunRecord, error) - PurgeDismissedChatShellRuns(ctx context.Context, before int64) (int64, error) - DismissedChatShellRuns(ctx context.Context, sessionID string) ([]string, error) + RestoreChatShellRuns(ctx context.Context, sessionID string, ids []string) ([]protocol.ChatShellRunRecord, error) + DismissedChatShellRuns(ctx context.Context, sessionID string) ([]protocol.ChatShellRunRecord, error) } func validChatShellRunIDs(ids []string) error { @@ -27,9 +25,9 @@ func validChatShellRunIDs(ids []string) error { return nil } -// Dismiss removes the session's finished runs among ids for every watcher and -// returns the ids it dismissed. Their output is purged once the undo window -// has passed. +// Dismiss takes the session's finished runs among ids out of the transcript +// for every watcher and returns the ids it dismissed. Their record and output +// are kept: the readback lists them as dismissed and Restore brings them back. func (r *chatShellRunner) Dismiss(ctx context.Context, sessionID string, ids []string) ([]string, error) { if err := validChatShellRunIDs(ids); err != nil { return nil, err @@ -52,20 +50,17 @@ func (r *chatShellRunner) Dismiss(ctx context.Context, sessionID string, ids []s for _, id := range dismissed { r.publishFrame(protocol.ChatShellRunEventFrame{SessionID: sessionID, RunID: id, Dismissed: true}) } - if len(dismissed) > 0 { - r.schedulePurge() - } return dismissed, nil } -// Restore undoes the dismissal of the session's runs among ids that are still -// inside the undo window and returns them with their list output tail. +// Restore undoes the dismissal of the session's runs among ids, however long +// ago they were dismissed, and returns them with their list output tail. A +// purged run (an older server's tombstone) cannot be restored. func (r *chatShellRunner) Restore(ctx context.Context, sessionID string, ids []string) ([]protocol.ChatShellRunRecord, error) { if err := validChatShellRunIDs(ids); err != nil { return nil, err } - since := r.now().Add(-r.undo).UnixMilli() - runs, err := r.store.RestoreChatShellRuns(ctx, sessionID, ids, since) + runs, err := r.store.RestoreChatShellRuns(ctx, sessionID, ids) if err != nil { return nil, err } @@ -80,24 +75,20 @@ func (r *chatShellRunner) Restore(ctx context.Context, sessionID string, ids []s return runs, nil } -// Dismissed is the session's dismissed run ids (their tombstones). -func (r *chatShellRunner) Dismissed(ctx context.Context, sessionID string) ([]string, error) { - return r.store.DismissedChatShellRuns(ctx, sessionID) -} - -// purgeDismissed deletes the output of runs whose undo window has passed. -func (r *chatShellRunner) purgeDismissed(ctx context.Context) { - _, _ = r.store.PurgeDismissedChatShellRuns(ctx, r.now().Add(-r.undo).UnixMilli()) -} - -// schedulePurge purges once the window of a dismissal made now has passed. -// A server stopping before then purges on its next start (recover). -func (r *chatShellRunner) schedulePurge() { - time.AfterFunc(r.undo+time.Second, func() { - if r.base.Err() == nil { - r.purgeDismissed(r.base) - } - }) +// Dismissed is the session's dismissed runs, oldest first, each with at most +// protocol.ChatShellRunListOutput bytes of its output tail, and their ids. +func (r *chatShellRunner) Dismissed(ctx context.Context, sessionID string) ([]protocol.ChatShellRunRecord, []string, error) { + runs, err := r.store.DismissedChatShellRuns(ctx, sessionID) + if err != nil { + return nil, nil, err + } + ids := make([]string, len(runs)) + for i, run := range runs { + runs[i] = chatShellRecordTail(run, protocol.ChatShellRunListOutput) + runs[i].Text = "" + ids[i] = run.ID + } + return runs, ids, nil } func (r *chatShellRunner) publishFrame(frame protocol.ChatShellRunEventFrame) { diff --git a/internal/server/chat_shell_dismiss_test.go b/internal/server/chat_shell_dismiss_test.go index 28acfd4d..6a3d1b16 100644 --- a/internal/server/chat_shell_dismiss_test.go +++ b/internal/server/chat_shell_dismiss_test.go @@ -13,9 +13,9 @@ func dismissRequest(kind, id string, runIDs ...string) protocol.Message { return protocol.Message{Type: kind, ID: id, ChatShellRunRequest: &protocol.ChatShellRunRequest{SessionID: "ses_1", RunIDs: runIDs}} } -func TestChatShellDismissRemovesForEveryWatcherAndRestores(t *testing.T) { +func TestChatShellDismissKeepsTheRunForEveryWatcherAndRestores(t *testing.T) { ctx, conns, _ := shellChat(t) - done := runShell(t, ctx, conns[0], "r1", "echo kept-output") + done := runShell(t, ctx, conns[0], "r1", "echo kept-output; exit 2") for _, conn := range conns { finishedShell(t, ctx, conn, done.ID) } @@ -44,21 +44,32 @@ func TestChatShellDismissRemovesForEveryWatcherAndRestores(t *testing.T) { } } - // The readback leaves it out and reports its tombstone; its output is gone. + // The readback lists it apart, flagged, with its command, status and output. writeChat(t, ctx, conns[1], protocol.Message{Type: protocol.ChatShellRuns, ID: "list", ChatQuery: &protocol.ChatQuery{SessionID: "ses_1"}}) list := readShellFrame(t, ctx, conns[1], func(m protocol.Message) bool { return m.ID == "list" }) if len(list.ChatShellRuns) != 1 || list.ChatShellRuns[0].ID != live.ID || fmt.Sprint(list.ChatShellDismissed) != fmt.Sprint([]string{done.ID}) { t.Fatalf("readback = %+v", list) } + if len(list.ChatShellDismissedRuns) != 1 { + t.Fatalf("dismissed runs = %+v", list.ChatShellDismissedRuns) + } + if run := list.ChatShellDismissedRuns[0]; run.ID != done.ID || !run.Dismissed || run.DismissedAt == 0 || run.Purged || + run.Command != "echo kept-output; exit 2" || run.ExitCode == nil || *run.ExitCode != 2 || + run.Output != "kept-output\r\n" || run.Text != "" { + t.Fatalf("dismissed run = %+v", run) + } + // Its whole output stays readable (the history's output view, Copy output). writeChat(t, ctx, conns[1], shellRequest(protocol.ChatShellRunOutput, "out", done.ID, "")) - if got := readShellFrame(t, ctx, conns[1], func(m protocol.Message) bool { return m.ID == "out" }); got.Type != protocol.Error { + if got := readShellFrame(t, ctx, conns[1], func(m protocol.Message) bool { return m.ID == "out" }); got.Type != protocol.ChatShellRunOutput || + got.ChatShellRun == nil || !got.ChatShellRun.Dismissed || got.ChatShellRun.Text != "kept-output\n" { t.Fatalf("output of a dismissed run = %+v", got) } - // Undo brings the run back, output included, for every watcher. + // Restore brings the run back, output included, for every watcher. writeChat(t, ctx, conns[1], dismissRequest(protocol.ChatShellRestore, "undo", done.ID)) restored := readShellFrame(t, ctx, conns[1], func(m protocol.Message) bool { return m.ID == "undo" }) - if restored.Type != protocol.ChatShellRestore || len(restored.ChatShellRuns) != 1 || restored.ChatShellRuns[0].Output != "kept-output\r\n" { + if restored.Type != protocol.ChatShellRestore || len(restored.ChatShellRuns) != 1 || restored.ChatShellRuns[0].Output != "kept-output\r\n" || + restored.ChatShellRuns[0].Dismissed { t.Fatalf("restore reply = %+v", restored) } for i, conn := range conns { @@ -77,13 +88,13 @@ func TestChatShellDismissRemovesForEveryWatcherAndRestores(t *testing.T) { finishedShell(t, ctx, conns[0], live.ID) } -func TestChatShellDismissPurgesAfterTheUndoWindow(t *testing.T) { +func TestChatShellDismissedRunIsKeptAcrossRestartsAndRestoresLater(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) defer cancel() runner, frames := testShellRunner(t, ctx) now := time.UnixMilli(1_000_000) runner.now = func() time.Time { return now } - run, err := runner.Start(ctx, "ses_1", t.TempDir(), "echo gone", 0, 0) + run, err := runner.Start(ctx, "ses_1", t.TempDir(), "echo kept", 0, 0) if err != nil { t.Fatal(err) } @@ -94,21 +105,21 @@ func TestChatShellDismissPurgesAfterTheUndoWindow(t *testing.T) { if _, err := runner.Dismiss(ctx, "ses_1", []string{run.ID}); err != nil { t.Fatal(err) } - now = now.Add(runner.undo - time.Millisecond) - runner.purgeDismissed(ctx) - if restored, err := runner.Restore(ctx, "ses_1", []string{run.ID}); err != nil || len(restored) != 1 || restored[0].Output == "" { - t.Fatalf("restore inside the window = %+v, %v", restored, err) - } - if _, err := runner.Dismiss(ctx, "ses_1", []string{run.ID}); err != nil { - t.Fatal(err) - } - now = now.Add(runner.undo + time.Millisecond) - // A restart purges what expired while no server ran. + // A day later, after a restart, the run is still whole and restorable. + now = now.Add(24 * time.Hour) runner.recover(ctx) - if _, err := runner.Restore(ctx, "ses_1", []string{run.ID}); err == nil { - t.Fatal("a run was restored after the undo window") + held, ids, err := runner.Dismissed(ctx, "ses_1") + if err != nil || len(held) != 1 || fmt.Sprint(ids) != fmt.Sprint([]string{run.ID}) || held[0].Command != "echo kept" || + held[0].Output == "" || held[0].Purged { + t.Fatalf("dismissed = %+v, %v, %v", held, ids, err) } - if tombs, err := runner.Dismissed(ctx, "ses_1"); err != nil || fmt.Sprint(tombs) != fmt.Sprint([]string{run.ID}) { - t.Fatalf("tombstones = %v, %v", tombs, err) + if read, err := runner.Read(ctx, "ses_1", run.ID); err != nil || read.Text != "kept\n" || !read.Dismissed { + t.Fatalf("read = %+v, %v", read, err) + } + if restored, err := runner.Restore(ctx, "ses_1", []string{run.ID}); err != nil || len(restored) != 1 || restored[0].Output == "" { + t.Fatalf("restore a day later = %+v, %v", restored, err) + } + if held, _, _ := runner.Dismissed(ctx, "ses_1"); len(held) != 0 { + t.Fatalf("still dismissed: %+v", held) } } diff --git a/internal/server/chat_shell_run_handlers.go b/internal/server/chat_shell_run_handlers.go index b6098cbd..6abab624 100644 --- a/internal/server/chat_shell_run_handlers.go +++ b/internal/server/chat_shell_run_handlers.go @@ -70,12 +70,13 @@ func handleChatShellRunRequest(ctx context.Context, request protocol.Message, br fail(err) return } - dismissed, err := runner.Dismissed(ctx, sessionID) + dismissedRuns, dismissed, err := runner.Dismissed(ctx, sessionID) if err != nil { fail(err) return } - _ = write(protocol.Message{Type: protocol.ChatShellRuns, ID: request.ID, ChatShellRuns: runs, ChatShellDismissed: dismissed}) + _ = write(protocol.Message{Type: protocol.ChatShellRuns, ID: request.ID, ChatShellRuns: runs, + ChatShellDismissed: dismissed, ChatShellDismissedRuns: dismissedRuns}) case protocol.ChatShellDismiss: dismissed, err := runner.Dismiss(ctx, sessionID, body.RunIDs) if err != nil { diff --git a/internal/server/chat_shell_runner.go b/internal/server/chat_shell_runner.go index 17a15e5f..1de83da0 100644 --- a/internal/server/chat_shell_runner.go +++ b/internal/server/chat_shell_runner.go @@ -49,8 +49,6 @@ type chatShellRunner struct { grace time.Duration flush time.Duration persist time.Duration - // undo is how long a dismissed run stays restorable before its purge. - undo time.Duration mu sync.Mutex active map[string]*chatShellProcess @@ -77,7 +75,6 @@ func newChatShellRunner(base context.Context, store chatShellRunStore, publish f return &chatShellRunner{ base: base, store: store, publish: publish, now: time.Now, shell: chatShellProgram, grace: 3 * time.Second, flush: 100 * time.Millisecond, persist: 2 * time.Second, - undo: protocol.ChatShellRunUndoWindow * time.Millisecond, active: map[string]*chatShellProcess{}, } } @@ -93,14 +90,12 @@ func chatShellProgram() string { } // recover marks runs a previous server process left running as interrupted: -// their processes died with it (or are no longer owned by anyone). It also -// purges dismissals whose undo window passed while no server was running. +// their processes died with it (or are no longer owned by anyone). func (r *chatShellRunner) recover(ctx context.Context) { if r.store == nil { return } _, _ = r.store.InterruptChatShellRuns(ctx, r.now().UnixMilli(), chatShellInterruptedReason) - r.purgeDismissed(ctx) } // resolveChatShellDirectory requires the chat's recorded directory to still be From cf9f71f27c0db1ddec897a09f7d43f6329a2cb12 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Mon, 9 Nov 2026 23:47:14 +0000 Subject: [PATCH 2/2] Show dismissed commands as an answer footer chip; move Copy to the left gutter Dismissed shell runs leave the transcript and fold into a "N commands" chip in the footer of the first answer at or after each run (the last answer for newer runs, or a row of its own without any answer). The chip opens the turn sheet (wide) or a full-screen page (narrow) listing the commands; each opens its output read-only with Copy output, Send to agent and Restore. On a wide conversation the answer's Copy button moves out of the footer into a 48 px gutter left of the reading column (chatCopyGutter), shown on hover or focus on desktops and always on touch; narrow widths keep it in the footer. --- .../chat/conversation/chat_reading_width.dart | 11 + .../chat/conversation/chat_thread_view.dart | 86 ++++-- .../chat/shell/chat_shell_dismiss.dart | 1 - .../chat/shell/chat_shell_history.dart | 65 ++++ .../chat/shell/chat_shell_history_chip.dart | 82 ++++++ .../shell/chat_shell_history_output_page.dart | 277 ++++++++++++++++++ .../chat/shell/chat_shell_history_view.dart | 186 ++++++++++++ .../features/chat/shell/chat_shell_run.dart | 13 + .../chat/shell/chat_shell_run_card.dart | 3 +- .../shell/chat_shell_runs_controller.dart | 15 +- .../chat/shell/chat_shell_runs_dismissal.dart | 41 ++- .../shell/chat_shell_runs_repository.dart | 33 ++- .../chat/ui/transcript/chat_copy_gutter.dart | 110 +++++++ .../chat/ui/transcript/chat_message_view.dart | 40 ++- app/notes/chat-copy-gutter.md | 31 ++ app/notes/chat-shell-commands.md | 95 ++++-- .../chat/shell/chat_shell_fixtures.dart | 27 +- .../chat/shell/chat_shell_history_test.dart | 71 +++++ .../shell/chat_shell_history_view_test.dart | 256 ++++++++++++++++ .../ui/transcript/chat_copy_gutter_test.dart | 150 ++++++++++ app/tool/perf/chat_shell_fixture.dart | 18 +- 21 files changed, 1534 insertions(+), 77 deletions(-) create mode 100644 app/lib/features/chat/shell/chat_shell_history.dart create mode 100644 app/lib/features/chat/shell/chat_shell_history_chip.dart create mode 100644 app/lib/features/chat/shell/chat_shell_history_output_page.dart create mode 100644 app/lib/features/chat/shell/chat_shell_history_view.dart create mode 100644 app/lib/features/chat/ui/transcript/chat_copy_gutter.dart create mode 100644 app/notes/chat-copy-gutter.md create mode 100644 app/test/features/chat/shell/chat_shell_history_test.dart create mode 100644 app/test/features/chat/shell/chat_shell_history_view_test.dart create mode 100644 app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart diff --git a/app/lib/features/chat/conversation/chat_reading_width.dart b/app/lib/features/chat/conversation/chat_reading_width.dart index c4f8325a..de38d045 100644 --- a/app/lib/features/chat/conversation/chat_reading_width.dart +++ b/app/lib/features/chat/conversation/chat_reading_width.dart @@ -8,3 +8,14 @@ const double kChatReadingWidth = 760; /// The space on each side of the centred reading column in [width]. double chatReadingInset(double width) => math.max(0, (width - kChatReadingWidth) / 2); + +/// The strip left of the reading column that holds an answer's Copy button, +/// outside the answer itself. +const double kChatCopyGutterWidth = 48; + +/// The copy gutter a transcript [width] wide gives each answer: +/// [kChatCopyGutterWidth] when the margin left of the centred reading column +/// fits it, else 0, and Copy stays in the answer's footer (phones, narrow +/// panes). +double chatCopyGutter(double width) => + chatReadingInset(width) >= kChatCopyGutterWidth ? kChatCopyGutterWidth : 0; diff --git a/app/lib/features/chat/conversation/chat_thread_view.dart b/app/lib/features/chat/conversation/chat_thread_view.dart index 070a8c89..bd0e8b10 100644 --- a/app/lib/features/chat/conversation/chat_thread_view.dart +++ b/app/lib/features/chat/conversation/chat_thread_view.dart @@ -59,6 +59,7 @@ import '../../../ui/adaptive/segmented_bar_overlay.dart'; import '../../../ui/layout/app_sheet_header.dart'; import '../../../ui/layout/wheel_scroll_forwarding.dart'; import 'chat_reading_width.dart'; +import '../ui/transcript/chat_copy_gutter.dart'; import 'chat_pane_presentation.dart'; import 'chat_thread_header.dart'; import 'chat_transcript_anchor.dart'; @@ -67,6 +68,8 @@ import '../files/files_controller.dart'; import '../files/files_panel.dart'; import '../files/files_preferences.dart'; import '../shell/chat_shell_command.dart'; +import '../shell/chat_shell_history.dart'; +import '../shell/chat_shell_history_chip.dart'; import '../shell/chat_shell_dismiss.dart'; import '../shell/chat_shell_run.dart'; import '../shell/chat_shell_run_card.dart'; @@ -1053,11 +1056,15 @@ class _ChatThreadViewState extends State { ); final notices = _dismissals.visible(allNotices); final compactionNotice = _noticeOf(notices, ChatNoticeKind.compaction); - // The operator's own shell commands sit among the turns by start time. - final rows = withChatShellRunRows([ - for (final row in allRows) - if (!_hiddenRunningCompaction(row)) row, - ], _shellRuns.runs); + // The operator's own shell commands sit among the turns by start time; + // dismissed ones fold into a chip under the answer that followed them. + final rows = attachChatShellHistory( + withChatShellRunRows([ + for (final row in allRows) + if (!_hiddenRunningCompaction(row)) row, + ], _shellRuns.runs), + _shellRuns.dismissedRuns, + ); // Older pages prepend messages and a live frame can append one, so a // folded assistant turn's first message id is not a stable identity. // ChatRowKeys carries a turn's key forward while it still holds any of @@ -1129,29 +1136,42 @@ class _ChatThreadViewState extends State { // Rows keep to the centred reading column on a wide // window; the margins beside it still scroll the list. final side = chatReadingInset(constraints.maxWidth); + // Answers draw Copy in a strip left of the column; every + // other row keeps to the column by insetting past it. + final gutter = chatCopyGutter(constraints.maxWidth); final media = MediaQuery.paddingOf(context); final transcript = [ for (var index = 0; index < rows.length; index++) Padding( key: ValueKey(keys[index]), - padding: const EdgeInsets.symmetric(horizontal: 16), + padding: EdgeInsets.only( + left: + 16 + + (rows[index]['kind'] == 'assistant' ? 0 : gutter), + right: 16, + ), // Slivers mount only visible rows. Defer constructing // their chips and checking cached widgets until then, // rather than visiting the entire history per delta. - child: Builder( - builder: (_) => _entering( - rows[index], - _transcriptRow( + 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, + ), ), ), ), @@ -1177,12 +1197,12 @@ class _ChatThreadViewState extends State { ? null : ValueKey(keys[split]), padding: EdgeInsets.fromLTRB( - side, + side - gutter, media.top + 8, side, 8, ), - children: [ + children: chatCopyGutterInset(gutter, transcript, [ if (initialLoad) Padding( key: const Key('chat-thread-loading'), @@ -1278,7 +1298,7 @@ class _ChatThreadViewState extends State { notice: notice, onDismiss: _dismiss, ), - ], + ]), ), ), if (showJump) @@ -1538,6 +1558,16 @@ class _ChatThreadViewState extends State { runId: '${row['run_id']}', ); } + if (kind == chatShellHistoryRowKind) { + // A chat with no answer yet keeps its dismissed commands on their own. + return Align( + alignment: AlignmentDirectional.centerStart, + child: ChatShellHistoryChip( + controller: _shellRuns, + runIds: chatShellHistoryIds(row), + ), + ); + } if (kind == chatShownRowKind) { return ChatShownCard( row: row, @@ -1563,6 +1593,8 @@ class _ChatThreadViewState extends State { summary: Map.from(diff), load: () => _controller.turnDiff('${diff['turn_id']}'), ), + if (chatShellHistoryIds(row) case final ids when ids.isNotEmpty) + ChatShellHistoryChip(controller: _shellRuns, runIds: ids), ]; if (kind == 'permissions') { return Align( @@ -1587,7 +1619,15 @@ class _ChatThreadViewState extends State { return _rowWidgets.widgetFor( key, row, - [delivery, cupertino, onRemove != null, _images, _controller, _composer], + [ + delivery, + cupertino, + onRemove != null, + _images, + _controller, + _composer, + _shellRuns, + ], () => ChatMessageView( row: row, textBuilder: chatMarkdownText, diff --git a/app/lib/features/chat/shell/chat_shell_dismiss.dart b/app/lib/features/chat/shell/chat_shell_dismiss.dart index d1f013cf..eeaba15e 100644 --- a/app/lib/features/chat/shell/chat_shell_dismiss.dart +++ b/app/lib/features/chat/shell/chat_shell_dismiss.dart @@ -9,7 +9,6 @@ import 'chat_shell_runs_controller.dart'; const String chatShellDismissLabel = 'Dismiss'; const String chatShellDismissAllLabel = 'Dismiss all finished commands'; - /// The card's Dismiss button, offered once the command has finished. class ChatShellDismissButton extends StatelessWidget { const ChatShellDismissButton({ diff --git a/app/lib/features/chat/shell/chat_shell_history.dart b/app/lib/features/chat/shell/chat_shell_history.dart new file mode 100644 index 00000000..3020c4ee --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_history.dart @@ -0,0 +1,65 @@ +import '../../../core/api_gateway.dart'; +import 'chat_shell_run.dart'; + +/// The row field that carries an answer's dismissed command ids, oldest +/// first: what its footer's "N commands" chip lists. +const String chatShellHistoryField = 'shellHistory'; + +/// The transcript row kind of the history chip a chat with no answer shows. +const String chatShellHistoryRowKind = 'shell_history'; + +/// Attaches each dismissed run to an answer's footer as [chatShellHistoryField]: +/// the first assistant reply created at or after the run started, or the last +/// reply for a run newer than every reply. A reply without a recorded time is +/// only chosen as that last reply. With no assistant reply at all, one +/// [chatShellHistoryRowKind] row at the end holds every run. +List attachChatShellHistory( + List rows, + List dismissed, +) { + if (dismissed.isEmpty) return rows; + final replies = [ + for (var i = 0; i < rows.length; i++) + if (rows[i]['kind'] == 'assistant') i, + ]; + final ordered = [...dismissed] + ..sort((a, b) => a.startedAt.compareTo(b.startedAt)); + if (replies.isEmpty) { + return [ + ...rows, + { + 'kind': chatShellHistoryRowKind, + 'key': 'chat-shell-history', + chatShellHistoryField: [for (final run in ordered) run.id], + }, + ]; + } + final assigned = >{}; + for (final run in ordered) { + final index = replies.firstWhere((i) { + final created = rows[i]['created_at']; + return created is num && created >= run.startedAt; + }, orElse: () => replies.last); + (assigned[index] ??= []).add(run.id); + } + return [ + for (var i = 0; i < rows.length; i++) + if (assigned[i] case final ids?) + {...rows[i], chatShellHistoryField: ids} + else + rows[i], + ]; +} + +/// The dismissed command ids [row] carries, oldest first. +List chatShellHistoryIds(JsonMap row) => [ + for (final id in row[chatShellHistoryField] as List? ?? const []) '$id', +]; + +/// The chip's label, e.g. `2 commands`. +String chatShellHistoryLabel(int count) => + count == 1 ? '1 command' : '$count commands'; + +/// The chip's accessible name. +String chatShellHistorySemantics(int count) => + '${chatShellHistoryLabel(count)} dismissed, open command history'; diff --git a/app/lib/features/chat/shell/chat_shell_history_chip.dart b/app/lib/features/chat/shell/chat_shell_history_chip.dart new file mode 100644 index 00000000..3587941e --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_history_chip.dart @@ -0,0 +1,82 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../shell/list_detail_policy.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import '../ui/transcript/chat_turn_chip.dart'; +import 'chat_shell_history.dart'; +import 'chat_shell_history_view.dart'; +import 'chat_shell_runs_controller.dart'; + +/// The dismissed commands attached to an answer, as a chip in its footer +/// beside the change and tool chips: `2 commands`. A wide window opens the +/// list in the turn sheet; a narrow one opens it as a full-screen page. +class ChatShellHistoryChip extends StatelessWidget { + const ChatShellHistoryChip({ + super.key, + required this.controller, + required this.runIds, + }); + + final ChatShellRunsController controller; + + /// The dismissed runs this chip lists, oldest first. + final List runIds; + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final color = cupertino + ? CupertinoColors.secondaryLabel.resolveFrom(context) + : Theme.of(context).colorScheme.onSurfaceVariant; + return ChatTurnChip( + chipKey: const Key('chat-shell-history-chip'), + leading: Icon( + cupertino + ? CupertinoIcons.chevron_left_slash_chevron_right + : Icons.terminal, + size: 14, + color: color, + ), + label: chatShellHistoryLabel(runIds.length), + color: color, + semanticsLabel: chatShellHistorySemantics(runIds.length), + ellipsizeLabel: true, + open: _open, + ); + } + + Future _open(BuildContext context, bool cupertino) { + if (MediaQuery.sizeOf(context).width >= kListDetailMinWidth) { + return showChatTurnSheet( + context, + cupertino, + ChatShellHistoryView(controller: controller, runIds: runIds), + ); + } + final view = ChatShellHistoryView( + controller: controller, + runIds: runIds, + inSheet: false, + ); + const title = Text(chatShellHistoryTitle); + return Navigator.of(context).push( + cupertino + ? CupertinoPageRoute( + fullscreenDialog: true, + builder: (_) => CupertinoPageScaffold( + navigationBar: const CupertinoNavigationBar(middle: title), + child: SafeArea(child: view), + ), + ) + : MaterialPageRoute( + fullscreenDialog: true, + builder: (_) => Scaffold( + appBar: AppBar(title: title), + body: SafeArea(child: view), + ), + ), + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_history_output_page.dart b/app/lib/features/chat/shell/chat_shell_history_output_page.dart new file mode 100644 index 00000000..47332555 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_history_output_page.dart @@ -0,0 +1,277 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; + +import '../../../ui/text/monospace.dart'; +import '../conversation/chat_card_styles.dart'; +import 'chat_shell_card_actions.dart'; +import 'chat_shell_run.dart'; +import 'chat_shell_runs_controller.dart'; +import 'chat_shell_status.dart'; +import 'chat_shell_terminal_session.dart'; +import 'chat_shell_terminal_view.dart'; + +/// Opens a dismissed command's output read-only, full screen. +Future openChatShellHistoryOutput( + BuildContext context, { + required ChatShellRunsController controller, + required String runId, + required bool cupertino, +}) { + Widget page(BuildContext _) => ChatShellHistoryOutputPage( + controller: controller, + runId: runId, + cupertino: cupertino, + ); + return Navigator.of(context).push( + cupertino + ? CupertinoPageRoute(builder: page) + : MaterialPageRoute(builder: page), + ); +} + +/// One dismissed command: everything the server kept of its output in the +/// card's terminal view (read-only), with Copy output, Send to agent and +/// Restore, which puts its card back in the transcript and closes the page. +class ChatShellHistoryOutputPage extends StatefulWidget { + const ChatShellHistoryOutputPage({ + super.key, + required this.controller, + required this.runId, + required this.cupertino, + }); + + final ChatShellRunsController controller; + final String runId; + final bool cupertino; + + @override + State createState() => + _ChatShellHistoryOutputPageState(); +} + +class _ChatShellHistoryOutputPageState + extends State { + late final Future _full = widget.controller.fullOutput( + widget.runId, + ); + ChatShellTerminalSession? _session; + bool _copied = false; + String? _refusal; + Timer? _reset; + + @override + void dispose() { + _reset?.cancel(); + super.dispose(); + } + + Future _copy(ChatShellRun full) async { + final text = full.terminal || full.text.isNotEmpty + ? full.text + : full.output; + await Clipboard.setData(ClipboardData(text: text)); + if (!mounted) return; + setState(() => _copied = true); + _reset?.cancel(); + _reset = Timer(const Duration(seconds: 2), () { + if (mounted) setState(() => _copied = false); + }); + } + + Future _restore() async { + final refusal = await widget.controller.restore([widget.runId]); + if (!mounted) return; + if (refusal == null) { + Navigator.of(context).maybePop(); + } else { + setState(() => _refusal = refusal); + } + } + + @override + Widget build(BuildContext context) { + final cupertino = widget.cupertino; + final held = widget.controller.dismissedRun(widget.runId); + final title = Text( + held == null ? 'Command' : '\$ ${held.command}', + maxLines: 1, + overflow: TextOverflow.ellipsis, + style: const TextStyle(fontFamily: appMonospaceFamily), + ); + final body = SafeArea( + child: Padding( + padding: const EdgeInsets.all(8), + child: FutureBuilder( + future: _full, + builder: (context, snapshot) { + if (snapshot.hasError) { + return Text( + "Couldn't read the output: ${snapshot.error}", + style: chatCardSecondaryStyle(context, cupertino), + ); + } + final full = snapshot.data; + if (full == null) { + return Center( + child: cupertino + ? const CupertinoActivityIndicator() + : const CircularProgressIndicator(), + ); + } + return _content(context, full); + }, + ), + ), + ); + if (cupertino) { + return CupertinoPageScaffold( + navigationBar: CupertinoNavigationBar(middle: title), + child: body, + ); + } + return Scaffold( + appBar: AppBar(title: title), + body: body, + ); + } + + Widget _content(BuildContext context, ChatShellRun full) { + final cupertino = widget.cupertino; + final session = _session ??= ChatShellTerminalSession( + full, + onInput: (_) {}, + onResize: (_, _) {}, + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Padding( + padding: const EdgeInsets.only(bottom: 8), + child: Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + ChatShellStatus(run: full, cupertino: cupertino), + if (full.directory.isNotEmpty) + Text( + full.directory, + style: chatCardSecondaryStyle(context, cupertino), + ), + ], + ), + ), + Expanded( + child: full.output.isEmpty + ? Text( + 'No output.', + key: const Key('chat-shell-output-empty'), + style: chatCardSecondaryStyle(context, cupertino), + ) + : ChatShellTerminalView( + session: session, + cupertino: cupertino, + fill: true, + ), + ), + const SizedBox(height: 8), + ListenableBuilder( + listenable: widget.controller, + builder: (context, _) => _actions(context, full), + ), + ], + ); + } + + Widget _actions(BuildContext context, ChatShellRun full) { + final controller = widget.controller; + final share = controller.shareState(widget.runId); + final error = _refusal ?? controller.errorFor(widget.runId); + return Column( + crossAxisAlignment: CrossAxisAlignment.start, + mainAxisSize: MainAxisSize.min, + children: [ + Wrap( + spacing: 8, + runSpacing: 4, + children: [ + if (full.outputBytes > 0) + _button( + key: const Key('chat-shell-history-copy'), + label: _copied ? chatShellCopiedLabel : chatShellCopyLabel, + material: _copied ? Icons.check : Icons.copy_outlined, + cupertino: _copied + ? CupertinoIcons.checkmark + : CupertinoIcons.doc_on_doc, + onPressed: () => unawaited(_copy(full)), + ), + _button( + key: const Key('chat-shell-history-share'), + label: switch (share) { + ChatShellShareState.idle => chatShellShareLabel, + ChatShellShareState.sending => chatShellSharingLabel, + ChatShellShareState.sent => chatShellSharedLabel, + }, + material: share == ChatShellShareState.sent + ? Icons.check + : Icons.send_outlined, + cupertino: share == ChatShellShareState.sent + ? CupertinoIcons.checkmark + : CupertinoIcons.paperplane, + onPressed: share == ChatShellShareState.idle + ? () => unawaited(controller.share(widget.runId)) + : null, + ), + _button( + key: const Key('chat-shell-history-page-restore'), + label: 'Restore', + material: Icons.restore, + cupertino: CupertinoIcons.arrow_counterclockwise, + onPressed: () => unawaited(_restore()), + ), + ], + ), + if (error != null) + Semantics( + liveRegion: true, + child: Text( + error, + style: chatCardSecondaryStyle( + context, + widget.cupertino, + )?.copyWith(color: chatCardErrorColor(context, widget.cupertino)), + ), + ), + ], + ); + } + + Widget _button({ + required Key key, + required String label, + required IconData material, + required IconData cupertino, + required VoidCallback? onPressed, + }) { + if (widget.cupertino) { + return CupertinoButton( + key: key, + padding: const EdgeInsets.symmetric(horizontal: 8), + onPressed: onPressed, + child: Row( + mainAxisSize: MainAxisSize.min, + children: [Icon(cupertino), const SizedBox(width: 6), Text(label)], + ), + ); + } + return TextButton.icon( + key: key, + onPressed: onPressed, + icon: Icon(material), + label: Text(label), + ); + } +} diff --git a/app/lib/features/chat/shell/chat_shell_history_view.dart b/app/lib/features/chat/shell/chat_shell_history_view.dart new file mode 100644 index 00000000..b5babf23 --- /dev/null +++ b/app/lib/features/chat/shell/chat_shell_history_view.dart @@ -0,0 +1,186 @@ +import 'dart:async'; + +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../../ui/text/monospace.dart'; +import '../conversation/chat_card_styles.dart'; +import '../ui/sessions/chat_adaptive.dart'; +import 'chat_shell_history_output_page.dart'; +import 'chat_shell_run.dart'; +import 'chat_shell_runs_controller.dart'; +import 'chat_shell_status.dart'; + +const String chatShellHistoryTitle = 'Dismissed commands'; +const String chatShellRestoreLabel = 'Restore'; +const String chatShellCommandNotKept = 'Command not kept'; +const String chatShellOutputNotKept = 'Output not kept'; + +/// The dismissed commands of one answer: each command with its exit status, +/// how long it ran and when. Tapping one opens its output read-only; Restore +/// puts its card back in the transcript. +class ChatShellHistoryView extends StatefulWidget { + const ChatShellHistoryView({ + super.key, + required this.controller, + required this.runIds, + this.inSheet = true, + }); + + final ChatShellRunsController controller; + final List runIds; + + /// In the turn sheet (shrinks to its content) rather than a page. + final bool inSheet; + + @override + State createState() => _ChatShellHistoryViewState(); +} + +class _ChatShellHistoryViewState extends State { + final Map _refusals = {}; + + Future _restore(String id) async { + final refusal = await widget.controller.restore([id]); + if (!mounted) return; + setState(() { + if (refusal == null) { + _refusals.remove(id); + } else { + _refusals[id] = refusal; + } + }); + } + + @override + Widget build(BuildContext context) { + final cupertino = + chatControlsStyleOf(context) == ChatControlsStyle.cupertino; + final list = ListenableBuilder( + listenable: widget.controller.membership, + builder: (context, _) { + final runs = [ + for (final id in widget.runIds) ?widget.controller.dismissedRun(id), + ]; + return ListView( + key: const Key('chat-shell-history-list'), + shrinkWrap: widget.inSheet, + padding: const EdgeInsets.symmetric(vertical: 8), + children: [ + if (widget.inSheet) + Padding( + padding: const EdgeInsets.fromLTRB(16, 0, 16, 4), + child: Text( + chatShellHistoryTitle, + style: const TextStyle(fontWeight: FontWeight.w600), + ), + ), + if (runs.isEmpty) + Padding( + padding: const EdgeInsets.all(16), + child: Text( + 'Every command here was restored to the transcript.', + style: chatCardSecondaryStyle(context, cupertino), + ), + ), + for (final run in runs) _entry(context, run, cupertino), + ], + ); + }, + ); + final style = cupertino + ? CupertinoTheme.of(context).textTheme.textStyle + : Theme.of(context).textTheme.bodyMedium; + // Entries are Material list tiles inside a Cupertino surface too. + final content = Material( + type: MaterialType.transparency, + child: DefaultTextStyle.merge(style: style, child: list), + ); + if (!widget.inSheet) return content; + return ConstrainedBox( + constraints: BoxConstraints( + maxHeight: MediaQuery.sizeOf(context).height * 0.8, + ), + child: content, + ); + } + + Widget _entry(BuildContext context, ChatShellRun run, bool cupertino) { + final secondary = chatCardSecondaryStyle(context, cupertino); + final refusal = _refusals[run.id]; + final command = run.purged || run.command.isEmpty + ? Text(chatShellCommandNotKept, style: secondary) + : Text( + '\$ ${run.command}', + maxLines: 2, + overflow: TextOverflow.ellipsis, + style: const TextStyle( + fontFamily: appMonospaceFamily, + fontWeight: FontWeight.w600, + ), + ); + final details = Wrap( + spacing: 8, + runSpacing: 4, + crossAxisAlignment: WrapCrossAlignment.center, + children: [ + ChatShellStatus(run: run, cupertino: cupertino), + Text(chatShellRunTime(context, run.startedAt), style: secondary), + if (run.purged) Text(chatShellOutputNotKept, style: secondary), + if (refusal != null) + Text( + refusal, + key: const Key('chat-shell-history-refusal'), + style: secondary?.copyWith( + color: chatCardErrorColor(context, cupertino), + ), + ), + ], + ); + final restore = run.purged + ? null + : cupertino + ? CupertinoButton( + key: ValueKey('chat-shell-history-restore-${run.id}'), + padding: const EdgeInsets.symmetric(horizontal: 8), + onPressed: () => unawaited(_restore(run.id)), + child: const Text(chatShellRestoreLabel), + ) + : TextButton( + key: ValueKey('chat-shell-history-restore-${run.id}'), + onPressed: () => unawaited(_restore(run.id)), + child: const Text(chatShellRestoreLabel), + ); + return ListTile( + key: ValueKey('chat-shell-history-${run.id}'), + title: command, + subtitle: Padding(padding: const EdgeInsets.only(top: 4), child: details), + trailing: restore, + enabled: !run.purged, + onTap: run.purged + ? null + : () => unawaited( + openChatShellHistoryOutput( + context, + controller: widget.controller, + runId: run.id, + cupertino: cupertino, + ), + ), + ); + } +} + +/// When a command started, as the operator's local date and time. +String chatShellRunTime(BuildContext context, int startedAt) { + if (startedAt <= 0) return ''; + final instant = DateTime.fromMillisecondsSinceEpoch(startedAt).toLocal(); + final material = Localizations.of( + context, + MaterialLocalizations, + ); + final hour = instant.hour.toString().padLeft(2, '0'); + final minute = instant.minute.toString().padLeft(2, '0'); + if (material == null) return '${instant.day}/${instant.month} $hour:$minute'; + return '${material.formatShortMonthDay(instant)} · $hour:$minute'; +} diff --git a/app/lib/features/chat/shell/chat_shell_run.dart b/app/lib/features/chat/shell/chat_shell_run.dart index d23f5e74..608b0ba1 100644 --- a/app/lib/features/chat/shell/chat_shell_run.dart +++ b/app/lib/features/chat/shell/chat_shell_run.dart @@ -31,6 +31,8 @@ class ChatShellRun { this.cols = 0, this.rows = 0, this.text = '', + this.dismissedAt = 0, + this.purged = false, }); final String id; @@ -68,6 +70,13 @@ class ChatShellRun { /// removed); only a whole-output readback carries it. final String text; + /// When the operator dismissed the run (epoch ms; 0 when not dismissed). + final int dismissedAt; + + /// True when an older server deleted the dismissed run's command and + /// output: only its status and times are left, and it cannot be restored. + final bool purged; + /// Whether earlier output is not shown here. bool get truncated => outputStart > 0 || gap; @@ -111,6 +120,8 @@ class ChatShellRun { cols: _int(value['cols']), rows: _int(value['rows']), text: '${value['text'] ?? ''}', + dismissedAt: _int(value['dismissed_at']), + purged: value['purged'] == true, ); } @@ -137,6 +148,8 @@ class ChatShellRun { cols: next.cols == 0 ? cols : next.cols, rows: next.rows == 0 ? rows : next.rows, text: text, + dismissedAt: next.dismissedAt, + purged: next.purged, ); /// This run with one live output chunk covering bytes [offset, end). A diff --git a/app/lib/features/chat/shell/chat_shell_run_card.dart b/app/lib/features/chat/shell/chat_shell_run_card.dart index 12892563..ff4cfd30 100644 --- a/app/lib/features/chat/shell/chat_shell_run_card.dart +++ b/app/lib/features/chat/shell/chat_shell_run_card.dart @@ -18,7 +18,8 @@ import 'chat_shell_terminal_page.dart'; /// One operator command in the transcript, as a terminal card in the reading /// column: the command and folder, its terminal (typed into while it runs), /// a spinner and Stop while it runs, then its exit status, Copy output and -/// Send to agent, and Dismiss (for every client of the chat, with Undo). A +/// Send to agent, and Dismiss (for every client of the chat; the run moves +/// into the answer's command history chip, which can restore it). A /// running command has no Dismiss: Stop it first. Full screen opens the same /// terminal over the whole window. /// diff --git a/app/lib/features/chat/shell/chat_shell_runs_controller.dart b/app/lib/features/chat/shell/chat_shell_runs_controller.dart index 7e59097f..c3db2992 100644 --- a/app/lib/features/chat/shell/chat_shell_runs_controller.dart +++ b/app/lib/features/chat/shell/chat_shell_runs_controller.dart @@ -51,6 +51,10 @@ class ChatShellRunsController extends ChangeNotifier { /// Runs dismissed here or by another client: a readback racing the /// dismissal does not bring their cards back. final Set _gone = {}; + + /// The dismissed runs this copy holds, shown collapsed in the transcript's + /// command history rather than as cards. + final Map _dismissed = {}; bool _disposed = false; int _generation = 0; @@ -75,11 +79,16 @@ class ChatShellRunsController extends ChangeNotifier { Future refresh() async { final token = ++_generation; try { - final (:runs, :dismissed) = await _repository.runs(sessionId); + final (:runs, :dismissed, :dismissedRuns) = await _repository.runs( + sessionId, + ); if (_disposed || token != _generation) return; dismissed.forEach(_remove); + _holdDismissed(dismissedRuns); for (final run in runs) { if (_gone.contains(run.id)) continue; + // Restored by another client while this copy missed the frame. + _dismissed.remove(run.id); final held = _runs[run.id]; if (held != null && held.running && @@ -204,7 +213,10 @@ class ChatShellRunsController extends ChangeNotifier { if (frame is! Map || frame['session_id'] != sessionId) return; final id = '${frame['run_id'] ?? ''}'; if (frame['dismissed'] == true) { + final known = _runs.containsKey(id) || _dismissed.containsKey(id); _remove(id); + // Another client dismissed a run this copy never held: read it. + if (!known) unawaited(refresh()); _changed(membership: true); return; } @@ -212,6 +224,7 @@ class ChatShellRunsController extends ChangeNotifier { if (record != null) { // A restored run (another client's Undo) comes back without output. if (_gone.remove(record.id) && !record.running) unawaited(refresh()); + _dismissed.remove(record.id); final held = _runs[record.id]; final next = held == null ? record : held.withLifecycle(record); _runs[record.id] = next; diff --git a/app/lib/features/chat/shell/chat_shell_runs_dismissal.dart b/app/lib/features/chat/shell/chat_shell_runs_dismissal.dart index 64de9e53..d1f2d88f 100644 --- a/app/lib/features/chat/shell/chat_shell_runs_dismissal.dart +++ b/app/lib/features/chat/shell/chat_shell_runs_dismissal.dart @@ -1,11 +1,21 @@ part of 'chat_shell_runs_controller.dart'; -/// Dismissing finished command cards for every client of the chat, and the -/// Undo that restores them while the server still keeps them. +/// Dismissing finished command cards for every client of the chat, the +/// dismissed runs the server keeps (the transcript's command history), and +/// Restore, which puts a card back. extension ChatShellRunsDismissal on ChatShellRunsController { + /// The dismissed runs this copy holds, oldest first. + List get dismissedRuns => + [..._dismissed.values] + ..sort((a, b) => a.startedAt.compareTo(b.startedAt)); + + /// One dismissed run, or null once it was restored (or aged out). + ChatShellRun? dismissedRun(String id) => _dismissed[id]; + /// Dismisses finished runs [ids] for every client of the chat: their cards - /// go at once and come back (with the refusal) if the server refuses. - /// Returns the refusal, or null. A running command is never dismissed. + /// go at once into the command history and come back (with the refusal) if + /// the server refuses. Returns the refusal, or null. A running command is + /// never dismissed. Future dismiss(List ids) async { final removed = [ for (final id in ids) @@ -24,6 +34,7 @@ extension ChatShellRunsDismissal on ChatShellRunsController { final reason = _reason(error); for (final run in removed) { _gone.remove(run.id); + _dismissed.remove(run.id); _runs[run.id] = run; _errors[run.id] = reason; } @@ -32,14 +43,15 @@ extension ChatShellRunsDismissal on ChatShellRunsController { } } - /// Undoes the dismissal of [ids] while the server still keeps them. - /// Returns the refusal, or null. + /// Puts dismissed runs [ids] back in the transcript as cards, for every + /// client. Returns the refusal, or null. Future restore(List ids) async { try { final restored = await _repository.restore(sessionId, ids); if (_disposed) return null; for (final run in restored) { _gone.remove(run.id); + _dismissed.remove(run.id); final held = _runs[run.id]; final keep = held != null && held.outputEnd >= run.outputEnd; _runs[run.id] = keep ? held.withLifecycle(run) : run; @@ -52,7 +64,24 @@ extension ChatShellRunsDismissal on ChatShellRunsController { } } + /// The dismissed run [id] with everything the server kept of its output + /// and its plain-text rendering, for the history's read-only output view. + Future fullOutput(String id) => + _repository.output(sessionId, id); + + /// Folds a readback's dismissed runs into the history. Runs this copy + /// dismissed but the readback does not list yet stay held. + void _holdDismissed(List runs) { + for (final run in runs) { + _gone.add(run.id); + _dismissed[run.id] = run; + } + } + + /// Takes [id]'s card out of the transcript; a held copy moves into the + /// command history. void _remove(String id) { + if (_runs[id] case final run?) _dismissed[id] = run; _gone.add(id); _runs.remove(id); _errors.remove(id); diff --git a/app/lib/features/chat/shell/chat_shell_runs_repository.dart b/app/lib/features/chat/shell/chat_shell_runs_repository.dart index 037201bd..5297c9be 100644 --- a/app/lib/features/chat/shell/chat_shell_runs_repository.dart +++ b/app/lib/features/chat/shell/chat_shell_runs_repository.dart @@ -57,15 +57,25 @@ class ChatShellRunsRepository { Future stop(String sessionId, String runId) => gateway.call('chat_shell_stop', _body(sessionId, runId: runId)); - /// The session's recorded runs, oldest first, each with its output tail, - /// and the ids of its dismissed runs (whose cards go away). - Future<({List runs, Set dismissed})> runs( - String sessionId, - ) async { + /// The session's recorded runs, oldest first, each with its output tail; + /// the ids of its dismissed runs (whose cards go away); and the dismissed + /// runs themselves, which a server that keeps them also sends. + Future< + ({ + List runs, + Set dismissed, + List dismissedRuns, + }) + > + runs(String sessionId) async { final reply = await gateway.call('chat_shell_runs', { 'chat_query': {'session_id': sessionId}, }); - return (runs: _records(reply), dismissed: _ids(reply)); + return ( + runs: _records(reply), + dismissed: _ids(reply), + dismissedRuns: _records(reply, 'chat_shell_dismissed_runs'), + ); } /// Dismisses finished runs for every client of the chat; the reply names @@ -78,8 +88,8 @@ class ChatShellRunsRepository { ), ); - /// Undoes a dismissal still inside the server's undo window; the reply is - /// the restored runs with their output tail. + /// Undoes a dismissal (at any time; an older server only within its undo + /// window); the reply is the restored runs with their output tail. Future> restore( String sessionId, List runIds, @@ -87,8 +97,11 @@ class ChatShellRunsRepository { await gateway.call('chat_shell_restore', _body(sessionId, runIds: runIds)), ); - List _records(JsonMap reply) { - final value = reply['chat_shell_runs']; + List _records( + JsonMap reply, [ + String field = 'chat_shell_runs', + ]) { + final value = reply[field]; return [ if (value is List) for (final item in value) ?ChatShellRun.fromJson(item), diff --git a/app/lib/features/chat/ui/transcript/chat_copy_gutter.dart b/app/lib/features/chat/ui/transcript/chat_copy_gutter.dart new file mode 100644 index 00000000..b4d84d31 --- /dev/null +++ b/app/lib/features/chat/ui/transcript/chat_copy_gutter.dart @@ -0,0 +1,110 @@ +import 'package:flutter/material.dart'; + +import '../../../../ui/adaptive/platform.dart'; + +/// The width of the strip left of the reading column that an answer row +/// draws its Copy button in (`chatCopyGutter`); 0 when there is no room, and +/// Copy stays in the answer's footer. +class ChatCopyGutter extends InheritedWidget { + const ChatCopyGutter({super.key, required this.width, required super.child}); + + final double width; + + static double of(BuildContext context) => + context.dependOnInheritedWidgetOfExactType()?.width ?? 0; + + @override + bool updateShouldNotify(ChatCopyGutter oldWidget) => width != oldWidget.width; +} + +/// The transcript's [children] when the list starts [gutter] left of the +/// reading column: every child except the transcript [rows] (which inset +/// themselves) is inset past the gutter, so it keeps to the column. +List chatCopyGutterInset( + double gutter, + List rows, + List children, +) { + if (gutter <= 0) return children; + final own = Set.identity()..addAll(rows); + return [ + for (final child in children) + if (own.contains(child)) + child + else + Padding( + key: child.key, + padding: EdgeInsets.only(left: gutter), + child: child, + ), + ]; +} + +/// An answer with its Copy button in the gutter to its left, bottom-aligned +/// with the answer's footer row. On a desktop the button shows while the +/// pointer is over the answer or the button has focus; it stays in the +/// focus order and the semantics tree when hidden. Touch platforms always +/// show it. +class ChatCopyGutterRow extends StatefulWidget { + const ChatCopyGutterRow({ + super.key, + required this.width, + required this.copy, + required this.child, + }); + + final double width; + + /// The Copy button, or null when the answer has nothing to copy yet. + final Widget? copy; + final Widget child; + + @override + State createState() => _ChatCopyGutterRowState(); +} + +class _ChatCopyGutterRowState extends State { + bool _hovered = false; + bool _focused = false; + + @override + Widget build(BuildContext context) { + final hover = prefersCompactHitTargets(context); + final copy = widget.copy; + final row = Row( + mainAxisSize: MainAxisSize.min, + crossAxisAlignment: CrossAxisAlignment.end, + children: [ + SizedBox( + key: const Key('chat-copy-gutter'), + width: widget.width, + child: copy == null + ? null + : Align( + alignment: Alignment.bottomRight, + child: Focus( + canRequestFocus: false, + skipTraversal: true, + onFocusChange: (focused) => + setState(() => _focused = focused), + child: AnimatedOpacity( + key: const Key('chat-copy-gutter-visibility'), + opacity: !hover || _hovered || _focused ? 1 : 0, + duration: const Duration(milliseconds: 120), + alwaysIncludeSemantics: true, + child: copy, + ), + ), + ), + ), + Flexible(child: widget.child), + ], + ); + if (!hover || copy == null) return row; + return MouseRegion( + onEnter: (_) => setState(() => _hovered = true), + onExit: (_) => setState(() => _hovered = false), + child: row, + ); + } +} diff --git a/app/lib/features/chat/ui/transcript/chat_message_view.dart b/app/lib/features/chat/ui/transcript/chat_message_view.dart index 060a3699..a8005b8d 100644 --- a/app/lib/features/chat/ui/transcript/chat_message_view.dart +++ b/app/lib/features/chat/ui/transcript/chat_message_view.dart @@ -10,6 +10,7 @@ import 'chat_attachment_gallery.dart'; import '../../domain/chat_tool_calls.dart'; import '../../domain/chat_transcript.dart'; import 'chat_copy_button.dart'; +import 'chat_copy_gutter.dart'; import 'chat_link_text.dart'; import 'chat_message_bubble.dart'; import 'chat_turn_activity_view.dart'; @@ -49,6 +50,9 @@ class ChatMessageView extends StatelessWidget { final role = user ? 'User' : 'Assistant'; final cupertino = _isCupertino(context); final content = user ? _userParts(context) : _agentParts(context); + // A wide window draws an answer's Copy in the gutter left of the reading + // column; without room it stays at the start of the answer's footer. + final gutter = user ? 0.0 : ChatCopyGutter.of(context); // No visible role label: side and surface say who spoke and the row's // semantics label names the role. The operator's turn is a neutral bubble // that shrinks to its content; the agent's answer sits on the page with no @@ -79,14 +83,15 @@ class ChatMessageView extends StatelessWidget { constraints: BoxConstraints( maxWidth: user ? (constraints.maxWidth * 0.85).clamp(0, 560).toDouble() - : 720, + : 720 + gutter, ), child: user ? _userTurn(cupertino, content, body) - : _agentTurn( + : _agentRow( context, content, ChatAgentSurface(cupertino: cupertino, child: body), + gutter, ), ), ), @@ -174,9 +179,34 @@ class ChatMessageView extends StatelessWidget { return widgets; } + /// The answer, with its Copy button in the [gutter] to its left when there + /// is one, or else first in its footer. + Widget _agentRow( + BuildContext context, + List content, + Widget answer, + double gutter, + ) { + final copyText = row['streaming'] == true ? '' : _answerText(_partsOf(row)); + final copy = copyText.isEmpty + ? null + : ChatCopyButton(text: copyText, cupertino: _isCupertino(context)); + if (gutter <= 0) return _agentTurn(context, content, answer, copy); + return ChatCopyGutterRow( + width: gutter, + copy: copy, + child: _agentTurn(context, content, answer, null), + ); + } + /// Stable activity precedes the answer; permission summaries and recorded /// model remain beneath it. Pending interaction cards are rendered separately. - Widget _agentTurn(BuildContext context, List content, Widget answer) { + Widget _agentTurn( + BuildContext context, + List content, + Widget answer, + Widget? copy, + ) { final parts = _partsOf(row); final reasoning = [ for (final part in parts) @@ -189,10 +219,8 @@ class ChatMessageView extends StatelessWidget { if (isChatToolPart(part)) part, ]; final model = '${row['model'] ?? ''}'.trim(); - final copyText = row['streaming'] == true ? '' : _answerText(parts); final footer = [ - if (copyText.isNotEmpty) - ChatCopyButton(text: copyText, cupertino: _isCupertino(context)), + ?copy, ...this.footer, if (model.isNotEmpty) Text( diff --git a/app/notes/chat-copy-gutter.md b/app/notes/chat-copy-gutter.md new file mode 100644 index 00000000..2a8d96c4 --- /dev/null +++ b/app/notes/chat-copy-gutter.md @@ -0,0 +1,31 @@ +# Answer Copy button in the left gutter + +Operator request: "Let's move the copy button from the answer to the left, +outside the chat, to the left." + +- On a wide conversation the answer's Copy icon button sits in a strip left + of the reading column, outside the answer, bottom-aligned with the + answer's footer row. The footer now starts with the chips, model and time. +- The rule is centralized in `conversation/chat_reading_width.dart`: + `chatCopyGutter(width)` is `kChatCopyGutterWidth` (48 px) when the margin + beside the centred 760 px reading column is at least that wide, else 0. + With 0 (phones, narrow panes) Copy stays first in the footer as before. +- The transcript list starts the gutter's width further left; answer rows + draw the gutter themselves (`ChatCopyGutterRow`, provided through the + `ChatCopyGutter` inherited width) and every other row and notice is inset + past it (`chatCopyGutterInset`), so the column itself does not move. +- Visibility: touch platforms always show it. Desktops + (`prefersCompactHitTargets`) show it while the pointer is over the answer + or the button has keyboard focus. Hidden, it stays in the focus order and + the semantics tree (tooltip and name "Copy"). +- Files: `lib/features/chat/ui/transcript/chat_copy_gutter.dart`, + `chat_message_view.dart`, `conversation/chat_reading_width.dart`, + `conversation/chat_thread_view.dart`. +- Tests: `test/features/chat/ui/transcript/chat_copy_gutter_test.dart` (the + rule, footer vs gutter placement, alignment with the footer, hover and + focus on macOS, semantics while hidden, a 1400 px vs 560 px conversation). +- Verification (2026-11-09): `tool/memwatch/full.sh test/features/chat`: + `PASS: 1161 passed, 0 failed`; `tool/analyze.sh` clean. Real Chrome + captures (Material light and dark): at 1400x900 the gutter Copy hidden and + shown on hover, aligned with the footer chip; at 560x1000 Copy back in the + footer. Touch platforms (always visible) were checked by widget tests only. diff --git a/app/notes/chat-shell-commands.md b/app/notes/chat-shell-commands.md index 384f6850..1ed32a2d 100644 --- a/app/notes/chat-shell-commands.md +++ b/app/notes/chat-shell-commands.md @@ -143,28 +143,34 @@ change, and `{session_id, run_id, output, offset, end}` for output chunks. run has finished. It dismisses every finished run and leaves running ones. - Dismissal is per chat, for every client (not per device). The card goes at once. A refusal brings the card back with the server's reason. -- Undo: a 5 s SnackBar (Material) or a transient notice over the - conversation (Cupertino, `ChatUndoBar` in the root overlay) offers Undo. - The Cupertino notice briefly covers the composer. -- Server design: dismiss-then-restore within a window, then purge. +- History: a dismissed card is not lost. It moves into a "N commands" chip + in an answer's footer (see "Command history" below), which can restore it. + There is no Undo notice. +- Server design (since 2026-11-09): dismiss keeps the run. `chat_shell_dismiss {session_id, run_ids}` sets `dismissed_at` on finished runs and pushes `chat_shell_run_event {dismissed: true}` to every watcher. - `chat_shell_restore {session_id, run_ids}` clears it within - `ChatShellRunUndoWindow` (30 s, longer than the 5 s notice). The reply - carries the runs, and watchers get lifecycle frames. A client that held no - copy reads the list again for the output. After the window the server - purges the run's command, output, output text and error (an `AfterFunc`, - plus on every server start). Only a tombstone row remains. -- Readback: `chat_shell_runs` and `chat_shell_run_output` exclude dismissed - runs. `chat_shell_runs` lists tombstone ids in `chat_shell_dismissed`, so a - client that missed the event drops those cards on its next refresh. - Tombstones age out with the 50-run history prune. + The command, folder, status, exit code, times, output tail (1 MiB) and + plain-text rendering stay, within the usual 50-run history. Nothing is + purged: the undo window, its `AfterFunc` and the startup purge are gone. + `chat_shell_restore {session_id, run_ids}` clears `dismissed_at` at any + time. The reply carries the runs, and watchers get lifecycle frames. +- Readback: `chat_shell_runs` leaves dismissed runs out of + `chat_shell_runs`, lists their ids in `chat_shell_dismissed` (as before) + and the runs themselves in `chat_shell_dismissed_runs` (oldest first, + 64 KiB tail each, `dismissed: true`, `dismissed_at`). + `chat_shell_run_output` and `chat_shell_share` work for a dismissed run. +- Older rows: a run an older server already purged keeps `purged = 1`. It is + listed with `purged: true` and no command or output. The app shows it as + "Command not kept" / "Output not kept" and offers no Restore (the server + refuses to restore it). - Files: `internal/protocol/chat_shell_dismiss.go`, `internal/pipeline/chat_shell_dismiss.go`, `internal/server/chat_shell_dismiss.go`, - `lib/features/chat/shell/chat_shell_dismiss.dart` (button, menu entry, - Undo notice) and `chat_shell_runs_dismissal.dart` (controller part). -- Tests: `internal/pipeline/chat_shell_dismiss_test.go` covers dismiss, + `lib/features/chat/shell/chat_shell_dismiss.dart` (button, menu entry) + and `chat_shell_runs_dismissal.dart` (controller part). +- Tests and verification of the first version (superseded where they + mention Undo or purging; see "Command history" below for the current + tests): `internal/pipeline/chat_shell_dismiss_test.go` covers dismiss, readback, restore, purge and tombstones. `internal/server/chat_shell_dismiss_test.go` covers the websocket dismiss to two watchers, refusing a running or empty request, readback with @@ -247,5 +253,56 @@ end to end. The Go websocket tests cover the server with real processes, and the browser captures use the fixture channel. Mobile devices were not tested. **Update:** dismissing no longer shows a notice or Undo; the card simply -goes away (operator request). The server still accepts `chat_shell_restore` -within its 30 s window, but the app no longer offers it. +goes away (operator request). + +## Command history (2026-11-09) + +Operator request: "when we dismiss a command, it should show in the bottom +like the files changes, model, etc, so that I can expand and see the +history." + +- A dismissed run leaves the transcript and shows as a chip in an answer's + footer, in the same row and chip family (`ChatTurnChip`) as + "3 files changed +9 −2", the tool chips, the model and the time: a terminal + icon and "2 commands". +- Placement (`shell/chat_shell_history.dart`, `attachChatShellHistory`): + each run goes to the first assistant reply created at or after the run + started. A run newer than every reply goes to the last reply. A chat with + no reply shows the chip on its own row at the end of the transcript. +- Tapping the chip opens the turn sheet on a wide window (≥ 600 px) or a + full-screen page on a narrow one, like the diff chip. "Dismissed commands" + lists each command with its exit status chip and duration, its start time, + and Restore. Tapping a command opens its whole retained output read-only + in the card's terminal view (`chat_shell_run_output`), with Copy output, + Send to agent and Restore. Restore puts the card back in the transcript for + every client. A refusal shows the server's reason under the entry. +- Multi-machine: everything goes through the chat's own gateway, as cards do. +- Files: `lib/features/chat/shell/chat_shell_history.dart` (placement, + labels), `chat_shell_history_chip.dart`, `chat_shell_history_view.dart`, + `chat_shell_history_output_page.dart`; controller part + `chat_shell_runs_dismissal.dart` (`dismissedRuns`, `restore`, + `fullOutput`); hooks in `conversation/chat_thread_view.dart`. Server: + `internal/{protocol,pipeline,server}/chat_shell_dismiss.go`. +- Tests: `internal/pipeline/chat_shell_dismiss_test.go` (dismiss keeps + output, readback, restore without a time limit, older purged tombstones, + dismissed runs counting toward the 50-run history); + `internal/server/chat_shell_dismiss_test.go` (websocket dismiss to two + watchers, readback of dismissed runs with output, output read of a + dismissed run, restore, restore a day later after a restart); + `test/features/chat/shell/chat_shell_history_test.dart` (placement rules) + and `chat_shell_history_view_test.dart` (chip in the right answer's + footer, the no-reply row, dismiss moving a card into the chip, sheet, + output, Copy, Send to agent, Restore, narrow page, purged rows, a refused + restore). +- Capture fixture: `?shell_dismissed=run_status,run_tests` starts with those + runs dismissed (`tool/perf/chat_shell_fixture.dart`). +- Verification (2026-11-09): `go test ./internal/protocol ./internal/pipeline + ./internal/server` all ok (server 74 s). `tool/memwatch/full.sh + test/features/chat`: `PASS: 1161 passed, 0 failed`. `tool/analyze.sh`: + clean. Real Chrome captures (`tool/capture`, + `chats=1&msgs=4&shell=1&rich=1&shell_dismissed=run_status,run_tests`), + Material light and dark: at 1400x900 the footer chip, the sheet and a + command's output page; at 560x1000 the footer chip, the full-screen list + and the list after Restore, plus (light) the restored card back in the + transcript with "1 command". The PNGs were inspected. Cupertino, a live + server end to end and mobile devices were not exercised. diff --git a/app/test/features/chat/shell/chat_shell_fixtures.dart b/app/test/features/chat/shell/chat_shell_fixtures.dart index 0b37fb35..577e935b 100644 --- a/app/test/features/chat/shell/chat_shell_fixtures.dart +++ b/app/test/features/chat/shell/chat_shell_fixtures.dart @@ -16,10 +16,15 @@ class ShellGateway implements ApiGateway { final calls = <({String type, JsonMap fields})>[]; final _frames = StreamController.broadcast(); List runs = const []; + + /// The chat history `chat_messages` answers with. + List messages = const []; String? refusal; - /// Tombstone ids the `chat_shell_runs` readback reports. + /// Dismissed ids the `chat_shell_runs` readback reports, and the dismissed + /// runs it carries (a server that keeps them). List dismissed = const []; + List dismissedRuns = const []; /// The refusal of `chat_shell_dismiss` / `chat_shell_restore`, when set. String? dismissRefusal; @@ -47,9 +52,13 @@ class ShellGateway implements ApiGateway { final body = fields['chat_shell_run_request'] as JsonMap? ?? const {}; switch (type) { case 'chat_messages': - return chatPage(const []); + return chatPage(messages); case 'chat_shell_runs': - return {'chat_shell_runs': runs, 'chat_shell_dismissed': dismissed}; + return { + 'chat_shell_runs': runs, + 'chat_shell_dismissed': dismissed, + 'chat_shell_dismissed_runs': dismissedRuns, + }; case 'chat_shell_dismiss': if (dismissRefusal != null) throw StateError(dismissRefusal!); return {'chat_shell_dismissed': body['run_ids']}; @@ -58,7 +67,7 @@ class ShellGateway implements ApiGateway { final ids = (body['run_ids'] as List).toSet(); return { 'chat_shell_runs': [ - for (final run in runs) + for (final run in [...runs, ...dismissedRuns]) if (ids.contains(run['id'])) run, ], }; @@ -75,7 +84,10 @@ class ShellGateway implements ApiGateway { return {'chat_shell_run': resumeReply}; } return { - 'chat_shell_run': runs.firstWhere((r) => r['id'] == body['run_id']), + 'chat_shell_run': [ + ...runs, + ...dismissedRuns, + ].firstWhere((r) => r['id'] == body['run_id']), }; } return {}; @@ -123,6 +135,7 @@ JsonMap shellRecord( bool terminal = false, String text = '', int outputStart = 0, + int startedAt = 1000, }) => { 'id': id, 'session_id': 's', @@ -130,8 +143,8 @@ JsonMap shellRecord( 'directory': '/home/op/project', 'status': status, 'exit_code': ?exitCode, - 'started_at': 1000, - 'ended_at': ?(status == 'running' ? null : 1000 + durationMs), + 'started_at': startedAt, + 'ended_at': ?(status == 'running' ? null : startedAt + durationMs), 'duration_ms': durationMs, 'output': output, 'output_start': outputStart, diff --git a/app/test/features/chat/shell/chat_shell_history_test.dart b/app/test/features/chat/shell/chat_shell_history_test.dart new file mode 100644 index 00000000..8fe18502 --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_history_test.dart @@ -0,0 +1,71 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/api_gateway.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_history.dart'; +import 'package:pipelines_app/features/chat/shell/chat_shell_run.dart'; + +ChatShellRun _run(String id, int started) => ChatShellRun( + id: id, + command: 'echo $id', + directory: '/w', + status: 'exited', + exitCode: 0, + startedAt: started, +); + +JsonMap _reply(String id, int? created) => { + 'kind': 'assistant', + 'key': id, + 'created_at': ?created, +}; + +void main() { + test('each run attaches to the first reply at or after its start', () { + final rows = [ + {'kind': 'user', 'created_at': 5}, + _reply('a', 10), + {'kind': 'user', 'created_at': 15}, + _reply('b', 20), + _reply('c', 30), + ]; + final attached = attachChatShellHistory(rows, [ + _run('late', 31), + _run('before', 1), + _run('exact', 20), + _run('between', 12), + ]); + expect(chatShellHistoryIds(attached[1]), ['before']); + expect(chatShellHistoryIds(attached[3]), ['between', 'exact']); + // Newer than every reply: the last reply. + expect(chatShellHistoryIds(attached[4]), ['late']); + expect(attached[0].containsKey(chatShellHistoryField), isFalse); + expect(attached[2].containsKey(chatShellHistoryField), isFalse); + expect(attached, hasLength(rows.length)); + }); + + test('a reply without a time is only the fallback last reply', () { + final rows = [_reply('a', 10), _reply('pending', null)]; + final attached = attachChatShellHistory(rows, [ + _run('x', 5), + _run('y', 50), + ]); + expect(chatShellHistoryIds(attached[0]), ['x']); + expect(chatShellHistoryIds(attached[1]), ['y']); + }); + + test('with no reply the runs get their own row at the end', () { + final rows = [ + {'kind': 'user', 'created_at': 5}, + ]; + final attached = attachChatShellHistory(rows, [_run('b', 9), _run('a', 1)]); + expect(attached, hasLength(2)); + expect(attached.last['kind'], chatShellHistoryRowKind); + expect(chatShellHistoryIds(attached.last), ['a', 'b']); + expect(attachChatShellHistory(rows, const []), same(rows)); + }); + + test('labels count the commands', () { + expect(chatShellHistoryLabel(1), '1 command'); + expect(chatShellHistoryLabel(2), '2 commands'); + expect(chatShellHistorySemantics(2), contains('open command history')); + }); +} diff --git a/app/test/features/chat/shell/chat_shell_history_view_test.dart b/app/test/features/chat/shell/chat_shell_history_view_test.dart new file mode 100644 index 00000000..e735f44e --- /dev/null +++ b/app/test/features/chat/shell/chat_shell_history_view_test.dart @@ -0,0 +1,256 @@ +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/ui/transcript/chat_message_view.dart'; + +import 'chat_shell_fixtures.dart'; + +void main() { + late ShellGateway gateway; + + setUp(() => gateway = ShellGateway()); + tearDown(() => gateway.close()); + + Finder card() => find.bySemanticsIdentifier('chat-shell-run-card'); + final chip = find.byKey(const Key('chat-shell-history-chip')); + + JsonMap dismissed(String id, int started, {String command = 'true'}) => { + ...shellRecord( + id, + command: command, + status: 'exited', + exitCode: 0, + output: 'out $id\r\n', + text: 'out $id\n', + durationMs: 50, + startedAt: started, + ), + 'dismissed': true, + 'dismissed_at': started + 100, + }; + + JsonMap reply(String id, int created, String text) => { + 'id': id, + 'role': 'assistant', + 'created_at': created, + 'parts': [ + {'type': 'text', 'text': text}, + ], + }; + + void size(WidgetTester tester, Size size) { + tester.view.physicalSize = size; + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + } + + Future open(WidgetTester tester) async { + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + await tester.pump(); + } + + void history(List runs) { + gateway.dismissedRuns = runs; + gateway.dismissed = [for (final run in runs) '${run['id']}']; + } + + testWidgets('dismissed runs sit in the footer of the reply that followed', ( + tester, + ) async { + size(tester, const Size(1400, 900)); + gateway.messages = [ + reply('a1', 10000, 'First answer'), + { + 'id': 'u2', + 'role': 'user', + 'created_at': 11000, + 'parts': [ + {'type': 'text', 'text': 'Next question'}, + ], + }, + reply('a2', 20000, 'Second answer'), + ]; + history([ + dismissed('run_a', 12000, command: 'ls'), + dismissed('run_b', 15000, command: 'pwd'), + ]); + await open(tester); + + expect(card(), findsNothing); + expect(chip, findsOneWidget); + expect(find.text('2 commands'), findsOneWidget); + // The chip is in the second answer's footer, beside its other chips. + final footer = find.ancestor( + of: chip, + matching: find.byKey(const Key('chat-message-footer')), + ); + expect(footer, findsOneWidget); + final message = find.ancestor( + of: chip, + matching: find.byType(ChatMessageView), + ); + expect( + find.descendant(of: message, matching: find.text('Second answer')), + findsOneWidget, + ); + expect( + find.descendant(of: message, matching: find.text('First answer')), + findsNothing, + ); + }); + + testWidgets('a chat with no answer shows the chip on its own row', ( + tester, + ) async { + history([dismissed('run_a', 1000)]); + await open(tester); + expect(find.text('1 command'), findsOneWidget); + expect( + find.ancestor( + of: chip, + matching: find.byKey(const Key('chat-message-footer')), + ), + findsNothing, + ); + }); + + testWidgets('dismissing a card moves it into the chip', (tester) async { + gateway.runs = [ + shellRecord('run_done', status: 'exited', exitCode: 0, durationMs: 9), + ]; + await open(tester); + expect(chip, findsNothing); + await tester.tap(find.byKey(const Key('chat-shell-run-dismiss'))); + await tester.pump(); + expect(card(), findsNothing); + expect(find.text('1 command'), findsOneWidget); + }); + + testWidgets('wide: the sheet lists commands, opens output and restores', ( + tester, + ) async { + size(tester, const Size(1400, 900)); + final copied = []; + tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + (call) async { + if (call.method == 'Clipboard.setData') { + copied.add('${(call.arguments as Map)['text']}'); + } + return null; + }, + ); + addTearDown( + () => tester.binding.defaultBinaryMessenger.setMockMethodCallHandler( + SystemChannels.platform, + null, + ), + ); + gateway.messages = [reply('a1', 10000, 'Answer')]; + history([dismissed('run_a', 5000, command: 'git status')]); + await open(tester); + + await tester.tap(chip); + await tester.pumpAndSettle(); + expect(find.byType(BottomSheet), findsOneWidget); + expect(find.text('Dismissed commands'), findsOneWidget); + expect(find.text('\$ git status'), findsOneWidget); + expect(find.text('Exit 0 · 50 ms'), findsOneWidget); + + // Its output, read-only, with Copy output and Send to agent. + await tester.tap(find.byKey(const ValueKey('chat-shell-history-run_a'))); + await tester.pumpAndSettle(); + expect(gateway.bodies('chat_shell_run_output').last['run_id'], 'run_a'); + expect(terminalText(tester), 'out run_a'); + await tester.tap(find.byKey(const Key('chat-shell-history-copy'))); + await tester.pump(); + expect(copied, ['out run_a\n']); + await tester.tap(find.byKey(const Key('chat-shell-history-share'))); + await tester.pump(); + expect(gateway.bodies('chat_shell_share').single['run_id'], 'run_a'); + await tester.pageBack(); + await tester.pumpAndSettle(); + + // Restore puts the card back and the chip goes. + await tester.tap( + find.byKey(const ValueKey('chat-shell-history-restore-run_a')), + ); + await tester.pumpAndSettle(); + expect(gateway.bodies('chat_shell_restore').single['run_ids'], ['run_a']); + expect(find.textContaining('restored to the transcript'), findsOneWidget); + Navigator.of(tester.element(find.byType(BottomSheet))).pop(); + await tester.pumpAndSettle(); + expect(card(), findsOneWidget); + expect(chip, findsNothing); + }); + + testWidgets('narrow: the history opens as a full-screen page', ( + tester, + ) async { + size(tester, const Size(400, 800)); + gateway.messages = [reply('a1', 10000, 'Answer')]; + history([dismissed('run_a', 5000)]); + await open(tester); + await tester.tap(chip); + await tester.pumpAndSettle(); + expect(find.byType(BottomSheet), findsNothing); + expect( + find.descendant( + of: find.byType(AppBar), + matching: find.text('Dismissed commands'), + ), + findsOneWidget, + ); + await tester.tap( + find.byKey(const ValueKey('chat-shell-history-restore-run_a')), + ); + await tester.pumpAndSettle(); + expect(gateway.bodies('chat_shell_restore').single['run_ids'], ['run_a']); + }); + + testWidgets('a run an older server purged says its output was not kept', ( + tester, + ) async { + size(tester, const Size(1400, 900)); + history([ + { + 'id': 'run_old', + 'session_id': 's', + 'command': '', + 'directory': '/w', + 'status': 'exited', + 'exit_code': 0, + 'started_at': 1000, + 'dismissed': true, + 'purged': true, + }, + ]); + await open(tester); + await tester.tap(chip); + await tester.pumpAndSettle(); + expect(find.text('Command not kept'), findsOneWidget); + expect(find.text('Output not kept'), findsOneWidget); + expect( + find.byKey(const ValueKey('chat-shell-history-restore-run_old')), + findsNothing, + ); + }); + + testWidgets('a refused restore shows the reason in the list', (tester) async { + size(tester, const Size(1400, 900)); + gateway.restoreRefusal = 'these commands can no longer be restored'; + history([dismissed('run_a', 1000)]); + await open(tester); + await tester.tap(chip); + await tester.pumpAndSettle(); + await tester.tap( + find.byKey(const ValueKey('chat-shell-history-restore-run_a')), + ); + await tester.pumpAndSettle(); + expect(find.byKey(const Key('chat-shell-history-refusal')), findsOneWidget); + expect(find.textContaining('no longer be restored'), findsOneWidget); + }); +} diff --git a/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart b/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart new file mode 100644 index 00000000..c66a4070 --- /dev/null +++ b/app/test/features/chat/ui/transcript/chat_copy_gutter_test.dart @@ -0,0 +1,150 @@ +import 'package:flutter/gestures.dart'; +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_reading_width.dart'; +import 'package:pipelines_app/features/chat/domain/chat_transcript.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_copy_gutter.dart'; +import 'package:pipelines_app/features/chat/ui/transcript/chat_message_view.dart'; + +import '../../shell/chat_shell_fixtures.dart'; + +JsonMap _answer() => transcriptRows([ + { + 'id': 'a1', + 'role': 'assistant', + 'model': 'gpt-test', + 'created_at': 1000, + 'parts': [ + {'type': 'text', 'text': 'The answer text'}, + ], + }, +]).single; + +Widget _host(double gutter) => MaterialApp( + home: Scaffold( + body: ListView( + children: [ + ChatCopyGutter( + width: gutter, + child: ChatMessageView(row: _answer()), + ), + ], + ), + ), +); + +final _copy = find.byKey(const Key('chat-message-copy')); +final _footer = find.byKey(const Key('chat-message-footer')); +final _gutter = find.byKey(const Key('chat-copy-gutter')); + +double _opacity(WidgetTester tester) => tester + .widget( + find.byKey(const Key('chat-copy-gutter-visibility')), + ) + .opacity; + +void main() { + test('the gutter needs room left of the reading column', () { + expect(chatCopyGutter(kChatReadingWidth + 2 * kChatCopyGutterWidth), 48); + expect(chatCopyGutter(1400), kChatCopyGutterWidth); + expect(chatCopyGutter(kChatReadingWidth + 90), 0); + expect(chatCopyGutter(560), 0); + }); + + testWidgets('without a gutter Copy starts the footer', (tester) async { + await tester.pumpWidget(_host(0)); + expect(find.descendant(of: _footer, matching: _copy), findsOneWidget); + expect(_gutter, findsNothing); + }); + + testWidgets('with a gutter Copy sits left of the answer, not in it', ( + tester, + ) async { + await tester.pumpWidget(_host(48)); + expect(find.descendant(of: _footer, matching: _copy), findsNothing); + expect(find.descendant(of: _gutter, matching: _copy), findsOneWidget); + expect(find.byTooltip('Copy'), findsOneWidget); + final copy = tester.getRect(_copy); + final text = tester.getRect(find.text('The answer text')); + final footer = tester.getRect(_footer); + expect(copy.right, lessThanOrEqualTo(text.left)); + // Bottom-aligned with the footer row (model and time). + expect((copy.bottom - footer.bottom).abs(), lessThan(1)); + // Touch platforms always show it. + expect(_opacity(tester), 1); + }); + + testWidgets('desktop shows it on hover and focus, and keeps semantics', ( + tester, + ) async { + final semantics = tester.ensureSemantics(); + await tester.pumpWidget(_host(48)); + expect(_opacity(tester), 0); + // Hidden, it is still reachable by a screen reader. + expect( + tester.getSemantics(_copy), + isSemantics(tooltip: 'Copy', isButton: true, isFocusable: true), + ); + + final mouse = await tester.createGesture(kind: PointerDeviceKind.mouse); + addTearDown(mouse.removePointer); + await mouse.addPointer(location: Offset.zero); + await mouse.moveTo(tester.getCenter(find.text('The answer text'))); + await tester.pumpAndSettle(); + expect(_opacity(tester), 1); + await mouse.moveTo(const Offset(5, 590)); + await tester.pumpAndSettle(); + expect(_opacity(tester), 0); + + // Keyboard focus reveals it too. + await tester.sendKeyEvent(LogicalKeyboardKey.tab); + await tester.pumpAndSettle(); + expect(_opacity(tester), 1); + semantics.dispose(); + }, variant: TargetPlatformVariant.only(TargetPlatform.macOS)); + + for (final (width, inGutter) in [(1400.0, true), (560.0, false)]) { + testWidgets('a ${width.toInt()} px conversation puts Copy ' + '${inGutter ? 'in the gutter' : 'in the footer'}', (tester) async { + tester.view.physicalSize = Size(width, 900); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final gateway = ShellGateway() + ..messages = [ + { + 'id': 'a1', + 'role': 'assistant', + 'created_at': 1000, + 'parts': [ + {'type': 'text', 'text': 'The answer text'}, + ], + }, + ]; + addTearDown(gateway.close); + await tester.pumpWidget(shellThread(gateway)); + await tester.pump(); + await tester.pump(); + expect(_copy, findsOneWidget); + expect( + find.descendant(of: _footer, matching: _copy), + inGutter ? findsNothing : findsOneWidget, + ); + final copy = tester.getRect(_copy); + final text = tester.getRect(find.text('The answer text')); + if (inGutter) { + expect(copy.right, lessThanOrEqualTo(text.left)); + // The answer itself did not move: it starts where the column does. + final column = chatReadingInset( + tester.getSize(find.byType(Scaffold)).width, + ); + expect(text.left, greaterThanOrEqualTo(column)); + expect(copy.left, greaterThanOrEqualTo(column - kChatCopyGutterWidth)); + } else { + expect(copy.top, greaterThanOrEqualTo(text.bottom)); + } + }); + } +} diff --git a/app/tool/perf/chat_shell_fixture.dart b/app/tool/perf/chat_shell_fixture.dart index 9d88d9e1..c12b9632 100644 --- a/app/tool/perf/chat_shell_fixture.dart +++ b/app/tool/perf/chat_shell_fixture.dart @@ -2,8 +2,10 @@ // `?chats=N`): every fixture chat lists four recorded terminal runs // (succeeded, failed, stopped and an interactive login still waiting for a // token), and chat_shell_run/stop/share/input answer as the server does, with -// the frames that follow; chat_shell_dismiss/restore hide and bring back runs. The login prompt hides what is typed, as a real -// terminal's password prompt does, and finishes on Enter. +// the frames that follow; chat_shell_dismiss/restore move runs into and out +// of the dismissed list the readback reports (`?shell_dismissed=a,b` starts +// with those run ids dismissed). The login prompt hides what is typed, as a +// real terminal's password prompt does, and finishes on Enter. import 'dart:convert'; import 'package:pipelines_app/core/api_gateway.dart'; @@ -23,7 +25,12 @@ void configureChatShellFixture(Map params) { _enabled = params['shell'] == '1'; _base = DateTime.now().subtract(const Duration(minutes: 3)); _loginEnd = utf8.encode(_loginPrompt).length; - _dismissed.clear(); + _dismissed + ..clear() + ..addAll([ + for (final id in (params['shell_dismissed'] ?? '').split(',')) + if (id.trim().isNotEmpty) id.trim(), + ]); } const String _loginPrompt = @@ -128,6 +135,11 @@ JsonMap? chatShellReply(JsonMap request) { if (!_dismissed.contains(run['id'])) run, ], 'chat_shell_dismissed': _dismissed.toList(), + 'chat_shell_dismissed_runs': [ + for (final run in _runs(session)) + if (_dismissed.contains(run['id'])) + {...run, 'dismissed': true, 'dismissed_at': _at(200)}, + ], }; case 'chat_shell_dismiss': final ids = _runIds(body);