feat(chat): broker Codex approvals and complete typed tool interactions
This commit is contained in:
+17
-4
@@ -15,7 +15,20 @@ chat issues `thread/start`; a prompt issues `turn/start`; history comes from
|
||||
question card and `chat_answer` returns the JSON-RPC response. Threads created
|
||||
this way are ordinary Codex threads and remain visible to the Codex app.
|
||||
|
||||
The adapter creates threads with `approvalPolicy: never` and
|
||||
`sandbox: workspace-write`; Codex approvals are not brokered through the chat
|
||||
permission card yet. Claude is not advertised as a backend until its sidecar and
|
||||
login flow are wired.
|
||||
New threads retain the `workspace-write` sandbox and inherit Codex's configured
|
||||
approval policy (Pipelines no longer forces `never`). Command, file-change,
|
||||
network and explicit permission requests appear in the web approval cards. Each
|
||||
JSON-RPC callback has its own identity, including Code Mode subcommands sharing
|
||||
one item. Allow once maps to `accept`, session grants to `acceptForSession`, and
|
||||
Reject to `decline`; explicit permission profiles grant only requested fields.
|
||||
The web labels session scope explicitly, never as a permanent policy change.
|
||||
|
||||
Pending questions and approvals survive browser reconnects while the App Server
|
||||
connection lives. Standard MCP form/URL elicitation supports typed answers,
|
||||
Accept/Decline/Cancel and safe external links. Extended OpenAI elicitation is not
|
||||
advertised; unknown request formats return an explicit unsupported RPC error,
|
||||
not a fake empty success or silent auto-approval. App Server socket loss does
|
||||
not provide durable callback recovery; a disconnected transport is reported as
|
||||
an error rather than claiming old requests are still actionable.
|
||||
|
||||
Claude is not advertised as a backend until its sidecar and login flow are wired.
|
||||
|
||||
@@ -322,6 +322,15 @@ transient client logs are presentation, not separate server capabilities.
|
||||
|
||||
## Chat sessions
|
||||
|
||||
Structured tools use `chat_answer` with
|
||||
`chat_answer: {session_id, form_id, answers, action?}`. Optional `action` is
|
||||
`accept`, `decline` or `cancel` only when advertised by the pending form's
|
||||
`actions`; ordinary question replies can omit it. Answers retain JSON types.
|
||||
OpenCode cancellation calls the existing form DELETE API. Codex MCP elicitation
|
||||
returns the corresponding action/content; other Codex questions accept answers
|
||||
only. Permission frames may provide `always_label: "Allow for session"` to avoid
|
||||
misrepresenting a session-scoped grant as a permanent policy change.
|
||||
|
||||
The brokered OpenCode chat exposes the operator's own sessions, separate from the
|
||||
sessions pipeline runs create. The protocol types are:
|
||||
|
||||
|
||||
@@ -16,3 +16,17 @@ 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.
|
||||
|
||||
## Typed interaction controls
|
||||
|
||||
Web form fields now preserve booleans and numbers (`false`/`0` are answers),
|
||||
integer/range and length constraints, defaults, conditional visibility,
|
||||
multiselect/custom values, masked secret inputs and HTTP(S)-only external links.
|
||||
Hidden conditional answers are omitted. OpenCode forms offer cancellation through
|
||||
their documented DELETE endpoint, without answering or rerunning the tool.
|
||||
|
||||
Codex command/file/network/permission approvals and standard MCP elicitation are
|
||||
brokered over their original JSON-RPC callbacks. Session grants are labelled as
|
||||
such. Responses are acknowledged only after the transport write succeeds;
|
||||
foreign-session answers are refused. Schemas were checked against generated
|
||||
protocol source tagged `rust-v0.163.0`, matching the installed package manifest.
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"sort"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
)
|
||||
|
||||
type pendingApproval struct {
|
||||
requestID json.RawMessage
|
||||
method string
|
||||
frame protocol.ChatPermissionFrame
|
||||
permissions map[string]any
|
||||
answering bool
|
||||
}
|
||||
|
||||
func (c *Chat) respondResult(ctx context.Context, id json.RawMessage, result any) error {
|
||||
data, err := json.Marshal(map[string]any{"id": id, "result": result})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.writeMu.Lock()
|
||||
defer c.writeMu.Unlock()
|
||||
return c.conn.Write(ctx, websocket.MessageText, data)
|
||||
}
|
||||
|
||||
func (c *Chat) respondUnsupported(id json.RawMessage) {
|
||||
data, _ := json.Marshal(map[string]any{"id": id, "error": map[string]any{"code": -32601, "message": "This client does not support this interaction"}})
|
||||
c.writeMu.Lock()
|
||||
defer c.writeMu.Unlock()
|
||||
_ = c.conn.Write(c.ctx, websocket.MessageText, data)
|
||||
}
|
||||
|
||||
// receiveApproval retains the exact callback identity. itemId is not unique:
|
||||
// Code Mode can have multiple subcommand approvals beneath the same item.
|
||||
func (c *Chat) receiveApproval(msg rpcMessage) {
|
||||
var p struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
ItemID string `json:"itemId"`
|
||||
Command string `json:"command"`
|
||||
Cwd string `json:"cwd"`
|
||||
Reason string `json:"reason"`
|
||||
GrantRoot string `json:"grantRoot"`
|
||||
Permissions map[string]any `json:"permissions"`
|
||||
Network *struct {
|
||||
Host string `json:"host"`
|
||||
Protocol string `json:"protocol"`
|
||||
} `json:"networkApprovalContext"`
|
||||
}
|
||||
if json.Unmarshal(msg.Params, &p) != nil || p.ThreadID == "" || p.ItemID == "" {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
id := "codex_" + base64.RawURLEncoding.EncodeToString(msg.ID)
|
||||
frame := protocol.ChatPermissionFrame{SessionID: p.ThreadID, RequestID: id, Action: "command execution", Message: p.Reason, AlwaysLabel: "Allow for session"}
|
||||
if p.Command != "" {
|
||||
frame.Resources = append(frame.Resources, p.Command)
|
||||
}
|
||||
if p.Cwd != "" {
|
||||
frame.Resources = append(frame.Resources, "Directory: "+p.Cwd)
|
||||
}
|
||||
if msg.Method == "item/fileChange/requestApproval" {
|
||||
frame.Action = "file changes"
|
||||
if p.GrantRoot != "" {
|
||||
frame.Resources = append(frame.Resources, p.GrantRoot)
|
||||
}
|
||||
}
|
||||
if p.Network != nil {
|
||||
frame.Action = "network access"
|
||||
frame.Resources = append(frame.Resources, p.Network.Protocol+"://"+p.Network.Host)
|
||||
}
|
||||
if msg.Method == "item/permissions/requestApproval" {
|
||||
frame.Action = "additional permissions"
|
||||
if p.Permissions == nil {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
raw, _ := json.MarshalIndent(p.Permissions, "", " ")
|
||||
frame.Resources = append(frame.Resources, string(raw))
|
||||
}
|
||||
c.mu.Lock()
|
||||
if c.approvals == nil {
|
||||
c.approvals = map[string]pendingApproval{}
|
||||
}
|
||||
c.approvals[id] = pendingApproval{requestID: msg.ID, method: msg.Method, frame: frame, permissions: p.Permissions}
|
||||
c.mu.Unlock()
|
||||
}
|
||||
|
||||
func (c *Chat) Permissions(_ context.Context, id string) ([]protocol.ChatPermissionFrame, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.connectionErr != nil {
|
||||
return nil, c.connectionErr
|
||||
}
|
||||
frames := []protocol.ChatPermissionFrame{}
|
||||
for _, p := range c.approvals {
|
||||
if p.frame.SessionID == id {
|
||||
frames = append(frames, p.frame)
|
||||
}
|
||||
}
|
||||
sort.Slice(frames, func(i, j int) bool { return frames[i].RequestID < frames[j].RequestID })
|
||||
return frames, nil
|
||||
}
|
||||
|
||||
func (c *Chat) Forms(_ context.Context, id string) ([]protocol.ChatForm, error) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
if c.connectionErr != nil {
|
||||
return nil, c.connectionErr
|
||||
}
|
||||
forms := []protocol.ChatForm{}
|
||||
for _, p := range c.forms {
|
||||
if p.threadID == id {
|
||||
forms = append(forms, p.form)
|
||||
}
|
||||
}
|
||||
sort.Slice(forms, func(i, j int) bool { return forms[i].ID < forms[j].ID })
|
||||
return forms, nil
|
||||
}
|
||||
|
||||
func (c *Chat) resolveInteraction(thread string, id json.RawMessage) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
for key, p := range c.approvals {
|
||||
if p.frame.SessionID == thread && string(p.requestID) == string(id) {
|
||||
delete(c.approvals, key)
|
||||
}
|
||||
}
|
||||
for key, p := range c.forms {
|
||||
if p.threadID == thread && string(p.requestID) == string(id) {
|
||||
delete(c.forms, key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) Reply(ctx context.Context, request protocol.ChatReplyRequest) error {
|
||||
c.mu.Lock()
|
||||
p, ok := c.approvals[request.RequestID]
|
||||
if !ok || p.frame.SessionID != request.SessionID || p.answering {
|
||||
c.mu.Unlock()
|
||||
return errors.New("the Codex approval is no longer awaiting an answer")
|
||||
}
|
||||
var result any
|
||||
if p.method == "item/permissions/requestApproval" {
|
||||
granted := map[string]any{}
|
||||
scope := "turn"
|
||||
switch request.Decision {
|
||||
case protocol.ChatDecisionAlways:
|
||||
scope = "session"
|
||||
fallthrough
|
||||
case protocol.ChatDecisionOnce:
|
||||
for key, value := range p.permissions {
|
||||
if (key == "network" || key == "fileSystem") && value != nil {
|
||||
granted[key] = value
|
||||
}
|
||||
}
|
||||
case protocol.ChatDecisionReject:
|
||||
default:
|
||||
c.mu.Unlock()
|
||||
return errors.New("invalid approval decision")
|
||||
}
|
||||
result = map[string]any{"permissions": granted, "scope": scope}
|
||||
} else {
|
||||
decision := ""
|
||||
switch request.Decision {
|
||||
case protocol.ChatDecisionOnce:
|
||||
decision = "accept"
|
||||
case protocol.ChatDecisionAlways:
|
||||
decision = "acceptForSession"
|
||||
case protocol.ChatDecisionReject:
|
||||
decision = "decline"
|
||||
default:
|
||||
c.mu.Unlock()
|
||||
return errors.New("invalid approval decision")
|
||||
}
|
||||
result = map[string]any{"decision": decision}
|
||||
}
|
||||
p.answering = true
|
||||
c.approvals[request.RequestID] = p
|
||||
c.mu.Unlock()
|
||||
err := c.respondResult(ctx, p.requestID, result)
|
||||
c.mu.Lock()
|
||||
if err == nil {
|
||||
delete(c.approvals, request.RequestID)
|
||||
} else if _, exists := c.approvals[request.RequestID]; exists {
|
||||
p.answering = false
|
||||
c.approvals[request.RequestID] = p
|
||||
}
|
||||
c.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
"github.com/coder/websocket"
|
||||
"github.com/coder/websocket/wsjson"
|
||||
)
|
||||
|
||||
func approvalChat(t *testing.T) (*Chat, <-chan rpcMessage) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
responses := make(chan rpcMessage, 8)
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
conn, err := websocket.Accept(w, r, nil)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
defer conn.CloseNow()
|
||||
for {
|
||||
var msg rpcMessage
|
||||
if wsjson.Read(ctx, conn, &msg) != nil {
|
||||
return
|
||||
}
|
||||
responses <- msg
|
||||
}
|
||||
}))
|
||||
conn, _, err := websocket.Dial(ctx, "ws"+strings.TrimPrefix(srv.URL, "http"), nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
c := &Chat{conn: conn, ctx: ctx, cancel: cancel, forms: map[string]pendingForm{}}
|
||||
t.Cleanup(func() { cancel(); conn.CloseNow(); srv.Close() })
|
||||
return c, responses
|
||||
}
|
||||
|
||||
func TestApprovalCallbacksAreDistinctAndSessionOwned(t *testing.T) {
|
||||
c, replies := approvalChat(t)
|
||||
for _, id := range []string{`1`, `"second-callback"`} {
|
||||
c.receiveApproval(rpcMessage{ID: json.RawMessage(id), Method: "item/commandExecution/requestApproval", Params: json.RawMessage(`{"threadId":"thread-a","itemId":"shared-item","command":"echo test","cwd":"/work"}`)})
|
||||
}
|
||||
pending, _ := c.Permissions(context.Background(), "thread-a")
|
||||
if len(pending) != 2 || pending[0].RequestID == pending[1].RequestID {
|
||||
t.Fatalf("callbacks collapsed: %+v", pending)
|
||||
}
|
||||
for i, p := range pending {
|
||||
if err := c.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: "foreign", RequestID: p.RequestID, Decision: protocol.ChatDecisionOnce}); err == nil {
|
||||
t.Fatal("cross-session approval accepted")
|
||||
}
|
||||
decision := protocol.ChatDecisionOnce
|
||||
want := "accept"
|
||||
if i == 1 {
|
||||
decision = protocol.ChatDecisionAlways
|
||||
want = "acceptForSession"
|
||||
}
|
||||
if err := c.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: "thread-a", RequestID: p.RequestID, Decision: decision}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case msg := <-replies:
|
||||
var result struct {
|
||||
Decision string `json:"decision"`
|
||||
}
|
||||
json.Unmarshal(msg.Result, &result)
|
||||
if result.Decision != want || string(msg.ID) != string(capturedApprovalID(p.RequestID)) {
|
||||
t.Fatalf("wrong reply: %+v", msg)
|
||||
}
|
||||
case <-time.After(time.Second):
|
||||
t.Fatal("approval response not delivered")
|
||||
}
|
||||
}
|
||||
pending, _ = c.Permissions(context.Background(), "thread-a")
|
||||
if len(pending) != 0 {
|
||||
t.Fatal("completed approvals retained")
|
||||
}
|
||||
}
|
||||
|
||||
func capturedApprovalID(id string) []byte {
|
||||
raw, _ := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(id, "codex_"))
|
||||
return raw
|
||||
}
|
||||
|
||||
func TestPermissionGrantNeverAddsUnrequestedAccess(t *testing.T) {
|
||||
for _, decision := range []string{protocol.ChatDecisionOnce, protocol.ChatDecisionAlways, protocol.ChatDecisionReject} {
|
||||
t.Run(decision, func(t *testing.T) {
|
||||
c, replies := approvalChat(t)
|
||||
c.receiveApproval(rpcMessage{ID: json.RawMessage(`99`), Method: "item/permissions/requestApproval", Params: json.RawMessage(`{"threadId":"thread-a","itemId":"item","permissions":{"network":{"enabled":true},"fileSystem":null,"unrecognized":"never grant"}}`)})
|
||||
pending, _ := c.Permissions(context.Background(), "thread-a")
|
||||
if err := c.Reply(context.Background(), protocol.ChatReplyRequest{SessionID: "thread-a", RequestID: pending[0].RequestID, Decision: decision}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msg := <-replies
|
||||
var response struct {
|
||||
Permissions map[string]any `json:"permissions"`
|
||||
Scope string `json:"scope"`
|
||||
}
|
||||
json.Unmarshal(msg.Result, &response)
|
||||
if _, ok := response.Permissions["unrecognized"]; ok {
|
||||
t.Fatal("granted unknown access")
|
||||
}
|
||||
want := 1
|
||||
if decision == protocol.ChatDecisionReject {
|
||||
want = 0
|
||||
}
|
||||
if len(response.Permissions) != want {
|
||||
t.Fatalf("grant=%s", msg.Result)
|
||||
}
|
||||
if (response.Scope == "session") != (decision == protocol.ChatDecisionAlways) {
|
||||
t.Fatalf("wrong scope: %s", msg.Result)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCodexQuestionReadbackAndOwnership(t *testing.T) {
|
||||
c, _ := approvalChat(t)
|
||||
c.forms["question"] = pendingForm{threadID: "thread-a", form: protocol.ChatForm{ID: "question", SessionID: "thread-a"}}
|
||||
forms, _ := c.Forms(context.Background(), "thread-a")
|
||||
if len(forms) != 1 {
|
||||
t.Fatal("pending question not recoverable")
|
||||
}
|
||||
if err := c.Answer(context.Background(), protocol.ChatAnswerRequest{SessionID: "foreign", FormID: "question", Answers: map[string]any{"a": "no"}}); err == nil {
|
||||
t.Fatal("foreign session answered question")
|
||||
}
|
||||
forms, _ = c.Forms(context.Background(), "thread-a")
|
||||
if len(forms) != 1 {
|
||||
t.Fatal("refused reply consumed pending question")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMCPElicitationUsesTypedAnswersAndExplicitCancellation(t *testing.T) {
|
||||
for _, action := range []string{"accept", "cancel", "decline"} {
|
||||
t.Run(action, func(t *testing.T) {
|
||||
c, replies := approvalChat(t)
|
||||
c.handleServerRequest(rpcMessage{ID: json.RawMessage(`"mcp-request"`), Method: "mcpServer/elicitation/request", Params: json.RawMessage(`{"threadId":"thread-a","mode":"form","message":"MCP input","requestedSchema":{"type":"object","properties":{"enabled":{"type":"boolean"},"count":{"type":"integer","minimum":0}},"required":["enabled","count"]}}`)})
|
||||
forms, err := c.Forms(context.Background(), "thread-a")
|
||||
if err != nil || len(forms) != 1 || len(forms[0].Fields) != 2 {
|
||||
t.Fatalf("forms=%+v err=%v", forms, err)
|
||||
}
|
||||
if err := c.Answer(context.Background(), protocol.ChatAnswerRequest{SessionID: "thread-a", FormID: forms[0].ID, Action: action, Answers: map[string]any{"enabled": false, "count": 0}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
msg := <-replies
|
||||
var result struct {
|
||||
Action string `json:"action"`
|
||||
Content map[string]any `json:"content"`
|
||||
}
|
||||
json.Unmarshal(msg.Result, &result)
|
||||
if result.Action != action {
|
||||
t.Fatalf("wrong action: %s", msg.Result)
|
||||
}
|
||||
if action == "accept" {
|
||||
if result.Content["enabled"] != false || result.Content["count"] != float64(0) {
|
||||
t.Fatalf("lost typed values: %s", msg.Result)
|
||||
}
|
||||
} else if result.Content != nil {
|
||||
t.Fatal("cancel/decline returned content")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolvedCallbackClearsOnlyItsOwner(t *testing.T) {
|
||||
c, _ := approvalChat(t)
|
||||
c.receiveApproval(rpcMessage{ID: json.RawMessage(`7`), Method: "item/fileChange/requestApproval", Params: json.RawMessage(`{"threadId":"thread-a","itemId":"item","grantRoot":"/work"}`)})
|
||||
c.handleNotification(rpcMessage{Method: "serverRequest/resolved", Params: json.RawMessage(`{"threadId":"foreign","requestId":7}`)})
|
||||
pending, _ := c.Permissions(context.Background(), "thread-a")
|
||||
if len(pending) != 1 {
|
||||
t.Fatal("foreign notification consumed approval")
|
||||
}
|
||||
c.handleNotification(rpcMessage{Method: "serverRequest/resolved", Params: json.RawMessage(`{"threadId":"thread-a","requestId":7}`)})
|
||||
pending, _ = c.Permissions(context.Background(), "thread-a")
|
||||
if len(pending) != 0 {
|
||||
t.Fatal("resolved callback not removed")
|
||||
}
|
||||
}
|
||||
+71
-32
@@ -49,19 +49,23 @@ type Chat struct {
|
||||
writeMu sync.Mutex
|
||||
nextID int64
|
||||
|
||||
mu sync.Mutex
|
||||
pending map[string]chan rpcResponse
|
||||
subs map[string]map[chan protocol.ChatEventFrame]struct{}
|
||||
forms map[string]pendingForm
|
||||
turns map[string]string
|
||||
emitted map[string]bool
|
||||
closed bool
|
||||
mu sync.Mutex
|
||||
pending map[string]chan rpcResponse
|
||||
subs map[string]map[chan protocol.ChatEventFrame]struct{}
|
||||
forms map[string]pendingForm
|
||||
approvals map[string]pendingApproval
|
||||
turns map[string]string
|
||||
emitted map[string]bool
|
||||
closed bool
|
||||
connectionErr error
|
||||
}
|
||||
|
||||
type pendingForm struct {
|
||||
requestID json.RawMessage
|
||||
threadID string
|
||||
form protocol.ChatForm
|
||||
requestID json.RawMessage
|
||||
threadID string
|
||||
form protocol.ChatForm
|
||||
answering bool
|
||||
elicitation bool
|
||||
}
|
||||
|
||||
type rpcResponse struct {
|
||||
@@ -177,6 +181,9 @@ func (c *Chat) readLoop() {
|
||||
|
||||
func (c *Chat) failPending(err error) {
|
||||
c.mu.Lock()
|
||||
c.connectionErr = err
|
||||
c.approvals = nil
|
||||
c.forms = map[string]pendingForm{}
|
||||
pending := c.pending
|
||||
c.pending = map[string]chan rpcResponse{}
|
||||
subs := c.subs
|
||||
@@ -340,23 +347,12 @@ func (c *Chat) PromptWithMessageIDModel(ctx context.Context, id, text, messageID
|
||||
return err
|
||||
}
|
||||
|
||||
// Permissions is empty: Codex approvals are disabled on threads this adapter
|
||||
// creates (approvalPolicy never), and questions arrive as requestUserInput.
|
||||
func (c *Chat) Permissions(context.Context, string) ([]protocol.ChatPermissionFrame, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Shells is empty: Codex background terminals are not exposed through the chat
|
||||
// surface yet.
|
||||
func (c *Chat) Shells(context.Context, string) ([]protocol.ChatShell, error) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// Reply is unused because Codex approvals are not created for these threads.
|
||||
func (c *Chat) Reply(context.Context, protocol.ChatReplyRequest) error {
|
||||
return errors.New("Codex approvals are not enabled for this chat backend")
|
||||
}
|
||||
|
||||
// ActivateSkill is an OpenCode-only chat concept.
|
||||
func (c *Chat) ActivateSkill(context.Context, string, string) error {
|
||||
return errors.New("Codex chat has no out-of-band skill activation")
|
||||
@@ -380,9 +376,8 @@ func (c *Chat) Create(ctx context.Context, title, directory string) (protocol.Ch
|
||||
return protocol.ChatSession{}, errors.New("a directory is required")
|
||||
}
|
||||
raw, err := c.call(ctx, "thread/start", map[string]any{
|
||||
"cwd": directory,
|
||||
"approvalPolicy": "never",
|
||||
"sandbox": "workspace-write",
|
||||
"cwd": directory,
|
||||
"sandbox": "workspace-write",
|
||||
})
|
||||
if err != nil {
|
||||
return protocol.ChatSession{}, err
|
||||
@@ -481,10 +476,20 @@ func (c *Chat) Messages(ctx context.Context, id string, limit int, cursor string
|
||||
|
||||
// Answer replies to a pending requestUserInput request.
|
||||
func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) error {
|
||||
if request.Action != "" && request.Action != "accept" && request.Action != "cancel" && request.Action != "decline" {
|
||||
return errors.New("invalid form action")
|
||||
}
|
||||
c.mu.Lock()
|
||||
pending, ok := c.forms[request.FormID]
|
||||
if ok {
|
||||
delete(c.forms, request.FormID)
|
||||
if request.Action != "" && request.Action != "accept" && (!ok || !pending.elicitation) {
|
||||
c.mu.Unlock()
|
||||
return errors.New("this Codex question does not support that action")
|
||||
}
|
||||
if ok && pending.threadID == request.SessionID && !pending.answering {
|
||||
pending.answering = true
|
||||
c.forms[request.FormID] = pending
|
||||
} else {
|
||||
ok = false
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if !ok {
|
||||
@@ -503,7 +508,30 @@ func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) e
|
||||
answers[key] = map[string]any{"answers": []string{fmt.Sprint(v)}}
|
||||
}
|
||||
}
|
||||
c.respond(pending.requestID, map[string]any{"answers": answers})
|
||||
var result any = map[string]any{"answers": answers}
|
||||
if pending.elicitation {
|
||||
action := request.Action
|
||||
if action == "" {
|
||||
action = "accept"
|
||||
}
|
||||
var content any = request.Answers
|
||||
if action != "accept" {
|
||||
content = nil
|
||||
}
|
||||
result = map[string]any{"action": action, "content": content, "_meta": nil}
|
||||
}
|
||||
err := c.respondResult(ctx, pending.requestID, result)
|
||||
c.mu.Lock()
|
||||
if err == nil {
|
||||
delete(c.forms, request.FormID)
|
||||
} else if _, exists := c.forms[request.FormID]; exists {
|
||||
pending.answering = false
|
||||
c.forms[request.FormID] = pending
|
||||
}
|
||||
c.mu.Unlock()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
c.emit(protocol.ChatEventFrame{
|
||||
SessionID: pending.threadID,
|
||||
Kind: protocol.ChatEventForm,
|
||||
@@ -546,6 +574,7 @@ func (c *Chat) handleServerRequest(msg rpcMessage) {
|
||||
field := protocol.ChatFormField{
|
||||
Key: q.ID, Title: q.Question, Description: q.Header,
|
||||
Type: "string", Custom: q.IsOther, Required: true,
|
||||
Secret: q.IsSecret,
|
||||
}
|
||||
for _, option := range q.Options {
|
||||
value := option.Value
|
||||
@@ -562,17 +591,27 @@ func (c *Chat) handleServerRequest(msg rpcMessage) {
|
||||
c.forms[form.ID] = pendingForm{requestID: msg.ID, threadID: params.ThreadID, form: form}
|
||||
c.mu.Unlock()
|
||||
c.emit(protocol.ChatEventFrame{SessionID: params.ThreadID, Kind: protocol.ChatEventForm, Form: &form})
|
||||
case "item/commandExecution/requestApproval", "item/fileChange/requestApproval":
|
||||
// The thread is created with approvalPolicy never; if a provider still asks,
|
||||
// deny rather than leave the turn hanging.
|
||||
c.respond(msg.ID, map[string]any{"decision": "deny"})
|
||||
case "item/commandExecution/requestApproval", "item/fileChange/requestApproval", "item/permissions/requestApproval":
|
||||
c.receiveApproval(msg)
|
||||
case "mcpServer/elicitation/request":
|
||||
c.receiveElicitation(msg)
|
||||
default:
|
||||
// Unknown server requests must not stall the shared connection.
|
||||
c.respond(msg.ID, map[string]any{})
|
||||
c.respondUnsupported(msg.ID)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *Chat) handleNotification(msg rpcMessage) {
|
||||
if msg.Method == "serverRequest/resolved" {
|
||||
var p struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
RequestID json.RawMessage `json:"requestId"`
|
||||
}
|
||||
if json.Unmarshal(msg.Params, &p) == nil && p.ThreadID != "" && len(p.RequestID) > 0 {
|
||||
c.resolveInteraction(p.ThreadID, p.RequestID)
|
||||
}
|
||||
return
|
||||
}
|
||||
var params struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
TurnID string `json:"turnId"`
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
package codex
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"sort"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
// Standard MCP elicitation uses the same typed question controls. Extended
|
||||
// OpenAI forms are not advertised by initialize and fail explicitly if received.
|
||||
func (c *Chat) receiveElicitation(msg rpcMessage) {
|
||||
var p struct {
|
||||
ThreadID string `json:"threadId"`
|
||||
Mode string `json:"mode"`
|
||||
Message string `json:"message"`
|
||||
URL string `json:"url"`
|
||||
Schema struct {
|
||||
Type string `json:"type"`
|
||||
Properties map[string]json.RawMessage `json:"properties"`
|
||||
Required []string `json:"required"`
|
||||
} `json:"requestedSchema"`
|
||||
}
|
||||
if json.Unmarshal(msg.Params, &p) != nil || p.ThreadID == "" || (p.Mode != "form" && p.Mode != "url") {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
form := protocol.ChatForm{ID: "mcp_" + base64.RawURLEncoding.EncodeToString(msg.ID), SessionID: p.ThreadID, Kind: "elicitation", Title: p.Message, Actions: []string{"accept", "decline", "cancel"}}
|
||||
if p.Mode == "url" {
|
||||
form.Fields = []protocol.ChatFormField{{Key: "external", Type: "external", URL: p.URL, Title: "Continue in the external form"}}
|
||||
} else {
|
||||
if p.Schema.Type != "object" || p.Schema.Properties == nil {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
required := map[string]bool{}
|
||||
for _, key := range p.Schema.Required {
|
||||
required[key] = true
|
||||
}
|
||||
keys := make([]string, 0, len(p.Schema.Properties))
|
||||
for key := range p.Schema.Properties {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
for _, key := range keys {
|
||||
var field struct {
|
||||
Type string `json:"type"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Enum []string `json:"enum"`
|
||||
Default any `json:"default"`
|
||||
Minimum any `json:"minimum"`
|
||||
Maximum any `json:"maximum"`
|
||||
MinLength *int `json:"minLength"`
|
||||
MaxLength *int `json:"maxLength"`
|
||||
MinItems *int `json:"minItems"`
|
||||
MaxItems *int `json:"maxItems"`
|
||||
Format string `json:"format"`
|
||||
Items *struct {
|
||||
Type string `json:"type"`
|
||||
Enum []string `json:"enum"`
|
||||
} `json:"items"`
|
||||
}
|
||||
if json.Unmarshal(p.Schema.Properties[key], &field) != nil {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
out := protocol.ChatFormField{Key: key, Type: field.Type, Title: field.Title, Description: field.Description, Required: required[key], Default: field.Default, Minimum: field.Minimum, Maximum: field.Maximum, MinLength: field.MinLength, MaxLength: field.MaxLength, MinItems: field.MinItems, MaxItems: field.MaxItems, Format: field.Format}
|
||||
switch field.Type {
|
||||
case "string", "number", "integer", "boolean":
|
||||
case "array":
|
||||
if field.Items == nil || field.Items.Type != "string" {
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
out.Type = "multiselect"
|
||||
field.Enum = field.Items.Enum
|
||||
out.Custom = len(field.Enum) == 0
|
||||
default:
|
||||
c.respondUnsupported(msg.ID)
|
||||
return
|
||||
}
|
||||
for _, value := range field.Enum {
|
||||
out.Options = append(out.Options, protocol.ChatFormOption{Value: value, Label: value})
|
||||
}
|
||||
form.Fields = append(form.Fields, out)
|
||||
}
|
||||
}
|
||||
c.mu.Lock()
|
||||
c.forms[form.ID] = pendingForm{requestID: msg.ID, threadID: p.ThreadID, form: form, elicitation: true}
|
||||
c.mu.Unlock()
|
||||
c.emit(protocol.ChatEventFrame{SessionID: p.ThreadID, Kind: protocol.ChatEventForm, Form: &form})
|
||||
}
|
||||
@@ -258,11 +258,18 @@ func (c *Chat) Answer(ctx context.Context, request protocol.ChatAnswerRequest) e
|
||||
if strings.TrimSpace(request.FormID) == "" {
|
||||
return fmt.Errorf("a form id is required")
|
||||
}
|
||||
if request.Action == "cancel" {
|
||||
_, err := c.call(ctx, "delete", "/api/session/"+request.SessionID+"/form/"+url.PathEscape(request.FormID), nil)
|
||||
return err
|
||||
}
|
||||
if request.Action != "" && request.Action != "accept" {
|
||||
return fmt.Errorf("unsupported OpenCode form action")
|
||||
}
|
||||
body := map[string]any{"answer": request.Answers}
|
||||
if request.Answers == nil {
|
||||
body["answer"] = map[string]any{}
|
||||
}
|
||||
if _, err := c.call(ctx, "post", "/api/session/"+request.SessionID+"/form/"+request.FormID+"/reply", body); err != nil {
|
||||
if _, err := c.call(ctx, "post", "/api/session/"+request.SessionID+"/form/"+url.PathEscape(request.FormID)+"/reply", body); err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
@@ -906,13 +913,26 @@ func (c *Chat) Forms(ctx context.Context, id string) ([]protocol.ChatForm, error
|
||||
}
|
||||
|
||||
type chatFormField struct {
|
||||
Key string `json:"key"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type"`
|
||||
Options []chatFormOption `json:"options"`
|
||||
Custom bool `json:"custom"`
|
||||
Required bool `json:"required"`
|
||||
Key string `json:"key"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
Type string `json:"type"`
|
||||
Options []chatFormOption `json:"options"`
|
||||
Custom bool `json:"custom"`
|
||||
Required bool `json:"required"`
|
||||
URL string `json:"url"`
|
||||
Default any `json:"default"`
|
||||
Minimum any `json:"minimum"`
|
||||
Maximum any `json:"maximum"`
|
||||
MinLength *int `json:"minLength"`
|
||||
MaxLength *int `json:"maxLength"`
|
||||
MinItems *int `json:"minItems"`
|
||||
MaxItems *int `json:"maxItems"`
|
||||
Format string `json:"format"`
|
||||
Pattern string `json:"pattern"`
|
||||
Placeholder string `json:"placeholder"`
|
||||
Hidden bool `json:"hidden"`
|
||||
When []protocol.ChatFormWhen `json:"when"`
|
||||
}
|
||||
|
||||
type chatFormOption struct {
|
||||
@@ -1195,6 +1215,7 @@ func normalizeFormEvent(eventType string, data chatEvent, sessionID string, stre
|
||||
SessionID: sessionID,
|
||||
Title: form.Title,
|
||||
Kind: kind,
|
||||
Actions: []string{"accept", "cancel"},
|
||||
}
|
||||
for _, field := range form.Fields {
|
||||
out := protocol.ChatFormField{
|
||||
@@ -1204,6 +1225,9 @@ func normalizeFormEvent(eventType string, data chatEvent, sessionID string, stre
|
||||
Type: field.Type,
|
||||
Custom: field.Custom,
|
||||
Required: field.Required,
|
||||
URL: field.URL, Default: field.Default, Minimum: field.Minimum, Maximum: field.Maximum,
|
||||
MinLength: field.MinLength, MaxLength: field.MaxLength, MinItems: field.MinItems, MaxItems: field.MaxItems,
|
||||
Format: field.Format, Pattern: field.Pattern, Placeholder: field.Placeholder, Hidden: field.Hidden, When: field.When,
|
||||
}
|
||||
for _, option := range field.Options {
|
||||
value := option.Value
|
||||
|
||||
@@ -5,6 +5,8 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"git.a-wan.net/alan/pipelines/internal/protocol"
|
||||
)
|
||||
|
||||
func TestChatFormsReadbackUsesSessionOwnership(t *testing.T) {
|
||||
@@ -22,3 +24,22 @@ func TestChatFormsReadbackUsesSessionOwnership(t *testing.T) {
|
||||
t.Fatalf("forms=%+v err=%v", forms, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestChatQuestionCancellationDoesNotSendAnAnswer(t *testing.T) {
|
||||
calls := 0
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
calls++
|
||||
if r.Method != "DELETE" || r.URL.Path != "/api/session/ses_test/form/form_test" {
|
||||
t.Errorf("unexpected cancellation: %s %s", r.Method, r.URL.Path)
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
defer srv.Close()
|
||||
chat := NewChat(&Connection{Backend: "v2", URL: srv.URL})
|
||||
if err := chat.Answer(context.Background(), protocol.ChatAnswerRequest{SessionID: "ses_test", FormID: "form_test", Action: "cancel"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if calls != 1 {
|
||||
t.Fatalf("calls=%d", calls)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -478,6 +478,7 @@ type ChatForm struct {
|
||||
Resolved bool `json:"resolved,omitempty"`
|
||||
Cancelled bool `json:"cancelled,omitempty"`
|
||||
Answers map[string]any `json:"answers,omitempty"`
|
||||
Actions []string `json:"actions,omitempty"`
|
||||
}
|
||||
|
||||
// ChatFormField is one question/input in a form. Type is OpenCode's field type
|
||||
@@ -491,6 +492,26 @@ type ChatFormField struct {
|
||||
Options []ChatFormOption `json:"options,omitempty"`
|
||||
Custom bool `json:"custom,omitempty"`
|
||||
Required bool `json:"required,omitempty"`
|
||||
Secret bool `json:"secret,omitempty"`
|
||||
URL string `json:"url,omitempty"`
|
||||
Default any `json:"default,omitempty"`
|
||||
Minimum any `json:"minimum,omitempty"`
|
||||
Maximum any `json:"maximum,omitempty"`
|
||||
MinLength *int `json:"min_length,omitempty"`
|
||||
MaxLength *int `json:"max_length,omitempty"`
|
||||
MinItems *int `json:"min_items,omitempty"`
|
||||
MaxItems *int `json:"max_items,omitempty"`
|
||||
Format string `json:"format,omitempty"`
|
||||
Pattern string `json:"pattern,omitempty"`
|
||||
Placeholder string `json:"placeholder,omitempty"`
|
||||
Hidden bool `json:"hidden,omitempty"`
|
||||
When []ChatFormWhen `json:"when,omitempty"`
|
||||
}
|
||||
|
||||
type ChatFormWhen struct {
|
||||
Key string `json:"key"`
|
||||
Op string `json:"op"`
|
||||
Value any `json:"value"`
|
||||
}
|
||||
|
||||
// ChatFormOption is one selectable choice in a ChatFormField.
|
||||
@@ -511,6 +532,7 @@ type ChatRenameRequest struct {
|
||||
// answer object. It is deliberately separate from ChatQuery because its payload
|
||||
// is structured answers, not a session-scoped read.
|
||||
type ChatAnswerRequest struct {
|
||||
Action string `json:"action,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
FormID string `json:"form_id"`
|
||||
Answers map[string]any `json:"answers"`
|
||||
@@ -553,14 +575,15 @@ type ChatShellOutputPage struct {
|
||||
// The wire shape is spec-verified; a live pending request has not been observed.
|
||||
// Every optional field is omitempty so older peers ignore it.
|
||||
type ChatPermissionFrame struct {
|
||||
SessionID string `json:"session_id"`
|
||||
RequestID string `json:"request_id"`
|
||||
Action string `json:"action,omitempty"`
|
||||
Resources []string `json:"resources,omitempty"`
|
||||
Save []string `json:"save,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
Source *ChatPermissionSource `json:"source,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
SessionID string `json:"session_id"`
|
||||
RequestID string `json:"request_id"`
|
||||
Action string `json:"action,omitempty"`
|
||||
Resources []string `json:"resources,omitempty"`
|
||||
Save []string `json:"save,omitempty"`
|
||||
Metadata map[string]any `json:"metadata,omitempty"`
|
||||
Source *ChatPermissionSource `json:"source,omitempty"`
|
||||
Message string `json:"message,omitempty"`
|
||||
AlwaysLabel string `json:"always_label,omitempty"`
|
||||
// Resolved, Decision and ResolvedBy report the shared, exactly-once outcome
|
||||
// of a request any client may answer: once the first answer is recorded the
|
||||
// server pushes the same frame back to every watching client with Resolved
|
||||
|
||||
@@ -30,7 +30,11 @@ func handleChatAnswer(ctx context.Context, request protocol.Message, broker chat
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "a form id is required"})
|
||||
return
|
||||
}
|
||||
if len(answer.Answers) == 0 {
|
||||
if answer.Action != "" && answer.Action != "accept" && answer.Action != "decline" && answer.Action != "cancel" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "invalid form action"})
|
||||
return
|
||||
}
|
||||
if len(answer.Answers) == 0 && answer.Action == "" {
|
||||
_ = write(protocol.Message{Type: protocol.Error, ID: request.ID, Error: "at least one answer is required"})
|
||||
return
|
||||
}
|
||||
|
||||
@@ -26,6 +26,7 @@ type browserForms struct {
|
||||
mu sync.Mutex
|
||||
pending []protocol.ChatForm
|
||||
answered int
|
||||
canceled int
|
||||
}
|
||||
|
||||
func (b browserModelFixture) Forms(context.Context, string) ([]protocol.ChatForm, error) {
|
||||
@@ -37,13 +38,25 @@ func (b browserModelFixture) Forms(context.Context, string) ([]protocol.ChatForm
|
||||
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" {
|
||||
if answer.Action != "cancel" && answer.Answers["answer"] != "Browser answer" {
|
||||
return fmt.Errorf("unexpected answer")
|
||||
}
|
||||
if answer.FormID == "form_second" {
|
||||
if answer.Answers["enabled"] != false || answer.Answers["count"] != float64(0) {
|
||||
return fmt.Errorf("typed answers were lost")
|
||||
}
|
||||
if _, ok := answer.Answers["conditional"]; ok {
|
||||
return fmt.Errorf("hidden conditional answer leaked")
|
||||
}
|
||||
}
|
||||
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++
|
||||
if answer.Action == "cancel" {
|
||||
b.forms.canceled++
|
||||
} else {
|
||||
b.forms.answered++
|
||||
}
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -109,6 +122,13 @@ func TestChatBrowserLifecycleAndModelDialog(t *testing.T) {
|
||||
handler := HandlerWithOptions(ctx, Options{Chat: browserModelFixture{fake, forms}}, store)
|
||||
defer func() { cancel(); WaitRuns(handler) }()
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
|
||||
if req.URL.Path == "/fixture-cancel" && req.Method == http.MethodPost {
|
||||
forms.mu.Lock()
|
||||
forms.pending = append(forms.pending, protocol.ChatForm{ID: "form_cancel", SessionID: session.ID, Title: "Cancel this question", Actions: []string{"accept", "cancel"}, Fields: []protocol.ChatFormField{{Key: "answer", Type: "string", Required: true}}})
|
||||
forms.mu.Unlock()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
return
|
||||
}
|
||||
if req.URL.Path == "/fixture-attention" && req.Method == http.MethodPost {
|
||||
fake.mu.Lock()
|
||||
fake.permissions = []protocol.ChatPermissionFrame{
|
||||
@@ -118,7 +138,16 @@ func TestChatBrowserLifecycleAndModelDialog(t *testing.T) {
|
||||
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}}})
|
||||
fields := []protocol.ChatFormField{{Key: "answer", Type: "string", Title: "Your answer", Required: true}}
|
||||
if id == "form_second" {
|
||||
fields = append(fields,
|
||||
protocol.ChatFormField{Key: "enabled", Type: "boolean", Title: "Enabled", Required: true},
|
||||
protocol.ChatFormField{Key: "count", Type: "integer", Title: "Count", Minimum: 0, Maximum: 5, Required: true},
|
||||
protocol.ChatFormField{Key: "secret", Type: "string", Title: "Secret", Secret: true},
|
||||
protocol.ChatFormField{Key: "conditional", Type: "string", Title: "Only when enabled", Required: true, When: []protocol.ChatFormWhen{{Key: "enabled", Op: "eq", Value: true}}},
|
||||
)
|
||||
}
|
||||
forms.pending = append(forms.pending, protocol.ChatForm{ID: id, SessionID: session.ID, Title: "Recovered question", Fields: fields})
|
||||
}
|
||||
forms.mu.Unlock()
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
@@ -138,8 +167,9 @@ func TestChatBrowserLifecycleAndModelDialog(t *testing.T) {
|
||||
fake.mu.Unlock()
|
||||
forms.mu.Lock()
|
||||
answers := forms.answered
|
||||
canceled := forms.canceled
|
||||
forms.mu.Unlock()
|
||||
if replies != 2 || answers != 2 {
|
||||
t.Fatalf("browser did not deliver all interactions: approvals=%d answers=%d", replies, answers)
|
||||
if replies != 2 || answers != 2 || canceled != 1 {
|
||||
t.Fatalf("browser did not deliver all interactions: approvals=%d answers=%d canceled=%d", replies, answers, canceled)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,6 +247,18 @@ to it, but the server never lists it and a reload drops it.
|
||||
|
||||
## Web interaction recovery (2026-10-20)
|
||||
|
||||
Typed-tool follow-up: number/integer/boolean/default/conditional/secret and
|
||||
external-link fields use native controls, preserve JSON types and validate before
|
||||
sending. `typed-question-controls.png` and the scratch browser regression cover
|
||||
false/zero, masked input and hidden-answer omission. OpenCode questions can be
|
||||
cancelled. Codex approvals now reach the normal cards (with explicit session
|
||||
scope); standard MCP elicitation supports Accept/Decline/Cancel. Adapter tests
|
||||
verify exact callback identity, session ownership, transport writes and requested
|
||||
permission bounds. This is not a live grant/command-execution claim: no real
|
||||
permission request was approved for testing. Extended OpenAI elicitation remains
|
||||
unadvertised/unsupported; callback recovery across App Server socket loss is not
|
||||
available. See `docs/chat-backends.md`.
|
||||
|
||||
- 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
|
||||
|
||||
@@ -1164,6 +1164,7 @@
|
||||
pointer-events: none;
|
||||
}
|
||||
.chat-backend-logo svg { width: 18px; height: 18px; display: block; }
|
||||
.chat-question-field[hidden] { display: none; }
|
||||
.chat-backend-logo[data-activity="streaming"] { color: var(--accent); }
|
||||
.chat-backend-logo[data-activity="new"] { color: var(--ok); }
|
||||
.chat-row .row-head { padding-right: 86px; }
|
||||
|
||||
+2
-1
@@ -2311,7 +2311,8 @@ export function approvalCard(permission, answer) {
|
||||
actionable: state === APPROVAL_PENDING,
|
||||
showRisk:
|
||||
state === APPROVAL_PENDING || (state === APPROVAL_ANSWERED && decision === DECISION_REJECT),
|
||||
headline: approvalHeadline(state, decision, str(permission.action)),
|
||||
headline: decision === DECISION_ALWAYS && permission.always_label === "Allow for session"
|
||||
? "Allowed for session" : approvalHeadline(state, decision, str(permission.action)),
|
||||
statusLine: approvalStatusLine(state, note),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
/** Preserve protocol types; false and zero are valid answers, not missing input. */
|
||||
export function formFieldVisible(field, answers) {
|
||||
return field?.hidden !== true && (field?.when ?? []).every((condition) =>
|
||||
condition.op === 'neq' ? answers[condition.key] !== condition.value : answers[condition.key] === condition.value);
|
||||
}
|
||||
|
||||
export function formFieldValue(field, raw) {
|
||||
if (raw === '') return undefined;
|
||||
if (field.type === 'boolean') return raw === 'true';
|
||||
if (field.type === 'number' || field.type === 'integer') return Number(raw);
|
||||
return raw;
|
||||
}
|
||||
|
||||
export function formAnswerError(fields, answers) {
|
||||
for (const field of fields ?? []) {
|
||||
if (!formFieldVisible(field, answers) || field.type === 'external') continue;
|
||||
const value = answers[field.key];
|
||||
const missing = value == null || value === '' || (Array.isArray(value) && !value.length);
|
||||
const label = field.title || field.key;
|
||||
if (missing) { if (field.required) return `Answer ${label} before sending.`; continue; }
|
||||
if (['number', 'integer'].includes(field.type)) {
|
||||
if (typeof value !== 'number' || !Number.isFinite(value) || (field.type === 'integer' && !Number.isInteger(value))) return `${label} needs a valid ${field.type}.`;
|
||||
if (typeof field.minimum === 'number' && value < field.minimum) return `${label} must be at least ${field.minimum}.`;
|
||||
if (typeof field.maximum === 'number' && value > field.maximum) return `${label} must be at most ${field.maximum}.`;
|
||||
}
|
||||
if (field.type === 'boolean' && typeof value !== 'boolean') return `${label} needs Yes or No.`;
|
||||
if (typeof value === 'string') {
|
||||
if (field.min_length != null && value.length < field.min_length) return `${label} is too short.`;
|
||||
if (field.max_length != null && value.length > field.max_length) return `${label} is too long.`;
|
||||
}
|
||||
if (Array.isArray(value)) {
|
||||
if (field.min_items != null && value.length < field.min_items) return `Select at least ${field.min_items} choices for ${label}.`;
|
||||
if (field.max_items != null && value.length > field.max_items) return `Select at most ${field.max_items} choices for ${label}.`;
|
||||
}
|
||||
}
|
||||
return '';
|
||||
}
|
||||
|
||||
export function visibleFormAnswers(fields, answers) {
|
||||
return Object.fromEntries((fields ?? []).filter(f => formFieldVisible(f,answers) && f.type !== 'external' && answers[f.key] !== undefined).map(f => [f.key, answers[f.key]]));
|
||||
}
|
||||
|
||||
export function safeFormURL(raw) {
|
||||
try { const url=new URL(raw); return ['http:','https:'].includes(url.protocol) ? url.href : null; } catch { return null; }
|
||||
}
|
||||
@@ -426,10 +426,10 @@ export class PipelinesRepository {
|
||||
* the form field key; the server forwards it to the paused tool call and the
|
||||
* resolved form arrives on the normal chat_event stream.
|
||||
*/
|
||||
async answerChatForm(sessionId, formId, answers) {
|
||||
async answerChatForm(sessionId, formId, answers, action = "") {
|
||||
return this.#client.call({
|
||||
type: Protocol.CHAT_ANSWER,
|
||||
[ChatKeys.ANSWER]: { session_id: sessionId, form_id: formId, answers },
|
||||
[ChatKeys.ANSWER]: { session_id: sessionId, form_id: formId, answers, ...(action ? {action} : {}) },
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+63
-22
@@ -4,6 +4,7 @@
|
||||
// in chat.js and markdown.js; this module owns the DOM and the chat wire wiring.
|
||||
|
||||
import { backChevronIcon, h } from "../dom.js";
|
||||
import { formFieldVisible, formFieldValue, formAnswerError, visibleFormAnswers, safeFormURL } from "../chatForms.js";
|
||||
import { readChatStars, writeChatStars } from "../chatStars.js";
|
||||
import { chatModelLabel, chatModelSelectionNote, supportsChatModels } from "../chatModels.js";
|
||||
import { describeError } from "../format.js";
|
||||
@@ -745,7 +746,9 @@ function refreshChatTranscript(sessionId) {
|
||||
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());
|
||||
const jumpLabel=chatApprovalCards(thread).some(card=>card.actionable) ? WAITING_FOR_APPROVAL_LABEL : "Answer question";
|
||||
if (awaiting && bar && !jump) bar.append(approvalJumpButton(jumpLabel));
|
||||
else if (awaiting && jump) jump.textContent=jumpLabel;
|
||||
else if (!awaiting) jump?.remove();
|
||||
captureChatPosition();
|
||||
// The background-tasks bar sits outside the transcript but is driven by the
|
||||
@@ -891,10 +894,10 @@ async function answerPermission(sessionId, requestId, decision) {
|
||||
* field's own key and mirrors OpenCode's form.reply body; the resolved form
|
||||
* arrives on the stream and clears the card for every watching client.
|
||||
*/
|
||||
async function answerChatQuestion(sessionId, form, answers) {
|
||||
async function answerChatQuestion(sessionId, form, answers, action = "") {
|
||||
if (!form?.id) return;
|
||||
try {
|
||||
await repo.answerChatForm(sessionId, form.id, answers);
|
||||
await repo.answerChatForm(sessionId, form.id, answers, action);
|
||||
const current = state.chatThreads.get(sessionId);
|
||||
if (current) state.chatThreads.set(sessionId, applyChatForm(current, { ...form, resolved: true }));
|
||||
renderContent();
|
||||
@@ -2499,7 +2502,7 @@ function renderChatConversation() {
|
||||
// The approval jump control appears only while a request is actionable, and
|
||||
// brings its card (the transcript's last item) into view — the one scroll path,
|
||||
// so a pending request is reached the same way new content is.
|
||||
if (awaiting) bar.append(approvalJumpButton());
|
||||
if (awaiting) bar.append(approvalJumpButton(chatApprovalCards(thread).some(card=>card.actionable) ? WAITING_FOR_APPROVAL_LABEL : "Answer question"));
|
||||
pane.append(bar);
|
||||
const modelButton = effective ? renderChatModelButton(effective) : null;
|
||||
if (modelButton) {
|
||||
@@ -3050,11 +3053,11 @@ function renderChatTranscript(
|
||||
}
|
||||
|
||||
/** The chat pane's approval jump control (C10), naming the pending request. */
|
||||
function approvalJumpButton() {
|
||||
function approvalJumpButton(label = WAITING_FOR_APPROVAL_LABEL) {
|
||||
return h("button", {
|
||||
class: "ghost chat-approval-jump",
|
||||
type: "button",
|
||||
text: WAITING_FOR_APPROVAL_LABEL,
|
||||
text: label,
|
||||
onclick: () => {
|
||||
// The card is the transcript's last item, so the transcript's own end is the
|
||||
// card; the one scroll path shared with jump-to-latest.
|
||||
@@ -3113,7 +3116,8 @@ function renderChatApproval(sessionId, card) {
|
||||
if (card.actionable) {
|
||||
const controls = h("div", { class: "chat-approval-controls" });
|
||||
controls.append(approvalControl(APPROVAL_CONTROL_ONCE, DECISION_ONCE, sessionId, card.requestId, "primary"));
|
||||
controls.append(approvalControl(APPROVAL_CONTROL_ALWAYS, DECISION_ALWAYS, sessionId, card.requestId));
|
||||
const frame = (state.chatThreads.get(sessionId)?.permissions ?? []).find((entry) => entry.request_id === card.requestId);
|
||||
controls.append(approvalControl(frame?.always_label || APPROVAL_CONTROL_ALWAYS, DECISION_ALWAYS, sessionId, card.requestId));
|
||||
controls.append(approvalControl(APPROVAL_CONTROL_REJECT, DECISION_REJECT, sessionId, card.requestId));
|
||||
node.append(controls);
|
||||
}
|
||||
@@ -3144,18 +3148,41 @@ function renderChatQuestion(sessionId, form) {
|
||||
if (thread && !thread.formAnswers) thread.formAnswers = {};
|
||||
const answers = thread ? (thread.formAnswers[form.id] ??= {}) : {};
|
||||
const parts = [];
|
||||
const fieldNodes = [];
|
||||
for (const field of form.fields ?? []) {
|
||||
if (answers[field.key] === undefined && field.default !== undefined) answers[field.key] = field.default;
|
||||
}
|
||||
const paintVisibility = () => {
|
||||
for (const { field, part } of fieldNodes) part.hidden = !formFieldVisible(field, answers);
|
||||
};
|
||||
for (const field of form.fields ?? []) {
|
||||
const key = String(field.key ?? "");
|
||||
if (key === "") continue;
|
||||
const options = Array.isArray(field.options) ? field.options : [];
|
||||
const multi = field.type === "multiselect";
|
||||
const part = h("div", { class: "chat-question-field" });
|
||||
fieldNodes.push({field,part});
|
||||
part.append(
|
||||
h("div", { class: "chat-question-label", text: field.title || field.description || key }),
|
||||
);
|
||||
if (field.description && field.description !== field.title) {
|
||||
part.append(h("div", { class: "chat-question-desc muted", text: field.description }));
|
||||
}
|
||||
if (field.type === "external") {
|
||||
const url = safeFormURL(field.url);
|
||||
part.append(url ? h("a", { href: url, target: "_blank", rel: "noopener noreferrer", text: "Open external form" }) : h("div", {role:"alert",text:"This form has an unsupported external URL."}));
|
||||
parts.push(part);
|
||||
continue;
|
||||
}
|
||||
if (field.type === "boolean") {
|
||||
const select = h("select", {class:"chat-question-input", "aria-label":field.title || key},
|
||||
h("option",{value:"",text:"Choose Yes or No"}),h("option",{value:"true",text:"Yes"}),h("option",{value:"false",text:"No"}));
|
||||
select.value = typeof answers[key] === "boolean" ? String(answers[key]) : "";
|
||||
select.addEventListener("change",()=>{const value=formFieldValue(field,select.value);if(value===undefined)delete answers[key];else answers[key]=value;paintVisibility();});
|
||||
part.append(select);
|
||||
parts.push(part);
|
||||
continue;
|
||||
}
|
||||
if (options.length) {
|
||||
const rows = h("div", { class: "chat-question-options" });
|
||||
const buttons = [];
|
||||
@@ -3194,6 +3221,7 @@ function renderChatQuestion(sessionId, form) {
|
||||
answers[key] = value;
|
||||
}
|
||||
paint();
|
||||
paintVisibility();
|
||||
});
|
||||
buttons.push(button);
|
||||
rows.append(button);
|
||||
@@ -3204,21 +3232,33 @@ function renderChatQuestion(sessionId, form) {
|
||||
if (field.custom === true || options.length === 0) {
|
||||
const input = h("input", {
|
||||
class: "chat-question-input",
|
||||
type: "text",
|
||||
placeholder: options.length ? "Type another answer" : "Your answer",
|
||||
type: field.secret ? "password" : ["number","integer"].includes(field.type) ? "number" : field.format === "email" ? "email" : field.format === "uri" ? "url" : field.format === "date" ? "date" : "text",
|
||||
step: field.type === "number" ? "any" : field.type === "integer" ? "1" : null,
|
||||
min: typeof field.minimum === "number" ? String(field.minimum) : null,
|
||||
max: typeof field.maximum === "number" ? String(field.maximum) : null,
|
||||
minlength: field.min_length ?? null,
|
||||
maxlength: field.max_length ?? null,
|
||||
pattern: field.pattern || null,
|
||||
"aria-label": field.title || key,
|
||||
placeholder: field.placeholder || (options.length ? "Type another answer" : "Your answer"),
|
||||
autocomplete: "off",
|
||||
value: typeof answers[key] === "string" ? answers[key] : "",
|
||||
value: ["string","number"].includes(typeof answers[key]) ? String(answers[key]) : "",
|
||||
});
|
||||
input.addEventListener("input", () => {
|
||||
const value = input.value.trim();
|
||||
if (value === "") delete answers[key];
|
||||
else answers[key] = value;
|
||||
const value = formFieldValue(field,input.value);
|
||||
if (value === undefined) delete answers[key];
|
||||
else if (multi) {
|
||||
const known=new Set(options.map(option=>String(option.value ?? option.label ?? "")));
|
||||
answers[key]=[...(Array.isArray(answers[key]) ? answers[key].filter(v=>known.has(v)) : []),...String(value).split(",").map(v=>v.trim()).filter(Boolean)];
|
||||
} else answers[key] = value;
|
||||
paintVisibility();
|
||||
});
|
||||
part.append(input);
|
||||
}
|
||||
parts.push(part);
|
||||
}
|
||||
node.append(...parts);
|
||||
paintVisibility();
|
||||
|
||||
const error = h("div", { class: "chat-question-error", role: "alert", hidden: true });
|
||||
node.append(error);
|
||||
@@ -3226,27 +3266,28 @@ function renderChatQuestion(sessionId, form) {
|
||||
const submit = h("button", {
|
||||
class: "primary chat-question-submit",
|
||||
type: "button",
|
||||
text: "Send answer",
|
||||
text: (form.fields ?? []).every(field=>field.type === "external") ? "Confirm completion" : "Send answer",
|
||||
});
|
||||
let sent = false;
|
||||
submit.addEventListener("click", () => {
|
||||
if (sent) return;
|
||||
const missing = (form.fields ?? []).some((field) => {
|
||||
if (!field.required) return false;
|
||||
const value = answers[field.key];
|
||||
return Array.isArray(value) ? value.length === 0 : !value;
|
||||
});
|
||||
if (missing) {
|
||||
const invalidInput=[...node.querySelectorAll('input')].find(input=>!input.closest('.chat-question-field').hidden && !input.checkValidity());
|
||||
const reason=formAnswerError(form.fields,answers);
|
||||
if (reason || invalidInput) {
|
||||
error.hidden = false;
|
||||
error.textContent = "Answer the required questions before sending.";
|
||||
error.textContent = reason || invalidInput.validationMessage;
|
||||
return;
|
||||
}
|
||||
sent = true;
|
||||
submit.disabled = true;
|
||||
submit.textContent = "Sending…";
|
||||
answerChatQuestion(sessionId, form, answers);
|
||||
answerChatQuestion(sessionId, form, visibleFormAnswers(form.fields,answers), form.actions?.includes("accept") ? "accept" : "");
|
||||
});
|
||||
controls.append(submit);
|
||||
for (const action of ["decline","cancel"]) {
|
||||
if (!form.actions?.includes(action)) continue;
|
||||
controls.append(h("button",{class:"ghost",type:"button",text:action === "cancel" ? "Cancel question" : "Decline",onclick:()=>answerChatQuestion(sessionId,form,{},action)}));
|
||||
}
|
||||
node.append(controls);
|
||||
return node;
|
||||
}
|
||||
|
||||
@@ -127,12 +127,25 @@ try {
|
||||
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');
|
||||
if(id==='form_second') {
|
||||
await page.evaluate("(()=>{const s=document.querySelector('[data-form-id=form_second] select');s.value='true';s.dispatchEvent(new Event('change',{bubbles:true}));})()");
|
||||
await page.fill('[data-form-id=form_second] input[aria-label="Only when enabled"]','must not leak');
|
||||
await page.evaluate("(()=>{const s=document.querySelector('[data-form-id=form_second] select');s.value='false';s.dispatchEvent(new Event('change',{bubbles:true}));})()");
|
||||
await page.fill('[data-form-id=form_second] input[type=number]','0');
|
||||
assert.equal(await page.evaluate("document.querySelector('[data-form-id=form_second] input[aria-label=\"Only when enabled\"]').closest('.chat-question-field').getBoundingClientRect().height"),0);
|
||||
assert.equal(await page.evaluate("document.querySelector('[data-form-id=form_second] input[aria-label=Secret]').type"),'password');
|
||||
if(process.env.PIPELINES_CAPTURE_DIR) await page.screenshot(join(process.env.PIPELINES_CAPTURE_DIR,'typed-question-controls.png'));
|
||||
}
|
||||
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.equal((await fetch(`http://${target}/fixture-cancel`,{method:'POST'})).status,204);
|
||||
await page.waitForSelector('[data-form-id=form_cancel]');
|
||||
await page.evaluate("[...document.querySelectorAll('[data-form-id=form_cancel] button')].find(button=>button.textContent==='Cancel question').click()");
|
||||
await eventually(()=>page.evaluate("!document.querySelector('[data-form-id=form_cancel]')"));
|
||||
assert.deepEqual(await page.evaluate("window.__errors"), []);
|
||||
console.log("Model dialog, stable activity mark, keyboard/caret, Back restoration, send-to-bottom and all recovered approvals/questions passed.");
|
||||
} finally {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {formFieldValue,formAnswerError,visibleFormAnswers,safeFormURL} from '../src/chatForms.js';
|
||||
|
||||
test('typed questions preserve false and zero, and reject invalid numeric answers',()=>{
|
||||
const fields=[{key:'yes',type:'boolean',required:true},{key:'count',type:'integer',required:true,minimum:0,maximum:5}];
|
||||
const answers={yes:formFieldValue(fields[0],'false'),count:formFieldValue(fields[1],'0')};
|
||||
assert.deepEqual(answers,{yes:false,count:0});
|
||||
assert.equal(formAnswerError(fields,answers),'');
|
||||
assert.match(formAnswerError(fields,{...answers,count:1.5}),/integer/);
|
||||
assert.match(formAnswerError(fields,{...answers,count:6}),/at most/);
|
||||
assert.match(formAnswerError(fields,{...answers,count:NaN}),/valid/);
|
||||
});
|
||||
|
||||
test('conditional and hidden fields never send stale answers',()=>{
|
||||
const fields=[{key:'yes',type:'boolean'},{key:'extra',type:'string',required:true,when:[{key:'yes',op:'eq',value:true}]},{key:'hidden',hidden:true}];
|
||||
const answers={yes:false,extra:'stale',hidden:'hidden'};
|
||||
assert.deepEqual(visibleFormAnswers(fields,answers),{yes:false});
|
||||
assert.equal(formAnswerError(fields,answers),'');
|
||||
assert.match(formAnswerError(fields,{yes:true}),/extra/);
|
||||
});
|
||||
|
||||
test('external question links accept only explicit HTTP(S) URLs',()=>{
|
||||
assert.equal(safeFormURL('https://example.test/form'),'https://example.test/form');
|
||||
for(const value of ['javascript:alert(1)','file:///etc/passwd','//example.test','bad'])assert.equal(safeFormURL(value),null);
|
||||
});
|
||||
@@ -1,6 +1,6 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { applyChatForm, applyChatPermission, chatApprovalCards, chatPendingForms } from '../src/chat.js';
|
||||
import { applyChatForm, applyChatPermission, chatApprovalCards, chatPendingForms, approvalCard } from '../src/chat.js';
|
||||
|
||||
test('parallel approvals stay independently actionable and resolve by identity',()=>{
|
||||
let thread={};
|
||||
@@ -12,6 +12,11 @@ test('parallel approvals stay independently actionable and resolve by identity',
|
||||
assert.deepEqual(chatApprovalCards(thread),[]);
|
||||
});
|
||||
|
||||
test('Codex session-scoped approval is never described as a permanent grant',()=>{
|
||||
const card=approvalCard({request_id:'a',always_label:'Allow for session',resolved:true,decision:'always'},'');
|
||||
assert.equal(card.headline,'Allowed for session');
|
||||
});
|
||||
|
||||
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:[]});
|
||||
|
||||
Reference in New Issue
Block a user