Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5870: fix(chat): hide channel issue commands from Chat
YYClaw318d51377f20
diff --git a/apps/docs/content/docs/channels.ja.mdx b/apps/docs/content/docs/channels.ja.mdxindex 65852cdc81..30afa8ef52 100644--- a/apps/docs/content/docs/channels.ja.mdx+++ b/apps/docs/content/docs/channels.ja.mdx@@ -43,6 +43,8 @@ WeCom が現在扱えるのはテキストメッセージのみです。音声Bot を @メンションしていないチャンネルメッセージは、エージェントをトリガーせず、会話コンテキストにも追加されません。+通常のメッセージはこの流れで処理されます。`/issue` はコマンドであり、チャットのターンではありません。Multica は元のプラットフォームに結果を返しますが、コマンド自体は Multica Chat に追加しません。Slack のネイティブスラッシュコマンドは、独立した非同期のタスク作成フローで処理されます。+## セッションの分離- Feishu/Lark はチャットごとにセッションを分けます。同じチャットの後続メッセージは同じセッションを継続します。diff --git a/apps/docs/content/docs/channels.ko.mdx b/apps/docs/content/docs/channels.ko.mdxindex d8a0725201..8eac47d8ed 100644--- a/apps/docs/content/docs/channels.ko.mdx+++ b/apps/docs/content/docs/channels.ko.mdx@@ -43,6 +43,8 @@ WeCom은 현재 텍스트 메시지만 처리합니다. 음성, 이미지, 파Bot을 @멘션하지 않은 채널 메시지는 에이전트를 트리거하지 않으며 대화 컨텍스트에도 추가되지 않습니다.+일반 메시지는 위 흐름으로 처리됩니다. `/issue`는 명령이며 채팅 turn이 아닙니다. Multica는 원래 플랫폼에 처리 결과를 보내지만 명령 자체는 Multica Chat에 추가하지 않습니다. Slack의 기본 slash 명령은 별도의 비동기 태스크 생성 흐름으로 처리됩니다.+## 대화 격리- Feishu/Lark는 채팅별로 대화를 구분하며 같은 채팅의 후속 메시지는 기존 대화를 이어갑니다.diff --git a/apps/docs/content/docs/channels.mdx b/apps/docs/content/docs/channels.mdxindex ee8550d424..936cebb438 100644--- a/apps/docs/content/docs/channels.mdx+++ b/apps/docs/content/docs/channels.mdx@@ -43,6 +43,8 @@ Step-by-step guides:Channel messages that don't @-mention the Bot never trigger the agent and are not added to its conversation context.+Ordinary messages follow this flow. `/issue` is a command, not a chat turn: Multica posts the result back to the originating platform but does not add the command to Multica Chat. Slack's native slash command continues through its separate asynchronous issue-creation flow.+## Session isolation- Feishu/Lark separates sessions by chat; later messages in the same chat continue the same session.diff --git a/apps/docs/content/docs/channels.zh.mdx b/apps/docs/content/docs/channels.zh.mdxindex 13ae8c748f..c71d8afb73 100644--- a/apps/docs/content/docs/channels.zh.mdx+++ b/apps/docs/content/docs/channels.zh.mdx@@ -43,6 +43,8 @@ import { Callout } from "fumadocs-ui/components/callout";没有 @ Bot 的频道消息不会触发智能体,也不会被加入它的对话上下文。+普通消息按上述流程处理。`/issue` 是命令,不是对话轮次:Multica 会在原平台返回处理结果,但不会把命令加入 Multica Chat。Slack 原生 slash 命令仍按独立的异步创建任务流程处理。+## 会话隔离- 飞书/Lark 按聊天区分会话;同一个聊天中的后续消息会继续原会话。diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdxindex 8ac0da4c17..a98da64c67 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.ja.mdx@@ -74,7 +74,7 @@ DingTalk にはネイティブの入力中/リアクションのインジケ| **Bot に DM** | ワークスペースメンバーが 1:1 チャットで Bot に直接メッセージを送ります。会話はそのエージェントとの Multica [chat](/chat) セッションになり、すべてのメッセージが読み取られます。 || **グループで @ メンション** | Bot をグループに追加し、@ メンションします。読み取られるのはメンションしたメッセージだけで、Bot はグループ全体を聞いているわけではありません。 || **画像を送る** | DM の画像も、グループで @ メンションと一緒に送った画像も、会話に入りエージェントが見られるようになります——PNG・JPEG・GIF・WebP・BMP に対応し、1 メッセージあたり最大 4 枚、1 枚あたり 10 MB までです。各画像は Multica のストレージにコピーされるため、DingTalk の一時リンクが失効した後も会話の中に表示され続けます。`/issue` と一緒に送った画像は、チャットの turn ではなく作成されたイシューに添付されます。ファイルと音声には対応していません。 |-| **`/issue` コマンド** | `/issue <タイトル>` で始めると、入力内容からあなた名義の Multica イシューを直接かつ同期的に作成し、同じ会話へ ID とタイトルを返します。続く行は説明になります。同じ DingTalk メッセージの画像は、作成したイシューに添付されます。 |+| **`/issue` コマンド** | `/issue <タイトル>` で始めると、入力内容からあなた名義の Multica タスクを直接かつ同期的に作成し、同じ会話へ ID とタイトルを返します。続く行は説明になります。同じ DingTalk メッセージの画像は、作成したタスクに添付されます。コマンド自体は Multica Chat に表示されず、作成したタスクが Multica に記録される処理結果になります。 || **`/new` コマンド** | `/new <あなたのメッセージ>` で始めると、そのメッセージを過去の文脈なしで実行します。`/new` だけを送ると、同じ fresh-start の意図が次の空でないメッセージに適用され、空の turn は作られません。既存の会話履歴はそのまま残ります。 || **返信** | エージェントの回答は、同じ 1:1 チャットまたはグループに投稿し返されます。 |diff --git a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdxindex baef9dab1b..b8a15d03bf 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.ko.mdx@@ -74,7 +74,7 @@ DingTalk에는 기본 입력 중 / 반응 표시기가 없으므로 — Slack과| **봇에게 DM** | 워크스페이스 멤버가 1:1 채팅에서 봇에게 직접 메시지를 보냅니다. 그 대화는 에이전트와의 Multica [chat](/chat) 세션이 되며, 모든 메시지를 읽습니다. || **그룹에서 `@`-멘션** | 봇을 그룹에 추가하고 `@`로 멘션하세요. 멘션한 메시지만 읽으며, 봇이 그룹 전체를 듣지는 않습니다. || **이미지 보내기** | DM의 이미지, 또는 그룹에서 `@`-멘션과 함께 보낸 이미지는 대화에 들어가 에이전트가 볼 수 있습니다 — PNG, JPEG, GIF, WebP, BMP를 지원하며, 메시지당 최대 4장, 장당 10 MB까지입니다. 각 이미지는 Multica 스토리지로 복사되므로, DingTalk의 임시 링크가 만료된 뒤에도 대화에서 계속 보입니다. `/issue`와 함께 보낸 이미지는 채팅 turn이 아니라 생성된 이슈에 첨부됩니다. 파일과 음성은 지원하지 않습니다. |-| **`/issue` 명령** | `/issue <제목>`으로 시작하면 입력 내용에서 당신 이름의 Multica 이슈를 직접 동기적으로 만들고 같은 대화에 ID와 제목을 돌려줍니다. 다음 줄은 설명이 됩니다. 같은 DingTalk 메시지의 이미지는 생성된 이슈에 첨부됩니다. |+| **`/issue` 명령** | `/issue <제목>`으로 시작하면 입력 내용에서 당신 이름의 Multica 태스크를 직접 동기적으로 만들고 같은 대화에 ID와 제목을 돌려줍니다. 다음 줄은 설명이 됩니다. 같은 DingTalk 메시지의 이미지는 생성된 태스크에 첨부됩니다. 명령 자체는 Multica Chat에 표시되지 않으며 생성된 태스크가 Multica에 기록되는 처리 결과입니다. || **`/new` 명령** | `/new <당신의 메시지>`로 시작하면 그 메시지를 이전 대화 맥락 없이 실행합니다. `/new`만 보내면 같은 fresh-start 의도가 다음 비어 있지 않은 메시지에 적용되며 빈 turn은 만들어지지 않습니다. 기존 대화 기록은 그대로 유지됩니다. || **답변** | 에이전트의 답변은 같은 1:1 채팅 또는 그룹으로 다시 게시됩니다. |diff --git a/apps/docs/content/docs/dingtalk-bot-integration.mdx b/apps/docs/content/docs/dingtalk-bot-integration.mdxindex 1f45c0a774..d97f61cd8c 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.mdx@@ -74,7 +74,7 @@ Setting this up for **multiple agents**? Repeat the whole flow once per agent| **DM the bot** | A workspace member messages the bot in a 1:1 chat. The conversation becomes a Multica [chat](/chat) session with the agent; every message is read. || **@-mention in a group** | Add the bot to the group and @-mention it. Only the mentioning message is read — the bot does not listen to the whole group. || **Send images** | Images in a DM, or sent alongside a group @-mention, land in the conversation for the agent to see — PNG, JPEG, GIF, WebP, or BMP, up to 4 images per message and 10 MB each. Each image is copied into Multica storage, so it stays visible in the chat after DingTalk's temporary link expires. Images sent with `/issue` go to the created issue instead of the chat turn. Files and voice messages aren't supported. |-| **`/issue` command** | Starting a message with `/issue <title>` creates a Multica issue directly from your input, attributed to you, and posts the issue ID and title back into the same conversation. Put the description on following lines. Images sent in the same DingTalk message are attached to the created issue. |+| **`/issue` command** | Starting a message with `/issue <title>` creates a Multica issue directly from your input, attributed to you, and posts the issue ID and title back into the same conversation. Put the description on following lines. Images sent in the same DingTalk message are attached to the created issue. The command itself does not appear in Multica Chat; the created issue is the result recorded in Multica. || **`/new` command** | Starting a message with `/new <your message>` runs that message without prior conversation context. Sending `/new` by itself records the same fresh-start intent for your next non-empty message without creating an empty turn. The conversation history remains intact. || **Reply** | The agent's answer is posted back into the same 1:1 chat or group. |diff --git a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdxindex 933a128b25..cee1f54950 100644--- a/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx+++ b/apps/docs/content/docs/dingtalk-bot-integration.zh.mdx@@ -74,7 +74,7 @@ import { Callout } from "fumadocs-ui/components/callout";| **私聊 Bot** | 工作区成员在单聊里直接给 Bot 发消息。这段对话会成为该智能体的一个 Multica [chat](/chat) 会话;每一条消息都会被读取。 || **群里 @ 它** | 把 Bot 加进群再 @ 它。只有 @ 它的那条消息会被读取——Bot 不会监听整个群。 || **发图片** | 单聊里的图片、或群里随 @ 一起发的图片,都会进入对话让智能体看到——支持 PNG、JPEG、GIF、WebP、BMP,每条消息最多 4 张、每张不超过 10 MB。每张图片都会复制进 Multica 存储,所以钉钉的临时链接过期后,它在对话里依然可见。随 `/issue` 一起发送的图片会改为附到新建的 issue 上,而不是这条聊天消息。文件和语音不支持。 |-| **`/issue` 命令** | 以 `/issue <标题>` 开头,会按输入直接、同步地以你的身份创建 Multica issue,并在原对话中返回 issue 编号和标题;后续行会作为描述。同一条钉钉消息中的图片会附到新建的 issue。 |+| **`/issue` 命令** | 以 `/issue <标题>` 开头,会按输入直接、同步地以你的身份创建 Multica 任务,并在原对话中返回任务编号和标题;后续行会作为描述。同一条钉钉消息中的图片会附到新建任务中。这条命令不会出现在 Multica Chat;新建任务是 Multica 中记录的处理结果。 || **`/new` 命令** | 以 `/new <你的消息>` 开头,会让这条消息在不带旧上下文的情况下运行。单独发送 `/new` 会把同样的 fresh 意图留给下一条非空消息,不会创建空 turn;已有对话记录保持不变。 || **回复** | 智能体的答复会被发回同一个单聊或群里。 |diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex a492c4af0e..a36ad83732 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -285,6 +285,28 @@ func (h *Handler) gateChatSessionForUser(w http.ResponseWriter, r *http.Request,return session, true}+// gatePublicChatSessionForUser adds the member-visible projection boundary to+// the normal ownership and private-agent checks. Internal channel commands stay+// durable, but a session containing only those commands is not a public Chat.+// Cleanup and recovery operations keep using the lower-level ownership gates+// so an empty bound session can still be archived or deleted and a member's+// own cancelled draft is never stranded. Every ordinary Chat interaction uses+// this gate so a cached hidden session ID cannot resurrect a command-only Chat.+func (h *Handler) gatePublicChatSessionForUser(w http.ResponseWriter, r *http.Request, userID, workspaceID, sessionID string) (db.ChatSession, bool) {+ session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ if !ok {+ return db.ChatSession{}, false+ }+ if _, err := h.Queries.GetPublicChatSessionInWorkspace(r.Context(), db.GetPublicChatSessionInWorkspaceParams{+ ID: session.ID,+ WorkspaceID: session.WorkspaceID,+ }); err != nil {+ writeError(w, http.StatusNotFound, "chat session not found")+ return db.ChatSession{}, false+ }+ return session, true+}+func (h *Handler) GetChatSession(w http.ResponseWriter, r *http.Request) {userID, ok := requireUserID(w, r)if !ok {@@ -293,7 +315,7 @@ func (h *Handler) GetChatSession(w http.ResponseWriter, r *http.Request) {workspaceID := ctxWorkspaceID(r.Context())sessionID := chi.URLParam(r, "sessionId")- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}@@ -331,7 +353,7 @@ func (h *Handler) UpdateChatSession(w http.ResponseWriter, r *http.Request) {return}- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}@@ -448,7 +470,7 @@ func (h *Handler) SetChatSessionPinned(w http.ResponseWriter, r *http.Request) {return}- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}@@ -738,7 +760,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {// workspace role (or the agent's owner) may have changed since — keep// stale sessions from being a back-door into a private agent the user// can no longer reach. Agent senders bypass to preserve A2A collaboration.- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}@@ -772,7 +794,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {}// Re-run the INVOKE gate on every send, not just the softer view gate in- // gateChatSessionForUser (MUL-4525). canAccessPrivateAgent lets a workspace+ // gatePublicChatSessionForUser (MUL-4525). canAccessPrivateAgent lets a workspace// admin keep reading a transcript, but sending a message enqueues a run and// must satisfy canInvokeAgent — which has no admin bypass. A session created// while the user could invoke the agent must stop enqueuing work the instant@@ -947,7 +969,7 @@ func (h *Handler) RegenerateChatQuickActions(w http.ResponseWriter, r *http.RequworkspaceID := ctxWorkspaceID(r.Context())sessionID := chi.URLParam(r, "sessionId")- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}@@ -967,7 +989,7 @@ func (h *Handler) RegenerateChatQuickActions(w http.ResponseWriter, r *http.Requ// The refresh no longer runs the agent, but it is still a user-triggered// spend against that agent's conversation, so it keeps clearing the same// INVOKE gate as a send (MUL-4525) rather than the softer view gate in- // gateChatSessionForUser. Deliberately NOT relaxed as a side effect of+ // gatePublicChatSessionForUser. Deliberately NOT relaxed as a side effect of// moving generation server-side.actorType, actorID := h.resolveActor(r, userID, workspaceID)if !h.canInvokeAgent(r.Context(), agent, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID) {@@ -1023,7 +1045,7 @@ func (h *Handler) ListChatMessages(w http.ResponseWriter, r *http.Request) {workspaceID := ctxWorkspaceID(r.Context())sessionID := chi.URLParam(r, "sessionId")- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}@@ -1056,7 +1078,7 @@ func (h *Handler) ListChatMessagesPage(w http.ResponseWriter, r *http.Request) {workspaceID := ctxWorkspaceID(r.Context())sessionID := chi.URLParam(r, "sessionId")- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}@@ -1156,7 +1178,7 @@ func (h *Handler) MarkChatSessionRead(w http.ResponseWriter, r *http.Request) {workspaceID := ctxWorkspaceID(r.Context())sessionID := chi.URLParam(r, "sessionId")- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}@@ -1472,7 +1494,7 @@ func (h *Handler) GetPendingChatTask(w http.ResponseWriter, r *http.Request) {workspaceID := ctxWorkspaceID(r.Context())sessionID := chi.URLParam(r, "sessionId")- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}@@ -1526,7 +1548,7 @@ func (h *Handler) PrioritizeQueuedChatTask(w http.ResponseWriter, r *http.Requesreturn}- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}@@ -1598,7 +1620,7 @@ func (h *Handler) ClearQueuedChatTasks(w http.ResponseWriter, r *http.Request) {}workspaceID := ctxWorkspaceID(r.Context())sessionID := chi.URLParam(r, "sessionId")- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, sessionID)+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, sessionID)if !ok {return}diff --git a/server/internal/handler/chat_channel_command_visibility_test.go b/server/internal/handler/chat_channel_command_visibility_test.gonew file mode 100644index 0000000000..b9e591178c--- /dev/null+++ b/server/internal/handler/chat_channel_command_visibility_test.go@@ -0,0 +1,213 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "net/url"+ "testing"+ "time"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func insertChatVisibilityMessage(t *testing.T, sessionID, content, messageKind string, channelIngested bool, createdAt time.Time) {+ t.Helper()+ if _, err := testPool.Exec(context.Background(), `+ INSERT INTO chat_message (+ chat_session_id, role, content, message_kind, channel_ingested, created_at+ )+ VALUES ($1, 'user', $2, $3, $4, $5)+ `, sessionID, content, messageKind, channelIngested, createdAt); err != nil {+ t.Fatalf("insert chat visibility message %q: %v", content, err)+ }+}++func TestChannelCommandVisibility_MessageListsExcludeCommandsBeforePagination(t *testing.T) {+ agentID := createHandlerTestAgent(t, "ChannelCommandMessageVisibilityAgent", []byte("[]"))+ sessionID := createHandlerTestChatSession(t, agentID)+ base := time.Date(2026, 8, 7, 1, 0, 0, 0, time.UTC)++ insertChatVisibilityMessage(t, sessionID, "visible oldest", "message", true, base)+ insertChatVisibilityMessage(t, sessionID, "/issue hidden oldest", "channel_command", true, base.Add(time.Second))+ insertChatVisibilityMessage(t, sessionID, "visible middle", "message", true, base.Add(2*time.Second))+ insertChatVisibilityMessage(t, sessionID, "/issue hidden newest", "channel_command", true, base.Add(3*time.Second))+ insertChatVisibilityMessage(t, sessionID, "visible newest", "message", true, base.Add(4*time.Second))++ legacyReq := httptest.NewRequest(http.MethodGet, "/api/chat/sessions/"+sessionID+"/messages", nil)+ legacyReq.Header.Set("X-User-ID", testUserID)+ legacyReq = withURLParam(legacyReq, "sessionId", sessionID)+ legacyReq = withChatTestWorkspaceCtx(t, legacyReq)+ legacyW := httptest.NewRecorder()+ testHandler.ListChatMessages(legacyW, legacyReq)+ if legacyW.Code != http.StatusOK {+ t.Fatalf("ListChatMessages: expected 200, got %d: %s", legacyW.Code, legacyW.Body.String())+ }+ var legacy []ChatMessageResponse+ if err := json.Unmarshal(legacyW.Body.Bytes(), &legacy); err != nil {+ t.Fatalf("decode legacy messages: %v", err)+ }+ if len(legacy) != 3 || legacy[0].Content != "visible oldest" || legacy[1].Content != "visible middle" || legacy[2].Content != "visible newest" {+ t.Fatalf("legacy visible messages = %#v", legacy)+ }++ latest := fetchChatMessagesPageForTest(t, sessionID, url.Values{"limit": {"2"}})+ if len(latest.Messages) != 2 || latest.Messages[0].Content != "visible middle" || latest.Messages[1].Content != "visible newest" {+ t.Fatalf("latest visible page = %#v", latest)+ }+ if !latest.HasMore || latest.NextCursor == nil {+ t.Fatalf("latest visible page metadata = %#v", latest)+ }++ older := fetchChatMessagesPageForTest(t, sessionID, url.Values{+ "limit": {"2"},+ "before_created_at": {latest.NextCursor.CreatedAt},+ "before_id": {latest.NextCursor.ID},+ })+ if len(older.Messages) != 1 || older.Messages[0].Content != "visible oldest" || older.HasMore || older.NextCursor != nil {+ t.Fatalf("older visible page = %#v", older)+ }+}++func TestChannelCommandVisibility_SessionProjectionUsesPublicMessages(t *testing.T) {+ agentID := createHandlerTestAgent(t, "ChannelCommandSessionVisibilityAgent", []byte("[]"))+ webEmptySessionID := createHandlerTestChatSession(t, agentID)+ commandOnlySessionID := createHandlerTestChatSession(t, agentID)+ mixedSessionID := createHandlerTestChatSession(t, agentID)+ newerPublicSessionID := createHandlerTestChatSession(t, agentID)+ base := time.Date(2026, 8, 7, 2, 0, 0, 0, time.UTC)++ insertChatVisibilityMessage(t, commandOnlySessionID, "/issue hidden only", "channel_command", true, base.Add(3*time.Second))+ insertChatVisibilityMessage(t, mixedSessionID, "mixed public", "message", true, base)+ insertChatVisibilityMessage(t, mixedSessionID, "/issue hidden after public", "channel_command", true, base.Add(4*time.Second))+ insertChatVisibilityMessage(t, newerPublicSessionID, "newer public", "message", true, base.Add(2*time.Second))++ active, err := testHandler.Queries.ListChatSessionsByCreator(context.Background(), db.ListChatSessionsByCreatorParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ CreatorID: parseUUID(testUserID),+ })+ if err != nil {+ t.Fatalf("list active chat sessions: %v", err)+ }+ activeIndex := make(map[string]int, len(active))+ for i, row := range active {+ activeIndex[uuidToString(row.ID)] = i+ }+ if _, ok := activeIndex[commandOnlySessionID]; ok {+ t.Fatalf("command-only session %s is publicly listed", commandOnlySessionID)+ }+ if _, ok := activeIndex[webEmptySessionID]; !ok {+ t.Fatalf("empty web-created session %s must remain publicly listed", webEmptySessionID)+ }+ mixedIndex, mixedOK := activeIndex[mixedSessionID]+ newerIndex, newerOK := activeIndex[newerPublicSessionID]+ if !mixedOK || !newerOK {+ t.Fatalf("public sessions missing: mixed=%v newer=%v", mixedOK, newerOK)+ }+ if newerIndex >= mixedIndex {+ t.Fatalf("hidden command reordered mixed session: newer index=%d mixed index=%d", newerIndex, mixedIndex)+ }+ for _, row := range active {+ if uuidToString(row.ID) == mixedSessionID && (row.LastMessageContent != "mixed public" || row.LastMessageKind != "message") {+ t.Fatalf("mixed session preview = content %q kind %q", row.LastMessageContent, row.LastMessageKind)+ }+ }++ if _, err := testPool.Exec(context.Background(), `UPDATE chat_session SET status = 'archived' WHERE id = $1`, commandOnlySessionID); err != nil {+ t.Fatalf("archive command-only session: %v", err)+ }+ all, err := testHandler.Queries.ListAllChatSessionsByCreator(context.Background(), db.ListAllChatSessionsByCreatorParams{+ WorkspaceID: parseUUID(testWorkspaceID),+ CreatorID: parseUUID(testUserID),+ })+ if err != nil {+ t.Fatalf("list all chat sessions: %v", err)+ }+ for _, row := range all {+ if uuidToString(row.ID) == commandOnlySessionID {+ t.Fatalf("command-only session %s is publicly listed in status=all", commandOnlySessionID)+ }+ }+}++func TestChannelCommandVisibility_CommandOnlySessionRejectsChatInteractionsButAllowsCleanup(t *testing.T) {+ agentID := createHandlerTestAgent(t, "ChannelCommandDirectAccessAgent", []byte("[]"))+ commandOnlySessionID := createHandlerTestChatSession(t, agentID)+ webEmptySessionID := createHandlerTestChatSession(t, agentID)+ insertChatVisibilityMessage(t, commandOnlySessionID, "/issue hidden", "channel_command", true, time.Now())++ get := func(sessionID string) *httptest.ResponseRecorder {+ t.Helper()+ req := httptest.NewRequest(http.MethodGet, "/api/chat/sessions/"+sessionID, nil)+ req.Header.Set("X-User-ID", testUserID)+ req = withURLParam(req, "sessionId", sessionID)+ req = withChatTestWorkspaceCtx(t, req)+ w := httptest.NewRecorder()+ testHandler.GetChatSession(w, req)+ return w+ }++ if w := get(commandOnlySessionID); w.Code != http.StatusNotFound {+ t.Fatalf("command-only session: expected 404, got %d: %s", w.Code, w.Body.String())+ }+ if w := get(webEmptySessionID); w.Code != http.StatusOK {+ t.Fatalf("empty web-created session: expected 200, got %d: %s", w.Code, w.Body.String())+ }++ request := func(method, path string, body any, handler http.HandlerFunc) *httptest.ResponseRecorder {+ t.Helper()+ req := newRequest(method, path, body)+ req.Header.Set("X-User-ID", testUserID)+ req = withURLParam(req, "sessionId", commandOnlySessionID)+ req = withChatTestWorkspaceCtx(t, req)+ w := httptest.NewRecorder()+ handler(w, req)+ return w+ }++ if w := request(+ http.MethodPatch,+ "/api/chat/sessions/"+commandOnlySessionID,+ map[string]any{"title": "must not be renamed"},+ testHandler.UpdateChatSession,+ ); w.Code != http.StatusNotFound {+ t.Fatalf("rename command-only session: expected 404, got %d: %s", w.Code, w.Body.String())+ }+ if w := request(+ http.MethodPost,+ "/api/chat/sessions/"+commandOnlySessionID+"/messages",+ map[string]any{"content": "must not resurrect the chat"},+ testHandler.SendChatMessage,+ ); w.Code != http.StatusNotFound {+ t.Fatalf("send to command-only session: expected 404, got %d: %s", w.Code, w.Body.String())+ }+ var publicMessages int+ if err := testPool.QueryRow(context.Background(), `+ SELECT count(*) FROM chat_message+ WHERE chat_session_id = $1 AND message_kind != 'channel_command'+ `, commandOnlySessionID).Scan(&publicMessages); err != nil {+ t.Fatalf("count public messages after rejected send: %v", err)+ }+ if publicMessages != 0 {+ t.Fatalf("rejected send created %d public messages", publicMessages)+ }++ // Archive remains reachable for stale clients so they can sever a channel+ // binding and clean up a session that the public Chat projection hides.+ if w := request(+ http.MethodPatch,+ "/api/chat/sessions/"+commandOnlySessionID+"/archive",+ map[string]any{"archived": true},+ testHandler.SetChatSessionArchived,+ ); w.Code != http.StatusOK {+ t.Fatalf("archive command-only session: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var status string+ if err := testPool.QueryRow(context.Background(), `SELECT status FROM chat_session WHERE id = $1`, commandOnlySessionID).Scan(&status); err != nil {+ t.Fatalf("load archived command-only session: %v", err)+ }+ if status != "archived" {+ t.Fatalf("command-only session status = %q, want archived", status)+ }+}diff --git a/server/internal/handler/file.go b/server/internal/handler/file.goindex d368972fdc..6bf47fe012 100644--- a/server/internal/handler/file.go+++ b/server/internal/handler/file.go@@ -480,10 +480,10 @@ func (h *Handler) UploadFile(w http.ResponseWriter, r *http.Request) {params.CommentID = comment.ID}if chatSessionID := r.FormValue("chat_session_id"); chatSessionID != "" {- // Re-use the existing private-agent gate so the user can still- // reach this session — covers role downgrade and agent- // visibility flips. The gate writes 4xx on failure.- session, ok := h.gateChatSessionForUser(w, r, userID, workspaceID, chatSessionID)+ // Require the member-visible Chat projection as well as private-agent+ // access. A cached command-only session id must not accept uploads that+ // could later be attached by an old client and resurrect the session.+ session, ok := h.gatePublicChatSessionForUser(w, r, userID, workspaceID, chatSessionID)if !ok {return}diff --git a/server/internal/handler/mika_onboarding.go b/server/internal/handler/mika_onboarding.goindex 0e5cb3608a..fb155dcf47 100644--- a/server/internal/handler/mika_onboarding.go+++ b/server/internal/handler/mika_onboarding.go@@ -59,7 +59,7 @@ func (h *Handler) StartMikaOnboarding(w http.ResponseWriter, r *http.Request) {return}- session, ok := h.gateChatSessionForUser(+ session, ok := h.gatePublicChatSessionForUser(w,r,userID,@@ -90,7 +90,7 @@ func (h *Handler) StartMikaOnboarding(w http.ResponseWriter, r *http.Request) {// the *first* member's agent — so an owner check would 403 the exact race// that handler's advisory lock exists to survive: the loser gets a valid// Mika, opens a session, and then cannot start onboarding at all. The two- // gates that matter already ran: gateChatSessionForUser proved the session+ // gates that matter already ran: gatePublicChatSessionForUser proved the session// is the caller's, and canInvokeAgent below proves they may invoke Mika.if agent.ArchivedAt.Valid {writeError(w, http.StatusConflict, "chat agent is archived")diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.goindex 88e38ed30f..90c82b56af 100644--- a/server/internal/integrations/channel/engine/session.go+++ b/server/internal/integrations/channel/engine/session.go@@ -303,9 +303,9 @@ type BindMediaInput struct {MediaRefs []channel.MediaRef}-// channelCommandMessageKind marks a visible user turn handled synchronously by-// Router. It remains an ordinary public message, but the task batch seal omits-// it so the agent cannot execute the command again on a later turn.+// channelCommandMessageKind marks a durable control-plane turn handled+// synchronously by Router. Public Chat projections omit it, and the task batch+// seal does too so the agent cannot execute the command again on a later turn.const channelCommandMessageKind = "channel_command"// AppendUserMessage writes the user message into the chat_session (touching itdiff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex ee0018d1a7..a2cede7b3a 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -988,6 +988,64 @@ func (q *Queries) GetPendingChatTask(ctx context.Context, chatSessionID pgtype.Ureturn i, err}+const getPublicChatSessionInWorkspace = `-- name: GetPublicChatSessionInWorkspace :one+SELECT 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 FROM chat_session AS cs+WHERE cs.id = $1+ AND cs.workspace_id = $2+ AND (+ EXISTS (+ SELECT 1 FROM chat_message AS public_message+ WHERE public_message.chat_session_id = cs.id+ AND public_message.message_kind != 'channel_command'+ )+ OR (+ NOT EXISTS (+ SELECT 1 FROM channel_chat_session_binding AS binding+ WHERE binding.chat_session_id = cs.id+ )+ AND NOT EXISTS (+ SELECT 1 FROM chat_message AS channel_message+ WHERE channel_message.chat_session_id = cs.id+ AND channel_message.channel_ingested+ )+ )+ )+`++type GetPublicChatSessionInWorkspaceParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// 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+// non-command message. Empty first-party sessions stay public so the member can+// open a newly-created Web Chat and send its first message. channel_ingested is+// the immutable fallback when a channel binding has since been removed.+func (q *Queries) GetPublicChatSessionInWorkspace(ctx context.Context, arg GetPublicChatSessionInWorkspaceParams) (ChatSession, error) {+ row := q.db.QueryRow(ctx, getPublicChatSessionInWorkspace, arg.ID, arg.WorkspaceID)+ var i ChatSession+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.AgentID,+ &i.CreatorID,+ &i.Title,+ &i.SessionID,+ &i.WorkDir,+ &i.Status,+ &i.CreatedAt,+ &i.UpdatedAt,+ &i.UnreadSince,+ &i.RuntimeID,+ &i.LastReadAt,+ &i.IsAgentIntro,+ &i.PinnedAt,+ &i.ProjectID,+ )+ return i, err+}+const hasActiveChatTaskForSession = `-- name: HasActiveChatTaskForSession :oneSELECT EXISTS (SELECT 1 FROM agent_task_queue@@ -1117,8 +1175,9 @@ type LinkUnownedChannelChatMessagesToTaskParams struct {// Seals the trailing channel-message batch to its task. The task row and these// links are committed together, so an older in-flight task cannot absorb a// newer media message and a later assistant row cannot hide that message.-// channel_command turns were already handled synchronously by Router; keeping-// them visible but unowned prevents both immediate and delayed re-execution.+// channel_command turns were already handled synchronously by Router. They stay+// durable for channel orchestration but remain unowned and absent from public+// Chat projections, preventing both immediate and delayed re-execution.func (q *Queries) LinkUnownedChannelChatMessagesToTask(ctx context.Context, arg LinkUnownedChannelChatMessagesToTaskParams) error {_, err := q.db.Exec(ctx, linkUnownedChannelChatMessagesToTask, arg.TaskID, arg.ChatSessionID)return err@@ -1250,10 +1309,25 @@ LEFT JOIN LATERAL (SELECT content, role, created_at, failure_reason, message_kindFROM chat_message mWHERE m.chat_session_id = cs.id+ AND m.message_kind != 'channel_command'ORDER BY m.created_at DESCLIMIT 1) lm ON trueWHERE cs.workspace_id = $1 AND cs.creator_id = $2+ AND (+ lm.created_at IS NOT NULL+ OR (+ NOT EXISTS (+ SELECT 1 FROM channel_chat_session_binding AS binding+ WHERE binding.chat_session_id = cs.id+ )+ AND NOT EXISTS (+ SELECT 1 FROM chat_message AS channel_message+ WHERE channel_message.chat_session_id = cs.id+ AND channel_message.channel_ingested+ )+ )+ )ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC`@@ -1419,6 +1493,7 @@ func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID)const listChatMessages = `-- name: ListChatMessages :manySELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions FROM chat_message AS messageWHERE message.chat_session_id = $1+ AND message.message_kind != 'channel_command'AND NOT (message.role = 'user'AND EXISTS (@@ -1565,6 +1640,7 @@ func (q *Queries) ListChatMessagesForLegacyTask(ctx context.Context, chatSessionconst listChatMessagesPage = `-- name: ListChatMessagesPage :manySELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions FROM chat_message AS messageWHERE message.chat_session_id = $1+ AND message.message_kind != 'channel_command'AND NOT (message.role = 'user'AND EXISTS (@@ -1661,10 +1737,25 @@ LEFT JOIN LATERAL (SELECT content, role, created_at, failure_reason, message_kindFROM chat_message mWHERE m.chat_session_id = cs.id+ AND m.message_kind != 'channel_command'ORDER BY m.created_at DESCLIMIT 1) lm ON trueWHERE cs.workspace_id = $1 AND cs.creator_id = $2 AND cs.status = 'active'+ AND (+ lm.created_at IS NOT NULL+ OR (+ NOT EXISTS (+ SELECT 1 FROM channel_chat_session_binding AS binding+ WHERE binding.chat_session_id = cs.id+ )+ AND NOT EXISTS (+ SELECT 1 FROM chat_message AS channel_message+ WHERE channel_message.chat_session_id = cs.id+ AND channel_message.channel_ingested+ )+ )+ )ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC`diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sqlindex dc8bd8436b..b6116c4869 100644--- a/server/pkg/db/queries/chat.sql+++ b/server/pkg/db/queries/chat.sql@@ -19,6 +19,34 @@ WHERE id = $1;SELECT * FROM chat_sessionWHERE id = $1 AND workspace_id = $2;+-- 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+-- non-command message. Empty first-party sessions stay public so the member can+-- open a newly-created Web Chat and send its first message. channel_ingested is+-- the immutable fallback when a channel binding has since been removed.+SELECT cs.* FROM chat_session AS cs+WHERE cs.id = $1+ AND cs.workspace_id = $2+ AND (+ EXISTS (+ SELECT 1 FROM chat_message AS public_message+ WHERE public_message.chat_session_id = cs.id+ AND public_message.message_kind != 'channel_command'+ )+ OR (+ NOT EXISTS (+ SELECT 1 FROM channel_chat_session_binding AS binding+ WHERE binding.chat_session_id = cs.id+ )+ AND NOT EXISTS (+ SELECT 1 FROM chat_message AS channel_message+ WHERE channel_message.chat_session_id = cs.id+ AND channel_message.channel_ingested+ )+ )+ );+-- name: ListChatSessionsByCreator :many-- IM-style list: each active session with its unread *count* (assistant-- messages after the read cursor), a preview of the latest message, and@@ -38,10 +66,25 @@ LEFT JOIN LATERAL (SELECT content, role, created_at, failure_reason, message_kindFROM chat_message mWHERE m.chat_session_id = cs.id+ AND m.message_kind != 'channel_command'ORDER BY m.created_at DESCLIMIT 1) lm ON trueWHERE cs.workspace_id = $1 AND cs.creator_id = $2 AND cs.status = 'active'+ AND (+ lm.created_at IS NOT NULL+ OR (+ NOT EXISTS (+ SELECT 1 FROM channel_chat_session_binding AS binding+ WHERE binding.chat_session_id = cs.id+ )+ AND NOT EXISTS (+ SELECT 1 FROM chat_message AS channel_message+ WHERE channel_message.chat_session_id = cs.id+ AND channel_message.channel_ingested+ )+ )+ )ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC;-- name: ListAllChatSessionsByCreator :many@@ -69,10 +112,25 @@ LEFT JOIN LATERAL (SELECT content, role, created_at, failure_reason, message_kindFROM chat_message mWHERE m.chat_session_id = cs.id+ AND m.message_kind != 'channel_command'ORDER BY m.created_at DESCLIMIT 1) lm ON trueWHERE cs.workspace_id = $1 AND cs.creator_id = $2+ AND (+ lm.created_at IS NOT NULL+ OR (+ NOT EXISTS (+ SELECT 1 FROM channel_chat_session_binding AS binding+ WHERE binding.chat_session_id = cs.id+ )+ AND NOT EXISTS (+ SELECT 1 FROM chat_message AS channel_message+ WHERE channel_message.chat_session_id = cs.id+ AND channel_message.channel_ingested+ )+ )+ )ORDER BY (cs.pinned_at IS NOT NULL) DESC, cs.pinned_at DESC, COALESCE(lm.created_at, cs.updated_at) DESC;-- name: ListAgentBuilderSessionsByCreator :many@@ -418,8 +476,9 @@ WHERE id = $1 AND role = 'user';-- Seals the trailing channel-message batch to its task. The task row and these-- links are committed together, so an older in-flight task cannot absorb a-- newer media message and a later assistant row cannot hide that message.--- channel_command turns were already handled synchronously by Router; keeping--- them visible but unowned prevents both immediate and delayed re-execution.+-- channel_command turns were already handled synchronously by Router. They stay+-- durable for channel orchestration but remain unowned and absent from public+-- Chat projections, preventing both immediate and delayed re-execution.UPDATE chat_message AS messageSET task_id = @task_idWHERE message.chat_session_id = @chat_session_id@@ -473,6 +532,7 @@ RETURNING *;-- claimed during the backoff and then becomes the visible claimed head.SELECT message.* FROM chat_message AS messageWHERE message.chat_session_id = $1+ AND message.message_kind != 'channel_command'AND NOT (message.role = 'user'AND EXISTS (@@ -675,6 +735,7 @@ WHERE queued_input.chat_session_id = $1-- name: ListChatMessagesPage :manySELECT message.* FROM chat_message AS messageWHERE message.chat_session_id = $1+ AND message.message_kind != 'channel_command'AND NOT (message.role = 'user'AND EXISTS (