Dismiss and restore operator shell commands per chat

chat_shell_dismiss hides finished runs from every readback and pushes a
dismissal frame to every watcher; chat_shell_restore undoes it within a
30 s window, after which the command, output and error are purged and only
a tombstone remains, reported by chat_shell_runs for clients that missed
the event.
This commit is contained in:
2026-11-09 21:22:07 +00:00
parent 8f06f12d49
commit 03123c23fd
11 changed files with 513 additions and 9 deletions
+1 -1
View File
@@ -259,7 +259,7 @@ func handleChat(ctx context.Context, request protocol.Message, broker chatBroker
handleChatShellOutput(ctx, request, broker, registry, write)
return true
case protocol.ChatShellRun, protocol.ChatShellStop, protocol.ChatShellRuns, protocol.ChatShellRunOutput, protocol.ChatShellShare,
protocol.ChatShellInput, protocol.ChatShellResize:
protocol.ChatShellInput, protocol.ChatShellResize, protocol.ChatShellDismiss, protocol.ChatShellRestore:
handleChatShellRunRequest(ctx, request, broker, hub, registry, clientID, write)
return true
case protocol.ChatAttachmentImage:
+107
View File
@@ -0,0 +1,107 @@
package server
import (
"context"
"errors"
"fmt"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
// 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)
}
func validChatShellRunIDs(ids []string) error {
if len(ids) == 0 {
return errors.New("name at least one command")
}
if len(ids) > protocol.ChatShellDismissLimit {
return fmt.Errorf("name at most %d commands", protocol.ChatShellDismissLimit)
}
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.
func (r *chatShellRunner) Dismiss(ctx context.Context, sessionID string, ids []string) ([]string, error) {
if err := validChatShellRunIDs(ids); err != nil {
return nil, err
}
finished := make([]string, 0, len(ids))
for _, id := range ids {
// The store refuses a run recorded as running; a process that just
// exited may not have saved its final record yet, so ask it too.
if r.activeProcess(sessionID, id) == nil {
finished = append(finished, id)
}
}
if len(finished) == 0 {
return nil, errors.New("stop the command and wait for it to finish before dismissing it")
}
dismissed, err := r.store.DismissChatShellRuns(ctx, sessionID, finished, r.now().UnixMilli())
if err != nil {
return nil, err
}
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.
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)
if err != nil {
return nil, err
}
if len(runs) == 0 {
return nil, errors.New("these commands can no longer be restored")
}
for i, run := range runs {
r.publishRun(run)
runs[i] = chatShellRecordTail(run, protocol.ChatShellRunListOutput)
runs[i].Text = ""
}
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)
}
})
}
func (r *chatShellRunner) publishFrame(frame protocol.ChatShellRunEventFrame) {
if r.publish != nil {
r.publish(frame.SessionID, frame)
}
}
+114
View File
@@ -0,0 +1,114 @@
package server
import (
"context"
"fmt"
"testing"
"time"
"git.a-wan.net/alan/pipelines/internal/protocol"
)
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) {
ctx, conns, _ := shellChat(t)
done := runShell(t, ctx, conns[0], "r1", "echo kept-output")
for _, conn := range conns {
finishedShell(t, ctx, conn, done.ID)
}
live := runShell(t, ctx, conns[0], "r2", "sleep 30")
// A running command alone is refused; with a finished one it is skipped.
writeChat(t, ctx, conns[0], dismissRequest(protocol.ChatShellDismiss, "running", live.ID))
if reply := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool { return m.ID == "running" }); reply.Type != protocol.Error {
t.Fatalf("dismissing a running command = %+v", reply)
}
writeChat(t, ctx, conns[0], dismissRequest(protocol.ChatShellDismiss, "empty"))
if reply := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool { return m.ID == "empty" }); reply.Type != protocol.Error {
t.Fatalf("dismissing nothing = %+v", reply)
}
writeChat(t, ctx, conns[0], dismissRequest(protocol.ChatShellDismiss, "d", done.ID, live.ID))
reply := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool { return m.ID == "d" })
if reply.Type != protocol.ChatShellDismiss || fmt.Sprint(reply.ChatShellDismissed) != fmt.Sprint([]string{done.ID}) {
t.Fatalf("dismiss reply = %+v", reply)
}
isDismissal := func(m protocol.Message) bool {
return m.Type == protocol.ChatShellRunEvent && m.ChatShellRunEvent != nil && m.ChatShellRunEvent.Dismissed
}
for i, conn := range conns {
if frame := readShellFrame(t, ctx, conn, isDismissal).ChatShellRunEvent; frame.RunID != done.ID || frame.SessionID != "ses_1" {
t.Fatalf("dismissal frame %d = %+v", i, frame)
}
}
// The readback leaves it out and reports its tombstone; its output is gone.
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)
}
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 {
t.Fatalf("output of a dismissed run = %+v", got)
}
// Undo 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" {
t.Fatalf("restore reply = %+v", restored)
}
for i, conn := range conns {
frame := readShellFrame(t, ctx, conn, func(m protocol.Message) bool {
return m.Type == protocol.ChatShellRunEvent && m.ChatShellRunEvent != nil && m.ChatShellRunEvent.RunID == done.ID && m.ChatShellRunEvent.Run != nil
}).ChatShellRunEvent
if frame.Run.Status != protocol.ChatShellRunExited {
t.Fatalf("restore frame %d = %+v", i, frame)
}
}
writeChat(t, ctx, conns[0], dismissRequest(protocol.ChatShellRestore, "undo-again", done.ID))
if got := readShellFrame(t, ctx, conns[0], func(m protocol.Message) bool { return m.ID == "undo-again" }); got.Type != protocol.Error {
t.Fatalf("restoring an undismissed run = %+v", got)
}
writeChat(t, ctx, conns[0], shellRequest(protocol.ChatShellStop, "stop", live.ID, ""))
finishedShell(t, ctx, conns[0], live.ID)
}
func TestChatShellDismissPurgesAfterTheUndoWindow(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)
if err != nil {
t.Fatal(err)
}
runner.Wait()
if frames.final(run.ID) == nil {
t.Fatal("the run never finished")
}
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.
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")
}
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)
}
}
+20 -1
View File
@@ -70,7 +70,26 @@ func handleChatShellRunRequest(ctx context.Context, request protocol.Message, br
fail(err)
return
}
_ = write(protocol.Message{Type: protocol.ChatShellRuns, ID: request.ID, ChatShellRuns: runs})
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})
case protocol.ChatShellDismiss:
dismissed, err := runner.Dismiss(ctx, sessionID, body.RunIDs)
if err != nil {
fail(err)
return
}
_ = write(protocol.Message{Type: protocol.ChatShellDismiss, ID: request.ID, ChatShellDismissed: dismissed})
case protocol.ChatShellRestore:
runs, err := runner.Restore(ctx, sessionID, body.RunIDs)
if err != nil {
fail(err)
return
}
_ = write(protocol.Message{Type: protocol.ChatShellRestore, ID: request.ID, ChatShellRuns: runs})
case protocol.ChatShellInput:
if err := runner.Input(sessionID, body.RunID, body.Data); err != nil {
fail(err)
+7 -1
View File
@@ -23,6 +23,7 @@ type chatShellRunStore interface {
ChatShellRuns(ctx context.Context, sessionID string) ([]protocol.ChatShellRunRecord, error)
ChatShellRun(ctx context.Context, sessionID, id string) (protocol.ChatShellRunRecord, bool, error)
InterruptChatShellRuns(ctx context.Context, endedAt int64, reason string) (int64, error)
chatShellDismissStore
}
const (
@@ -48,6 +49,8 @@ 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
@@ -74,6 +77,7 @@ 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{},
}
}
@@ -89,12 +93,14 @@ 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).
// 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.
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