Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(chat): persist optional submission acceptance receipts (#10469)

沙雕的小鱼儿 boyfeiyue2b398739ace
diff --git a/docs/engineering/chat-submissions.md b/docs/engineering/chat-submissions.md
new file mode 100644
index 0000000000..8ee7cb69b6
--- /dev/null
+++ b/docs/engineering/chat-submissions.md
@@ -0,0 +1,69 @@
+# Chat submission acceptance receipts
+
+`POST /api/chat/sessions/{sessionId}/messages` accepts an optional UUID
+`submission_id` alongside `content` and `attachment_ids`.
+
+```json
+{
+ "content": "Review the deployment plan",
+ "submission_id": "646fed2d-71b3-4cbb-bdb3-e39675f005c3",
+ "attachment_ids": []
+}
+```
+
+Choose a submission UUID when creating a logical send and persist it with the
+request. After a timeout or lost response, retry that UUID with the same content
+and requested attachments. A successful first send and its replays return
+`201` with the original `message_id`, `task_id`, `created_at`, `queued`,
+`supports_queue`, and actual bound `attachment_ids` snapshot. Replaying an
+acceptance keeps the message, task, queue position, title work, events and
+daemon wakeup at their original first-send counts.
+
+Receipts are scoped to the workspace, authenticated user, server-resolved actor
+type and ID, chat session, and submission UUID. Rotating a task token for the
+same logical agent preserves that identity. Every replay requires current
+workspace membership, session ownership/public projection, and agent view and
+invocation access. Accepted requests can replay after the session or agent is
+archived or its runtime becomes unavailable.
+
+If invocation permission is revoked, replay returns `403` before reading the
+receipt. Stop automatic retries and surface the permission failure to the user;
+do not choose a new UUID to bypass it.
+
+The fingerprint uses exact decoded content bytes and sorted distinct parsed
+attachment UUIDs. Omitted, `null`, and empty attachment lists are equivalent.
+The requested IDs define the fingerprint even when some attachments could not
+be bound. Reusing an accepted UUID with a different fingerprint returns `409`
+without changing the turn. An empty or malformed provided submission UUID
+returns `400`.
+
+The endpoint also uses `409` for an archived agent, an unavailable runtime, or a
+session archived after preflight. Distinguish a submission conflict by the JSON
+`error` value `submission_id was already accepted with a different payload`;
+status `409` alone does not identify it. Stop retrying that UUID with the changed
+payload; use the original persisted request to recover its acceptance. An empty
+`content` with an already accepted UUID returns `409` because its fingerprint
+differs. With a new UUID it returns `400` (`content is required`). A session
+already archived at handler preflight returns the existing `400` (`chat session
+is archived`); the transaction's archive-race check returns `409`.
+
+An acceptance receipt records the historical accepted send. Cancellation,
+queued-turn editing/removal, message deletion, and attachment deletion or
+detachment preserve the receipt and original response. Replaying after these
+operations keeps the original task ID and leaves the current message, task and
+attachment state intact. Use a new UUID when deliberately sending a restored
+draft or repeating identical text as a new turn. Read the task and chat APIs
+for current execution state.
+
+Receipts persist until their session is deleted. Session, workspace, and system
+runtime-agent teardown remove them atomically under the existing session-lock
+protocol. User-agent sessions surviving a runtime unbind keep their receipts.
+Requests for a deleted session receive the existing `404` response.
+The receipt's `created_at` records its creation time for diagnostics; it does
+not introduce a TTL or change retention.
+
+Omitting `submission_id` or setting it to `null` uses the existing send behavior.
+Each such request creates a new turn. Clients can adopt the field independently.
+Keyed writes require a transaction starter and commit the task, input ownership,
+message, attachment bindings, initial title, session touch and receipt together.
+Migrations 653–655 create the receipt table and concurrent indexes.
diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.go
index 021d06f96b..c34c6f66c6 100644
--- a/server/cmd/migrate/main.go
+++ b/server/cmd/migrate/main.go
@@ -140,6 +140,8 @@ var pgBigmOperatorClass = extensionOperatorClass{
// they are still pending: a fresh self-hosted install, which is exactly where an
// interrupted build would otherwise leave a permanently unusable index.
var concurrentIndexCleanups = map[string]string{
+ "654_chat_submission_receipt_key": "uq_chat_submission_receipt_key",
+ "655_chat_submission_receipt_workspace": "idx_chat_submission_receipt_workspace",
"651_task_context_receipt_issue_idx": "idx_task_context_receipt_issue",
"650_task_context_receipt_workspace_idx": "idx_task_context_receipt_workspace",
"648_project_subscriber_user_idx": "idx_project_subscriber_workspace_user",
diff --git a/server/cmd/server/chat_submission_contract_test.go b/server/cmd/server/chat_submission_contract_test.go
new file mode 100644
index 0000000000..b3bf867e4f
--- /dev/null
+++ b/server/cmd/server/chat_submission_contract_test.go
@@ -0,0 +1,494 @@
+package main
+
+import (
+ "bytes"
+ "encoding/json"
+ "fmt"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "sync"
+ "sync/atomic"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/events"
+ obsmetrics "github.com/multica-ai/multica/server/internal/metrics"
+ "github.com/multica-ai/multica/server/internal/realtime"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ "github.com/multica-ai/multica/server/pkg/protocol"
+ "github.com/prometheus/client_golang/prometheus"
+)
+
+func submissionHTTP(serverURL, token, workspaceID, method, path string, body any) (int, map[string]any, error) {
+ encoded, err := json.Marshal(body)
+ if err != nil {
+ return 0, nil, err
+ }
+ req, err := http.NewRequest(method, serverURL+path, bytes.NewReader(encoded))
+ if err != nil {
+ return 0, nil, err
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("X-Workspace-ID", workspaceID)
+ req.Header.Set("Content-Type", "application/json")
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ return 0, nil, err
+ }
+ defer resp.Body.Close()
+ var out map[string]any
+ if err := json.NewDecoder(resp.Body).Decode(&out); err != nil && err != io.EOF {
+ return resp.StatusCode, nil, err
+ }
+ return resp.StatusCode, out, nil
+}
+
+func submissionStatus(t *testing.T, serverURL, token, workspaceID, method, path string, body any, want int) map[string]any {
+ t.Helper()
+ status, out, err := submissionHTTP(serverURL, token, workspaceID, method, path, body)
+ if err != nil || status != want {
+ t.Fatalf("%s %s status=%d want=%d response=%v error=%v", method, path, status, want, out, err)
+ }
+ return out
+}
+
+func cleanupSubmissionSession(t *testing.T, token, workspaceID, sessionID string) {
+ t.Helper()
+ t.Cleanup(func() {
+ status, body, err := submissionHTTP(testServer.URL, token, workspaceID, "DELETE", "/api/chat/sessions/"+sessionID, nil)
+ if err != nil || (status != http.StatusNoContent && status != http.StatusNotFound) {
+ t.Errorf("cleanup session=%s status=%d body=%v error=%v", sessionID, status, body, err)
+ }
+ })
+}
+
+func submissionCounts(t *testing.T, sessionID string, wantMessages, wantTasks, wantReceipts int) {
+ t.Helper()
+ fx := workspaceFixture(t)
+ for _, check := range []struct {
+ table string
+ want int
+ }{{"chat_message", wantMessages}, {"agent_task_queue", wantTasks}, {"chat_submission_receipt", wantReceipts}} {
+ if got := fx.Count(t, "SELECT count(*) FROM "+check.table+" WHERE chat_session_id=$1", sessionID); got != check.want {
+ t.Errorf("%s count=%d want=%d", check.table, got, check.want)
+ }
+ }
+}
+
+func TestChatSubmissionIdentityAndConflict(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ path := "/api/chat/sessions/" + sessionID + "/messages"
+ id := uuid.NewString()
+ body := map[string]any{"content": "exact content\n", "submission_id": id}
+ first := submissionSend(t, sessionID, body)
+ for _, attachmentIDs := range []any{nil, []string{}} {
+ body["attachment_ids"] = attachmentIDs
+ if replay := submissionSend(t, sessionID, body); !reflect.DeepEqual(first, replay) {
+ t.Fatalf("equivalent replay changed acceptance first=%v replay=%v", first, replay)
+ }
+ }
+ for _, content := range []string{"exact content", "different content", ""} {
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", path, map[string]any{"content": content, "submission_id": id}, http.StatusConflict)
+ }
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", path, map[string]any{"content": "exact content\n", "submission_id": id, "attachment_ids": []string{uuid.NewString()}}, http.StatusConflict)
+ submissionCounts(t, sessionID, 1, 1, 1)
+ body["submission_id"] = uuid.NewString()
+ second := submissionSend(t, sessionID, body)
+ if second["task_id"] == first["task_id"] || second["queued"] != true {
+ t.Fatalf("new submission identity response=%v", second)
+ }
+ for _, invalid := range []string{"", "malformed", "1234"} {
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", path, map[string]any{"content": "new", "submission_id": invalid}, http.StatusBadRequest)
+ }
+ for i := 0; i < 2; i++ {
+ submissionSend(t, sessionID, map[string]any{"content": "legacy null", "submission_id": nil})
+ submissionSend(t, sessionID, map[string]any{"content": "legacy omitted"})
+ }
+ submissionCounts(t, sessionID, 6, 6, 2)
+}
+
+type submissionWakeupCounter struct{ calls atomic.Int32 }
+
+func (w *submissionWakeupCounter) NotifyTaskAvailable(string, string) { w.calls.Add(1) }
+
+func TestChatSubmissionConcurrentFirstSendAndPersistentReplay(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ bus := events.New()
+ var messageEvents, queuedEvents atomic.Int32
+ bus.Subscribe(protocol.EventChatMessage, func(events.Event) { messageEvents.Add(1) })
+ bus.Subscribe(protocol.EventTaskQueued, func(events.Event) { queuedEvents.Add(1) })
+ hub := realtime.NewHub()
+ go hub.Run()
+ metrics := obsmetrics.NewBusinessMetrics()
+ registry := prometheus.NewRegistry()
+ registry.MustRegister(metrics.Collectors()...)
+ router, h := NewRouterWithOptions(testPool, hub, bus, analytics.NoopClient{}, nil, RouterOptions{BusinessMetrics: metrics})
+ wakeups := &submissionWakeupCounter{}
+ h.TaskService.Wakeup = wakeups
+ server := httptest.NewServer(router)
+ t.Cleanup(server.Close)
+ body := map[string]any{"content": "parallel accepted turn", "submission_id": uuid.NewString()}
+ path := "/api/chat/sessions/" + sessionID + "/messages"
+ start := make(chan struct{})
+ const requests = 12
+ results := make(chan map[string]any, requests)
+ errors := make(chan error, requests)
+ var wg sync.WaitGroup
+ for i := 0; i < requests; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ <-start
+ status, result, err := submissionHTTP(server.URL, testToken, testWorkspaceID, "POST", path, body)
+ if err != nil || status != http.StatusCreated {
+ errors <- fmt.Errorf("status=%d response=%v error=%v", status, result, err)
+ return
+ }
+ results <- result
+ }()
+ }
+ close(start)
+ wg.Wait()
+ close(results)
+ close(errors)
+ for err := range errors {
+ t.Error(err)
+ }
+ var original map[string]any
+ for result := range results {
+ if original == nil {
+ original = result
+ }
+ if !reflect.DeepEqual(original, result) {
+ t.Errorf("parallel responses diverged original=%v result=%v", original, result)
+ }
+ }
+ submissionCounts(t, sessionID, 1, 1, 1)
+ if messageEvents.Load() != 1 || queuedEvents.Load() != 1 {
+ t.Fatalf("events message=%d queued=%d", messageEvents.Load(), queuedEvents.Load())
+ }
+ // A fresh router builds fresh service instances and reads the committed receipt.
+ var beforeTouch string
+ workspaceFixture(t).QueryRow(t, `SELECT updated_at::text FROM chat_session WHERE id=$1`, sessionID).Scan(&beforeTouch)
+ restartedRouter, restartedHandler := NewRouterWithOptions(testPool, hub, bus, analytics.NoopClient{}, nil, RouterOptions{BusinessMetrics: metrics})
+ restartedHandler.TaskService.Wakeup = wakeups
+ restarted := httptest.NewServer(restartedRouter)
+ t.Cleanup(restarted.Close)
+ replay := submissionStatus(t, restarted.URL, testToken, testWorkspaceID, "POST", path, body, http.StatusCreated)
+ if !reflect.DeepEqual(original, replay) || messageEvents.Load() != 1 || queuedEvents.Load() != 1 {
+ t.Fatalf("fresh instance replay=%v original=%v events=%d/%d", replay, original, messageEvents.Load(), queuedEvents.Load())
+ }
+ var afterTouch string
+ workspaceFixture(t).QueryRow(t, `SELECT updated_at::text FROM chat_session WHERE id=$1`, sessionID).Scan(&afterTouch)
+ families, err := registry.Gather()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var sentMetrics float64
+ for _, family := range families {
+ if family.GetName() == "multica_chat_message_sent_total" {
+ for _, metric := range family.Metric {
+ sentMetrics += metric.GetCounter().GetValue()
+ }
+ }
+ }
+ if beforeTouch != afterTouch || wakeups.calls.Load() != 1 || sentMetrics != 1 {
+ t.Fatalf("replay side effects touch=%s/%s wakeups=%d chat metrics=%v", beforeTouch, afterTouch, wakeups.calls.Load(), sentMetrics)
+ }
+}
+
+func TestChatSubmissionAttachmentSnapshotAndCanonicalRequest(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ fx := workspaceFixture(t)
+ newAttachment := func() string {
+ return fx.Insert(t, "attachment", testutil.Cols{
+ "workspace_id": testWorkspaceID, "chat_session_id": sessionID,
+ "uploader_type": "member", "uploader_id": testUserID,
+ "filename": "offline.txt", "url": "https://example.invalid/offline.txt", "content_type": "text/plain", "size_bytes": 1,
+ })
+ }
+ a, b := newAttachment(), newAttachment()
+ missing := uuid.NewString()
+ body := map[string]any{"content": "attached", "submission_id": uuid.NewString(), "attachment_ids": []string{a, b, a, missing}}
+ first := submissionSend(t, sessionID, body)
+ bound, ok := first["attachment_ids"].([]any)
+ if !ok || len(bound) != 2 {
+ t.Fatalf("actual binding snapshot=%v", first)
+ }
+ body["attachment_ids"] = []string{missing, b, a}
+ if replay := submissionSend(t, sessionID, body); !reflect.DeepEqual(first, replay) {
+ t.Fatalf("canonical request changed acceptance %v", replay)
+ }
+ fx.Exec(t, `DELETE FROM attachment WHERE id=$1`, a)
+ fx.Exec(t, `UPDATE attachment SET chat_message_id=NULL, chat_session_id=NULL WHERE id=$1`, b)
+ if replay := submissionSend(t, sessionID, body); !reflect.DeepEqual(first, replay) {
+ t.Fatalf("attachment deletion changed historical acceptance %v", replay)
+ }
+ if count := fx.Count(t, `SELECT count(*) FROM attachment WHERE id=$1 AND chat_message_id IS NOT NULL`, b); count != 0 {
+ t.Fatal("replay rebound an attachment")
+ }
+ body["attachment_ids"] = []string{b}
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", "/api/chat/sessions/"+sessionID+"/messages", body, http.StatusConflict)
+ submissionCounts(t, sessionID, 1, 1, 1)
+}
+
+func TestChatSubmissionReplayAfterArchiveAndDelete(t *testing.T) {
+ sessionID, agentID := submissionSession(t)
+ fx := workspaceFixture(t)
+ body := map[string]any{"content": "accepted before archive", "submission_id": uuid.NewString()}
+ first := submissionSend(t, sessionID, body)
+ fx.Exec(t, `UPDATE chat_session SET status='archived' WHERE id=$1`, sessionID)
+ fx.Exec(t, `UPDATE agent SET archived_at=now(), runtime_id=NULL WHERE id=$1`, agentID)
+ t.Cleanup(func() {
+ fx.Exec(t, `UPDATE agent SET archived_at=NULL, runtime_id=(SELECT id FROM agent_runtime WHERE workspace_id=$2 AND name='Integration Test Runtime') WHERE id=$1`, agentID, testWorkspaceID)
+ })
+ if replay := submissionSend(t, sessionID, body); !reflect.DeepEqual(first, replay) {
+ t.Fatalf("archive changed historical acceptance %v", replay)
+ }
+ path := "/api/chat/sessions/" + sessionID
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "DELETE", path, nil, http.StatusNoContent)
+ submissionCounts(t, sessionID, 0, 0, 0)
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", path+"/messages", body, http.StatusNotFound)
+}
+
+func TestChatSubmissionTransactionFailureRollsBackTurn(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ body := map[string]any{"content": "atomic accepted turn", "submission_id": uuid.NewString()}
+ hub := realtime.NewHub()
+ go hub.Run()
+ router, h := NewRouterWithOptions(testPool, hub, events.New(), analytics.NoopClient{}, nil, RouterOptions{})
+ server := httptest.NewServer(router)
+ t.Cleanup(server.Close)
+ h.TaskService.TxStarter = membershipFailCommitPool{testPool}
+ path := "/api/chat/sessions/" + sessionID + "/messages"
+ submissionStatus(t, server.URL, testToken, testWorkspaceID, "POST", path, body, http.StatusInternalServerError)
+ submissionCounts(t, sessionID, 0, 0, 0)
+ var title string
+ workspaceFixture(t).QueryRow(t, `SELECT title FROM chat_session WHERE id=$1`, sessionID).Scan(&title)
+ if title != "" {
+ t.Fatalf("failed transaction left a title=%q", title)
+ }
+ h.TaskService.TxStarter = nil
+ submissionStatus(t, server.URL, testToken, testWorkspaceID, "POST", path, body, http.StatusInternalServerError)
+ submissionCounts(t, sessionID, 0, 0, 0)
+ h.TaskService.TxStarter = testPool
+ submissionStatus(t, server.URL, testToken, testWorkspaceID, "POST", path, body, http.StatusCreated)
+ submissionCounts(t, sessionID, 1, 1, 1)
+}
+
+func TestChatSubmissionActorAndSessionNamespaces(t *testing.T) {
+ sessionID, agentID := submissionSession(t)
+ path := "/api/chat/sessions/" + sessionID + "/messages"
+ body := map[string]any{"content": "scoped identity", "submission_id": uuid.NewString()}
+ member := submissionSend(t, sessionID, body)
+ tokenA := mintAgentTaskToken(t, agentID, member["task_id"].(string), testUserID)
+ agent := submissionStatus(t, testServer.URL, tokenA, testWorkspaceID, "POST", path, body, http.StatusCreated)
+ if member["task_id"] == agent["task_id"] {
+ t.Fatal("member and agent shared an acceptance namespace")
+ }
+ // A new token bound to another task of the same logical agent replays it.
+ fx := workspaceFixture(t)
+ var runtimeID string
+ fx.QueryRow(t, `SELECT runtime_id::text FROM agent WHERE id=$1`, agentID).Scan(&runtimeID)
+ taskID := fx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "originator_user_id": testUserID, "accountable_user_id": testUserID})
+ tokenB := mintAgentTaskToken(t, agentID, taskID, testUserID)
+ replay := submissionStatus(t, testServer.URL, tokenB, testWorkspaceID, "POST", path, body, http.StatusCreated)
+ if !reflect.DeepEqual(agent, replay) {
+ t.Fatalf("token rotation changed logical caller agent=%v replay=%v", agent, replay)
+ }
+ otherAgent := fx.Agent(t, "Other submission actor", runtimeID)
+ otherTask := fx.Task(t, otherAgent, testutil.Cols{"runtime_id": runtimeID, "originator_user_id": testUserID, "accountable_user_id": testUserID})
+ otherToken := mintAgentTaskToken(t, otherAgent, otherTask, testUserID)
+ other := submissionStatus(t, testServer.URL, otherToken, testWorkspaceID, "POST", path, body, http.StatusCreated)
+ if other["task_id"] == agent["task_id"] || other["task_id"] == member["task_id"] {
+ t.Fatal("different logical agent reused an acceptance")
+ }
+ otherSession, _ := submissionSession(t)
+ independent := submissionSend(t, otherSession, body)
+ if independent["task_id"] == member["task_id"] {
+ t.Fatal("different session reused an acceptance")
+ }
+ submissionCounts(t, sessionID, 3, 3, 3)
+ submissionCounts(t, otherSession, 1, 1, 1)
+}
+
+func TestChatSubmissionCurrentAuthorizationBeforeReplay(t *testing.T) {
+ sessionID, agentID := submissionSession(t)
+ fx := workspaceFixture(t)
+ body := map[string]any{"content": "private acceptance", "submission_id": uuid.NewString()}
+ first := submissionSend(t, sessionID, body)
+ agentToken := mintAgentTaskToken(t, agentID, first["task_id"].(string), testUserID)
+ submissionStatus(t, testServer.URL, agentToken, testWorkspaceID, "POST", "/api/chat/sessions/"+sessionID+"/messages", body, http.StatusCreated)
+ path := "/api/chat/sessions/" + sessionID + "/messages"
+ otherID := fx.User(t, "Other submission user", uuid.NewString()+"@example.test")
+ fx.Member(t, testWorkspaceID, otherID, "member")
+ otherToken, err := generateTestJWT(otherID, "[email protected]", "Other")
+ if err != nil {
+ t.Fatal(err)
+ }
+ submissionStatus(t, testServer.URL, otherToken, testWorkspaceID, "POST", path, body, http.StatusForbidden)
+ foreign := fx.Workspace(t, "Foreign submission", "foreign-"+uuid.NewString())
+ fx.Member(t, foreign, testUserID, "owner")
+ submissionStatus(t, testServer.URL, testToken, foreign, "POST", path, body, http.StatusNotFound)
+ fx.Exec(t, `UPDATE agent SET visibility='private', permission_mode='private', owner_id=$2 WHERE id=$1`, agentID, otherID)
+ t.Cleanup(func() {
+ fx.Exec(t, `UPDATE agent SET visibility='workspace', owner_id=$2 WHERE id=$1`, agentID, testUserID)
+ })
+ // Workspace owners retain view access but cannot invoke another owner's private agent.
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", path, body, http.StatusForbidden)
+ submissionStatus(t, testServer.URL, agentToken, testWorkspaceID, "POST", path, body, http.StatusForbidden)
+ fx.Exec(t, `UPDATE member SET role='member' WHERE workspace_id=$1 AND user_id=$2`, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ fx.Exec(t, `UPDATE member SET role='owner' WHERE workspace_id=$1 AND user_id=$2`, testWorkspaceID, testUserID)
+ })
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", path, body, http.StatusForbidden)
+ fx.Exec(t, `UPDATE agent SET visibility='workspace', owner_id=$2 WHERE id=$1`, agentID, testUserID)
+ fx.Exec(t, `DELETE FROM member WHERE workspace_id=$1 AND user_id=$2`, testWorkspaceID, testUserID)
+ t.Cleanup(func() {
+ fx.Exec(t, `INSERT INTO member (workspace_id,user_id,role) VALUES ($1,$2,'owner') ON CONFLICT DO NOTHING`, testWorkspaceID, testUserID)
+ })
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", path, body, http.StatusNotFound)
+ submissionStatus(t, testServer.URL, agentToken, testWorkspaceID, "POST", path, body, http.StatusNotFound)
+ fx.Exec(t, `INSERT INTO member (workspace_id,user_id,role) VALUES ($1,$2,'owner')`, testWorkspaceID, testUserID)
+ if replay := submissionSend(t, sessionID, body); !reflect.DeepEqual(first, replay) {
+ t.Fatalf("restored authorization changed acceptance=%v", replay)
+ }
+ submissionCounts(t, sessionID, 2, 2, 2)
+}
+
+func TestChatSubmissionCancelAndExplicitRestore(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ body := map[string]any{"content": "draft to restore", "submission_id": uuid.NewString()}
+ first := submissionSend(t, sessionID, body)
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", "/api/tasks/"+first["task_id"].(string)+"/cancel", nil, http.StatusOK)
+ // Unstarted empty turns are removed immediately. A replay acknowledges the
+ // original accepted task without bringing that cancelled message back.
+ if replay := submissionSend(t, sessionID, body); !reflect.DeepEqual(first, replay) {
+ t.Fatalf("cancelled acceptance changed %v", replay)
+ }
+ submissionCounts(t, sessionID, 0, 1, 1)
+ fx := workspaceFixture(t)
+ var status string
+ fx.QueryRow(t, `SELECT status FROM agent_task_queue WHERE id=$1`, first["task_id"]).Scan(&status)
+ if status != "cancelled" {
+ t.Fatalf("replay changed cancelled task to %s", status)
+ }
+ body["submission_id"] = uuid.NewString()
+ restored := submissionSend(t, sessionID, body)
+ if restored["task_id"] == first["task_id"] {
+ t.Fatal("explicit restore must create a new task")
+ }
+ submissionCounts(t, sessionID, 1, 2, 2)
+}
+
+func TestChatSubmissionQueueEditPreservesAcceptance(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ submissionSend(t, sessionID, map[string]any{"content": "visible head"})
+ body := map[string]any{"content": "original follow-up", "submission_id": uuid.NewString()}
+ accepted := submissionSend(t, sessionID, body)
+ path := "/api/tasks/" + accepted["task_id"].(string) + "/cancel?expected_status=queued&chat_session_id=" + sessionID + "&queue_action=edit"
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", path, nil, http.StatusOK)
+ if replay := submissionSend(t, sessionID, body); !reflect.DeepEqual(accepted, replay) || replay["queued"] != true {
+ t.Fatalf("queue edit changed acceptance=%v", replay)
+ }
+ body["content"] = "edited follow-up"
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", "/api/chat/sessions/"+sessionID+"/messages", body, http.StatusConflict)
+ body["submission_id"] = uuid.NewString()
+ submissionSend(t, sessionID, body)
+ submissionCounts(t, sessionID, 2, 3, 2)
+}
+
+func TestChatSubmissionIgnoresSpoofedActorHeaders(t *testing.T) {
+ sessionID, agentID := submissionSession(t)
+ body := map[string]any{"content": "member actor", "submission_id": uuid.NewString()}
+ accepted := submissionSend(t, sessionID, body)
+ encoded, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req, err := http.NewRequest("POST", testServer.URL+"/api/chat/sessions/"+sessionID+"/messages", bytes.NewReader(encoded))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+testToken)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ req.Header.Set("X-Agent-ID", agentID)
+ req.Header.Set("X-Task-ID", accepted["task_id"].(string))
+ req.Header.Set("X-Actor-Source", "task_token")
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if resp.StatusCode != http.StatusCreated {
+ resp.Body.Close()
+ t.Fatalf("spoofed-header status=%d", resp.StatusCode)
+ }
+ var replay map[string]any
+ readJSON(t, resp, &replay)
+ if !reflect.DeepEqual(accepted, replay) {
+ t.Fatalf("spoofed actor changed member acceptance=%v", replay)
+ }
+ submissionCounts(t, sessionID, 1, 1, 1)
+}
+
+func TestChatSubmissionPreservesProjectContextContract(t *testing.T) {
+ fx := workspaceFixture(t)
+ caller := fx.User(t, "Submission project member", uuid.NewString()+"@example.test")
+ fx.Member(t, testWorkspaceID, caller, "member")
+ token, err := generateTestJWT(caller, "[email protected]", "Project member")
+ if err != nil {
+ t.Fatal(err)
+ }
+ runtime := fx.Runtime(t, "Submission project runtime", testutil.Cols{"owner_id": caller})
+ agent := fx.Agent(t, "Submission project agent", runtime, testutil.Cols{"owner_id": caller})
+ project := fx.Project(t, "Submission project context")
+ created := submissionStatus(t, testServer.URL, token, testWorkspaceID, "POST", "/api/chat/sessions", map[string]any{"agent_id": agent, "project_id": project}, http.StatusCreated)
+ sessionID := created["id"].(string)
+ cleanupSubmissionSession(t, token, testWorkspaceID, sessionID)
+ path := "/api/chat/sessions/" + sessionID + "/messages"
+ body := map[string]any{"content": "project conversation", "submission_id": uuid.NewString()}
+ accepted := submissionStatus(t, testServer.URL, token, testWorkspaceID, "POST", path, body, http.StatusCreated)
+ fx.Exec(t, `UPDATE project SET visibility='private' WHERE id=$1`, project)
+ submissionStatus(t, testServer.URL, token, testWorkspaceID, "POST", "/api/chat/sessions", map[string]any{"agent_id": agent, "project_id": project}, http.StatusNotFound)
+ submissionStatus(t, testServer.URL, token, testWorkspaceID, "PATCH", "/api/chat/sessions/"+sessionID, map[string]any{"project_id": project}, http.StatusNotFound)
+ // The existing send path retains the selected project until claim time.
+ // Both legacy and keyed sends keep that behavior after visibility changes.
+ submissionStatus(t, testServer.URL, token, testWorkspaceID, "POST", path, map[string]any{"content": "legacy after visibility change"}, http.StatusCreated)
+ if replay := submissionStatus(t, testServer.URL, token, testWorkspaceID, "POST", path, body, http.StatusCreated); !reflect.DeepEqual(accepted, replay) {
+ t.Fatalf("project visibility changed historical acceptance=%v", replay)
+ }
+ body["submission_id"] = uuid.NewString()
+ submissionStatus(t, testServer.URL, token, testWorkspaceID, "POST", path, body, http.StatusCreated)
+ var stored string
+ fx.QueryRow(t, `SELECT project_id::text FROM chat_session WHERE id=$1`, sessionID).Scan(&stored)
+ if stored != project {
+ t.Fatalf("selected context changed to %s", stored)
+ }
+}
+
+func TestChatSubmissionAttachmentOwnershipPerActor(t *testing.T) {
+ sessionID, agentID := submissionSession(t)
+ fx := workspaceFixture(t)
+ attachment := fx.Insert(t, "attachment", testutil.Cols{
+ "workspace_id": testWorkspaceID, "chat_session_id": sessionID,
+ "uploader_type": "agent", "uploader_id": agentID,
+ "filename": "agent.txt", "url": "https://example.invalid/agent.txt", "content_type": "text/plain", "size_bytes": 1,
+ })
+ body := map[string]any{"content": "actor scoped attachment", "submission_id": uuid.NewString(), "attachment_ids": []string{attachment}}
+ member := submissionSend(t, sessionID, body)
+ if bound, ok := member["attachment_ids"].([]any); !ok || len(bound) != 0 {
+ t.Fatalf("member bound another actor's attachment=%v", member)
+ }
+ token := mintAgentTaskToken(t, agentID, member["task_id"].(string), testUserID)
+ agent := submissionStatus(t, testServer.URL, token, testWorkspaceID, "POST", "/api/chat/sessions/"+sessionID+"/messages", body, http.StatusCreated)
+ if bound, ok := agent["attachment_ids"].([]any); !ok || len(bound) != 1 || bound[0] != attachment {
+ t.Fatalf("agent failed to bind its own attachment=%v", agent)
+ }
+ if replay := submissionSend(t, sessionID, body); !reflect.DeepEqual(member, replay) {
+ t.Fatalf("member's empty binding snapshot changed=%v", replay)
+ }
+ submissionCounts(t, sessionID, 2, 2, 2)
+}
diff --git a/server/cmd/server/chat_submission_race_test.go b/server/cmd/server/chat_submission_race_test.go
new file mode 100644
index 0000000000..f8c3d8a016
--- /dev/null
+++ b/server/cmd/server/chat_submission_race_test.go
@@ -0,0 +1,301 @@
+package main
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "net/http"
+ "net/http/httptest"
+ "reflect"
+ "strings"
+ "sync"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/multica-ai/multica/server/internal/analytics"
+ "github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/featureflags"
+ "github.com/multica-ai/multica/server/internal/realtime"
+ "github.com/multica-ai/multica/server/internal/runtimeapps"
+ "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/featureflag"
+)
+
+type submissionCommitBarrier struct {
+ pool *pgxpool.Pool
+ ready chan struct{}
+ proceed chan struct{}
+}
+
+type submissionBarrierTx struct {
+ pgx.Tx
+ barrier *submissionCommitBarrier
+}
+
+func (b *submissionCommitBarrier) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := b.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return submissionBarrierTx{tx, b}, nil
+}
+
+func (tx submissionBarrierTx) Commit(ctx context.Context) error {
+ close(tx.barrier.ready)
+ select {
+ case <-tx.barrier.proceed:
+ return tx.Tx.Commit(ctx)
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+}
+
+type submissionBeginBarrier submissionCommitBarrier
+
+func (b *submissionBeginBarrier) Begin(ctx context.Context) (pgx.Tx, error) {
+ close(b.ready)
+ select {
+ case <-b.proceed:
+ return b.pool.Begin(ctx)
+ case <-ctx.Done():
+ return nil, ctx.Err()
+ }
+}
+
+type submissionHTTPResult struct {
+ status int
+ body map[string]any
+ err error
+}
+
+func submissionAsync(serverURL, workspace, method, path string, body any) <-chan submissionHTTPResult {
+ result := make(chan submissionHTTPResult, 1)
+ go func() {
+ status, response, err := submissionHTTP(serverURL, testToken, workspace, method, path, body)
+ result <- submissionHTTPResult{status, response, err}
+ }()
+ return result
+}
+
+func submissionResult(t *testing.T, results <-chan submissionHTTPResult, want int) submissionHTTPResult {
+ t.Helper()
+ select {
+ case result := <-results:
+ if result.err != nil || result.status != want {
+ t.Fatalf("HTTP result=%+v want status=%d", result, want)
+ }
+ return result
+ case <-time.After(10 * time.Second):
+ t.Fatal("HTTP request did not finish")
+ return submissionHTTPResult{}
+ }
+}
+
+func TestChatSubmissionConcurrentParentDelete(t *testing.T) {
+ for _, parent := range []string{"session", "workspace"} {
+ t.Run(parent, func(t *testing.T) {
+ fx := workspaceFixture(t)
+ workspace := fx.Workspace(t, "Submission deletion", "delete-"+uuid.NewString())
+ fx.Member(t, workspace, testUserID, "owner")
+ runtime := fx.Runtime(t, "Offline synthetic runtime", testutil.Cols{"workspace_id": workspace, "owner_id": testUserID})
+ agent := fx.Agent(t, "Submission deletion agent", runtime, testutil.Cols{"workspace_id": workspace})
+ created := submissionStatus(t, testServer.URL, testToken, workspace, "POST", "/api/chat/sessions", map[string]any{"agent_id": agent}, http.StatusCreated)
+ sessionID := created["id"].(string)
+ cleanupSubmissionSession(t, testToken, workspace, sessionID)
+ hub := realtime.NewHub()
+ go hub.Run()
+ router, h := NewRouterWithOptions(testPool, hub, events.New(), analytics.NoopClient{}, nil, RouterOptions{})
+ server := httptest.NewServer(router)
+ t.Cleanup(server.Close)
+ barrier := &submissionCommitBarrier{testPool, make(chan struct{}), make(chan struct{})}
+ var release sync.Once
+ t.Cleanup(func() { release.Do(func() { close(barrier.proceed) }) })
+ h.TaskService.TxStarter = barrier
+ body := map[string]any{"content": "delete race", "submission_id": uuid.NewString()}
+ send := submissionAsync(server.URL, workspace, "POST", "/api/chat/sessions/"+sessionID+"/messages", body)
+ select {
+ case <-barrier.ready:
+ case <-time.After(10 * time.Second):
+ t.Fatal("send did not reach its pre-commit barrier")
+ }
+ deletePath := "/api/chat/sessions/" + sessionID
+ if parent == "workspace" {
+ deletePath = "/api/workspaces/" + workspace
+ }
+ deleted := submissionAsync(server.URL, workspace, "DELETE", deletePath, nil)
+ deadline := time.Now().Add(5 * time.Second)
+ blocked := false
+ for time.Now().Before(deadline) {
+ var waiting int
+ fx.QueryRow(t, `SELECT count(*) FROM pg_stat_activity WHERE datname=current_database() AND wait_event_type='Lock'`).Scan(&waiting)
+ if waiting > 0 {
+ blocked = true
+ break
+ }
+ time.Sleep(10 * time.Millisecond)
+ }
+ if !blocked {
+ t.Fatal("parent delete did not wait for the send's session lock")
+ }
+ release.Do(func() { close(barrier.proceed) })
+ submissionResult(t, send, http.StatusCreated)
+ submissionResult(t, deleted, http.StatusNoContent)
+ submissionCounts(t, sessionID, 0, 0, 0)
+ submissionStatus(t, server.URL, testToken, workspace, "POST", "/api/chat/sessions/"+sessionID+"/messages", body, http.StatusNotFound)
+ })
+ }
+}
+
+func TestChatSubmissionDeleteWinsBeforeSendTransaction(t *testing.T) {
+ for _, keyed := range []bool{false, true} {
+ t.Run(fmt.Sprint(keyed), func(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ hub := realtime.NewHub()
+ go hub.Run()
+ router, h := NewRouterWithOptions(testPool, hub, events.New(), analytics.NoopClient{}, nil, RouterOptions{})
+ server := httptest.NewServer(router)
+ t.Cleanup(server.Close)
+ barrier := &submissionBeginBarrier{testPool, make(chan struct{}), make(chan struct{})}
+ var release sync.Once
+ t.Cleanup(func() { release.Do(func() { close(barrier.proceed) }) })
+ h.TaskService.TxStarter = barrier
+ body := map[string]any{"content": "send after deleted session"}
+ wantStatus := http.StatusInternalServerError
+ if keyed {
+ body["submission_id"] = uuid.NewString()
+ wantStatus = http.StatusNotFound
+ }
+ path := "/api/chat/sessions/" + sessionID
+ send := submissionAsync(server.URL, testWorkspaceID, "POST", path+"/messages", body)
+ select {
+ case <-barrier.ready:
+ case <-time.After(10 * time.Second):
+ t.Fatal("send did not reach its pre-transaction barrier")
+ }
+ submissionStatus(t, server.URL, testToken, testWorkspaceID, "DELETE", path, nil, http.StatusNoContent)
+ release.Do(func() { close(barrier.proceed) })
+ submissionResult(t, send, wantStatus)
+ submissionCounts(t, sessionID, 0, 0, 0)
+ })
+ }
+}
+
+type submissionMissingAgentPool struct{ pool *pgxpool.Pool }
+type submissionMissingAgentTx struct{ pgx.Tx }
+
+func (p submissionMissingAgentPool) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := p.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return submissionMissingAgentTx{tx}, nil
+}
+
+func (tx submissionMissingAgentTx) QueryRow(ctx context.Context, sql string, args ...any) pgx.Row {
+ // Inject an absent agent read without deleting the real session with it.
+ if strings.HasPrefix(sql, "-- name: GetAgentForClaimUpdate :one") {
+ return tx.Tx.QueryRow(ctx, "SELECT 1 WHERE false")
+ }
+ return tx.Tx.QueryRow(ctx, sql, args...)
+}
+
+func TestChatSubmissionMissingAgentIsNotMissingSession(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ hub := realtime.NewHub()
+ go hub.Run()
+ router, h := NewRouterWithOptions(testPool, hub, events.New(), analytics.NoopClient{}, nil, RouterOptions{})
+ server := httptest.NewServer(router)
+ t.Cleanup(server.Close)
+ h.TaskService.TxStarter = submissionMissingAgentPool{testPool}
+ body := map[string]any{"content": "agent disappears after preflight", "submission_id": uuid.NewString()}
+ submissionStatus(t, server.URL, testToken, testWorkspaceID, "POST", "/api/chat/sessions/"+sessionID+"/messages", body, http.StatusInternalServerError)
+ if got := workspaceFixture(t).Count(t, `SELECT count(*) FROM chat_session WHERE id=$1`, sessionID); got != 1 {
+ t.Fatalf("session count=%d, want 1", got)
+ }
+ submissionCounts(t, sessionID, 0, 0, 0)
+}
+
+type submissionOverlay struct{ calls atomic.Int32 }
+
+func (o *submissionOverlay) BuildTaskOverlay(context.Context, pgtype.UUID, db.Agent) (runtimeapps.MCPOverlayResult, error) {
+ o.calls.Add(1)
+ return runtimeapps.MCPOverlayResult{}, errors.New("synthetic offline overlay failure")
+}
+
+type submissionFailingWakeup struct{ calls atomic.Int32 }
+
+func (w *submissionFailingWakeup) NotifyTaskAvailable(string, string) {
+ w.calls.Add(1)
+ panic("synthetic post-commit wakeup failure")
+}
+
+func TestChatSubmissionRecoversPostCommitNotificationFailure(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ hub := realtime.NewHub()
+ go hub.Run()
+ router, h := NewRouterWithOptions(testPool, hub, events.New(), analytics.NoopClient{}, nil, RouterOptions{})
+ server := httptest.NewServer(router)
+ t.Cleanup(server.Close)
+ overlay := &submissionOverlay{}
+ wakeup := &submissionFailingWakeup{}
+ flags := featureflag.NewStaticProvider()
+ flags.Set(featureflags.ComposioMCPApps, featureflag.Rule{Default: true})
+ h.TaskService.FeatureFlags = featureflag.NewService(flags)
+ h.TaskService.Composio = overlay
+ h.TaskService.Wakeup = wakeup
+ body := map[string]any{"content": "committed before notification", "submission_id": uuid.NewString()}
+ path := "/api/chat/sessions/" + sessionID + "/messages"
+ status, _, err := submissionHTTP(server.URL, testToken, testWorkspaceID, "POST", path, body)
+ if status != http.StatusInternalServerError {
+ t.Fatalf("injected wakeup failure status=%d error=%v", status, err)
+ }
+ submissionCounts(t, sessionID, 1, 1, 1)
+ var raw []byte
+ workspaceFixture(t).QueryRow(t, `SELECT response FROM chat_submission_receipt WHERE chat_session_id=$1`, sessionID).Scan(&raw)
+ var accepted map[string]any
+ if err := json.Unmarshal(raw, &accepted); err != nil {
+ t.Fatal(err)
+ }
+ replay := submissionStatus(t, server.URL, testToken, testWorkspaceID, "POST", path, body, http.StatusCreated)
+ if !reflect.DeepEqual(accepted, replay) || overlay.calls.Load() != 1 || wakeup.calls.Load() != 1 {
+ t.Fatalf("post-commit replay=%v accepted=%v overlay=%d wakeup=%d", replay, accepted, overlay.calls.Load(), wakeup.calls.Load())
+ }
+}
+
+func TestChatSubmissionConcurrentPayloadConflict(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ id := uuid.NewString()
+ start := make(chan struct{})
+ results := make(chan submissionHTTPResult, 2)
+ for _, content := range []string{"first payload", "second payload"} {
+ go func(content string) {
+ <-start
+ status, body, err := submissionHTTP(testServer.URL, testToken, testWorkspaceID, "POST", "/api/chat/sessions/"+sessionID+"/messages", map[string]any{"content": content, "submission_id": id})
+ results <- submissionHTTPResult{status, body, err}
+ }(content)
+ }
+ close(start)
+ statuses := map[int]int{}
+ for i := 0; i < 2; i++ {
+ select {
+ case result := <-results:
+ if result.err != nil {
+ t.Fatal(result.err)
+ }
+ statuses[result.status]++
+ case <-time.After(10 * time.Second):
+ t.Fatal("parallel conflicting send did not complete")
+ }
+ }
+ if statuses[http.StatusCreated] != 1 || statuses[http.StatusConflict] != 1 {
+ t.Fatalf("parallel conflicting statuses=%v", statuses)
+ }
+ submissionCounts(t, sessionID, 1, 1, 1)
+}
diff --git a/server/cmd/server/chat_submission_teardown_test.go b/server/cmd/server/chat_submission_teardown_test.go
new file mode 100644
index 0000000000..e16f49fb17
--- /dev/null
+++ b/server/cmd/server/chat_submission_teardown_test.go
@@ -0,0 +1,126 @@
+package main
+
+import (
+ "context"
+ "net/http"
+ "reflect"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/testutil"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func TestChatSubmissionWorkspaceDeletionIsScoped(t *testing.T) {
+ fx := workspaceFixture(t)
+ neighbourSession, _ := submissionSession(t)
+ body := map[string]any{"content": "workspace-scoped acceptance", "submission_id": uuid.NewString()}
+ neighbourAcceptance := submissionSend(t, neighbourSession, body)
+
+ workspace := fx.Workspace(t, "Submission cleanup", "submission-cleanup-"+uuid.NewString())
+ fx.Member(t, workspace, testUserID, "owner")
+ runtime := fx.Runtime(t, "Offline cleanup runtime", testutil.Cols{"workspace_id": workspace, "owner_id": testUserID})
+ agent := fx.Agent(t, "Submission cleanup agent", runtime, testutil.Cols{"workspace_id": workspace})
+ created := submissionStatus(t, testServer.URL, testToken, workspace, "POST", "/api/chat/sessions", map[string]any{"agent_id": agent}, http.StatusCreated)
+ sessionID := created["id"].(string)
+ cleanupSubmissionSession(t, testToken, workspace, sessionID)
+ path := "/api/chat/sessions/" + sessionID + "/messages"
+ submissionStatus(t, testServer.URL, testToken, workspace, "POST", path, body, http.StatusCreated)
+ submissionCounts(t, sessionID, 1, 1, 1)
+
+ // The FK-free workspace selector must also remove receipts whose session
+ // is already absent, without depending on the session ownership join.
+ fx.Cleanup(t, `DELETE FROM chat_submission_receipt WHERE workspace_id=$1`, workspace)
+ fx.Exec(t, `
+INSERT INTO chat_submission_receipt (
+ chat_session_id, workspace_id, initiator_user_id, actor_type, actor_id,
+ submission_id, request_fingerprint, response
+)
+SELECT $2, workspace_id, initiator_user_id, actor_type, actor_id,
+ submission_id, request_fingerprint, response
+FROM chat_submission_receipt WHERE chat_session_id=$1
+`, sessionID, uuid.NewString())
+ if count := fx.Count(t, `SELECT count(*) FROM chat_submission_receipt WHERE workspace_id=$1`, workspace); count != 2 {
+ t.Fatalf("workspace receipt fixture count=%d want=2", count)
+ }
+
+ submissionStatus(t, testServer.URL, testToken, workspace, "DELETE", "/api/workspaces/"+workspace, nil, http.StatusNoContent)
+ submissionCounts(t, sessionID, 0, 0, 0)
+ if count := fx.Count(t, `SELECT count(*) FROM chat_submission_receipt WHERE workspace_id=$1`, workspace); count != 0 {
+ t.Fatalf("deleted workspace retained %d receipts", count)
+ }
+ submissionStatus(t, testServer.URL, testToken, workspace, "POST", path, body, http.StatusNotFound)
+ submissionCounts(t, neighbourSession, 1, 1, 1)
+ if replay := submissionSend(t, neighbourSession, body); !reflect.DeepEqual(neighbourAcceptance, replay) {
+ t.Fatalf("workspace deletion changed neighbouring acceptance original=%v replay=%v", neighbourAcceptance, replay)
+ }
+ submissionCounts(t, neighbourSession, 1, 1, 1)
+}
+
+func TestChatSubmissionRuntimeUnbindKeepsUserReceipts(t *testing.T) {
+ fx := workspaceFixture(t)
+ runtimeID := fx.Runtime(t, "Submission runtime teardown", testutil.Cols{"owner_id": testUserID})
+ agentID := fx.Agent(t, "Persistent submission agent", runtimeID)
+ created := submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", "/api/chat/sessions", map[string]any{"agent_id": agentID}, http.StatusCreated)
+ sessionID := created["id"].(string)
+ cleanupSubmissionSession(t, testToken, testWorkspaceID, sessionID)
+ userBody := map[string]any{"content": "keep accepted user turn", "submission_id": uuid.NewString()}
+ accepted := submissionSend(t, sessionID, userBody)
+ builder := submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", "/api/agent-builder/sessions", map[string]any{"runtime_id": runtimeID}, http.StatusCreated)
+ builderSession := builder["session_id"].(string)
+ cleanupSubmissionSession(t, testToken, testWorkspaceID, builderSession)
+ submissionSend(t, builderSession, map[string]any{"content": "accepted builder turn", "submission_id": uuid.NewString()})
+ // Both active user agents and runtime-local system carriers participate in
+ // the same production teardown. The confirmed snapshot contains user agents.
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", "/api/runtimes/"+runtimeID+"/unbind-agents-and-delete", map[string]any{"expected_active_agent_ids": []string{agentID}}, http.StatusOK)
+ submissionCounts(t, builderSession, 0, 0, 0)
+ if count := fx.Count(t, `SELECT count(*) FROM chat_submission_receipt WHERE chat_session_id=$1`, sessionID); count != 1 {
+ t.Fatalf("surviving user session receipt count=%d", count)
+ }
+ if replay := submissionSend(t, sessionID, userBody); !reflect.DeepEqual(accepted, replay) {
+ t.Fatalf("unbinding changed historical acceptance %v", replay)
+ }
+ var unbound bool
+ fx.QueryRow(t, `SELECT runtime_id IS NULL FROM agent WHERE id=$1`, agentID).Scan(&unbound)
+ if !unbound {
+ t.Fatal("user agent did not survive unbound")
+ }
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "DELETE", "/api/chat/sessions/"+sessionID, nil, http.StatusNoContent)
+ submissionCounts(t, sessionID, 0, 0, 0)
+}
+
+func TestChatSubmissionProfileAndGCTeardown(t *testing.T) {
+ for _, path := range []string{"profile", "gc"} {
+ t.Run(path, func(t *testing.T) {
+ fx := workspaceFixture(t)
+ runtimeID := fx.Runtime(t, "Submission "+path+" runtime", testutil.Cols{"owner_id": testUserID})
+ var profileID string
+ if path == "profile" {
+ profile := submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles", map[string]any{
+ "display_name": "Submission profile " + uuid.NewString(), "protocol_family": "codex", "command_name": "offline-submission-test",
+ }, http.StatusCreated)
+ profileID = profile["id"].(string)
+ fx.Exec(t, `UPDATE agent_runtime SET profile_id=$2 WHERE id=$1`, runtimeID, profileID)
+ }
+ builder := submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", "/api/agent-builder/sessions", map[string]any{"runtime_id": runtimeID}, http.StatusCreated)
+ sessionID := builder["session_id"].(string)
+ cleanupSubmissionSession(t, testToken, testWorkspaceID, sessionID)
+ accepted := submissionSend(t, sessionID, map[string]any{"content": "retired builder acceptance", "submission_id": uuid.NewString()})
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "POST", "/api/tasks/"+accepted["task_id"].(string)+"/cancel", nil, http.StatusOK)
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "PATCH", "/api/chat/sessions/"+sessionID+"/archive", map[string]any{"archived": true}, http.StatusOK)
+ fx.Exec(t, `UPDATE agent_runtime SET status='offline', last_seen_at=now()-interval '10 days' WHERE id=$1`, runtimeID)
+ if path == "profile" {
+ submissionStatus(t, testServer.URL, testToken, testWorkspaceID, "DELETE", "/api/workspaces/"+testWorkspaceID+"/runtime-profiles/"+profileID, nil, http.StatusNoContent)
+ } else {
+ result, err := gcRuntime(context.Background(), testPool, db.New(testPool), parseUUID(runtimeID))
+ if err != nil || !result.deleted {
+ t.Fatalf("shared GC teardown result=%+v error=%v", result, err)
+ }
+ }
+ submissionCounts(t, sessionID, 0, 0, 0)
+ if count := fx.Count(t, `SELECT count(*) FROM chat_session WHERE id=$1`, sessionID); count != 0 {
+ t.Fatal("retired builder session survived its parent")
+ }
+ })
+ }
+}
diff --git a/server/cmd/server/chat_submission_test.go b/server/cmd/server/chat_submission_test.go
new file mode 100644
index 0000000000..69d616dcea
--- /dev/null
+++ b/server/cmd/server/chat_submission_test.go
@@ -0,0 +1,173 @@
+package main
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "net/http"
+ "testing"
+
+ "github.com/google/uuid"
+ "github.com/multica-ai/multica/server/internal/testutil"
+)
+
+func submissionSession(t *testing.T) (string, string) {
+ t.Helper()
+ var agentID string
+ if err := testPool.QueryRow(context.Background(), `SELECT id FROM agent WHERE workspace_id=$1 AND name='Integration Test Agent'`, testWorkspaceID).Scan(&agentID); err != nil {
+ t.Fatal(err)
+ }
+ resp := authRequest(t, "POST", "/api/chat/sessions", map[string]any{"agent_id": agentID})
+ if resp.StatusCode != http.StatusCreated {
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ t.Fatalf("create status=%d body=%s", resp.StatusCode, body)
+ }
+ var session struct {
+ ID string `json:"id"`
+ }
+ readJSON(t, resp, &session)
+ cleanupSubmissionSession(t, testToken, testWorkspaceID, session.ID)
+ return session.ID, agentID
+}
+
+func submissionSend(t *testing.T, sessionID string, body any) map[string]any {
+ t.Helper()
+ resp := authRequest(t, "POST", "/api/chat/sessions/"+sessionID+"/messages", body)
+ if resp.StatusCode != http.StatusCreated {
+ raw, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ t.Fatalf("send status=%d body=%s", resp.StatusCode, raw)
+ }
+ var sent map[string]any
+ readJSON(t, resp, &sent)
+ return sent
+}
+
+func TestChatSubmissionNormalControl(t *testing.T) {
+ sessionID, agentID := submissionSession(t)
+ first := submissionSend(t, sessionID, map[string]any{"content": "first normal turn"})
+ second := submissionSend(t, sessionID, map[string]any{"content": "second normal turn"})
+ if first["queued"] != false || second["queued"] != true || first["task_id"] == second["task_id"] {
+ t.Fatalf("queue contract first=%v second=%v", first, second)
+ }
+ resp := authRequest(t, "GET", "/api/chat/sessions/"+sessionID+"/messages", nil)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("history status=%d", resp.StatusCode)
+ }
+ var history []map[string]any
+ readJSON(t, resp, &history)
+ if len(history) != 1 {
+ t.Fatalf("visible history count=%d", len(history))
+ }
+ agentToken := mintAgentTaskToken(t, agentID, first["task_id"].(string), testUserID)
+ submissionStatus(t, testServer.URL, agentToken, testWorkspaceID, "POST", "/api/chat/sessions/"+sessionID+"/messages", map[string]any{"content": "task token turn"}, http.StatusCreated)
+ fx := workspaceFixture(t)
+ attachmentID := fx.Insert(t, "attachment", testutil.Cols{
+ "workspace_id": testWorkspaceID, "chat_session_id": sessionID,
+ "uploader_type": "member", "uploader_id": testUserID,
+ "filename": "offline.txt", "url": "https://example.invalid/offline.txt", "content_type": "text/plain", "size_bytes": 1,
+ })
+ attached := submissionSend(t, sessionID, map[string]any{"content": "attached turn", "attachment_ids": []string{attachmentID}})
+ bound, ok := attached["attachment_ids"].([]any)
+ if !ok || len(bound) != 1 || bound[0] != attachmentID {
+ t.Fatalf("attachment response=%v", attached)
+ }
+ var messageID string
+ fx.QueryRow(t, `SELECT chat_message_id::text FROM attachment WHERE id=$1`, attachmentID).Scan(&messageID)
+ if messageID != attached["message_id"] {
+ t.Fatalf("attachment bound to %s", messageID)
+ }
+ otherID := fx.User(t, "Submission outsider", uuid.NewString()+"@example.test")
+ fx.Member(t, testWorkspaceID, otherID, "member")
+ otherToken, err := generateTestJWT(otherID, "[email protected]", "Outsider")
+ if err != nil {
+ t.Fatal(err)
+ }
+ checkDenied := func(token, workspace string) {
+ t.Helper()
+ req, err := http.NewRequest("POST", testServer.URL+"/api/chat/sessions/"+sessionID+"/messages", bytes.NewBufferString(`{"content":"denied"}`))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("X-Workspace-ID", workspace)
+ resp, err := http.DefaultClient.Do(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusForbidden && resp.StatusCode != http.StatusNotFound {
+ t.Fatalf("denial status=%d", resp.StatusCode)
+ }
+ }
+ checkDenied(otherToken, testWorkspaceID)
+ foreignWorkspace := fx.Workspace(t, "Foreign submission", "submission-"+uuid.NewString())
+ fx.Member(t, foreignWorkspace, testUserID, "owner")
+ checkDenied(testToken, foreignWorkspace)
+ fx.Exec(t, `UPDATE agent_runtime SET visibility='public' WHERE id=(SELECT runtime_id FROM agent WHERE id=$1)`, agentID)
+ fx.Exec(t, `UPDATE agent SET visibility='private', permission_mode='private', owner_id=$2 WHERE id=$1`, agentID, otherID)
+ checkDenied(testToken, testWorkspaceID)
+ fx.Exec(t, `UPDATE agent SET visibility='workspace', owner_id=$2 WHERE id=$1`, agentID, testUserID)
+ fx.Exec(t, `DELETE FROM member WHERE workspace_id=$1 AND user_id=$2`, testWorkspaceID, otherID)
+ checkDenied(otherToken, testWorkspaceID)
+}
+
+type submissionLostResponse struct{ transport http.RoundTripper }
+
+func (rt submissionLostResponse) RoundTrip(req *http.Request) (*http.Response, error) {
+ resp, err := rt.transport.RoundTrip(req)
+ if err != nil {
+ return nil, err
+ }
+ _, err = io.Copy(io.Discard, resp.Body)
+ resp.Body.Close()
+ if err != nil {
+ return nil, err
+ }
+ return nil, errors.New("synthetic loss after server committed response")
+}
+
+func TestChatSubmissionResponseLossReplay(t *testing.T) {
+ sessionID, _ := submissionSession(t)
+ body := map[string]any{"content": "response loss turn", "submission_id": uuid.NewString()}
+ raw, err := json.Marshal(body)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req, err := http.NewRequest("POST", testServer.URL+"/api/chat/sessions/"+sessionID+"/messages", bytes.NewReader(raw))
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Authorization", "Bearer "+testToken)
+ req.Header.Set("X-Workspace-ID", testWorkspaceID)
+ req.Header.Set("Content-Type", "application/json")
+ client := &http.Client{Transport: submissionLostResponse{http.DefaultTransport}}
+ if _, err := client.Do(req); err == nil {
+ t.Fatal("expected synthetic response loss")
+ }
+ var firstMessage, firstTask string
+ if err := testPool.QueryRow(context.Background(), `SELECT id::text, task_id::text FROM chat_message WHERE chat_session_id=$1 AND role='user'`, sessionID).Scan(&firstMessage, &firstTask); err != nil {
+ t.Fatal(err)
+ }
+ replay := submissionSend(t, sessionID, body)
+ resp := authRequest(t, "GET", "/api/chat/sessions/"+sessionID+"/messages", nil)
+ if resp.StatusCode != http.StatusOK {
+ t.Fatalf("history status=%d", resp.StatusCode)
+ }
+ var history []map[string]any
+ readJSON(t, resp, &history)
+ var messages, tasks int
+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM chat_message WHERE chat_session_id=$1 AND role='user'`, sessionID).Scan(&messages); err != nil {
+ t.Fatal(err)
+ }
+ if err := testPool.QueryRow(context.Background(), `SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1`, sessionID).Scan(&tasks); err != nil {
+ t.Fatal(err)
+ }
+ t.Logf("original message=%s task=%s replay=%v messages=%d tasks=%d history=%d", firstMessage, firstTask, replay, messages, tasks, len(history))
+ if replay["message_id"] != firstMessage || replay["task_id"] != firstTask || messages != 1 || tasks != 1 || len(history) != 1 {
+ t.Fatalf("accepted submission must replay original identity once; messages=%d tasks=%d history=%d", messages, tasks, len(history))
+ }
+}
diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.go
index c941d97811..544902a29c 100644
--- a/server/internal/handler/chat.go
+++ b/server/internal/handler/chat.go
@@ -765,6 +765,10 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
// draft-restore protocol: FinalizeDeferredCancelledChat takes the same
// chat_session lock before inserting a restore, so it cannot slip one past
// this sweep (see LockChatSessionForTask in chat.sql).
+ if err := qtx.DeleteChatSubmissionReceiptsBySession(r.Context(), session.ID); err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to delete chat submission receipts")
+ return
+ }
if err := qtx.DeleteChatDraftRestoresBySession(r.Context(), session.ID); err != nil {
writeError(w, http.StatusInternalServerError, "failed to delete chat session draft restores")
return
@@ -818,32 +822,12 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {
// Chat Messages
type SendChatMessageRequest struct {
+ SubmissionID *string `json:"submission_id"`
Content string `json:"content"`
AttachmentIDs []string `json:"attachment_ids"`
}
-type SendChatMessageResponse struct {
- MessageID string `json:"message_id"`
- TaskID string `json:"task_id"`
- SupportsQueue bool `json:"supports_queue"`
- Queued bool `json:"queued"`
- // AttachmentIDs are the attachment rows actually bound to this message by
- // the server. The client diffs these against the ids it requested so it
- // can warn the user when an attachment silently failed to bind — no extra
- // round-trip needed. No `omitempty`: a send that requested attachments but
- // bound none must serialize `[]` (not be omitted), otherwise the client
- // can't tell "all binds failed" from "older server without this field" and
- // would silently skip the very warning this exists for. When no
- // attachments were requested the value is nil → `null`, which the client's
- // guard short-circuits on the requested-ids check.
- AttachmentIDs []string `json:"attachment_ids"`
- // CreatedAt anchors the chat StatusPill timer the instant the user
- // hits send. Without it the front-end falls back to its local clock
- // and the timer "snaps backwards" later when WS events deliver the
- // real created_at. Returning it here means the pill renders 0s from
- // the start with a stable anchor.
- CreatedAt string `json:"created_at"`
-}
+type SendChatMessageResponse = service.ChatSubmissionResponse
func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
userID, ok := requireUserID(w, r)
@@ -858,7 +842,7 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid request body")
return
}
- if req.Content == "" {
+ if req.Content == "" && req.SubmissionID == nil {
writeError(w, http.StatusBadRequest, "content is required")
return
}
@@ -871,6 +855,14 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
return
}
+ var submissionID pgtype.UUID
+ if req.SubmissionID != nil {
+ submissionID, ok = parseUUIDOrBadRequest(w, *req.SubmissionID, "submission_id")
+ if !ok {
+ return
+ }
+ }
+
// Load chat session and re-check the private-agent gate on every send.
// The session's creator passed the gate at create time, but their
// workspace role (or the agent's owner) may have changed since — keep
@@ -880,6 +872,33 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
+ if submissionID.Valid {
+ agent, err := h.Queries.GetAgent(r.Context(), session.AgentID)
+ if err != nil {
+ writeError(w, http.StatusInternalServerError, "failed to load chat agent")
+ return
+ }
+ actorType, actorID := h.resolveActor(r, userID, workspaceID)
+ if !h.canInvokeAgent(r.Context(), agent, actorType, actorID, h.invokeOriginatorFromRequest(r, actorType, actorID), workspaceID) {
+ h.writeDispatchBlocked(w, http.StatusForbidden, ReasonInvocationNotAllowed)
+ return
+ }
+ response, err := h.TaskService.LookupDirectChatSubmission(r.Context(), session, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID), submissionID)
+ if err != nil {
+ h.writeChatSubmissionError(w, err)
+ return
+ }
+ if response != nil {
+ writeJSON(w, http.StatusCreated, response)
+ return
+ }
+ }
+
+ if req.Content == "" {
+ writeError(w, http.StatusBadRequest, "content is required")
+ return
+ }
+
// Archived sessions are read-only: refuse to enqueue new agent work for
// them (see SetChatSessionArchived). The frontend disables the composer
// for status='archived' and only offers unarchive/delete there. Legacy
@@ -958,9 +977,18 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
// creator-only), so they are the task initiator and the run's originator —
// surfaced to the agent under `## On Behalf Of`. actorType/actorID were
// resolved above for the invoke gate.
- sent, err := h.TaskService.SendDirectChatMessage(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID))
+ var sent *service.DirectChatSendResult
+ if submissionID.Valid {
+ sent, err = h.TaskService.SendDirectChatMessageWithSubmission(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID), submissionID)
+ } else {
+ sent, err = h.TaskService.SendDirectChatMessage(r.Context(), session, agent, parseUUID(userID), req.Content, attachmentIDs, actorType, parseUUID(actorID))
+ }
if err != nil {
switch {
+ case errors.Is(err, service.ErrChatSubmissionConflict):
+ h.writeChatSubmissionError(w, err)
+ case submissionID.Valid && errors.Is(err, service.ErrChatSessionNotFound):
+ writeError(w, http.StatusNotFound, "chat session not found")
case errors.Is(err, service.ErrChatSessionArchived):
writeError(w, http.StatusConflict, "chat session is archived")
case errors.Is(err, service.ErrChatTaskAgentArchived):
@@ -973,6 +1001,10 @@ func (h *Handler) SendChatMessage(w http.ResponseWriter, r *http.Request) {
}
return
}
+ if sent.Replayed {
+ writeJSON(w, http.StatusCreated, sent.Acceptance)
+ return
+ }
msg := sent.Message
task := sent.Task
currentTitle := session.Title
diff --git a/server/internal/handler/chat_submission.go b/server/internal/handler/chat_submission.go
new file mode 100644
index 0000000000..e6d944e1d4
--- /dev/null
+++ b/server/internal/handler/chat_submission.go
@@ -0,0 +1,16 @@
+package handler
+
+import (
+ "errors"
+ "net/http"
+
+ "github.com/multica-ai/multica/server/internal/service"
+)
+
+func (h *Handler) writeChatSubmissionError(w http.ResponseWriter, err error) {
+ if errors.Is(err, service.ErrChatSubmissionConflict) {
+ writeError(w, http.StatusConflict, service.ErrChatSubmissionConflict.Error())
+ return
+ }
+ writeError(w, http.StatusInternalServerError, "failed to read chat submission receipt")
+}
diff --git a/server/internal/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.go
index 7da74c5728..c63245e7a3 100644
--- a/server/internal/handler/workspace_delete_manifest_test.go
+++ b/server/internal/handler/workspace_delete_manifest_test.go
@@ -54,6 +54,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{
"chat_message": workspaceDelete,
"chat_pinned_agent": workspaceDelete,
"chat_session": workspaceDelete,
+ "chat_submission_receipt": workspaceDelete,
"client_usage_daily": workspaceDeleteDetach,
"comment": workspaceDelete,
"comment_reaction": workspaceDelete,
diff --git a/server/internal/service/chat_submission.go b/server/internal/service/chat_submission.go
new file mode 100644
index 0000000000..2055b2b130
--- /dev/null
+++ b/server/internal/service/chat_submission.go
@@ -0,0 +1,141 @@
+package service
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "slices"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+var ErrChatSubmissionConflict = errors.New("submission_id was already accepted with a different payload")
+
+var ErrChatSessionNotFound = errors.New("chat session not found")
+
+// ChatSubmissionResponse is the original acceptance snapshot. Cancellation,
+// queue edits and attachment deletion do not change what was accepted.
+type ChatSubmissionResponse struct {
+ MessageID string `json:"message_id"`
+ TaskID string `json:"task_id"`
+ SupportsQueue bool `json:"supports_queue"`
+ Queued bool `json:"queued"`
+ // AttachmentIDs are the attachment rows actually bound to this message by
+ // the server. The client diffs these against the ids it requested so it
+ // can warn the user when an attachment silently failed to bind — no extra
+ // round-trip needed. No `omitempty`: a send that requested attachments but
+ // bound none must serialize `[]` (not be omitted), otherwise the client
+ // can't tell "all binds failed" from "older server without this field" and
+ // would silently skip the very warning this exists for. When no
+ // attachments were requested the value is nil → `null`, which the client's
+ // guard short-circuits on the requested-ids check.
+ AttachmentIDs []string `json:"attachment_ids"`
+ // CreatedAt anchors the chat StatusPill timer the instant the user
+ // hits send. Without it the front-end falls back to its local clock
+ // and the timer "snaps backwards" later when WS events deliver the
+ // real created_at. Returning it here means the pill renders 0s from
+ // the start with a stable anchor.
+ CreatedAt string `json:"created_at"`
+}
+
+type chatSubmission struct {
+ key db.GetChatSubmissionReceiptParams
+ fingerprint []byte
+}
+
+func newChatSubmission(session db.ChatSession, userID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, actorType string, actorID, submissionID pgtype.UUID) chatSubmission {
+ ids := make([]string, 0, len(attachmentIDs))
+ for _, id := range attachmentIDs {
+ ids = append(ids, util.UUIDToString(id))
+ }
+ slices.Sort(ids)
+ ids = slices.Compact(ids)
+ // A structured encoding preserves content bytes and unambiguous boundaries.
+ payload, _ := json.Marshal(struct {
+ Content string `json:"content"`
+ AttachmentIDs []string `json:"attachment_ids"`
+ }{content, ids})
+ hash := sha256.Sum256(payload)
+ return chatSubmission{
+ key: db.GetChatSubmissionReceiptParams{
+ ChatSessionID: session.ID, WorkspaceID: session.WorkspaceID,
+ InitiatorUserID: userID, ActorType: actorType, ActorID: actorID, SubmissionID: submissionID,
+ },
+ fingerprint: hash[:],
+ }
+}
+
+func (submission chatSubmission) lookup(ctx context.Context, q *db.Queries) (*ChatSubmissionResponse, error) {
+ receipt, err := q.GetChatSubmissionReceipt(ctx, submission.key)
+ if errors.Is(err, pgx.ErrNoRows) {
+ return nil, nil
+ }
+ if err != nil {
+ return nil, fmt.Errorf("read chat submission receipt: %w", err)
+ }
+ if !bytes.Equal(receipt.RequestFingerprint, submission.fingerprint) {
+ return nil, ErrChatSubmissionConflict
+ }
+ var response ChatSubmissionResponse
+ if err := json.Unmarshal(receipt.Response, &response); err != nil {
+ return nil, fmt.Errorf("decode chat submission receipt: %w", err)
+ }
+ return &response, nil
+}
+
+// LookupDirectChatSubmission must be called only after current authorization.
+// It intentionally avoids runtime readiness, overlays and provider lookups.
+func (s *TaskService) LookupDirectChatSubmission(ctx context.Context, session db.ChatSession, userID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, actorType string, actorID, submissionID pgtype.UUID) (*ChatSubmissionResponse, error) {
+ return newChatSubmission(session, userID, content, attachmentIDs, actorType, actorID, submissionID).lookup(ctx, s.Queries)
+}
+
+// SendDirectChatMessageWithSubmission requires a real transaction even for
+// callers which construct TaskService without its usual database wiring.
+func (s *TaskService) SendDirectChatMessageWithSubmission(ctx context.Context, session db.ChatSession, agent db.Agent, userID pgtype.UUID, content string, attachmentIDs []pgtype.UUID, actorType string, actorID, submissionID pgtype.UUID) (*DirectChatSendResult, error) {
+ if !submissionID.Valid {
+ return nil, errors.New("submission_id is required for keyed chat send")
+ }
+ if s.TxStarter == nil {
+ return nil, errors.New("chat submission requires a transaction starter")
+ }
+ submission := newChatSubmission(session, userID, content, attachmentIDs, actorType, actorID, submissionID)
+ if response, err := submission.lookup(ctx, s.Queries); err != nil {
+ return nil, err
+ } else if response != nil {
+ return &DirectChatSendResult{Replayed: true, Acceptance: response}, nil
+ }
+ return s.sendDirectChatMessage(ctx, session, agent, userID, content, attachmentIDs, actorType, actorID, &submission)
+}
+
+func (submission chatSubmission) store(ctx context.Context, q *db.Queries, sent *DirectChatSendResult, attachmentsRequested bool) error {
+ response := ChatSubmissionResponse{
+ MessageID: util.UUIDToString(sent.Message.ID), TaskID: util.UUIDToString(sent.Task.ID),
+ SupportsQueue: true, Queued: sent.Queued, CreatedAt: util.TimestampToString(sent.Task.CreatedAt),
+ }
+ if attachmentsRequested {
+ response.AttachmentIDs = make([]string, 0, len(sent.BoundAttachmentIDs))
+ for _, id := range sent.BoundAttachmentIDs {
+ response.AttachmentIDs = append(response.AttachmentIDs, util.UUIDToString(id))
+ }
+ }
+ encoded, err := json.Marshal(response)
+ if err != nil {
+ return err
+ }
+ key := submission.key
+ if err := q.CreateChatSubmissionReceipt(ctx, db.CreateChatSubmissionReceiptParams{
+ ChatSessionID: key.ChatSessionID, WorkspaceID: key.WorkspaceID, InitiatorUserID: key.InitiatorUserID,
+ ActorType: key.ActorType, ActorID: key.ActorID, SubmissionID: key.SubmissionID,
+ RequestFingerprint: submission.fingerprint, Response: encoded,
+ }); err != nil {
+ return fmt.Errorf("store chat submission receipt: %w", err)
+ }
+ sent.Acceptance = &response
+ return nil
+}
diff --git a/server/internal/service/runtime_teardown.go b/server/internal/service/runtime_teardown.go
index c19259718b..719ab3f501 100644
--- a/server/internal/service/runtime_teardown.go
+++ b/server/internal/service/runtime_teardown.go
@@ -171,6 +171,9 @@ func pruneRuntimeSystemAgentChatDraftRestores(ctx context.Context, q *db.Queries
if _, err := q.LockChatSessionsBySystemRuntimeAgents(ctx, runtimeID); err != nil {
return err
}
+ if err := q.DeleteChatSubmissionReceiptsBySystemRuntimeAgents(ctx, runtimeID); err != nil {
+ return err
+ }
if err := q.DeleteChatDraftRestoresBySystemRuntimeAgents(ctx, runtimeID); err != nil {
return err
}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 6421063d25..f7f28722d0 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -2370,6 +2370,8 @@ func (s *TaskService) PromoteDeferredChannelIssueTask(ctx context.Context, taskI
// persisted, so the handler can broadcast the user message and shape its
// response without re-reading them.
type DirectChatSendResult struct {
+ Replayed bool
+ Acceptance *ChatSubmissionResponse
Task db.AgentTaskQueue
Message db.ChatMessage
BoundAttachmentIDs []pgtype.UUID
@@ -2399,6 +2401,20 @@ func (s *TaskService) SendDirectChatMessage(
attachmentIDs []pgtype.UUID,
uploaderType string,
uploaderID pgtype.UUID,
+) (*DirectChatSendResult, error) {
+ return s.sendDirectChatMessage(ctx, session, agent, initiatorUserID, content, attachmentIDs, uploaderType, uploaderID, nil)
+}
+
+func (s *TaskService) sendDirectChatMessage(
+ ctx context.Context,
+ session db.ChatSession,
+ agent db.Agent,
+ initiatorUserID pgtype.UUID,
+ content string,
+ attachmentIDs []pgtype.UUID,
+ uploaderType string,
+ uploaderID pgtype.UUID,
+ submission *chatSubmission,
) (*DirectChatSendResult, error) {
// Build the per-task Composio overlay before the transaction — it can do
// network I/O and must not run with a DB transaction open.
@@ -2427,12 +2443,29 @@ func (s *TaskService) SendDirectChatMessage(
// running on the old runtime. Locking chat_session first also matches the
// delete path's lock order, so the two cannot deadlock.
if _, err := qtx.LockChatSessionForRuntimeBind(ctx, session.ID); err != nil {
+ if submission != nil && errors.Is(err, pgx.ErrNoRows) {
+ return ErrChatSessionNotFound
+ }
return fmt.Errorf("lock chat session: %w", err)
}
currentSession, err := qtx.GetChatSession(ctx, session.ID)
if err != nil {
+ if submission != nil && errors.Is(err, pgx.ErrNoRows) {
+ return ErrChatSessionNotFound
+ }
return fmt.Errorf("reload chat session: %w", err)
}
+ if submission != nil {
+ response, err := submission.lookup(ctx, qtx)
+ if err != nil {
+ return err
+ }
+ if response != nil {
+ out.Replayed = true
+ out.Acceptance = response
+ return nil
+ }
+ }
if currentSession.Status != "active" {
return ErrChatSessionArchived
}
@@ -2572,6 +2605,9 @@ func (s *TaskService) SendDirectChatMessage(
if err := qtx.TouchChatSession(ctx, session.ID); err != nil {
return fmt.Errorf("touch chat session: %w", err)
}
+ if submission != nil {
+ return submission.store(ctx, qtx, &out, len(attachmentIDs) > 0)
+ }
return nil
}); err != nil {
slog.Error("direct chat send failed",
@@ -2581,6 +2617,9 @@ func (s *TaskService) SendDirectChatMessage(
return nil, err
}
+ if out.Replayed {
+ return &out, nil
+ }
slog.Info("direct chat task enqueued",
"task_id", util.UUIDToString(out.Task.ID),
"chat_session_id", util.UUIDToString(session.ID),
diff --git a/server/migrations/653_chat_submission_receipt.down.sql b/server/migrations/653_chat_submission_receipt.down.sql
new file mode 100644
index 0000000000..920057838e
--- /dev/null
+++ b/server/migrations/653_chat_submission_receipt.down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS chat_submission_receipt;
diff --git a/server/migrations/653_chat_submission_receipt.up.sql b/server/migrations/653_chat_submission_receipt.up.sql
new file mode 100644
index 0000000000..dfd7d91d0a
--- /dev/null
+++ b/server/migrations/653_chat_submission_receipt.up.sql
@@ -0,0 +1,13 @@
+-- Acceptance receipts outlive message cancellation and attachment deletion.
+-- Writers and session/parent deleters hold the chat_session row lock.
+CREATE TABLE chat_submission_receipt (
+ chat_session_id UUID NOT NULL,
+ workspace_id UUID NOT NULL,
+ initiator_user_id UUID NOT NULL,
+ actor_type TEXT NOT NULL,
+ actor_id UUID NOT NULL,
+ submission_id UUID NOT NULL,
+ request_fingerprint BYTEA NOT NULL,
+ response JSONB NOT NULL,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/654_chat_submission_receipt_key.down.sql b/server/migrations/654_chat_submission_receipt_key.down.sql
new file mode 100644
index 0000000000..b1299c83da
--- /dev/null
+++ b/server/migrations/654_chat_submission_receipt_key.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS uq_chat_submission_receipt_key;
diff --git a/server/migrations/654_chat_submission_receipt_key.up.sql b/server/migrations/654_chat_submission_receipt_key.up.sql
new file mode 100644
index 0000000000..5d3cffc261
--- /dev/null
+++ b/server/migrations/654_chat_submission_receipt_key.up.sql
@@ -0,0 +1 @@
+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS uq_chat_submission_receipt_key ON chat_submission_receipt (chat_session_id, workspace_id, initiator_user_id, actor_type, actor_id, submission_id);
diff --git a/server/migrations/655_chat_submission_receipt_workspace.down.sql b/server/migrations/655_chat_submission_receipt_workspace.down.sql
new file mode 100644
index 0000000000..4677aaf5e9
--- /dev/null
+++ b/server/migrations/655_chat_submission_receipt_workspace.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_chat_submission_receipt_workspace;
diff --git a/server/migrations/655_chat_submission_receipt_workspace.up.sql b/server/migrations/655_chat_submission_receipt_workspace.up.sql
new file mode 100644
index 0000000000..48acbe2b05
--- /dev/null
+++ b/server/migrations/655_chat_submission_receipt_workspace.up.sql
@@ -0,0 +1 @@
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_chat_submission_receipt_workspace ON chat_submission_receipt (workspace_id);
diff --git a/server/pkg/db/generated/chat_submission.sql.go b/server/pkg/db/generated/chat_submission.sql.go
new file mode 100644
index 0000000000..2953b7ab96
--- /dev/null
+++ b/server/pkg/db/generated/chat_submission.sql.go
@@ -0,0 +1,100 @@
+// Code generated by sqlc. DO NOT EDIT.
+// versions:
+// sqlc v1.31.1
+// source: chat_submission.sql
+
+package db
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+)
+
+const createChatSubmissionReceipt = `-- name: CreateChatSubmissionReceipt :exec
+INSERT INTO chat_submission_receipt (
+ chat_session_id, workspace_id, initiator_user_id, actor_type, actor_id,
+ submission_id, request_fingerprint, response
+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
+`
+
+type CreateChatSubmissionReceiptParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ SubmissionID pgtype.UUID `json:"submission_id"`
+ RequestFingerprint []byte `json:"request_fingerprint"`
+ Response []byte `json:"response"`
+}
+
+func (q *Queries) CreateChatSubmissionReceipt(ctx context.Context, arg CreateChatSubmissionReceiptParams) error {
+ _, err := q.db.Exec(ctx, createChatSubmissionReceipt,
+ arg.ChatSessionID,
+ arg.WorkspaceID,
+ arg.InitiatorUserID,
+ arg.ActorType,
+ arg.ActorID,
+ arg.SubmissionID,
+ arg.RequestFingerprint,
+ arg.Response,
+ )
+ return err
+}
+
+const deleteChatSubmissionReceiptsBySession = `-- name: DeleteChatSubmissionReceiptsBySession :exec
+DELETE FROM chat_submission_receipt WHERE chat_session_id = $1
+`
+
+func (q *Queries) DeleteChatSubmissionReceiptsBySession(ctx context.Context, chatSessionID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteChatSubmissionReceiptsBySession, chatSessionID)
+ return err
+}
+
+const deleteChatSubmissionReceiptsBySystemRuntimeAgents = `-- name: DeleteChatSubmissionReceiptsBySystemRuntimeAgents :exec
+DELETE FROM chat_submission_receipt
+WHERE chat_session_id IN (
+ SELECT cs.id FROM chat_session cs JOIN agent a ON a.id = cs.agent_id
+ WHERE a.runtime_id = $1 AND a.kind = 'system'
+)
+`
+
+func (q *Queries) DeleteChatSubmissionReceiptsBySystemRuntimeAgents(ctx context.Context, runtimeID pgtype.UUID) error {
+ _, err := q.db.Exec(ctx, deleteChatSubmissionReceiptsBySystemRuntimeAgents, runtimeID)
+ return err
+}
+
+const getChatSubmissionReceipt = `-- name: GetChatSubmissionReceipt :one
+SELECT request_fingerprint, response FROM chat_submission_receipt
+WHERE chat_session_id = $1 AND workspace_id = $2 AND initiator_user_id = $3
+ AND actor_type = $4 AND actor_id = $5 AND submission_id = $6
+`
+
+type GetChatSubmissionReceiptParams struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ SubmissionID pgtype.UUID `json:"submission_id"`
+}
+
+type GetChatSubmissionReceiptRow struct {
+ RequestFingerprint []byte `json:"request_fingerprint"`
+ Response []byte `json:"response"`
+}
+
+func (q *Queries) GetChatSubmissionReceipt(ctx context.Context, arg GetChatSubmissionReceiptParams) (GetChatSubmissionReceiptRow, error) {
+ row := q.db.QueryRow(ctx, getChatSubmissionReceipt,
+ arg.ChatSessionID,
+ arg.WorkspaceID,
+ arg.InitiatorUserID,
+ arg.ActorType,
+ arg.ActorID,
+ arg.SubmissionID,
+ )
+ var i GetChatSubmissionReceiptRow
+ err := row.Scan(&i.RequestFingerprint, &i.Response)
+ return i, err
+}
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index c5d83b96b0..b2f72a0816 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -648,6 +648,18 @@ type ChatSession struct {
ExplicitlyCreatedAt pgtype.Timestamptz `json:"explicitly_created_at"`
}
+type ChatSubmissionReceipt struct {
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ ActorType string `json:"actor_type"`
+ ActorID pgtype.UUID `json:"actor_id"`
+ SubmissionID pgtype.UUID `json:"submission_id"`
+ RequestFingerprint []byte `json:"request_fingerprint"`
+ Response []byte `json:"response"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type ClientUsageDaily struct {
UserID pgtype.UUID `json:"user_id"`
ClientType string `json:"client_type"`
diff --git a/server/pkg/db/generated/workspace.sql.go b/server/pkg/db/generated/workspace.sql.go
index f2e72e4a46..b8d3771e1b 100644
--- a/server/pkg/db/generated/workspace.sql.go
+++ b/server/pkg/db/generated/workspace.sql.go
@@ -96,6 +96,9 @@ cleared_outbound_cards AS (
DELETE FROM channel_outbound_card_message
WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
),
+cleared_chat_submission_receipts AS (
+ DELETE FROM chat_submission_receipt WHERE chat_submission_receipt.workspace_id = $1
+),
cleared_draft_restores AS (
-- chat_draft_restore is keyed by chat_session_id with no FK (MUL-3515) and has
-- no reaper, while its chat_session rows cascade away with the workspace. Reach
diff --git a/server/pkg/db/generated/workspace_delete.sql.go b/server/pkg/db/generated/workspace_delete.sql.go
index c3b49c9d38..f2b096a141 100644
--- a/server/pkg/db/generated/workspace_delete.sql.go
+++ b/server/pkg/db/generated/workspace_delete.sql.go
@@ -339,6 +339,9 @@ deleted_lark_outbound_cards AS (
DELETE FROM lark_outbound_card_message
WHERE chat_session_id IN (SELECT id FROM ws_sessions)
),
+deleted_chat_submission_receipts AS (
+ DELETE FROM chat_submission_receipt WHERE chat_submission_receipt.workspace_id = $1
+),
deleted_draft_restores AS (
DELETE FROM chat_draft_restore
WHERE chat_session_id IN (SELECT id FROM ws_sessions)
diff --git a/server/pkg/db/queries/chat_submission.sql b/server/pkg/db/queries/chat_submission.sql
new file mode 100644
index 0000000000..343c8a87e3
--- /dev/null
+++ b/server/pkg/db/queries/chat_submission.sql
@@ -0,0 +1,20 @@
+-- name: GetChatSubmissionReceipt :one
+SELECT request_fingerprint, response FROM chat_submission_receipt
+WHERE chat_session_id = $1 AND workspace_id = $2 AND initiator_user_id = $3
+ AND actor_type = $4 AND actor_id = $5 AND submission_id = $6;
+
+-- name: CreateChatSubmissionReceipt :exec
+INSERT INTO chat_submission_receipt (
+ chat_session_id, workspace_id, initiator_user_id, actor_type, actor_id,
+ submission_id, request_fingerprint, response
+) VALUES ($1, $2, $3, $4, $5, $6, $7, $8);
+
+-- name: DeleteChatSubmissionReceiptsBySession :exec
+DELETE FROM chat_submission_receipt WHERE chat_session_id = $1;
+
+-- name: DeleteChatSubmissionReceiptsBySystemRuntimeAgents :exec
+DELETE FROM chat_submission_receipt
+WHERE chat_session_id IN (
+ SELECT cs.id FROM chat_session cs JOIN agent a ON a.id = cs.agent_id
+ WHERE a.runtime_id = $1 AND a.kind = 'system'
+);
diff --git a/server/pkg/db/queries/workspace.sql b/server/pkg/db/queries/workspace.sql
index c3f7d9e4f7..f0ebab18c9 100644
--- a/server/pkg/db/queries/workspace.sql
+++ b/server/pkg/db/queries/workspace.sql
@@ -165,6 +165,9 @@ cleared_outbound_cards AS (
DELETE FROM channel_outbound_card_message
WHERE chat_session_id IN (SELECT chat_session_id FROM cleared_chat_sessions)
),
+cleared_chat_submission_receipts AS (
+ DELETE FROM chat_submission_receipt WHERE chat_submission_receipt.workspace_id = $1
+),
cleared_draft_restores AS (
-- chat_draft_restore is keyed by chat_session_id with no FK (MUL-3515) and has
-- no reaper, while its chat_session rows cascade away with the workspace. Reach
diff --git a/server/pkg/db/queries/workspace_delete.sql b/server/pkg/db/queries/workspace_delete.sql
index 6ace374cee..6c5a21d434 100644
--- a/server/pkg/db/queries/workspace_delete.sql
+++ b/server/pkg/db/queries/workspace_delete.sql
@@ -346,6 +346,9 @@ deleted_lark_outbound_cards AS (
DELETE FROM lark_outbound_card_message
WHERE chat_session_id IN (SELECT id FROM ws_sessions)
),
+deleted_chat_submission_receipts AS (
+ DELETE FROM chat_submission_receipt WHERE chat_submission_receipt.workspace_id = $1
+),
deleted_draft_restores AS (
DELETE FROM chat_draft_restore
WHERE chat_session_id IN (SELECT id FROM ws_sessions)