Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(channel): attach /issue media to created issues (#6388)
YYClaw24d209794e23
diff --git a/apps/mobile/CLAUDE.md b/apps/mobile/CLAUDE.mdindex c265d60ca0..a0b2b770e7 100644--- a/apps/mobile/CLAUDE.md+++ b/apps/mobile/CLAUDE.md@@ -228,7 +228,7 @@ Each hook registers a single `ws.onReconnect(cb)` that invalidates **only the qu|---|---|| `useInboxRealtime` | `inboxKeys.list(wsId)` || `useMyIssuesRealtime` | `issueKeys.myAll(wsId)` |-| `useIssueRealtime(id)` | `issueKeys.detail(wsId, id)` + `issueKeys.timeline(wsId, id)` |+| `useIssueRealtime(id)` | detail + timeline + attachments + active tasks + task history for that issue |No global "invalidate everything on reconnect" sweep. The fanout would be every screen the user has ever visited in this session refetching simultaneously — wasteful on cellular and prone to rate-limiting the server in low-signal areas where reconnects happen frequently.diff --git a/apps/mobile/data/realtime/issue-ws-updaters.test.ts b/apps/mobile/data/realtime/issue-ws-updaters.test.tsnew file mode 100644index 0000000000..08071fa1d5--- /dev/null+++ b/apps/mobile/data/realtime/issue-ws-updaters.test.ts@@ -0,0 +1,24 @@+import { QueryClient } from "@tanstack/react-query";+import { describe, expect, it, vi } from "vitest";++import { issueKeys } from "@/data/queries/issue-keys";+import { invalidateIssueAfterReconnect } from "./issue-ws-updaters";++describe("invalidateIssueAfterReconnect", () => {+ it("invalidates attachments together with the issue and task caches", () => {+ const qc = new QueryClient();+ const invalidate = vi.spyOn(qc, "invalidateQueries");+ const wsId = "workspace-1";+ const issueId = "issue-1";++ invalidateIssueAfterReconnect(qc, wsId, issueId);++ expect(invalidate.mock.calls.map(([filters]) => filters?.queryKey)).toEqual([+ issueKeys.detail(wsId, issueId),+ issueKeys.timeline(wsId, issueId),+ issueKeys.attachments(wsId, issueId),+ issueKeys.activeTasks(wsId, issueId),+ issueKeys.tasks(wsId, issueId),+ ]);+ });+});diff --git a/apps/mobile/data/realtime/issue-ws-updaters.ts b/apps/mobile/data/realtime/issue-ws-updaters.tsindex 0d05ce0203..d5b846151f 100644--- a/apps/mobile/data/realtime/issue-ws-updaters.ts+++ b/apps/mobile/data/realtime/issue-ws-updaters.ts@@ -62,6 +62,18 @@ export function clearIssueDetail(qc.removeQueries({ queryKey: issueKeys.timeline(wsId, issueId) });}+export function invalidateIssueAfterReconnect(+ qc: QueryClient,+ wsId: string,+ issueId: string,+) {+ qc.invalidateQueries({ queryKey: issueKeys.detail(wsId, issueId) });+ qc.invalidateQueries({ queryKey: issueKeys.timeline(wsId, issueId) });+ qc.invalidateQueries({ queryKey: issueKeys.attachments(wsId, issueId) });+ qc.invalidateQueries({ queryKey: issueKeys.activeTasks(wsId, issueId) });+ qc.invalidateQueries({ queryKey: issueKeys.tasks(wsId, issueId) });+}+// =====================================================// Issue timeline (flat TimelineEntry[], ASC oldest-first)// =====================================================diff --git a/apps/mobile/data/realtime/use-issue-realtime.ts b/apps/mobile/data/realtime/use-issue-realtime.tsindex ef4f97d994..898becdcce 100644--- a/apps/mobile/data/realtime/use-issue-realtime.ts+++ b/apps/mobile/data/realtime/use-issue-realtime.ts@@ -4,6 +4,7 @@** Handles:* - issue:updated / issue:deleted / issue_labels:changed → detail cache+ * - issue_attachments:changed → attachment cache* - comment:created / comment:updated / comment:deleted → timeline* - activity:created → timeline* - reaction:added / reaction:removed → comment reactions on timeline@@ -40,6 +41,7 @@ import {appendTimelineEntry,clearIssueDetail,commentToTimelineEntry,+ invalidateIssueAfterReconnect,patchIssueDetail,patchIssueLabels,patchMyIssuesList,@@ -113,6 +115,12 @@ export function useIssueRealtime(if (payload.issue_id !== issueId) return;patchIssueLabels(qc, wsId, issueId, payload.labels);}),+ ws.on("issue_attachments:changed", (payload) => {+ if (payload.issue_id !== issueId) return;+ qc.invalidateQueries({+ queryKey: issueKeys.attachments(wsId, issueId),+ });+ }),// ----- Comments / activity -----ws.on("comment:created", (payload) => {@@ -225,8 +233,7 @@ export function useIssueRealtime(// ----- Reconnect -----ws.onReconnect(() => {- invalidateThisIssue();- invalidateTaskQueries();+ invalidateIssueAfterReconnect(qc, wsId, issueId);}),];},diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex cbd8daf31c..0e12856bad 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -218,6 +218,23 @@ describe("useRealtimeSync — ws instance change", () => {expect(calls).toContainEqual(chatKeys.messagesPageAll());expect(calls).toContainEqual(chatKeys.pendingTaskAll());});++ it("invalidates one issue attachment cache after detached channel media binds", () => {+ const ws = createMockWs();+ renderHook(() => useRealtimeSync(ws, stores), {+ wrapper: createWrapper(qc),+ });+ const attachmentChanged = vi+ .mocked(ws.on)+ .mock.calls.find(([event]) => event === "issue_attachments:changed")?.[1];+ expect(attachmentChanged).toBeDefined();++ (attachmentChanged as (payload: unknown) => void)({ issue_id: "issue-1" });++ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: issueKeys.attachments("issue-1"),+ });+ });});describe("useRealtimeSync — queued chat promotion", () => {diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 044b116ebd..bc3517cb1c 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -68,6 +68,7 @@ import type {IssueUpdatedPayload,IssueCreatedPayload,IssueDeletedPayload,+ IssueAttachmentsChangedPayload,IssueLabelsChangedPayload,IssueMetadataChangedPayload,IssuePropertiesChangedPayload,@@ -878,7 +879,7 @@ export function useRealtimeSync(// Event types handled by specific handlers below -- skip generic refreshconst specificEvents = new Set(["workspace:updated",- "issue:updated", "issue:created", "issue:deleted", "issue_labels:changed", "issue_metadata:changed", "issue_properties:changed", "property:created", "property:updated", "inbox:new",+ "issue:updated", "issue:created", "issue:deleted", "issue_attachments:changed", "issue_labels:changed", "issue_metadata:changed", "issue_properties:changed", "property:created", "property:updated", "inbox:new","comment:created", "comment:updated", "comment:deleted","comment:resolved", "comment:unresolved","activity:created",@@ -954,6 +955,12 @@ export function useRealtimeSync(if (wsId) onIssueLabelsChanged(qc, wsId, issue_id, labels ?? []);});+ const unsubIssueAttachmentsChanged = ws.on("issue_attachments:changed", (p) => {+ const { issue_id } = p as IssueAttachmentsChangedPayload;+ if (!issue_id) return;+ qc.invalidateQueries({ queryKey: issueKeys.attachments(issue_id) });+ });+const unsubIssueMetadataChanged = ws.on("issue_metadata:changed", (p) => {const { issue_id, metadata } = p as IssueMetadataChangedPayload;if (!issue_id) return;@@ -1503,6 +1510,7 @@ export function useRealtimeSync(unsubIssueUpdated();unsubIssueCreated();unsubIssueDeleted();+ unsubIssueAttachmentsChanged();unsubIssueLabelsChanged();unsubIssueMetadataChanged();unsubIssuePropertiesChanged();diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex 58f659b83b..416bfd5872 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -12,6 +12,7 @@ import type { Label } from "./label";export type WSEventType =| "issue:created"| "issue:updated"+ | "issue_attachments:changed"| "issue:deleted"| "comment:created"| "comment:updated"@@ -125,6 +126,10 @@ export interface IssueLabelsChangedPayload {labels: Label[];}+export interface IssueAttachmentsChangedPayload {+ issue_id: string;+}+export interface IssueMetadataChangedPayload {issue_id: string;metadata: IssueMetadata;@@ -501,6 +506,7 @@ export interface WSEventPayloadMap {"issue:created": IssueCreatedPayload;"issue:updated": IssueUpdatedPayload;"issue:deleted": IssueDeletedPayload;+ "issue_attachments:changed": IssueAttachmentsChangedPayload;"issue_labels:changed": IssueLabelsChangedPayload;"issue_properties:changed": IssuePropertiesChangedPayload;"property:created": PropertyChangedPayload;diff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 7402cd6349..1e9ba7671a 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -2,6 +2,7 @@ package mainimport ("context"+ "errors""fmt""log/slog""os"@@ -48,9 +49,53 @@ type preMigrationHook func(ctx context.Context, pool *pgxpool.Pool) error// VALIDATE, so a stuck-at-197 instance auto-heals on `migrate up` with no// manual SQL. A higher-numbered migration cannot help — the instance never// reaches a version above the failing 198.+//+// GH #6388: migration 257 builds a replacement unique index concurrently. A+// failed build can leave an INVALID relation that IF NOT EXISTS would otherwise+// mistake for a successful retry. The hook removes only that invalid leftover;+// migration 257 can then rebuild it while the valid v1 index remains in place.var preMigrationHooks = map[string]preMigrationHook{"103_drop_legacy_daily_rollups": runTaskUsageHourlyHook,"198_agent_task_attribution_strict_constraint_validate": runAttributionStrictHook,+ "257_agent_task_queue_channel_media_pending_unique_v2": cleanupInvalidConcurrentIndexHook("idx_one_pending_task_per_issue_agent_v2"),+}++// cleanupInvalidConcurrentIndexHook removes an INVALID index left by an+// interrupted or failed CREATE INDEX CONCURRENTLY before the migration retries.+// Without this guard, CREATE INDEX ... IF NOT EXISTS would treat the leftover+// relation as success and allow a later migration to drop the still-valid old+// index. Non-index relations fail closed instead of being dropped implicitly.+func cleanupInvalidConcurrentIndexHook(indexRegclass string) preMigrationHook {+ return func(ctx context.Context, pool *pgxpool.Pool) error {+ var schemaName, relationName string+ var isIndex, isValid bool+ err := pool.QueryRow(ctx, `+ SELECT n.nspname, c.relname, c.relkind = 'i', COALESCE(i.indisvalid, FALSE)+ FROM pg_class c+ JOIN pg_namespace n ON n.oid = c.relnamespace+ LEFT JOIN pg_index i ON i.indexrelid = c.oid+ WHERE c.oid = to_regclass($1)+ `, indexRegclass).Scan(&schemaName, &relationName, &isIndex, &isValid)+ if errors.Is(err, pgx.ErrNoRows) {+ return nil+ }+ if err != nil {+ return fmt.Errorf("inspect concurrent index %q: %w", indexRegclass, err)+ }+ if !isIndex {+ return fmt.Errorf("relation %q exists but is not an index", indexRegclass)+ }+ if isValid {+ return nil+ }++ qualifiedName := pgx.Identifier{schemaName, relationName}.Sanitize()+ if _, err := pool.Exec(ctx, "DROP INDEX CONCURRENTLY IF EXISTS "+qualifiedName); err != nil {+ return fmt.Errorf("drop invalid concurrent index %s: %w", qualifiedName, err)+ }+ slog.Warn("removed invalid index before migration retry", "index", qualifiedName)+ return nil+ }}func runTaskUsageHourlyHook(ctx context.Context, pool *pgxpool.Pool) error {diff --git a/server/cmd/migrate/migrate_invalid_index_test.go b/server/cmd/migrate/migrate_invalid_index_test.gonew file mode 100644index 0000000000..474b042166--- /dev/null+++ b/server/cmd/migrate/migrate_invalid_index_test.go@@ -0,0 +1,116 @@+package main++import (+ "context"+ "fmt"+ "math/rand/v2"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+)++func TestRunMigrationsRepairsInvalidConcurrentIndexBeforeRetry(t *testing.T) {+ pool := openTestPool(t)+ ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)+ defer cancel()++ suffix := fmt.Sprintf("%d_%d", time.Now().UnixNano(), rand.Uint32())+ schema := "migrate_invalid_index_" + suffix+ schemaIdent := pgx.Identifier{schema}.Sanitize()+ if _, err := pool.Exec(ctx, "CREATE SCHEMA "+schemaIdent); err != nil {+ t.Fatalf("create schema: %v", err)+ }+ t.Cleanup(func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cleanupCancel()+ if _, err := pool.Exec(cleanupCtx, "DROP SCHEMA IF EXISTS "+schemaIdent+" CASCADE"); err != nil {+ t.Logf("drop schema %s: %v", schema, err)+ }+ })++ tableName := pgx.Identifier{schema, "agent_task_queue"}.Sanitize()+ v1Name := pgx.Identifier{"idx_one_pending_task_per_issue_agent"}.Sanitize()+ v2Name := pgx.Identifier{"idx_one_pending_task_per_issue_agent_v2"}.Sanitize()+ if _, err := pool.Exec(ctx, "CREATE TABLE "+tableName+` (+ id BIGSERIAL PRIMARY KEY,+ issue_id BIGINT NOT NULL,+ agent_id BIGINT NOT NULL,+ status TEXT NOT NULL,+ context JSONB NOT NULL DEFAULT '{}'+ )`); err != nil {+ t.Fatalf("create task table: %v", err)+ }+ if _, err := pool.Exec(ctx, "CREATE UNIQUE INDEX CONCURRENTLY "+v1Name+" ON "+tableName+" (issue_id, agent_id) WHERE status IN ('queued', 'dispatched')"); err != nil {+ t.Fatalf("create valid v1 index: %v", err)+ }+ if _, err := pool.Exec(ctx, "INSERT INTO "+tableName+` (issue_id, agent_id, status, context) VALUES+ (1, 1, 'deferred', '{"channel_issue_media_pending":true}'),+ (1, 1, 'deferred', '{"channel_issue_media_pending":true}')`); err != nil {+ t.Fatalf("seed duplicate deferred rows: %v", err)+ }++ createV2 := "CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS " + v2Name + " ON " + tableName + " (issue_id, agent_id) WHERE status IN ('queued', 'dispatched') OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')"+ if _, err := pool.Exec(ctx, createV2); err == nil {+ t.Fatal("initial v2 build unexpectedly succeeded with duplicate deferred rows")+ }+ assertIndexValidity(t, pool, schema, "idx_one_pending_task_per_issue_agent", true)+ assertIndexValidity(t, pool, schema, "idx_one_pending_task_per_issue_agent_v2", false)++ if _, err := pool.Exec(ctx, "DELETE FROM "+tableName+" WHERE id = (SELECT max(id) FROM "+tableName+")"); err != nil {+ t.Fatalf("remove conflicting row before retry: %v", err)+ }++ const version = "257_agent_task_queue_channel_media_pending_unique_v2"+ if preMigrationHooks[version] == nil {+ t.Fatalf("production hook is not registered for %s", version)+ }+ migrationPath := filepath.Join(t.TempDir(), version+".up.sql")+ if err := os.WriteFile(migrationPath, []byte(createV2+";\n"), 0o600); err != nil {+ t.Fatalf("write retry migration: %v", err)+ }+ indexRegclass := pgx.Identifier{schema, "idx_one_pending_task_per_issue_agent_v2"}.Sanitize()+ opts := runOptions{+ Direction: "up",+ Files: []string{migrationPath},+ SchemaMigrationsTable: schema + ".schema_migrations",+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: map[string]preMigrationHook{+ version: cleanupInvalidConcurrentIndexHook(indexRegclass),+ },+ }+ if err := runMigrations(ctx, pool, opts); err != nil {+ t.Fatalf("retry migration with invalid-index cleanup: %v", err)+ }++ assertIndexValidity(t, pool, schema, "idx_one_pending_task_per_issue_agent", true)+ assertIndexValidity(t, pool, schema, "idx_one_pending_task_per_issue_agent_v2", true)+ var recorded bool+ if err := pool.QueryRow(ctx, "SELECT EXISTS (SELECT 1 FROM "+pgx.Identifier{schema, "schema_migrations"}.Sanitize()+" WHERE version = $1)", version).Scan(&recorded); err != nil {+ t.Fatalf("read migration version: %v", err)+ }+ if !recorded {+ t.Fatal("repaired migration was not recorded")+ }+}++func assertIndexValidity(t *testing.T, pool interface {+ QueryRow(context.Context, string, ...any) pgx.Row+}, schema, index string, want bool) {+ t.Helper()+ var valid bool+ if err := pool.QueryRow(context.Background(), `+ SELECT i.indisvalid+ FROM pg_index i+ JOIN pg_class c ON c.oid = i.indexrelid+ JOIN pg_namespace n ON n.oid = c.relnamespace+ WHERE n.nspname = $1 AND c.relname = $2+ `, schema, index).Scan(&valid); err != nil {+ t.Fatalf("read validity for %s.%s: %v", schema, index, err)+ }+ if valid != want {+ t.Fatalf("index %s.%s validity = %v, want %v", schema, index, valid, want)+ }+}diff --git a/server/internal/handler/channel_new_e2e_test.go b/server/internal/handler/channel_new_e2e_test.goindex 81694a5703..4c603adf60 100644--- a/server/internal/handler/channel_new_e2e_test.go+++ b/server/internal/handler/channel_new_e2e_test.go@@ -326,6 +326,7 @@ func (b *channelNewE2ESessionBinder) BindMedia(ctx context.Context, p engine.BinSessionID: p.SessionID,WorkspaceID: p.WorkspaceID,Sender: p.Sender,+ IssueID: p.IssueID,MediaRefs: p.MediaRefs,})}diff --git a/server/internal/handler/comment.go b/server/internal/handler/comment.goindex 3086fab75a..f0e6743719 100644--- a/server/internal/handler/comment.go+++ b/server/internal/handler/comment.go@@ -2335,7 +2335,7 @@ func commentMergeTerminalOutcome(result commentMergeResult) (status DispatchStat}// mergeCommentIntoPendingTask folds a newly-arrived comment into the existing-// QUEUED (not-yet-claimed) task for (issue, agent) instead of dropping it+// pre-claim task for (issue, agent) instead of dropping it// (MUL-4195). It reports HOW it resolved via commentMergeResult so the caller// never mislabels a refused/failed merge as success (MUL-4525 §2). No path here// enqueues a duplicate: on any failure the original task is kept intact, so thediff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.goindex 7c296a3d73..55640da068 100644--- a/server/internal/handler/issue.go+++ b/server/internal/handler/issue.go@@ -3174,13 +3174,7 @@ func (h *Handler) DeleteIssue(w http.ResponseWriter, r *http.Request) {// Fail any linked autopilot runs before delete (ON DELETE SET NULL clears issue_id).h.Queries.FailAutopilotRunsByIssue(r.Context(), issue.ID)- // Collect all attachment URLs (issue-level + comment-level) before CASCADE delete.- attachmentURLs, _ := h.Queries.ListAttachmentURLsByIssueOrComments(r.Context(), issue.ID)-- err := h.Queries.DeleteIssue(r.Context(), db.DeleteIssueParams{- ID: issue.ID,- WorkspaceID: issue.WorkspaceID,- })+ attachmentURLs, err := h.deleteIssueAndCollectAttachmentURLs(r.Context(), issue)if err != nil {writeError(w, http.StatusInternalServerError, "failed to delete issue")return@@ -3198,6 +3192,41 @@ func (h *Handler) DeleteIssue(w http.ResponseWriter, r *http.Request) {w.WriteHeader(http.StatusNoContent)}+// deleteIssueAndCollectAttachmentURLs serializes issue deletion with channel+// media binding. The delete-side FOR UPDATE conflicts with the binder's+// FOR KEY SHARE, and URL collection happens only after that lock is held:+// bind-first means the new URL is collected; delete-first means the bind rolls+// back without consuming its durable object intent.+func (h *Handler) deleteIssueAndCollectAttachmentURLs(ctx context.Context, issue db.Issue) ([]string, error) {+ tx, err := h.TxStarter.Begin(ctx)+ if err != nil {+ return nil, fmt.Errorf("begin issue delete: %w", err)+ }+ defer tx.Rollback(ctx)+ qtx := h.Queries.WithTx(tx)++ if _, err := qtx.LockIssueForDelete(ctx, db.LockIssueForDeleteParams{+ ID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ }); err != nil {+ return nil, fmt.Errorf("lock issue for delete: %w", err)+ }+ attachmentURLs, err := qtx.ListAttachmentURLsByIssueOrComments(ctx, issue.ID)+ if err != nil {+ return nil, fmt.Errorf("list issue attachment URLs: %w", err)+ }+ if err := qtx.DeleteIssue(ctx, db.DeleteIssueParams{+ ID: issue.ID,+ WorkspaceID: issue.WorkspaceID,+ }); err != nil {+ return nil, fmt.Errorf("delete issue: %w", err)+ }+ if err := tx.Commit(ctx); err != nil {+ return nil, fmt.Errorf("commit issue delete: %w", err)+ }+ return attachmentURLs, nil+}+// ---------------------------------------------------------------------------// Batch operations// ---------------------------------------------------------------------------@@ -3549,13 +3578,8 @@ func (h *Handler) BatchDeleteIssues(w http.ResponseWriter, r *http.Request) {h.TaskService.CancelTasksForIssue(r.Context(), issue.ID)h.Queries.FailAutopilotRunsByIssue(r.Context(), issue.ID)- // Collect attachment URLs before CASCADE delete to clean up S3 objects.- attachmentURLs, _ := h.Queries.ListAttachmentURLsByIssueOrComments(r.Context(), issue.ID)-- if err := h.Queries.DeleteIssue(r.Context(), db.DeleteIssueParams{- ID: issue.ID,- WorkspaceID: issue.WorkspaceID,- }); err != nil {+ attachmentURLs, err := h.deleteIssueAndCollectAttachmentURLs(r.Context(), issue)+ if err != nil {slog.Warn("batch delete issue failed", "issue_id", issueID, "error", err)continue}diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.goindex 17b7556d22..9dca04e8e3 100644--- a/server/internal/integrations/channel/engine/resolvers.go+++ b/server/internal/integrations/channel/engine/resolvers.go@@ -123,13 +123,16 @@ type AppendResult struct {}// BindMediaParams carries stored media references to the post-append-// attachment transaction. MessageID is the durable chat_message created by-// AppendMessage; media downloads must never run inside this transaction.+// attachment transaction. MessageID is the durable chat_message whose pending+// marker the binder clears. IssueID selects issue ownership for an /issue turn;+// otherwise the references bind to MessageID. Media downloads must never run+// inside this transaction.type BindMediaParams struct {MessageID pgtype.UUIDSessionID pgtype.UUIDWorkspaceID pgtype.UUIDSender pgtype.UUID+ IssueID pgtype.UUIDMediaRefs []channel.MediaRef}@@ -208,8 +211,9 @@ type MediaResolver interface {// plain ingest path: no marker, no deferred run, no semaphore slot.HasMedia(msg channel.InboundMessage) bool// ResolveMedia downloads the platform media and uploads it to object- // storage. chatMessageID is the durable chat_message the refs will bind- // to; the intent ledger keys the reconciler's reference check on it.+ // storage. chatMessageID is the durable chat_message that owns the pending+ // intent; the Router decides whether the resulting refs belong to that+ // message or to an issue created from the same turn.ResolveMedia(ctx context.Context, inst ResolvedInstallation, sender ResolvedIdentity, sessionID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage}@@ -312,6 +316,7 @@ type ResolverSet struct {// for the /issue command. Shared across platforms.type IssueCreator interface {Create(ctx context.Context, p service.IssueCreateParams, opts service.IssueCreateOpts) (service.IssueCreateResult, error)+ PublishAttachmentsChanged(issue db.Issue, actorID pgtype.UUID)}// TaskEnqueuer is the narrow subset of service.TaskService the Router needs to@@ -319,6 +324,7 @@ type IssueCreator interface {type TaskEnqueuer interface {EnqueueChatTask(ctx context.Context, session db.ChatSession, initiatorUserID pgtype.UUID, forceFreshSession bool) (db.AgentTaskQueue, error)PromoteChannelChatTasksIfMediaReady(ctx context.Context, sessionID pgtype.UUID) error+ PromoteDeferredChannelIssueTask(ctx context.Context, taskID pgtype.UUID) error}// SessionReader reads the rows the debounced flush + /issue identifier need.diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex 408c811dc4..2093642f07 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -401,6 +401,8 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channeChatSessionID: sessionID,Sender: msg.Source.SenderID,}+ var mediaIssue db.Issue+ var deferredIssueTaskID pgtype.UUID// 7. /issue command, if present. chat_message is already durable; all// error returns from here signal finalizeNone (or the defensive Mark).@@ -408,7 +410,14 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// One lookup feeds both the broadcast payload's identifier and the// chat reply's.prefix := r.issuePrefix(ctx, inst.WorkspaceID)- issueRes, err := r.createIssue(ctx, inst, set.OriginType, identity.UserID, sessionID, *appendRes.IssueCommand, prefix)+ var assignedRunFireAt time.Time+ if resolveMedia {+ // The generic deferred-task sweeper is the crash fallback. Leave room+ // after the media deadline for the bounded attachment finalizer so it+ // cannot race an issue agent reading the newly-created issue.+ assignedRunFireAt = localMediaDeadline.Add(mediaFinalizeTimeout)+ }+ issueRes, err := r.createIssue(ctx, inst, set.OriginType, identity.UserID, sessionID, *appendRes.IssueCommand, prefix, assignedRunFireAt)if errors.Is(err, service.ErrActiveDuplicate) && issueRes.DuplicateIssue != nil {duplicate := *issueRes.DuplicateIssueres.IssueID = duplicate.ID@@ -420,7 +429,7 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// failure and not a chat prompt. Media binding remains independent,// exactly like the successful direct-create path below.if resolveMedia {- r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, localMediaDeadline)+ r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, duplicate, pgtype.UUID{}, localMediaDeadline)}return res, postAppendFinalize, nil}@@ -428,6 +437,8 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channereturn Result{}, postAppendFinalize, fmt.Errorf("create issue from command: %w", err)}res.IssueID = issueRes.Issue.ID+ mediaIssue = issueRes.Issue+ deferredIssueTaskID = issueRes.AssignedTaskIDres.IssueNumber = issueRes.Issue.Numberres.IssueTitle = issueRes.Issue.Title// Same renderer the broadcast payload uses, so a degraded prefix can't@@ -437,7 +448,7 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// Scheduling the command as a chat run too makes the agent execute the// same /issue input again. A synchronous issue command is terminal.if resolveMedia {- r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, localMediaDeadline)+ r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, mediaIssue, deferredIssueTaskID, localMediaDeadline)}return res, postAppendFinalize, nil}@@ -450,7 +461,7 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channer.scheduleRun(set, inst, msg, sessionID, identity.UserID)res.runScheduled = trueif resolveMedia {- r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, localMediaDeadline)+ r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, mediaIssue, deferredIssueTaskID, localMediaDeadline)}return res, postAppendFinalize, nil}@@ -459,7 +470,7 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe// order within a chat session. Run scheduling is independent and durable: the// task service defers a task to the persisted media deadline, then media// completion promotes it early.-func (r *Router) enqueueMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, deadline time.Time) {+func (r *Router) enqueueMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueTaskID pgtype.UUID, deadline time.Time) {key := keyForSession(sessionID)done := make(chan struct{})@@ -514,13 +525,13 @@ func (r *Router) enqueueMedia(set ResolverSet, inst ResolvedInstallation, identi// sees the dead deadline and runs only the empty finalize.}}- r.resolveAndBindMedia(set, inst, identity, chatMessageID, msg, sessionID, deadline)+ r.resolveAndBindMedia(set, inst, identity, chatMessageID, msg, sessionID, issue, issueTaskID, deadline)}()}const mediaFinalizeTimeout = 5 * time.Second-func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, deadline time.Time) {+func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation, identity ResolvedIdentity, chatMessageID pgtype.UUID, msg channel.InboundMessage, sessionID pgtype.UUID, issue db.Issue, issueTaskID pgtype.UUID, deadline time.Time) {ctx, cancel := context.WithDeadline(r.mediaCtx, deadline)defer cancel()@@ -545,13 +556,15 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,"message_id", msg.MessageID,"error", err)}- if err := set.Session.BindMedia(finalizeCtx, BindMediaParams{+ bindErr := set.Session.BindMedia(finalizeCtx, BindMediaParams{MessageID: chatMessageID,SessionID: sessionID,WorkspaceID: inst.WorkspaceID,Sender: identity.UserID,+ IssueID: issue.ID,MediaRefs: resolved.MediaRefs,- }); err != nil {+ })+ if bindErr != nil {// Never delete inline: the attachments may or may not have landed// (an ambiguous commit), but the intent rows are deleted in the SAME// transaction, so the ledger already reflects whichever outcome is@@ -560,7 +573,20 @@ func (r *Router) resolveAndBindMedia(set ResolverSet, inst ResolvedInstallation,"channel_type", string(msg.Source.ChannelType),"event_id", msg.EventID,"message_id", msg.MessageID,- "err", err)+ "err", bindErr)+ }+ if bindErr == nil && issue.ID.Valid && len(resolved.MediaRefs) > 0 {+ r.issues.PublishAttachmentsChanged(issue, identity.UserID)+ }+ if issueTaskID.Valid {+ if err := r.tasks.PromoteDeferredChannelIssueTask(finalizeCtx, issueTaskID); err != nil {+ r.logger.Warn("channel router: media-ready issue task promotion failed",+ "channel_type", string(msg.Source.ChannelType),+ "event_id", msg.EventID,+ "message_id", msg.MessageID,+ "task_id", util.UUIDToString(issueTaskID),+ "err", err)+ }}if err := r.tasks.PromoteChannelChatTasksIfMediaReady(finalizeCtx, sessionID); err != nil {r.logger.Warn("channel router: media-ready task promotion failed",@@ -736,7 +762,7 @@ func (r *Router) drop(ctx context.Context, set ResolverSet, msg channel.InboundMreturn Result{Outcome: OutcomeDropped, DropReason: reason, InstallationID: instID}}-func (r *Router) createIssue(ctx context.Context, inst ResolvedInstallation, originType string, creatorUserID, sessionID pgtype.UUID, cmd IssueCommand, issuePrefix string) (service.IssueCreateResult, error) {+func (r *Router) createIssue(ctx context.Context, inst ResolvedInstallation, originType string, creatorUserID, sessionID pgtype.UUID, cmd IssueCommand, issuePrefix string, assignedRunFireAt time.Time) (service.IssueCreateResult, error) {if cmd.Title == "" {return service.IssueCreateResult{}, ErrEmptyIssueTitle}@@ -762,6 +788,7 @@ func (r *Router) createIssue(ctx context.Context, inst ResolvedInstallation, ori// IssueResponse that handler path broadcasts, so clients see one issue// shape regardless of which entry point created the issue.opts := service.IssueCreateOpts{+ AssignedAgentRunFireAt: assignedRunFireAt,BroadcastPayload: func(issue db.Issue, _ []db.Attachment, _ []db.IssueLabel) map[string]any {return map[string]any{"issue": service.IssueToMap(issue, issuePrefix)}},diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex 3c7205d708..ec6e87ee56 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -242,11 +242,12 @@ func (f *fakeMedia) calls() int {}type fakeIssues struct {- called bool- params service.IssueCreateParams- opts service.IssueCreateOpts- result service.IssueCreateResult- err error+ called bool+ params service.IssueCreateParams+ opts service.IssueCreateOpts+ result service.IssueCreateResult+ err error+ attachmentsChanged int}func (f *fakeIssues) Create(_ context.Context, p service.IssueCreateParams, o service.IssueCreateOpts) (service.IssueCreateResult, error) {@@ -256,14 +257,19 @@ func (f *fakeIssues) Create(_ context.Context, p service.IssueCreateParams, o sereturn f.result, f.err}+func (f *fakeIssues) PublishAttachmentsChanged(db.Issue, pgtype.UUID) {+ f.attachmentsChanged+++}+type fakeTasks struct {- mu sync.Mutex- called bool- callCount int- promotions int- forceFresh bool- initiator pgtype.UUID- err error+ mu sync.Mutex+ called bool+ callCount int+ promotions int+ issueTaskPromotions []pgtype.UUID+ forceFresh bool+ initiator pgtype.UUID+ err error}func (f *fakeTasks) PromoteChannelChatTasksIfMediaReady(_ context.Context, _ pgtype.UUID) error {@@ -273,6 +279,13 @@ func (f *fakeTasks) PromoteChannelChatTasksIfMediaReady(_ context.Context, _ pgtreturn nil}+func (f *fakeTasks) PromoteDeferredChannelIssueTask(_ context.Context, taskID pgtype.UUID) error {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.issueTaskPromotions = append(f.issueTaskPromotions, taskID)+ return nil+}+func (f *fakeTasks) EnqueueChatTask(_ context.Context, _ db.ChatSession, initiator pgtype.UUID, forceFresh bool) (db.AgentTaskQueue, error) {f.mu.Lock()defer f.mu.Unlock()@@ -560,6 +573,9 @@ func TestRouter_Ingested_InTxMark_FinalizeNone(t *testing.T) {if !waitFor(time.Second, func() bool { return len(h.binder.boundMedia().MediaRefs) == 1 }) {t.Fatalf("resolved media not bound after append: %+v", h.binder.boundMedia().MediaRefs)}+ if h.binder.boundMedia().IssueID.Valid {+ t.Fatalf("plain chat media unexpectedly targeted issue %v", h.binder.boundMedia().IssueID)+ }}func TestRouter_NoMediaMessageSkipsMediaPipeline(t *testing.T) {@@ -804,6 +820,7 @@ func TestRouter_IssueCommand_Creates(t *testing.T) {func TestRouter_IssueCommandWithMediaBindsWithoutChatRun(t *testing.T) {h := newHarness(t)+ issueTaskID := uuidFromString(t, "99999999-9999-4999-8999-999999999999")h.binder.appendResult = AppendResult{MessageID: uuidFromString(t, "77777777-7777-4777-8777-777777777777"),DedupMarked: true,@@ -811,9 +828,12 @@ func TestRouter_IssueCommandWithMediaBindsWithoutChatRun(t *testing.T) {Title: "Inspect image",},}- h.issues.result = service.IssueCreateResult{Issue: db.Issue{- ID: uuidFromString(t, "88888888-8888-4888-8888-888888888888"), Number: 43, Title: "Inspect image",- }}+ h.issues.result = service.IssueCreateResult{+ Issue: db.Issue{+ ID: uuidFromString(t, "88888888-8888-4888-8888-888888888888"), Number: 43, Title: "Inspect image",+ },+ AssignedTaskID: issueTaskID,+ }if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {t.Fatalf("Handle: %v", err)}@@ -864,6 +884,18 @@ func TestRouter_IssueCommand_ActiveDuplicateIsTerminalProductOutcome(t *testing.}) {t.Fatalf("duplicate result was not delivered to replier: %+v", h.replier.calls())}+ if !waitFor(time.Second, func() bool { return len(h.binder.boundMedia().MediaRefs) == 1 }) {+ t.Fatalf("duplicate media was not finalized: %+v", h.binder.boundMedia())+ }+ if got := h.binder.boundMedia().IssueID; got != duplicate.ID {+ t.Fatalf("duplicate media target = %v, want %v", got, duplicate.ID)+ }+ h.tasks.mu.Lock()+ issuePromotions := len(h.tasks.issueTaskPromotions)+ h.tasks.mu.Unlock()+ if issuePromotions != 0 {+ t.Fatalf("duplicate media promoted a non-existent issue task, calls=%d", issuePromotions)+ }}func TestRouter_IssueCommand_InfrastructureFailureRemainsError(t *testing.T) {@@ -889,6 +921,109 @@ func TestRouter_IssueCommand_InfrastructureFailureRemainsError(t *testing.T) {}}+func TestRouter_IssueCommand_MediaTargetsCreatedIssue(t *testing.T) {+ h := newHarness(t)+ issueID := uuidFromString(t, "77777777-7777-7777-7777-777777777777")+ issueTaskID := uuidFromString(t, "88888888-8888-4888-8888-888888888888")+ h.binder.appendResult = AppendResult{+ MessageID: uuidFromString(t, "99999999-9999-4999-8999-999999999999"),+ DedupMarked: true,+ IssueCommand: &IssueCommand{+ Title: "Fix broken layout",+ },+ }+ h.issues.result = service.IssueCreateResult{+ Issue: db.Issue{ID: issueID, Number: 42, Title: "Fix broken layout"},+ AssignedTaskID: issueTaskID,+ }++ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("Handle: %v", err)+ }+ if !waitFor(time.Second, func() bool { return len(h.binder.boundMedia().MediaRefs) == 1 }) {+ t.Fatalf("resolved media not bound: %+v", h.binder.boundMedia())+ }+ if got := h.binder.boundMedia().IssueID; got != issueID {+ t.Fatalf("media target issue = %v, want %v", got, issueID)+ }+ if h.issues.opts.AssignedAgentRunFireAt.IsZero() {+ t.Fatal("media-backed /issue must defer its assigned-agent task")+ }+ if !waitFor(time.Second, func() bool {+ h.tasks.mu.Lock()+ defer h.tasks.mu.Unlock()+ return len(h.tasks.issueTaskPromotions) == 1+ }) {+ t.Fatal("deferred issue task was not promoted after media binding")+ }+ h.tasks.mu.Lock()+ gotTaskID := h.tasks.issueTaskPromotions[0]+ h.tasks.mu.Unlock()+ if gotTaskID != issueTaskID {+ t.Fatalf("promoted issue task = %v, want %v", gotTaskID, issueTaskID)+ }+ if h.issues.attachmentsChanged != 1 {+ t.Fatalf("attachment change events = %d, want 1", h.issues.attachmentsChanged)+ }+}++func TestRouter_IssueCommand_WithoutMediaKeepsImmediateAssignedTask(t *testing.T) {+ h := newHarness(t)+ h.media.noMedia = true+ h.binder.appendResult = AppendResult{+ DedupMarked: true,+ IssueCommand: &IssueCommand{+ Title: "Fix broken layout",+ },+ }+ h.issues.result = service.IssueCreateResult{+ Issue: db.Issue{ID: uuidFromString(t, "77777777-7777-7777-7777-777777777777"), Number: 42, Title: "Fix broken layout"},+ }++ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("Handle: %v", err)+ }+ if !h.issues.opts.AssignedAgentRunFireAt.IsZero() {+ t.Fatalf("text-only /issue unexpectedly deferred its assigned task until %v", h.issues.opts.AssignedAgentRunFireAt)+ }+ h.tasks.mu.Lock()+ promotions := len(h.tasks.issueTaskPromotions)+ h.tasks.mu.Unlock()+ if promotions != 0 {+ t.Fatalf("text-only /issue task promotions = %d, want 0", promotions)+ }+}++func TestRouter_IssueCommand_BindFailurePromotesDeferredTaskWithoutAttachmentEvent(t *testing.T) {+ h := newHarness(t)+ issueTaskID := uuidFromString(t, "88888888-8888-4888-8888-888888888888")+ h.binder.appendResult = AppendResult{+ DedupMarked: true,+ IssueCommand: &IssueCommand{+ Title: "Fix broken layout",+ },+ }+ h.binder.bindErr = errors.New("attachment write failed")+ h.issues.result = service.IssueCreateResult{+ Issue: db.Issue{ID: uuidFromString(t, "77777777-7777-7777-7777-777777777777"), Number: 42, Title: "Fix broken layout"},+ AssignedTaskID: issueTaskID,+ }++ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {+ t.Fatalf("Handle: %v", err)+ }+ if !waitFor(time.Second, func() bool {+ h.tasks.mu.Lock()+ defer h.tasks.mu.Unlock()+ return len(h.tasks.issueTaskPromotions) == 1+ }) {+ t.Fatal("failed attachment bind left the issue task deferred")+ }+ if h.issues.attachmentsChanged != 0 {+ t.Fatalf("attachment change events after failed bind = %d, want 0", h.issues.attachmentsChanged)+ }+}+func TestRouter_GroupSessionCreatorIsInstaller(t *testing.T) {h := newHarness(t)msg := p2pMessage(t)diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.goindex 219475c456..1fa40832a4 100644--- a/server/internal/integrations/channel/engine/session.go+++ b/server/internal/integrations/channel/engine/session.go@@ -45,6 +45,7 @@ type SessionQueries interface {CreateChannelChatSessionBinding(ctx context.Context, arg db.CreateChannelChatSessionBindingParams) (db.ChannelChatSessionBinding, error)CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error)ClearChatMessageChannelMediaPending(ctx context.Context, arg db.ClearChatMessageChannelMediaPendingParams) error+ LockIssueForChannelMediaBind(ctx context.Context, arg db.LockIssueForChannelMediaBindParams) (pgtype.UUID, error)CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error)LinkAttachmentsToChatMessage(ctx context.Context, arg db.LinkAttachmentsToChatMessageParams) ([]pgtype.UUID, error)ClaimChannelMediaPendingObjectsForBind(ctx context.Context, arg db.ClaimChannelMediaPendingObjectsForBindParams) ([]string, error)@@ -80,6 +81,9 @@ func (a dbSessionQueries) CreateChatMessage(ctx context.Context, arg db.CreateChfunc (a dbSessionQueries) ClearChatMessageChannelMediaPending(ctx context.Context, arg db.ClearChatMessageChannelMediaPendingParams) error {return a.q.ClearChatMessageChannelMediaPending(ctx, arg)}+func (a dbSessionQueries) LockIssueForChannelMediaBind(ctx context.Context, arg db.LockIssueForChannelMediaBindParams) (pgtype.UUID, error) {+ return a.q.LockIssueForChannelMediaBind(ctx, arg)+}func (a dbSessionQueries) CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error) {return a.q.CreateAttachment(ctx, arg)}@@ -270,14 +274,15 @@ type AppendInput struct {MediaPendingSeconds float64}-// BindMediaInput links already-uploaded media to a durable chat message in a-// short database-only transaction. Remote downloads/uploads happen before-// this call and outside the connector ACK path.+// BindMediaInput links already-uploaded media to either an /issue target or a+// durable chat message in a short database-only transaction. Remote downloads/+// uploads happen before this call and outside the connector ACK path.type BindMediaInput struct {MessageID pgtype.UUIDSessionID pgtype.UUIDWorkspaceID pgtype.UUIDSender pgtype.UUID+ IssueID pgtype.UUIDMediaRefs []channel.MediaRef}@@ -370,10 +375,11 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Apreturn AppendResult{MessageID: msg.ID, IssueCommand: cmd, DedupMarked: markedInTx}, nil}-// BindMediaRefs creates attachment rows, links them to an existing durable chat-// message, and clears its media-pending marker. A link failure rolls back the-// attachment rows, then clears the marker separately so the placeholder can be-// promoted immediately for graceful degradation.+// BindMediaRefs creates attachment rows owned by IssueID when present, otherwise+// links them to the existing durable chat message. It also clears the message's+// media-pending marker. A failure rolls back the attachment rows, then clears+// the marker separately so the placeholder can be promoted immediately for+// graceful degradation.func (s *ChatSession) BindMediaRefs(ctx context.Context, in BindMediaInput) error {tx, err := s.tx.Begin(ctx)if err != nil {@@ -429,6 +435,14 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in}keys = append(keys, ref.StorageKey)}+ if in.IssueID.Valid {+ if _, err := qtx.LockIssueForChannelMediaBind(ctx, db.LockIssueForChannelMediaBindParams{+ ID: in.IssueID,+ WorkspaceID: in.WorkspaceID,+ }); err != nil {+ return fmt.Errorf("validate issue media target: %w", err)+ }+ }// Claim the intent-ledger rows inside this same transaction: commit// landed <=> intents gone, atomically, so an ambiguous COMMIT never needs// adjudication. A key the reconciler already moved to 'deleting' is not@@ -464,10 +478,15 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, inif filename == "" {filename = defaultMediaFilename(ref.Type, id.String(), contentType)}+ chatSessionID := in.SessionID+ if in.IssueID.Valid {+ chatSessionID = pgtype.UUID{}+ }att, err := qtx.CreateAttachment(ctx, db.CreateAttachmentParams{ID: pgtype.UUID{Bytes: id, Valid: true},WorkspaceID: in.WorkspaceID,- ChatSessionID: in.SessionID,+ IssueID: in.IssueID,+ ChatSessionID: chatSessionID,UploaderType: "member",UploaderID: in.Sender,Filename: filename,@@ -476,13 +495,16 @@ func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, inSizeBytes: ref.SizeBytes,})if err != nil {- return fmt.Errorf("create chat attachment: %w", err)+ return fmt.Errorf("create channel attachment: %w", err)}ids = append(ids, att.ID)}if len(ids) == 0 {return nil}+ if in.IssueID.Valid {+ return nil+ }if _, err := qtx.LinkAttachmentsToChatMessage(ctx, db.LinkAttachmentsToChatMessageParams{ChatMessageID: in.MessageID,ChatSessionID: in.SessionID,diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.goindex fa26ce939a..1b6d8e21d1 100644--- a/server/internal/integrations/channel/engine/session_db_test.go+++ b/server/internal/integrations/channel/engine/session_db_test.go@@ -214,6 +214,181 @@ func TestBindMediaRefs_PersistsAndLinksAttachmentToDurableMessage(t *testing.T)}}+func TestBindMediaRefs_IssueAttachmentSurvivesChatSessionDeletion(t *testing.T) {+ pool := sessionPersistenceTestDB(t)+ fixture := seedSessionPersistenceFixture(t, pool)+ session := NewChatSession(db.New(pool), pool, channel.TypeFeishu, SessionTitles{})+ ctx := context.Background()++ appendRes, err := session.AppendUserMessage(ctx, AppendInput{+ SessionID: fixture.sessionID,+ Sender: fixture.userID,+ Body: "/issue Fix broken layout [Image]",+ MediaPendingSeconds: 60,+ })+ if err != nil {+ t.Fatalf("AppendUserMessage: %v", err)+ }+ var issueID pgtype.UUID+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, number)+ VALUES ($1, 'Fix broken layout', 'todo', 'none', 'member', $2, 1)+ RETURNING id+ `, fixture.workspaceID, fixture.userID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ const key = "workspaces/ws/lark/issue-image"+ const url = "https://cdn.example.test/issue-image"+ seedPendingMediaObject(t, pool, fixture, appendRes.MessageID, key, url, "pending")+ if err := session.BindMediaRefs(ctx, BindMediaInput{+ MessageID: appendRes.MessageID,+ SessionID: fixture.sessionID,+ WorkspaceID: fixture.workspaceID,+ Sender: fixture.userID,+ IssueID: issueID,+ MediaRefs: []channel.MediaRef{{+ Type: channel.MsgTypeImage,+ StorageKey: key,+ StorageURL: url,+ Filename: "issue-image.png",+ MimeType: "image/png",+ SizeBytes: 3,+ }},+ }); err != nil {+ t.Fatalf("BindMediaRefs: %v", err)+ }+ if _, exists := pendingMediaObjectState(t, pool, key); exists {+ t.Fatal("issue bind must clear the intent row in the same transaction")+ }++ var attachmentID, gotIssueID pgtype.UUID+ var chatSessionID, chatMessageID pgtype.UUID+ if err := pool.QueryRow(ctx, `+ SELECT id, issue_id, chat_session_id, chat_message_id+ FROM attachment+ WHERE workspace_id = $1 AND url = $2+ `, fixture.workspaceID, url).Scan(&attachmentID, &gotIssueID, &chatSessionID, &chatMessageID); err != nil {+ t.Fatalf("load issue attachment: %v", err)+ }+ if gotIssueID != issueID || chatSessionID.Valid || chatMessageID.Valid {+ t.Fatalf("attachment ownership = issue:%v session:%v message:%v", gotIssueID, chatSessionID, chatMessageID)+ }++ if _, err := pool.Exec(ctx, `DELETE FROM chat_session WHERE id = $1`, fixture.sessionID); err != nil {+ t.Fatalf("delete chat session: %v", err)+ }+ var remaining int+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM attachment WHERE id = $1 AND issue_id = $2`, attachmentID, issueID).Scan(&remaining); err != nil {+ t.Fatalf("count issue attachment after chat deletion: %v", err)+ }+ if remaining != 1 {+ t.Fatalf("issue attachment rows after chat deletion = %d, want 1", remaining)+ }+}++func TestIssueDeleteLockPreventsLateMediaBindFromOrphaningObject(t *testing.T) {+ pool := sessionPersistenceTestDB(t)+ fixture := seedSessionPersistenceFixture(t, pool)+ session := NewChatSession(db.New(pool), pool, channel.TypeFeishu, SessionTitles{})+ ctx := context.Background()++ appendRes, err := session.AppendUserMessage(ctx, AppendInput{+ SessionID: fixture.sessionID,+ Sender: fixture.userID,+ Body: "/issue Delete while binding [Image]",+ MediaPendingSeconds: 60,+ })+ if err != nil {+ t.Fatalf("AppendUserMessage: %v", err)+ }+ var issueID pgtype.UUID+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, creator_type, creator_id, number)+ VALUES ($1, 'Delete while binding', 'todo', 'none', 'member', $2, 2)+ RETURNING id`, fixture.workspaceID, fixture.userID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ const key = "workspaces/ws/lark/delete-race-image"+ const url = "https://cdn.example.test/delete-race-image"+ seedPendingMediaObject(t, pool, fixture, appendRes.MessageID, key, url, "pending")++ deleteTx, err := pool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin delete transaction: %v", err)+ }+ defer deleteTx.Rollback(ctx)+ deleteQueries := db.New(pool).WithTx(deleteTx)+ if _, err := deleteQueries.LockIssueForDelete(ctx, db.LockIssueForDeleteParams{+ ID: issueID, WorkspaceID: fixture.workspaceID,+ }); err != nil {+ t.Fatalf("lock issue for delete: %v", err)+ }++ bindTx, err := pool.Begin(ctx)+ if err != nil {+ t.Fatalf("begin bind transaction: %v", err)+ }+ defer bindTx.Rollback(ctx)+ var bindPID int32+ if err := bindTx.QueryRow(ctx, `SELECT pg_backend_pid()`).Scan(&bindPID); err != nil {+ t.Fatalf("load bind backend pid: %v", err)+ }+ bindResult := make(chan error, 1)+ go func() {+ _, lockErr := db.New(pool).WithTx(bindTx).LockIssueForChannelMediaBind(context.Background(), db.LockIssueForChannelMediaBindParams{+ ID: issueID, WorkspaceID: fixture.workspaceID,+ })+ bindResult <- lockErr+ }()++ blocked := false+ for deadline := time.Now().Add(2 * time.Second); time.Now().Before(deadline); {+ if err := pool.QueryRow(ctx, `SELECT cardinality(pg_blocking_pids($1)) > 0`, bindPID).Scan(&blocked); err != nil {+ t.Fatalf("inspect bind lock wait: %v", err)+ }+ if blocked {+ break+ }+ time.Sleep(10 * time.Millisecond)+ }+ if !blocked {+ t.Fatal("media bind did not block behind the delete lock")+ }++ urls, err := deleteQueries.ListAttachmentURLsByIssueOrComments(ctx, issueID)+ if err != nil {+ t.Fatalf("list attachment URLs under delete lock: %v", err)+ }+ if len(urls) != 0 {+ t.Fatalf("attachment URLs before blocked bind = %v, want none", urls)+ }+ if err := deleteQueries.DeleteIssue(ctx, db.DeleteIssueParams{ID: issueID, WorkspaceID: fixture.workspaceID}); err != nil {+ t.Fatalf("delete issue: %v", err)+ }+ if err := deleteTx.Commit(ctx); err != nil {+ t.Fatalf("commit issue delete: %v", err)+ }++ select {+ case err := <-bindResult:+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("bind lock after delete = %v, want no target row", err)+ }+ case <-time.After(2 * time.Second):+ t.Fatal("media bind stayed blocked after delete commit")+ }+ if state, exists := pendingMediaObjectState(t, pool, key); !exists || state != "pending" {+ t.Fatalf("intent after delete-first race = (%q, %v), want preserved pending", state, exists)+ }+ var attachmentCount int+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM attachment WHERE url = $1`, url).Scan(&attachmentCount); err != nil {+ t.Fatalf("count leaked attachment rows: %v", err)+ }+ if attachmentCount != 0 {+ t.Fatalf("attachment rows after delete-first race = %d, want 0", attachmentCount)+ }+}+type failingLinkSessionQueries struct {SessionQueries}diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.goindex f076d7a0d6..6594a45ea2 100644--- a/server/internal/integrations/channel/engine/session_test.go+++ b/server/internal/integrations/channel/engine/session_test.go@@ -2,6 +2,7 @@ package engineimport ("context"+ "errors""fmt""testing"@@ -49,6 +50,7 @@ type fakeSessionQueries struct {linked db.LinkAttachmentsToChatMessageParamsmediaCleared intreconcilerOwnedKeys map[string]bool+ issueLookupErr errorprevMessage *string // GetMostRecentUserChatMessage result; nil → ErrNoRowsmarkRows int64 // MarkChannelInboundDedupProcessed result@@ -104,6 +106,13 @@ func (f *fakeSessionQueries) ClearChatMessageChannelMediaPending(context.Contextreturn nil}+func (f *fakeSessionQueries) LockIssueForChannelMediaBind(_ context.Context, arg db.LockIssueForChannelMediaBindParams) (pgtype.UUID, error) {+ if f.issueLookupErr != nil {+ return pgtype.UUID{}, f.issueLookupErr+ }+ return arg.ID, nil+}+func (f *fakeSessionQueries) CreateAttachment(_ context.Context, arg db.CreateAttachmentParams) (db.Attachment, error) {f.attachments = append(f.attachments, arg)return db.Attachment{ID: arg.ID}, nil@@ -384,6 +393,9 @@ func TestBindMediaRefs_CreatesAndLinksChatAttachments(t *testing.T) {if att.WorkspaceID != uid(9) || att.ChatSessionID != uid(1) || att.UploaderType != "member" || att.UploaderID != uid(7) {t.Fatalf("attachment ownership/session wrong: %+v", att)}+ if att.IssueID.Valid {+ t.Fatalf("plain chat attachment unexpectedly targeted issue %v", att.IssueID)+ }if att.Filename != "screenshot.png" || att.Url != "https://cdn.example.test/lark/cli/img.png" ||att.ContentType != "image/png" || att.SizeBytes != 3 {t.Fatalf("attachment metadata wrong: %+v", att)@@ -396,6 +408,71 @@ func TestBindMediaRefs_CreatesAndLinksChatAttachments(t *testing.T) {}}+func TestBindMediaRefs_CreatesIssueOwnedAttachments(t *testing.T) {+ f := newFake()+ s := newTestSession(f)+ err := s.BindMediaRefs(context.Background(), BindMediaInput{+ MessageID: uid(42),+ SessionID: uid(1),+ WorkspaceID: uid(9),+ Sender: uid(7),+ IssueID: uid(8),+ MediaRefs: []channel.MediaRef{{+ Type: channel.MsgTypeImage,+ StorageKey: "lark/cli/issue.png",+ StorageURL: "https://cdn.example.test/lark/cli/issue.png",+ Filename: "issue.png",+ MimeType: "image/png",+ SizeBytes: 3,+ }},+ })+ if err != nil {+ t.Fatalf("BindMediaRefs: %v", err)+ }+ if len(f.attachments) != 1 {+ t.Fatalf("attachments created = %d, want 1", len(f.attachments))+ }+ att := f.attachments[0]+ if att.IssueID != uid(8) {+ t.Fatalf("attachment issue = %v, want %v", att.IssueID, uid(8))+ }+ if att.ChatSessionID.Valid {+ t.Fatalf("issue attachment must not retain chat-session ownership: %+v", att.ChatSessionID)+ }+ if f.linked.ChatMessageID.Valid || len(f.linked.AttachmentIds) != 0 {+ t.Fatalf("issue attachment must not also bind to chat message: %+v", f.linked)+ }+ if f.mediaCleared != 1 {+ t.Fatalf("media pending marker clears = %d, want 1", f.mediaCleared)+ }+}++func TestBindMediaRefs_MissingIssueRollsBackAndClearsPendingMarker(t *testing.T) {+ f := newFake()+ f.issueLookupErr = pgx.ErrNoRows+ s := newTestSession(f)+ err := s.BindMediaRefs(context.Background(), BindMediaInput{+ MessageID: uid(42),+ SessionID: uid(1),+ WorkspaceID: uid(9),+ Sender: uid(7),+ IssueID: uid(8),+ MediaRefs: []channel.MediaRef{{+ StorageKey: "lark/cli/deleted-issue.png",+ StorageURL: "https://cdn.example.test/lark/cli/deleted-issue.png",+ }},+ })+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Fatalf("BindMediaRefs error = %v, want missing issue", err)+ }+ if len(f.attachments) != 0 || len(f.linked.AttachmentIds) != 0 {+ t.Fatalf("missing issue created or linked attachments: created=%d linked=%d", len(f.attachments), len(f.linked.AttachmentIds))+ }+ if f.mediaCleared != 1 {+ t.Fatalf("media pending marker clears = %d, want 1", f.mediaCleared)+ }+}+func TestAppendUserMessage_BareIssueUsesPreviousMessage(t *testing.T) {f := newFake()prev := "Make the export button work"diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.goindex 9c8701c037..b5cae30651 100644--- a/server/internal/integrations/lark/feishu_resolvers.go+++ b/server/internal/integrations/lark/feishu_resolvers.go@@ -226,6 +226,7 @@ func (r *feishuSessionBinder) BindMedia(ctx context.Context, p engine.BindMediaPSessionID: p.SessionID,WorkspaceID: p.WorkspaceID,Sender: p.Sender,+ IssueID: p.IssueID,MediaRefs: p.MediaRefs,})}diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.goindex 045bf49e86..82d0b5b611 100644--- a/server/internal/integrations/lark/feishu_resolvers_test.go+++ b/server/internal/integrations/lark/feishu_resolvers_test.go@@ -165,12 +165,13 @@ func TestFeishuSessionBinder_BindMediaMapping(t *testing.T) {SessionID: binderUUID(1),WorkspaceID: binderUUID(2),Sender: binderUUID(7),+ IssueID: binderUUID(8),MediaRefs: []channel.MediaRef{ref},}); err != nil {t.Fatalf("BindMedia: %v", err)}got := f.mediaIn- if got.MessageID != binderUUID(4) || got.SessionID != binderUUID(1) || got.WorkspaceID != binderUUID(2) || got.Sender != binderUUID(7) || len(got.MediaRefs) != 1 || got.MediaRefs[0] != ref {+ if got.MessageID != binderUUID(4) || got.SessionID != binderUUID(1) || got.WorkspaceID != binderUUID(2) || got.Sender != binderUUID(7) || got.IssueID != binderUUID(8) || len(got.MediaRefs) != 1 || got.MediaRefs[0] != ref {t.Fatalf("media mapping wrong: %+v", got)}}diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.goindex 464106bb99..8d183cff39 100644--- a/server/internal/integrations/slack/resolvers.go+++ b/server/internal/integrations/slack/resolvers.go@@ -357,6 +357,7 @@ func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams)SessionID: p.SessionID,WorkspaceID: p.WorkspaceID,Sender: p.Sender,+ IssueID: p.IssueID,MediaRefs: p.MediaRefs,})}diff --git a/server/internal/service/duplicate_pending_task_test.go b/server/internal/service/duplicate_pending_task_test.goindex 779a1d9450..4663f413f3 100644--- a/server/internal/service/duplicate_pending_task_test.go+++ b/server/internal/service/duplicate_pending_task_test.go@@ -15,23 +15,32 @@ import ()// TestIsDuplicatePendingTaskErr locks the driver-code detection (#5914): only a-// 23505 on the idx_one_pending_task_per_issue_agent index is a benign-// duplicate-pending-task race. A different unique constraint (e.g. the agent-// name) or a plain error must not be mistaken for it, and the wrapped sentinel-// must remain detectable via errors.Is by callers. This runs without a database.+// 23505 on either pending-task index name used during the v1/v2 rolling-deploy+// window is a benign duplicate-pending-task race. A different unique constraint+// (e.g. the agent name) or a plain error must not be mistaken for it, and the+// wrapped sentinel must remain detectable via errors.Is by callers. This runs+// without a database.func TestIsDuplicatePendingTaskErr(t *testing.T) {- dup := &pgconn.PgError{Code: "23505", ConstraintName: "idx_one_pending_task_per_issue_agent"}- if !isDuplicatePendingTaskErr(dup) {- t.Fatal("expected the pending-task unique-index violation to be recognized")+ for _, indexName := range []string{+ "idx_one_pending_task_per_issue_agent",+ "idx_one_pending_task_per_issue_agent_v2",+ } {+ dup := &pgconn.PgError{Code: "23505", ConstraintName: indexName}+ if !isDuplicatePendingTaskErr(dup) {+ t.Errorf("expected pending-task index %q to be recognized", indexName)+ }}if isDuplicatePendingTaskErr(&pgconn.PgError{Code: "23505", ConstraintName: "agent_workspace_name_unique"}) {t.Fatal("a different unique constraint must not be treated as a duplicate pending task")}+ if isDuplicatePendingTaskErr(&pgconn.PgError{Code: "40001", ConstraintName: "idx_one_pending_task_per_issue_agent_v2"}) {+ t.Fatal("a non-unique-violation SQLSTATE must not be treated as a duplicate pending task")+ }if isDuplicatePendingTaskErr(errors.New("boom")) {t.Fatal("a non-pg error must not be treated as a duplicate pending task")}- wrapped := fmt.Errorf("%w: %v", ErrDuplicatePendingTask, dup)+ wrapped := fmt.Errorf("%w: duplicate pending task", ErrDuplicatePendingTask)if !errors.Is(wrapped, ErrDuplicatePendingTask) {t.Fatal("the wrapped sentinel must stay detectable via errors.Is")}diff --git a/server/internal/service/issue.go b/server/internal/service/issue.goindex 124d8c5ab9..67a5c45625 100644--- a/server/internal/service/issue.go+++ b/server/internal/service/issue.go@@ -5,6 +5,7 @@ import ("errors""fmt""log/slog"+ "time""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"@@ -112,6 +113,12 @@ type IssueCreateOpts struct {// daemon / lark / autopilot). Derived from middleware's client// metadata at the handler layer.Platform string++ // AssignedAgentRunFireAt creates the automatic assigned-agent task in a+ // durable deferred state. Channel /issue uses this while detached media is+ // still resolving, then promotes the returned task after attachment binding.+ // Zero preserves the ordinary immediate enqueue path.+ AssignedAgentRunFireAt time.Time}// ErrActiveDuplicate signals that the duplicate guard found an active@@ -149,6 +156,9 @@ var ErrIssueLabelNotFound = errors.New("issue label not found in this workspace"type IssueCreateResult struct {Issue db.IssueAttachments []db.Attachment+ // AssignedTaskID is populated when Create enqueues the automatic task for+ // an agent assignee, including a task deferred by AssignedAgentRunFireAt.+ AssignedTaskID pgtype.UUID// Labels is the authoritative set of labels attached to the new issue in// the create transaction (empty when none were requested). Callers echo it// on the create response + issue:created event so every client renders the@@ -167,10 +177,13 @@ type IssueCreateResult struct {// 5. Insert the issue row (with optional origin stamping).// 6. Commit.// 7. Link any pre-uploaded attachments (post-commit, idempotent).-// 8. Publish EventIssueCreated to the bus (payload via opts.BroadcastPayload).-// 9. Capture the IssueCreated analytics event.-// 10. Enqueue an agent task or trigger the squad leader when the issue is-// assigned and not in `backlog`.+// 8. For a media-gated channel issue, persist its deferred assigned-agent+// task in the issue transaction so both rows become visible atomically.+// Ordinary creates keep their existing event-before-enqueue ordering.+// 9. Publish EventIssueCreated to the bus (payload via opts.BroadcastPayload).+// 10. Capture the IssueCreated analytics event.+// 11. Enqueue the ordinary agent task or trigger the squad leader when the+// issue is assigned and not in `backlog`.//// Validation that lives in the service (parent existence, project// workspace membership, parent → project back-fill) is enforced here so@@ -254,6 +267,7 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss}var issue db.Issue+ var assignedTask db.AgentTaskQueueif p.OriginType.Valid {issue, err = qtx.CreateIssueWithOrigin(ctx, db.CreateIssueWithOriginParams{WorkspaceID: p.WorkspaceID,@@ -315,6 +329,17 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts Iss}}+ if !opts.AssignedAgentRunFireAt.IsZero() && s.shouldEnqueueAgentTaskWithQueries(ctx, qtx, issue) {+ // The issue must never become visible without its media-gated assigned+ // task. Inserting both rows through qtx makes the unique-index winner+ // deterministic: any observer that can discover the committed issue also+ // sees the inert deferred task and must merge into it.+ assignedTask, err = s.TaskService.createDeferredChannelIssueTaskWithQueries(ctx, qtx, issue, opts.AssignedAgentRunFireAt)+ if err != nil {+ return IssueCreateResult{}, fmt.Errorf("create deferred channel issue task: %w", err)+ }+ }+if err := tx.Commit(ctx); err != nil {return IssueCreateResult{}, fmt.Errorf("commit: %w", err)}@@ -326,11 +351,34 @@ func (s *IssueService) Create(ctx context.Context, p IssueCreateParams, opts IssactorID = util.UUIDToString(issue.CreatorID)}+ var assignedTaskID pgtype.UUID+ if !opts.AssignedAgentRunFireAt.IsZero() {+ assignedTaskID = assignedTask.ID+ if assignedTaskID.Valid {+ if err := s.TaskService.hydrateDeferredChannelIssueTaskOverlay(ctx, assignedTask); err != nil {+ // Runtime overlays are best-effort on every enqueue path. The task is+ // already durable and safely deferred, so an optional integration+ // failure must not turn a committed issue into a retry duplicate.+ slog.Warn("hydrate deferred channel issue task overlay failed",+ "issue_id", util.UUIDToString(issue.ID),+ "task_id", util.UUIDToString(assignedTask.ID),+ "error", err)+ }+ } else if s.shouldEnqueueSquadLeaderOnAssign(ctx, issue) {+ // AssignedAgentRunFireAt currently belongs to channel /issue, which+ // always resolves an agent assignee. Preserve the ordinary squad path+ // for any future caller that supplies the option with a squad.+ s.enqueueSquadLeaderTask(ctx, issue, pgtype.UUID{}, p.CreatorType, actorID)+ }+ }+s.publishIssueCreated(issue, attachments, labels, p.CreatorType, actorID, opts)s.captureCreatedAnalytics(issue, p.CreatorType, actorID, opts)- s.maybeEnqueueOnAssign(ctx, issue, p.CreatorType, actorID)+ if opts.AssignedAgentRunFireAt.IsZero() {+ assignedTaskID = s.maybeEnqueueOnAssign(ctx, issue, p.CreatorType, actorID, opts.AssignedAgentRunFireAt)+ }- return IssueCreateResult{Issue: issue, Attachments: attachments, Labels: labels}, nil+ return IssueCreateResult{Issue: issue, Attachments: attachments, Labels: labels, AssignedTaskID: assignedTaskID}, nil}// validateIssueLabels checks that every requested label exists in the@@ -430,6 +478,25 @@ func (s *IssueService) publishIssueCreated(issue db.Issue, attachments []db.Atta})}+// PublishAttachmentsChanged refreshes the per-issue attachment cache after a+// detached channel media transaction. Issue creation is broadcast before the+// remote download finishes, so this follow-up event closes the realtime gap+// for a detail page opened from the immediate /issue confirmation.+func (s *IssueService) PublishAttachmentsChanged(issue db.Issue, actorID pgtype.UUID) {+ if s.Bus == nil {+ return+ }+ s.Bus.Publish(events.Event{+ Type: protocol.EventIssueAttachmentsChanged,+ WorkspaceID: util.UUIDToString(issue.WorkspaceID),+ ActorType: "member",+ ActorID: util.UUIDToString(actorID),+ Payload: map[string]any{+ "issue_id": util.UUIDToString(issue.ID),+ },+ })+}+func (s *IssueService) captureCreatedAnalytics(issue db.Issue, creatorType, actorID string, opts IssueCreateOpts) {if s.Analytics == nil {return@@ -478,20 +545,30 @@ func classifyOrigin(issue db.Issue, opts IssueCreateOpts) (source, taskID, autop}}-func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue, creatorType, actorID string) {+func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue, creatorType, actorID string, agentRunFireAt time.Time) pgtype.UUID {if !issue.AssigneeType.Valid || !issue.AssigneeID.Valid {- return+ return pgtype.UUID{}}if s.shouldEnqueueAgentTask(ctx, issue) {- if _, err := s.TaskService.EnqueueTaskForIssue(ctx, issue); err != nil {+ var task db.AgentTaskQueue+ var err error+ if agentRunFireAt.IsZero() {+ task, err = s.TaskService.EnqueueTaskForIssue(ctx, issue)+ } else {+ task, err = s.TaskService.EnqueueDeferredChannelIssueTask(ctx, issue, agentRunFireAt)+ }+ if err != nil {slog.Warn("enqueue agent task on create failed","issue_id", util.UUIDToString(issue.ID),"error", err)+ } else {+ return task.ID}}if s.shouldEnqueueSquadLeaderOnAssign(ctx, issue) {s.enqueueSquadLeaderTask(ctx, issue, pgtype.UUID{}, creatorType, actorID)}+ return pgtype.UUID{}}// shouldEnqueueAgentTask returns true when an issue create or assignment@@ -500,17 +577,21 @@ func (s *IssueService) maybeEnqueueOnAssign(ctx context.Context, issue db.Issue,// Mirrors handler.shouldEnqueueAgentTask; kept here to make the service// self-contained, since both code paths must move together.func (s *IssueService) shouldEnqueueAgentTask(ctx context.Context, issue db.Issue) bool {+ return s.shouldEnqueueAgentTaskWithQueries(ctx, s.Queries, issue)+}++func (s *IssueService) shouldEnqueueAgentTaskWithQueries(ctx context.Context, q *db.Queries, issue db.Issue) bool {if issue.Status == "backlog" {return false}- return s.isAgentAssigneeReady(ctx, issue)+ return isAgentAssigneeReadyWithQueries(ctx, q, issue)}-func (s *IssueService) isAgentAssigneeReady(ctx context.Context, issue db.Issue) bool {+func isAgentAssigneeReadyWithQueries(ctx context.Context, q *db.Queries, issue db.Issue) bool {if !issue.AssigneeType.Valid || issue.AssigneeType.String != "agent" || !issue.AssigneeID.Valid {return false}- agent, err := s.Queries.GetAgent(ctx, issue.AssigneeID)+ agent, err := q.GetAgent(ctx, issue.AssigneeID)if err != nil || !agent.RuntimeID.Valid || agent.ArchivedAt.Valid {return false}diff --git a/server/internal/service/issue_channel_media_test.go b/server/internal/service/issue_channel_media_test.gonew file mode 100644index 0000000000..9d6c096980--- /dev/null+++ b/server/internal/service/issue_channel_media_test.go@@ -0,0 +1,289 @@+package service++import (+ "context"+ "encoding/json"+ "fmt"+ "reflect"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type afterCommitTxStarter struct {+ pool *pgxpool.Pool+ afterCommit func()+}++func (s *afterCommitTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {+ tx, err := s.pool.Begin(ctx)+ if err != nil {+ return nil, err+ }+ return &afterCommitTx{Tx: tx, afterCommit: s.afterCommit}, nil+}++type afterCommitTx struct {+ pgx.Tx+ afterCommit func()+}++func (t *afterCommitTx) Commit(ctx context.Context) error {+ if err := t.Tx.Commit(ctx); err != nil {+ return err+ }+ if t.afterCommit != nil {+ t.afterCommit()+ t.afterCommit = nil+ }+ return nil+}++func TestPublishAttachmentsChangedCarriesIssueScope(t *testing.T) {+ bus := events.New()+ svc := &IssueService{Bus: bus}+ workspaceID := util.MustParseUUID("11111111-1111-4111-8111-111111111111")+ issueID := util.MustParseUUID("22222222-2222-4222-8222-222222222222")+ actorID := util.MustParseUUID("33333333-3333-4333-8333-333333333333")+ var got events.Event+ bus.Subscribe(protocol.EventIssueAttachmentsChanged, func(e events.Event) { got = e })++ svc.PublishAttachmentsChanged(db.Issue{ID: issueID, WorkspaceID: workspaceID}, actorID)++ if got.Type != protocol.EventIssueAttachmentsChanged || got.WorkspaceID != util.UUIDToString(workspaceID) || got.ActorType != "member" || got.ActorID != util.UUIDToString(actorID) {+ t.Fatalf("event envelope = %+v", got)+ }+ payload, ok := got.Payload.(map[string]any)+ if !ok || payload["issue_id"] != util.UUIDToString(issueID) {+ t.Fatalf("event payload = %#v", got.Payload)+ }+}++func TestCreateMediaGatedIssueCommitsDeferredTaskAtomicallyBeforeCreatedEvent(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)+ workspaceUUID := util.MustParseUUID(workspaceID)+ userUUID := util.MustParseUUID(userID)+ agentUUID := util.MustParseUUID(agentID)++ bus := events.New()+ createdOverlay := json.RawMessage(`{"mcpServers":{"creator":{"url":"https://creator.example"}}}`)+ taskService := &TaskService{+ Queries: q,+ TxStarter: pool,+ Bus: bus,+ Composio: &stubOverlayBuilder{resp: createdOverlay},+ FeatureFlags: composioMCPAppsTestFlags(true),+ }+ var competingTaskID pgtype.UUID+ var competingErr error+ txStarter := &afterCommitTxStarter{pool: pool, afterCommit: func() {+ // This callback runs after the issue transaction is visible but before+ // IssueService resumes. The old implementation committed only the issue,+ // so this ordinary queued insert won the unique slot. The fixed path has+ // already committed the deferred task in the same transaction.+ var issueID, runtimeID pgtype.UUID+ if err := pool.QueryRow(ctx, `+ SELECT i.id, a.runtime_id+ FROM issue i+ JOIN agent a ON a.id = i.assignee_id+ WHERE i.workspace_id = $1 AND i.title = 'Media-gated issue'`, workspaceUUID).+ Scan(&issueID, &runtimeID); err != nil {+ competingErr = fmt.Errorf("discover committed issue: %w", err)+ return+ }+ competingErr = pool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)+ VALUES ($1, $2, $3, 'queued', 1)+ RETURNING id`, agentUUID, runtimeID, issueID).Scan(&competingTaskID)+ }}+ issueService := NewIssueService(q, txStarter, bus, nil, taskService)++ var callbackErr error+ var mergedCommentID pgtype.UUID+ bus.Subscribe(protocol.EventIssueCreated, func(event events.Event) {+ payload, ok := event.Payload.(map[string]any)+ if !ok {+ callbackErr = fmt.Errorf("issue:created payload = %#v", event.Payload)+ return+ }+ issueID, ok := payload["issue_id"].(string)+ if !ok {+ callbackErr = fmt.Errorf("issue:created issue_id = %#v", payload["issue_id"])+ return+ }+ issueUUID := util.MustParseUUID(issueID)++ var status string+ var mediaPending bool+ var runtimeOverlay []byte+ if err := pool.QueryRow(ctx, `+ SELECT status, context->>'channel_issue_media_pending' = 'true', runtime_mcp_overlay+ FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2`, issueUUID, agentUUID).Scan(&status, &mediaPending, &runtimeOverlay); err != nil {+ callbackErr = fmt.Errorf("load task during issue:created: %w", err)+ return+ }+ if status != "deferred" || !mediaPending {+ callbackErr = fmt.Errorf("task during issue:created = status %q media_pending %v", status, mediaPending)+ return+ }+ var runtimeOverlayValue, createdOverlayValue any+ if err := json.Unmarshal(runtimeOverlay, &runtimeOverlayValue); err != nil {+ callbackErr = fmt.Errorf("decode task overlay during issue:created: %w", err)+ return+ }+ if err := json.Unmarshal(createdOverlay, &createdOverlayValue); err != nil || !reflect.DeepEqual(runtimeOverlayValue, createdOverlayValue) {+ callbackErr = fmt.Errorf("task overlay during issue:created = %s, want %s", runtimeOverlay, createdOverlay)+ return+ }++ if err := pool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, 'Immediate follow-up')+ RETURNING id`, issueUUID, workspaceUUID, userUUID).Scan(&mergedCommentID); err != nil {+ callbackErr = fmt.Errorf("insert immediate comment: %w", err)+ return+ }+ if _, err := q.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{+ IssueID: issueUUID,+ AgentID: agentUUID,+ NewTriggerCommentID: mergedCommentID,+ NewOriginatorUserID: userUUID,+ NewAccountableUserID: userUUID,+ NewOriginatorSource: pgtype.Text{String: "direct_human", Valid: true},+ NewTriggerEvidenceKind: pgtype.Text{String: "comment", Valid: true},+ NewTriggerEvidenceRefID: mergedCommentID,+ }); err != nil {+ callbackErr = fmt.Errorf("merge immediate comment into deferred task: %w", err)+ }+ })++ result, err := issueService.Create(ctx, IssueCreateParams{+ WorkspaceID: workspaceUUID,+ Title: "Media-gated issue",+ Status: "todo",+ Priority: "medium",+ AssigneeType: pgtype.Text{String: "agent", Valid: true},+ AssigneeID: agentUUID,+ CreatorType: "member",+ CreatorID: userUUID,+ }, IssueCreateOpts{AssignedAgentRunFireAt: time.Now().Add(time.Minute)})+ if err != nil {+ t.Fatalf("Create: %v", err)+ }+ if callbackErr != nil {+ t.Fatal(callbackErr)+ }+ if !result.AssignedTaskID.Valid {+ t.Fatal("media-gated issue did not return its deferred task")+ }+ if !isDuplicatePendingTaskErr(competingErr) {+ t.Fatalf("post-commit competing queued insert error = %v, want duplicate pending task", competingErr)+ }+ if competingTaskID.Valid {+ t.Fatalf("post-commit competing task unexpectedly won: %s", util.UUIDToString(competingTaskID))+ }++ var taskID, triggerCommentID pgtype.UUID+ var taskCount int+ if err := pool.QueryRow(ctx, `+ SELECT id, trigger_comment_id, count(*) OVER ()+ FROM agent_task_queue+ WHERE issue_id = $1 AND agent_id = $2+ AND status IN ('queued', 'dispatched', 'deferred')+ ORDER BY created_at+ LIMIT 1`, result.Issue.ID, agentUUID).+ Scan(&taskID, &triggerCommentID, &taskCount); err != nil {+ t.Fatalf("load final pending task: %v", err)+ }+ if taskCount != 1 || taskID != result.AssignedTaskID || triggerCommentID != mergedCommentID {+ t.Fatalf("pending task = count %d id %v trigger %v, want one task %v with trigger %v", taskCount, taskID, triggerCommentID, result.AssignedTaskID, mergedCommentID)+ }+}++func TestHydrateDeferredChannelIssueTaskOverlayDoesNotOverwriteMergedCommentPlan(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, issueID := seedAttributionFixture(t, pool)+ userUUID := util.MustParseUUID(userID)++ plainService := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}+ task, err := plainService.EnqueueDeferredChannelIssueTask(ctx, db.Issue{+ ID: util.MustParseUUID(issueID),+ WorkspaceID: util.MustParseUUID(workspaceID),+ AssigneeType: pgtype.Text{String: "agent", Valid: true},+ AssigneeID: util.MustParseUUID(agentID),+ CreatorType: "member",+ CreatorID: userUUID,+ Priority: "medium",+ }, time.Now().Add(time.Minute))+ if err != nil {+ t.Fatalf("EnqueueDeferredChannelIssueTask: %v", err)+ }++ var commentID pgtype.UUID+ if err := pool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, 'New effective trigger')+ RETURNING id`, task.IssueID, workspaceID, userID).Scan(&commentID); err != nil {+ t.Fatalf("seed merged comment: %v", err)+ }+ mergedOverlay := json.RawMessage(`{"mcpServers":{"merged":{"url":"https://merged.example"}}}`)+ if _, err := q.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{+ IssueID: task.IssueID,+ AgentID: task.AgentID,+ NewTriggerCommentID: commentID,+ NewOriginatorUserID: userUUID,+ NewAccountableUserID: userUUID,+ NewRuntimeMcpOverlay: mergedOverlay,+ NewOriginatorSource: pgtype.Text{String: "direct_human", Valid: true},+ NewTriggerEvidenceKind: pgtype.Text{String: "comment", Valid: true},+ NewTriggerEvidenceRefID: commentID,+ }); err != nil {+ t.Fatalf("MergeCommentIntoPendingTask: %v", err)+ }++ hydrationBuilder := &stubOverlayBuilder{+ resp: json.RawMessage(`{"mcpServers":{"stale":{"url":"https://stale.example"}}}`),+ }+ hydratingService := &TaskService{+ Queries: q,+ Composio: hydrationBuilder,+ FeatureFlags: composioMCPAppsTestFlags(true),+ }+ if err := hydratingService.hydrateDeferredChannelIssueTaskOverlay(ctx, task); err != nil {+ t.Fatalf("hydrateDeferredChannelIssueTaskOverlay: %v", err)+ }++ var triggerID pgtype.UUID+ var storedOverlay []byte+ if err := pool.QueryRow(ctx, `+ SELECT trigger_comment_id, runtime_mcp_overlay+ FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&triggerID, &storedOverlay); err != nil {+ t.Fatalf("load hydrated task: %v", err)+ }+ if triggerID != commentID {+ t.Fatalf("trigger_comment_id = %s, want %s", util.UUIDToString(triggerID), util.UUIDToString(commentID))+ }+ var storedValue, mergedValue any+ if err := json.Unmarshal(storedOverlay, &storedValue); err != nil {+ t.Fatalf("decode stored runtime_mcp_overlay: %v", err)+ }+ if err := json.Unmarshal(mergedOverlay, &mergedValue); err != nil {+ t.Fatalf("decode expected runtime_mcp_overlay: %v", err)+ }+ if !reflect.DeepEqual(storedValue, mergedValue) {+ t.Fatalf("runtime_mcp_overlay = %s, want merged overlay %s", storedOverlay, mergedOverlay)+ }+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex be874a3585..322969fa9b 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -571,8 +571,8 @@ var ErrAttributionFailClosed = errors.New("attribution: no precise accountable h// ErrDuplicatePendingTask means a fresh enqueue lost the race to a concurrent// one: a queued/dispatched task for the same (issue, agent) already exists, so-// the idx_one_pending_task_per_issue_agent unique index rejected the insert-// (#5914). This is a benign outcome — a sibling run already covers this target+// the pending-task unique index rejected the insert (#5914). This is a benign+// outcome — a sibling run already covers this target// — not a server fault. Enqueue paths return it so callers can report a// success-shaped coalesced outcome / structured 409 instead of surfacing the// raw Postgres constraint as a 500. It is returned BARE (the raw driver text,@@ -580,11 +580,20 @@ var ErrAttributionFailClosed = errors.New("attribution: no precise accountable h// upper-layer log or response can leak the constraint name (#5914, Elon review).var ErrDuplicatePendingTask = errors.New("a pending task for this issue and agent already exists")-// isDuplicatePendingTaskErr reports whether err is the unique-index violation on-// idx_one_pending_task_per_issue_agent (a concurrent enqueue won the race).+// isDuplicatePendingTaskErr reports whether err is the pending-task unique-index+// violation (a concurrent enqueue won the race). Accept both names while v1 and+// v2 can coexist during a rolling deploy.func isDuplicatePendingTaskErr(err error) bool {var pgErr *pgconn.PgError- return errors.As(err, &pgErr) && pgErr.Code == "23505" && pgErr.ConstraintName == "idx_one_pending_task_per_issue_agent"+ if !errors.As(err, &pgErr) || pgErr.Code != "23505" {+ return false+ }+ switch pgErr.ConstraintName {+ case "idx_one_pending_task_per_issue_agent", "idx_one_pending_task_per_issue_agent_v2":+ return true+ default:+ return false+ }}// applyAttributionFallback applies the workspace's degraded-attribution policy to a@@ -945,7 +954,58 @@ func (s *TaskService) EnqueueTaskForIssue(ctx context.Context, issue db.Issue, tif len(triggerCommentID) > 0 {commentID = triggerCommentID[0]}- return s.enqueueIssueTask(ctx, issue, commentID, false, "", pgtype.UUID{}, pgtype.UUID{})+ return s.enqueueIssueTask(ctx, issue, commentID, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{})+}++// EnqueueDeferredChannelIssueTask persists the assigned task for a media-backed+// channel /issue turn without making it claimable yet. The fireAt deadline is a+// crash-safe fallback; the channel router promotes the task as soon as the+// detached attachment transaction settles.+func (s *TaskService) EnqueueDeferredChannelIssueTask(ctx context.Context, issue db.Issue, fireAt time.Time) (db.AgentTaskQueue, error) {+ return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{Time: fireAt, Valid: true})+}++// createDeferredChannelIssueTaskWithQueries inserts the inert media-gated task+// through the caller's query handle. IssueService passes its transaction-bound+// Queries so the issue and task become visible atomically. Composio is+// intentionally absent from the transaction-scoped service: the task cannot be+// claimed while deferred, so the optional external overlay is hydrated after+// commit without holding database locks across a network call.+func (s *TaskService) createDeferredChannelIssueTaskWithQueries(ctx context.Context, q *db.Queries, issue db.Issue, fireAt time.Time) (db.AgentTaskQueue, error) {+ txService := &TaskService{Queries: q}+ return txService.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, "", pgtype.UUID{}, pgtype.UUID{}, pgtype.Timestamptz{Time: fireAt, Valid: true})+}++// hydrateDeferredChannelIssueTaskOverlay fills the optional Composio overlay+// after the issue+task transaction commits. The conditional update refuses to+// overwrite a comment merge that won the post-commit race and already+// re-attributed the task (with its own matching overlay).+func (s *TaskService) hydrateDeferredChannelIssueTaskOverlay(ctx context.Context, task db.AgentTaskQueue) error {+ if s == nil || s.Queries == nil || s.Composio == nil || !featureflags.ComposioMCPAppsEnabled(ctx, s.FeatureFlags) {+ return nil+ }+ agent, err := s.Queries.GetAgent(ctx, task.AgentID)+ if err != nil {+ return fmt.Errorf("load agent for deferred channel issue task overlay: %w", err)+ }+ overlay := s.buildRuntimeMCPOverlay(ctx, task.OriginatorUserID, agent)+ if len(overlay.Overlay) == 0 {+ return nil+ }+ updated, err := s.Queries.SetDeferredChannelIssueTaskRuntimeOverlay(ctx, db.SetDeferredChannelIssueTaskRuntimeOverlayParams{+ ID: task.ID,+ RuntimeMcpOverlay: overlay.Overlay,+ RuntimeConnectedApps: overlay.ConnectedApps,+ ExpectedOriginatorUserID: task.OriginatorUserID,+ })+ if err != nil {+ return fmt.Errorf("set deferred channel issue task overlay: %w", err)+ }+ if updated == 0 {+ slog.Debug("deferred channel issue task overlay skipped: task plan changed",+ "task_id", util.UUIDToString(task.ID))+ }+ return nil}// EnqueueTaskForIssueWithHandoff is the assign/promote variant that carries a@@ -955,7 +1015,7 @@ func (s *TaskService) EnqueueTaskForIssue(ctx context.Context, issue db.Issue, t// member who performed the assign/promote and becomes the accountable human for// the run (MUL-4302 §4); invalid when the caller has no member actor.func (s *TaskService) EnqueueTaskForIssueWithHandoff(ctx context.Context, issue db.Issue, handoffNote string, actorUserID pgtype.UUID) (db.AgentTaskQueue, error) {- return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, handoffNote, actorUserID, pgtype.UUID{})+ return s.enqueueIssueTask(ctx, issue, pgtype.UUID{}, false, handoffNote, actorUserID, pgtype.UUID{}, pgtype.Timestamptz{})}// enqueueIssueTask is the shared implementation behind EnqueueTaskForIssue@@ -1003,11 +1063,11 @@ func (s *TaskService) ResolveIssueReviewSHAParam(ctx context.Context, issueID pgreturn headShaText(s.ResolveIssueReviewSHA(ctx, issueID))}-func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {- return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, nil, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID)+func (s *TaskService) enqueueIssueTask(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, fireAt pgtype.Timestamptz) (db.AgentTaskQueue, error) {+ return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, nil, forceFreshSession, handoffNote, actorUserID, rerunOfTaskID, fireAt)}-func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {+func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue db.Issue, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, forceFreshSession bool, handoffNote string, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID, fireAt pgtype.Timestamptz) (db.AgentTaskQueue, error) {if !issue.AssigneeID.Valid {slog.Error("task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "error", "issue has no assignee")return db.AgentTaskQueue{}, fmt.Errorf("issue has no assignee")@@ -1043,7 +1103,7 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issueoriginatorUserID := attr.UserIDruntimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, originatorUserID, agent)attrSource, attrDelegatedFrom, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)- task, err := s.Queries.CreateAgentTask(ctx, db.CreateAgentTaskParams{+ createParams := db.CreateAgentTaskParams{AgentID: issue.AssigneeID,RuntimeID: agent.RuntimeID,IssueID: issue.ID,@@ -1066,7 +1126,37 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue// Stamp the reviewed head so dedup can distinguish this run's target// from a later request against a new HEAD (TEN-356).HeadSha: headShaText(s.ResolveIssueReviewSHA(ctx, issue.ID)),- })+ }+ var task db.AgentTaskQueue+ if fireAt.Valid {+ task, err = s.Queries.CreateDeferredChannelIssueTask(ctx, db.CreateDeferredChannelIssueTaskParams{+ AgentID: createParams.AgentID,+ RuntimeID: createParams.RuntimeID,+ IssueID: createParams.IssueID,+ Priority: createParams.Priority,+ TriggerCommentID: createParams.TriggerCommentID,+ CoalescedCommentIds: createParams.CoalescedCommentIds,+ TriggerSummary: createParams.TriggerSummary,+ ForceFreshSession: createParams.ForceFreshSession,+ IsLeaderTask: createParams.IsLeaderTask,+ HandoffNote: createParams.HandoffNote,+ SquadID: createParams.SquadID,+ HeadSha: createParams.HeadSha,+ OriginatorUserID: createParams.OriginatorUserID,+ AccountableUserID: createParams.AccountableUserID,+ RuntimeMcpOverlay: createParams.RuntimeMcpOverlay,+ RuntimeConnectedApps: createParams.RuntimeConnectedApps,+ OriginatorSource: createParams.OriginatorSource,+ DelegatedFromTaskID: createParams.DelegatedFromTaskID,+ RuleVersionID: createParams.RuleVersionID,+ RerunOfTaskID: createParams.RerunOfTaskID,+ TriggerEvidenceKind: createParams.TriggerEvidenceKind,+ TriggerEvidenceRefID: createParams.TriggerEvidenceRefID,+ FireAt: fireAt,+ })+ } else {+ task, err = s.Queries.CreateAgentTask(ctx, createParams)+ }if err != nil {slog.Error("task enqueue failed", "issue_id", util.UUIDToString(issue.ID), "error", err)return db.AgentTaskQueue{}, fmt.Errorf("create task: %w", err)@@ -1078,6 +1168,9 @@ func (s *TaskService) enqueueIssueTaskWithCommentPlan(ctx context.Context, issue"agent_id", util.UUIDToString(issue.AssigneeID),"force_fresh_session", forceFreshSession,)+ if fireAt.Valid {+ return task, nil+ }// Order matters: broadcast first, notify daemon second. notifyTaskAvailable// kicks an in-process channel that the daemon picks up over HTTP and// claims; the claim path then emits its own task:dispatch. Doing the@@ -1711,6 +1804,27 @@ func (s *TaskService) PromoteChannelChatTasksIfMediaReady(ctx context.Context, sreturn nil}+// PromoteDeferredChannelIssueTask makes a media-gated /issue task claimable.+// ErrNoRows means the deadline sweeper already promoted it (or the task was+// cancelled), so this is idempotent across the two promotion paths.+func (s *TaskService) PromoteDeferredChannelIssueTask(ctx context.Context, taskID pgtype.UUID) error {+ task, err := s.Queries.PromoteDeferredChannelIssueTask(ctx, taskID)+ if errors.Is(err, pgx.ErrNoRows) {+ return nil+ }+ if err != nil {+ return fmt.Errorf("promote deferred channel issue task: %w", err)+ }+ slog.Info("channel media-ready issue task promoted",+ "task_id", util.UUIDToString(task.ID),+ "issue_id", util.UUIDToString(task.IssueID),+ "agent_id", util.UUIDToString(task.AgentID),+ )+ s.broadcastTaskEvent(ctx, protocol.EventTaskQueued, task)+ s.NotifyTaskEnqueued(ctx, task)+ return nil+}+// DirectChatSendResult carries the rows a transactional direct-chat send// persisted, so the handler can broadcast the user message and shape its// response without re-reading them.@@ -4242,7 +4356,7 @@ func (s *TaskService) promoteNewestSurvivingComment(ctx context.Context, ids []pfunc (s *TaskService) enqueueRerunTask(ctx context.Context, issue db.Issue, agentID pgtype.UUID, triggerCommentID pgtype.UUID, coalescedCommentIDs []pgtype.UUID, isLeader bool, squadID pgtype.UUID, actorUserID pgtype.UUID, rerunOfTaskID pgtype.UUID) (db.AgentTaskQueue, error) {if issue.AssigneeType.String == "agent" && issue.AssigneeID.Valid &&util.UUIDToString(issue.AssigneeID) == util.UUIDToString(agentID) {- return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, coalescedCommentIDs, true, "", actorUserID, rerunOfTaskID)+ return s.enqueueIssueTaskWithCommentPlan(ctx, issue, triggerCommentID, coalescedCommentIDs, true, "", actorUserID, rerunOfTaskID, pgtype.Timestamptz{})}return s.enqueueMentionTaskWithCommentPlan(ctx, issue, agentID, triggerCommentID, coalescedCommentIDs, isLeader, squadID, true, "", actorUserID, rerunOfTaskID)}diff --git a/server/internal/service/task_channel_media_race_test.go b/server/internal/service/task_channel_media_race_test.goindex 99df3192fc..78b1ebcf3d 100644--- a/server/internal/service/task_channel_media_race_test.go+++ b/server/internal/service/task_channel_media_race_test.go@@ -2,6 +2,7 @@ package serviceimport ("context"+ "errors""strings""testing""time"@@ -14,6 +15,7 @@ import ("github.com/multica-ai/multica/server/internal/events""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol")// raceInjectTxStarter wraps the pool so the transaction handed to@@ -135,3 +137,145 @@ func TestEnqueueChatTaskDefersWhenMediaMessageCommitsDuringEnqueue(t *testing.T)t.Fatalf("promoted task status = %q, want queued", status)}}++func TestDeferredChannelIssueTaskPromotesAfterMediaSettlement(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()+ q := db.New(pool)+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)++ var issueID pgtype.UUID+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, assignee_type, assignee_id, creator_type, creator_id, number)+ VALUES ($1, 'Channel media', 'todo', 'none', 'agent', $2, 'member', $3, 880001)+ RETURNING id`, workspaceID, agentID, userID).Scan(&issueID); err != nil {+ t.Fatalf("seed issue: %v", err)+ }+ t.Cleanup(func() {+ _, _ = pool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE issue_id = $1`, issueID)+ _, _ = pool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })++ bus := events.New()+ queued := 0+ bus.Subscribe(protocol.EventTaskQueued, func(events.Event) { queued++ })+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: bus}+ deadline := time.Now().Add(time.Minute)+ task, err := svc.EnqueueDeferredChannelIssueTask(ctx, db.Issue{+ ID: issueID,+ WorkspaceID: util.MustParseUUID(workspaceID),+ AssigneeType: pgtype.Text{String: "agent", Valid: true},+ AssigneeID: util.MustParseUUID(agentID),+ CreatorType: "member",+ CreatorID: util.MustParseUUID(userID),+ Priority: "none",+ }, deadline)+ if err != nil {+ t.Fatalf("EnqueueDeferredChannelIssueTask: %v", err)+ }+ if task.Status != "deferred" || !task.FireAt.Valid {+ t.Fatalf("task = status %q fire_at %v, want deferred", task.Status, task.FireAt)+ }+ if queued != 0 {+ t.Fatalf("queued events before media settlement = %d, want 0", queued)+ }+ hasPending, err := q.HasPendingTaskForIssueAndAgent(ctx, db.HasPendingTaskForIssueAndAgentParams{+ IssueID: issueID,+ AgentID: util.MustParseUUID(agentID),+ })+ if err != nil || !hasPending {+ t.Fatalf("media-gated task pending check = %v, %v; want true, nil", hasPending, err)+ }+ hasActive, err := q.HasActiveTaskForIssueAndAgent(ctx, db.HasActiveTaskForIssueAndAgentParams{+ IssueID: issueID,+ AgentID: util.MustParseUUID(agentID),+ })+ if err != nil || !hasActive {+ t.Fatalf("media-gated task active check = %v, %v; want true, nil", hasActive, err)+ }+ var commentID pgtype.UUID+ if err := pool.QueryRow(ctx, `+ INSERT INTO comment (issue_id, workspace_id, author_type, author_id, content)+ VALUES ($1, $2, 'member', $3, 'More context') RETURNING id`, issueID, workspaceID, userID).Scan(&commentID); err != nil {+ t.Fatalf("seed comment: %v", err)+ }+ merged, err := q.MergeCommentIntoPendingTask(ctx, db.MergeCommentIntoPendingTaskParams{+ IssueID: issueID,+ AgentID: util.MustParseUUID(agentID),+ NewTriggerCommentID: commentID,+ NewOriginatorUserID: util.MustParseUUID(userID),+ NewAccountableUserID: util.MustParseUUID(userID),+ NewOriginatorSource: pgtype.Text{String: "direct_human", Valid: true},+ NewTriggerEvidenceKind: pgtype.Text{String: "comment", Valid: true},+ NewTriggerEvidenceRefID: commentID,+ })+ if err != nil || merged.ID != task.ID {+ t.Fatalf("merge into media-gated task = %+v, %v; want task %s", merged, err, util.UUIDToString(task.ID))+ }++ if err := svc.PromoteDeferredChannelIssueTask(ctx, task.ID); err != nil {+ t.Fatalf("PromoteDeferredChannelIssueTask: %v", err)+ }+ if queued != 1 {+ t.Fatalf("queued events after promotion = %d, want 1", queued)+ }+ var status string+ var fireAt pgtype.Timestamptz+ if err := pool.QueryRow(ctx, `SELECT status, fire_at FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&status, &fireAt); err != nil {+ t.Fatalf("load promoted task: %v", err)+ }+ if status != "queued" || fireAt.Valid {+ t.Fatalf("promoted task = status %q fire_at %v, want queued with no deadline", status, fireAt)+ }+ if err := svc.PromoteDeferredChannelIssueTask(ctx, task.ID); err != nil {+ t.Fatalf("idempotent promotion: %v", err)+ }+ if queued != 1 {+ t.Fatalf("queued events after idempotent promotion = %d, want 1", queued)+ }+}++func TestDeferredChannelIssueTaskConflictsWithQueuedSiblingAtDatabase(t *testing.T) {+ pool := newResolveOriginatorPool(t)+ ctx := context.Background()++ var indexDefinition string+ if err := pool.QueryRow(ctx, `SELECT pg_get_indexdef('idx_one_pending_task_per_issue_agent_v2'::regclass)`).Scan(&indexDefinition); err != nil {+ t.Fatalf("load pending-task index: %v", err)+ }+ if !strings.Contains(indexDefinition, "channel_issue_media_pending") {+ t.Skip("channel-media pending-task uniqueness migration is not applied")+ }++ q := db.New(pool)+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)+ var issueID pgtype.UUID+ if err := pool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, status, priority, assignee_type, assignee_id, creator_type, creator_id, number)+ VALUES ($1, 'Channel media uniqueness', 'todo', 'none', 'agent', $2, 'member', $3, 880002)+ RETURNING id`, workspaceID, agentID, userID).Scan(&issueID); err != nil {+ t.Fatalf("seed issue: %v", err)+ }++ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}+ task, err := svc.EnqueueDeferredChannelIssueTask(ctx, db.Issue{+ ID: issueID,+ WorkspaceID: util.MustParseUUID(workspaceID),+ AssigneeType: pgtype.Text{String: "agent", Valid: true},+ AssigneeID: util.MustParseUUID(agentID),+ CreatorType: "member",+ CreatorID: util.MustParseUUID(userID),+ Priority: "none",+ }, time.Now().Add(time.Minute))+ if err != nil {+ t.Fatalf("EnqueueDeferredChannelIssueTask: %v", err)+ }++ _, err = pool.Exec(ctx, `+ INSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority)+ VALUES ($1, $2, $3, 'queued', 0)`, task.AgentID, task.RuntimeID, issueID)+ var pgErr *pgconn.PgError+ if !errors.As(err, &pgErr) || pgErr.Code != "23505" || pgErr.ConstraintName != "idx_one_pending_task_per_issue_agent_v2" {+ t.Fatalf("queued sibling insert error = %v, want unique violation on pending-task index", err)+ }+}diff --git a/server/migrations/257_agent_task_queue_channel_media_pending_unique_v2.down.sql b/server/migrations/257_agent_task_queue_channel_media_pending_unique_v2.down.sqlnew file mode 100644index 0000000000..eeeecd75b9--- /dev/null+++ b/server/migrations/257_agent_task_queue_channel_media_pending_unique_v2.down.sql@@ -0,0 +1,2 @@+-- Drop v2 only after migration 258's down step has restored v1.+DROP INDEX CONCURRENTLY IF EXISTS idx_one_pending_task_per_issue_agent_v2;diff --git a/server/migrations/257_agent_task_queue_channel_media_pending_unique_v2.up.sql b/server/migrations/257_agent_task_queue_channel_media_pending_unique_v2.up.sqlnew file mode 100644index 0000000000..fd52a9f0a9--- /dev/null+++ b/server/migrations/257_agent_task_queue_channel_media_pending_unique_v2.up.sql@@ -0,0 +1,9 @@+-- Build v2 before dropping v1 so queued/dispatched uniqueness remains enforced+-- throughout rolling deploys and interrupted migration runs. The v1 predicate+-- is a strict subset of v2, so both indexes can coexist safely. This file stays+-- a single statement because CREATE INDEX CONCURRENTLY cannot run in a+-- transaction or a multi-command string.+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS idx_one_pending_task_per_issue_agent_v2+ ON agent_task_queue (issue_id, agent_id)+ WHERE status IN ('queued', 'dispatched')+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true');diff --git a/server/migrations/258_drop_pending_issue_agent_v1.down.sql b/server/migrations/258_drop_pending_issue_agent_v1.down.sqlnew file mode 100644index 0000000000..b43f71276e--- /dev/null+++ b/server/migrations/258_drop_pending_issue_agent_v1.down.sql@@ -0,0 +1,6 @@+-- Recreate v1 before migration 257's down step removes v2.+-- Do not use IF NOT EXISTS here: a leftover INVALID v1 must fail closed while+-- the valid v2 index remains in place instead of being recorded as restored.+CREATE UNIQUE INDEX CONCURRENTLY idx_one_pending_task_per_issue_agent+ ON agent_task_queue (issue_id, agent_id)+ WHERE status IN ('queued', 'dispatched');diff --git a/server/migrations/258_drop_pending_issue_agent_v1.up.sql b/server/migrations/258_drop_pending_issue_agent_v1.up.sqlnew file mode 100644index 0000000000..b1475d826e--- /dev/null+++ b/server/migrations/258_drop_pending_issue_agent_v1.up.sql@@ -0,0 +1,2 @@+-- Drop the superseded queued/dispatched-only index after v2 is available.+DROP INDEX CONCURRENTLY IF EXISTS idx_one_pending_task_per_issue_agent;diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 01397da4b0..59a627047f 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -1990,6 +1990,153 @@ func (q *Queries) CreateDeferredAgentTask(ctx context.Context, arg CreateDeferrereturn i, err}+const createDeferredChannelIssueTask = `-- name: CreateDeferredChannelIssueTask :one+INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,+ coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,+ squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id,+ trigger_evidence_kind, trigger_evidence_ref_id, fire_at+)+VALUES (+ $1, $2, $3, 'deferred', $4, $5,+ COALESCE($6::uuid[], '{}'),+ $7,+ COALESCE($8::boolean, FALSE),+ COALESCE($9::boolean, FALSE),+ $10,+ $11,+ jsonb_strip_nulls(jsonb_build_object(+ 'head_sha', NULLIF(COALESCE($12::text, ''), ''),+ 'channel_issue_media_pending', TRUE+ )),+ $13,+ $14,+ $15,+ $16,+ $17,+ $18,+ $19,+ $20,+ $21,+ $22,+ $23+)+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for+`++type CreateDeferredChannelIssueTaskParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ RuntimeID pgtype.UUID `json:"runtime_id"`+ IssueID pgtype.UUID `json:"issue_id"`+ Priority int32 `json:"priority"`+ TriggerCommentID pgtype.UUID `json:"trigger_comment_id"`+ CoalescedCommentIds []pgtype.UUID `json:"coalesced_comment_ids"`+ TriggerSummary pgtype.Text `json:"trigger_summary"`+ ForceFreshSession pgtype.Bool `json:"force_fresh_session"`+ IsLeaderTask pgtype.Bool `json:"is_leader_task"`+ HandoffNote pgtype.Text `json:"handoff_note"`+ SquadID pgtype.UUID `json:"squad_id"`+ HeadSha pgtype.Text `json:"head_sha"`+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`+ OriginatorSource pgtype.Text `json:"originator_source"`+ DelegatedFromTaskID pgtype.UUID `json:"delegated_from_task_id"`+ RuleVersionID pgtype.UUID `json:"rule_version_id"`+ RerunOfTaskID pgtype.UUID `json:"rerun_of_task_id"`+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`+ FireAt pgtype.Timestamptz `json:"fire_at"`+}++// Channel /issue media resolves after issue creation. Persist the assigned+// issue task up front for crash safety, but keep it inert until attachment+// binding settles or the fire_at fallback is promoted by the normal sweeper.+func (q *Queries) CreateDeferredChannelIssueTask(ctx context.Context, arg CreateDeferredChannelIssueTaskParams) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, createDeferredChannelIssueTask,+ arg.AgentID,+ arg.RuntimeID,+ arg.IssueID,+ arg.Priority,+ arg.TriggerCommentID,+ arg.CoalescedCommentIds,+ arg.TriggerSummary,+ arg.ForceFreshSession,+ arg.IsLeaderTask,+ arg.HandoffNote,+ arg.SquadID,+ arg.HeadSha,+ arg.OriginatorUserID,+ arg.AccountableUserID,+ arg.RuntimeMcpOverlay,+ arg.RuntimeConnectedApps,+ arg.OriginatorSource,+ arg.DelegatedFromTaskID,+ arg.RuleVersionID,+ arg.RerunOfTaskID,+ arg.TriggerEvidenceKind,+ arg.TriggerEvidenceRefID,+ arg.FireAt,+ )+ var i AgentTaskQueue+ err := row.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ )+ return i, err+}+const createQuickCreateTask = `-- name: CreateQuickCreateTask :oneINSERT INTO agent_task_queue (agent_id, runtime_id, issue_id, status, priority, context, originator_user_id,@@ -3422,7 +3569,10 @@ func (q *Queries) HasActiveTaskForIssue(ctx context.Context, issueID pgtype.UUIDconst hasActiveTaskForIssueAndAgent = `-- name: HasActiveTaskForIssueAndAgent :oneSELECT count(*) > 0 AS has_active FROM agent_task_queueWHERE issue_id = $1 AND agent_id = $2- AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ AND (+ status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')+ )`type HasActiveTaskForIssueAndAgentParams struct {@@ -3432,7 +3582,8 @@ type HasActiveTaskForIssueAndAgentParams struct {// MUL-4195: true when the (issue, agent) pair has any non-terminal task in a// state whose completion will run completion reconciliation — queued,-// dispatched, running, or waiting_local_directory. Used by the comment enqueue+// dispatched, running, waiting_local_directory, or the explicitly-marked+// channel-media deferred state. Used by the comment enqueue// path: when a merge into a pre-claim task fails (the task is already// dispatched/running, or a mismatched pre-claim task exists), a fresh queued// INSERT would collide with idx_one_pending_task_per_issue_agent AND would risk@@ -3464,7 +3615,11 @@ func (q *Queries) HasPendingTaskForIssue(ctx context.Context, issueID pgtype.UUIconst hasPendingTaskForIssueAndAgent = `-- name: HasPendingTaskForIssueAndAgent :oneSELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched')+WHERE issue_id = $1 AND agent_id = $2+ AND (+ status IN ('queued', 'dispatched')+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')+ )AND (COALESCE($3::text, '') = ''OR context->>'head_sha' = $3::text@@ -3478,7 +3633,8 @@ type HasPendingTaskForIssueAndAgentParams struct {}// Returns true if a specific agent already has a queued or dispatched task-// for the given issue. Used by @mention trigger dedup.+// for the given issue, or the explicitly-marked deferred task whose channel+// media must bind before the issue agent runs. Used by @mention trigger dedup.//// head_sha keys the dedup on the commit under review (TEN-356): when a caller// passes a non-empty head_sha, a pending task only dedups if it was stamped@@ -3498,7 +3654,10 @@ const hasPendingTaskForIssueAndAgentExcludingTriggerComment = `-- name: HasPendiSELECT count(*) > 0 AS has_pending FROM agent_task_queueWHERE issue_id = $1AND agent_id = $2- AND status IN ('queued', 'dispatched')+ AND (+ status IN ('queued', 'dispatched')+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')+ )AND trigger_comment_id IS DISTINCT FROM $3::uuidAND (COALESCE($4::text, '') = ''@@ -5018,7 +5177,10 @@ WHERE id = (SELECT t.id FROM agent_task_queue tWHERE t.issue_id = $12AND t.agent_id = $13- AND t.status = 'queued'+ AND (+ t.status = 'queued'+ OR (t.status = 'deferred' AND t.context->>'channel_issue_media_pending' = 'true')+ )-- Head-scoped (TEN-356, #5914): never fold across HEADs. The physical-- unique index is only (issue_id, agent_id), so an insert-race loser can-- collide with a pending task stamped for a DIFFERENT head_sha; merging@@ -5064,22 +5226,21 @@ type MergeCommentIntoPendingTaskRow struct {// the latest deliberate instruction while the single run is still told to// address every folded comment.//-// Target is restricted to the single 'queued' task on purpose (MUL-4195 review-// rounds 2–4). This merge is only reached when HasPendingTaskForIssueAndAgent-// matched a 'queued'/'dispatched' task, and 'dispatched' is deliberately NOT a+// Target is restricted to a pre-claim task on purpose (MUL-4195 review rounds+// 2–4). This merge is reached when HasPendingTaskForIssueAndAgent matched a+// 'queued'/'dispatched' task, or the channel-media deferred task described+// below. 'dispatched' is deliberately NOT a// target: a dispatched / waiting_local_directory / running task has already had// its claim response built. Folding afterward would add a planned id that is// absent from that response's delivered_comment_ids receipt; completion-// reconciliation handles it instead. 'deferred' is also NOT-// a target: a deferred row is an assignee-fallback escalation with its own-// fire_at/promotion lifecycle, and it never sets AlreadyPending-// (HasPendingTaskForIssueAndAgent only looks at queued/dispatched). If a newer-// deferred fallback and an older queued task coexisted, a status-IN target would-// pick the deferred one by created_at and steal the coalescing target away from-// the queued run that is actually about to be claimed — so we match ONLY the-// queued row (the idx_one_pending_task_per_issue_agent unique index guarantees-// at most one). coalesced_comment_ids remains the pre-claim plan; the claim-// path records the actual embedded subset in delivered_comment_ids.+// reconciliation handles it instead. Ordinary 'deferred' rows remain excluded:+// assignee-fallback escalations have their own fire_at lifecycle and may coexist+// with a queued primary. The one exception is a task explicitly marked+// channel_issue_media_pending. It is the issue's sole assigned-agent task and+// has not been claimable yet, so a new comment must merge into it instead of+// creating a competing queued task. coalesced_comment_ids remains the pre-claim+// plan; the claim path records the actual embedded subset in+// delivered_comment_ids.//// Recompute-on-merge (MUL-4195 review must-fix #1): originator_user_id,// runtime_mcp_overlay and runtime_connected_apps are re-stamped to the NEW@@ -5121,6 +5282,74 @@ func (q *Queries) MergeCommentIntoPendingTask(ctx context.Context, arg MergeCommreturn i, err}+const promoteDeferredChannelIssueTask = `-- name: PromoteDeferredChannelIssueTask :one+UPDATE agent_task_queue+SET status = 'queued', fire_at = NULL+WHERE id = $1 AND issue_id IS NOT NULL AND status = 'deferred'+RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for+`++// Early promotion is idempotent at the service layer: a task already promoted+// by the fire_at sweeper no longer matches and is treated as settled.+func (q *Queries) PromoteDeferredChannelIssueTask(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {+ row := q.db.QueryRow(ctx, promoteDeferredChannelIssueTask, id)+ var i AgentTaskQueue+ err := row.Scan(+ &i.ID,+ &i.AgentID,+ &i.IssueID,+ &i.Status,+ &i.Priority,+ &i.DispatchedAt,+ &i.StartedAt,+ &i.CompletedAt,+ &i.Result,+ &i.Error,+ &i.CreatedAt,+ &i.Context,+ &i.RuntimeID,+ &i.SessionID,+ &i.WorkDir,+ &i.TriggerCommentID,+ &i.ChatSessionID,+ &i.AutopilotRunID,+ &i.Attempt,+ &i.MaxAttempts,+ &i.ParentTaskID,+ &i.FailureReason,+ &i.TriggerSummary,+ &i.ForceFreshSession,+ &i.IsLeaderTask,+ &i.WaitReason,+ &i.InitiatorUserID,+ &i.HandoffNote,+ &i.PrepareLeaseExpiresAt,+ &i.SquadID,+ &i.RuntimeMcpOverlay,+ &i.EscalationForTaskID,+ &i.FireAt,+ &i.OriginatorUserID,+ &i.RuntimeConnectedApps,+ &i.CoalescedCommentIds,+ &i.DeliveredCommentIds,+ &i.ChatInputTaskID,+ &i.ChatFinalizeDeferredAt,+ &i.OriginatorSource,+ &i.DelegatedFromTaskID,+ &i.RetryOfTaskID,+ &i.RerunOfTaskID,+ &i.RuleVersionID,+ &i.TriggerEvidenceKind,+ &i.TriggerEvidenceRefID,+ &i.AccountableUserID,+ &i.SessionRolloutMissing,+ &i.RetiredSessionID,+ &i.QuickActionsDisabled,+ &i.RegenerateQuickActionsFor,+ )+ return i, err+}+const promoteDueDeferredTasksForRuntime = `-- name: PromoteDueDeferredTasksForRuntime :manyUPDATE agent_task_queueSET status = 'queued'@@ -5888,6 +6117,40 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erroreturn i, err}+const setDeferredChannelIssueTaskRuntimeOverlay = `-- name: SetDeferredChannelIssueTaskRuntimeOverlay :execrows+UPDATE agent_task_queue+SET runtime_mcp_overlay = $1,+ runtime_connected_apps = $2+WHERE id = $3+ AND status = 'deferred'+ AND context->>'channel_issue_media_pending' = 'true'+ AND trigger_comment_id IS NULL+ AND originator_user_id IS NOT DISTINCT FROM $4::uuid+`++type SetDeferredChannelIssueTaskRuntimeOverlayParams struct {+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`+ ID pgtype.UUID `json:"id"`+ ExpectedOriginatorUserID pgtype.UUID `json:"expected_originator_user_id"`+}++// The issue and its inert media-gated task commit atomically before the optional+// external overlay is built. Only hydrate the untouched original plan: a comment+// merge may already have replaced the trigger, attribution, and matching overlay.+func (q *Queries) SetDeferredChannelIssueTaskRuntimeOverlay(ctx context.Context, arg SetDeferredChannelIssueTaskRuntimeOverlayParams) (int64, error) {+ result, err := q.db.Exec(ctx, setDeferredChannelIssueTaskRuntimeOverlay,+ arg.RuntimeMcpOverlay,+ arg.RuntimeConnectedApps,+ arg.ID,+ arg.ExpectedOriginatorUserID,+ )+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const setTaskDeliveredCommentIDs = `-- name: SetTaskDeliveredCommentIDs :oneUPDATE agent_task_queueSET delivered_comment_ids = $1::uuid[]diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.goindex 49dc5d7d91..0b24fb5dea 100644--- a/server/pkg/db/generated/issue.sql.go+++ b/server/pkg/db/generated/issue.sql.go@@ -1233,6 +1233,49 @@ func (q *Queries) LockIssueDuplicateKey(ctx context.Context, dollar_1 string) erreturn err}+const lockIssueForChannelMediaBind = `-- name: LockIssueForChannelMediaBind :one+SELECT id FROM issue+WHERE id = $1 AND workspace_id = $2+FOR KEY SHARE+`++type LockIssueForChannelMediaBindParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Channel media resolves after /issue creation. Hold a key-share lock while+// the attachment row is written so a concurrent issue delete cannot land+// between the workspace-scoped validation and the attachment insert.+func (q *Queries) LockIssueForChannelMediaBind(ctx context.Context, arg LockIssueForChannelMediaBindParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, lockIssueForChannelMediaBind, arg.ID, arg.WorkspaceID)+ var id pgtype.UUID+ err := row.Scan(&id)+ return id, err+}++const lockIssueForDelete = `-- name: LockIssueForDelete :one+SELECT id FROM issue+WHERE id = $1 AND workspace_id = $2+FOR UPDATE+`++type LockIssueForDeleteParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Issue deletion must collect every attachment URL after it has won the same+// row-lock race used by channel media binding. FOR UPDATE conflicts with the+// binder's FOR KEY SHARE: either bind commits first and its URL is collected,+// or delete commits first and the binder leaves its durable intent for cleanup.+func (q *Queries) LockIssueForDelete(ctx context.Context, arg LockIssueForDeleteParams) (pgtype.UUID, error) {+ row := q.db.QueryRow(ctx, lockIssueForDelete, arg.ID, arg.WorkspaceID)+ var id pgtype.UUID+ err := row.Scan(&id)+ return id, err+}+const markIssueFirstExecuted = `-- name: MarkIssueFirstExecuted :oneUPDATE issueSET first_executed_at = now()diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 5b36243d25..b9e5a81c5c 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -309,6 +309,64 @@ VALUES ()RETURNING *;+-- name: CreateDeferredChannelIssueTask :one+-- Channel /issue media resolves after issue creation. Persist the assigned+-- issue task up front for crash safety, but keep it inert until attachment+-- binding settles or the fire_at fallback is promoted by the normal sweeper.+INSERT INTO agent_task_queue (+ agent_id, runtime_id, issue_id, status, priority, trigger_comment_id,+ coalesced_comment_ids, trigger_summary, force_fresh_session, is_leader_task, handoff_note,+ squad_id, context, originator_user_id, accountable_user_id, runtime_mcp_overlay, runtime_connected_apps,+ originator_source, delegated_from_task_id, rule_version_id, rerun_of_task_id,+ trigger_evidence_kind, trigger_evidence_ref_id, fire_at+)+VALUES (+ $1, $2, $3, 'deferred', $4, sqlc.narg(trigger_comment_id),+ COALESCE(sqlc.narg(coalesced_comment_ids)::uuid[], '{}'),+ sqlc.narg(trigger_summary),+ COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),+ COALESCE(sqlc.narg('is_leader_task')::boolean, FALSE),+ sqlc.narg(handoff_note),+ sqlc.narg(squad_id),+ jsonb_strip_nulls(jsonb_build_object(+ 'head_sha', NULLIF(COALESCE(sqlc.narg('head_sha')::text, ''), ''),+ 'channel_issue_media_pending', TRUE+ )),+ sqlc.narg(originator_user_id),+ sqlc.narg(accountable_user_id),+ sqlc.narg(runtime_mcp_overlay),+ sqlc.narg(runtime_connected_apps),+ sqlc.narg(originator_source),+ sqlc.narg(delegated_from_task_id),+ sqlc.narg(rule_version_id),+ sqlc.narg(rerun_of_task_id),+ sqlc.narg(trigger_evidence_kind),+ sqlc.narg(trigger_evidence_ref_id),+ @fire_at+)+RETURNING *;++-- name: PromoteDeferredChannelIssueTask :one+-- Early promotion is idempotent at the service layer: a task already promoted+-- by the fire_at sweeper no longer matches and is treated as settled.+UPDATE agent_task_queue+SET status = 'queued', fire_at = NULL+WHERE id = $1 AND issue_id IS NOT NULL AND status = 'deferred'+RETURNING *;++-- name: SetDeferredChannelIssueTaskRuntimeOverlay :execrows+-- The issue and its inert media-gated task commit atomically before the optional+-- external overlay is built. Only hydrate the untouched original plan: a comment+-- merge may already have replaced the trigger, attribution, and matching overlay.+UPDATE agent_task_queue+SET runtime_mcp_overlay = sqlc.narg(runtime_mcp_overlay),+ runtime_connected_apps = sqlc.narg(runtime_connected_apps)+WHERE id = @id+ AND status = 'deferred'+ AND context->>'channel_issue_media_pending' = 'true'+ AND trigger_comment_id IS NULL+ AND originator_user_id IS NOT DISTINCT FROM sqlc.narg(expected_originator_user_id)::uuid;+-- name: CreateQuickCreateTask :one-- Quick-create tasks have no issue / chat / autopilot link; the entire job-- description (prompt, requester, workspace) lives in context JSONB. The@@ -1183,7 +1241,8 @@ WHERE issue_id = $1 AND status IN ('queued', 'dispatched');-- name: HasPendingTaskForIssueAndAgent :one-- Returns true if a specific agent already has a queued or dispatched task--- for the given issue. Used by @mention trigger dedup.+-- for the given issue, or the explicitly-marked deferred task whose channel+-- media must bind before the issue agent runs. Used by @mention trigger dedup.---- head_sha keys the dedup on the commit under review (TEN-356): when a caller-- passes a non-empty head_sha, a pending task only dedups if it was stamped@@ -1193,7 +1252,11 @@ WHERE issue_id = $1 AND status IN ('queued', 'dispatched');-- When head_sha is empty/NULL (issue has no linked PR) the check falls back to-- the pre-TEN-356 (issue_id, agent_id) key so non-PR issues keep coalescing.SELECT count(*) > 0 AS has_pending FROM agent_task_queue-WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched')+WHERE issue_id = $1 AND agent_id = $2+ AND (+ status IN ('queued', 'dispatched')+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')+ )AND (COALESCE(sqlc.narg('head_sha')::text, '') = ''OR context->>'head_sha' = sqlc.narg('head_sha')::text@@ -1207,7 +1270,10 @@ WHERE issue_id = $1 AND agent_id = $2 AND status IN ('queued', 'dispatched')SELECT count(*) > 0 AS has_pending FROM agent_task_queueWHERE issue_id = @issue_idAND agent_id = @agent_id- AND status IN ('queued', 'dispatched')+ AND (+ status IN ('queued', 'dispatched')+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')+ )AND trigger_comment_id IS DISTINCT FROM @exclude_trigger_comment_id::uuidAND (COALESCE(sqlc.narg('head_sha')::text, '') = ''@@ -1223,22 +1289,21 @@ WHERE issue_id = @issue_id-- the latest deliberate instruction while the single run is still told to-- address every folded comment.----- Target is restricted to the single 'queued' task on purpose (MUL-4195 review--- rounds 2–4). This merge is only reached when HasPendingTaskForIssueAndAgent--- matched a 'queued'/'dispatched' task, and 'dispatched' is deliberately NOT a+-- Target is restricted to a pre-claim task on purpose (MUL-4195 review rounds+-- 2–4). This merge is reached when HasPendingTaskForIssueAndAgent matched a+-- 'queued'/'dispatched' task, or the channel-media deferred task described+-- below. 'dispatched' is deliberately NOT a-- target: a dispatched / waiting_local_directory / running task has already had-- its claim response built. Folding afterward would add a planned id that is-- absent from that response's delivered_comment_ids receipt; completion--- reconciliation handles it instead. 'deferred' is also NOT--- a target: a deferred row is an assignee-fallback escalation with its own--- fire_at/promotion lifecycle, and it never sets AlreadyPending--- (HasPendingTaskForIssueAndAgent only looks at queued/dispatched). If a newer--- deferred fallback and an older queued task coexisted, a status-IN target would--- pick the deferred one by created_at and steal the coalescing target away from--- the queued run that is actually about to be claimed — so we match ONLY the--- queued row (the idx_one_pending_task_per_issue_agent unique index guarantees--- at most one). coalesced_comment_ids remains the pre-claim plan; the claim--- path records the actual embedded subset in delivered_comment_ids.+-- reconciliation handles it instead. Ordinary 'deferred' rows remain excluded:+-- assignee-fallback escalations have their own fire_at lifecycle and may coexist+-- with a queued primary. The one exception is a task explicitly marked+-- channel_issue_media_pending. It is the issue's sole assigned-agent task and+-- has not been claimable yet, so a new comment must merge into it instead of+-- creating a competing queued task. coalesced_comment_ids remains the pre-claim+-- plan; the claim path records the actual embedded subset in+-- delivered_comment_ids.---- Recompute-on-merge (MUL-4195 review must-fix #1): originator_user_id,-- runtime_mcp_overlay and runtime_connected_apps are re-stamped to the NEW@@ -1286,7 +1351,10 @@ WHERE id = (SELECT t.id FROM agent_task_queue tWHERE t.issue_id = @issue_idAND t.agent_id = @agent_id- AND t.status = 'queued'+ AND (+ t.status = 'queued'+ OR (t.status = 'deferred' AND t.context->>'channel_issue_media_pending' = 'true')+ )-- Head-scoped (TEN-356, #5914): never fold across HEADs. The physical-- unique index is only (issue_id, agent_id), so an insert-race loser can-- collide with a pending task stamped for a DIFFERENT head_sha; merging@@ -1348,7 +1416,8 @@ RETURNING id, coalesced_comment_ids;-- name: HasActiveTaskForIssueAndAgent :one-- MUL-4195: true when the (issue, agent) pair has any non-terminal task in a-- state whose completion will run completion reconciliation — queued,--- dispatched, running, or waiting_local_directory. Used by the comment enqueue+-- dispatched, running, waiting_local_directory, or the explicitly-marked+-- channel-media deferred state. Used by the comment enqueue-- path: when a merge into a pre-claim task fails (the task is already-- dispatched/running, or a mismatched pre-claim task exists), a fresh queued-- INSERT would collide with idx_one_pending_task_per_issue_agent AND would risk@@ -1357,7 +1426,10 @@ RETURNING id, coalesced_comment_ids;-- NO active task exists.SELECT count(*) > 0 AS has_active FROM agent_task_queueWHERE issue_id = $1 AND agent_id = $2- AND status IN ('queued', 'dispatched', 'running', 'waiting_local_directory');+ AND (+ status IN ('queued', 'dispatched', 'running', 'waiting_local_directory')+ OR (status = 'deferred' AND context->>'channel_issue_media_pending' = 'true')+ );-- name: GetLatestTaskRoleForIssueAndAgent :one-- Returns the role markers from the agent's most recent task on this issue.diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sqlindex 91d7d6f089..9d0823329d 100644--- a/server/pkg/db/queries/issue.sql+++ b/server/pkg/db/queries/issue.sql@@ -80,6 +80,23 @@ WHERE workspace_id = sqlc.arg('workspace_id')SELECT * FROM issueWHERE id = $1 AND workspace_id = $2;+-- name: LockIssueForChannelMediaBind :one+-- Channel media resolves after /issue creation. Hold a key-share lock while+-- the attachment row is written so a concurrent issue delete cannot land+-- between the workspace-scoped validation and the attachment insert.+SELECT id FROM issue+WHERE id = $1 AND workspace_id = $2+FOR KEY SHARE;++-- name: LockIssueForDelete :one+-- Issue deletion must collect every attachment URL after it has won the same+-- row-lock race used by channel media binding. FOR UPDATE conflicts with the+-- binder's FOR KEY SHARE: either bind commits first and its URL is collected,+-- or delete commits first and the binder leaves its durable intent for cleanup.+SELECT id FROM issue+WHERE id = $1 AND workspace_id = $2+FOR UPDATE;+-- name: CreateIssue :oneINSERT INTO issue (workspace_id, title, description, status, priority,diff --git a/server/pkg/protocol/events.go b/server/pkg/protocol/events.goindex e5fc06dbb7..d54694bb4e 100644--- a/server/pkg/protocol/events.go+++ b/server/pkg/protocol/events.go@@ -3,10 +3,11 @@ package protocol// Event types for WebSocket communication between server, web clients, and daemon.const (// Issue events- EventIssueCreated = "issue:created"- EventIssueUpdated = "issue:updated"- EventIssueDeleted = "issue:deleted"- EventIssueMetadataChanged = "issue_metadata:changed"+ EventIssueCreated = "issue:created"+ EventIssueUpdated = "issue:updated"+ EventIssueDeleted = "issue:deleted"+ EventIssueMetadataChanged = "issue_metadata:changed"+ EventIssueAttachmentsChanged = "issue_attachments:changed"// Comment eventsEventCommentCreated = "comment:created"