Fan a chat session out to every client and share approvals exactly-once
A session was owned by one connection: the claim map in chat_claims.go let the
first client hold it, every other client saw the session Busy and read-only, and
a second client's prompt was rejected. Replace the claim with a per-session
"room" so the operator's phone, tablet and terminal all watch and write the same
conversation, and a pending approval is a shared, exactly-once object.
Server (internal/server, internal/protocol):
- New chat_room.go: one room per session holding the session's single broker
stream, its one bounded prompt queue (8) and the fan-out to every attached
client. A chat_subscribe frame attaches a connection to a session's shared
stream and replays the still-unresolved approval requests the room holds.
- chat_stream.go: handleChatPrompt accepts a prompt from any client. It attaches
the sender, either starts a turn or queues the prompt behind the in-flight turn
and acknowledges it with chat_queued:true ("queued" is the chosen behaviour,
stated on the wire and in docs/cli.md), and echoes the user turn to every other
client attributed to the sender's label. The prompt handler no longer owns the
stream; one turn runner per room drains the queue, so two turns never
interleave. Per-connection write serialisation is unchanged (each chatSub has
its own writer goroutine and bounded buffer).
- chat_permissions.go / chat_commands.go: an approval is reserved by the first
answer and confirmed once delivered; the first answer wins, is recorded with
the answering client's label, and the resolution is pushed to every watching
client as chat_permission with resolved/decision/resolved_by so their cards
clear. A later answer is refused with an error naming the client that answered,
and never reaches the agent twice; a reservation whose reply failed is
released.
- chat_hub.go / chat_sessions.go / chat.go: the hub now owns rooms and the
user-turn id sequence; the resulting user turns are retained (role and client
carried) so a reconnect re-syncs who said what. chat_sessions no longer marks a
session Busy and its clientID parameter is gone; the protocol keeps the Busy
field for wire compatibility only. websocket.go detaches a connection's chat
subscriptions when the read loop ends.
- chat_claims.go is removed, not left vestigial: the only exclusive thing left is
a turn, and the room's queue is that.
App (android):
- PipelinesRepository carries a stable per-device client label (Build.MODEL, with
a fallback) on prompts and replies, and adds chatSubscribe; AppViewModel
subscribes on opening a chat (best-effort, an older server's error frame does
not stop history loading) and records the queued ack.
- ChatStore folds a user frame from another client into the transcript once,
attributed by the sender's label, and never receives its own prompt back, so
the sender's own message is never duplicated. ChatThread.readOnly is gone:
canSend no longer depends on another client, the composer says "Queued - it
will send when the current turn finishes." instead of disabling input, and the
status label is Running/Idle only. Scroll/follow behaviour is untouched.
- Tests: ChatProtocolTest round-trips the new wire fields, ChatFormatTest asserts
the stale Busy flag cannot produce a read-only label, MultiChatStateTest asserts
a session another client watches stays writable.
Reflected where it belongs: no packaged template changes (no bundled starter
embeds the chat protocol). Checked the packaged authoring skill references: none
of them describes the chat wire beyond operations.md, and
internal/author/skill/references/operations.md is now stale - its "Brokered
OpenCode chat" section still says chat_sessions marks "busy" when another client
holds the session and that a second client's chat_prompt is rejected, and it does
not mention chat_subscribe, the per-session prompt queue/chat_queued, the
per-client label or the shared exactly-once approval (it also still describes the
per-subscription permission poller, which the room's single poller replaced). The
supported semantics are the ones in docs/cli.md, updated in this commit; the
operations.md section needs a rewrite to match. No README or other shared
document was edited here.
Checks run on the committed tree: gofmt -l internal cmd examples (nothing), go
build ./..., go vet ./internal/... ./cmd/..., go test ./internal/server
./internal/protocol ./internal/stage ./internal/pipeline.
This commit is contained in:
+29
-111
@@ -436,10 +436,18 @@ func TestChatMessagesResumesRetainedState(t *testing.T) {
|
||||
if err := wsjson.Read(ctx, conn, &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.Type != protocol.ChatMessages || response.ID != "r2" || len(response.ChatMessages) != 1 {
|
||||
if response.Type != protocol.ChatMessages || response.ID != "r2" || len(response.ChatMessages) != 2 {
|
||||
t.Fatalf("resume response = %+v", response)
|
||||
}
|
||||
message := response.ChatMessages[0]
|
||||
// The prompt is retained as a user turn and the assistant reply beside it, so
|
||||
// a reconnecting client re-syncs a conversation that still says who sent
|
||||
// what. The user turn carries the sending client's label (the generic
|
||||
// fallback when the prompt did not name one).
|
||||
user := response.ChatMessages[0]
|
||||
if user.Role != protocol.ChatRoleUser || len(user.Parts) != 1 || user.Parts[0].Type != protocol.ChatPartText || user.Parts[0].Text != "hi" || user.Client != chatClientLabelFallback {
|
||||
t.Fatalf("resumed user turn = %+v", user)
|
||||
}
|
||||
message := response.ChatMessages[1]
|
||||
if message.ID != "msg_1" || message.Role != protocol.ChatRoleAssistant || len(message.Parts) != 2 {
|
||||
t.Fatalf("resumed message = %+v", message)
|
||||
}
|
||||
@@ -1361,88 +1369,6 @@ func TestChatSessionsFailsClosedWithoutOwnership(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatSessionsBusyRejectsSecondClient is the task evidence for busy state:
|
||||
// while client A holds ses_1 with a blocking prompt, client B's chat_sessions
|
||||
// reports ses_1 Busy=true and B's chat_prompt for ses_1 is rejected before any
|
||||
// broker.Prompt call; after A disconnects the claim is released and a later list
|
||||
// is no longer busy.
|
||||
func TestChatSessionsBusyRejectsSecondClient(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := newOperatorStore(t)
|
||||
if err := store.RecordOperatorSession(ctx, "ses_1", "/work", "operator chat", protocol.ChatSessionTagOperator); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
broker := scriptedChat()
|
||||
broker.block = true
|
||||
broker.done = make(chan struct{})
|
||||
broker.sessions = []protocol.ChatSession{{ID: "ses_1"}}
|
||||
ctx, _, conns := dialChatConns(t, Options{Chat: broker, OperatorRegistry: store}, 2)
|
||||
connA, connB := conns[0], conns[1]
|
||||
|
||||
if err := wsjson.Write(ctx, connA, protocol.Message{Type: protocol.ChatPrompt, ID: "a1", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hi"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var ack protocol.Message
|
||||
if err := wsjson.Read(ctx, connA, &ack); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ack.Type != protocol.ChatPrompt || ack.ID != "a1" {
|
||||
t.Fatalf("prompt ack = %+v", ack)
|
||||
}
|
||||
|
||||
if err := wsjson.Write(ctx, connB, protocol.Message{Type: protocol.ChatSessions, ID: "b1"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var listing protocol.Message
|
||||
if err := wsjson.Read(ctx, connB, &listing); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if listing.Type != protocol.ChatSessions || len(listing.ChatSessions) != 1 || !listing.ChatSessions[0].Busy {
|
||||
t.Fatalf("held session not marked busy: %+v", listing)
|
||||
}
|
||||
|
||||
if err := wsjson.Write(ctx, connB, protocol.Message{Type: protocol.ChatPrompt, ID: "b2", ChatPrompt: &protocol.ChatPromptRequest{SessionID: "ses_1", Text: "hello"}}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var rejected protocol.Message
|
||||
if err := wsjson.Read(ctx, connB, &rejected); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rejected.Type != protocol.Error || !strings.Contains(rejected.Error, "busy") {
|
||||
t.Fatalf("second client's prompt was not rejected as busy: %+v", rejected)
|
||||
}
|
||||
if prompts, _, _ := broker.counts(); prompts != 1 {
|
||||
t.Fatalf("busy prompt reached OpenCode: %d prompt calls, want 1", prompts)
|
||||
}
|
||||
|
||||
// Disconnecting A releases the claim so a later client is no longer blocked.
|
||||
if err := connA.Close(websocket.StatusNormalClosure, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case <-broker.done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("stream did not stop after disconnect")
|
||||
}
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
if err := wsjson.Write(ctx, connB, protocol.Message{Type: protocol.ChatSessions, ID: "b3"}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var after protocol.Message
|
||||
if err := wsjson.Read(ctx, connB, &after); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.Type == protocol.ChatSessions && len(after.ChatSessions) == 1 && !after.ChatSessions[0].Busy {
|
||||
return
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatalf("claim not released after disconnect: %+v", after)
|
||||
}
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPromptPushesPermissionAndForwardsReply is the task evidence: with a
|
||||
// blocking scripted stream keeping the subscription open, a seeded pending
|
||||
// approval request is pushed as a chat_permission frame carrying the seeded
|
||||
@@ -1522,11 +1448,29 @@ func TestChatPermissionDedupesRepeatedPolls(t *testing.T) {
|
||||
mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
if sub := hub.attach("ses_1", "c1", "phone", broker, write); sub == nil {
|
||||
t.Fatal("attach returned nil")
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
if err := pushChatPermissions(context.Background(), broker, hub, "ses_1", write); err != nil {
|
||||
if err := hub.pollPermissionsOnce(context.Background(), broker, "ses_1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
mu.Lock()
|
||||
count := len(pushed)
|
||||
mu.Unlock()
|
||||
if count > 0 {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("no permission frame was pushed")
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
// Give a duplicate a chance to arrive before asserting there is none.
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(pushed) != 1 {
|
||||
@@ -1684,32 +1628,6 @@ func TestChatPermissionUnsupportedBackendIsQuiet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatPermissionWriteFailureDoesNotDropRequest pins that a request id is not
|
||||
// retained as "seen" when its frame could not be written, so the next poll
|
||||
// re-pushes it instead of silently dropping the approval request.
|
||||
func TestChatPermissionWriteFailureDoesNotDropRequest(t *testing.T) {
|
||||
broker := scriptedChat()
|
||||
broker.permissions = []protocol.ChatPermissionFrame{{SessionID: "ses_1", RequestID: "req_1", Action: "bash"}}
|
||||
hub := newChatHub()
|
||||
attempts := 0
|
||||
write := func(protocol.Message) error {
|
||||
attempts++
|
||||
if attempts == 1 {
|
||||
return fmt.Errorf("connection closed")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := pushChatPermissions(context.Background(), broker, hub, "ses_1", write); err == nil {
|
||||
t.Fatal("a failed write must surface an error")
|
||||
}
|
||||
if err := pushChatPermissions(context.Background(), broker, hub, "ses_1", write); err != nil {
|
||||
t.Fatalf("retry after a failed write: %v", err)
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Fatalf("push attempts = %d, want the request re-pushed after the failure", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestChatAdoptRecordsEndpointSession is the chat_adopt acceptance test: the
|
||||
// endpoint's own record supplies the directory and title, the handler records
|
||||
// the row with the operator tag, and the response echoes the session and its
|
||||
|
||||
Reference in New Issue
Block a user