Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-8374: fix: keep private chat content to the session owner (realtime + REST) (#9677)
Jiayuan Zhang2083970b51c0
diff --git a/server/cmd/server/chat_realtime_privacy_test.go b/server/cmd/server/chat_realtime_privacy_test.gonew file mode 100644index 0000000000..34aa174d48--- /dev/null+++ b/server/cmd/server/chat_realtime_privacy_test.go@@ -0,0 +1,273 @@+package main++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"+ "time"++ "github.com/gorilla/websocket"+ "github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/internal/util"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type chatPrivacyFrame struct {+ Type string `json:"type"`+ raw string+}++// readChatPrivacyFrames reads conn until a frame of type stop arrives and+// returns every frame before it.+func readChatPrivacyFrames(t *testing.T, conn *websocket.Conn, stop string) []chatPrivacyFrame {+ t.Helper()+ var frames []chatPrivacyFrame+ for {+ conn.SetReadDeadline(time.Now().Add(5 * time.Second))+ _, raw, err := conn.ReadMessage()+ if err != nil {+ t.Fatalf("waiting for %s: %v (got %d frames)", stop, err, len(frames))+ }+ var f chatPrivacyFrame+ if err := json.Unmarshal(raw, &f); err != nil {+ t.Fatalf("decode frame %s: %v", raw, err)+ }+ if f.Type == stop {+ return frames+ }+ f.raw = string(raw)+ frames = append(frames, f)+ }+}++func chatPrivacyRequest(t *testing.T, server *httptest.Server, token, method, path string, body any, out any) {+ t.Helper()+ b, _ := json.Marshal(body)+ req, err := http.NewRequest(method, server.URL+path, bytes.NewReader(b))+ if err != nil {+ t.Fatal(err)+ }+ req.Header.Set("Content-Type", "application/json")+ req.Header.Set("Authorization", "Bearer "+token)+ req.Header.Set("X-Workspace-ID", testWorkspaceID)+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatal(err)+ }+ defer resp.Body.Close()+ if resp.StatusCode/100 != 2 {+ var e map[string]any+ _ = json.NewDecoder(resp.Body).Decode(&e)+ t.Fatalf("%s %s: status %d %v", method, path, resp.StatusCode, e)+ }+ if out != nil {+ if err := json.NewDecoder(resp.Body).Decode(out); err != nil {+ t.Fatalf("decode %s %s: %v", method, path, err)+ }+ }+}++// A member's chat with an agent is private to that member. Another member of+// the same workspace, connected to the same workspace room, must not receive+// the user turn, the agent's streamed transcript, or the final reply — while+// the owner still receives all three, and every member still sees the task+// lifecycle that drives agent presence.+func TestChatRealtimeIsPrivateToSessionOwner(t *testing.T) {+ ctx := context.Background()+ fx := workspaceFixture(t)+ bystanderID := fx.User(t, "Chat bystander", "[email protected]")+ fx.Member(t, testWorkspaceID, bystanderID, "member")+ var agentID string+ if err := testPool.QueryRow(ctx,+ `SELECT id FROM agent WHERE workspace_id = $1 AND name = 'Integration Test Agent'`,+ testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("load fixture agent: %v", err)+ }++ hub := realtime.NewHub()+ go hub.Run()+ bus := events.New()+ registerListeners(bus, hub)+ router, h := NewRouterWithOptions(testPool, hub, bus, analytics.NoopClient{}, nil, RouterOptions{})+ server := httptest.NewServer(router)+ t.Cleanup(server.Close)++ owner, ownerToken := realtimeMembershipConn(t, server, testUserID, testWorkspaceID)+ bystander, _ := realtimeMembershipConn(t, server, bystanderID, testWorkspaceID)++ const userTurn = "private-user-turn-7f3a"+ const transcript = "private-transcript-9c1d"+ const reply = "private-reply-4b8e"+ const followUp = "private-follow-up-2e6a"++ var session struct {+ ID string `json:"id"`+ }+ chatPrivacyRequest(t, server, ownerToken, http.MethodPost, "/api/chat/sessions",+ map[string]any{"agent_id": agentID}, &session)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE chat_session_id = $1`, session.ID)+ testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, session.ID)+ })+ var sent struct {+ TaskID string `json:"task_id"`+ }+ chatPrivacyRequest(t, server, ownerToken, http.MethodPost, "/api/chat/sessions/"+session.ID+"/messages",+ map[string]any{"content": userTurn}, &sent)++ // The daemon claims and runs the task, streams a transcript row, then+ // completes with the reply — through the production producers.+ if _, err := testPool.Exec(ctx,+ `UPDATE agent_task_queue SET status = 'running', dispatched_at = now(), started_at = now() WHERE id = $1`,+ sent.TaskID); err != nil {+ t.Fatalf("start task: %v", err)+ }+ report := testutil.JSONRequest(http.MethodPost, "/api/daemon/tasks/"+sent.TaskID+"/messages",+ map[string]any{"messages": []any{map[string]any{"seq": 1, "type": "text", "content": transcript}}})+ report = testutil.WithURLParams(report, "taskId", sent.TaskID)+ report.Header.Set("X-User-ID", testUserID)+ testutil.Call(t, h.ReportTaskMessages, report).Want(http.StatusOK)+ result, _ := json.Marshal(map[string]string{"output": reply})+ completed, err := h.TaskService.CompleteTask(ctx, util.MustParseUUID(sent.TaskID), result, "", "", "", false, "", "")+ if err != nil {+ t.Fatalf("complete task: %v", err)+ }+ if err := h.TaskService.SupplementChatQuickActions(ctx, *completed,+ `[{"label":"`+followUp+`","prompt":"`+followUp+`"}]`, false); err != nil {+ t.Fatalf("supplement quick actions: %v", err)+ }++ // A workspace event published last marks the end of what each socket got.+ bus.Publish(events.Event{Type: protocol.EventIssueUpdated, WorkspaceID: testWorkspaceID, Payload: map[string]string{}})+ ownerFrames := readChatPrivacyFrames(t, owner, protocol.EventIssueUpdated)+ bystanderFrames := readChatPrivacyFrames(t, bystander, protocol.EventIssueUpdated)++ ownerGot := map[string]string{}+ for _, f := range ownerFrames {+ ownerGot[f.Type] += f.raw+ }+ for typ, secret := range map[string]string{+ protocol.EventChatMessage: userTurn,+ protocol.EventTaskMessage: transcript,+ protocol.EventChatDone: reply,+ protocol.EventChatQuickActions: followUp,+ } {+ if !strings.Contains(ownerGot[typ], secret) {+ t.Errorf("owner did not receive %s carrying %q; got %v", typ, secret, ownerGot)+ }+ }++ var bystanderTypes []string+ for _, f := range bystanderFrames {+ bystanderTypes = append(bystanderTypes, f.Type)+ if strings.HasPrefix(f.Type, "chat:") || f.Type == protocol.EventTaskMessage {+ t.Errorf("bystander received %s: %s", f.Type, f.raw)+ }+ for _, secret := range []string{userTurn, transcript, reply, followUp} {+ if strings.Contains(f.raw, secret) {+ t.Errorf("bystander frame %s leaked %q: %s", f.Type, secret, f.raw)+ }+ }+ }+ hasCompleted := false+ for _, typ := range bystanderTypes {+ hasCompleted = hasCompleted || typ == protocol.EventTaskCompleted+ }+ if !hasCompleted {+ t.Errorf("bystander lost task:completed, which drives agent presence; got %v", bystanderTypes)+ }+}++// Removal from a workspace must stop that workspace's chat content even while+// the creator stays connected to another workspace. That connection is+// authorized against its own workspace only, so user-scope delivery would+// carry the agent's transcript and reply past the removal.+func TestChatRealtimeStopsAtWorkspaceRemoval(t *testing.T) {+ ctx := context.Background()+ fx := workspaceFixture(t)+ creatorID := fx.User(t, "Removed chat creator", "[email protected]")+ memberID := fx.Member(t, testWorkspaceID, creatorID, "member")+ otherWS := fx.Workspace(t, "Still accessible workspace", "chat-removal-other-workspace")+ fx.Member(t, otherWS, creatorID, "owner")+ var runtimeID string+ fx.QueryRow(t, `SELECT runtime_id FROM agent WHERE workspace_id=$1 AND name='Integration Test Agent'`, testWorkspaceID).Scan(&runtimeID)+ agentID := fx.Agent(t, "Workspace shared agent", runtimeID, testutil.Cols{+ "visibility": "workspace", "permission_mode": "public_to",+ })+ fx.Insert(t, "agent_invocation_target", testutil.Cols{+ "agent_id": agentID, "target_type": "workspace", "target_id": testWorkspaceID,+ })++ hub := realtime.NewHub()+ go hub.Run()+ bus := events.New()+ registerListeners(bus, hub)+ router, h := NewRouterWithOptions(testPool, hub, bus, analytics.NoopClient{}, nil, RouterOptions{})+ server := httptest.NewServer(router)+ t.Cleanup(server.Close)+ other, creatorToken := realtimeMembershipConn(t, server, creatorID, otherWS)++ var session struct {+ ID string `json:"id"`+ }+ chatPrivacyRequest(t, server, creatorToken, http.MethodPost, "/api/chat/sessions",+ map[string]any{"agent_id": agentID}, &session)+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE chat_session_id=$1`, session.ID)+ testPool.Exec(context.Background(), `DELETE FROM chat_session WHERE id=$1`, session.ID)+ })+ var sent struct {+ TaskID string `json:"task_id"`+ }+ chatPrivacyRequest(t, server, creatorToken, http.MethodPost, "/api/chat/sessions/"+session.ID+"/messages",+ map[string]any{"content": "read workspace documents"}, &sent)+ fx.Exec(t, `UPDATE agent_task_queue SET status='running', dispatched_at=now(), started_at=now() WHERE id=$1`, sent.TaskID)+ bus.Publish(events.Event{Type: protocol.EventIssueUpdated, WorkspaceID: otherWS, Payload: map[string]string{}})+ readChatPrivacyFrames(t, other, protocol.EventIssueUpdated)++ // Use the actual removal API. The shared agent/runtime belongs to the+ // workspace owner, so this member's removal does not cancel the task.+ chatPrivacyRequest(t, server, testToken, http.MethodDelete,+ "/api/workspaces/"+testWorkspaceID+"/members/"+memberID, nil, nil)+ if fx.Count(t, `SELECT count(*) FROM member WHERE id=$1`, memberID) != 0 {+ t.Fatal("membership was not removed")+ }+ if fx.Count(t, `SELECT count(*) FROM agent_task_queue WHERE id=$1 AND status='running'`, sent.TaskID) != 1 {+ t.Fatal("shared-agent task unexpectedly stopped")+ }+ req, _ := http.NewRequest(http.MethodGet, server.URL+"/api/tasks/"+sent.TaskID+"/messages", nil)+ req.Header.Set("Authorization", "Bearer "+creatorToken)+ req.Header.Set("X-Workspace-ID", testWorkspaceID)+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatal(err)+ }+ resp.Body.Close()+ if resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusNotFound {+ t.Fatalf("removed member's REST read: got %d, want 403 or 404", resp.StatusCode)+ }++ const secret = "workspace-secret-after-membership-was-revoked"+ report := testutil.JSONRequest(http.MethodPost, "/api/daemon/tasks/"+sent.TaskID+"/messages",+ map[string]any{"messages": []any{map[string]any{"seq": 1, "type": "text", "content": secret}}})+ report = testutil.WithURLParams(report, "taskId", sent.TaskID)+ report.Header.Set("X-User-ID", testUserID)+ testutil.Call(t, h.ReportTaskMessages, report).Want(http.StatusOK)+ result, _ := json.Marshal(map[string]string{"output": secret})+ if _, err := h.TaskService.CompleteTask(ctx, util.MustParseUUID(sent.TaskID), result, "", "", "", false, "", ""); err != nil {+ t.Fatal(err)+ }+ bus.Publish(events.Event{Type: protocol.EventIssueUpdated, WorkspaceID: otherWS, Payload: map[string]string{}})+ for _, frame := range readChatPrivacyFrames(t, other, protocol.EventIssueUpdated) {+ if strings.Contains(frame.raw, secret) {+ t.Errorf("removed member received old-workspace content via other-workspace socket: %s", frame.raw)+ }+ }+}diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.goindex 5dc32524fe..a3aafe0a58 100644--- a/server/cmd/server/listeners.go+++ b/server/cmd/server/listeners.go@@ -67,9 +67,24 @@ func projectOutbound(eventType string, payload any) any {return projected}+// isChatPrivateEvent reports whether e carries chat session content that only+// the session's creator may receive. Every chat:* event qualifies, including+// ones added later. Of the task events only task:message does: it streams the+// agent's transcript. Chat-task lifecycle events (task:queued, task:completed,+// ...) keep workspace fanout because every member's agent presence and+// workload views depend on them; they carry ids and status, and task:failed+// has its error text stripped by projectOutbound.+func isChatPrivateEvent(e events.Event) bool {+ if strings.HasPrefix(e.Type, "chat:") {+ return true+ }+ return e.Type == protocol.EventTaskMessage && e.ChatSessionID != ""+}+// registerListeners wires up event bus listeners for WS broadcasting.// Personal events (inbox, invites) are sent only to the target user via-// SendToUser. All other events are broadcast to the workspace room.+// SendToUser, and chat content only to the chat session's creator. All other+// events are broadcast to the workspace room.//// The broadcaster parameter is intentionally typed as the realtime.Broadcaster// interface (not *realtime.Hub) so that this layer can later be swapped out@@ -87,8 +102,6 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {protocol.EventInboxBatchArchived: true,protocol.EventInvitationCreated: true,protocol.EventInvitationRevoked: true,- protocol.EventChatSessionCreated: true,- protocol.EventChatSessionUpdated: true,}// Helper: marshal event and send to a specific user.@@ -201,16 +214,6 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {})}- // A Chat session is creator-private. Its initial title may be derived from- // the creator's first message, so the list-invalidation event must not be- // broadcast to every workspace member. ActorID is the creator on every- // producer path for this event.- for _, eventType := range []string{protocol.EventChatSessionCreated, protocol.EventChatSessionUpdated} {- bus.Subscribe(eventType, func(e events.Event) {- sendToRecipient(b, e, e.ActorID)- })- }-// member:added — also send to the invited user so they discover the new workspace.// Pass excludeWorkspace so clients already in the target room (reached via// BroadcastToWorkspace in SubscribeAll) don't receive the event twice.@@ -246,6 +249,30 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {return}+ // A chat session is creator-private: its events and its tasks'+ // transcript go only to the creator's connections bound to the+ // session's workspace. Not the whole user scope: a connection to+ // another workspace is authorized against that workspace, so it would+ // keep receiving this content after the creator is removed from this+ // one. The scope is joined at connect time, so this needs no client+ // subscribe frame. Without a known owner and workspace the event is+ // dropped, never widened.+ if isChatPrivateEvent(e) {+ if e.ChatSessionOwnerID == "" || e.WorkspaceID == "" {+ slog.Warn("realtime: dropping chat event without session owner",+ "event_type", e.Type, "chat_session_id", e.ChatSessionID, "task_id", e.TaskID)+ return+ }+ data, err := json.Marshal(map[string]any{"type": e.Type, "payload": projectOutbound(e.Type, e.Payload), "actor_id": e.ActorID, "actor_type": e.ActorType})+ if err != nil {+ slog.Error("failed to marshal event", "event_type", e.Type, "error", err)+ return+ }+ realtime.M.RecordEvent(e.Type)+ b.BroadcastToScope(realtime.ScopeWorkspaceMember, realtime.WorkspaceMemberScopeID(e.WorkspaceID, e.ChatSessionOwnerID), data)+ return+ }+msg := map[string]any{"type": e.Type,"payload": projectOutbound(e.Type, e.Payload),@@ -268,11 +295,12 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster) {// every chat/task message on the floor, breaking the live chat// timeline, chat unread badges, and pending-task UI.//- // Until the client lands its scope-subscription PR, we keep- // task/chat events on workspace fanout (same behavior as before this- // PR). The `Event.TaskID` / `Event.ChatSessionID` hints are still- // populated by producers so that flipping the switch later is a- // one-line change here. See review on PR #1429 for context.+ // Until the client lands its scope-subscription PR, task events stay+ // on workspace fanout, except chat-task transcripts, which take the+ // creator-only user-scope route above. The `Event.TaskID` /+ // `Event.ChatSessionID` hints are still populated by producers so+ // that flipping the switch later is a one-line change here. See+ // review on PR #1429 for context.if e.WorkspaceID != "" {realtime.M.RecordEvent(e.Type)diff --git a/server/cmd/server/listeners_scope_test.go b/server/cmd/server/listeners_scope_test.goindex 8978718336..d4adb527f8 100644--- a/server/cmd/server/listeners_scope_test.go+++ b/server/cmd/server/listeners_scope_test.go@@ -6,6 +6,7 @@ import ("testing""github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/realtime""github.com/multica-ai/multica/server/pkg/protocol")@@ -26,23 +27,18 @@ func TestRegisterListeners_ChatSessionCreatedGoesOnlyToCreator(t *testing.T) {bus.Publish(events.Event{Type: protocol.EventChatSessionCreated, WorkspaceID: "ws-1",- ActorType: "member", ActorID: "creator-1", ChatSessionID: "chat-1",+ ActorType: "member", ActorID: "creator-1", ChatSessionID: "chat-1", ChatSessionOwnerID: "creator-1",Payload: protocol.ChatSessionCreatedPayload{WorkspaceID: "ws-1", ChatSessionID: "chat-1", CreatorID: "creator-1",Title: "private opening title",},})- if len(fb.workspaceCalls) != 0 {- t.Fatalf("private Chat create reached workspace fanout: %+v", fb.workspaceCalls)- }- if len(fb.userCalls) != 1 || fb.userCalls[0].userID != "creator-1" {- t.Fatalf("creator fanout = %+v, want creator-1 once", fb.userCalls)- }+ msg := onlyOwnerWorkspaceFrame(t, fb, "ws-1", "creator-1")var frame struct {Payload protocol.ChatSessionCreatedPayload `json:"payload"`}- if err := json.Unmarshal(fb.userCalls[0].msg, &frame); err != nil {+ if err := json.Unmarshal(msg, &frame); err != nil {t.Fatalf("decode creator frame: %v", err)}if frame.Payload.WorkspaceID != "ws-1" || frame.Payload.ChatSessionID != "chat-1" {@@ -57,18 +53,32 @@ func TestRegisterListeners_ChatSessionTitleUpdateGoesOnlyToCreator(t *testing.T)bus.Publish(events.Event{Type: protocol.EventChatSessionUpdated, WorkspaceID: "ws-1",- ActorType: "member", ActorID: "creator-1", ChatSessionID: "chat-1",+ ActorType: "member", ActorID: "creator-1", ChatSessionID: "chat-1", ChatSessionOwnerID: "creator-1",Payload: protocol.ChatSessionUpdatedPayload{ChatSessionID: "chat-1", Title: "private derived title",},})- if len(fb.workspaceCalls) != 0 {- t.Fatalf("private Chat title reached workspace fanout: %+v", fb.workspaceCalls)+ onlyOwnerWorkspaceFrame(t, fb, "ws-1", "creator-1")+}++// onlyOwnerWorkspaceFrame asserts that the one delivery went to ownerID's+// connections bound to workspaceID, and returns its frame. The user scope+// would also reach the owner's connections to other workspaces, which are not+// re-authorized against workspaceID.+func onlyOwnerWorkspaceFrame(t *testing.T, fb *fakeBroadcaster, workspaceID, ownerID string) []byte {+ t.Helper()+ fb.mu.Lock()+ defer fb.mu.Unlock()+ if len(fb.workspaceCalls) != 0 || len(fb.userCalls) != 0 || fb.broadcastCalled != 0 {+ t.Fatalf("chat content left the owner's workspace connections: workspace=%+v user=%+v broadcast=%d",+ fb.workspaceCalls, fb.userCalls, fb.broadcastCalled)}- if len(fb.userCalls) != 1 || fb.userCalls[0].userID != "creator-1" {- t.Fatalf("creator fanout = %+v, want creator-1 once", fb.userCalls)+ want := realtime.WorkspaceMemberScopeID(workspaceID, ownerID)+ if len(fb.scopeCalls) != 1 || fb.scopeCalls[0].scopeType != realtime.ScopeWorkspaceMember || fb.scopeCalls[0].scopeID != want {+ t.Fatalf("scope fanout = %+v, want %s/%s once", fb.scopeCalls, realtime.ScopeWorkspaceMember, want)}+ return fb.scopeCalls[0].msg}type scopeCall struct {@@ -106,24 +116,26 @@ func (f *fakeBroadcaster) Broadcast(message []byte) {f.broadcastCalled++}-// TestRegisterListeners_TaskChatGoToWorkspace pins the must-fix #1 contract+// TestRegisterListeners_TaskEventsGoToWorkspace pins the must-fix #1 contract// from the PR #1429 review: until the WS client supports scope-subscribe and-// reconnect-replay, high-frequency task/chat events MUST keep going through-// workspace fanout. Routing them via BroadcastToScope("task"|"chat", ...)-// with no client-side subscriber would silently drop every chat / task-// message and break the live timeline + chat unread badges.-func TestRegisterListeners_TaskChatGoToWorkspace(t *testing.T) {+// reconnect-replay, task events MUST keep going through workspace fanout.+// Routing them via BroadcastToScope("task"|"chat", ...) with no client-side+// subscriber would silently drop them. Chat-task lifecycle events stay here+// too: every member's agent presence depends on them.+func TestRegisterListeners_TaskEventsGoToWorkspace(t *testing.T) {cases := []struct {name stringeventType stringtaskID stringchatID string}{- {"task:message with TaskID", protocol.EventTaskMessage, "task-1", ""},- {"task:progress with TaskID", protocol.EventTaskProgress, "task-2", ""},- {"chat:message with ChatSessionID", protocol.EventChatMessage, "", "chat-1"},- {"chat:done with ChatSessionID", protocol.EventChatDone, "", "chat-2"},- {"chat:session_read with ChatSessionID", protocol.EventChatSessionRead, "", "chat-3"},+ {"issue task:message", protocol.EventTaskMessage, "task-1", ""},+ {"task:progress", protocol.EventTaskProgress, "task-2", ""},+ {"chat task:queued", protocol.EventTaskQueued, "task-3", "chat-1"},+ {"chat task:dispatch", protocol.EventTaskDispatch, "task-3", ""},+ {"chat task:completed", protocol.EventTaskCompleted, "task-3", "chat-1"},+ {"chat task:failed", protocol.EventTaskFailed, "task-3", "chat-1"},+ {"chat task:cancelled", protocol.EventTaskCancelled, "task-3", "chat-1"},}for _, tc := range cases {t.Run(tc.name, func(t *testing.T) {@@ -152,6 +164,116 @@ func TestRegisterListeners_TaskChatGoToWorkspace(t *testing.T) {}}+// chatPrivateCases is every event carrying chat session content: all chat:*+// events, plus the transcript stream of a chat task.+var chatPrivateCases = []struct {+ eventType string+ taskID string+}{+ {protocol.EventChatMessage, ""},+ {protocol.EventChatDone, "task-1"},+ {protocol.EventChatQuickActions, "task-1"},+ {protocol.EventChatCancelFinalized, "task-1"},+ {protocol.EventChatSessionCreated, ""},+ {protocol.EventChatSessionUpdated, ""},+ {protocol.EventChatSessionRead, ""},+ {protocol.EventChatSessionDeleted, ""},+ {protocol.EventTaskMessage, "task-1"},+}++func TestRegisterListeners_ChatContentGoesOnlyToSessionOwner(t *testing.T) {+ for _, tc := range chatPrivateCases {+ t.Run(tc.eventType, func(t *testing.T) {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb)++ bus.Publish(events.Event{+ Type: tc.eventType, WorkspaceID: "ws-1", ActorType: "system",+ TaskID: tc.taskID, ChatSessionID: "chat-1", ChatSessionOwnerID: "owner-1",+ Payload: map[string]any{"content": "private chat content"},+ })++ msg := onlyOwnerWorkspaceFrame(t, fb, "ws-1", "owner-1")+ var frame struct {+ Type string `json:"type"`+ Payload map[string]any `json:"payload"`+ }+ if err := json.Unmarshal(msg, &frame); err != nil {+ t.Fatalf("decode owner frame: %v", err)+ }+ if frame.Type != tc.eventType || frame.Payload["content"] != "private chat content" {+ t.Fatalf("owner frame = %+v", frame)+ }+ })+ }+}++// A producer that cannot name the owner and workspace must not fall back to a+// wider fanout: the owner refetches on the next lifecycle event, a leak is+// permanent.+func TestRegisterListeners_ChatContentWithoutOwnerIsDropped(t *testing.T) {+ for _, tc := range chatPrivateCases {+ for _, missing := range []struct{ name, workspaceID, ownerID string }{+ {"no owner", "ws-1", ""},+ {"no workspace", "", "owner-1"},+ } {+ t.Run(tc.eventType+"/"+missing.name, func(t *testing.T) {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb)++ bus.Publish(events.Event{+ Type: tc.eventType, WorkspaceID: missing.workspaceID, ActorType: "system",+ TaskID: tc.taskID, ChatSessionID: "chat-1", ChatSessionOwnerID: missing.ownerID,+ Payload: map[string]any{"content": "private chat content"},+ })++ if len(fb.workspaceCalls) != 0 || len(fb.userCalls) != 0 || len(fb.scopeCalls) != 0 || fb.broadcastCalled != 0 {+ t.Fatalf("unroutable chat event was delivered: workspace=%+v user=%+v scope=%+v broadcast=%d",+ fb.workspaceCalls, fb.userCalls, fb.scopeCalls, fb.broadcastCalled)+ }+ })+ }+ }+}++// IM outbounds (Slack, Lark, ...) subscribe to chat:done and task:message on+// the bus in-process. Narrowing the WebSocket fanout must not narrow them.+func TestRegisterListeners_ChatRoutingKeepsInProcessListeners(t *testing.T) {+ bus := events.New()+ fb := &fakeBroadcaster{}+ var got []events.Event+ for _, eventType := range []string{protocol.EventChatDone, protocol.EventTaskMessage} {+ bus.Subscribe(eventType, func(e events.Event) { got = append(got, e) })+ }+ registerListeners(bus, fb)++ done := protocol.ChatDonePayload{ChatSessionID: "chat-1", TaskID: "task-1", Content: "assistant reply"}+ message := protocol.TaskMessagePayload{TaskID: "task-1", Seq: 1, Type: "text", Content: "streamed text"}+ for _, e := range []events.Event{+ {Type: protocol.EventChatDone, WorkspaceID: "ws-1", ChatSessionID: "chat-1", ChatSessionOwnerID: "owner-1", Payload: done},+ {Type: protocol.EventTaskMessage, WorkspaceID: "ws-1", TaskID: "task-1", ChatSessionID: "chat-1", ChatSessionOwnerID: "owner-1", Payload: message},+ // Ownerless events are dropped from the WebSocket only.+ {Type: protocol.EventChatDone, WorkspaceID: "ws-1", ChatSessionID: "chat-1", Payload: done},+ } {+ bus.Publish(e)+ }++ if len(got) != 3 {+ t.Fatalf("in-process listener saw %d events, want 3", len(got))+ }+ if p, ok := got[0].Payload.(protocol.ChatDonePayload); !ok || p.Content != "assistant reply" {+ t.Fatalf("chat:done payload = %#v, want the full reply", got[0].Payload)+ }+ if p, ok := got[1].Payload.(protocol.TaskMessagePayload); !ok || p.Content != "streamed text" {+ t.Fatalf("task:message payload = %#v, want the full message", got[1].Payload)+ }+ if p, ok := got[2].Payload.(protocol.ChatDonePayload); !ok || p.Content != "assistant reply" {+ t.Fatalf("ownerless chat:done payload = %#v, want the full reply", got[2].Payload)+ }+}+// An invitation conclusion must reach the invitee BOTH ways: the workspace// broadcast keeps admin pending lists fresh, and a targeted send reaches the// invitee's own clients — which are usually bound to a different workspacediff --git a/server/internal/events/bus.go b/server/internal/events/bus.goindex 95e035afb9..12ffb0e69d 100644--- a/server/internal/events/bus.go+++ b/server/internal/events/bus.go@@ -28,6 +28,12 @@ type Event struct {TaskID stringChatSessionID stringChannelReactionTarget *ChannelReactionTarget `json:"-"`++ // ChatSessionOwnerID is the creator of the chat session the event belongs+ // to. A chat session is creator-private, so the realtime layer delivers+ // chat events and chat-task transcript events only to this user, and drops+ // them when it is empty rather than falling back to workspace fanout.+ ChatSessionOwnerID string}// Handler is a function that processes an event.diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex e08bcc2ddc..884ccfe13e 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -2967,6 +2967,11 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {taskIDs[i] = t.ID}}+ if err := h.redactForeignChatTaskContent(r.Context(), requestUserID(r), tasks, resp); err != nil {+ slog.Warn("list agent tasks: resolve chat owners failed", append(logger.RequestAttrs(r), "error", err, "agent_id", id)...)+ writeError(w, http.StatusInternalServerError, "failed to list agent tasks")+ return+ }h.hydrateTaskSupplementMetadata(r.Context(), r, agent.WorkspaceID, tasks, resp)h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))if includeUsage {@@ -3256,11 +3261,18 @@ func (h *Handler) ListWorkspaceAgentTaskSnapshot(w http.ResponseWriter, r *http.}resp := make([]AgentTaskResponse, 0, len(tasks))+ kept := make([]db.AgentTaskQueue, 0, len(tasks))for _, t := range tasks {if _, ok := allowed[uuidToString(t.AgentID)]; !ok {continue}resp = append(resp, taskToResponse(t, workspaceID))+ kept = append(kept, t)+ }+ if err := h.redactForeignChatTaskContent(r.Context(), requestUserID(r), kept, resp); err != nil {+ slog.Warn("agent task snapshot: resolve chat owners failed", append(logger.RequestAttrs(r), "error", err)...)+ writeError(w, http.StatusInternalServerError, "failed to list agent task snapshot")+ return}h.hydrateTaskAttributions(r.Context(), attributionsOf(resp))diff --git a/server/internal/handler/chat_task_privacy.go b/server/internal/handler/chat_task_privacy.gonew file mode 100644index 0000000000..13b4cd016c--- /dev/null+++ b/server/internal/handler/chat_task_privacy.go@@ -0,0 +1,49 @@+package handler++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// A chat session is creator-private, and so is everything its tasks produce:+// the transcript, the reply in result, and the failure text in error. Task+// lists stay workspace-wide because presence and workload views count every+// run, so they keep a foreign chat task's row and drop only its content.++// redactForeignChatTaskContent clears the content of every chat task in resp+// that viewerID did not start. tasks[i] must be the row behind resp[i]. A chat+// task whose session can no longer be resolved is treated as foreign.+func (h *Handler) redactForeignChatTaskContent(ctx context.Context, viewerID string, tasks []db.AgentTaskQueue, resp []AgentTaskResponse) error {+ seen := map[pgtype.UUID]bool{}+ var sessionIDs []pgtype.UUID+ for _, t := range tasks {+ if t.ChatSessionID.Valid && !seen[t.ChatSessionID] {+ seen[t.ChatSessionID] = true+ sessionIDs = append(sessionIDs, t.ChatSessionID)+ }+ }+ if len(sessionIDs) == 0 {+ return nil+ }+ rows, err := h.Queries.ListChatSessionCreators(ctx, sessionIDs)+ if err != nil {+ return err+ }+ owners := make(map[pgtype.UUID]string, len(rows))+ for _, row := range rows {+ owners[row.ID] = uuidToString(row.CreatorID)+ }+ for i, t := range tasks {+ if !t.ChatSessionID.Valid {+ continue+ }+ if owner, ok := owners[t.ChatSessionID]; ok && owner != "" && owner == viewerID {+ continue+ }+ resp[i].Result = nil+ resp[i].Error = nil+ }+ return nil+}diff --git a/server/internal/handler/chat_task_privacy_test.go b/server/internal/handler/chat_task_privacy_test.gonew file mode 100644index 0000000000..f5505e2cc3--- /dev/null+++ b/server/internal/handler/chat_task_privacy_test.go@@ -0,0 +1,129 @@+package handler++import (+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type chatTaskPrivacyFixture struct {+ ownerID string+ agentID string+ chatTaskID string+ issueTaskID string+}++// seedChatTaskPrivacy builds a plain member's agent with a finished chat task+// the member started and a running issue task, both carrying a result and an+// error. The bystander in these tests is testUserID, the workspace owner, so an+// admin role cannot be what decides access.+func seedChatTaskPrivacy(t *testing.T) chatTaskPrivacyFixture {+ t.Helper()+ ownerID := dbfx.User(t, "Chat task owner", "[email protected]")+ dbfx.Member(t, testWorkspaceID, ownerID, "member")+ runtimeID := handlerTestRuntimeID(t)+ agentID := dbfx.Agent(t, "chat task privacy agent", runtimeID, testutil.Cols{"owner_id": ownerID})+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{"creator_id": ownerID})+ chatTaskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "chat_session_id": chatSessionID,+ "status": "completed",+ "completed_at": testutil.Raw("now()"),+ "result": testutil.Raw(`'{"output":"private chat reply"}'::jsonb`),+ "error": "private chat error",+ })+ dbfx.Insert(t, "task_message", testutil.Cols{+ "task_id": chatTaskID,+ "seq": 1,+ "type": "text",+ "content": "private chat transcript",+ })+ issueID := dbfx.Issue(t, "chat task privacy issue", testutil.Cols{"status": "in_progress"})+ issueTaskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ "result": testutil.Raw(`'{"output":"issue output"}'::jsonb`),+ "error": "issue error",+ })+ return chatTaskPrivacyFixture{ownerID: ownerID, agentID: agentID, chatTaskID: chatTaskID, issueTaskID: issueTaskID}+}++func TestListTaskMessagesByUserHidesChatTranscriptFromNonOwner(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ f := seedChatTaskPrivacy(t)+ read := func(userID, taskID string) *testutil.Response {+ req := withURLParam(newRequestAs(userID, http.MethodGet, "/api/tasks/"+taskID+"/messages", nil), "taskId", taskID)+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))+ return testutil.Call(t, testHandler.ListTaskMessagesByUser, req)+ }++ var history []protocol.TaskMessagePayload+ read(f.ownerID, f.chatTaskID).Want(http.StatusOK).JSON(&history)+ if len(history) != 1 || history[0].Content != "private chat transcript" {+ t.Fatalf("owner transcript = %+v, want the one private message", history)+ }+ read(testUserID, f.chatTaskID).Want(http.StatusNotFound)+ read(testUserID, f.issueTaskID).Want(http.StatusOK)+}++func TestAgentTaskListsRedactForeignChatTaskContent(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ f := seedChatTaskPrivacy(t)++ lists := map[string]func(t *testing.T, userID string) []AgentTaskResponse{+ "agent tasks": func(t *testing.T, userID string) []AgentTaskResponse {+ req := withURLParam(newRequestAs(userID, http.MethodGet, "/api/agents/"+f.agentID+"/tasks", nil), "id", f.agentID)+ var tasks []AgentTaskResponse+ testutil.Call(t, testHandler.ListAgentTasks, req).Want(http.StatusOK).JSON(&tasks)+ return tasks+ },+ "workspace snapshot": func(t *testing.T, userID string) []AgentTaskResponse {+ req := newRequestAs(userID, http.MethodGet, "/api/agent-task-snapshot", nil)+ var tasks []AgentTaskResponse+ testutil.Call(t, testHandler.ListWorkspaceAgentTaskSnapshot, req).Want(http.StatusOK).JSON(&tasks)+ return tasks+ },+ }+ for name, list := range lists {+ t.Run(name, func(t *testing.T) {+ byViewer := map[string]map[string]AgentTaskResponse{}+ for _, viewer := range []string{f.ownerID, testUserID} {+ byViewer[viewer] = map[string]AgentTaskResponse{}+ for _, task := range list(t, viewer) {+ byViewer[viewer][task.ID] = task+ }+ for _, id := range []string{f.chatTaskID, f.issueTaskID} {+ if _, ok := byViewer[viewer][id]; !ok {+ t.Fatalf("viewer %s: task %s missing; rows must stay listed for presence", viewer, id)+ }+ }+ }++ own := byViewer[f.ownerID][f.chatTaskID]+ if own.Result == nil || own.Error == nil || *own.Error != "private chat error" {+ t.Fatalf("owner sees chat task result=%v error=%v, want full content", own.Result, own.Error)+ }+ foreign := byViewer[testUserID][f.chatTaskID]+ if foreign.Result != nil || foreign.Error != nil {+ t.Fatalf("non-owner sees chat task result=%v error=%v, want both redacted", foreign.Result, foreign.Error)+ }+ if foreign.ChatSessionID == "" || foreign.Status != "completed" {+ t.Fatalf("non-owner chat row = %+v, want its metadata kept", foreign)+ }+ issue := byViewer[testUserID][f.issueTaskID]+ if issue.Result == nil || issue.Error == nil || *issue.Error != "issue error" {+ t.Fatalf("issue task result=%v error=%v, want it untouched", issue.Result, issue.Error)+ }+ })+ }+}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex cdd04528b1..efb8698f24 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -23,6 +23,7 @@ import ("github.com/multica-ai/multica/server/internal/analytics""github.com/multica-ai/multica/server/internal/auth""github.com/multica-ai/multica/server/internal/daemonws"+ "github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/integrations/slack""github.com/multica-ai/multica/server/internal/issuestatus""github.com/multica-ai/multica/server/internal/logger"@@ -210,9 +211,16 @@ func (h *Handler) requireDaemonTaskAccess(w http.ResponseWriter, r *http.Request// results, messages and credentials, and "any workspace member" must not be// a fallback for them.func (h *Handler) requireDaemonTaskAccessWithWorkspace(w http.ResponseWriter, r *http.Request, taskID string) (db.AgentTaskQueue, string, bool) {+ task, scope, ok := h.requireDaemonTaskAccessWithScope(w, r, taskID)+ return task, scope.WorkspaceID, ok+}++// requireDaemonTaskAccessWithScope is requireDaemonTaskAccessWithWorkspace+// plus the chat session owner, resolved from the same lookup.+func (h *Handler) requireDaemonTaskAccessWithScope(w http.ResponseWriter, r *http.Request, taskID string) (db.AgentTaskQueue, service.TaskScope, bool) {taskUUID, ok := parseUUIDOrBadRequest(w, taskID, "task_id")if !ok {- return db.AgentTaskQueue{}, "", false+ return db.AgentTaskQueue{}, service.TaskScope{}, false}task, err := h.Queries.GetAgentTask(r.Context(), taskUUID)if err != nil {@@ -221,11 +229,11 @@ func (h *Handler) requireDaemonTaskAccessWithWorkspace(w http.ResponseWriter, r// error must not be reported as a deletion.if isNotFound(err) {writeError(w, http.StatusNotFound, "task not found")- return db.AgentTaskQueue{}, "", false+ return db.AgentTaskQueue{}, service.TaskScope{}, false}slog.Warn("get agent task failed", "task_id", taskID, "error", err)writeError(w, http.StatusInternalServerError, "failed to load task")- return db.AgentTaskQueue{}, "", false+ return db.AgentTaskQueue{}, service.TaskScope{}, false}// Same rule as the GetAgentTask branch above, one link further out: the@@ -234,39 +242,40 @@ func (h *Handler) requireDaemonTaskAccessWithWorkspace(w http.ResponseWriter, r// issue / chat session / autopilot leaves us unable to tell whether the// task is reachable, and "I don't know" must not be reported as "deleted"// (MUL-7259 / GH #8272 — the branch #2127 hardened above, missed here).- wsID, err := h.TaskService.ResolveTaskWorkspaceIDChecked(r.Context(), task)+ scope, err := h.TaskService.ResolveTaskScopeChecked(r.Context(), task)if err != nil {slog.Warn("resolve task workspace failed", "task_id", taskID, "error", err)writeError(w, http.StatusInternalServerError, "failed to load task")- return db.AgentTaskQueue{}, "", false+ return db.AgentTaskQueue{}, service.TaskScope{}, false}+ wsID := scope.WorkspaceIDif wsID == "" {writeError(w, http.StatusNotFound, "task not found")- return db.AgentTaskQueue{}, "", false+ return db.AgentTaskQueue{}, service.TaskScope{}, false}if !h.requireDaemonWorkspaceAccess(w, r, wsID) {- return db.AgentTaskQueue{}, "", false+ return db.AgentTaskQueue{}, service.TaskScope{}, false}if !task.RuntimeID.Valid {writeError(w, http.StatusNotFound, "task not found")- return db.AgentTaskQueue{}, "", false+ return db.AgentTaskQueue{}, service.TaskScope{}, false}rt, err := h.getAgentRuntime(r.Context(), obsmetrics.RuntimeLookupSourceDaemonAPI, task.RuntimeID)if err != nil {if isNotFound(err) {writeError(w, http.StatusNotFound, "task not found")- return db.AgentTaskQueue{}, "", false+ return db.AgentTaskQueue{}, service.TaskScope{}, false}slog.Warn("get task runtime failed", "task_id", taskID, "error", err)writeError(w, http.StatusInternalServerError, "failed to load task")- return db.AgentTaskQueue{}, "", false+ return db.AgentTaskQueue{}, service.TaskScope{}, false}if uuidToString(rt.WorkspaceID) != wsID || !daemonRuntimeBindingAllowed(r, rt.DaemonID, rt.OwnerID) {writeError(w, http.StatusNotFound, "task not found")- return db.AgentTaskQueue{}, "", false+ return db.AgentTaskQueue{}, service.TaskScope{}, false}- return task, wsID, true+ return task, scope, true}// verifyDaemonWorkspaceAccess checks workspace access without writing an HTTP error.@@ -5687,7 +5696,7 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {// endpoint fires every 500ms for every running task, and that second// lookup was a whole extra query per batch on the hottest write path in// the system (MUL-6523).- task, wsID, ok := h.requireDaemonTaskAccessWithWorkspace(w, r, taskID)+ task, scope, ok := h.requireDaemonTaskAccessWithScope(w, r, taskID)if !ok {return}@@ -5697,7 +5706,7 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {// quick-create tasks is a product decision, not part of this optimization.workspaceID := ""if task.IssueID.Valid || task.ChatSessionID.Valid {- workspaceID = wsID+ workspaceID = scope.WorkspaceID}// Column-wise parameters for the single batch insert below. Building them@@ -5810,13 +5819,24 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {// per-message loop did. A bare INSERT ... RETURNING has no row-order// guarantee, and subscribers render these events as they arrive, so the// ordering lives in the query rather than in the clients.+ chatSessionID := ""+ if task.ChatSessionID.Valid {+ chatSessionID = uuidToString(task.ChatSessionID)+ }for _, m := range created {// The ordered CTE makes sqlc name the row type after the query// rather than reusing the table model; the columns are the table's,// in order, so the conversion is checked by the compiler and breaks// loudly if the query ever stops returning the whole row.- h.publishTask(protocol.EventTaskMessage, workspaceID, "system", "", taskID,- taskMessageToPayload(db.TaskMessage(m), taskID, uuidToString(task.IssueID)))+ h.Bus.Publish(events.Event{+ Type: protocol.EventTaskMessage,+ WorkspaceID: workspaceID,+ ActorType: "system",+ TaskID: taskID,+ ChatSessionID: chatSessionID,+ ChatSessionOwnerID: scope.ChatSessionOwnerID,+ Payload: taskMessageToPayload(db.TaskMessage(m), taskID, uuidToString(task.IssueID)),+ })}}@@ -6426,7 +6446,7 @@ func (h *Handler) ListTaskMessagesByUser(w http.ResponseWriter, r *http.Request)// 5xx here too: this endpoint does not drive the daemon's interrupt, but// telling a reader "this task does not exist" because the DB blinked is// the same lie, and it trains clients to give up on a retryable error.- wsID, err := h.TaskService.ResolveTaskWorkspaceIDChecked(r.Context(), task)+ scope, err := h.TaskService.ResolveTaskScopeChecked(r.Context(), task)if err != nil {slog.Warn("resolve task workspace failed", "task_id", taskID, "error", err)writeError(w, http.StatusInternalServerError, "failed to load task")@@ -6434,10 +6454,17 @@ func (h *Handler) ListTaskMessagesByUser(w http.ResponseWriter, r *http.Request)}// Mismatch stays a 404 rather than a 403: a task in another workspace must// be indistinguishable from one that does not exist.+ wsID := scope.WorkspaceIDif wsID == "" || wsID != middleware.WorkspaceIDFromContext(r.Context()) {writeError(w, http.StatusNotFound, "task not found")return}+ // A chat task's transcript belongs to the chat session's creator alone;+ // to anyone else it does not exist either.+ if task.ChatSessionID.Valid && (scope.ChatSessionOwnerID == "" || scope.ChatSessionOwnerID != requestUserID(r)) {+ writeError(w, http.StatusNotFound, "task not found")+ return+ }var (messages []db.TaskMessagediff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 308ef074d5..b230119907 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -821,16 +821,19 @@ func (h *Handler) publishTask(eventType, workspaceID, actorType, actorID, taskID})}-// publishChat is publish() plus a ChatSessionID hint so the realtime layer-// can route the event to the per-chat-session scope.+// publishChat is publish() plus the chat session routing hints. actorID must+// be the session's creator: every chat endpoint gates on creator ownership+// before publishing, and the realtime layer delivers the event to that user+// only.func (h *Handler) publishChat(eventType, workspaceID, actorType, actorID, chatSessionID string, payload any) {h.Bus.Publish(events.Event{- Type: eventType,- WorkspaceID: workspaceID,- ActorType: actorType,- ActorID: actorID,- ChatSessionID: chatSessionID,- Payload: payload,+ Type: eventType,+ WorkspaceID: workspaceID,+ ActorType: actorType,+ ActorID: actorID,+ ChatSessionID: chatSessionID,+ ChatSessionOwnerID: actorID,+ Payload: payload,})}diff --git a/server/internal/handler/task_message_batch_test.go b/server/internal/handler/task_message_batch_test.goindex d5050c08dc..7569ffd7a1 100644--- a/server/internal/handler/task_message_batch_test.go+++ b/server/internal/handler/task_message_batch_test.go@@ -236,6 +236,66 @@ func TestReportTaskMessagesPublishesInSeqOrder(t *testing.T) {}}+// A chat task's transcript is the agent's half of a private conversation, so+// its task:message events must name the chat session and its creator for the+// realtime layer to deliver them to that member only. The creator here is not+// the daemon's user, so the owner cannot have come from the request.+func TestReportTaskMessagesStampsChatSessionOwner(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ creatorID := dbfx.User(t, "Chat owner", "[email protected]")+ dbfx.Member(t, testWorkspaceID, creatorID, "member")+ agentID := dbfx.Agent(t, "chat transcript agent", handlerTestRuntimeID(t), testutil.Cols{+ "instructions": "",+ "custom_env": testutil.Raw("'{}'::jsonb"),+ "custom_args": testutil.Raw("'[]'::jsonb"),+ })+ chatSessionID := dbfx.ChatSession(t, agentID, testutil.Cols{"creator_id": creatorID})+ chatTaskID := dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": handlerTestRuntimeID(t),+ "chat_session_id": chatSessionID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ })+ issueTaskID := seedBatchTask(t, "issue transcript")++ sharedBus := testHandler.Bus+ testHandler.Bus = events.New()+ t.Cleanup(func() { testHandler.Bus = sharedBus })+ var mu sync.Mutex+ got := map[string]events.Event{}+ testHandler.Bus.Subscribe(protocol.EventTaskMessage, func(e events.Event) {+ mu.Lock()+ defer mu.Unlock()+ got[e.TaskID] = e+ })++ for _, taskID := range []string{chatTaskID, issueTaskID} {+ testutil.Call(t, testHandler.ReportTaskMessages, batchMessagesRequest(t, taskID, []any{+ map[string]any{"seq": 1, "type": "text", "content": "transcript"},+ })).Want(http.StatusOK)+ }++ mu.Lock()+ defer mu.Unlock()+ chat, ok := got[chatTaskID]+ if !ok {+ t.Fatal("chat task published no task:message")+ }+ if chat.ChatSessionID != chatSessionID || chat.ChatSessionOwnerID != creatorID {+ t.Fatalf("chat task:message hints = session %q owner %q, want %q / %q",+ chat.ChatSessionID, chat.ChatSessionOwnerID, chatSessionID, creatorID)+ }+ issue, ok := got[issueTaskID]+ if !ok {+ t.Fatal("issue task published no task:message")+ }+ if issue.ChatSessionID != "" || issue.ChatSessionOwnerID != "" || issue.WorkspaceID != testWorkspaceID {+ t.Fatalf("issue task:message = %+v, want workspace-scoped without chat hints", issue)+ }+}+// TestCreateTaskMessagesBatchIsAtomic exercises the production query, not a copy// of it: a batch that violates the primary key must persist nothing. This is the// property the single statement buys over the per-message loop, which coulddiff --git a/server/internal/realtime/broadcaster.go b/server/internal/realtime/broadcaster.goindex 058542b07f..bc756e2b90 100644--- a/server/internal/realtime/broadcaster.go+++ b/server/internal/realtime/broadcaster.go@@ -8,6 +8,14 @@ const (ScopeUser = "user"ScopeTask = "task"ScopeChat = "chat"+ // ScopeWorkspaceMember holds one user's connections bound to one+ // workspace (see WorkspaceMemberScopeID). Content private to a member of+ // a workspace goes here rather than to ScopeUser: each of these+ // connections is re-authorized against that workspace on every write, so+ // removal from the workspace stops delivery even while the user stays+ // connected to another workspace. Joined at connect time only; clients+ // cannot subscribe to it.+ ScopeWorkspaceMember = "workspace_member"// ScopeDaemonRuntime routes daemon wakeup frames through the Redis relay.// It is consumed by the daemon WebSocket hub, not by browser clients.ScopeDaemonRuntime = "daemon_runtime"@@ -29,6 +37,12 @@ const (ScopeWecomOutbound = "wecom_outbound")+// WorkspaceMemberScopeID is the ScopeWorkspaceMember room for userID's+// connections to workspaceID.+func WorkspaceMemberScopeID(workspaceID, userID string) string {+ return workspaceID + ":" + userID+}+// Broadcaster is the abstraction every realtime event producer should depend// on instead of *Hub directly.//diff --git a/server/internal/realtime/hub_test.go b/server/internal/realtime/hub_test.goindex ea3dba2918..1c4b527138 100644--- a/server/internal/realtime/hub_test.go+++ b/server/internal/realtime/hub_test.go@@ -183,6 +183,39 @@ func TestClientHandleSubscribeReportsLookupFailure(t *testing.T) {}}+// A workspace-member room carries one member's private content in one+// workspace. A connection joins only its own room, at connect time, and no+// subscribe frame can add another one.+func TestWorkspaceMemberScopeReachesOnlyThatMembersWorkspaceConnection(t *testing.T) {+ hub := NewHub()+ newClient := func(userID, workspaceID string) *Client {+ c := &Client{hub: hub, send: make(chan []byte, 4), userID: userID, workspaceID: workspaceID}+ hub.registerClient(c)+ return c+ }+ owner := newClient("owner", "ws-x")+ ownerElsewhere := newClient("owner", "ws-y")+ peer := newClient("peer", "ws-x")++ peer.handleSubscribe(ScopeWorkspaceMember, WorkspaceMemberScopeID("ws-x", "owner"))+ select {+ case raw := <-peer.send:+ if !strings.Contains(string(raw), "subscribe_error") {+ t.Fatalf("peer subscribe reply = %s, want subscribe_error", raw)+ }+ default:+ t.Fatal("peer subscribe to another member's room was not refused")+ }++ hub.BroadcastToScope(ScopeWorkspaceMember, WorkspaceMemberScopeID("ws-x", "owner"), []byte(`{"type":"chat:done"}`))+ if len(owner.send) != 1 {+ t.Fatalf("owner's ws-x connection got %d frames, want 1", len(owner.send))+ }+ if len(ownerElsewhere.send) != 0 || len(peer.send) != 0 {+ t.Fatalf("frame reached ws-y owner (%d) or peer (%d)", len(ownerElsewhere.send), len(peer.send))+ }+}+// totalClients counts all currently registered clients.func totalClients(hub *Hub) int {hub.mu.RLock()diff --git a/server/internal/realtime/membership.go b/server/internal/realtime/membership.goindex 2c32a1e9d7..270518f9cb 100644--- a/server/internal/realtime/membership.go+++ b/server/internal/realtime/membership.go@@ -55,6 +55,9 @@ func (h *Hub) registerClient(client *Client) {M.ActiveConnections.Add(1)h.subscribe(client, ScopeWorkspace, client.workspaceID)h.subscribe(client, ScopeUser, client.userID)+ if client.workspaceID != "" && client.userID != "" {+ h.subscribe(client, ScopeWorkspaceMember, WorkspaceMemberScopeID(client.workspaceID, client.userID))+ }slog.Info("ws client connected", "workspace_id", client.workspaceID, "user_id", client.userID, "total_clients", total)}diff --git a/server/internal/realtime/sharded_stream_relay_test.go b/server/internal/realtime/sharded_stream_relay_test.goindex 0f1cc87527..1d095bdaab 100644--- a/server/internal/realtime/sharded_stream_relay_test.go+++ b/server/internal/realtime/sharded_stream_relay_test.go@@ -111,6 +111,35 @@ func TestShardedStreamRelayDeliverMessageUsesEnvelopeScope(t *testing.T) {}}+// A member's private content published on another node lands only on that+// member's connections to the same workspace, as it does on the local path.+func TestShardedStreamRelayDeliversWorkspaceMemberScopeToThatWorkspaceOnly(t *testing.T) {+ hub := NewHub()+ newClient := func(userID, workspaceID string) *Client {+ c := &Client{hub: hub, send: make(chan []byte, 4), userID: userID, workspaceID: workspaceID}+ hub.registerClient(c)+ return c+ }+ owner := newClient("owner", "ws-x")+ ownerElsewhere := newClient("owner", "ws-y")+ peer := newClient("peer", "ws-x")+ relay := NewShardedStreamRelay(hub, nil, nil, ShardedStreamRelayConfig{})++ relay.deliverMessage(redis.XMessage{Values: envelopeRedisValues(envelope{+ EventID: "event-1",+ Scope: ScopeWorkspaceMember,+ ScopeID: WorkspaceMemberScopeID("ws-x", "owner"),+ PayloadJSON: `{"type":"chat:done"}`,+ })})++ if len(owner.send) != 1 {+ t.Fatalf("owner's ws-x connection got %d frames, want 1", len(owner.send))+ }+ if len(ownerElsewhere.send) != 0 || len(peer.send) != 0 {+ t.Fatalf("relayed frame reached ws-y owner (%d) or peer (%d)", len(ownerElsewhere.send), len(peer.send))+ }+}+func TestShardedStreamRelayReplayStartIDIsBounded(t *testing.T) {grace := 5 * time.Minuterelay := NewShardedStreamRelay(NewHub(), nil, nil, ShardedStreamRelayConfig{diff --git a/server/internal/service/chat_quick_actions.go b/server/internal/service/chat_quick_actions.goindex c780464831..1cbffd9e76 100644--- a/server/internal/service/chat_quick_actions.go+++ b/server/internal/service/chat_quick_actions.go@@ -269,7 +269,8 @@ func (s *TaskService) SupplementChatQuickActions(ctx context.Context, task db.Agreturn fmt.Errorf("attach chat quick actions: %w", err)}- workspaceID := s.ResolveTaskWorkspaceID(ctx, task)+ scope := s.ResolveTaskScope(ctx, task)+ workspaceID := scope.WorkspaceIDif workspaceID == "" {return nil}@@ -282,12 +283,13 @@ func (s *TaskService) SupplementChatQuickActions(ctx context.Context, task db.Ag}_ = json.Unmarshal(msg.QuickActions, &payload.QuickActions)s.Bus.Publish(events.Event{- Type: protocol.EventChatQuickActions,- WorkspaceID: workspaceID,- ActorType: "system",- ActorID: "",- ChatSessionID: util.UUIDToString(task.ChatSessionID),- Payload: payload,+ Type: protocol.EventChatQuickActions,+ WorkspaceID: workspaceID,+ ActorType: "system",+ ActorID: "",+ ChatSessionID: util.UUIDToString(task.ChatSessionID),+ ChatSessionOwnerID: scope.ChatSessionOwnerID,+ Payload: payload,})return nil}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 18198dd842..4e88c9ff45 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -3575,17 +3575,19 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID}func (s *TaskService) broadcastChatCancelFinalized(ctx context.Context, task db.AgentTaskQueue, payload protocol.ChatCancelFinalizedPayload) {- workspaceID := s.ResolveTaskWorkspaceID(ctx, task)+ scope := s.ResolveTaskScope(ctx, task)+ workspaceID := scope.WorkspaceIDif workspaceID == "" {return}s.Bus.Publish(events.Event{- Type: protocol.EventChatCancelFinalized,- WorkspaceID: workspaceID,- ActorType: "system",- ActorID: "",- ChatSessionID: util.UUIDToString(task.ChatSessionID),- Payload: payload,+ Type: protocol.EventChatCancelFinalized,+ WorkspaceID: workspaceID,+ ActorType: "system",+ ActorID: "",+ ChatSessionID: util.UUIDToString(task.ChatSessionID),+ ChatSessionOwnerID: scope.ChatSessionOwnerID,+ Payload: payload,})}@@ -7574,6 +7576,28 @@ func (s *TaskService) ResolveTaskWorkspaceID(ctx context.Context, task db.AgentT// keeps a task carrying several links working during a partial outage while// still refusing to call an unknown state "not found".func (s *TaskService) ResolveTaskWorkspaceIDChecked(ctx context.Context, task db.AgentTaskQueue) (string, error) {+ scope, err := s.ResolveTaskScopeChecked(ctx, task)+ return scope.WorkspaceID, err+}++// TaskScope is where a task's realtime events belong.+type TaskScope struct {+ WorkspaceID string+ // ChatSessionOwnerID is the chat session creator when the workspace was+ // resolved through the task's chat session, and "" otherwise.+ ChatSessionOwnerID string+}++// ResolveTaskScope is ResolveTaskWorkspaceID plus the chat session owner, read+// from the same chat_session row so chat broadcasts cost no extra query.+func (s *TaskService) ResolveTaskScope(ctx context.Context, task db.AgentTaskQueue) TaskScope {+ scope, _ := s.ResolveTaskScopeChecked(ctx, task)+ return scope+}++// ResolveTaskScopeChecked is ResolveTaskWorkspaceIDChecked plus the chat+// session owner, with the same failure semantics.+func (s *TaskService) ResolveTaskScopeChecked(ctx context.Context, task db.AgentTaskQueue) (TaskScope, error) {// isNotFound is the "genuinely absent" signal; every other error means the// lookup itself did not complete. pgx.ErrNoRows is the only error the// queries below use to say "this row does not exist".@@ -7587,14 +7611,17 @@ func (s *TaskService) ResolveTaskWorkspaceIDChecked(ctx context.Context, task dbif task.IssueID.Valid {issue, err := s.Queries.GetIssue(ctx, task.IssueID)if err == nil {- return util.UUIDToString(issue.WorkspaceID), nil+ return TaskScope{WorkspaceID: util.UUIDToString(issue.WorkspaceID)}, nil}note(err)}if task.ChatSessionID.Valid {cs, err := s.Queries.GetChatSession(ctx, task.ChatSessionID)if err == nil {- return util.UUIDToString(cs.WorkspaceID), nil+ return TaskScope{+ WorkspaceID: util.UUIDToString(cs.WorkspaceID),+ ChatSessionOwnerID: util.UUIDToString(cs.CreatorID),+ }, nil}note(err)}@@ -7603,7 +7630,7 @@ func (s *TaskService) ResolveTaskWorkspaceIDChecked(ctx context.Context, task dbif err == nil {ap, apErr := s.Queries.GetAutopilot(ctx, run.AutopilotID)if apErr == nil {- return util.UUIDToString(ap.WorkspaceID), nil+ return TaskScope{WorkspaceID: util.UUIDToString(ap.WorkspaceID)}, nil}note(apErr)}@@ -7615,16 +7642,17 @@ func (s *TaskService) ResolveTaskWorkspaceIDChecked(ctx context.Context, task db// for the daemon) and silently dropped task:dispatch / task:completed// broadcasts, which is why quick-create tasks appeared stuck queued.if qc, ok := s.parseQuickCreateContext(task); ok {- return qc.WorkspaceID, nil+ return TaskScope{WorkspaceID: qc.WorkspaceID}, nil}if lookupErr != nil {- return "", fmt.Errorf("resolve task workspace: %w", lookupErr)+ return TaskScope{}, fmt.Errorf("resolve task workspace: %w", lookupErr)}- return "", nil+ return TaskScope{}, nil}func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQueue, msg *db.ChatMessage, quickActionsPending bool) {- workspaceID := s.ResolveTaskWorkspaceID(ctx, task)+ scope := s.ResolveTaskScope(ctx, task)+ workspaceID := scope.WorkspaceIDif workspaceID == "" {return}@@ -7648,12 +7676,13 @@ func (s *TaskService) broadcastChatDone(ctx context.Context, task db.AgentTaskQu}}s.Bus.Publish(events.Event{- Type: protocol.EventChatDone,- WorkspaceID: workspaceID,- ActorType: "system",- ActorID: "",- ChatSessionID: util.UUIDToString(task.ChatSessionID),- Payload: payload,+ Type: protocol.EventChatDone,+ WorkspaceID: workspaceID,+ ActorType: "system",+ ActorID: "",+ ChatSessionID: util.UUIDToString(task.ChatSessionID),+ ChatSessionOwnerID: scope.ChatSessionOwnerID,+ Payload: payload,})}diff --git a/server/internal/service/task_cancel_finalize_test.go b/server/internal/service/task_cancel_finalize_test.goindex a8c72bd7b9..610b9707c6 100644--- a/server/internal/service/task_cancel_finalize_test.go+++ b/server/internal/service/task_cancel_finalize_test.go@@ -22,6 +22,7 @@ func newCancelFinalizePool(t *testing.T) *pgxpool.Pool {type cancelFinalizeFixture struct {pool *pgxpool.PoolworkspaceID string+ creatorID stringagentID stringchatSessionID stringtaskID string@@ -133,6 +134,7 @@ func createCancelFinalizeFixture(t *testing.T, ctx context.Context, pool *pgxpooreturn cancelFinalizeFixture{pool: pool,workspaceID: workspaceID,+ creatorID: userID,agentID: agentID,chatSessionID: chatSessionID,taskID: taskID,@@ -381,6 +383,9 @@ func TestFinalizeDeferredCancelledChat_StillEmpty_RestoresDraft(t *testing.T) {if payload.ChatSessionID != f.chatSessionID {t.Errorf("chat_session_id = %q, want %q", payload.ChatSessionID, f.chatSessionID)}+ if evts[0].ChatSessionOwnerID != f.creatorID {+ t.Errorf("owner = %q, want session creator %q (realtime delivers only to the owner)", evts[0].ChatSessionOwnerID, f.creatorID)+ }}// The recoverability guarantee behind the restored outcome: the draft-restorediff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 71c12593e0..9ea6a1be4c 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -2295,6 +2295,38 @@ func (q *Queries) ListChatMessagesPageForChannelContext(ctx context.Context, argreturn items, nil}+const listChatSessionCreators = `-- name: ListChatSessionCreators :many+SELECT id, creator_id FROM chat_session+WHERE id = ANY($1::uuid[])+`++type ListChatSessionCreatorsRow struct {+ ID pgtype.UUID `json:"id"`+ CreatorID pgtype.UUID `json:"creator_id"`+}++// Owners of a page of chat tasks, so task lists can hide the content of chat+// tasks the viewer did not start.+func (q *Queries) ListChatSessionCreators(ctx context.Context, ids []pgtype.UUID) ([]ListChatSessionCreatorsRow, error) {+ rows, err := q.db.Query(ctx, listChatSessionCreators, ids)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListChatSessionCreatorsRow{}+ for rows.Next() {+ var i ListChatSessionCreatorsRow+ if err := rows.Scan(&i.ID, &i.CreatorID); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listChatSessionsByCreator = `-- name: ListChatSessionsByCreator :manySELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id, cs.explicitly_created_at,(SELECT count(*) FROM chat_message mdiff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex 8635a8dc09..cbd6f28c3c 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -19,6 +19,12 @@ WHERE id = $1;SELECT * FROM chat_sessionWHERE id = $1 AND workspace_id = $2;+-- name: ListChatSessionCreators :many+-- Owners of a page of chat tasks, so task lists can hide the content of chat+-- tasks the viewer did not start.+SELECT id, creator_id FROM chat_session+WHERE id = ANY(@ids::uuid[]);+-- name: GetPublicChatSessionInWorkspace :one-- A channel command is a durable control-plane record, not a public chat turn.-- Channel-created sessions therefore become public only after they contain a