From c78def70ddf06e89cc40e5ad640db0b8a636d558 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Tue, 20 Oct 2026 17:23:07 +0100 Subject: [PATCH] fix(chat): recover web approvals and questions across clients and reconnects --- docs/notes/web-interaction-recovery.md | 18 +++ internal/opencode/chat.go | 37 +++++- internal/opencode/chat_forms_readback_test.go | 24 ++++ internal/opencode/chat_test.go | 4 +- internal/opencode/native.go | 3 + internal/server/chat.go | 4 + internal/server/chat_browser_test.go | 81 ++++++++++++- internal/server/chat_manager.go | 13 ++ internal/server/chat_room.go | 111 +++++++++++++++--- internal/server/chat_stream.go | 3 + internal/server/chat_test.go | 4 +- web/PARITY.md | 22 ++++ web/src/chat.js | 31 ++++- web/src/views/chat.js | 68 ++++++++--- web/test/chat-hardening-probe.mjs | 28 ++++- web/test/chatInteractions.test.mjs | 23 ++++ 16 files changed, 420 insertions(+), 54 deletions(-) create mode 100644 docs/notes/web-interaction-recovery.md create mode 100644 internal/opencode/chat_forms_readback_test.go create mode 100644 web/test/chatInteractions.test.mjs diff --git a/docs/notes/web-interaction-recovery.md b/docs/notes/web-interaction-recovery.md new file mode 100644 index 00000000..7760d8a5 --- /dev/null +++ b/docs/notes/web-interaction-recovery.md @@ -0,0 +1,18 @@ +# Web interaction recovery + +The OpenCode V2 pending-permission list is location-scoped. Chat must use +`GET /api/session/{sessionID}/permission`, not `/api/permission/request`, +otherwise a browser can miss a request from another directory. Merely attaching +to a chat starts permission polling: the web must not require a new prompt to +show a CLI-originated approval. Deduplication belongs to the current room, not +the retained turn's historical seen-id set. + +Pending questions are reconciled from `GET /api/session/{sessionID}/form`. +Unknown readback capability is distinct from an authoritative empty list, so an +unsupported backend cannot clear a live question. The browser retains each +request independently; answering one must not hide another. Draft question +answers survive streaming updates. Full approval resource text is expandable. + +The controlled browser regression reloads with two pending approvals and two +questions, then checks that all four replies reach Go. It does not execute real +commands, alter permission configuration, or approve a production request. diff --git a/internal/opencode/chat.go b/internal/opencode/chat.go index 7eb19d74..9508956c 100644 --- a/internal/opencode/chat.go +++ b/internal/opencode/chat.go @@ -442,8 +442,9 @@ func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) err } // Permissions lists the session's pending OpenCode approval requests, mirroring -// GET /api/permission/request. The endpoint is global, so the decoded list is -// filtered to sessionID; a malformed response is an error, never an empty +// GET /api/session/{id}/permission. The location-wide endpoint can silently +// miss chats in another directory. Results are still filtered to sessionID; +// a malformed response is an error, never an empty // success. It reuses Connection.Call so the request keeps the shared bounds, // auth and translation, and reuses ValidSessionID for the same rejection the // other chat calls apply. @@ -451,7 +452,7 @@ func (c *Chat) Permissions(ctx context.Context, id string) ([]protocol.ChatPermi if !sessionID.MatchString(id) { return nil, fmt.Errorf("invalid OpenCode session id") } - data, err := c.call(ctx, "get", "/api/permission/request", nil) + data, err := c.call(ctx, "get", "/api/session/"+id+"/permission", nil) if err != nil { return nil, err } @@ -874,6 +875,36 @@ type chatFormPayload struct { Fields []chatFormField `json:"fields"` } +// Forms recovers pending questions even when their creation event preceded the +// browser connection or the Pipelines process. Session ownership is explicit. +func (c *Chat) Forms(ctx context.Context, id string) ([]protocol.ChatForm, error) { + if !ValidSessionID(id) { + return nil, fmt.Errorf("invalid OpenCode session id") + } + data, err := c.call(ctx, "get", "/api/session/"+id+"/form", nil) + if err != nil { + return nil, err + } + forms, ok := chatEnvelope[chatFormPayload](data) + if !ok { + return nil, fmt.Errorf("invalid OpenCode form response") + } + result := make([]protocol.ChatForm, 0, len(forms)) + for _, form := range forms { + if form.ID == "" || form.SessionID != id { + continue + } + frame, valid, err := normalizeFormEvent("form.created", chatEvent{Form: &form}, id, nil) + if err != nil { + return nil, err + } + if valid { + result = append(result, *frame.Form) + } + } + return result, nil +} + type chatFormField struct { Key string `json:"key"` Title string `json:"title"` diff --git a/internal/opencode/chat_forms_readback_test.go b/internal/opencode/chat_forms_readback_test.go new file mode 100644 index 00000000..acb13777 --- /dev/null +++ b/internal/opencode/chat_forms_readback_test.go @@ -0,0 +1,24 @@ +package opencode + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" +) + +func TestChatFormsReadbackUsesSessionOwnership(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/session/ses_otherdir/form" { + t.Errorf("wrong session path: %s", r.URL.Path) + } + w.Header().Set("Content-Type", "application/json") + w.Write([]byte(`{"data":[{"id":"f_1","sessionID":"ses_otherdir","title":"Pending before connect","metadata":{"kind":"question"},"fields":[{"key":"answer","type":"text","required":true}]},{"id":"foreign","sessionID":"ses_foreign"}]}`)) + })) + defer srv.Close() + chat := NewChat(&Connection{Backend: "v2", URL: srv.URL, Directory: "/unrelated"}) + forms, err := chat.Forms(context.Background(), "ses_otherdir") + if err != nil || len(forms) != 1 || forms[0].ID != "f_1" || len(forms[0].Fields) != 1 || !forms[0].Fields[0].Required { + t.Fatalf("forms=%+v err=%v", forms, err) + } +} diff --git a/internal/opencode/chat_test.go b/internal/opencode/chat_test.go index 7bb7f261..21f9d098 100644 --- a/internal/opencode/chat_test.go +++ b/internal/opencode/chat_test.go @@ -182,13 +182,13 @@ func TestChatRejectsInvalidSessionWithoutCalling(t *testing.T) { } // TestChatPermissionsListsAndFilters loads a pending-request fixture in the -// verified V2 envelope (GET /api/permission/request) and asserts the adapter +// verified V2 session-owned envelope and asserts the adapter // returns the requested session's request with its fields intact, filters out a // foreign session's request, and reads the endpoint once. func TestChatPermissionsListsAndFilters(t *testing.T) { var reads atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if r.Method != http.MethodGet || r.URL.Path != "/api/permission/request" { + if r.Method != http.MethodGet || r.URL.Path != "/api/session/ses_1/permission" { t.Errorf("unexpected request %s %s", r.Method, r.URL.Path) return } diff --git a/internal/opencode/native.go b/internal/opencode/native.go index e5d7fa3a..44163f40 100644 --- a/internal/opencode/native.go +++ b/internal/opencode/native.go @@ -158,6 +158,9 @@ func (c *Connection) Call(ctx context.Context, method, path string, body any) ([ return nil, fmt.Errorf("unsupported native OpenCode operation") } id := parts[0] + if len(parts) == 2 && parts[1] == "permission" { + return nil, fmt.Errorf("permission listing: %w", ErrPermissionUnsupported) + } // The approval reply is V2-only in this translation (see the permission-list // gate above); the V2 path has four trailing segments. if len(parts) == 4 && parts[1] == "permission" && parts[3] == "reply" { diff --git a/internal/server/chat.go b/internal/server/chat.go index c18ffce7..b8d39718 100644 --- a/internal/server/chat.go +++ b/internal/server/chat.go @@ -76,6 +76,10 @@ type chatAnswerer interface { Answer(context.Context, protocol.ChatAnswerRequest) error } +type chatFormReader interface { + Forms(context.Context, string) ([]protocol.ChatForm, error) +} + type chatShellOutputReader interface { ShellOutput(ctx context.Context, query protocol.ChatShellOutputQuery) (protocol.ChatShellOutputPage, error) } diff --git a/internal/server/chat_browser_test.go b/internal/server/chat_browser_test.go index c3b01a06..155ee0b6 100644 --- a/internal/server/chat_browser_test.go +++ b/internal/server/chat_browser_test.go @@ -3,11 +3,13 @@ package server import ( "context" "fmt" + "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "strings" + "sync" "testing" "time" @@ -15,7 +17,53 @@ import ( "git.a-wan.net/alan/pipelines/internal/protocol" ) -type browserModelFixture struct{ *fakeChat } +type browserModelFixture struct { + *fakeChat + forms *browserForms +} + +type browserForms struct { + mu sync.Mutex + pending []protocol.ChatForm + answered int +} + +func (b browserModelFixture) Forms(context.Context, string) ([]protocol.ChatForm, error) { + b.forms.mu.Lock() + defer b.forms.mu.Unlock() + return append([]protocol.ChatForm(nil), b.forms.pending...), nil +} + +func (b browserModelFixture) Answer(_ context.Context, answer protocol.ChatAnswerRequest) error { + b.forms.mu.Lock() + defer b.forms.mu.Unlock() + if answer.Answers["answer"] != "Browser answer" { + return fmt.Errorf("unexpected answer") + } + for i, form := range b.forms.pending { + if form.ID == answer.FormID { + b.forms.pending = append(b.forms.pending[:i], b.forms.pending[i+1:]...) + b.forms.answered++ + return nil + } + } + return fmt.Errorf("unknown form") +} + +func (b browserModelFixture) Reply(ctx context.Context, answer protocol.ChatReplyRequest) error { + if err := b.fakeChat.Reply(ctx, answer); err != nil { + return err + } + b.fakeChat.mu.Lock() + defer b.fakeChat.mu.Unlock() + for i, p := range b.fakeChat.permissions { + if p.RequestID == answer.RequestID { + b.fakeChat.permissions = append(b.fakeChat.permissions[:i], b.fakeChat.permissions[i+1:]...) + break + } + } + return nil +} func (b browserModelFixture) Models(ctx context.Context, id string) ([]protocol.ChatModel, error) { select { @@ -57,9 +105,27 @@ func TestChatBrowserLifecycleAndModelDialog(t *testing.T) { {ID: "msg_user", Role: protocol.ChatRoleUser, Parts: []protocol.ChatPart{{Type: "text", Text: strings.Repeat("Earlier scratch prompt line\n", 100)}}}, {ID: "msg_answer", Role: protocol.ChatRoleAssistant, Parts: []protocol.ChatPart{{Type: "reasoning", Text: "Controlled reasoning evidence"}, {Type: "text", Text: "Controlled answer"}}}, } - handler := HandlerWithOptions(ctx, Options{Chat: browserModelFixture{fake}}, store) + forms := &browserForms{} + handler := HandlerWithOptions(ctx, Options{Chat: browserModelFixture{fake, forms}}, store) defer func() { cancel(); WaitRuns(handler) }() - srv := httptest.NewServer(handler) + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { + if req.URL.Path == "/fixture-attention" && req.Method == http.MethodPost { + fake.mu.Lock() + fake.permissions = []protocol.ChatPermissionFrame{ + {SessionID: session.ID, RequestID: "per_first", Action: "shell", Resources: []string{"Controlled first command"}}, + {SessionID: session.ID, RequestID: "per_second", Action: "edit", Resources: []string{"Controlled second path"}}, + } + fake.mu.Unlock() + forms.mu.Lock() + for _, id := range []string{"form_first", "form_second"} { + forms.pending = append(forms.pending, protocol.ChatForm{ID: id, SessionID: session.ID, Title: "Recovered question", Fields: []protocol.ChatFormField{{Key: "answer", Type: "text", Title: "Your answer", Required: true}}}) + } + forms.mu.Unlock() + w.WriteHeader(http.StatusNoContent) + return + } + handler.ServeHTTP(w, req) + })) defer srv.Close() cmd := exec.CommandContext(ctx, "node", "../../web/test/chat-hardening-probe.mjs", strings.TrimPrefix(srv.URL, "http://"), session.ID) if output, err := cmd.CombinedOutput(); err != nil { @@ -67,4 +133,13 @@ func TestChatBrowserLifecycleAndModelDialog(t *testing.T) { } else { t.Log(string(output)) } + fake.mu.Lock() + replies := fake.replies + fake.mu.Unlock() + forms.mu.Lock() + answers := forms.answered + forms.mu.Unlock() + if replies != 2 || answers != 2 { + t.Fatalf("browser did not deliver all interactions: approvals=%d answers=%d", replies, answers) + } } diff --git a/internal/server/chat_manager.go b/internal/server/chat_manager.go index 5346be0d..135460ae 100644 --- a/internal/server/chat_manager.go +++ b/internal/server/chat_manager.go @@ -172,6 +172,19 @@ func (m *chatManager) PromptWithMessageIDFiles(ctx context.Context, sessionID, t } var errChatAttachmentsUnsupported = errors.New("this chat harness does not support attachments") +var errChatFormReadbackUnsupported = errors.New("this chat harness does not support pending question readback") + +func (m *chatManager) Forms(ctx context.Context, sessionID string) ([]protocol.ChatForm, error) { + adapter, err := m.brokerFor(ctx, sessionID) + if err != nil { + return nil, err + } + if reader, ok := adapter.(chatFormReader); ok { + return reader.Forms(ctx, sessionID) + } + return nil, errChatFormReadbackUnsupported +} + var errChatInstructionsUnsupported = errors.New("this chat harness does not support session instructions") func (m *chatManager) CheckAttachments(ctx context.Context, sessionID string) error { diff --git a/internal/server/chat_room.go b/internal/server/chat_room.go index 5929c4cb..7f0d634a 100644 --- a/internal/server/chat_room.go +++ b/internal/server/chat_room.go @@ -5,6 +5,8 @@ import ( "errors" "fmt" "log" + "reflect" + "slices" "strings" "sync" "time" @@ -595,25 +597,27 @@ func (h *chatHub) pushPermission(sessionID string, frame protocol.ChatPermission if frame.RequestID == "" || frame.Resolved { return } - if !h.seenPermission(sessionID, frame.RequestID) { - return - } h.mu.Lock() + // Deduplicate the active room, not the lifetime turn cache: the last + // subscriber leaving destroys the room, and a reconnect must replay pending + // approvals from the harness even if an earlier room already saw them. + if turn := h.turns[sessionID]; turn != nil { + if resolution := turn.resolutions[frame.RequestID]; resolution != nil { + h.mu.Unlock() + return + } + } var targets []*chatSub if room := h.rooms[sessionID]; room != nil { - known := false for i := range room.pending { if room.pending[i].RequestID == frame.RequestID { - room.pending[i] = frame - known = true - break + h.mu.Unlock() + return } } - if !known { - room.pending = append(room.pending, frame) - if len(room.pending) > chatRoomPendingLimit { - room.pending = room.pending[len(room.pending)-chatRoomPendingLimit:] - } + room.pending = append(room.pending, frame) + if len(room.pending) > chatRoomPendingLimit { + room.pending = room.pending[len(room.pending)-chatRoomPendingLimit:] } for _, sub := range room.subs { targets = append(targets, sub) @@ -719,13 +723,7 @@ func (h *chatHub) runTurn(room *chatRoom, p *chatQueuedPrompt, done chan struct{ h.flushBuffered(room.sessionID) // Start the approval poller once, after the first ack, so a pending request // is surfaced after the prompt is acknowledged and shared with every client. - h.mu.Lock() - startPoller := !room.pollerStarted - room.pollerStarted = true - h.mu.Unlock() - if startPoller { - go h.pollRoom(room, broker) - } + h.startRoomPoller(room, broker) select { case <-done: case <-room.ctx.Done(): @@ -819,6 +817,16 @@ func (h *chatHub) drainStream(room *chatRoom, result <-chan error) { // pollRoom polls the broker's pending-approval list for the room on a fixed // interval and pushes each newly seen request to every attached client. The // first poll runs immediately; the loop stops with the room's context. +func (h *chatHub) startRoomPoller(room *chatRoom, broker chatBroker) { + h.mu.Lock() + start := !room.pollerStarted && room.ctx.Err() == nil + room.pollerStarted = true + h.mu.Unlock() + if start { + go h.pollRoom(room, broker) + } +} + func (h *chatHub) pollRoom(room *chatRoom, broker chatBroker) { ticker := time.NewTicker(chatPermissionPollInterval) defer ticker.Stop() @@ -850,6 +858,7 @@ func (h *chatHub) pollRoom(room *chatRoom, broker chatBroker) { // pollPermissionsOnce performs one poll and pushes each newly seen request of the // session to every client watching it. func (h *chatHub) pollPermissionsOnce(ctx context.Context, broker chatBroker, sessionID string) error { + beforePermissions := h.pendingFrames(sessionID) pending, err := broker.Permissions(ctx, sessionID) if err != nil { return err @@ -860,6 +869,70 @@ func (h *chatHub) pollPermissionsOnce(ctx context.Context, broker chatBroker, se } h.pushPermission(sessionID, request) } + for _, old := range beforePermissions { + found := false + for _, request := range pending { + if request.SessionID == sessionID && request.RequestID == old.RequestID { + found = true + break + } + } + if !found { + h.confirmPermission(sessionID, old.RequestID, "the harness", "") + } + } + if reader, ok := broker.(chatFormReader); ok { + h.mu.Lock() + room := h.rooms[sessionID] + var before []protocol.ChatForm + if room != nil { + before = slices.Clone(room.forms) + } + h.mu.Unlock() + forms, err := reader.Forms(ctx, sessionID) + if errors.Is(err, errChatFormReadbackUnsupported) { + return nil + } + if err != nil { + return fmt.Errorf("question readback: %w", err) + } + // Do not overwrite a live event that raced this readback. The next poll + // retries from an authoritative snapshot instead. + h.mu.Lock() + current := h.rooms[sessionID] + unchanged := current == room && room != nil && reflect.DeepEqual(before, room.forms) + h.mu.Unlock() + if unchanged { + for _, form := range forms { + if form.SessionID != sessionID || form.ID == "" { + continue + } + found := false + for _, old := range before { + if reflect.DeepEqual(old, form) { + found = true + break + } + } + if !found { + h.emitRoom(room, protocol.ChatEventFrame{SessionID: sessionID, Kind: protocol.ChatEventForm, Form: &form}) + } + } + for _, old := range before { + found := false + for _, form := range forms { + if form.ID == old.ID && form.SessionID == sessionID { + found = true + break + } + } + if !found { + old.Resolved = true + h.emitRoom(room, protocol.ChatEventFrame{SessionID: sessionID, Kind: protocol.ChatEventForm, Form: &old}) + } + } + } + } return nil } diff --git a/internal/server/chat_stream.go b/internal/server/chat_stream.go index db53c37b..3993180d 100644 --- a/internal/server/chat_stream.go +++ b/internal/server/chat_stream.go @@ -206,6 +206,9 @@ func handleChatSubscribe(request protocol.Message, broker chatBroker, hub *chatH _ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "could not observe session " + query.SessionID}) return } + // Observe requests from CLI-originated turns and recover after reload; do + // not require the browser to send another prompt just to start polling. + hub.startRoomPoller(sub.room, broker) // A turn already in flight when this client attaches has no `step started` // frame in its future, so replay the live marker. The composer's Stop control // and the transcript's one activity row read it; the later `step ended` frame diff --git a/internal/server/chat_test.go b/internal/server/chat_test.go index ab85477a..0b5884ba 100644 --- a/internal/server/chat_test.go +++ b/internal/server/chat_test.go @@ -851,7 +851,7 @@ func TestChatInterruptEndsRunningPrompt(t *testing.T) { mu.Unlock() w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`)) - case r.Method == http.MethodGet && r.URL.Path == "/api/permission/request": + case r.Method == http.MethodGet && (r.URL.Path == "/api/session/ses_1/permission" || r.URL.Path == "/api/session/ses_1/form"): w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[]}`)) case r.Method == http.MethodGet && r.URL.Path == "/api/shell": @@ -1384,7 +1384,7 @@ func realAdapterChat(t *testing.T, frames []string) []protocol.ChatEventFrame { prompts.Add(1) w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"data":{"id":"msg_1","sessionID":"ses_1","type":"user"}}`)) - case r.Method == http.MethodGet && r.URL.Path == "/api/permission/request": + case r.Method == http.MethodGet && (r.URL.Path == "/api/session/ses_1/permission" || r.URL.Path == "/api/session/ses_1/form"): w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"location":{"directory":"/work"},"data":[]}`)) case r.Method == http.MethodGet && r.URL.Path == "/api/shell": diff --git a/web/PARITY.md b/web/PARITY.md index 79e679f3..ac226e1e 100644 --- a/web/PARITY.md +++ b/web/PARITY.md @@ -183,6 +183,28 @@ history, so that row stays as closed history (there is no delete command). The page keeps its own ephemeral throwaway row in memory so the check can switch back to it, but the server never lists it and a reload drops it. +## Web interaction recovery (2026-10-20) + +- C10 approvals are read from the **session-owned** OpenCode endpoint, including + turns started in another client/directory. Merely subscribing starts polling; + no web prompt is needed. Room recreation no longer suppresses an already-seen + pending approval. Requests answered in the harness clear on readback. +- C10/B6 retain multiple approvals and questions independently, recover questions + from the session form list after reconnect/server restart, and keep typed + question answers across unrelated streaming paints. Long approval resources + can be expanded before deciding. No permission policy is bypassed. +- Scratch Chrome regression captures `mobile-pending-interactions.png` at 390px: + two broker-originated approvals and two questions survive a reload; both + decisions and both answers reach the server. This is not a claim about every + backend: Codex request recovery remains limited to its live App Server socket. + +Runs layout follow-up: run task titles wrap without ellipsis (including long +unbroken tokens); all applied pipeline/status/time filters have their own +clearable, wrapping row beneath Filter/Sort. Browser measurements at 390/420px +confirm no horizontal overflow and full-width run rows; the selected row also +fills its scroll pane at 1100px. Captures: `wrapped-run-title-390.png`, +`wrapped-run-title-420.png`, `full-width-selected-run.png`. + ## Settings, layout, platform | # | Feature | Protocol | Status | | --- | --- | --- | --- | diff --git a/web/src/chat.js b/web/src/chat.js index 6a059515..0c4eb4b3 100644 --- a/web/src/chat.js +++ b/web/src/chat.js @@ -1576,18 +1576,21 @@ export function applyChatForm(thread, form) { const id = str(form?.id); if (id === "") return current; const existing = current.form ?? null; + const forms = [...(current.forms ?? (existing ? [existing] : []))].filter((entry) => entry.id !== id); + if (form?.resolved !== true && form?.cancelled !== true) forms.push(form); + const next = { ...current, forms }; if (form?.cancelled === true) { - if (str(existing?.id) !== id) return current; - return { ...current, form: null }; + if (str(existing?.id) !== id) return next; + return { ...next, form: forms.at(-1) ?? null }; } if (form?.resolved === true) { - if (str(existing?.id) !== id) return current; - return { ...current, form: { ...existing, ...form, resolved: true } }; + if (str(existing?.id) !== id) return next; + return { ...next, form: forms.at(-1) ?? { ...existing, ...form, resolved: true } }; } if (str(existing?.id) === id) { - return { ...current, form: { ...existing, ...form } }; + return { ...next, form: { ...existing, ...form } }; } - return { ...current, form }; + return { ...next, form }; } /** @@ -2324,9 +2327,25 @@ export function applyChatPermission(thread, frame) { const current = thread ?? newChatThread(str(frame?.session_id)); const requestId = str(frame?.request_id); const sameRequest = requestId !== "" && str(current.permission?.request_id) === requestId; + const permissions = [...(current.permissions ?? (current.permission ? [current.permission] : []))] + .filter((entry) => str(entry?.request_id) !== requestId && entry?.resolved !== true); + if (requestId && frame?.resolved !== true) permissions.push(frame); return { ...current, + permissions, permission: frame ?? null, permissionAnswer: sameRequest ? str(current.permissionAnswer) : "", }; } + +export function chatApprovalCards(thread) { + return (thread?.permissions ?? (thread?.permission ? [thread.permission] : [])) + .map((frame) => approvalCard(frame, thread?.permissionAnswers?.[frame.request_id] ?? + (frame.request_id === thread?.permission?.request_id ? thread.permissionAnswer : ""))) + .filter(Boolean); +} + +export function chatPendingForms(thread) { + return (thread?.forms ?? (thread?.form ? [thread.form] : [])) + .filter((form) => form?.resolved !== true && form?.cancelled !== true); +} diff --git a/web/src/views/chat.js b/web/src/views/chat.js index f52520a6..a19ea3a7 100644 --- a/web/src/views/chat.js +++ b/web/src/views/chat.js @@ -79,6 +79,9 @@ import { applyChatEvent, applyChatOverrides, applyChatPermission, + applyChatForm, + chatApprovalCards, + chatPendingForms, abbreviateHome, appendChatNotice, approvalCard, @@ -738,7 +741,12 @@ function refreshChatTranscript(sessionId) { if (rows.length === 0 && notices.length === 0 && !thread.running && !approval && !form) { return false; } - const running = thread.running === true && approval?.actionable !== true; + const awaiting = chatApprovalCards(thread).some((card) => card.actionable) || chatPendingForms(thread).length > 0; + const running = thread.running === true && !awaiting; + const bar = document.querySelector(".chat-bar"); + const jump = bar?.querySelector(".chat-approval-jump"); + if (awaiting && bar && !jump) bar.append(approvalJumpButton()); + else if (!awaiting) jump?.remove(); captureChatPosition(); // The background-tasks bar sits outside the transcript but is driven by the // same shell frames. Patch it in place instead of full-rendering the pane (and @@ -841,7 +849,8 @@ function onChatPermission(frame) { next.permissionError = ""; } state.chatThreads.set(sessionId, next); - if (state.view === "chat" && sessionId === state.chatActiveId) scheduleChatRender(); + markBackgroundChatUnseen(sessionId); + if (state.view === "chat" && sessionId === state.chatActiveId) scheduleChatRender("transcript"); } /** @@ -854,9 +863,9 @@ function onChatPermission(frame) { */ async function answerPermission(sessionId, requestId, decision) { const thread = state.chatThreads.get(sessionId); - const permission = thread?.permission; - if (!thread || String(permission?.request_id ?? "") !== requestId) return; - setThread(sessionId, { permissionAnswer: decision }); + const permission = (thread?.permissions ?? [thread?.permission]).find((entry) => entry?.request_id === requestId); + if (!thread || !permission) return; + setThread(sessionId, { permissionAnswers: { ...thread.permissionAnswers, [requestId]: decision } }); renderContent(); try { await repo.chatReply(sessionId, requestId, decision); @@ -870,9 +879,9 @@ async function answerPermission(sessionId, requestId, decision) { } } catch (error) { const current = state.chatThreads.get(sessionId); - if (!current || String(current.permission?.request_id ?? "") !== requestId) return; + if (!current || !(current.permissions ?? [current.permission]).some((entry) => entry?.request_id === requestId)) return; const reason = describeError(error); - setThread(sessionId, { permissionAnswer: "", error: reason, permissionError: reason }); + setThread(sessionId, { permissionAnswers: { ...current.permissionAnswers, [requestId]: "" }, error: reason, permissionError: reason }); renderContent(); } } @@ -887,9 +896,7 @@ async function answerChatQuestion(sessionId, form, answers) { try { await repo.answerChatForm(sessionId, form.id, answers); const current = state.chatThreads.get(sessionId); - if (current?.form && current.form.id === form.id) { - setThread(sessionId, { form: { ...current.form, resolved: true } }); - } + if (current) state.chatThreads.set(sessionId, applyChatForm(current, { ...form, resolved: true })); renderContent(); } catch (error) { state.actionError = describeError(error); @@ -1017,7 +1024,10 @@ async function loadChatHistory(id) { // The merged page replaces only the history fields; spreading it over the // held thread keeps the composer's draft, attachments and flags intact (a // draft typed while the page was loading is not lost). - setThread(id, mergeHistoryPage(previous, page, { older: false })); + // Live approvals/questions can arrive before this HTTP read finishes. Merge + // over the current thread, never the pre-request snapshot that would erase + // the just-delivered interaction (and any draft typed during the read). + setThread(id, mergeHistoryPage(state.chatThreads.get(id) ?? previous, page, { older: false })); } catch (error) { setThread(id, { loading: false, loaded: true, error: describeError(error) }); } @@ -2449,7 +2459,7 @@ function renderChatConversation() { thread?.form && thread.form.resolved !== true && thread.form.cancelled !== true ? thread.form : null; - const awaiting = approval?.actionable === true || form != null; + const awaiting = chatApprovalCards(thread).some((card) => card.actionable) || chatPendingForms(thread).length > 0; const bar = h("div", { class: "chat-bar" }); const lead = h("div", { class: "chat-bar-lead" }); @@ -3007,8 +3017,19 @@ function renderChatTranscript( // The approval card is the transcript's last item (C10) — after the notices and // after the running indicator when it is shown — so the pane's jump control // and a fresh card both land at the end. - if (approval) transcript.append(renderChatApproval(sessionId, approval)); - if (form) transcript.append(renderChatQuestion(sessionId, form)); + const approvals = chatApprovalCards(thread); + const forms = chatPendingForms(thread); + if (!approvals.length && approval) approvals.push(approval); + approvals.forEach((card, index) => { + const node = renderChatApproval(sessionId, card); + if (index === 0) node.id = "chatApproval"; + transcript.append(node); + }); + forms.forEach((pending, index) => { + const node = renderChatQuestion(sessionId, pending); + if (index === 0) node.id = "chatQuestion"; + transcript.append(node); + }); wrap.append(transcript); wrap.append( h("button", { @@ -3057,7 +3078,7 @@ function approvalJumpButton() { function renderChatApproval(sessionId, card) { const node = h("div", { class: `chat-approval${card.actionable ? " chat-approval-pending" : ""}`, - id: "chatApproval", + id: `chatApproval-${card.requestId}`, "data-request-id": card.requestId, }); const head = h("div", { class: "chat-approval-head" }); @@ -3073,6 +3094,12 @@ function renderChatApproval(sessionId, card) { const box = h("div", { class: "chat-approval-resources" }); box.append(h("pre", { class: "chat-approval-resources-text", text: card.resourceText })); node.append(box); + const full = card.resources.join("\n"); + if (full !== card.resourceText) { + node.append(h("details", { class: "chat-approval-details" }, + h("summary", { text: "Show full request" }), + h("pre", { text: full, style: "white-space: pre-wrap; overflow-wrap: anywhere;" }))); + } } if (card.showRisk && card.risk.trim() !== "") { const risk = h("div", { class: "chat-approval-risk" }); @@ -3102,7 +3129,7 @@ function renderChatApproval(sessionId, card) { function renderChatQuestion(sessionId, form) { const node = h("div", { class: "chat-question", - id: "chatQuestion", + id: `chatQuestion-${form.id}`, "data-form-id": form.id, }); const head = h("div", { class: "chat-question-head" }); @@ -3112,7 +3139,10 @@ function renderChatQuestion(sessionId, form) { ); node.append(head); - const answers = {}; + // Keep entered answers across unrelated streaming frames and reconnect paints. + const thread = state.chatThreads.get(sessionId); + if (thread && !thread.formAnswers) thread.formAnswers = {}; + const answers = thread ? (thread.formAnswers[form.id] ??= {}) : {}; const parts = []; for (const field of form.fields ?? []) { const key = String(field.key ?? ""); @@ -3168,6 +3198,7 @@ function renderChatQuestion(sessionId, form) { buttons.push(button); rows.append(button); } + paint(); part.append(rows); } if (field.custom === true || options.length === 0) { @@ -3176,6 +3207,7 @@ function renderChatQuestion(sessionId, form) { type: "text", placeholder: options.length ? "Type another answer" : "Your answer", autocomplete: "off", + value: typeof answers[key] === "string" ? answers[key] : "", }); input.addEventListener("input", () => { const value = input.value.trim(); @@ -4186,7 +4218,7 @@ function updateChatJump(el) { function refreshChatClock() { chatNow = Date.now(); const thread = state.chatActiveId ? state.chatThreads.get(state.chatActiveId) : null; - const awaiting = approvalCard(thread?.permission, thread?.permissionAnswer)?.actionable === true; + const awaiting = chatApprovalCards(thread).some((card) => card.actionable) || chatPendingForms(thread).length > 0; if (state.view !== "chat" || !thread?.running || awaiting) { stopChatClock(); return; diff --git a/web/test/chat-hardening-probe.mjs b/web/test/chat-hardening-probe.mjs index 66fb47ab..e40a0790 100644 --- a/web/test/chat-hardening-probe.mjs +++ b/web/test/chat-hardening-probe.mjs @@ -107,8 +107,34 @@ try { await page.fill("#chatInput", "New message must scroll into view"); await page.click("#chatSend"); await eventually(() => page.evaluate("(() => { const t=document.querySelector('#chatTranscript'); return t.textContent.includes('New message must scroll into view') && t.scrollHeight-t.scrollTop-t.clientHeight<3; })()")); + // These requests originate at the broker snapshot, not an injected browser + // frame. A reload must recover all of them, and each control reaches Go. + assert.equal((await fetch(`http://${target}/fixture-attention`,{method:'POST'})).status,204); + await eventually(() => page.evaluate("document.querySelectorAll('.chat-approval-pending').length===2 && document.querySelectorAll('.chat-question').length===2")); + await page.goto(`http://127.0.0.1:${port}/chat/${sessionId}`); + try { + await eventually(() => page.evaluate("document.querySelectorAll('.chat-approval-pending').length===2 && document.querySelectorAll('.chat-question').length===2")); + } catch(error) { + console.log(await page.evaluate("({approvals:document.querySelectorAll('.chat-approval-pending').length,questions:document.querySelectorAll('.chat-question').length,errors:window.__errors,text:document.body.innerText.slice(-2000)})")); + throw error; + } + assert.equal(await page.evaluate("!!document.querySelector('.chat-approval-jump')"),true); + await page.click('.chat-approval-jump'); + if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,'mobile-pending-interactions.png')); + await page.evaluate("document.querySelector('[data-request-id=per_first] .chat-approval-control').click()"); + await eventually(() => page.evaluate("document.querySelectorAll('.chat-approval-pending').length===1")); + await page.evaluate("document.querySelector('[data-request-id=per_second] .chat-approval-control:last-child').click()"); + await eventually(() => page.evaluate("document.querySelectorAll('.chat-approval-pending').length===0")); + for(const id of ['form_first','form_second']) { + await page.fill(`[data-form-id=${id}] .chat-question-input`,'Browser answer'); + await emit({message_id:'msg_answer',kind:'text',part:{id:'draft-check',type:'text',text:'unrelated frame'}}); + await eventually(() => page.evaluate(`document.querySelector('[data-form-id=${id}] .chat-question-input')?.value==='Browser answer'`)); + await page.evaluate(`document.querySelector('[data-form-id=${id}] .chat-question-submit').click()`); + await eventually(() => page.evaluate(`!document.querySelector('[data-form-id=${id}]')`)); + } + await eventually(() => page.evaluate("!document.querySelector('.chat-approval-jump')")); assert.deepEqual(await page.evaluate("window.__errors"), []); - console.log("Model dialog, stable activity mark, keyboard/caret, Back restoration and send-to-bottom passed."); + console.log("Model dialog, stable activity mark, keyboard/caret, Back restoration, send-to-bottom and all recovered approvals/questions passed."); } finally { await browser?.close(); serve.kill("SIGTERM"); diff --git a/web/test/chatInteractions.test.mjs b/web/test/chatInteractions.test.mjs new file mode 100644 index 00000000..68a8d37d --- /dev/null +++ b/web/test/chatInteractions.test.mjs @@ -0,0 +1,23 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { applyChatForm, applyChatPermission, chatApprovalCards, chatPendingForms } from '../src/chat.js'; + +test('parallel approvals stay independently actionable and resolve by identity',()=>{ + let thread={}; + for(const id of ['a','b']) thread=applyChatPermission(thread,{session_id:'s',request_id:id,action:'shell'}); + assert.deepEqual(chatApprovalCards(thread).map(c=>c.requestId),['a','b']); + thread=applyChatPermission(thread,{session_id:'s',request_id:'a',resolved:true}); + assert.deepEqual(chatApprovalCards(thread).map(c=>c.requestId),['b']); + thread=applyChatPermission(thread,{session_id:'s',request_id:'b',resolved:true}); + assert.deepEqual(chatApprovalCards(thread),[]); +}); + +test('parallel questions survive replies and cancellation of a different question',()=>{ + let thread={}; + for(const id of ['a','b']) thread=applyChatForm(thread,{id,session_id:'s',fields:[]}); + assert.deepEqual(chatPendingForms(thread).map(f=>f.id),['a','b']); + thread=applyChatForm(thread,{id:'a',resolved:true}); + assert.deepEqual(chatPendingForms(thread).map(f=>f.id),['b']); + thread=applyChatForm(thread,{id:'b',cancelled:true}); + assert.deepEqual(chatPendingForms(thread),[]); +});