Skip to content

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

Go

fix(lark): ingest inbound images and videos as chat attachments (MUL-4934) (#5580)

beast60048172a7d6
diff --git a/server/cmd/server/channel_media_invariant_test.go b/server/cmd/server/channel_media_invariant_test.go
new file mode 100644
index 0000000000..3e2046fc96
--- /dev/null
+++ b/server/cmd/server/channel_media_invariant_test.go
@@ -0,0 +1,28 @@
+package main
+
+import (
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+ "github.com/multica-ai/multica/server/internal/integrations/lark"
+ "github.com/multica-ai/multica/server/internal/service"
+)
+
+// The reconciler's settle delay carries NO correctness weight (the ledger
+// state machine does), but it must dwarf every media/HTTP budget in the
+// pipeline so the reconciler never races a healthy in-flight operation's
+// normal completion. This is the cross-package assertion of that invariant:
+// if any budget grows past a tenth of the settle delay, this test forces the
+// author to re-derive the margin instead of silently eroding it.
+func TestChannelMediaSettleDwarfsEveryPipelineBudget(t *testing.T) {
+ budgets := map[string]int64{
+ "engine media timeout (download+upload+bind budget)": int64(engine.DefaultMediaTimeout),
+ "lark resource download cap": int64(lark.DefaultResourceDownloadTimeout),
+ }
+ settle := int64(service.ChannelMediaReconcileSettleDelay)
+ for name, budget := range budgets {
+ if settle < 10*budget {
+ t.Fatalf("settle delay %d must be >= 10x %s (%d)", settle, name, budget)
+ }
+ }
+}
diff --git a/server/cmd/server/main.go b/server/cmd/server/main.go
index 19c49c8aa3..9c55d8231f 100644
--- a/server/cmd/server/main.go
+++ b/server/cmd/server/main.go
@@ -338,6 +338,7 @@ func main() {
var httpMetrics *obsmetrics.HTTPMetrics
var businessMetrics *obsmetrics.BusinessMetrics
var samplerPool *pgxpool.Pool
+ var channelMediaMetrics *obsmetrics.ChannelMediaReconcilerMetrics
if metricsConfig.Enabled() {
// Build a dedicated tiny pool for the BusinessSamplerCollector
// so a stalled scrape can never starve business traffic. If the
@@ -365,6 +366,7 @@ func main() {
})
httpMetrics = metricsRegistry.HTTP
businessMetrics = metricsRegistry.Business
+ channelMediaMetrics = metricsRegistry.ChannelMedia
// Forward inbound daemon WS frames into the per-kind counter so
// dashboards can split heartbeat / unknown / invalid traffic.
if daemonHub != nil {
@@ -443,6 +445,14 @@ func main() {
go h.ChannelSupervisor.Run(sweepCtx)
}
+ // Media intent-ledger reconciler (PR #5580): settles uploaded-but-unbound
+ // channel media objects. An independent worker so object-storage latency
+ // spikes cannot starve any other sweeper's cadence.
+ if h.ChannelMediaReconciler != nil {
+ h.ChannelMediaReconciler.Metrics = channelMediaMetrics
+ go h.ChannelMediaReconciler.Run(sweepCtx)
+ }
+
// MUL-2957: DB-backed execution scheduler. The scheduler turns the
// `sys_cron_executions` table into the distributed lease + audit
// log for internal periodic jobs. The first job is
@@ -541,7 +551,11 @@ func main() {
)
}
if h.ChannelRouter != nil {
- h.ChannelRouter.Drain()
+ drainCtx, drainCancel := context.WithTimeout(context.Background(), 10*time.Second)
+ if !h.ChannelRouter.Drain(drainCtx) {
+ slog.Warn("channel router: drain deadline reached; deferred media fallback remains durable")
+ }
+ drainCancel()
}
}
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index c48bda7196..3c30a89b25 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -268,6 +268,21 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
// into one agent run instead of one per message (MUL-2968).
channelRouter.EnableRunBatching(engine.DefaultChatRunBatchWindow)
h.ChannelRouter = channelRouter
+ // Media intent-ledger reconciler: settles uploaded-but-unbound objects.
+ // Built ONLY when a storage backend exists — store is nil when S3 is not
+ // configured and the local upload dir failed to initialize, and a
+ // reconciler with nil Storage would panic the worker goroutine on the
+ // first unreferenced row (ledger rows can pre-exist from a boot where
+ // storage WAS configured). Without storage the resolver skips every
+ // upload, so no new rows appear and the ledger simply waits for a boot
+ // with working storage. Started from main.go as its own worker.
+ if store != nil {
+ h.ChannelMediaReconciler = &service.ChannelMediaReconciler{
+ Queries: queries,
+ Storage: store,
+ Logger: slog.Default(),
+ }
+ }
h.ChannelSupervisor = engine.NewSupervisor(
lark.NewChannelInstallationStore(queries),
channelRegistry,
@@ -392,8 +407,9 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus
Credentials: installSvc,
Logger: slog.Default(),
})
+ mediaResolver := lark.NewFeishuMediaResolver(larkClient, installSvc, store, engine.NewDBMediaIntentLedger(queries), slog.Default())
channelRouter.Register(channel.TypeFeishu, lark.NewFeishuResolverSet(
- cs, feishuSession, auditLogger, resolverReplier, typingIndicator,
+ cs, feishuSession, auditLogger, resolverReplier, typingIndicator, mediaResolver,
))
slog.Info("lark inbound pipeline wired", "connector", connectorLabel)
diff --git a/server/internal/handler/chat_input_ownership_test.go b/server/internal/handler/chat_input_ownership_test.go
index 25de0b2eff..f4fe58f475 100644
--- a/server/internal/handler/chat_input_ownership_test.go
+++ b/server/internal/handler/chat_input_ownership_test.go
@@ -349,12 +349,40 @@ func insertChannelChatTask(t *testing.T, ctx context.Context, agentID, runtimeID
return taskID
}
-// TestCompleteTask_ChannelEmptyOutputWritesNoRow pins the MUL-4351 review fix:
-// a legacy/channel task (chat_input_task_id NULL) that completes with empty
-// output must NOT write an assistant row — so chat:done carries empty content
-// and the Slack/Lark outbound keeps silently dropping it. The no_response
-// fallback body must never reach an external channel. A non-empty channel
-// completion still writes an ordinary message.
+// insertSealedChannelChatTask creates a running channel-shaped chat task the
+// way EnqueueChatTask now does: the task owns its input batch
+// (chat_input_task_id = id) and the sealed user message carries the immutable
+// channel_ingested stamp.
+func insertSealedChannelChatTask(t *testing.T, ctx context.Context, agentID, runtimeID, sessionID, content string) string {
+ t.Helper()
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority, started_at, dispatched_at)
+ VALUES ($1, $2, $3, 'running', 2, now(), now())
+ RETURNING id
+ `, agentID, runtimeID, sessionID).Scan(&taskID); err != nil {
+ t.Fatalf("setup: create sealed channel chat task: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ UPDATE agent_task_queue SET chat_input_task_id = id WHERE id = $1
+ `, taskID); err != nil {
+ t.Fatalf("setup: set input owner: %v", err)
+ }
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content, task_id, channel_ingested)
+ VALUES ($1, 'user', $2, $3, TRUE)
+ `, sessionID, content, taskID); err != nil {
+ t.Fatalf("setup: seal channel user message: %v", err)
+ }
+ return taskID
+}
+
+// TestCompleteTask_ChannelEmptyOutputWritesNoRow pins the MUL-4351 review fix
+// for the LEGACY channel shape (chat_input_task_id NULL): an empty completion
+// must NOT write an assistant row — so chat:done carries empty content and the
+// Slack/Lark outbound keeps silently dropping it. The no_response fallback
+// body must never reach an external channel. A non-empty channel completion
+// still writes an ordinary message.
func TestCompleteTask_ChannelEmptyOutputWritesNoRow(t *testing.T) {
if testHandler == nil {
t.Skip("database not available")
@@ -384,3 +412,65 @@ func TestCompleteTask_ChannelEmptyOutputWritesNoRow(t *testing.T) {
t.Fatalf("channel message = kind %q content %q, want message/'channel reply'", rows[0].MessageKind, rows[0].Content)
}
}
+
+// TestCompleteTask_SealedChannelEmptyOutputWritesNoRow pins the silent-drop
+// contract for the NEW channel shape: sealed channel tasks own their input
+// batch (chat_input_task_id = id), so the discriminator is the immutable
+// channel_ingested stamp, not a NULL owner. An empty completion must write no
+// assistant row — the outbound patcher forwards any non-empty content
+// verbatim, so a no_response fallback row would be pushed to Feishu/Slack.
+func TestCompleteTask_SealedChannelEmptyOutputWritesNoRow(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "sealed channel chat")
+
+ emptyTask := insertSealedChannelChatTask(t, ctx, agentID, runtimeID, sessionID, "[Image]")
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(emptyTask), completeResult(t, " "), "", "", false); err != nil {
+ t.Fatalf("complete sealed channel task (empty): %v", err)
+ }
+ if rows := assistantRows(t, ctx, sessionID); len(rows) != 0 {
+ t.Fatalf("sealed channel empty completion must write NO assistant row, got %d", len(rows))
+ }
+
+ // Non-empty output still writes one ordinary message.
+ textTask := insertSealedChannelChatTask(t, ctx, agentID, runtimeID, sessionID, "hello")
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(textTask), completeResult(t, "sealed channel reply"), "", "", false); err != nil {
+ t.Fatalf("complete sealed channel task (text): %v", err)
+ }
+ rows := assistantRows(t, ctx, sessionID)
+ if len(rows) != 1 || rows[0].MessageKind != protocol.ChatMessageKindMessage || rows[0].Content != "sealed channel reply" {
+ t.Fatalf("sealed channel non-empty completion = %+v, want one ordinary message", rows)
+ }
+}
+
+// TestCompleteTask_SealedChannelRetryEmptyOutputWritesNoRow: an auto-retry
+// clone inherits its parent's chat_input_task_id while the sealed messages
+// stay tagged with the parent's id. The provenance check must follow the
+// inherited owner — keying it off the retry's own id would misread the task
+// as direct and push the no_response fallback to the external channel.
+func TestCompleteTask_SealedChannelRetryEmptyOutputWritesNoRow(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+ agentID, sessionID, runtimeID, _ := setupDirectChatSession(t, ctx, "sealed channel retry chat")
+
+ parentTask := insertSealedChannelChatTask(t, ctx, agentID, runtimeID, sessionID, "[Video]")
+ var retryTask string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (agent_id, runtime_id, chat_session_id, status, priority, started_at, dispatched_at, parent_task_id, retry_of_task_id, chat_input_task_id)
+ VALUES ($1, $2, $3, 'running', 2, now(), now(), $4, $4, $4)
+ RETURNING id
+ `, agentID, runtimeID, sessionID, parentTask).Scan(&retryTask); err != nil {
+ t.Fatalf("setup: create retry clone: %v", err)
+ }
+
+ if _, err := testHandler.TaskService.CompleteTask(ctx, parseUUID(retryTask), completeResult(t, ""), "", "", false); err != nil {
+ t.Fatalf("complete sealed channel retry (empty): %v", err)
+ }
+ if rows := assistantRows(t, ctx, sessionID); len(rows) != 0 {
+ t.Fatalf("sealed channel retry empty completion must write NO assistant row, got %d", len(rows))
+ }
+}
diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.go
index 4641678709..dc61b885db 100644
--- a/server/internal/handler/daemon.go
+++ b/server/internal/handler/daemon.go
@@ -2191,16 +2191,19 @@ func (h *Handler) buildClaimedTaskResponse(r *http.Request, task *db.AgentTaskQu
}
}
// Resolve the user-message input batch for this run. A task-owned
- // direct-chat task (chat_input_task_id set, MUL-4351) reads exactly
- // the user messages tagged with its own input owner, so a message
- // that arrived after this turn was sealed can never be absorbed here.
- // Legacy and channel (Slack/Lark) tasks carry a NULL owner and keep
- // the trailing-message selector — the run of user messages after the
- // last assistant row, which also covers a debounced burst (MUL-2968:
- // "看上海天气" then "还有青岛" must both be delivered) — so a rolling
- // deploy never replays their history. Attachments are collected per
- // included message so the agent can `multica attachment download <id>`
- // (the inline markdown URL is signed + 30-min expiring on the CDN).
+ // task (chat_input_task_id set) reads exactly the user messages
+ // tagged with its own input owner, so a message that arrived after
+ // this turn was sealed can never be absorbed here. Direct-chat
+ // tasks have owned their single message since MUL-4351; channel
+ // (Slack/Lark) tasks now seal their trailing batch at enqueue too.
+ // Only legacy tasks created before that deploy carry a NULL owner
+ // and keep the trailing-message selector — the run of user messages
+ // after the last assistant row, which also covers a debounced burst
+ // (MUL-2968: "看上海天气" then "还有青岛" must both be delivered) —
+ // so a rolling deploy never replays their history. Attachments are
+ // collected per included message so the agent can
+ // `multica attachment download <id>` (the inline markdown URL is
+ // signed + 30-min expiring on the CDN).
var unanswered []db.ChatMessage
var inputLoadErr error
if task.ChatInputTaskID.Valid {
@@ -2733,6 +2736,9 @@ func (h *Handler) ResolveTaskSkillBundles(w http.ResponseWriter, r *http.Request
// these, not just the latest. Every completed or failed run writes an
// assistant row, so the anchor advances one turn at a time; the result is the
// whole slice on the first turn and exactly the new message(s) thereafter.
+// Legacy channel tasks also stop at the first unexpired media marker so an old
+// run cannot consume a placeholder that has not been bound yet. New channel
+// tasks use task-owned input batches and do not depend on this fallback.
func trailingUserMessages(msgs []db.ChatMessage) []db.ChatMessage {
start := 0
for i := len(msgs) - 1; i >= 0; i-- {
@@ -2741,7 +2747,15 @@ func trailingUserMessages(msgs []db.ChatMessage) []db.ChatMessage {
break
}
}
- return msgs[start:]
+ msgs = msgs[start:]
+ now := time.Now()
+ for i := range msgs {
+ pending := msgs[i].ChannelMediaPendingUntil
+ if pending.Valid && pending.Time.After(now) {
+ return msgs[:i]
+ }
+ }
+ return msgs
}
// ListPendingTasksByRuntime returns queued/dispatched tasks for a runtime.
diff --git a/server/internal/handler/daemon_chat_prompt_test.go b/server/internal/handler/daemon_chat_prompt_test.go
index 2f4280f05b..80682feb25 100644
--- a/server/internal/handler/daemon_chat_prompt_test.go
+++ b/server/internal/handler/daemon_chat_prompt_test.go
@@ -2,7 +2,9 @@ package handler
import (
"testing"
+ "time"
+ "github.com/jackc/pgx/v5/pgtype"
db "github.com/multica-ai/multica/server/pkg/db/generated"
)
@@ -10,6 +12,14 @@ func msg(role, content string) db.ChatMessage {
return db.ChatMessage{Role: role, Content: content}
}
+func mediaPendingMsg(content string, until time.Time) db.ChatMessage {
+ return db.ChatMessage{
+ Role: "user",
+ Content: content,
+ ChannelMediaPendingUntil: pgtype.Timestamptz{Time: until, Valid: true},
+ }
+}
+
func contents(msgs []db.ChatMessage) []string {
out := make([]string, len(msgs))
for i, m := range msgs {
@@ -76,6 +86,23 @@ func TestTrailingUserMessages(t *testing.T) {
in: []db.ChatMessage{msg("user", "hi")},
want: []string{"hi"},
},
+ {
+ name: "stops before media that is still pending",
+ in: []db.ChatMessage{
+ msg("user", "ready"),
+ mediaPendingMsg("[Image]", time.Now().Add(time.Minute)),
+ msg("user", "after image"),
+ },
+ want: []string{"ready"},
+ },
+ {
+ name: "expired media placeholder is ready",
+ in: []db.ChatMessage{
+ mediaPendingMsg("[Image]", time.Now().Add(-time.Minute)),
+ msg("user", "after image"),
+ },
+ want: []string{"[Image]", "after image"},
+ },
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
diff --git a/server/internal/handler/file_test.go b/server/internal/handler/file_test.go
index 4d6480bc97..371e73f437 100644
--- a/server/internal/handler/file_test.go
+++ b/server/internal/handler/file_test.go
@@ -74,7 +74,14 @@ func (m *mockStorage) Delete(_ context.Context, key string) {
defer m.mu.Unlock()
delete(m.files, key)
}
+func (m *mockStorage) DeleteObject(ctx context.Context, key string) error {
+ m.Delete(ctx, key)
+ return nil
+}
func (m *mockStorage) DeleteKeys(_ context.Context, _ []string) {}
+func (m *mockStorage) ObjectURL(key string) string {
+ return "https://cdn.example.com/" + key
+}
func (m *mockStorage) KeyFromURL(rawURL string) string {
for _, prefix := range []string{
"https://cdn.example.com/",
diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.go
index 97a06e4b94..655ea0c127 100644
--- a/server/internal/handler/handler.go
+++ b/server/internal/handler/handler.go
@@ -220,6 +220,11 @@ type Handler struct {
// delivering events, to flush debounced run triggers and join in-flight
// reply goroutines. Built unconditionally (even without Lark).
ChannelRouter *engine.Router
+ // ChannelMediaReconciler settles the channel-media intent ledger
+ // (uploaded-but-unbound object reclaim). Built in cmd/server/router.go
+ // where the storage backend exists; main.go starts it as an independent
+ // worker goroutine. Nil when no storage backend is configured.
+ ChannelMediaReconciler *service.ChannelMediaReconciler
// SlackInstall owns the bring-your-own-app Slack install lifecycle (register
// pasted tokens / list / revoke) and the at-rest encryption of each app's bot
// + app tokens (MUL-3666). Nil unless MULTICA_SLACK_SECRET_KEY is set.
diff --git a/server/internal/integrations/channel/engine/provenance.go b/server/internal/integrations/channel/engine/provenance.go
new file mode 100644
index 0000000000..be663c0068
--- /dev/null
+++ b/server/internal/integrations/channel/engine/provenance.go
@@ -0,0 +1,34 @@
+package engine
+
+import (
+ "context"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// ChannelProvenanceQueries is the single query the reply-origin check needs.
+// *db.Queries satisfies it.
+type ChannelProvenanceQueries interface {
+ TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)
+}
+
+// TaskInputIsChannelIngested reports whether a completed chat task took its
+// input from the channel, so its reply (or failure notice) belongs on the
+// external platform. Direct (web/mobile) tasks can reuse a channel-bound
+// session, but their replies stay in Multica (MUL-4988).
+//
+// chat_input_task_id alone cannot discriminate: sealed channel tasks own an
+// input batch exactly like direct tasks do. The verdict is the immutable
+// channel_ingested stamp on the owned batch, keyed by the batch OWNER id so an
+// auto-retry clone (which inherits chat_input_task_id while its messages stay
+// tagged with the parent) reaches the same verdict as its parent. A NULL owner
+// is a pre-sealing channel task — direct tasks have owned their batch since
+// MUL-4351 — so it keeps the deliver-by-default behavior #5645 shipped with.
+func TaskInputIsChannelIngested(ctx context.Context, q ChannelProvenanceQueries, task db.AgentTaskQueue) (bool, error) {
+ if !task.ChatInputTaskID.Valid {
+ return true, nil
+ }
+ return q.TaskHasChannelIngestedMessages(ctx, task.ChatInputTaskID)
+}
diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.go
index 80b1d76a6c..9aef3745eb 100644
--- a/server/internal/integrations/channel/engine/resolvers.go
+++ b/server/internal/integrations/channel/engine/resolvers.go
@@ -4,6 +4,7 @@ import (
"context"
"errors"
+ "github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/integrations/channel"
@@ -89,16 +90,24 @@ type EnsureSessionParams struct {
// AppendParams carries the inputs for SessionBinder.AppendMessage. ClaimToken
// is the dedup owner-fence token; the binder runs the dedup Mark INSIDE its
// chat_message+session tx so the durable write and the Mark commit atomically.
+// MediaPendingSeconds persists the placeholder fallback budget; the append
+// transaction turns it into a DB-clock deadline (now() + budget) so every
+// now()-based consumer reads the same clock that wrote it.
type AppendParams struct {
- SessionID pgtype.UUID
- Sender pgtype.UUID
- InstallationID pgtype.UUID
- Message channel.InboundMessage
- ClaimToken pgtype.UUID
+ SessionID pgtype.UUID
+ Sender pgtype.UUID
+ InstallationID pgtype.UUID
+ Message channel.InboundMessage
+ ClaimToken pgtype.UUID
+ MediaPendingSeconds float64
}
// AppendResult reports what AppendMessage decided.
type AppendResult struct {
+ // MessageID is the durable chat_message row created by AppendMessage.
+ // Detached media processing uses it to link attachments after the
+ // connector ACK path has completed.
+ MessageID pgtype.UUID
// IssueCommand is non-nil when the message was an /issue command.
IssueCommand *IssueCommand
// DedupMarked is true when AppendMessage finalized the dedup claim in its
@@ -106,6 +115,17 @@ type AppendResult struct {
DedupMarked bool
}
+// 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.
+type BindMediaParams struct {
+ MessageID pgtype.UUID
+ SessionID pgtype.UUID
+ WorkspaceID pgtype.UUID
+ Sender pgtype.UUID
+ MediaRefs []channel.MediaRef
+}
+
// IssueCommand is the parsed /issue command.
type IssueCommand struct {
Title string
@@ -161,6 +181,80 @@ type Deduper interface {
type SessionBinder interface {
EnsureSession(ctx context.Context, p EnsureSessionParams) (pgtype.UUID, error)
AppendMessage(ctx context.Context, p AppendParams) (AppendResult, error)
+ BindMedia(ctx context.Context, p BindMediaParams) error
+}
+
+// MediaResolver resolves platform media after the user message and dedup mark
+// are durable. The Router runs it off the connector ACK path and binds any
+// returned MediaRefs; the independently scheduled task remains deferred until
+// binding finishes or the persisted deadline expires. Implementations are
+// best-effort: failures leave the stored placeholder text intact and NEVER
+// delete anything inline — every uploaded object is covered by an intent-
+// ledger row written before the PUT (see MediaIntentLedger), and the
+// asynchronous reconciler settles whatever binding did not claim.
+type MediaResolver interface {
+ // HasMedia reports whether msg references platform media that
+ // ResolveMedia would fetch. The Router calls it synchronously on the
+ // connector ACK path to decide whether to persist a media deadline and
+ // queue a resolution job at all, so implementations must be pure
+ // in-memory checks (no I/O). A false result keeps the message on the
+ // 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.
+ ResolveMedia(ctx context.Context, inst ResolvedInstallation, sender ResolvedIdentity, sessionID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage
+}
+
+// MediaIntentLedger persists upload intent BEFORE the object is written. The
+// row is the only artifact any failure path leaves behind: upload error,
+// resolve deadline, bind failure, ambiguous commit, or a crash all simply
+// leave it for the reconciler, which settles it long after any in-flight PUT
+// or COMMIT can still land. This is what makes "did my side effect happen?"
+// a question nobody has to answer inline.
+type MediaIntentLedger interface {
+ // RecordPendingMediaObject upserts the intent row. ok=false means the
+ // key has left 'pending' (the reconciler owns it) — the caller must skip
+ // the upload entirely rather than resurrect the row.
+ RecordPendingMediaObject(ctx context.Context, p RecordPendingMediaObjectParams) (ok bool, err error)
+}
+
+// RecordPendingMediaObjectParams identifies one intended object. StorageURL
+// is the URL the attachment row will carry (pure function of the key), so
+// the reconciler can check for a durable reference. InstallationID is an
+// ops-diagnostic only.
+type RecordPendingMediaObjectParams struct {
+ StorageKey string
+ WorkspaceID pgtype.UUID
+ ChatMessageID pgtype.UUID
+ StorageURL string
+ InstallationID pgtype.UUID
+}
+
+// NewDBMediaIntentLedger adapts *db.Queries to MediaIntentLedger.
+func NewDBMediaIntentLedger(q *db.Queries) MediaIntentLedger {
+ return dbMediaIntentLedger{q: q}
+}
+
+type dbMediaIntentLedger struct{ q *db.Queries }
+
+func (l dbMediaIntentLedger) RecordPendingMediaObject(ctx context.Context, p RecordPendingMediaObjectParams) (bool, error) {
+ _, err := l.q.RecordChannelMediaPendingObject(ctx, db.RecordChannelMediaPendingObjectParams{
+ StorageKey: p.StorageKey,
+ WorkspaceID: p.WorkspaceID,
+ ChatMessageID: p.ChatMessageID,
+ StorageUrl: p.StorageURL,
+ InstallationID: p.InstallationID,
+ })
+ if errors.Is(err, pgx.ErrNoRows) {
+ // The state-guarded upsert matched a 'deleting' row: the reconciler
+ // owns this key and it must not be resurrected.
+ return false, nil
+ }
+ if err != nil {
+ return false, err
+ }
+ return true, nil
}
// Auditor records a dropped inbound event (no message body — drop-audit
@@ -200,6 +294,7 @@ type ResolverSet struct {
Identity IdentityResolver
Dedup Deduper
Session SessionBinder
+ Media MediaResolver
Audit Auditor
Replier OutboundReplier
Typing TypingNotifier
@@ -216,6 +311,7 @@ type IssueCreator interface {
// trigger a chat run. Shared across platforms.
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
}
// 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.go
index 1335ea5487..919e7b08fb 100644
--- a/server/internal/integrations/channel/engine/router.go
+++ b/server/internal/integrations/channel/engine/router.go
@@ -21,8 +21,9 @@ import (
// channel.InboundMessage and calls Handle, which routes by ChannelType to that
// platform's registered resolver set and runs the same ordered pipeline for
// every platform — installation route → two-phase dedup → group @bot filter →
-// identity + membership → ensure session → append+mark → /issue → debounced
-// run trigger — then drives the detached outbound replier + typing indicator.
+// identity + membership → ensure session → append+mark → /issue → durable
+// debounced run trigger + detached media binding — then drives the detached
+// outbound replier + typing indicator.
//
// The core contains no platform specifics: everything platform-shaped lives
// behind the resolver interfaces (a feishu ResolverSet is the first
@@ -39,7 +40,16 @@ type Router struct {
batcher *pendingBatcher
replyTimeout time.Duration
+ mediaTimeout time.Duration
+ mediaCtx context.Context
+ mediaCancel context.CancelFunc
+ mediaSem chan struct{}
replyWg sync.WaitGroup
+ mediaWg sync.WaitGroup
+
+ mediaQueueMu sync.Mutex
+ mediaQueues map[string]*mediaQueueEntry
+ stopping bool
logger *slog.Logger
@@ -53,7 +63,18 @@ type RouterConfig struct {
// call. It runs off the connector ACK path, so it must stay strictly
// under the platform ACK deadline (Lark: 3s). Defaults to 2.5s.
ReplyTimeout time.Duration
- Logger *slog.Logger
+ // MediaTimeout caps detached best-effort media download, upload, and
+ // attachment binding for one message. The budget starts at append time
+ // (it must match the persisted fire_at fallback), so it also spans any
+ // wait behind earlier media in the same session and for a global
+ // concurrency slot. Defaults to 45s.
+ MediaTimeout time.Duration
+ // MediaConcurrency caps concurrent media resolutions across all
+ // sessions, bounding burst memory (unknown-length uploads buffer up to
+ // the 100 MiB resource cap each) and platform download pressure.
+ // Per-session ordering is unaffected. Defaults to 8.
+ MediaConcurrency int
+ Logger *slog.Logger
}
// NewRouter builds a Router around the shared (platform-agnostic) services:
@@ -64,20 +85,41 @@ func NewRouter(issues IssueCreator, tasks TaskEnqueuer, reader SessionReader, cf
if cfg.ReplyTimeout == 0 {
cfg.ReplyTimeout = 2500 * time.Millisecond
}
+ if cfg.MediaTimeout == 0 {
+ cfg.MediaTimeout = DefaultMediaTimeout
+ }
+ if cfg.MediaConcurrency == 0 {
+ cfg.MediaConcurrency = 8
+ }
if cfg.Logger == nil {
cfg.Logger = slog.Default()
}
+ mediaCtx, mediaCancel := context.WithCancel(context.Background())
return &Router{
sets: make(map[channel.Type]ResolverSet),
issues: issues,
tasks: tasks,
reader: reader,
replyTimeout: cfg.ReplyTimeout,
+ mediaTimeout: cfg.MediaTimeout,
+ mediaCtx: mediaCtx,
+ mediaCancel: mediaCancel,
+ mediaSem: make(chan struct{}, cfg.MediaConcurrency),
logger: cfg.Logger,
pendingFresh: make(map[string]bool),
+ mediaQueues: make(map[string]*mediaQueueEntry),
}
}
+// DefaultMediaTimeout is the default RouterConfig.MediaTimeout. Exported so
+// the channel-media settle invariant test can assert the reconciler's settle
+// delay dwarfs every pipeline budget.
+const DefaultMediaTimeout = 45 * time.Second
+
+type mediaQueueEntry struct {
+ tail chan struct{}
+}
+
// Register binds a platform's ResolverSet under t. Call at boot, before Run.
// Registering an empty Type or a set missing a required resolver is ignored.
func (r *Router) Register(t channel.Type, set ResolverSet) {
@@ -97,13 +139,31 @@ func (r *Router) EnableRunBatching(window time.Duration) {
r.batcher = newPendingBatcher(window)
}
-// Drain flushes debounced run triggers and joins in-flight reply goroutines.
-// Call on shutdown AFTER the Supervisor has stopped delivering events.
-func (r *Router) Drain() {
- if r.batcher != nil {
- r.batcher.FlushAll()
+// Drain cancels detached media processing, flushes debounced run triggers, and
+// joins media/reply goroutines until ctx ends. It returns whether everything
+// completed. Call on shutdown AFTER the Supervisor has stopped delivering
+// events; timed-out media retains its durable placeholder fallback.
+func (r *Router) Drain(ctx context.Context) bool {
+ r.mediaQueueMu.Lock()
+ r.stopping = true
+ r.mediaCancel()
+ r.mediaQueueMu.Unlock()
+
+ done := make(chan struct{})
+ go func() {
+ if r.batcher != nil {
+ r.batcher.FlushAll()
+ }
+ r.mediaWg.Wait()
+ r.replyWg.Wait()
+ close(done)
+ }()
+ select {
+ case <-done:
+ return true
+ case <-ctx.Done():
+ return false
}
- r.replyWg.Wait()
}
// ErrNoResolverSet is returned by Handle when a message arrives for a channel
@@ -258,14 +318,31 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
// Single tx; an error rolled it back, nothing landed. Release.
return Result{}, finalizeRelease, fmt.Errorf("ensure chat session: %w", err)
}
-
// 6. Append message + in-tx dedup Mark — the durable transition point.
+ // The media budget is persisted only when the message actually carries
+ // media: a plain text message must never wait behind the media semaphore
+ // or fall back to the 45s deadline after a crash. It is a relative
+ // duration — the append transaction anchors it to the DB clock, the same
+ // clock every now()-based reader uses.
+ mediaPendingSeconds := 0.0
+ resolveMedia := set.Media != nil && set.Media.HasMedia(msg)
+ // The local monotonic budget starts BEFORE the append: the DB anchors its
+ // fallback at now() during the insert, so a post-commit local start would
+ // end Δ(append latency) AFTER the durable deadline — a window where the
+ // task is already claimable while the resolver still runs, handing the
+ // agent a placeholder that binds moments later. Starting here keeps the
+ // ordering local-gives-up ≤ durable-fallback-fires.
+ localMediaDeadline := time.Now().Add(r.mediaTimeout)
+ if resolveMedia {
+ mediaPendingSeconds = r.mediaTimeout.Seconds()
+ }
appendRes, err := set.Session.AppendMessage(ctx, AppendParams{
- SessionID: sessionID,
- Sender: identity.UserID,
- InstallationID: inst.ID,
- Message: msg,
- ClaimToken: claimToken,
+ SessionID: sessionID,
+ Sender: identity.UserID,
+ InstallationID: inst.ID,
+ Message: msg,
+ ClaimToken: claimToken,
+ MediaPendingSeconds: mediaPendingSeconds,
})
if err != nil {
if errors.Is(err, ErrClaimLost) {
@@ -312,9 +389,138 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channe
// session creator (group sessions are creator=installer). Latest sender
// in a window wins (MUL-2645).
r.scheduleRun(set, inst, msg, sessionID, identity.UserID)
+ if resolveMedia {
+ r.enqueueMedia(set, inst, identity, appendRes.MessageID, msg, sessionID, localMediaDeadline)
+ }
return res, postAppendFinalize, nil
}
+// enqueueMedia detaches remote media I/O from Handle while preserving message
+// 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) {
+ key := keyForSession(sessionID)
+ done := make(chan struct{})
+
+ r.mediaQueueMu.Lock()
+ if r.stopping {
+ r.mediaQueueMu.Unlock()
+ return
+ }
+ entry, ok := r.mediaQueues[key]
+ var previous <-chan struct{}
+ if !ok {
+ entry = &mediaQueueEntry{}
+ r.mediaQueues[key] = entry
+ } else {
+ previous = entry.tail
+ }
+ entry.tail = done
+ r.mediaWg.Add(1)
+ r.mediaQueueMu.Unlock()
+
+ go func() {
+ defer r.mediaWg.Done()
+ defer close(done)
+ defer r.finishMediaQueue(key, done)
+ // Both queue waits are bounded by the message's own deadline, not
+ // just global shutdown: in a media burst an already-expired job must
+ // not keep holding its goroutine and payload until it reaches the
+ // front — it skips straight to the empty finalize (marker clear +
+ // promotion), which also unblocks the session's later messages.
+ expiry := time.NewTimer(time.Until(deadline))
+ defer expiry.Stop()
+ expired := false
+ if previous != nil {
+ select {
+ case <-previous:
+ case <-r.mediaCtx.Done():
+ case <-expiry.C:
+ expired = true
+ }
+ }
+ if !expired {
+ select {
+ case r.mediaSem <- struct{}{}:
+ defer func() { <-r.mediaSem }()
+ case <-r.mediaCtx.Done():
+ // Cancelled while queued for a slot: proceed without one.
+ // ResolveMedia is skipped on the dead context and only the
+ // bounded DB finalize runs, preserving prompt marker
+ // clearing on shutdown.
+ case <-expiry.C:
+ // Expired while queued: no slot needed — resolveAndBindMedia
+ // sees the dead deadline and runs only the empty finalize.
+ }
+ }
+ r.resolveAndBindMedia(set, inst, identity, chatMessageID, msg, sessionID, 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) {
+ ctx, cancel := context.WithDeadline(r.mediaCtx, deadline)
+ defer cancel()
+
+ resolved := msg
+ if ctx.Err() == nil {
+ // Skipped entirely when the budget expired while queued (or on
+ // shutdown): resolving on a dead context would only churn through
+ // intent writes that immediately fail.
+ resolved = set.Media.ResolveMedia(ctx, inst, identity, sessionID, chatMessageID, msg)
+ }
+ finalizeCtx, finalizeCancel := context.WithTimeout(context.Background(), mediaFinalizeTimeout)
+ defer finalizeCancel()
+ if err := ctx.Err(); err != nil {
+ // Refs resolved before the deadline already sit in object storage but
+ // will not gain an attachment row. Nothing is deleted here — their
+ // intent-ledger rows were written before the uploads, and the
+ // reconciler reclaims unreferenced objects after the settle delay.
+ resolved.MediaRefs = nil
+ r.logger.Warn("channel router: media resolution incomplete; using placeholder",
+ "channel_type", string(msg.Source.ChannelType),
+ "event_id", msg.EventID,
+ "message_id", msg.MessageID,
+ "error", err)
+ }
+ if err := set.Session.BindMedia(finalizeCtx, BindMediaParams{
+ MessageID: chatMessageID,
+ SessionID: sessionID,
+ WorkspaceID: inst.WorkspaceID,
+ Sender: identity.UserID,
+ MediaRefs: resolved.MediaRefs,
+ }); err != 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
+ // durable and the reconciler settles the objects.
+ r.logger.Warn("channel router: media attachment binding failed",
+ "channel_type", string(msg.Source.ChannelType),
+ "event_id", msg.EventID,
+ "message_id", msg.MessageID,
+ "err", err)
+ }
+ if err := r.tasks.PromoteChannelChatTasksIfMediaReady(finalizeCtx, sessionID); err != nil {
+ r.logger.Warn("channel router: media-ready task promotion failed",
+ "channel_type", string(msg.Source.ChannelType),
+ "event_id", msg.EventID,
+ "message_id", msg.MessageID,
+ "err", err)
+ }
+}
+
+func (r *Router) finishMediaQueue(key string, done chan struct{}) {
+ r.mediaQueueMu.Lock()
+ defer r.mediaQueueMu.Unlock()
+ entry, ok := r.mediaQueues[key]
+ if !ok || entry.tail != done {
+ return
+ }
+ delete(r.mediaQueues, key)
+}
+
// scheduleRun hands the per-session run trigger to the debouncer (or fires it
// inline when batching is disabled).
func (r *Router) scheduleRun(set ResolverSet, inst ResolvedInstallation, msg channel.InboundMessage, sessionID, initiatorUserID pgtype.UUID) {
diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.go
index 5afe8b8a7d..6f3c9cc65f 100644
--- a/server/internal/integrations/channel/engine/router_test.go
+++ b/server/internal/integrations/channel/engine/router_test.go
@@ -68,12 +68,16 @@ func (f *fakeDedup) marks() int { f.mu.Lock(); defer f.mu.Unlock(); return f.
func (f *fakeDedup) releases() int { f.mu.Lock(); defer f.mu.Unlock(); return f.relCalls }
type fakeBinder struct {
+ mu sync.Mutex
ensureID pgtype.UUID
ensureErr error
appendResult AppendResult
appendErr error
+ appendDelay time.Duration
+ bindErr error
lastEnsure EnsureSessionParams
lastAppend AppendParams
+ lastBind BindMediaParams
}
func (f *fakeBinder) EnsureSession(_ context.Context, p EnsureSessionParams) (pgtype.UUID, error) {
@@ -81,8 +85,31 @@ func (f *fakeBinder) EnsureSession(_ context.Context, p EnsureSessionParams) (pg
return f.ensureID, f.ensureErr
}
func (f *fakeBinder) AppendMessage(_ context.Context, p AppendParams) (AppendResult, error) {
+ f.mu.Lock()
+ delay := f.appendDelay
f.lastAppend = p
- return f.appendResult, f.appendErr
+ res, err := f.appendResult, f.appendErr
+ f.mu.Unlock()
+ if delay > 0 {
+ time.Sleep(delay)
+ }
+ return res, err
+}
+func (f *fakeBinder) BindMedia(_ context.Context, p BindMediaParams) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.lastBind = p
+ return f.bindErr
+}
+func (f *fakeBinder) boundMedia() BindMediaParams {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.lastBind
+}
+func (f *fakeBinder) appendedParams() AppendParams {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.lastAppend
}
type fakeAuditor struct {
@@ -140,6 +167,72 @@ func (f *fakeTyping) OnSettled(_ context.Context, _ pgtype.UUID) {
func (f *fakeTyping) calls() int { f.mu.Lock(); defer f.mu.Unlock(); return f.count }
func (f *fakeTyping) settledCalls() int { f.mu.Lock(); defer f.mu.Unlock(); return f.settled }
+type fakeMedia struct {
+ mu sync.Mutex
+ count int
+ noMedia bool
+ waitForCancel bool
+ started chan struct{}
+ release <-chan struct{}
+ resolve func(context.Context, channel.InboundMessage) channel.InboundMessage
+ lastMessageID pgtype.UUID
+}
+
+func (f *fakeMedia) HasMedia(_ channel.InboundMessage) bool {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return !f.noMedia
+}
+
+func (f *fakeMedia) resolvedMessageID() pgtype.UUID {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.lastMessageID
+}
+
+func (f *fakeMedia) ResolveMedia(ctx context.Context, _ ResolvedInstallation, _ ResolvedIdentity, _ pgtype.UUID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage {
+ f.mu.Lock()
+ f.count++
+ f.lastMessageID = chatMessageID
+ waitForCancel := f.waitForCancel
+ started := f.started
+ release := f.release
+ resolve := f.resolve
+ f.mu.Unlock()
+ if resolve != nil {
+ return resolve(ctx, msg)
+ }
+ if started != nil {
+ close(started)
+ }
+ if release != nil {
+ select {
+ case <-release:
+ case <-ctx.Done():
+ return msg
+ }
+ }
+ if waitForCancel {
+ <-ctx.Done()
+ return msg
+ }
+ msg.MediaRefs = append(msg.MediaRefs, channel.MediaRef{
+ Type: channel.MsgTypeImage,
+ StorageKey: "workspaces/ws/lark/image",
+ StorageURL: "https://cdn.example.test/image",
+ Filename: "image.png",
+ MimeType: "image/png",
+ SizeBytes: 3,
+ })
+ return msg
+}
+
+func (f *fakeMedia) calls() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.count
+}
+
type fakeIssues struct {
called bool
params service.IssueCreateParams
@@ -156,21 +249,42 @@ func (f *fakeIssues) Create(_ context.Context, p service.IssueCreateParams, _ se
type fakeTasks struct {
mu sync.Mutex
called bool
+ callCount int
+ promotions int
forceFresh bool
initiator pgtype.UUID
err error
}
+func (f *fakeTasks) PromoteChannelChatTasksIfMediaReady(_ context.Context, _ pgtype.UUID) error {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.promotions++
+ 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()
f.called = true
+ f.callCount++
f.forceFresh = forceFresh
f.initiator = initiator
return db.AgentTaskQueue{}, f.err
}
func (f *fakeTasks) wasCalled() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.called }
func (f *fakeTasks) freshArg() bool { f.mu.Lock(); defer f.mu.Unlock(); return f.forceFresh }
+func (f *fakeTasks) calls() int { f.mu.Lock(); defer f.mu.Unlock(); return f.callCount }
+func (f *fakeTasks) promotionCalls() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.promotions
+}
+func (f *fakeTasks) initiatorArg() pgtype.UUID {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.initiator
+}
type fakeReader struct {
session db.ChatSession
@@ -221,6 +335,7 @@ type harness struct {
audit *fakeAuditor
replier *fakeReplier
typing *fakeTyping
+ media *fakeMedia
issues *fakeIssues
tasks *fakeTasks
reader *fakeReader
@@ -229,13 +344,20 @@ type harness struct {
func newHarness(t *testing.T) *harness {
t.Helper()
h := &harness{
- inst: &fakeInstaller{inst: activeResolved(t)},
- ident: &fakeIdentity{id: ResolvedIdentity{UserID: uuidFromString(t, "44444444-4444-4444-4444-444444444444")}},
- dedup: &fakeDedup{token: uuidFromString(t, "55555555-5555-5555-5555-555555555555")},
- binder: &fakeBinder{ensureID: uuidFromString(t, "66666666-6666-6666-6666-666666666666"), appendResult: AppendResult{DedupMarked: true}},
+ inst: &fakeInstaller{inst: activeResolved(t)},
+ ident: &fakeIdentity{id: ResolvedIdentity{UserID: uuidFromString(t, "44444444-4444-4444-4444-444444444444")}},
+ dedup: &fakeDedup{token: uuidFromString(t, "55555555-5555-5555-5555-555555555555")},
+ binder: &fakeBinder{
+ ensureID: uuidFromString(t, "66666666-6666-6666-6666-666666666666"),
+ appendResult: AppendResult{
+ MessageID: uuidFromString(t, "99999999-9999-4999-8999-999999999999"),
+ DedupMarked: true,
+ },
+ },
audit: &fakeAuditor{},
replier: &fakeReplier{},
typing: &fakeTyping{},
+ media: &fakeMedia{},
issues: &fakeIssues{},
tasks: &fakeTasks{},
reader: &fakeReader{ws: db.Workspace{IssuePrefix: "MUL"}},
@@ -249,6 +371,7 @@ func newHarness(t *testing.T) *harness {
Audit: h.audit,
Replier: h.replier,
Typing: h.typing,
+ Media: h.media,
OriginType: "lark_chat",
})
return h
@@ -286,6 +409,9 @@ func TestRouter_RevokedInstallation_Drops(t *testing.T) {
if r, _ := h.audit.last(); r != DropReasonRevokedInstallation {
t.Fatalf("expected revoked_installation, got %q", r)
}
+ if h.media.calls() != 0 {
+ t.Fatal("revoked installation must not resolve media")
+ }
}
func TestRouter_Duplicate_Drops(t *testing.T) {
@@ -297,6 +423,9 @@ func TestRouter_Duplicate_Drops(t *testing.T) {
if r, _ := h.audit.last(); r != DropReasonDuplicate {
t.Fatalf("expected duplicate, got %q", r)
}
+ if h.media.calls() != 0 {
+ t.Fatal("duplicate message must not resolve media")
+ }
}
func TestRouter_GroupNotAddressed_Drops(t *testing.T) {
@@ -313,6 +442,9 @@ func TestRouter_GroupNotAddressed_Drops(t *testing.T) {
if h.dedup.marks() != 1 {
t.Fatalf("group-filter drop must finalize Mark (1), got %d", h.dedup.marks())
}
+ if h.media.calls() != 0 {
+ t.Fatal("unaddressed group message must not resolve media")
+ }
}
func TestRouter_UnboundSender_NeedsBinding(t *testing.T) {
@@ -327,6 +459,9 @@ func TestRouter_UnboundSender_NeedsBinding(t *testing.T) {
if h.dedup.marks() != 1 {
t.Fatalf("unbound drop must finalize Mark, got %d", h.dedup.marks())
}
+ if h.media.calls() != 0 {
+ t.Fatal("unbound sender must not resolve media")
+ }
if !waitFor(time.Second, func() bool {
for _, r := range h.replier.calls() {
if r.Outcome == OutcomeNeedsBinding && r.Sender == "ou_user_a" {
@@ -348,6 +483,9 @@ func TestRouter_NonMember_Drops(t *testing.T) {
if r, _ := h.audit.last(); r != DropReasonNonWorkspaceMember {
t.Fatalf("expected non_workspace_member, got %q", r)
}
+ if h.media.calls() != 0 {
+ t.Fatal("non-member sender must not resolve media")
+ }
}
func TestRouter_EnsureSessionError_Releases(t *testing.T) {
@@ -362,6 +500,25 @@ func TestRouter_EnsureSessionError_Releases(t *testing.T) {
}
}
+func TestRouter_AppendErrorReleasesClaimAndAllowsMediaRetry(t *testing.T) {
+ h := newHarness(t)
+ h.binder.appendErr = errors.New("db down")
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err == nil {
+ t.Fatal("append error must surface to the caller")
+ }
+ if h.dedup.releases() != 1 || h.media.calls() != 0 {
+ t.Fatalf("failed attempt: releases=%d media_calls=%d, want release=1 media_calls=0", h.dedup.releases(), h.media.calls())
+ }
+
+ h.binder.appendErr = nil
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("retry: %v", err)
+ }
+ if !waitFor(time.Second, func() bool { return h.media.calls() == 1 }) {
+ t.Fatalf("retry media calls = %d, want 1 total", h.media.calls())
+ }
+}
+
func TestRouter_Ingested_InTxMark_FinalizeNone(t *testing.T) {
h := newHarness(t)
h.reader.session = db.ChatSession{}
@@ -375,12 +532,213 @@ func TestRouter_Ingested_InTxMark_FinalizeNone(t *testing.T) {
if h.dedup.releases() != 0 {
t.Fatalf("a durable ingest must not Release, got %d", h.dedup.releases())
}
- if !h.tasks.wasCalled() {
+ if !waitFor(time.Second, h.tasks.wasCalled) {
t.Fatalf("ingest must trigger a chat run (inline, no batcher)")
}
if !waitFor(time.Second, func() bool { return h.typing.calls() == 1 }) {
t.Fatalf("ingest must show the typing indicator")
}
+ if h.media.calls() != 1 {
+ t.Fatalf("ingested message resolved media %d times, want 1", h.media.calls())
+ }
+ if refs := h.binder.boundMedia().MediaRefs; len(refs) != 1 {
+ t.Fatalf("resolved media not bound after append: %+v", refs)
+ }
+}
+
+func TestRouter_NoMediaMessageSkipsMediaPipeline(t *testing.T) {
+ h := newHarness(t)
+ h.media.noMedia = true
+
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if !waitFor(time.Second, h.tasks.wasCalled) {
+ t.Fatal("no-media message must still trigger a chat run")
+ }
+ if got := h.binder.appendedParams().MediaPendingSeconds; got != 0 {
+ t.Fatalf("no-media message persisted a media budget: %v", got)
+ }
+ if h.media.calls() != 0 {
+ t.Fatalf("no-media message ran ResolveMedia %d times, want 0", h.media.calls())
+ }
+ if h.tasks.promotionCalls() != 0 {
+ t.Fatalf("no-media message triggered %d promotions, want 0", h.tasks.promotionCalls())
+ }
+}
+
+func TestRouter_MediaResolverTimeoutAppendsOriginalMessage(t *testing.T) {
+ h := newHarness(t)
+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{MediaTimeout: 10 * time.Millisecond, Logger: discardLogger()})
+ h.media.waitForCancel = true
+ h.router.Register(channel.TypeFeishu, ResolverSet{
+ Installation: h.inst,
+ Identity: h.ident,
+ Dedup: h.dedup,
+ Session: h.binder,
+ Audit: h.audit,
+ Replier: h.replier,
+ Typing: h.typing,
+ Media: h.media,
+ OriginType: "lark_chat",
+ })
+
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("unexpected error: %v", err)
+ }
+ if !waitFor(time.Second, func() bool { return h.media.calls() == 1 }) {
+ t.Fatalf("media resolver calls = %d, want 1", h.media.calls())
+ }
+ if refs := h.binder.boundMedia().MediaRefs; len(refs) != 0 {
+ t.Fatalf("timed-out media refs must not attach: %+v", refs)
+ }
+ if !waitFor(time.Second, h.tasks.wasCalled) {
+ t.Fatalf("message should still be ingested and trigger a chat run")
+ }
+ if h.dedup.releases() != 0 {
+ t.Fatalf("media timeout must not release a durably appended message, got %d", h.dedup.releases())
+ }
+}
+
+func TestRouter_MediaBindFailureStillChecksPlaceholderPromotion(t *testing.T) {
+ h := newHarness(t)
+ h.binder.bindErr = errors.New("attachment write failed")
+
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if !waitFor(time.Second, func() bool { return h.tasks.promotionCalls() == 1 }) {
+ t.Fatal("binding failure did not check whether the cleared placeholder task could be promoted")
+ }
+ // No inline deletion on bind failure: the attachments may or may not
+ // have landed (ambiguous commit), and the intent ledger — cleared inside
+ // the same transaction — already reflects whichever outcome is durable.
+ // The reconciler settles the objects.
+}
+
+func TestRouter_MediaDeadlineDropsRefsWithoutBinding(t *testing.T) {
+ h := newHarness(t)
+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{MediaTimeout: 10 * time.Millisecond, Logger: discardLogger()})
+ // A rich post where an early upload succeeded before the deadline killed
+ // the rest of the resolution: the resolver returns the partial refs. The
+ // router must not bind them — and must not delete anything inline: the
+ // intent-ledger rows written before the uploads are the reclaim path.
+ h.media.resolve = func(ctx context.Context, msg channel.InboundMessage) channel.InboundMessage {
+ msg.MediaRefs = append(msg.MediaRefs, channel.MediaRef{
+ Type: channel.MsgTypeImage,
+ StorageKey: "workspaces/ws/lark/uploaded-before-deadline",
+ })
+ <-ctx.Done()
+ return msg
+ }
+ h.router.Register(channel.TypeFeishu, ResolverSet{
+ Installation: h.inst,
+ Identity: h.ident,
+ Dedup: h.dedup,
+ Session: h.binder,
+ Audit: h.audit,
+ Replier: h.replier,
+ Typing: h.typing,
+ Media: h.media,
+ OriginType: "lark_chat",
+ })
+
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ if !waitFor(time.Second, func() bool { return h.tasks.promotionCalls() == 1 }) {
+ t.Fatal("deadline expiry must still clear the marker and check promotion")
+ }
+ if refs := h.binder.boundMedia().MediaRefs; len(refs) != 0 {
+ t.Fatalf("timed-out refs must not bind: %+v", refs)
+ }
+}
+
+func TestRouter_MediaResolutionDoesNotBlockInboundHandle(t *testing.T) {
+ h := newHarness(t)
+ h.reader.session = db.ChatSession{}
+ started := make(chan struct{})
+ release := make(chan struct{})
+ h.media.started = started
+ h.media.release = release
+ msg := p2pMessage(t)
+
+ handled := make(chan error, 1)
+ go func() {
+ handled <- h.router.Handle(context.Background(), msg)
+ }()
+
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("media resolver did not start")
+ }
+ select {
+ case err := <-handled:
+ if err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ case <-time.After(100 * time.Millisecond):
+ t.Fatal("Handle waited for media resolution on the connector ACK path")
+ }
+ if !h.tasks.wasCalled() {
+ t.Fatal("durable run trigger was not scheduled while media resolution was pending")
+ }
+
+ close(release)
+ if !waitFor(time.Second, func() bool { return h.tasks.promotionCalls() == 1 }) {
+ t.Fatal("media completion did not promote the durable deferred run")
+ }
+}
+
+func TestRouter_MediaQueuePreservesSessionOrderWithoutCancellingRunBoundary(t *testing.T) {
+ h := newHarness(t)
+ timers := &fakeTimerFactory{}
+ h.router.batcher = newTestBatcher(timers)
+ secondStarted := make(chan struct{})
+ releaseSecond := make(chan struct{})
+ h.media.resolve = func(ctx context.Context, msg channel.InboundMessage) channel.InboundMessage {
+ if msg.MessageID == "m2" {
+ close(secondStarted)
+ select {
+ case <-releaseSecond:
+ case <-ctx.Done():
+ }
+ }
+ return msg
+ }
+
+ first := p2pMessage(t)
+ first.MessageID = "m1"
+ if err := h.router.Handle(context.Background(), first); err != nil {
+ t.Fatalf("first Handle: %v", err)
+ }
+ if got := h.router.batcher.pendingCount(); got != 1 {
+ t.Fatalf("first message did not arm a run, pending=%d", got)
+ }
+
+ second := p2pMessage(t)
+ second.MessageID = "m2"
+ if err := h.router.Handle(context.Background(), second); err != nil {
+ t.Fatalf("second Handle: %v", err)
+ }
+ select {
+ case <-secondStarted:
+ case <-time.After(time.Second):
+ t.Fatal("second media job did not start")
+ }
+ if got := h.router.batcher.pendingCount(); got != 1 {
+ t.Fatalf("new media must keep one fenced run boundary, pending=%d", got)
+ }
+ timers.fireArmed()
+ if !waitFor(time.Second, func() bool { return h.tasks.calls() == 1 }) {
+ t.Fatal("durable run trigger did not flush while media was pending")
+ }
+
+ close(releaseSecond)
+ if !waitFor(time.Second, func() bool { return h.tasks.promotionCalls() == 2 }) {
+ t.Fatalf("media completion promotions = %d, want 2", h.tasks.promotionCalls())
+ }
}
func TestRouter_ClaimLost_Drops(t *testing.T) {
@@ -434,7 +792,7 @@ func TestRouter_GroupSessionCreatorIsInstaller(t *testing.T) {
t.Fatalf("group session creator must be the installer")
}
// And the run initiator is the sender, not the installer.
- if h.tasks.initiator != h.ident.id.UserID {
+ if !waitFor(time.Second, h.tasks.wasCalled) || h.tasks.initiatorArg() != h.ident.id.UserID {
t.Fatalf("run initiator must be the message sender")
}
}
@@ -455,19 +813,19 @@ func TestRouter_FlushOffline_RepliesAgentOffline(t *testing.T) {
if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
t.Fatalf("unexpected error: %v", err)
}
- // Inline flush (no batcher) emits the offline notice synchronously via replier.
- found := false
- for _, r := range h.replier.calls() {
- if r.Outcome == OutcomeAgentOffline {
- found = true
+ if !waitFor(time.Second, func() bool {
+ for _, r := range h.replier.calls() {
+ if r.Outcome == OutcomeAgentOffline {
+ return true
+ }
}
- }
- if !found {
+ return false
+ }) {
t.Fatalf("agent-no-runtime must emit an AgentOffline reply")
}
// The reaction was added on ingest but no task will run, so the bus-driven
// clear never fires — the flush must clear the typing indicator itself.
- if h.typing.settledCalls() != 1 {
+ if !waitFor(time.Second, func() bool { return h.typing.settledCalls() == 1 }) {
t.Fatalf("offline flush must clear the typing indicator, got %d OnSettled calls", h.typing.settledCalls())
}
}
@@ -478,7 +836,7 @@ func TestRouter_FlushArchived_ClearsTyping(t *testing.T) {
if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
t.Fatalf("unexpected error: %v", err)
}
- if h.typing.settledCalls() != 1 {
+ if !waitFor(time.Second, func() bool { return h.typing.settledCalls() == 1 }) {
t.Fatalf("archived flush must clear the typing indicator, got %d OnSettled calls", h.typing.settledCalls())
}
}
@@ -488,7 +846,7 @@ func TestRouter_FlushSuccess_DoesNotClearTyping(t *testing.T) {
if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
t.Fatalf("unexpected error: %v", err)
}
- if !h.tasks.wasCalled() {
+ if !waitFor(time.Second, h.tasks.wasCalled) {
t.Fatalf("a healthy session must enqueue a task")
}
// A successfully enqueued task is cleared by the platform's bus-driven
@@ -505,7 +863,7 @@ func TestRouter_ForceFresh_Propagates(t *testing.T) {
if err := h.router.Handle(context.Background(), msg); err != nil {
t.Fatalf("unexpected error: %v", err)
}
- if !h.tasks.freshArg() {
+ if !waitFor(time.Second, h.tasks.wasCalled) || !h.tasks.freshArg() {
t.Fatalf("ForceFresh must propagate to EnqueueChatTask")
}
}
@@ -517,7 +875,7 @@ func TestRouter_DrainJoinsReplies(t *testing.T) {
t.Fatalf("unexpected error: %v", err)
}
done := make(chan struct{})
- go func() { h.router.Drain(); close(done) }()
+ go func() { h.router.Drain(context.Background()); close(done) }()
select {
case <-done:
case <-time.After(2 * time.Second):
@@ -528,6 +886,83 @@ func TestRouter_DrainJoinsReplies(t *testing.T) {
}
}
+func TestRouter_MediaConcurrencyCapAppliesAcrossSessions(t *testing.T) {
+ h := newHarness(t)
+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{MediaConcurrency: 1, Logger: discardLogger()})
+ release := make(chan struct{})
+ h.media.resolve = func(ctx context.Context, msg channel.InboundMessage) channel.InboundMessage {
+ select {
+ case <-release:
+ case <-ctx.Done():
+ }
+ return msg
+ }
+ h.router.Register(channel.TypeFeishu, ResolverSet{
+ Installation: h.inst,
+ Identity: h.ident,
+ Dedup: h.dedup,
+ Session: h.binder,
+ Audit: h.audit,
+ Replier: h.replier,
+ Typing: h.typing,
+ Media: h.media,
+ OriginType: "lark_chat",
+ })
+
+ first := p2pMessage(t)
+ first.MessageID = "m1"
+ if err := h.router.Handle(context.Background(), first); err != nil {
+ t.Fatalf("first Handle: %v", err)
+ }
+ if !waitFor(time.Second, func() bool { return h.media.calls() == 1 }) {
+ t.Fatalf("first media job did not start, calls=%d", h.media.calls())
+ }
+
+ // A different session gets its own queue; only the global cap gates it.
+ h.binder.ensureID = uuidFromString(t, "77777777-7777-4777-8777-777777777777")
+ second := p2pMessage(t)
+ second.MessageID = "m2"
+ second.Source.ChatID = "oc_chat_b"
+ if err := h.router.Handle(context.Background(), second); err != nil {
+ t.Fatalf("second Handle: %v", err)
+ }
+ if waitFor(150*time.Millisecond, func() bool { return h.media.calls() == 2 }) {
+ t.Fatal("second media job ran while the only concurrency slot was held")
+ }
+
+ close(release)
+ if !waitFor(time.Second, func() bool { return h.media.calls() == 2 }) {
+ t.Fatalf("second media job never ran after the slot freed, calls=%d", h.media.calls())
+ }
+}
+
+func TestRouter_DrainHonorsDeadlineWhenMediaResolverIgnoresCancellation(t *testing.T) {
+ h := newHarness(t)
+ release := make(chan struct{})
+ started := make(chan struct{})
+ h.media.resolve = func(_ context.Context, msg channel.InboundMessage) channel.InboundMessage {
+ close(started)
+ <-release
+ return msg
+ }
+
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ select {
+ case <-started:
+ case <-time.After(time.Second):
+ t.Fatal("media resolver did not start")
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
+ defer cancel()
+ if h.router.Drain(ctx) {
+ t.Fatal("Drain reported completion for a wedged media resolver")
+ }
+ close(release)
+}
+
func TestRouter_EmptyMessageID_SkipsDedup(t *testing.T) {
h := newHarness(t)
msg := p2pMessage(t)
@@ -538,7 +973,115 @@ func TestRouter_EmptyMessageID_SkipsDedup(t *testing.T) {
if h.dedup.claimCalls != 0 {
t.Fatalf("empty message id must skip the dedup claim, got %d", h.dedup.claimCalls)
}
- if !h.tasks.wasCalled() {
+ if !waitFor(time.Second, h.tasks.wasCalled) {
t.Fatalf("message must still ingest without a dedup key")
}
}
+
+// A media job whose budget expires while it is still QUEUED (waiting for the
+// global slot) must not wait for the front of the line: it finalizes the
+// placeholder (marker clear + promotion) immediately, without ever invoking
+// the resolver, while the slot holder keeps running.
+func TestRouter_MediaQueueWaitExpiryFinalizesWithoutResolving(t *testing.T) {
+ h := newHarness(t)
+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{MediaConcurrency: 1, MediaTimeout: 150 * time.Millisecond, Logger: discardLogger()})
+ release := make(chan struct{})
+ firstStarted := make(chan struct{})
+ h.media.resolve = func(_ context.Context, msg channel.InboundMessage) channel.InboundMessage {
+ if msg.MessageID == "m1" {
+ close(firstStarted)
+ // Deliberately ignores ctx: the slot must stay held past m2's
+ // expiry so m2 deterministically expires while QUEUED.
+ <-release
+ }
+ return msg
+ }
+ h.router.Register(channel.TypeFeishu, ResolverSet{
+ Installation: h.inst,
+ Identity: h.ident,
+ Dedup: h.dedup,
+ Session: h.binder,
+ Audit: h.audit,
+ Replier: h.replier,
+ Typing: h.typing,
+ Media: h.media,
+ OriginType: "lark_chat",
+ })
+
+ first := p2pMessage(t)
+ first.MessageID = "m1"
+ if err := h.router.Handle(context.Background(), first); err != nil {
+ t.Fatalf("first Handle: %v", err)
+ }
+ select {
+ case <-firstStarted:
+ case <-time.After(time.Second):
+ t.Fatal("first media job did not start")
+ }
+
+ // Second job (another session) queues behind the only slot and expires
+ // there; it must finalize while the slot is still held.
+ h.binder.ensureID = uuidFromString(t, "77777777-7777-4777-8777-777777777777")
+ second := p2pMessage(t)
+ second.MessageID = "m2"
+ second.Source.ChatID = "oc_chat_b"
+ if err := h.router.Handle(context.Background(), second); err != nil {
+ t.Fatalf("second Handle: %v", err)
+ }
+ if !waitFor(2*time.Second, func() bool { return h.tasks.promotionCalls() >= 1 }) {
+ t.Fatal("expired queued job did not finalize while the slot was held")
+ }
+ if h.media.calls() != 1 {
+ t.Fatalf("expired job must not invoke the resolver, calls=%d", h.media.calls())
+ }
+ close(release)
+ if !waitFor(2*time.Second, func() bool { return h.tasks.promotionCalls() == 2 }) {
+ t.Fatalf("slot holder promotion missing, promotions=%d", h.tasks.promotionCalls())
+ }
+}
+
+// The local resolve budget must start BEFORE the append transaction: the DB
+// anchors the durable fallback at insert-time now(), so a budget started
+// post-commit would outlive the fallback by the append latency and let the
+// task fire while the resolver still runs. With a slow append, the resolver's
+// context deadline must still be measured from the pre-append instant.
+func TestRouter_MediaDeadlineStartsBeforeAppend(t *testing.T) {
+ h := newHarness(t)
+ const timeout = 300 * time.Millisecond
+ const appendLatency = 150 * time.Millisecond
+ h.router = NewRouter(h.issues, h.tasks, h.reader, RouterConfig{MediaTimeout: timeout, Logger: discardLogger()})
+ h.binder.appendDelay = appendLatency
+ deadlines := make(chan time.Time, 1)
+ h.media.resolve = func(ctx context.Context, msg channel.InboundMessage) channel.InboundMessage {
+ if d, ok := ctx.Deadline(); ok {
+ deadlines <- d
+ }
+ return msg
+ }
+ h.router.Register(channel.TypeFeishu, ResolverSet{
+ Installation: h.inst,
+ Identity: h.ident,
+ Dedup: h.dedup,
+ Session: h.binder,
+ Audit: h.audit,
+ Replier: h.replier,
+ Typing: h.typing,
+ Media: h.media,
+ OriginType: "lark_chat",
+ })
+
+ start := time.Now()
+ if err := h.router.Handle(context.Background(), p2pMessage(t)); err != nil {
+ t.Fatalf("Handle: %v", err)
+ }
+ select {
+ case d := <-deadlines:
+ // Started pre-append: deadline ≈ start+timeout. Started post-append it
+ // would be ≥ start+appendLatency+timeout; the midpoint separates them.
+ if limit := start.Add(timeout + appendLatency/2); d.After(limit) {
+ t.Fatalf("resolve deadline %v exceeds %v — local budget started after the append", d.Sub(start), timeout+appendLatency/2)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatal("resolver did not run")
+ }
+}
diff --git a/server/internal/integrations/channel/engine/session.go b/server/internal/integrations/channel/engine/session.go
index cba3e0a835..565b5f7016 100644
--- a/server/internal/integrations/channel/engine/session.go
+++ b/server/internal/integrations/channel/engine/session.go
@@ -4,7 +4,9 @@ import (
"context"
"errors"
"fmt"
+ "log/slog"
+ "github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
@@ -42,6 +44,10 @@ type SessionQueries interface {
CreateChatSession(ctx context.Context, arg db.CreateChatSessionParams) (db.ChatSession, error)
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
+ 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)
TouchChatSession(ctx context.Context, id pgtype.UUID) error
GetMostRecentUserChatMessage(ctx context.Context, chatSessionID pgtype.UUID) (db.ChatMessage, error)
UpdateChannelChatSessionBindingReplyTarget(ctx context.Context, arg db.UpdateChannelChatSessionBindingReplyTargetParams) error
@@ -71,6 +77,18 @@ func (a dbSessionQueries) CreateChannelChatSessionBinding(ctx context.Context, a
func (a dbSessionQueries) CreateChatMessage(ctx context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error) {
return a.q.CreateChatMessage(ctx, arg)
}
+func (a dbSessionQueries) ClearChatMessageChannelMediaPending(ctx context.Context, arg db.ClearChatMessageChannelMediaPendingParams) error {
+ return a.q.ClearChatMessageChannelMediaPending(ctx, arg)
+}
+func (a dbSessionQueries) CreateAttachment(ctx context.Context, arg db.CreateAttachmentParams) (db.Attachment, error) {
+ return a.q.CreateAttachment(ctx, arg)
+}
+func (a dbSessionQueries) LinkAttachmentsToChatMessage(ctx context.Context, arg db.LinkAttachmentsToChatMessageParams) ([]pgtype.UUID, error) {
+ return a.q.LinkAttachmentsToChatMessage(ctx, arg)
+}
+func (a dbSessionQueries) ClaimChannelMediaPendingObjectsForBind(ctx context.Context, arg db.ClaimChannelMediaPendingObjectsForBindParams) ([]string, error) {
+ return a.q.ClaimChannelMediaPendingObjectsForBind(ctx, arg)
+}
func (a dbSessionQueries) TouchChatSession(ctx context.Context, id pgtype.UUID) error {
return a.q.TouchChatSession(ctx, id)
}
@@ -241,21 +259,34 @@ func (s *ChatSession) createSessionAndBinding(ctx context.Context, in EnsureSess
// its own binding row, recording the real thread here per session does not clash
// across sibling threads.
type AppendInput struct {
- SessionID pgtype.UUID
- Sender pgtype.UUID
- InstallationID pgtype.UUID
- Body string
- CommandText string
- MessageID string
- ThreadID string
- ClaimToken pgtype.UUID
+ SessionID pgtype.UUID
+ Sender pgtype.UUID
+ InstallationID pgtype.UUID
+ Body string
+ CommandText string
+ MessageID string
+ ThreadID string
+ ClaimToken pgtype.UUID
+ 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.
+type BindMediaInput struct {
+ MessageID pgtype.UUID
+ SessionID pgtype.UUID
+ WorkspaceID pgtype.UUID
+ Sender pgtype.UUID
+ MediaRefs []channel.MediaRef
}
// AppendUserMessage writes the user message into the chat_session (touching it
// and recording the reply target), runs the in-tx dedup Mark when a claim token
-// is supplied, and returns the parsed `/issue` command when present. Returns
-// ErrClaimLost when a concurrent reclaim rotated the dedup token mid-flight, in
-// which case the whole transaction rolls back (no chat_message lands).
+// is supplied, and returns the durable message id plus the parsed `/issue`
+// command when present. Returns ErrClaimLost when a concurrent reclaim rotated
+// the dedup token mid-flight, in which case the whole transaction rolls back
+// (no chat_message lands).
func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (AppendResult, error) {
tx, err := s.tx.Begin(ctx)
if err != nil {
@@ -280,11 +311,17 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
}
}
- if _, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
- ChatSessionID: in.SessionID,
- Role: "user",
- Content: in.Body,
- }); err != nil {
+ // channel_ingested is the immutable provenance the cancel path gates on:
+ // it must be stamped in the same transaction as the message so no later
+ // binding deletion (archive, installation rebind) can strip it.
+ msg, err := qtx.CreateChatMessage(ctx, db.CreateChatMessageParams{
+ ChatSessionID: in.SessionID,
+ Role: "user",
+ Content: in.Body,
+ ChannelMediaPendingSecs: pgtype.Float8{Float64: in.MediaPendingSeconds, Valid: in.MediaPendingSeconds > 0},
+ ChannelIngested: pgtype.Bool{Bool: true, Valid: true},
+ })
+ if err != nil {
return AppendResult{}, fmt.Errorf("create chat message: %w", err)
}
if err := qtx.TouchChatSession(ctx, in.SessionID); err != nil {
@@ -324,7 +361,161 @@ func (s *ChatSession) AppendUserMessage(ctx context.Context, in AppendInput) (Ap
if err := tx.Commit(ctx); err != nil {
return AppendResult{}, fmt.Errorf("commit: %w", err)
}
- return AppendResult{IssueCommand: cmd, DedupMarked: markedInTx}, nil
+ return 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.
+func (s *ChatSession) BindMediaRefs(ctx context.Context, in BindMediaInput) error {
+ tx, err := s.tx.Begin(ctx)
+ if err != nil {
+ return fmt.Errorf("begin media tx: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := s.q.WithTx(tx)
+ if len(in.MediaRefs) > 0 {
+ if err := s.bindMediaRefs(ctx, qtx, in); err != nil {
+ _ = tx.Rollback(ctx)
+ if clearErr := s.clearMediaPending(ctx, s.q, in); clearErr != nil {
+ return errors.Join(err, clearErr)
+ }
+ return err
+ }
+ }
+ if err := s.clearMediaPending(ctx, qtx, in); err != nil {
+ return err
+ }
+ if err := tx.Commit(ctx); err != nil {
+ // An ambiguous commit needs no adjudication: the intent-ledger rows
+ // were deleted in this same transaction, so commit landed ⇔ intents
+ // gone, atomically. Either way the reconciler settles the objects.
+ return fmt.Errorf("commit media: %w", err)
+ }
+ return nil
+}
+
+func (s *ChatSession) clearMediaPending(ctx context.Context, q SessionQueries, in BindMediaInput) error {
+ if err := q.ClearChatMessageChannelMediaPending(ctx, db.ClearChatMessageChannelMediaPendingParams{
+ ID: in.MessageID,
+ ChatSessionID: in.SessionID,
+ }); err != nil {
+ return fmt.Errorf("clear chat message media pending: %w", err)
+ }
+ return nil
+}
+
+func (s *ChatSession) bindMediaRefs(ctx context.Context, qtx SessionQueries, in BindMediaInput) error {
+ if !in.WorkspaceID.Valid {
+ return errors.New("bind media refs: workspace_id is required")
+ }
+ if !in.MessageID.Valid {
+ return errors.New("bind media refs: message_id is required")
+ }
+ keys := make([]string, 0, len(in.MediaRefs))
+ for _, ref := range in.MediaRefs {
+ if ref.StorageURL == "" {
+ return errors.New("bind media refs: storage_url is required")
+ }
+ if ref.StorageKey == "" {
+ return errors.New("bind media refs: storage_key is required")
+ }
+ keys = append(keys, ref.StorageKey)
+ }
+ // 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
+ // returned and its ref must NOT attach — the object is being deleted and
+ // the placeholder stays.
+ claimedKeys, err := qtx.ClaimChannelMediaPendingObjectsForBind(ctx, db.ClaimChannelMediaPendingObjectsForBindParams{
+ StorageKeys: keys,
+ WorkspaceID: in.WorkspaceID,
+ })
+ if err != nil {
+ return fmt.Errorf("claim media intents: %w", err)
+ }
+ claimed := make(map[string]bool, len(claimedKeys))
+ for _, k := range claimedKeys {
+ claimed[k] = true
+ }
+ ids := make([]pgtype.UUID, 0, len(in.MediaRefs))
+ for _, ref := range in.MediaRefs {
+ if !claimed[ref.StorageKey] {
+ slog.Warn("channel media: intent claimed by reconciler; skipping attach",
+ "storage_key", ref.StorageKey)
+ continue
+ }
+ id, err := uuid.NewV7()
+ if err != nil {
+ return fmt.Errorf("create attachment id: %w", err)
+ }
+ contentType := ref.MimeType
+ if contentType == "" {
+ contentType = "application/octet-stream"
+ }
+ filename := ref.Filename
+ if filename == "" {
+ filename = defaultMediaFilename(ref.Type, id.String(), contentType)
+ }
+ att, err := qtx.CreateAttachment(ctx, db.CreateAttachmentParams{
+ ID: pgtype.UUID{Bytes: id, Valid: true},
+ WorkspaceID: in.WorkspaceID,
+ ChatSessionID: in.SessionID,
+ UploaderType: "member",
+ UploaderID: in.Sender,
+ Filename: filename,
+ Url: ref.StorageURL,
+ ContentType: contentType,
+ SizeBytes: ref.SizeBytes,
+ })
+ if err != nil {
+ return fmt.Errorf("create chat attachment: %w", err)
+ }
+ ids = append(ids, att.ID)
+ }
+ if len(ids) == 0 {
+ return nil
+ }
+ if _, err := qtx.LinkAttachmentsToChatMessage(ctx, db.LinkAttachmentsToChatMessageParams{
+ ChatMessageID: in.MessageID,
+ ChatSessionID: in.SessionID,
+ WorkspaceID: in.WorkspaceID,
+ UploaderType: "member",
+ UploaderID: in.Sender,
+ AttachmentIds: ids,
+ }); err != nil {
+ return fmt.Errorf("link chat attachments: %w", err)
+ }
+ return nil
+}
+
+func defaultMediaFilename(kind channel.MsgType, id, contentType string) string {
+ prefix := "attachment"
+ switch kind {
+ case channel.MsgTypeImage:
+ prefix = "image"
+ case channel.MsgTypeVideo:
+ prefix = "video"
+ case channel.MsgTypeAudio:
+ prefix = "audio"
+ case channel.MsgTypeFile:
+ prefix = "file"
+ }
+ ext := ""
+ switch contentType {
+ case "image/jpeg":
+ ext = ".jpg"
+ case "image/png":
+ ext = ".png"
+ case "image/gif":
+ ext = ".gif"
+ case "image/webp":
+ ext = ".webp"
+ case "video/mp4":
+ ext = ".mp4"
+ }
+ return prefix + "-" + id + ext
}
func isUniqueViolation(err error) bool {
diff --git a/server/internal/integrations/channel/engine/session_db_test.go b/server/internal/integrations/channel/engine/session_db_test.go
new file mode 100644
index 0000000000..1b6018d4a0
--- /dev/null
+++ b/server/internal/integrations/channel/engine/session_db_test.go
@@ -0,0 +1,525 @@
+package engine
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "os"
+ "strings"
+ "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/integrations/channel"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+func sessionPersistenceTestDB(t *testing.T) *pgxpool.Pool {
+ t.Helper()
+ dsn := os.Getenv("DATABASE_URL")
+ if dsn == "" {
+ dsn = "postgres://multica:multica@localhost:5432/multica?sslmode=disable"
+ }
+ ctx := context.Background()
+ pool, err := pgxpool.New(ctx, dsn)
+ if err != nil {
+ t.Skipf("no database: %v", err)
+ }
+ if err := pool.Ping(ctx); err != nil {
+ pool.Close()
+ t.Skipf("database not reachable: %v", err)
+ }
+ var migrated bool
+ if err := pool.QueryRow(ctx, `SELECT to_regclass('public.attachment') IS NOT NULL`).Scan(&migrated); err != nil || !migrated {
+ pool.Close()
+ t.Skip("attachment table not present (database not migrated)")
+ }
+ t.Cleanup(pool.Close)
+ return pool
+}
+
+type sessionPersistenceFixture struct {
+ workspaceID pgtype.UUID
+ userID pgtype.UUID
+ sessionID pgtype.UUID
+}
+
+func seedSessionPersistenceFixture(t *testing.T, pool *pgxpool.Pool) sessionPersistenceFixture {
+ t.Helper()
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ var f sessionPersistenceFixture
+ var runtimeID, agentID pgtype.UUID
+
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
+ "Channel media test", fmt.Sprintf("channel-media-%[email protected]", suffix)).Scan(&f.userID); err != nil {
+ t.Fatalf("create user: %v", err)
+ }
+ t.Cleanup(func() {
+ cleanupCtx := context.Background()
+ if f.workspaceID.Valid {
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_media_pending_object WHERE workspace_id = $1`, f.workspaceID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM workspace WHERE id = $1`, f.workspaceID)
+ }
+ if f.userID.Valid {
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM "user" WHERE id = $1`, f.userID)
+ }
+ })
+ if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug, description) VALUES ($1, $2, '') RETURNING id`,
+ "Channel media test", fmt.Sprintf("channel-media-%d", suffix)).Scan(&f.workspaceID); err != nil {
+ t.Fatalf("create workspace: %v", err)
+ }
+ if _, err := pool.Exec(ctx, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`, f.workspaceID, f.userID); err != nil {
+ t.Fatalf("create member: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, owner_id)
+ VALUES ($1, $2, 'local', 'multica_daemon', $3)
+ RETURNING id`, f.workspaceID, fmt.Sprintf("channel-media-runtime-%d", suffix), f.userID).Scan(&runtimeID); err != nil {
+ t.Fatalf("create runtime: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent (workspace_id, name, runtime_mode, runtime_id, owner_id)
+ VALUES ($1, $2, 'local', $3, $4)
+ RETURNING id`, f.workspaceID, fmt.Sprintf("channel-media-agent-%d", suffix), runtimeID, f.userID).Scan(&agentID); err != nil {
+ t.Fatalf("create agent: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)
+ VALUES ($1, $2, $3, 'Channel media test')
+ RETURNING id`, f.workspaceID, agentID, f.userID).Scan(&f.sessionID); err != nil {
+ t.Fatalf("create chat session: %v", err)
+ }
+
+ return f
+}
+
+func TestBindMediaRefs_PersistsAndLinksAttachmentToDurableMessage(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ session := NewChatSession(db.New(pool), pool, channel.TypeFeishu, SessionTitles{})
+
+ appendRes, err := session.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: fixture.sessionID,
+ Sender: fixture.userID,
+ Body: "[Image]",
+ MediaPendingSeconds: 60,
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ seedPendingMediaObject(t, pool, fixture, appendRes.MessageID, "workspaces/ws/lark/image", "https://cdn.example.test/image", "pending")
+ err = session.BindMediaRefs(context.Background(), BindMediaInput{
+ MessageID: appendRes.MessageID,
+ SessionID: fixture.sessionID,
+ WorkspaceID: fixture.workspaceID,
+ Sender: fixture.userID,
+ MediaRefs: []channel.MediaRef{{
+ Type: channel.MsgTypeImage,
+ StorageKey: "workspaces/ws/lark/image",
+ StorageURL: "https://cdn.example.test/image",
+ Filename: "image.png",
+ MimeType: "image/png",
+ SizeBytes: 3,
+ }},
+ })
+ if err != nil {
+ t.Fatalf("BindMediaRefs: %v", err)
+ }
+ if _, exists := pendingMediaObjectState(t, pool, "workspaces/ws/lark/image"); exists {
+ t.Fatal("happy-path bind must clear the intent row in the same transaction")
+ }
+
+ var content, filename, url, contentType string
+ var mediaPendingUntil pgtype.Timestamptz
+ var sizeBytes int64
+ var channelIngested bool
+ if err := pool.QueryRow(context.Background(), `
+ SELECT m.content, a.filename, a.url, a.content_type, a.size_bytes, m.channel_media_pending_until, m.channel_ingested
+ FROM chat_message m
+ JOIN attachment a ON a.chat_message_id = m.id
+ WHERE m.chat_session_id = $1 AND a.chat_session_id = $1`, fixture.sessionID).
+ Scan(&content, &filename, &url, &contentType, &sizeBytes, &mediaPendingUntil, &channelIngested); err != nil {
+ t.Fatalf("load linked attachment: %v", err)
+ }
+ if content != "[Image]" || filename != "image.png" || url != "https://cdn.example.test/image" || contentType != "image/png" || sizeBytes != 3 {
+ t.Fatalf("persisted media mismatch: content=%q filename=%q url=%q content_type=%q size=%d", content, filename, url, contentType, sizeBytes)
+ }
+ if mediaPendingUntil.Valid {
+ t.Fatalf("media pending deadline was not cleared: %v", mediaPendingUntil.Time)
+ }
+ if !channelIngested {
+ t.Fatal("channel append must stamp channel_ingested for the cancel-path provenance gate")
+ }
+}
+
+type failingLinkSessionQueries struct {
+ SessionQueries
+}
+
+func (q failingLinkSessionQueries) WithTx(tx pgx.Tx) SessionQueries {
+ return failingLinkSessionQueries{SessionQueries: q.SessionQueries.WithTx(tx)}
+}
+
+func (failingLinkSessionQueries) LinkAttachmentsToChatMessage(context.Context, db.LinkAttachmentsToChatMessageParams) ([]pgtype.UUID, error) {
+ return nil, errors.New("injected attachment link failure")
+}
+
+func TestBindMediaRefs_LinkFailureKeepsMessageAndRollsBackAttachment(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ queries := failingLinkSessionQueries{SessionQueries: dbSessionQueries{q: db.New(pool)}}
+ session := newChatSessionWith(queries, pool, channel.TypeFeishu, SessionTitles{})
+
+ appendRes, err := session.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: fixture.sessionID,
+ Sender: fixture.userID,
+ Body: "rollback-media",
+ MediaPendingSeconds: 60,
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ seedPendingMediaObject(t, pool, fixture, appendRes.MessageID, "workspaces/ws/lark/rollback", "https://cdn.example.test/rollback.png", "pending")
+ err = session.BindMediaRefs(context.Background(), BindMediaInput{
+ MessageID: appendRes.MessageID,
+ SessionID: fixture.sessionID,
+ WorkspaceID: fixture.workspaceID,
+ Sender: fixture.userID,
+ MediaRefs: []channel.MediaRef{{
+ Type: channel.MsgTypeImage,
+ StorageKey: "workspaces/ws/lark/rollback",
+ StorageURL: "https://cdn.example.test/rollback.png",
+ Filename: "rollback.png",
+ MimeType: "image/png",
+ SizeBytes: 4,
+ }},
+ })
+ if err == nil || !strings.Contains(err.Error(), "injected attachment link failure") {
+ t.Fatalf("BindMediaRefs error = %v", err)
+ }
+ if state, exists := pendingMediaObjectState(t, pool, "workspaces/ws/lark/rollback"); !exists || state != "pending" {
+ t.Fatalf("intent row = (%q, %v), want preserved 'pending' after the rollback", state, exists)
+ }
+
+ var messageCount, attachmentCount int
+ var mediaPendingUntil pgtype.Timestamptz
+ ctx := context.Background()
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM chat_message WHERE chat_session_id = $1 AND content = 'rollback-media'`, fixture.sessionID).Scan(&messageCount); err != nil {
+ t.Fatalf("count messages: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `SELECT count(*) FROM attachment WHERE chat_session_id = $1 AND filename = 'rollback.png'`, fixture.sessionID).Scan(&attachmentCount); err != nil {
+ t.Fatalf("count attachments: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `SELECT channel_media_pending_until FROM chat_message WHERE id = $1`, appendRes.MessageID).Scan(&mediaPendingUntil); err != nil {
+ t.Fatalf("load fallback marker: %v", err)
+ }
+ if messageCount != 1 || attachmentCount != 0 {
+ t.Fatalf("fallback persistence mismatch: messages=%d attachments=%d", messageCount, attachmentCount)
+ }
+ if mediaPendingUntil.Valid {
+ t.Fatalf("failed attachment kept media pending until %v", mediaPendingUntil.Time)
+ }
+}
+
+// seedPendingMediaObject writes the intent-ledger row the resolver would have
+// written before the upload. state defaults to 'pending'.
+func seedPendingMediaObject(t *testing.T, pool *pgxpool.Pool, fixture sessionPersistenceFixture, messageID pgtype.UUID, key, url, state string) {
+ t.Helper()
+ if _, err := pool.Exec(context.Background(), `
+ INSERT INTO channel_media_pending_object (storage_key, workspace_id, chat_message_id, storage_url, state)
+ VALUES ($1, $2, $3, $4, $5)
+ ON CONFLICT (storage_key) DO UPDATE SET state = EXCLUDED.state, chat_message_id = EXCLUDED.chat_message_id, storage_url = EXCLUDED.storage_url
+ `, key, fixture.workspaceID, messageID, url, state); err != nil {
+ t.Fatalf("seed pending media object: %v", err)
+ }
+}
+
+func pendingMediaObjectState(t *testing.T, pool *pgxpool.Pool, key string) (string, bool) {
+ t.Helper()
+ var state string
+ err := pool.QueryRow(context.Background(), `
+ SELECT state FROM channel_media_pending_object WHERE storage_key = $1
+ `, key).Scan(&state)
+ if err != nil {
+ if strings.Contains(err.Error(), "no rows") {
+ return "", false
+ }
+ t.Fatalf("load pending media object: %v", err)
+ }
+ return state, true
+}
+
+// lostAckTxStarter simulates a lost commit ack: the transaction durably
+// commits, but the client is handed an error — the result-uncertain window
+// the compensation protocol must not treat as "nothing landed".
+type lostAckTxStarter struct{ pool *pgxpool.Pool }
+
+func (s *lostAckTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &lostAckTx{Tx: tx}, nil
+}
+
+type lostAckTx struct{ pgx.Tx }
+
+func (t *lostAckTx) Commit(ctx context.Context) error {
+ if err := t.Tx.Commit(ctx); err != nil {
+ return err
+ }
+ return errors.New("injected lost commit ack")
+}
+
+// rolledBackCommitTxStarter simulates a commit failure whose rollback is
+// definite: nothing landed, so the caller may safely reclaim the uploads.
+type rolledBackCommitTxStarter struct{ pool *pgxpool.Pool }
+
+func (s *rolledBackCommitTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &rolledBackCommitTx{Tx: tx}, nil
+}
+
+type rolledBackCommitTx struct{ pgx.Tx }
+
+func (t *rolledBackCommitTx) Commit(ctx context.Context) error {
+ _ = t.Tx.Rollback(ctx)
+ return errors.New("injected commit failure")
+}
+
+// bindOneMediaRef appends the user message through a healthy session, seeds
+// the intent-ledger row the resolver would have written before the upload,
+// then binds one ref through bindSession — the seam tests inject commit
+// faults into. Returns the bind error and the storage key used.
+func bindOneMediaRef(t *testing.T, pool *pgxpool.Pool, bindSession *ChatSession, fixture sessionPersistenceFixture, key, url string) error {
+ t.Helper()
+ appendSession := NewChatSession(db.New(pool), pool, channel.TypeFeishu, SessionTitles{})
+ appendRes, err := appendSession.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: fixture.sessionID,
+ Sender: fixture.userID,
+ Body: "[Image]",
+ MediaPendingSeconds: 60,
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ seedPendingMediaObject(t, pool, fixture, appendRes.MessageID, key, url, "pending")
+ return bindSession.BindMediaRefs(context.Background(), BindMediaInput{
+ MessageID: appendRes.MessageID,
+ SessionID: fixture.sessionID,
+ WorkspaceID: fixture.workspaceID,
+ Sender: fixture.userID,
+ MediaRefs: []channel.MediaRef{{
+ Type: channel.MsgTypeImage,
+ StorageKey: key,
+ StorageURL: url,
+ Filename: "ack.png",
+ MimeType: "image/png",
+ SizeBytes: 1,
+ }},
+ })
+}
+
+// A Commit error is not a rollback guarantee — and with the intent rows
+// cleared inside the SAME transaction, nobody has to adjudicate it: when the
+// commit durably landed despite the error report, the attachment exists AND
+// the ledger row is gone, so the reconciler has nothing to delete. The bind
+// still reports the error; the router only logs it.
+func TestBindMediaRefs_LostCommitAckClearsIntentWithAttachment(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ session := newChatSessionWith(dbSessionQueries{q: db.New(pool)}, &lostAckTxStarter{pool: pool}, channel.TypeFeishu, SessionTitles{})
+
+ key := "workspaces/ws/lark/lost-ack"
+ err := bindOneMediaRef(t, pool, session, fixture, key, "https://cdn.example.test/lost-ack.png")
+ if err == nil || !strings.Contains(err.Error(), "injected lost commit ack") {
+ t.Fatalf("lost-ack bind error = %v", err)
+ }
+ var attachments int
+ if err := pool.QueryRow(context.Background(), `
+ SELECT count(*) FROM attachment WHERE chat_session_id = $1 AND url = 'https://cdn.example.test/lost-ack.png'
+ `, fixture.sessionID).Scan(&attachments); err != nil {
+ t.Fatalf("count attachments: %v", err)
+ }
+ if attachments != 1 {
+ t.Fatalf("attachments = %d, want the durably committed row", attachments)
+ }
+ if _, exists := pendingMediaObjectState(t, pool, key); exists {
+ t.Fatal("intent row must be gone when the commit landed — atomic with the attachment")
+ }
+}
+
+// The mirror case: a commit failure whose transaction rolled back leaves the
+// intent row in place (also atomically), so the reconciler reclaims the
+// object after the settle delay. No attachment exists.
+func TestBindMediaRefs_RolledBackCommitKeepsIntentRow(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ session := newChatSessionWith(dbSessionQueries{q: db.New(pool)}, &rolledBackCommitTxStarter{pool: pool}, channel.TypeFeishu, SessionTitles{})
+
+ key := "workspaces/ws/lark/rolled-back"
+ err := bindOneMediaRef(t, pool, session, fixture, key, "https://cdn.example.test/rolled-back.png")
+ if err == nil || !strings.Contains(err.Error(), "injected commit failure") {
+ t.Fatalf("rolled-back commit error = %v", err)
+ }
+ var attachments int
+ if err := pool.QueryRow(context.Background(), `
+ SELECT count(*) FROM attachment WHERE chat_session_id = $1 AND url = 'https://cdn.example.test/rolled-back.png'
+ `, fixture.sessionID).Scan(&attachments); err != nil {
+ t.Fatalf("count attachments: %v", err)
+ }
+ if attachments != 0 {
+ t.Fatalf("attachments = %d, want none after rollback", attachments)
+ }
+ if state, exists := pendingMediaObjectState(t, pool, key); !exists || state != "pending" {
+ t.Fatalf("intent row = (%q, %v), want it preserved in 'pending' for the reconciler", state, exists)
+ }
+}
+
+// Reconciler-wins interleaving: a key already claimed to 'deleting' must not
+// be attached — the object is being deleted, the placeholder stays — and the
+// bind still succeeds for the rest of the batch (here: empty) and clears the
+// media marker.
+func TestBindMediaRefs_ReconcilerOwnedKeySkipsAttach(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ session := NewChatSession(db.New(pool), pool, channel.TypeFeishu, SessionTitles{})
+
+ appendRes, err := session.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: fixture.sessionID,
+ Sender: fixture.userID,
+ Body: "[Image]",
+ MediaPendingSeconds: 60,
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ key := "workspaces/ws/lark/reconciler-owned"
+ seedPendingMediaObject(t, pool, fixture, appendRes.MessageID, key, "https://cdn.example.test/owned.png", "deleting")
+
+ if err := session.BindMediaRefs(context.Background(), BindMediaInput{
+ MessageID: appendRes.MessageID,
+ SessionID: fixture.sessionID,
+ WorkspaceID: fixture.workspaceID,
+ Sender: fixture.userID,
+ MediaRefs: []channel.MediaRef{{
+ Type: channel.MsgTypeImage,
+ StorageKey: key,
+ StorageURL: "https://cdn.example.test/owned.png",
+ Filename: "owned.png",
+ MimeType: "image/png",
+ SizeBytes: 1,
+ }},
+ }); err != nil {
+ t.Fatalf("BindMediaRefs: %v", err)
+ }
+
+ var attachments int
+ if err := pool.QueryRow(context.Background(), `
+ SELECT count(*) FROM attachment WHERE chat_session_id = $1
+ `, fixture.sessionID).Scan(&attachments); err != nil {
+ t.Fatalf("count attachments: %v", err)
+ }
+ if attachments != 0 {
+ t.Fatalf("attachments = %d, want none for a reconciler-owned key", attachments)
+ }
+ if state, exists := pendingMediaObjectState(t, pool, key); !exists || state != "deleting" {
+ t.Fatalf("intent row = (%q, %v), want untouched 'deleting'", state, exists)
+ }
+ var mediaPendingUntil pgtype.Timestamptz
+ if err := pool.QueryRow(context.Background(), `SELECT channel_media_pending_until FROM chat_message WHERE id = $1`, appendRes.MessageID).Scan(&mediaPendingUntil); err != nil {
+ t.Fatalf("load marker: %v", err)
+ }
+ if mediaPendingUntil.Valid {
+ t.Fatalf("media marker must still clear when attach is skipped, got %v", mediaPendingUntil.Time)
+ }
+}
+
+// Tenancy must never trust the key string: a cross-workspace collision on the
+// same storage_key (impossible via the derived key, exactly why it must be
+// enforced in the query) must neither steal the row's ownership nor let the
+// caller believe it holds an intent — RecordPendingMediaObject reports
+// ok=false and the caller skips the upload.
+func TestDBMediaIntentLedger_CrossWorkspaceKeyCannotBeStolen(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ ledger := NewDBMediaIntentLedger(db.New(pool))
+
+ key := "workspaces/ws/lark/cross-tenant"
+ ok, err := ledger.RecordPendingMediaObject(context.Background(), RecordPendingMediaObjectParams{
+ StorageKey: key,
+ WorkspaceID: fixture.workspaceID,
+ ChatMessageID: fixture.sessionID, // any UUID; no FK on the ledger
+ StorageURL: "https://cdn.example.test/cross-a",
+ })
+ if err != nil || !ok {
+ t.Fatalf("first record: ok=%v err=%v", ok, err)
+ }
+
+ var otherWorkspace pgtype.UUID
+ if err := pool.QueryRow(context.Background(), `SELECT gen_random_uuid()`).Scan(&otherWorkspace); err != nil {
+ t.Fatalf("gen other workspace: %v", err)
+ }
+ ok, err = ledger.RecordPendingMediaObject(context.Background(), RecordPendingMediaObjectParams{
+ StorageKey: key,
+ WorkspaceID: otherWorkspace,
+ ChatMessageID: fixture.sessionID,
+ StorageURL: "https://cdn.example.test/cross-b",
+ })
+ if err != nil {
+ t.Fatalf("cross-workspace record: %v", err)
+ }
+ if ok {
+ t.Fatal("cross-workspace upsert must not claim the key")
+ }
+
+ var gotWorkspace pgtype.UUID
+ var gotURL string
+ if err := pool.QueryRow(context.Background(), `
+ SELECT workspace_id, storage_url FROM channel_media_pending_object WHERE storage_key = $1
+ `, key).Scan(&gotWorkspace, &gotURL); err != nil {
+ t.Fatalf("load row: %v", err)
+ }
+ if gotWorkspace != fixture.workspaceID || gotURL != "https://cdn.example.test/cross-a" {
+ t.Fatalf("row ownership changed: workspace=%v url=%q", gotWorkspace, gotURL)
+ }
+}
+
+// The persisted media deadline must come from the DATABASE clock: every
+// consumer compares it against SQL now(), so an application-clock timestamp
+// would let a skewed app node shrink or stretch the fallback window. The
+// budget is passed as a relative duration and anchored server-side.
+func TestAppendUserMessage_MediaDeadlineUsesDatabaseClock(t *testing.T) {
+ pool := sessionPersistenceTestDB(t)
+ fixture := seedSessionPersistenceFixture(t, pool)
+ session := NewChatSession(db.New(pool), pool, channel.TypeFeishu, SessionTitles{})
+
+ appendRes, err := session.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: fixture.sessionID,
+ Sender: fixture.userID,
+ Body: "[Image]",
+ MediaPendingSeconds: 60,
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ var remaining float64
+ if err := pool.QueryRow(context.Background(), `
+ SELECT EXTRACT(EPOCH FROM (channel_media_pending_until - now())) FROM chat_message WHERE id = $1
+ `, appendRes.MessageID).Scan(&remaining); err != nil {
+ t.Fatalf("load deadline: %v", err)
+ }
+ // Anchored to DB now() at insert time: the remaining budget measured by
+ // the SAME clock must be the requested 60s minus round-trip slack — a
+ // window no application clock skew can distort.
+ if remaining < 55 || remaining > 60 {
+ t.Fatalf("deadline remaining = %.2fs (DB clock), want ~60s budget", remaining)
+ }
+}
diff --git a/server/internal/integrations/channel/engine/session_test.go b/server/internal/integrations/channel/engine/session_test.go
index 3b9dd8e565..ec69d872fe 100644
--- a/server/internal/integrations/channel/engine/session_test.go
+++ b/server/internal/integrations/channel/engine/session_test.go
@@ -35,14 +35,20 @@ func (fakeTxStarter) Begin(context.Context) (pgx.Tx, error) { return fakeTx{}, n
// fakeSessionQueries is an in-memory SessionQueries for unit tests.
type fakeSessionQueries struct {
- bindings map[string]pgtype.UUID
- nextSession byte
- createdSessions int
- messages []string
- touched int
- replyTargets int
- lockedWorkspace int // count of LockWorkspaceForChatSessionCreate calls
- lastConfig []byte // config of the most recent CreateChannelChatSessionBinding
+ bindings map[string]pgtype.UUID
+ nextSession byte
+ createdSessions int
+ messages []string
+ messageID pgtype.UUID
+ lastCreate db.CreateChatMessageParams
+ touched int
+ replyTargets int
+ lockedWorkspace int // count of LockWorkspaceForChatSessionCreate calls
+ lastConfig []byte // config of the most recent CreateChannelChatSessionBinding
+ attachments []db.CreateAttachmentParams
+ linked db.LinkAttachmentsToChatMessageParams
+ mediaCleared int
+ reconcilerOwnedKeys map[string]bool
prevMessage *string // GetMostRecentUserChatMessage result; nil → ErrNoRows
markRows int64 // MarkChannelInboundDedupProcessed result
@@ -51,7 +57,7 @@ type fakeSessionQueries struct {
}
func newFake() *fakeSessionQueries {
- return &fakeSessionQueries{bindings: map[string]pgtype.UUID{}, markRows: 1}
+ return &fakeSessionQueries{bindings: map[string]pgtype.UUID{}, markRows: 1, messageID: uid(42)}
}
func bindKey(inst pgtype.UUID, chat string) string { return fmt.Sprintf("%x|%s", inst.Bytes, chat) }
@@ -89,7 +95,36 @@ func (f *fakeSessionQueries) CreateChannelChatSessionBinding(_ context.Context,
func (f *fakeSessionQueries) CreateChatMessage(_ context.Context, arg db.CreateChatMessageParams) (db.ChatMessage, error) {
f.messages = append(f.messages, arg.Content)
- return db.ChatMessage{}, nil
+ f.lastCreate = arg
+ return db.ChatMessage{ID: f.messageID}, nil
+}
+
+func (f *fakeSessionQueries) ClearChatMessageChannelMediaPending(context.Context, db.ClearChatMessageChannelMediaPendingParams) error {
+ f.mediaCleared++
+ return 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
+}
+
+func (f *fakeSessionQueries) LinkAttachmentsToChatMessage(_ context.Context, arg db.LinkAttachmentsToChatMessageParams) ([]pgtype.UUID, error) {
+ f.linked = arg
+ return append([]pgtype.UUID(nil), arg.AttachmentIds...), nil
+}
+
+func (f *fakeSessionQueries) ClaimChannelMediaPendingObjectsForBind(_ context.Context, arg db.ClaimChannelMediaPendingObjectsForBindParams) ([]string, error) {
+ if f.reconcilerOwnedKeys == nil {
+ return append([]string(nil), arg.StorageKeys...), nil
+ }
+ var claimed []string
+ for _, k := range arg.StorageKeys {
+ if !f.reconcilerOwnedKeys[k] {
+ claimed = append(claimed, k)
+ }
+ }
+ return claimed, nil
}
func (f *fakeSessionQueries) TouchChatSession(context.Context, pgtype.UUID) error {
@@ -286,6 +321,65 @@ func TestAppendUserMessage_CommandTextOverridesEnrichedBody(t *testing.T) {
}
}
+func TestBindMediaRefs_CreatesAndLinksChatAttachments(t *testing.T) {
+ f := newFake()
+ s := newTestSession(f)
+ res, err := s.AppendUserMessage(context.Background(), AppendInput{
+ SessionID: uid(1),
+ Sender: uid(7),
+ Body: "[Image]",
+ MessageID: "om_image",
+ })
+ if err != nil {
+ t.Fatalf("AppendUserMessage: %v", err)
+ }
+ if res.IssueCommand != nil {
+ t.Fatalf("media placeholder must not parse as /issue: %+v", res.IssueCommand)
+ }
+ if res.MessageID != f.messageID {
+ t.Fatalf("message id = %v, want %v", res.MessageID, f.messageID)
+ }
+ if !f.lastCreate.ChannelIngested.Valid || !f.lastCreate.ChannelIngested.Bool {
+ t.Fatalf("channel append must stamp channel_ingested, got %+v", f.lastCreate.ChannelIngested)
+ }
+ err = s.BindMediaRefs(context.Background(), BindMediaInput{
+ MessageID: res.MessageID,
+ SessionID: uid(1),
+ WorkspaceID: uid(9),
+ Sender: uid(7),
+ MediaRefs: []channel.MediaRef{
+ {
+ Type: channel.MsgTypeImage,
+ StorageKey: "lark/cli/img.png",
+ StorageURL: "https://cdn.example.test/lark/cli/img.png",
+ Filename: "screenshot.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.WorkspaceID != uid(9) || att.ChatSessionID != uid(1) || att.UploaderType != "member" || att.UploaderID != uid(7) {
+ t.Fatalf("attachment ownership/session wrong: %+v", att)
+ }
+ 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)
+ }
+ if f.linked.ChatMessageID != res.MessageID || f.linked.ChatSessionID != uid(1) || f.linked.WorkspaceID != uid(9) {
+ t.Fatalf("link params wrong: %+v", f.linked)
+ }
+ if len(f.linked.AttachmentIds) != 1 || f.linked.AttachmentIds[0] != att.ID {
+ t.Fatalf("linked ids = %+v, want attachment id %v", f.linked.AttachmentIds, att.ID)
+ }
+}
+
func TestAppendUserMessage_BareIssueUsesPreviousMessage(t *testing.T) {
f := newFake()
prev := "Make the export button work"
diff --git a/server/internal/integrations/channel/message.go b/server/internal/integrations/channel/message.go
index 6b688a6787..ca3f16d344 100644
--- a/server/internal/integrations/channel/message.go
+++ b/server/internal/integrations/channel/message.go
@@ -86,6 +86,10 @@ type MediaRef struct {
Type MsgType
// StorageKey locates the persisted object in Multica object storage.
StorageKey string
+ // StorageURL is the object URL returned by the storage backend and
+ // persisted on the attachment row so the existing attachment download
+ // endpoints can re-open it later.
+ StorageURL string
// Filename is the original display name, when the platform supplies
// one.
Filename string
@@ -129,7 +133,11 @@ type InboundMessage struct {
// itself is in MediaRefs.
Text string
- // MediaRefs are the attachments, already persisted to object storage.
+ // MediaRefs is the OUTPUT channel of engine.MediaResolver.ResolveMedia:
+ // the objects it downloaded and uploaded for this message, each covered
+ // by an intent-ledger row written before its PUT. Inbound messages always
+ // arrive with this empty — adapters must not pre-populate it, because
+ // binding only attaches refs whose ledger intent it can claim.
MediaRefs []MediaRef
// ReplyTo is the quoted/replied-to context, or nil.
diff --git a/server/internal/integrations/lark/client.go b/server/internal/integrations/lark/client.go
index 6b9d6964dd..44419f5300 100644
--- a/server/internal/integrations/lark/client.go
+++ b/server/internal/integrations/lark/client.go
@@ -3,6 +3,7 @@ package lark
import (
"context"
"errors"
+ "io"
"log/slog"
)
@@ -102,6 +103,12 @@ type APIClient interface {
// adapter: flattening and block assembly are the enricher's job.
ListChatMessages(ctx context.Context, creds InstallationCredentials, p ListMessagesParams) ([]LarkMessage, error)
+ // DownloadMessageResource downloads one binary resource attached to a
+ // message via GET /open-apis/im/v1/messages/{message_id}/resources/{file_key}.
+ // Type is the Open Platform resource class ("image" for image_key,
+ // "file" for file_key-backed video/file/audio).
+ DownloadMessageResource(ctx context.Context, creds InstallationCredentials, p DownloadResourceParams) (DownloadedResource, error)
+
// BatchGetUsers resolves a set of user open_ids to their display names
// via GET /open-apis/contact/v3/users/batch. The enricher uses it to
// label recent-context / quoted / forwarded speakers (and the sender
@@ -151,6 +158,26 @@ type ListMessagesParams struct {
EndTime int64
}
+type DownloadResourceParams struct {
+ MessageID string
+ FileKey string
+ Type string
+}
+
+type DownloadedResource struct {
+ Data []byte
+ ContentType string
+ Filename string
+ SizeBytes int64
+}
+
+type DownloadedResourceStream struct {
+ Body io.ReadCloser
+ ContentType string
+ Filename string
+ SizeBytes int64
+}
+
// LarkMessage is the normalized slice of an IM v1 message item the
// enricher needs. Body.content is passed through raw (still the
// JSON-encoded, msg_type-specific string Lark double-encodes) so the
@@ -399,6 +426,11 @@ func (s *stubAPIClient) ListChatMessages(ctx context.Context, creds Installation
return nil, ErrAPIClientNotConfigured
}
+func (s *stubAPIClient) DownloadMessageResource(ctx context.Context, creds InstallationCredentials, p DownloadResourceParams) (DownloadedResource, error) {
+ s.log.Warn("lark stub client: DownloadMessageResource called", "message_id", p.MessageID)
+ return DownloadedResource{}, ErrAPIClientNotConfigured
+}
+
func (s *stubAPIClient) BatchGetUsers(ctx context.Context, creds InstallationCredentials, openIDs []string) (map[string]string, error) {
s.log.Warn("lark stub client: BatchGetUsers called", "count", len(openIDs))
return nil, ErrAPIClientNotConfigured
diff --git a/server/internal/integrations/lark/content_flatten.go b/server/internal/integrations/lark/content_flatten.go
index 85e1c6dab4..30ceb14ac0 100644
--- a/server/internal/integrations/lark/content_flatten.go
+++ b/server/internal/integrations/lark/content_flatten.go
@@ -21,12 +21,13 @@ import (
// knows which one applies — so flattening stays mention-agnostic.
//
// Non-text media types render as a stable bracketed placeholder so the
-// agent sees that *something* was attached without us downloading the
-// binary. Attachment ingestion is explicitly out of scope (tracked as a
-// separate attachment-pipeline issue), and merge_forward is intercepted
-// by the enricher before it reaches here (expanding it needs an HTTP
-// round-trip); the inline placeholder is only a fallback for a forward
-// nested inside another forward.
+// agent sees that *something* was attached without this fast path
+// downloading the binary; the detached media resolver separately fetches
+// the resource and binds it as a chat attachment, with the placeholder
+// as the durable fallback. merge_forward is intercepted by the enricher
+// before it reaches here (expanding it needs an HTTP round-trip); the
+// inline placeholder is only a fallback for a forward nested inside
+// another forward.
func flattenContent(msgType, rawContent string) string {
switch msgType {
case "text":
@@ -39,7 +40,7 @@ func flattenContent(msgType, rawContent string) string {
return "[File]"
case "audio":
return "[Audio]"
- case "media":
+ case "media", "video":
return "[Video]"
case "sticker":
return "[Sticker]"
@@ -80,6 +81,11 @@ type larkPostSpan struct {
Href string `json:"href"`
UserID string `json:"user_id"`
UserName string `json:"user_name"`
+ ImageKey string `json:"image_key"`
+ FileKey string `json:"file_key"`
+ FileName string `json:"file_name"`
+ Name string `json:"name"`
+ MimeType string `json:"mime_type"`
}
// flattenPostContent flattens a received `post` body.content into plain
diff --git a/server/internal/integrations/lark/content_flatten_test.go b/server/internal/integrations/lark/content_flatten_test.go
index f20775fdab..0d37d91dc3 100644
--- a/server/internal/integrations/lark/content_flatten_test.go
+++ b/server/internal/integrations/lark/content_flatten_test.go
@@ -83,6 +83,7 @@ func TestFlattenContent_DispatchByType(t *testing.T) {
{"file", "file", `{"file_key":"f"}`, "[File]"},
{"audio", "audio", `{"file_key":"f"}`, "[Audio]"},
{"media", "media", `{"file_key":"f"}`, "[Video]"},
+ {"video", "video", `{"file_key":"f"}`, "[Video]"},
{"sticker", "sticker", `{"file_key":"f"}`, "[Sticker]"},
{"interactive", "interactive", `{"title":"t"}`, "[interactive card]"},
{"share_chat", "share_chat", `{"chat_id":"oc"}`, "[Shared Chat]"},
diff --git a/server/internal/integrations/lark/feishu_channel.go b/server/internal/integrations/lark/feishu_channel.go
index abfb781bed..b56bc8bb08 100644
--- a/server/internal/integrations/lark/feishu_channel.go
+++ b/server/internal/integrations/lark/feishu_channel.go
@@ -98,20 +98,24 @@ func (c *feishuChannel) Capabilities() channel.Capability {
}
func (c *feishuChannel) installationCredentials() (InstallationCredentials, error) {
- if c.creds == nil {
+ return installationCredentialsFor(c.inst, c.creds)
+}
+
+func installationCredentialsFor(inst Installation, resolver CredentialsResolver) (InstallationCredentials, error) {
+ if resolver == nil {
return InstallationCredentials{}, errors.New("lark: credentials resolver missing")
}
- secret, err := c.creds.DecryptAppSecret(c.inst)
+ secret, err := resolver.DecryptAppSecret(inst)
if err != nil {
return InstallationCredentials{}, fmt.Errorf("decrypt app_secret: %w", err)
}
creds := InstallationCredentials{
- AppID: c.inst.AppID,
+ AppID: inst.AppID,
AppSecret: secret,
- Region: RegionOrDefault(c.inst.Region),
+ Region: RegionOrDefault(inst.Region),
}
- if c.inst.TenantKey.Valid {
- creds.TenantKey = c.inst.TenantKey.String
+ if inst.TenantKey.Valid {
+ creds.TenantKey = inst.TenantKey.String
}
return creds, nil
}
diff --git a/server/internal/integrations/lark/feishu_channel_test.go b/server/internal/integrations/lark/feishu_channel_test.go
index 6bb1317ad5..f3b5942816 100644
--- a/server/internal/integrations/lark/feishu_channel_test.go
+++ b/server/internal/integrations/lark/feishu_channel_test.go
@@ -1,9 +1,13 @@
package lark
import (
+ "bytes"
"context"
"encoding/base64"
"encoding/json"
+ "errors"
+ "io"
+ "strings"
"testing"
"github.com/multica-ai/multica/server/internal/integrations/channel"
@@ -14,8 +18,13 @@ import (
// SendTextMessage — the single method feishuChannel.Send calls.
type fakeSender struct {
APIClient
- last SendTextParams
- msgID string
+ last SendTextParams
+ msgID string
+ downloadCalls []DownloadResourceParams
+ downloaded DownloadedResource
+ downloadErr error
+ downloadedByKey map[string]DownloadedResource
+ downloadErrByKey map[string]error
}
func (f *fakeSender) SendTextMessage(_ context.Context, p SendTextParams) (string, error) {
@@ -23,10 +32,115 @@ func (f *fakeSender) SendTextMessage(_ context.Context, p SendTextParams) (strin
return f.msgID, nil
}
+func (f *fakeSender) DownloadMessageResource(_ context.Context, _ InstallationCredentials, p DownloadResourceParams) (DownloadedResource, error) {
+ return f.download(p)
+}
+
+func (f *fakeSender) DownloadMessageResourceStream(_ context.Context, _ InstallationCredentials, p DownloadResourceParams) (DownloadedResourceStream, error) {
+ got, err := f.download(p)
+ if err != nil {
+ return DownloadedResourceStream{}, err
+ }
+ return DownloadedResourceStream{
+ Body: io.NopCloser(bytes.NewReader(got.Data)),
+ ContentType: got.ContentType,
+ Filename: got.Filename,
+ SizeBytes: got.SizeBytes,
+ }, nil
+}
+
+func (f *fakeSender) download(p DownloadResourceParams) (DownloadedResource, error) {
+ f.downloadCalls = append(f.downloadCalls, p)
+ if err := f.downloadErrByKey[p.FileKey]; err != nil {
+ return DownloadedResource{}, err
+ }
+ if got, ok := f.downloadedByKey[p.FileKey]; ok {
+ return got, nil
+ }
+ return f.downloaded, f.downloadErr
+}
+
+type fakeMediaStorage struct {
+ uploads []fakeMediaUpload
+ deleted []string
+ err error
+}
+
+func (s *fakeMediaStorage) Delete(_ context.Context, key string) {
+ s.deleted = append(s.deleted, key)
+}
+
+func (s *fakeMediaStorage) ObjectURL(key string) string {
+ return "https://cdn.example.test/" + key
+}
+
+type fakeMediaUpload struct {
+ key string
+ data []byte
+ sizeBytes int64
+ streamed bool
+ contentType string
+ filename string
+}
+
+func (s *fakeMediaStorage) Upload(_ context.Context, key string, data []byte, contentType string, filename string) (string, error) {
+ if s.err != nil {
+ return "", s.err
+ }
+ s.uploads = append(s.uploads, fakeMediaUpload{key: key, data: append([]byte(nil), data...), contentType: contentType, filename: filename})
+ return "https://cdn.example.test/" + key, nil
+}
+
+func (s *fakeMediaStorage) UploadStream(_ context.Context, key string, data io.Reader, sizeBytes int64, contentType string, filename string) (string, error) {
+ if s.err != nil {
+ return "", s.err
+ }
+ body, err := io.ReadAll(data)
+ if err != nil {
+ return "", err
+ }
+ s.uploads = append(s.uploads, fakeMediaUpload{key: key, data: body, sizeBytes: sizeBytes, streamed: true, contentType: contentType, filename: filename})
+ return "https://cdn.example.test/" + key, nil
+}
+
+// fakeMediaLedger records intent rows. ownedKeys marks keys the reconciler
+// owns ('deleting'): the resolver must skip them entirely.
+type fakeMediaLedger struct {
+ records []engine.RecordPendingMediaObjectParams
+ ownedKeys map[string]bool
+ ownAll bool
+ err error
+}
+
+func (l *fakeMediaLedger) RecordPendingMediaObject(_ context.Context, p engine.RecordPendingMediaObjectParams) (bool, error) {
+ if l.err != nil {
+ return false, l.err
+ }
+ l.records = append(l.records, p)
+ if l.ownAll || l.ownedKeys[p.StorageKey] {
+ return false, nil
+ }
+ return true, nil
+}
+
+func ownAllKeys(l *fakeMediaLedger) map[string]bool {
+ l.ownAll = true
+ return l.ownedKeys
+}
+
type fakeCreds struct{ secret string }
func (f fakeCreds) DecryptAppSecret(_ Installation) (string, error) { return f.secret, nil }
+func testMediaInstallation(t *testing.T) engine.ResolvedInstallation {
+ t.Helper()
+ return engine.ResolvedInstallation{
+ ID: uuidFromString(t, "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"),
+ WorkspaceID: uuidFromString(t, "11111111-1111-1111-1111-111111111111"),
+ Platform: Installation{AppID: "cli_app", Region: "feishu"},
+ }
+}
+
// feishuConfigJSON builds a channel_installation.config blob like migration 124
// backfills — the shape the Feishu factory decodes.
func feishuConfigJSON(t *testing.T, appID, region string) []byte {
@@ -133,6 +247,446 @@ func TestFeishuChannel_SendMapsTextAndReplyTarget(t *testing.T) {
}
}
+func TestFeishuMediaResolver_HasMedia(t *testing.T) {
+ resolver := NewFeishuMediaResolver(&fakeSender{}, fakeCreds{secret: "plain"}, &fakeMediaStorage{}, &fakeMediaLedger{}, newDiscardLogger())
+ cases := []struct {
+ name string
+ lm InboundMessage
+ want bool
+ }{
+ {"text", InboundMessage{MessageID: "om_t", MessageType: "text", Body: "hello", Content: `{"text":"hello"}`}, false},
+ {"image", InboundMessage{MessageID: "om_i", MessageType: "image", Body: "[Image]", Content: `{"image_key":"img_k"}`}, true},
+ {"video", InboundMessage{MessageID: "om_v", MessageType: "media", Body: "[Video]", Content: `{"file_key":"file_k"}`}, true},
+ {"post with image", InboundMessage{MessageID: "om_p", MessageType: "post",
+ Content: `{"content":[[{"tag":"img","image_key":"img_post"}]]}`}, true},
+ {"post text only", InboundMessage{MessageID: "om_pt", MessageType: "post",
+ Content: `{"content":[[{"tag":"text","text":"plain"}]]}`}, false},
+ {"image missing key", InboundMessage{MessageID: "om_bad", MessageType: "image", Content: `{}`}, false},
+ }
+ for _, tc := range cases {
+ t.Run(tc.name, func(t *testing.T) {
+ if got := resolver.HasMedia(channelMessageFromLark(tc.lm)); got != tc.want {
+ t.Fatalf("HasMedia = %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
+// TestFeishuMediaResolver_RecordsIntentBeforeUpload pins the ledger ordering:
+// the pending row is durable BEFORE the PUT, carries the URL the attachment
+// will hold, and identifies the message the reconciler checks against.
+func TestFeishuMediaResolver_RecordsIntentBeforeUpload(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{Data: []byte{1}, ContentType: "image/png", SizeBytes: 1}}
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ lm := InboundMessage{
+ MessageID: "om_intent",
+ MessageType: "image",
+ Body: "[Image]",
+ Content: `{"image_key":"img_intent"}`,
+ }
+ messageID := uuidFromString(t, "33333333-3333-4333-8333-333333333333")
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), messageID, channelMessageFromLark(lm))
+ if len(ledger.records) != 1 || len(storage.uploads) != 1 || len(got.MediaRefs) != 1 {
+ t.Fatalf("records=%d uploads=%d refs=%d, want 1/1/1", len(ledger.records), len(storage.uploads), len(got.MediaRefs))
+ }
+ rec := ledger.records[0]
+ if rec.StorageKey != storage.uploads[0].key {
+ t.Fatalf("intent key %q != uploaded key %q", rec.StorageKey, storage.uploads[0].key)
+ }
+ if rec.StorageURL != got.MediaRefs[0].StorageURL || rec.StorageURL != storage.ObjectURL(rec.StorageKey) {
+ t.Fatalf("intent url %q must match the ref/attachment url %q", rec.StorageURL, got.MediaRefs[0].StorageURL)
+ }
+ if rec.ChatMessageID != messageID {
+ t.Fatalf("intent message id = %v, want %v", rec.ChatMessageID, messageID)
+ }
+ if !rec.WorkspaceID.Valid || !rec.InstallationID.Valid {
+ t.Fatalf("intent must carry workspace and installation ids: %+v", rec)
+ }
+}
+
+// The object key is per CHAT message, not per platform message. The same
+// Feishu message can be ingested twice (its inbound dedup claim is reclaimable
+// once 60s stale, and the dedup row is vacuumed after 24h), and a shared key
+// would run the second ingest into the first one's ledger row — which may be a
+// tombstone that the intent upsert refuses to resurrect, silently dropping the
+// second ingest's media for as long as the re-delete schedule runs.
+func TestFeishuMediaResolver_KeyIsPerChatMessageSoReingestIsNotBlocked(t *testing.T) {
+ lm := InboundMessage{
+ MessageID: "om_reingest",
+ MessageType: "image",
+ Body: "[Image]",
+ Content: `{"image_key":"img_reingest"}`,
+ }
+ inst := testMediaInstallation(t)
+ sessionID := uuidFromString(t, "22222222-2222-2222-2222-222222222222")
+ newResolver := func(ledger *fakeMediaLedger, storage *fakeMediaStorage) engine.MediaResolver {
+ sender := &fakeSender{downloaded: DownloadedResource{Data: []byte{1}, ContentType: "image/png", SizeBytes: 1}}
+ return NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ }
+
+ firstStorage := &fakeMediaStorage{}
+ firstLedger := &fakeMediaLedger{}
+ newResolver(firstLedger, firstStorage).ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{},
+ sessionID, uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(lm))
+ if len(firstStorage.uploads) != 1 {
+ t.Fatalf("first ingest uploads = %d, want 1", len(firstStorage.uploads))
+ }
+ firstKey := firstStorage.uploads[0].key
+
+ // The first ingest's key is now owned by the reconciler (deleting or
+ // tombstoned); the redelivered ingest must not collide with it.
+ secondStorage := &fakeMediaStorage{}
+ secondLedger := &fakeMediaLedger{ownedKeys: map[string]bool{firstKey: true}}
+ got := newResolver(secondLedger, secondStorage).ResolveMedia(context.Background(), inst, engine.ResolvedIdentity{},
+ sessionID, uuidFromString(t, "44444444-4444-4444-8444-444444444444"), channelMessageFromLark(lm))
+ if len(secondStorage.uploads) != 1 || len(got.MediaRefs) != 1 {
+ t.Fatalf("re-ingest uploads=%d refs=%d, want 1/1 — a tombstoned first ingest must not gag it",
+ len(secondStorage.uploads), len(got.MediaRefs))
+ }
+ if secondStorage.uploads[0].key == firstKey {
+ t.Fatalf("both ingests used key %q; the key must be derived per chat message", firstKey)
+ }
+}
+
+// A key the reconciler owns must not be uploaded at all — the state-guarded
+// upsert refuses to resurrect it and the resolver skips the resource.
+func TestFeishuMediaResolver_ReconcilerOwnedKeySkipsUpload(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{Data: []byte{1}, ContentType: "image/png", SizeBytes: 1}}
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{ownedKeys: map[string]bool{}}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ lm := InboundMessage{
+ MessageID: "om_owned",
+ MessageType: "image",
+ Body: "[Image]",
+ Content: `{"image_key":"img_owned"}`,
+ }
+ // Every key is owned by the reconciler in this fake.
+ ledger.ownedKeys = ownAllKeys(ledger)
+
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(lm))
+ if len(storage.uploads) != 0 || len(sender.downloadCalls) != 0 {
+ t.Fatalf("owned key must skip download+upload entirely: uploads=%d downloads=%d", len(storage.uploads), len(sender.downloadCalls))
+ }
+ if len(got.MediaRefs) != 0 {
+ t.Fatalf("owned key must yield no refs: %+v", got.MediaRefs)
+ }
+}
+
+func TestFeishuMediaResolver_AttachesImageMediaRef(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{
+ Data: []byte{1, 2, 3},
+ ContentType: "image/png",
+ Filename: "from-header.png",
+ SizeBytes: 3,
+ }}
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ lm := InboundMessage{
+ EventID: "evt-image",
+ AppID: "cli_app",
+ ChatID: "oc_dm",
+ ChatType: ChatTypeP2P,
+ MessageID: "om_image",
+ SenderOpenID: "ou_user",
+ MessageType: "image",
+ Body: "[Image]",
+ Content: `{"image_key":"img_v3_key"}`,
+ }
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(lm))
+ if len(sender.downloadCalls) != 1 {
+ t.Fatalf("download calls = %d, want 1", len(sender.downloadCalls))
+ }
+ call := sender.downloadCalls[0]
+ if call.MessageID != "om_image" || call.FileKey != "img_v3_key" || call.Type != "image" {
+ t.Fatalf("download params wrong: %+v", call)
+ }
+ if len(storage.uploads) != 1 {
+ t.Fatalf("uploads = %d, want 1", len(storage.uploads))
+ }
+ up := storage.uploads[0]
+ if up.contentType != "image/png" || up.filename != "from-header.png" || string(up.data) != string([]byte{1, 2, 3}) {
+ t.Fatalf("upload metadata wrong: %+v", up)
+ }
+ if !up.streamed || up.sizeBytes != 3 {
+ t.Fatalf("known-length resource did not stream with its declared size: %+v", up)
+ }
+ if !strings.Contains(up.key, "workspaces/11111111-1111-1111-1111-111111111111/lark/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa/") {
+ t.Fatalf("upload key should be workspace-scoped, got %q", up.key)
+ }
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("media refs = %+v, want 1", got.MediaRefs)
+ }
+ ref := got.MediaRefs[0]
+ if ref.Type != channel.MsgTypeImage || ref.Filename != "from-header.png" || ref.MimeType != "image/png" ||
+ ref.SizeBytes != 3 || ref.StorageURL == "" || ref.StorageKey == "" {
+ t.Fatalf("media ref wrong: %+v", ref)
+ }
+}
+
+func TestFeishuMediaResolver_UnknownLengthUsesBufferedUpload(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{
+ Data: []byte{1, 2, 3},
+ ContentType: "image/png",
+ SizeBytes: 0,
+ }}
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ lm := InboundMessage{
+ MessageID: "om_unknown_length",
+ MessageType: "image",
+ Body: "[Image]",
+ Content: `{"image_key":"img_unknown_length"}`,
+ }
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(lm))
+ if len(storage.uploads) != 1 || storage.uploads[0].streamed {
+ t.Fatalf("unknown-length resource must use buffered Upload: %+v", storage.uploads)
+ }
+ if len(got.MediaRefs) != 1 || got.MediaRefs[0].SizeBytes != 3 {
+ t.Fatalf("buffered upload size not recorded: %+v", got.MediaRefs)
+ }
+}
+
+func TestFeishuMediaResolver_AttachesPostEmbeddedImageMediaRef(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{
+ Data: []byte{4, 5, 6},
+ ContentType: "image/png",
+ Filename: "post-image.png",
+ SizeBytes: 3,
+ }}
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ rawPost := `{"content":[[{"tag":"img","image_key":"img_post_key"}],[{"tag":"text","text":"识别一下图片"}]]}`
+ lm := InboundMessage{
+ EventID: "evt-post-image",
+ AppID: "cli_app",
+ ChatID: "oc_dm",
+ ChatType: ChatTypeP2P,
+ MessageID: "om_post_image",
+ SenderOpenID: "ou_user",
+ MessageType: "post",
+ Body: flattenPostContent(rawPost),
+ Content: rawPost,
+ }
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(lm))
+ if got.Text != "[Image]\n识别一下图片" {
+ t.Fatalf("message text = %q, want post placeholder plus text", got.Text)
+ }
+ if len(sender.downloadCalls) != 1 {
+ t.Fatalf("download calls = %d, want 1", len(sender.downloadCalls))
+ }
+ call := sender.downloadCalls[0]
+ if call.MessageID != "om_post_image" || call.FileKey != "img_post_key" || call.Type != "image" {
+ t.Fatalf("download params wrong: %+v", call)
+ }
+ if len(storage.uploads) != 1 {
+ t.Fatalf("uploads = %d, want 1", len(storage.uploads))
+ }
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("media refs = %+v, want 1", got.MediaRefs)
+ }
+ ref := got.MediaRefs[0]
+ if ref.Type != channel.MsgTypeImage || ref.Filename != "post-image.png" || ref.MimeType != "image/png" ||
+ ref.SizeBytes != 3 || ref.StorageURL == "" || ref.StorageKey == "" {
+ t.Fatalf("post image ref wrong: %+v", ref)
+ }
+}
+
+func TestFeishuMediaResolver_AttachesPostEmbeddedVideoMediaRef(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{
+ Data: []byte("mp4"),
+ ContentType: "video/mp4",
+ Filename: "demo.mp4",
+ SizeBytes: 3,
+ }}
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ rawPost := `{"content":[[{"tag":"text","text":"看一下视频"},{"tag":"media","file_key":"file_post_key","file_name":"demo.mp4"}]]}`
+ lm := InboundMessage{
+ EventID: "evt-post-video",
+ AppID: "cli_app",
+ ChatID: "oc_dm",
+ ChatType: ChatTypeP2P,
+ MessageID: "om_post_video",
+ SenderOpenID: "ou_user",
+ MessageType: "post",
+ Body: flattenPostContent(rawPost),
+ Content: rawPost,
+ }
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(lm))
+ if len(sender.downloadCalls) != 1 {
+ t.Fatalf("download calls = %d, want 1", len(sender.downloadCalls))
+ }
+ call := sender.downloadCalls[0]
+ if call.MessageID != "om_post_video" || call.FileKey != "file_post_key" || call.Type != "file" {
+ t.Fatalf("download params wrong: %+v", call)
+ }
+ if len(got.MediaRefs) != 1 || got.MediaRefs[0].Type != channel.MsgTypeVideo || got.MediaRefs[0].Filename != "demo.mp4" {
+ t.Fatalf("post video ref wrong: %+v", got.MediaRefs)
+ }
+}
+
+func TestFeishuMediaResolver_AttachesVideoMediaRef(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{
+ Data: []byte("mp4"),
+ ContentType: "video/mp4",
+ SizeBytes: 3,
+ }}
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ lm := InboundMessage{
+ EventID: "evt-video",
+ AppID: "cli_app",
+ ChatID: "oc_dm",
+ ChatType: ChatTypeP2P,
+ MessageID: "om_video",
+ SenderOpenID: "ou_user",
+ MessageType: "media",
+ Body: "[Video]",
+ Content: `{"file_key":"file_v3_key","file_name":"clip.mp4"}`,
+ }
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(lm))
+ if len(sender.downloadCalls) != 1 {
+ t.Fatalf("download calls = %d, want 1", len(sender.downloadCalls))
+ }
+ call := sender.downloadCalls[0]
+ if call.MessageID != "om_video" || call.FileKey != "file_v3_key" || call.Type != "file" {
+ t.Fatalf("download params wrong: %+v", call)
+ }
+ if len(got.MediaRefs) != 1 || got.MediaRefs[0].Type != channel.MsgTypeVideo || got.MediaRefs[0].Filename != "clip.mp4" {
+ t.Fatalf("video ref wrong: %+v", got.MediaRefs)
+ }
+}
+
+func TestFeishuMediaResolver_RetryReusesObjectKey(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{
+ Data: []byte{1, 2, 3},
+ ContentType: "image/png",
+ Filename: "shot.png",
+ }}
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ lm := InboundMessage{
+ MessageID: "om_retry",
+ MessageType: "image",
+ Body: "[Image]",
+ Content: `{"image_key":"img_retry"}`,
+ }
+
+ for range 2 {
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), channelMessageFromLark(lm))
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("media refs = %+v, want 1", got.MediaRefs)
+ }
+ }
+ if len(storage.uploads) != 2 {
+ t.Fatalf("uploads = %d, want 2 retry attempts", len(storage.uploads))
+ }
+ if storage.uploads[0].key != storage.uploads[1].key {
+ t.Fatalf("retry object keys differ: %q vs %q", storage.uploads[0].key, storage.uploads[1].key)
+ }
+}
+
+func TestFeishuMediaResolver_DownloadFailurePreservesMessage(t *testing.T) {
+ sender := &fakeSender{downloadErr: errors.New("download unavailable")}
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ lm := InboundMessage{
+ MessageID: "om_download_failure",
+ MessageType: "image",
+ Body: "[Image]",
+ Content: `{"image_key":"img_failure"}`,
+ }
+ before := channelMessageFromLark(lm)
+
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), before)
+ if got.Text != before.Text || len(got.MediaRefs) != 0 {
+ t.Fatalf("download failure changed message: before=%+v after=%+v", before, got)
+ }
+ if len(storage.uploads) != 0 {
+ t.Fatalf("download failure uploaded %d objects", len(storage.uploads))
+ }
+}
+
+func TestFeishuMediaResolver_UploadFailurePreservesMessage(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{Data: []byte{1}, ContentType: "image/png"}}
+ storage := &fakeMediaStorage{err: errors.New("storage unavailable")}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ lm := InboundMessage{
+ MessageID: "om_upload_failure",
+ MessageType: "image",
+ Body: "[Image]",
+ Content: `{"image_key":"img_failure"}`,
+ }
+ before := channelMessageFromLark(lm)
+
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), before)
+ if got.Text != before.Text || len(got.MediaRefs) != 0 {
+ t.Fatalf("upload failure changed message: before=%+v after=%+v", before, got)
+ }
+ // NO inline delete: the store may still be processing the PUT, and a
+ // DELETE issued now could reorder with it. The intent row (recorded
+ // before the upload) is the reclaim path — the reconciler settles it.
+ if len(storage.deleted) != 0 {
+ t.Fatalf("upload failure must not delete inline, got %v", storage.deleted)
+ }
+ if len(ledger.records) != 1 {
+ t.Fatalf("intent must be recorded before the failed upload, records=%d", len(ledger.records))
+ }
+}
+
+func TestFeishuMediaResolver_PostPartialFailureKeepsTextAndSuccessfulMedia(t *testing.T) {
+ sender := &fakeSender{
+ downloadedByKey: map[string]DownloadedResource{
+ "img_ok": {Data: []byte{1}, ContentType: "image/png", Filename: "ok.png"},
+ },
+ downloadErrByKey: map[string]error{"video_failed": errors.New("video unavailable")},
+ }
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ rawPost := `{"content":[[{"tag":"text","text":"inspect"},{"tag":"img","image_key":"img_ok"},{"tag":"media","file_key":"video_failed","file_name":"failed.mp4"}]]}`
+ lm := InboundMessage{
+ MessageID: "om_partial",
+ MessageType: "post",
+ Body: flattenPostContent(rawPost),
+ Content: rawPost,
+ }
+ before := channelMessageFromLark(lm)
+
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"), before)
+ if got.Text != before.Text {
+ t.Fatalf("partial failure changed text: got %q want %q", got.Text, before.Text)
+ }
+ if len(sender.downloadCalls) != 2 || len(storage.uploads) != 1 || len(got.MediaRefs) != 1 {
+ t.Fatalf("partial failure result: downloads=%d uploads=%d refs=%+v", len(sender.downloadCalls), len(storage.uploads), got.MediaRefs)
+ }
+ if got.MediaRefs[0].Type != channel.MsgTypeImage || got.MediaRefs[0].Filename != "ok.png" {
+ t.Fatalf("successful media ref lost: %+v", got.MediaRefs[0])
+ }
+}
+
func TestOutboundReplyTarget(t *testing.T) {
if got := outboundReplyTarget(channel.OutboundMessage{}); got.IsSet() {
t.Fatalf("no ReplyTo must yield an unset target, got %+v", got)
diff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.go
index 297fe26425..2aaad3b338 100644
--- a/server/internal/integrations/lark/feishu_resolvers.go
+++ b/server/internal/integrations/lark/feishu_resolvers.go
@@ -44,7 +44,7 @@ func larkMsgFromRaw(msg channel.InboundMessage) (InboundMessage, error) {
// shared session service, audit logger, and (optional) outbound replier +
// typing indicator. Feishu is just another consumer of the channel-agnostic
// engine.ChatSession — there is no Feishu-specific session implementation.
-func NewFeishuResolverSet(store *ChannelStore, session *engine.ChatSession, audit AuditLogger, replier OutcomeReplier, typing *TypingIndicatorManager) engine.ResolverSet {
+func NewFeishuResolverSet(store *ChannelStore, session *engine.ChatSession, audit AuditLogger, replier OutcomeReplier, typing *TypingIndicatorManager, media engine.MediaResolver) engine.ResolverSet {
set := engine.ResolverSet{
Installation: &feishuInstallationResolver{store: store},
Identity: &feishuIdentityResolver{store: store},
@@ -59,6 +59,9 @@ func NewFeishuResolverSet(store *ChannelStore, session *engine.ChatSession, audi
if typing != nil {
set.Typing = &feishuTypingNotifier{mgr: typing}
}
+ if media != nil {
+ set.Media = media
+ }
return set
}
@@ -157,6 +160,7 @@ func (r *feishuDeduper) Release(ctx context.Context, installationID pgtype.UUID,
type chatSession interface {
EnsureSession(ctx context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error)
AppendUserMessage(ctx context.Context, in engine.AppendInput) (engine.AppendResult, error)
+ BindMediaRefs(ctx context.Context, in engine.BindMediaInput) error
}
type feishuSessionBinder struct{ session chatSession }
@@ -207,14 +211,25 @@ func (r *feishuSessionBinder) AppendMessage(ctx context.Context, p engine.Append
return engine.AppendResult{}, err
}
return r.session.AppendUserMessage(ctx, engine.AppendInput{
- SessionID: p.SessionID,
- Sender: p.Sender,
- InstallationID: p.InstallationID,
- Body: p.Message.Text,
- CommandText: lm.CommandBody,
- MessageID: p.Message.MessageID,
- ThreadID: p.Message.Source.ThreadID,
- ClaimToken: p.ClaimToken,
+ SessionID: p.SessionID,
+ Sender: p.Sender,
+ InstallationID: p.InstallationID,
+ Body: p.Message.Text,
+ CommandText: lm.CommandBody,
+ MessageID: p.Message.MessageID,
+ ThreadID: p.Message.Source.ThreadID,
+ ClaimToken: p.ClaimToken,
+ MediaPendingSeconds: p.MediaPendingSeconds,
+ })
+}
+
+func (r *feishuSessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
+ return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
+ MessageID: p.MessageID,
+ SessionID: p.SessionID,
+ WorkspaceID: p.WorkspaceID,
+ Sender: p.Sender,
+ MediaRefs: p.MediaRefs,
})
}
diff --git a/server/internal/integrations/lark/feishu_resolvers_test.go b/server/internal/integrations/lark/feishu_resolvers_test.go
index 9b376a9cc0..26d2be798f 100644
--- a/server/internal/integrations/lark/feishu_resolvers_test.go
+++ b/server/internal/integrations/lark/feishu_resolvers_test.go
@@ -23,6 +23,7 @@ func binderUUID(b byte) pgtype.UUID {
type fakeChatSession struct {
ensureIn engine.EnsureSessionInput
appendIn engine.AppendInput
+ mediaIn engine.BindMediaInput
}
func (f *fakeChatSession) EnsureSession(_ context.Context, in engine.EnsureSessionInput) (pgtype.UUID, error) {
@@ -35,6 +36,11 @@ func (f *fakeChatSession) AppendUserMessage(_ context.Context, in engine.AppendI
return engine.AppendResult{}, nil
}
+func (f *fakeChatSession) BindMediaRefs(_ context.Context, in engine.BindMediaInput) error {
+ f.mediaIn = in
+ return nil
+}
+
func TestFeishuSessionBinder_EnsureSessionMapping(t *testing.T) {
f := &fakeChatSession{}
b := &feishuSessionBinder{session: f}
@@ -150,3 +156,22 @@ func TestFeishuSessionBinder_AppendUsesUnenrichedCommandBody(t *testing.T) {
t.Errorf("append mapping wrong: %+v", got)
}
}
+
+func TestFeishuSessionBinder_BindMediaMapping(t *testing.T) {
+ f := &fakeChatSession{}
+ b := &feishuSessionBinder{session: f}
+ ref := channel.MediaRef{Type: channel.MsgTypeImage, StorageURL: "https://cdn.example.test/image.png"}
+ if err := b.BindMedia(context.Background(), engine.BindMediaParams{
+ MessageID: binderUUID(4),
+ SessionID: binderUUID(1),
+ WorkspaceID: binderUUID(2),
+ Sender: binderUUID(7),
+ 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 {
+ t.Fatalf("media mapping wrong: %+v", got)
+ }
+}
diff --git a/server/internal/integrations/lark/feishu_types.go b/server/internal/integrations/lark/feishu_types.go
index 179733420d..9691542e7c 100644
--- a/server/internal/integrations/lark/feishu_types.go
+++ b/server/internal/integrations/lark/feishu_types.go
@@ -22,6 +22,11 @@ type InboundMessage struct {
MessageID string
SenderOpenID OpenID
Body string
+ // Content is the raw msg_type-specific JSON string Lark sends in
+ // event.message.content. Text/post decoding consumes it immediately; media
+ // ingestion keeps it so the adapter can extract image_key/file_key before
+ // translating to channel.InboundMessage.
+ Content string
// ForceFreshSession marks this dispatch as a one-off fresh start: the
// daemon should skip prior session resume when it claims the resulting
// chat task.
diff --git a/server/internal/integrations/lark/http_client.go b/server/internal/integrations/lark/http_client.go
index cd374ad227..f9d369eebd 100644
--- a/server/internal/integrations/lark/http_client.go
+++ b/server/internal/integrations/lark/http_client.go
@@ -8,6 +8,7 @@ import (
"fmt"
"io"
"log/slog"
+ "mime"
"net/http"
"net/url"
"strconv"
@@ -33,6 +34,11 @@ import (
// honoring Lark's `expire` field minus a safety margin so callers
// never present a token that's about to lapse mid-flight.
+// DefaultResourceDownloadTimeout is the default cap on one message-resource
+// download. Exported so the channel-media settle invariant test can assert
+// the reconciler's settle delay dwarfs every pipeline budget.
+const DefaultResourceDownloadTimeout = 45 * time.Second
+
const (
// defaultLarkBaseURL is the mainland 飞书 open-platform host. It is the
// fallback host for an installation whose region is feishu (or unset);
@@ -53,6 +59,18 @@ const (
// latency from a self-hosted Multica deployment to feishu.cn.
defaultRequestTimeout = 10 * time.Second
+ // defaultResourceDownloadTimeout is intentionally longer than normal
+ // OpenAPI calls because message videos are binary transfers, not JSON
+ // RPCs. Keep it below the inbound dedup stale-claim window (60s), so a
+ // slow download does not invite a second replica to reclaim the same
+ // message before this one can append and mark it processed.
+ defaultResourceDownloadTimeout = DefaultResourceDownloadTimeout
+
+ // Feishu caps message resources at 100 MiB. Keep the local transport guard
+ // aligned with that contract; detached media processing keeps large
+ // transfers off the connector ACK path.
+ maxMessageResourceBytes = 100 << 20
+
// Lark's "invalid tenant_access_token" / "tenant_access_token
// expired" error codes. When we see either, drop the cached token
// so the next call refreshes from /tenant_access_token/internal.
@@ -80,6 +98,15 @@ type HTTPClientConfig struct {
// defaultRequestTimeout.
HTTPClient *http.Client
+ // ResourceHTTPClient is used only for message resource downloads. It
+ // deliberately does not share HTTPClient's shorter timeout: image/video
+ // resource transfers are bounded by ResourceDownloadTimeout instead.
+ ResourceHTTPClient *http.Client
+
+ // ResourceDownloadTimeout caps a single message resource download. Zero
+ // defaults to defaultResourceDownloadTimeout.
+ ResourceDownloadTimeout time.Duration
+
// Now is overridable for deterministic token-expiry tests.
Now func() time.Time
@@ -99,6 +126,12 @@ func (c HTTPClientConfig) withDefaults() HTTPClientConfig {
if c.HTTPClient == nil {
c.HTTPClient = &http.Client{Timeout: defaultRequestTimeout}
}
+ if c.ResourceDownloadTimeout == 0 {
+ c.ResourceDownloadTimeout = defaultResourceDownloadTimeout
+ }
+ if c.ResourceHTTPClient == nil {
+ c.ResourceHTTPClient = &http.Client{Timeout: c.ResourceDownloadTimeout}
+ }
if c.Now == nil {
c.Now = time.Now
}
@@ -667,6 +700,195 @@ func (c *httpAPIClient) ListChatMessages(ctx context.Context, creds Installation
return out, nil
}
+// DownloadMessageResource obtains a binary message resource (image, video,
+// file, audio) from Lark/Feishu. Business errors are still represented as
+// JSON with a code/msg body on some failures, so JSON-looking responses are
+// checked before being treated as resource bytes.
+func (c *httpAPIClient) DownloadMessageResource(ctx context.Context, creds InstallationCredentials, p DownloadResourceParams) (DownloadedResource, error) {
+ stream, err := c.DownloadMessageResourceStream(ctx, creds, p)
+ if err != nil {
+ return DownloadedResource{}, err
+ }
+ defer stream.Body.Close()
+ rawBody, err := io.ReadAll(stream.Body)
+ if err != nil {
+ return DownloadedResource{}, fmt.Errorf("lark http client: download resource: read body: %w", err)
+ }
+ sizeBytes := stream.SizeBytes
+ if sizeBytes == 0 {
+ sizeBytes = int64(len(rawBody))
+ }
+ return DownloadedResource{
+ Data: rawBody,
+ ContentType: stream.ContentType,
+ Filename: stream.Filename,
+ SizeBytes: sizeBytes,
+ }, nil
+}
+
+func (c *httpAPIClient) DownloadMessageResourceStream(ctx context.Context, creds InstallationCredentials, p DownloadResourceParams) (DownloadedResourceStream, error) {
+ if p.MessageID == "" {
+ return DownloadedResourceStream{}, errors.New("lark http client: missing message_id")
+ }
+ if p.FileKey == "" {
+ return DownloadedResourceStream{}, errors.New("lark http client: missing file_key")
+ }
+ token, err := c.tenantAccessToken(ctx, creds)
+ if err != nil {
+ return DownloadedResourceStream{}, err
+ }
+ q := url.Values{}
+ if p.Type != "" {
+ q.Set("type", p.Type)
+ }
+ path := "/open-apis/im/v1/messages/" + url.PathEscape(p.MessageID) + "/resources/" + url.PathEscape(p.FileKey)
+ if encoded := q.Encode(); encoded != "" {
+ path += "?" + encoded
+ }
+
+ downloadCtx := ctx
+ var cancel context.CancelFunc
+ if c.cfg.ResourceDownloadTimeout > 0 {
+ downloadCtx, cancel = context.WithTimeout(ctx, c.cfg.ResourceDownloadTimeout)
+ }
+ req, err := http.NewRequestWithContext(downloadCtx, http.MethodGet, c.resolveBaseURL(creds)+path, nil)
+ if err != nil {
+ if cancel != nil {
+ cancel()
+ }
+ return DownloadedResourceStream{}, fmt.Errorf("lark http client: download resource: new request: %w", err)
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ resp, err := c.cfg.ResourceHTTPClient.Do(req)
+ if err != nil {
+ if cancel != nil {
+ cancel()
+ }
+ return DownloadedResourceStream{}, fmt.Errorf("lark http client: download resource: http do: %w", err)
+ }
+ closeWithCancel := func() {
+ resp.Body.Close()
+ if cancel != nil {
+ cancel()
+ }
+ }
+ if resp.ContentLength > maxMessageResourceBytes {
+ closeWithCancel()
+ return DownloadedResourceStream{}, fmt.Errorf("lark http client: download resource: resource exceeds %d bytes", maxMessageResourceBytes)
+ }
+ if resp.StatusCode < 200 || resp.StatusCode >= 300 {
+ rawBody, readErr := readMessageResourceErrorBody(resp.Body)
+ closeWithCancel()
+ if readErr != nil {
+ return DownloadedResourceStream{}, readErr
+ }
+ return DownloadedResourceStream{}, fmt.Errorf("lark http client: download resource: http %d: %s", resp.StatusCode, truncate(string(rawBody), 512))
+ }
+ contentType := resp.Header.Get("Content-Type")
+ if strings.Contains(strings.ToLower(contentType), "json") {
+ rawBody, readErr := readMessageResourceErrorBody(resp.Body)
+ closeWithCancel()
+ if readErr != nil {
+ return DownloadedResourceStream{}, readErr
+ }
+ var apiResp struct {
+ Code int `json:"code"`
+ Msg string `json:"msg"`
+ }
+ if err := json.Unmarshal(rawBody, &apiResp); err == nil && apiResp.Code != 0 {
+ if isTokenError(apiResp.Code) {
+ c.invalidateToken(creds.AppID)
+ }
+ return DownloadedResourceStream{}, &APIError{Op: "download resource", Code: apiResp.Code, Msg: apiResp.Msg}
+ }
+ return DownloadedResourceStream{
+ Body: cancelOnClose(io.NopCloser(bytes.NewReader(rawBody)), cancel),
+ ContentType: contentType,
+ Filename: filenameFromContentDisposition(resp.Header.Get("Content-Disposition")),
+ SizeBytes: int64(len(rawBody)),
+ }, nil
+ }
+ if contentType == "" {
+ contentType = "application/octet-stream"
+ }
+ sizeBytes := resp.ContentLength
+ if sizeBytes < 0 {
+ sizeBytes = 0
+ }
+ return DownloadedResourceStream{
+ Body: cancelOnClose(&maxBytesReadCloser{r: resp.Body, remaining: maxMessageResourceBytes}, cancel),
+ ContentType: contentType,
+ Filename: filenameFromContentDisposition(resp.Header.Get("Content-Disposition")),
+ SizeBytes: sizeBytes,
+ }, nil
+}
+
+func readMessageResourceErrorBody(body io.Reader) ([]byte, error) {
+ rawBody, err := io.ReadAll(io.LimitReader(body, maxMessageResourceBytes+1))
+ if err != nil {
+ return nil, fmt.Errorf("lark http client: download resource: read body: %w", err)
+ }
+ if len(rawBody) > maxMessageResourceBytes {
+ return nil, fmt.Errorf("lark http client: download resource: resource exceeds %d bytes", maxMessageResourceBytes)
+ }
+ return rawBody, nil
+}
+
+type maxBytesReadCloser struct {
+ r io.ReadCloser
+ remaining int64
+}
+
+func (r *maxBytesReadCloser) Read(p []byte) (int, error) {
+ if r.remaining > 0 {
+ if int64(len(p)) > r.remaining {
+ p = p[:r.remaining]
+ }
+ n, err := r.r.Read(p)
+ r.remaining -= int64(n)
+ return n, err
+ }
+ var one [1]byte
+ n, err := r.r.Read(one[:])
+ if n > 0 {
+ return 0, fmt.Errorf("lark http client: download resource: resource exceeds %d bytes", maxMessageResourceBytes)
+ }
+ return 0, err
+}
+
+func (r *maxBytesReadCloser) Close() error {
+ return r.r.Close()
+}
+
+type cancelReadCloser struct {
+ io.ReadCloser
+ cancel context.CancelFunc
+}
+
+func cancelOnClose(body io.ReadCloser, cancel context.CancelFunc) io.ReadCloser {
+ if cancel == nil {
+ return body
+ }
+ return &cancelReadCloser{ReadCloser: body, cancel: cancel}
+}
+
+func (r *cancelReadCloser) Close() error {
+ err := r.ReadCloser.Close()
+ r.cancel()
+ return err
+}
+
+func filenameFromContentDisposition(raw string) string {
+ if raw == "" {
+ return ""
+ }
+ _, params, err := mime.ParseMediaType(raw)
+ if err != nil {
+ return ""
+ }
+ return params["filename"]
+}
+
// larkBatchGetUsersMaxIDs is Lark's hard cap on user_ids per
// contact/v3/users/batch call. We drop the overflow rather than error so
// a caller asking for more still gets the first 50 resolved.
diff --git a/server/internal/integrations/lark/http_client_test.go b/server/internal/integrations/lark/http_client_test.go
index db2fad94f9..109d9838d3 100644
--- a/server/internal/integrations/lark/http_client_test.go
+++ b/server/internal/integrations/lark/http_client_test.go
@@ -7,6 +7,7 @@ import (
"io"
"net/http"
"net/http/httptest"
+ "strconv"
"strings"
"sync/atomic"
"testing"
@@ -240,6 +241,201 @@ func TestHTTPClient_IsConfigured(t *testing.T) {
}
}
+func TestHTTPClient_DownloadMessageResource(t *testing.T) {
+ fake := newLarkFake(t)
+ fake.stubToken("tok_resource", 7200)
+ fake.mux.HandleFunc("/open-apis/im/v1/messages/om_1/resources/img_1", func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ t.Errorf("resource: method = %s, want GET", r.Method)
+ }
+ if got := r.URL.Query().Get("type"); got != "image" {
+ t.Errorf("resource type = %q, want image", got)
+ }
+ if got := r.Header.Get("Authorization"); got != "Bearer tok_resource" {
+ t.Errorf("auth = %q", got)
+ }
+ w.Header().Set("Content-Type", "image/png")
+ w.Header().Set("Content-Disposition", `attachment; filename="shot.png"`)
+ _, _ = w.Write([]byte{1, 2, 3})
+ })
+ c := newTestClient(fake, time.Now)
+ got, err := c.DownloadMessageResource(context.Background(), testCreds(), DownloadResourceParams{
+ MessageID: "om_1",
+ FileKey: "img_1",
+ Type: "image",
+ })
+ if err != nil {
+ t.Fatalf("DownloadMessageResource: %v", err)
+ }
+ if string(got.Data) != string([]byte{1, 2, 3}) || got.ContentType != "image/png" ||
+ got.Filename != "shot.png" || got.SizeBytes != 3 {
+ t.Fatalf("downloaded resource wrong: %+v", got)
+ }
+}
+
+func TestHTTPClient_DownloadMessageResourceUsesResourceTimeout(t *testing.T) {
+ fake := newLarkFake(t)
+ fake.stubToken("tok_resource", 7200)
+ fake.mux.HandleFunc("/open-apis/im/v1/messages/om_video/resources/file_video", func(w http.ResponseWriter, r *http.Request) {
+ if got := r.URL.Query().Get("type"); got != "file" {
+ t.Errorf("resource type = %q, want file", got)
+ }
+ time.Sleep(80 * time.Millisecond)
+ w.Header().Set("Content-Type", "video/mp4")
+ w.Header().Set("Content-Disposition", `attachment; filename="clip.mp4"`)
+ _, _ = w.Write([]byte("slow-video"))
+ })
+ c := NewHTTPAPIClient(HTTPClientConfig{
+ BaseURL: fake.URL(),
+ HTTPClient: &http.Client{Timeout: 20 * time.Millisecond},
+ ResourceDownloadTimeout: 500 * time.Millisecond,
+ Now: time.Now,
+ }).(*httpAPIClient)
+ got, err := c.DownloadMessageResource(context.Background(), testCreds(), DownloadResourceParams{
+ MessageID: "om_video",
+ FileKey: "file_video",
+ Type: "file",
+ })
+ if err != nil {
+ t.Fatalf("DownloadMessageResource slow video: %v", err)
+ }
+ if string(got.Data) != "slow-video" || got.ContentType != "video/mp4" || got.Filename != "clip.mp4" {
+ t.Fatalf("downloaded slow video wrong: %+v", got)
+ }
+}
+
+func TestHTTPClient_DownloadMessageResourceExceedingTimeoutIsCancelled(t *testing.T) {
+ fake := newLarkFake(t)
+ fake.stubToken("tok_resource", 7200)
+ fake.mux.HandleFunc("/open-apis/im/v1/messages/om_timeout/resources/file_timeout", func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case <-r.Context().Done():
+ return
+ case <-time.After(500 * time.Millisecond):
+ _, _ = w.Write([]byte("too late"))
+ }
+ })
+ c := NewHTTPAPIClient(HTTPClientConfig{
+ BaseURL: fake.URL(),
+ ResourceDownloadTimeout: 20 * time.Millisecond,
+ Now: time.Now,
+ }).(*httpAPIClient)
+
+ _, err := c.DownloadMessageResource(context.Background(), testCreds(), DownloadResourceParams{
+ MessageID: "om_timeout",
+ FileKey: "file_timeout",
+ Type: "file",
+ })
+ if !errors.Is(err, context.DeadlineExceeded) {
+ t.Fatalf("timeout error = %v, want context deadline exceeded", err)
+ }
+}
+
+func TestHTTPClient_DownloadMessageResourceRejectsDeclaredOversize(t *testing.T) {
+ fake := newLarkFake(t)
+ fake.stubToken("tok_resource", 7200)
+ fake.mux.HandleFunc("/open-apis/im/v1/messages/om_large/resources/file_large", func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "video/mp4")
+ w.Header().Set("Content-Length", strconv.FormatInt(maxMessageResourceBytes+1, 10))
+ w.WriteHeader(http.StatusOK)
+ })
+ c := newTestClient(fake, time.Now)
+
+ _, err := c.DownloadMessageResourceStream(context.Background(), testCreds(), DownloadResourceParams{
+ MessageID: "om_large",
+ FileKey: "file_large",
+ Type: "file",
+ })
+ if err == nil || !strings.Contains(err.Error(), "resource exceeds") {
+ t.Fatalf("declared oversize error = %v", err)
+ }
+}
+
+func TestHTTPClient_DownloadMessageResourceAllowsDeclaredFeishuLimit(t *testing.T) {
+ fake := newLarkFake(t)
+ fake.stubToken("tok_resource", 7200)
+ fake.mux.HandleFunc("/open-apis/im/v1/messages/om_limit/resources/file_limit", func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "video/mp4")
+ w.Header().Set("Content-Length", strconv.FormatInt(maxMessageResourceBytes, 10))
+ w.WriteHeader(http.StatusOK)
+ })
+ c := newTestClient(fake, time.Now)
+
+ got, err := c.DownloadMessageResourceStream(context.Background(), testCreds(), DownloadResourceParams{
+ MessageID: "om_limit",
+ FileKey: "file_limit",
+ Type: "file",
+ })
+ if err != nil {
+ t.Fatalf("declared Feishu-limit resource should be accepted: %v", err)
+ }
+ got.Body.Close()
+ if got.SizeBytes != maxMessageResourceBytes {
+ t.Fatalf("SizeBytes = %d, want %d", got.SizeBytes, maxMessageResourceBytes)
+ }
+}
+
+func TestHTTPClient_DownloadMessageResourceAllowsAbovePreviousLocalLimit(t *testing.T) {
+ const previousLocalLimit = 20 << 20
+ fake := newLarkFake(t)
+ fake.stubToken("tok_resource", 7200)
+ fake.mux.HandleFunc("/open-apis/im/v1/messages/om_above_previous/resources/file_above_previous", func(w http.ResponseWriter, _ *http.Request) {
+ w.Header().Set("Content-Type", "video/mp4")
+ w.Header().Set("Content-Length", strconv.FormatInt(previousLocalLimit+1, 10))
+ w.WriteHeader(http.StatusOK)
+ })
+ c := newTestClient(fake, time.Now)
+
+ got, err := c.DownloadMessageResourceStream(context.Background(), testCreds(), DownloadResourceParams{
+ MessageID: "om_above_previous",
+ FileKey: "file_above_previous",
+ Type: "file",
+ })
+ if err != nil {
+ t.Fatalf("resource above previous 20MiB local limit should be accepted: %v", err)
+ }
+ got.Body.Close()
+ if got.SizeBytes != previousLocalLimit+1 {
+ t.Fatalf("SizeBytes = %d, want %d", got.SizeBytes, previousLocalLimit+1)
+ }
+}
+
+func TestMaxBytesReadCloserEnforcesUnknownLengthBoundary(t *testing.T) {
+ t.Run("exact limit", func(t *testing.T) {
+ body := &maxBytesReadCloser{r: io.NopCloser(strings.NewReader("abc")), remaining: 3}
+ got, err := io.ReadAll(body)
+ if err != nil || string(got) != "abc" {
+ t.Fatalf("exact limit: body=%q err=%v", got, err)
+ }
+ })
+
+ t.Run("one byte over", func(t *testing.T) {
+ body := &maxBytesReadCloser{r: io.NopCloser(strings.NewReader("abcd")), remaining: 3}
+ got, err := io.ReadAll(body)
+ if err == nil || !strings.Contains(err.Error(), "resource exceeds") || string(got) != "abc" {
+ t.Fatalf("overflow: body=%q err=%v", got, err)
+ }
+ })
+}
+
+func TestHTTPClient_DownloadMessageResourceBusinessError(t *testing.T) {
+ fake := newLarkFake(t)
+ fake.stubToken("tok_resource", 7200)
+ fake.mux.HandleFunc("/open-apis/im/v1/messages/om_1/resources/img_1", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ writeJSON(w, map[string]any{"code": 234003, "msg": "File not in msg"})
+ })
+ c := newTestClient(fake, time.Now)
+ _, err := c.DownloadMessageResource(context.Background(), testCreds(), DownloadResourceParams{
+ MessageID: "om_1",
+ FileKey: "img_1",
+ Type: "image",
+ })
+ if err == nil || !strings.Contains(err.Error(), "234003") {
+ t.Fatalf("expected APIError with code, got %v", err)
+ }
+}
+
// TestHTTPClient_StubReportsNotConfigured pins that the stub never
// claims wired outbound — handlers gate install / management UI on
// this signal.
@@ -1109,8 +1305,8 @@ func TestHTTPClient_GetBotInfo_HappyPath(t *testing.T) {
"code": 0,
"msg": "ok",
"bot": map[string]any{
- "open_id": "ou_bot_42",
- "app_name": "PersonalAgent",
+ "open_id": "ou_bot_42",
+ "app_name": "PersonalAgent",
"avatar_url": "https://example/avatar.png",
},
})
diff --git a/server/internal/integrations/lark/inbound_enricher_test.go b/server/internal/integrations/lark/inbound_enricher_test.go
index 6031ba18c7..158b31e4d5 100644
--- a/server/internal/integrations/lark/inbound_enricher_test.go
+++ b/server/internal/integrations/lark/inbound_enricher_test.go
@@ -80,6 +80,9 @@ func (f *enricherFakeClient) BatchGetUsers(ctx context.Context, creds Installati
}
return out, nil
}
+func (f *enricherFakeClient) DownloadMessageResource(context.Context, InstallationCredentials, DownloadResourceParams) (DownloadedResource, error) {
+ return DownloadedResource{}, nil
+}
// Unused-by-enricher methods — present only to satisfy APIClient.
func (f *enricherFakeClient) SendInteractiveCard(context.Context, SendCardParams) (string, error) {
diff --git a/server/internal/integrations/lark/media_dedup_test.go b/server/internal/integrations/lark/media_dedup_test.go
new file mode 100644
index 0000000000..e8fbea6b18
--- /dev/null
+++ b/server/internal/integrations/lark/media_dedup_test.go
@@ -0,0 +1,57 @@
+package lark
+
+import (
+ "context"
+ "testing"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+// A post referencing the same image_key twice must yield ONE resource: the
+// object key is derived from (message, type, key), so a duplicate would upload
+// to the same key twice — a later failure could destroy the object an earlier
+// success produced (dangling attachment) and a later success would produce two
+// attachment rows for one object.
+func TestMediaResourcesFromPost_DeduplicatesRepeatedKeys(t *testing.T) {
+ raw := `{"content":[[{"tag":"img","image_key":"img_dup"},{"tag":"text","text":"x"}],` +
+ `[{"tag":"img","image_key":"img_dup"},{"tag":"media","file_key":"file_dup"}],` +
+ `[{"tag":"media","file_key":"file_dup"},{"tag":"img","image_key":"img_other"}]]}`
+ got := mediaResourcesFromPost(InboundMessage{MessageID: "om_dup", MessageType: "post", Content: raw})
+ if len(got) != 3 {
+ t.Fatalf("resources = %d (%+v), want 3 unique", len(got), got)
+ }
+ seen := map[string]int{}
+ for _, r := range got {
+ seen[r.fetchType+"\x00"+r.key]++
+ }
+ for id, n := range seen {
+ if n != 1 {
+ t.Fatalf("resource %q appears %d times, want once", id, n)
+ }
+ }
+}
+
+// End-to-end shape of the same hazard: a duplicated span must upload once and
+// produce exactly one ref, so no second attempt can clobber the first object.
+func TestFeishuMediaResolver_DuplicatePostSpanUploadsOnce(t *testing.T) {
+ sender := &fakeSender{downloaded: DownloadedResource{Data: []byte{1, 2, 3}, ContentType: "image/png", SizeBytes: 3}}
+ storage := &fakeMediaStorage{}
+ ledger := &fakeMediaLedger{}
+ resolver := NewFeishuMediaResolver(sender, fakeCreds{secret: "plain"}, storage, ledger, newDiscardLogger())
+ raw := `{"content":[[{"tag":"img","image_key":"img_same"}],[{"tag":"img","image_key":"img_same"}]]}`
+ lm := InboundMessage{MessageID: "om_same", MessageType: "post", Body: flattenPostContent(raw), Content: raw}
+
+ got := resolver.ResolveMedia(context.Background(), testMediaInstallation(t), engine.ResolvedIdentity{},
+ uuidFromString(t, "22222222-2222-2222-2222-222222222222"), uuidFromString(t, "33333333-3333-4333-8333-333333333333"),
+ channelMessageFromLark(lm))
+
+ if len(sender.downloadCalls) != 1 || len(storage.uploads) != 1 {
+ t.Fatalf("downloads=%d uploads=%d, want 1/1 for a duplicated span", len(sender.downloadCalls), len(storage.uploads))
+ }
+ if len(got.MediaRefs) != 1 {
+ t.Fatalf("refs = %+v, want exactly one", got.MediaRefs)
+ }
+ if len(ledger.records) != 1 {
+ t.Fatalf("intent records = %d, want 1", len(ledger.records))
+ }
+}
diff --git a/server/internal/integrations/lark/media_ingest.go b/server/internal/integrations/lark/media_ingest.go
new file mode 100644
index 0000000000..61ff82fc75
--- /dev/null
+++ b/server/internal/integrations/lark/media_ingest.go
@@ -0,0 +1,421 @@
+package lark
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "log/slog"
+ "mime"
+ "path"
+ "strings"
+
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
+)
+
+type mediaStorage interface {
+ Upload(ctx context.Context, key string, data []byte, contentType string, filename string) (string, error)
+ // ObjectURL is the URL a successful upload of key returns — a pure
+ // function of configuration, so the intent ledger can persist it BEFORE
+ // the PUT.
+ ObjectURL(key string) string
+}
+
+type mediaStreamStorage interface {
+ UploadStream(ctx context.Context, key string, data io.Reader, sizeBytes int64, contentType string, filename string) (string, error)
+}
+
+type messageResourceStreamer interface {
+ DownloadMessageResourceStream(ctx context.Context, creds InstallationCredentials, p DownloadResourceParams) (DownloadedResourceStream, error)
+}
+
+type feishuMediaResolver struct {
+ api APIClient
+ creds CredentialsResolver
+ storage mediaStorage
+ ledger engine.MediaIntentLedger
+ logger *slog.Logger
+}
+
+func NewFeishuMediaResolver(api APIClient, creds CredentialsResolver, storage mediaStorage, ledger engine.MediaIntentLedger, logger *slog.Logger) engine.MediaResolver {
+ if logger == nil {
+ logger = slog.Default()
+ }
+ return &feishuMediaResolver{api: api, creds: creds, storage: storage, ledger: ledger, logger: logger}
+}
+
+// HasMedia reports whether the message carries downloadable Feishu resources
+// (standalone image/video or post-embedded img/media spans). Pure in-memory
+// decode of the already-received payload — it runs on the connector ACK path.
+func (r *feishuMediaResolver) HasMedia(msg channel.InboundMessage) bool {
+ lm, err := larkMsgFromRaw(msg)
+ if err != nil {
+ return false
+ }
+ return len(mediaResourcesFromMessage(lm)) > 0
+}
+
+func (r *feishuMediaResolver) ResolveMedia(ctx context.Context, inst engine.ResolvedInstallation, _ engine.ResolvedIdentity, _ pgtype.UUID, chatMessageID pgtype.UUID, msg channel.InboundMessage) channel.InboundMessage {
+ lm, err := larkMsgFromRaw(msg)
+ if err != nil {
+ r.logMediaWarn("lark media ingest skipped: raw decode failed", InboundMessage{MessageID: msg.MessageID}, err)
+ return msg
+ }
+ resources := mediaResourcesFromMessage(lm)
+ if len(resources) == 0 {
+ return msg
+ }
+ if r.api == nil || r.creds == nil || r.storage == nil || r.ledger == nil {
+ r.logMediaWarn("lark media ingest skipped: missing dependency", lm, nil)
+ return msg
+ }
+ larkInst, ok := inst.Platform.(Installation)
+ if !ok {
+ r.logMediaWarn("lark media ingest skipped: installation payload unavailable", lm, nil)
+ return msg
+ }
+ creds, err := installationCredentialsFor(larkInst, r.creds)
+ if err != nil {
+ r.logMediaWarn("lark media ingest skipped: credentials unavailable", lm, err)
+ return msg
+ }
+ for _, res := range resources {
+ key := mediaObjectKey(inst, chatMessageID, res)
+ link := r.storage.ObjectURL(key)
+ // Persist the upload intent BEFORE any write can happen. Every
+ // failure from here on — download error, upload error (even one the
+ // store may still be processing), resolve deadline, crash — simply
+ // leaves this row for the reconciler; nothing is ever deleted inline.
+ ok, err := r.ledger.RecordPendingMediaObject(ctx, engine.RecordPendingMediaObjectParams{
+ StorageKey: key,
+ WorkspaceID: inst.WorkspaceID,
+ ChatMessageID: chatMessageID,
+ StorageURL: link,
+ InstallationID: inst.ID,
+ })
+ if err != nil {
+ // No durable intent, no upload — fail-safe direction.
+ r.logMediaWarn("lark media ingest skipped: intent record failed", lm, err)
+ continue
+ }
+ if !ok {
+ // The reconciler owns this key ('deleting'); never resurrect it.
+ r.logMediaWarn("lark media ingest skipped: key owned by reconciler", lm, nil)
+ continue
+ }
+ got, err := r.downloadResource(ctx, creds, DownloadResourceParams{
+ MessageID: res.messageID,
+ FileKey: res.key,
+ Type: res.fetchType,
+ })
+ if err != nil {
+ r.logMediaWarn("lark media download failed", lm, err)
+ continue
+ }
+ contentType := got.ContentType
+ if contentType == "" {
+ contentType = res.mimeType
+ }
+ if contentType == "" {
+ contentType = "application/octet-stream"
+ }
+ filename := mediaFilename(lm, res, got, contentType)
+ uploadedBytes, err := r.uploadResource(ctx, key, got.Body, got.SizeBytes, contentType, filename)
+ if err != nil {
+ // The store may still be processing the PUT — deleting here
+ // could reorder with it. The intent row (written above) covers
+ // the object either way; the reconciler settles it.
+ r.logMediaWarn("lark media upload failed", lm, err)
+ continue
+ }
+ sizeBytes := got.SizeBytes
+ if sizeBytes == 0 {
+ sizeBytes = uploadedBytes
+ }
+ msg.MediaRefs = append(msg.MediaRefs, channel.MediaRef{
+ Type: res.kind,
+ StorageKey: key,
+ StorageURL: link,
+ Filename: filename,
+ MimeType: contentType,
+ SizeBytes: sizeBytes,
+ })
+ }
+ return msg
+}
+
+// mediaObjectKey derives the object key from the CHAT message the object will
+// be attached to, not from the platform message alone: a platform message can
+// be ingested twice (the inbound dedup row is reclaimable once its claim is 60s
+// stale, and vacuumed after 24h), and a shared key would run the second ingest
+// into the first one's ledger row. That row may be a tombstone — the intent
+// upsert refuses anything that has left 'pending', so the second ingest would
+// silently drop its media for as long as the re-delete schedule runs. A key
+// per chat message keeps the ingests independent; nothing leaks, because each
+// one's objects are covered by its own ledger row.
+func mediaObjectKey(inst engine.ResolvedInstallation, chatMessageID pgtype.UUID, res larkMediaResource) string {
+ sum := sha256.Sum256([]byte(uuidString(chatMessageID) + "\x00" + res.messageID + "\x00" + res.fetchType + "\x00" + res.key))
+ return path.Join(
+ "workspaces",
+ uuidString(inst.WorkspaceID),
+ "lark",
+ uuidString(inst.ID),
+ hex.EncodeToString(sum[:]),
+ )
+}
+
+func (r *feishuMediaResolver) downloadResource(ctx context.Context, creds InstallationCredentials, p DownloadResourceParams) (DownloadedResourceStream, error) {
+ if streamer, ok := r.api.(messageResourceStreamer); ok {
+ return streamer.DownloadMessageResourceStream(ctx, creds, p)
+ }
+ got, err := r.api.DownloadMessageResource(ctx, creds, p)
+ if err != nil {
+ return DownloadedResourceStream{}, err
+ }
+ return DownloadedResourceStream{
+ Body: io.NopCloser(bytes.NewReader(got.Data)),
+ ContentType: got.ContentType,
+ Filename: got.Filename,
+ SizeBytes: got.SizeBytes,
+ }, nil
+}
+
+func (r *feishuMediaResolver) uploadResource(ctx context.Context, key string, body io.ReadCloser, sizeBytes int64, contentType string, filename string) (int64, error) {
+ defer body.Close()
+ counter := &countingReader{r: body}
+ if streamStorage, ok := r.storage.(mediaStreamStorage); ok && sizeBytes > 0 {
+ _, err := streamStorage.UploadStream(ctx, key, counter, sizeBytes, contentType, filename)
+ return counter.n, err
+ }
+ // Unknown-length HTTP bodies cannot be sent through S3 PutObject as a
+ // non-seekable stream. The transport already enforces the 100 MiB resource
+ // cap, so buffer this uncommon fallback and use the seekable Upload path.
+ data, err := io.ReadAll(counter)
+ if err != nil {
+ return counter.n, err
+ }
+ _, err = r.storage.Upload(ctx, key, data, contentType, filename)
+ return int64(len(data)), err
+}
+
+type countingReader struct {
+ r io.Reader
+ n int64
+}
+
+func (r *countingReader) Read(p []byte) (int, error) {
+ n, err := r.r.Read(p)
+ r.n += int64(n)
+ return n, err
+}
+
+func (r *feishuMediaResolver) logMediaWarn(msg string, lm InboundMessage, err error) {
+ if r.logger == nil {
+ return
+ }
+ args := []any{"message_id", lm.MessageID, "message_type", lm.MessageType}
+ if err != nil {
+ args = append(args, "err", err)
+ }
+ r.logger.Warn(msg, args...)
+}
+
+type larkMediaResource struct {
+ key string
+ kind channel.MsgType
+ fetchType string
+ filename string
+ mimeType string
+ sizeBytes int64
+ messageID string
+}
+
+func mediaResourcesFromMessage(lm InboundMessage) []larkMediaResource {
+ var payload struct {
+ ImageKey string `json:"image_key"`
+ FileKey string `json:"file_key"`
+ FileName string `json:"file_name"`
+ Name string `json:"name"`
+ MimeType string `json:"mime_type"`
+ ContentType string `json:"content_type"`
+ Size int64 `json:"size"`
+ SizeBytes int64 `json:"size_bytes"`
+ }
+ if lm.Content == "" || json.Unmarshal([]byte(lm.Content), &payload) != nil {
+ return nil
+ }
+ filename := firstNonEmpty(payload.FileName, payload.Name)
+ mimeType := firstNonEmpty(payload.MimeType, payload.ContentType)
+ sizeBytes := payload.SizeBytes
+ if sizeBytes == 0 {
+ sizeBytes = payload.Size
+ }
+ switch lm.MessageType {
+ case "image":
+ if payload.ImageKey == "" {
+ return nil
+ }
+ return []larkMediaResource{{
+ key: payload.ImageKey,
+ kind: channel.MsgTypeImage,
+ fetchType: "image",
+ filename: filename,
+ mimeType: mimeType,
+ sizeBytes: sizeBytes,
+ messageID: lm.MessageID,
+ }}
+ case "post":
+ return mediaResourcesFromPost(lm)
+ case "media", "video":
+ if payload.FileKey == "" {
+ return nil
+ }
+ return []larkMediaResource{{
+ key: payload.FileKey,
+ kind: channel.MsgTypeVideo,
+ fetchType: "file",
+ filename: filename,
+ mimeType: mimeType,
+ sizeBytes: sizeBytes,
+ messageID: lm.MessageID,
+ }}
+ default:
+ return nil
+ }
+}
+
+func mediaResourcesFromPost(lm InboundMessage) []larkMediaResource {
+ if lm.Content == "" {
+ return nil
+ }
+ var doc larkPostContent
+ if err := json.Unmarshal([]byte(lm.Content), &doc); err != nil {
+ return nil
+ }
+ var out []larkMediaResource
+ // A post may reference the same image_key/file_key in more than one span.
+ // The object key is derived from (message, type, key), so duplicates would
+ // upload to the SAME key twice: a later failed attempt could destroy the
+ // object an earlier success already produced (dangling attachment), and a
+ // later success would yield two attachment rows for one object. Collapse
+ // them here, before any upload.
+ seen := make(map[string]bool)
+ for _, para := range doc.Content {
+ for _, span := range para {
+ switch span.Tag {
+ case "img":
+ if span.ImageKey == "" || seen["image\x00"+span.ImageKey] {
+ continue
+ }
+ seen["image\x00"+span.ImageKey] = true
+ out = append(out, larkMediaResource{
+ key: span.ImageKey,
+ kind: channel.MsgTypeImage,
+ fetchType: "image",
+ filename: firstNonEmpty(span.FileName, span.Name),
+ mimeType: span.MimeType,
+ messageID: lm.MessageID,
+ })
+ case "media":
+ if span.FileKey == "" || seen["file\x00"+span.FileKey] {
+ continue
+ }
+ seen["file\x00"+span.FileKey] = true
+ out = append(out, larkMediaResource{
+ key: span.FileKey,
+ kind: channel.MsgTypeVideo,
+ fetchType: "file",
+ filename: firstNonEmpty(span.FileName, span.Name),
+ mimeType: span.MimeType,
+ messageID: lm.MessageID,
+ })
+ }
+ }
+ }
+ return out
+}
+
+func mediaFilename(lm InboundMessage, res larkMediaResource, got DownloadedResourceStream, contentType string) string {
+ for _, candidate := range []string{got.Filename, res.filename} {
+ if name := cleanFilename(candidate); name != "" {
+ return name
+ }
+ }
+ prefix := "feishu-file"
+ switch res.kind {
+ case channel.MsgTypeImage:
+ prefix = "feishu-image"
+ case channel.MsgTypeVideo:
+ prefix = "feishu-video"
+ }
+ return prefix + "-" + safePathSegment(lm.MessageID) + mediaExtension(contentType)
+}
+
+func cleanFilename(name string) string {
+ name = strings.TrimSpace(name)
+ if name == "" {
+ return ""
+ }
+ name = path.Base(strings.ReplaceAll(name, "\\", "/"))
+ if name == "." || name == "/" {
+ return ""
+ }
+ return name
+}
+
+func mediaExtension(contentType string) string {
+ if semi := strings.IndexByte(contentType, ';'); semi >= 0 {
+ contentType = strings.TrimSpace(contentType[:semi])
+ }
+ switch contentType {
+ case "image/jpeg":
+ return ".jpg"
+ case "image/png":
+ return ".png"
+ case "image/gif":
+ return ".gif"
+ case "image/webp":
+ return ".webp"
+ case "video/mp4":
+ return ".mp4"
+ }
+ if exts, err := mime.ExtensionsByType(contentType); err == nil && len(exts) > 0 {
+ return exts[0]
+ }
+ return ""
+}
+
+func safePathSegment(s string) string {
+ s = strings.TrimSpace(s)
+ if s == "" {
+ return "unknown"
+ }
+ var b strings.Builder
+ for _, r := range s {
+ switch {
+ case r >= 'a' && r <= 'z', r >= 'A' && r <= 'Z', r >= '0' && r <= '9', r == '-', r == '_':
+ b.WriteRune(r)
+ default:
+ b.WriteByte('_')
+ }
+ }
+ out := strings.Trim(b.String(), "_")
+ if out == "" {
+ return "unknown"
+ }
+ return out
+}
+
+func firstNonEmpty(values ...string) string {
+ for _, v := range values {
+ if strings.TrimSpace(v) != "" {
+ return strings.TrimSpace(v)
+ }
+ }
+ return ""
+}
diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.go
index 5eae713462..e9893c18c4 100644
--- a/server/internal/integrations/lark/outbound.go
+++ b/server/internal/integrations/lark/outbound.go
@@ -11,6 +11,7 @@ import (
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgtype"
"github.com/multica-ai/multica/server/internal/events"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
db "github.com/multica-ai/multica/server/pkg/db/generated"
"github.com/multica-ai/multica/server/pkg/protocol"
)
@@ -142,6 +143,7 @@ func (defaultRenderer) Render(in RenderInput) (CardRender, error) {
// without a real Postgres connection.
type PatcherQueries interface {
GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)
+ TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)
GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)
GetAgent(ctx context.Context, id pgtype.UUID) (db.Agent, error)
GetLarkInstallation(ctx context.Context, id pgtype.UUID) (Installation, error)
@@ -299,12 +301,18 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {
// Only bound sessions reach here, so classify the task origin before
// spending any send work. Web/mobile direct-chat tasks can reuse a session
// that originated in Lark, but their replies belong only in Multica.
- // Channel-created tasks leave chat_input_task_id NULL and continue below.
+ // Sealed channel tasks own an input batch just like direct tasks, so the
+ // discriminator is the immutable channel_ingested provenance of that
+ // batch, not chat_input_task_id presence (which #5645 originally used).
task, err := p.queries.GetAgentTask(ctx, taskID)
if err != nil {
return fmt.Errorf("load agent task: %w", err)
}
- if task.ChatInputTaskID.Valid {
+ deliver, err := engine.TaskInputIsChannelIngested(ctx, p.queries, task)
+ if err != nil {
+ return fmt.Errorf("classify task input origin: %w", err)
+ }
+ if !deliver {
return nil
}
diff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.go
index 8fd178e30e..b8964710d6 100644
--- a/server/internal/integrations/lark/outbound_test.go
+++ b/server/internal/integrations/lark/outbound_test.go
@@ -17,25 +17,29 @@ import (
)
type fakePatcherQueries struct {
- mu sync.Mutex
- task db.AgentTaskQueue
- taskErr error
- binding ChatSessionBinding
- bindingErr error
- installation Installation
- installationErr error
- agent db.Agent
- agentErr error
- card OutboundCardMessage
- cardErr error
- created []CreateOutboundCardMessageParams
- createReturn OutboundCardMessage
- statusUpdates []UpdateOutboundCardStatusParams
+ mu sync.Mutex
+ task db.AgentTaskQueue
+ taskErr error
+ taskChannelIngested bool
+ binding ChatSessionBinding
+ bindingErr error
+ installation Installation
+ installationErr error
+ agent db.Agent
+ agentErr error
+ card OutboundCardMessage
+ cardErr error
+ created []CreateOutboundCardMessageParams
+ createReturn OutboundCardMessage
+ statusUpdates []UpdateOutboundCardStatusParams
}
func (f *fakePatcherQueries) GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error) {
return f.task, f.taskErr
}
+func (f *fakePatcherQueries) TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error) {
+ return f.taskChannelIngested, nil
+}
func (f *fakePatcherQueries) GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error) {
return db.ChatSession{}, nil
}
@@ -151,6 +155,9 @@ func (f *fakeAPIClient) GetMessage(ctx context.Context, creds InstallationCreden
func (f *fakeAPIClient) ListChatMessages(ctx context.Context, creds InstallationCredentials, p ListMessagesParams) ([]LarkMessage, error) {
return nil, nil
}
+func (f *fakeAPIClient) DownloadMessageResource(ctx context.Context, creds InstallationCredentials, p DownloadResourceParams) (DownloadedResource, error) {
+ return DownloadedResource{}, nil
+}
func (f *fakeAPIClient) BatchGetUsers(ctx context.Context, creds InstallationCredentials, openIDs []string) (map[string]string, error) {
return nil, nil
}
@@ -193,6 +200,34 @@ func newTestPatcher(t *testing.T) (*Patcher, *fakePatcherQueries, *fakeAPIClient
// a plain Lark IM text message (msg_type=text), not nested inside an
// interactive card. This is the load-bearing UX call — the prior card
// chrome made every reply look like a system notification.
+// TestPatcherSendsSealedChannelTaskReply is the other half of the boundary:
+// a sealed channel task owns an input batch exactly like a direct task, so
+// gating outbound on owner presence alone would silently drop every channel
+// reply. Channel provenance must let the reply through.
+func TestPatcherSendsSealedChannelTaskReply(t *testing.T) {
+ p, q, api := newTestPatcher(t)
+ taskID := uuidFromString(t, "ee555555-ee55-ee55-ee55-eeeeeeeeeeee")
+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}
+ q.taskChannelIngested = true
+
+ p.handleEvent(events.Event{
+ Type: protocol.EventChatDone,
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Payload: protocol.ChatDonePayload{
+ TaskID: uuidString(taskID),
+ ChatSessionID: uuidString(q.binding.ChatSessionID),
+ Content: "channel answer",
+ },
+ })
+
+ api.mu.Lock()
+ defer api.mu.Unlock()
+ if len(api.textSent) != 1 || api.textSent[0].Text != "channel answer" {
+ t.Fatalf("sealed channel reply must reach Lark; textSent=%+v", api.textSent)
+ }
+}
+
func TestPatcherSendsPlainTextOnChatDone(t *testing.T) {
p, q, api := newTestPatcher(t)
taskID := uuidFromString(t, "ee333333-ee33-ee33-ee33-eeeeeeeeeeee")
@@ -349,9 +384,9 @@ func TestPatcherSkipsWhenNoChatSessionBinding(t *testing.T) {
// TestPatcherSkipsDirectChatTaskOnBoundSession guards the channel boundary:
// opening a Lark-bound session in the web/mobile UI must not make that direct
-// conversation's reply or failure leak back into the external chat. Direct
-// tasks own an input batch through chat_input_task_id; channel tasks leave it
-// NULL and continue through the existing outbound paths.
+// conversation's reply or failure leak back into the external chat. Sealed
+// channel tasks own an input batch too, so the discriminator is the
+// channel_ingested provenance of the owned batch, not owner presence.
func TestPatcherSkipsDirectChatTaskOnBoundSession(t *testing.T) {
tests := []struct {
name string
diff --git a/server/internal/integrations/lark/outcome_replier_test.go b/server/internal/integrations/lark/outcome_replier_test.go
index 89bb04600a..50ddc8f940 100644
--- a/server/internal/integrations/lark/outcome_replier_test.go
+++ b/server/internal/integrations/lark/outcome_replier_test.go
@@ -90,6 +90,9 @@ func (s *stubAPIClientWithRecorder) GetMessage(ctx context.Context, creds Instal
func (s *stubAPIClientWithRecorder) ListChatMessages(ctx context.Context, creds InstallationCredentials, p ListMessagesParams) ([]LarkMessage, error) {
return nil, nil
}
+func (s *stubAPIClientWithRecorder) DownloadMessageResource(ctx context.Context, creds InstallationCredentials, p DownloadResourceParams) (DownloadedResource, error) {
+ return DownloadedResource{}, nil
+}
func (s *stubAPIClientWithRecorder) BatchGetUsers(ctx context.Context, creds InstallationCredentials, openIDs []string) (map[string]string, error) {
return nil, nil
}
diff --git a/server/internal/integrations/lark/typing_indicator_test.go b/server/internal/integrations/lark/typing_indicator_test.go
index c9a10db3e2..8779fec0fd 100644
--- a/server/internal/integrations/lark/typing_indicator_test.go
+++ b/server/internal/integrations/lark/typing_indicator_test.go
@@ -56,6 +56,9 @@ func (f *fakeTypingAPIClient) GetMessage(context.Context, InstallationCredential
func (f *fakeTypingAPIClient) ListChatMessages(context.Context, InstallationCredentials, ListMessagesParams) ([]LarkMessage, error) {
return nil, nil
}
+func (f *fakeTypingAPIClient) DownloadMessageResource(context.Context, InstallationCredentials, DownloadResourceParams) (DownloadedResource, error) {
+ return DownloadedResource{}, nil
+}
func (f *fakeTypingAPIClient) BatchGetUsers(context.Context, InstallationCredentials, []string) (map[string]string, error) {
return nil, nil
}
diff --git a/server/internal/integrations/lark/ws_endpoint.go b/server/internal/integrations/lark/ws_endpoint.go
index e48e1a3a44..e3167a636c 100644
--- a/server/internal/integrations/lark/ws_endpoint.go
+++ b/server/internal/integrations/lark/ws_endpoint.go
@@ -10,8 +10,8 @@ import (
"log/slog"
"net/http"
"net/url"
- "strings"
"strconv"
+ "strings"
"time"
)
diff --git a/server/internal/integrations/lark/ws_frame_decoder.go b/server/internal/integrations/lark/ws_frame_decoder.go
index f09dc2b341..4c4578b55b 100644
--- a/server/internal/integrations/lark/ws_frame_decoder.go
+++ b/server/internal/integrations/lark/ws_frame_decoder.go
@@ -73,6 +73,7 @@ func (d *LarkJSONFrameDecoder) Decode(payload []byte, inst Installation) (Inboun
MessageID: evt.Message.MessageID,
SenderOpenID: OpenID(evt.Sender.SenderID.OpenID),
MessageType: evt.Message.MessageType,
+ Content: evt.Message.Content,
CreateTime: evt.Message.CreateTime,
// parent_id / root_id are populated by Lark only in reply
// scenarios. The enricher keys quoted-reply expansion off
@@ -91,16 +92,18 @@ func (d *LarkJSONFrameDecoder) Decode(payload []byte, inst Installation) (Inboun
botUnionID = inst.BotUnionID.String
}
- // text + post are flattened synchronously here (no external calls —
- // the decoder must stay fast and dependency-free). merge_forward
- // leaves Body empty: it needs an HTTP round-trip to expand and is
- // handled downstream by the enricher, which keys off MessageType.
- // Other types (image, file, …) also leave Body empty in this MVP;
- // attachment ingestion is a separate issue.
+ // text + post are flattened synchronously here (no external calls — the
+ // decoder must stay fast and dependency-free). merge_forward leaves Body
+ // empty: it needs an HTTP round-trip to expand and is handled downstream by
+ // the enricher, which keys off MessageType. Standalone media gets a short
+ // visible marker while the channel adapter separately downloads and binds
+ // the binary as a Multica attachment.
switch evt.Message.MessageType {
case "text", "post":
msg.Body = resolveMentions(flattenContent(evt.Message.MessageType, evt.Message.Content),
evt.Message.Mentions, inst.BotOpenID, botUnionID)
+ case "image", "file", "audio", "media", "video":
+ msg.Body = flattenContent(evt.Message.MessageType, evt.Message.Content)
}
// Snapshot the user's own text as the command source BEFORE any
diff --git a/server/internal/integrations/lark/ws_frame_decoder_test.go b/server/internal/integrations/lark/ws_frame_decoder_test.go
index dcc51e54aa..da02c250c3 100644
--- a/server/internal/integrations/lark/ws_frame_decoder_test.go
+++ b/server/internal/integrations/lark/ws_frame_decoder_test.go
@@ -429,7 +429,7 @@ func TestLarkJSONFrameDecoderMessageContentEmptyOnInvalidContentJSON(t *testing.
}
}
-func TestLarkJSONFrameDecoderNonTextMessageHasEmptyBody(t *testing.T) {
+func TestLarkJSONFrameDecoderMediaMessageKeepsPlaceholderAndContent(t *testing.T) {
t.Parallel()
raw := []byte(`{
"type":"event_callback",
@@ -443,8 +443,11 @@ func TestLarkJSONFrameDecoderNonTextMessageHasEmptyBody(t *testing.T) {
if err != nil || !ok {
t.Fatalf("ok=%v err=%v", ok, err)
}
- if msg.Body != "" {
- t.Errorf("Body = %q; non-text messages should have empty body in MVP", msg.Body)
+ if msg.Body != "[Image]" {
+ t.Errorf("Body = %q; want media placeholder", msg.Body)
+ }
+ if msg.Content != `{"image_key":"img1"}` {
+ t.Errorf("Content = %q; want raw media content", msg.Content)
}
if msg.MessageID == "" {
t.Error("MessageID should still be populated for non-text events")
diff --git a/server/internal/integrations/slack/outbound.go b/server/internal/integrations/slack/outbound.go
index 434b256a84..e68cb69040 100644
--- a/server/internal/integrations/slack/outbound.go
+++ b/server/internal/integrations/slack/outbound.go
@@ -14,6 +14,7 @@ import (
"github.com/multica-ai/multica/server/internal/events"
"github.com/multica-ai/multica/server/internal/integrations/channel"
+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"
"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"
@@ -23,6 +24,7 @@ import (
// subscriber needs. *db.Queries satisfies it.
type outboundQueries interface {
GetAgentTask(ctx context.Context, id pgtype.UUID) (db.AgentTaskQueue, error)
+ TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error)
GetChannelChatSessionBindingBySession(ctx context.Context, arg db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error)
GetChannelInstallation(ctx context.Context, arg db.GetChannelInstallationParams) (db.ChannelInstallation, error)
}
@@ -101,7 +103,10 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
// before loading credentials or sending. Web/mobile direct-chat tasks can
// reuse a session that originated in Slack, but their replies belong only in
// Multica. Outbound delivery fails closed when the origin cannot be
- // established; channel-created tasks leave chat_input_task_id NULL and send.
+ // established. Sealed channel tasks own an input batch just like direct
+ // tasks, so the discriminator is the immutable channel_ingested provenance
+ // of that batch, not chat_input_task_id presence (which #5645 originally
+ // used).
taskID, ok := chatDoneTaskID(e)
if !ok {
return nil
@@ -110,7 +115,11 @@ func (o *Outbound) processEvent(ctx context.Context, e events.Event) error {
if err != nil {
return fmt.Errorf("load agent task: %w", err)
}
- if task.ChatInputTaskID.Valid {
+ deliver, err := engine.TaskInputIsChannelIngested(ctx, o.q, task)
+ if err != nil {
+ return fmt.Errorf("classify task input origin: %w", err)
+ }
+ if !deliver {
return nil
}
inst, err := o.q.GetChannelInstallation(ctx, db.GetChannelInstallationParams{
diff --git a/server/internal/integrations/slack/outbound_test.go b/server/internal/integrations/slack/outbound_test.go
index 724e7e98c9..5faa7f6f11 100644
--- a/server/internal/integrations/slack/outbound_test.go
+++ b/server/internal/integrations/slack/outbound_test.go
@@ -23,18 +23,23 @@ func uid(b byte) pgtype.UUID {
}
type fakeOutboundQueries struct {
- binding db.ChannelChatSessionBinding
- bindingErr error
- inst db.ChannelInstallation
- instErr error
- task db.AgentTaskQueue
- taskErr error
+ binding db.ChannelChatSessionBinding
+ bindingErr error
+ inst db.ChannelInstallation
+ instErr error
+ task db.AgentTaskQueue
+ taskErr error
+ taskChannelIngested bool
}
func (f *fakeOutboundQueries) GetAgentTask(context.Context, pgtype.UUID) (db.AgentTaskQueue, error) {
return f.task, f.taskErr
}
+func (f *fakeOutboundQueries) TaskHasChannelIngestedMessages(context.Context, pgtype.UUID) (bool, error) {
+ return f.taskChannelIngested, nil
+}
+
func (f *fakeOutboundQueries) GetChannelChatSessionBindingBySession(context.Context, db.GetChannelChatSessionBindingBySessionParams) (db.ChannelChatSessionBinding, error) {
return f.binding, f.bindingErr
}
@@ -102,6 +107,29 @@ func TestOutbound_SkipsDirectChatTaskOnBoundSlackSession(t *testing.T) {
}
}
+// A sealed channel task owns an input batch exactly like a direct task; the
+// outbound gate must key on channel provenance, not owner presence, or every
+// Slack reply is silently dropped.
+func TestOutbound_PostsSealedChannelTaskReply(t *testing.T) {
+ q := &fakeOutboundQueries{
+ task: db.AgentTaskQueue{ChatInputTaskID: uid(2)},
+ taskChannelIngested: true,
+ binding: db.ChannelChatSessionBinding{
+ InstallationID: uid(1),
+ ChannelChatID: "C123",
+ Config: []byte(`{"channel_id":"C123"}`),
+ },
+ inst: db.ChannelInstallation{ID: uid(1), Status: "active", Config: slackInstallConfigJSON()},
+ }
+ fs := &fakeSender{}
+
+ newTestOutbound(q, fs).handleEvent(chatDoneEvent("00000000-0000-0000-0000-000000000001", "channel answer"))
+
+ if fs.called != 1 {
+ t.Fatalf("sender called %d times, want 1 for a sealed channel task", fs.called)
+ }
+}
+
func TestOutbound_PostsReplyToBoundSlackChannel(t *testing.T) {
q := &fakeOutboundQueries{
// Composite isolation key; real channel + reply thread come from config /
diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.go
index fe3f95ec04..c8a3210551 100644
--- a/server/internal/integrations/slack/resolvers.go
+++ b/server/internal/integrations/slack/resolvers.go
@@ -340,10 +340,21 @@ func (r *sessionBinder) AppendMessage(ctx context.Context, p engine.AppendParams
InstallationID: p.InstallationID,
Body: p.Message.Text,
// Slack text is not enriched, so the command source is the body itself.
- CommandText: p.Message.Text,
- MessageID: p.Message.MessageID,
- ThreadID: replyThread,
- ClaimToken: p.ClaimToken,
+ CommandText: p.Message.Text,
+ MessageID: p.Message.MessageID,
+ ThreadID: replyThread,
+ ClaimToken: p.ClaimToken,
+ MediaPendingSeconds: p.MediaPendingSeconds,
+ })
+}
+
+func (r *sessionBinder) BindMedia(ctx context.Context, p engine.BindMediaParams) error {
+ return r.session.BindMediaRefs(ctx, engine.BindMediaInput{
+ MessageID: p.MessageID,
+ SessionID: p.SessionID,
+ WorkspaceID: p.WorkspaceID,
+ Sender: p.Sender,
+ MediaRefs: p.MediaRefs,
})
}
diff --git a/server/internal/metrics/channel_media.go b/server/internal/metrics/channel_media.go
new file mode 100644
index 0000000000..f6ea71ff3f
--- /dev/null
+++ b/server/internal/metrics/channel_media.go
@@ -0,0 +1,66 @@
+package metrics
+
+import "github.com/prometheus/client_golang/prometheus"
+
+// ChannelMediaReconcilerMetrics observes the media intent-ledger reconciler:
+// how many unreferenced objects it deletes, how many rows it clears because a
+// durable attachment reference exists, how many storage deletes fail (and go
+// to backoff), and the current ledger backlog. Whether the fixed settle/sweep
+// constants ever need a config surface is decided from these numbers.
+type ChannelMediaReconcilerMetrics struct {
+ ObjectsDeleted prometheus.Counter
+ RowsReferenced prometheus.Counter
+ DeleteFailures prometheus.Counter
+ Backlog prometheus.Gauge
+ Tombstones prometheus.Gauge
+ // TombstoneReferenced counts an invariant violation, not routine work:
+ // a tombstone pass found an attachment reading the object it was about to
+ // re-delete. The object is kept; a non-zero value means the per-message
+ // key or the bind's state guard stopped holding and needs investigation.
+ TombstoneReferenced prometheus.Counter
+}
+
+func NewChannelMediaReconcilerMetrics() *ChannelMediaReconcilerMetrics {
+ return &ChannelMediaReconcilerMetrics{
+ ObjectsDeleted: prometheus.NewCounter(prometheus.CounterOpts{
+ Namespace: "multica",
+ Subsystem: "channel_media",
+ Name: "reconciler_objects_deleted_total",
+ Help: "Unreferenced media objects deleted by the reconciler.",
+ }),
+ RowsReferenced: prometheus.NewCounter(prometheus.CounterOpts{
+ Namespace: "multica",
+ Subsystem: "channel_media",
+ Name: "reconciler_rows_referenced_total",
+ Help: "Ledger rows cleared because a durable attachment references the object.",
+ }),
+ DeleteFailures: prometheus.NewCounter(prometheus.CounterOpts{
+ Namespace: "multica",
+ Subsystem: "channel_media",
+ Name: "reconciler_delete_failures_total",
+ Help: "Object-storage deletes that failed and were scheduled for retry.",
+ }),
+ Backlog: prometheus.NewGauge(prometheus.GaugeOpts{
+ Namespace: "multica",
+ Subsystem: "channel_media",
+ Name: "pending_objects",
+ Help: "Live intent rows awaiting bind or reclaim (excludes tombstones).",
+ }),
+ Tombstones: prometheus.NewGauge(prometheus.GaugeOpts{
+ Namespace: "multica",
+ Subsystem: "channel_media",
+ Name: "tombstoned_objects",
+ Help: "Deleted objects still tombstoned for scheduled re-deletion.",
+ }),
+ TombstoneReferenced: prometheus.NewCounter(prometheus.CounterOpts{
+ Namespace: "multica",
+ Subsystem: "channel_media",
+ Name: "reconciler_tombstone_referenced_total",
+ Help: "Tombstone passes that found an attachment referencing the object (invariant violation; the object is kept).",
+ }),
+ }
+}
+
+func (m *ChannelMediaReconcilerMetrics) Collectors() []prometheus.Collector {
+ return []prometheus.Collector{m.ObjectsDeleted, m.RowsReferenced, m.DeleteFailures, m.Backlog, m.Tombstones, m.TombstoneReferenced}
+}
diff --git a/server/internal/metrics/registry.go b/server/internal/metrics/registry.go
index 35fb025b31..34842ae5c2 100644
--- a/server/internal/metrics/registry.go
+++ b/server/internal/metrics/registry.go
@@ -27,9 +27,10 @@ type RegistryOptions struct {
}
type Registry struct {
- Gatherer prometheus.Gatherer
- HTTP *HTTPMetrics
- Business *BusinessMetrics
+ Gatherer prometheus.Gatherer
+ HTTP *HTTPMetrics
+ Business *BusinessMetrics
+ ChannelMedia *ChannelMediaReconcilerMetrics
// Sampler is non-nil only when RegistryOptions.BusinessSampler was
// supplied with a valid Pool. Exposed so the cmd/server entrypoint
// can plumb the same instance into health checks if it ever wants to.
@@ -54,6 +55,9 @@ func NewRegistry(opts RegistryOptions) *Registry {
businessMetrics := NewBusinessMetrics()
reg.MustRegister(businessMetrics.Collectors()...)
+ channelMedia := NewChannelMediaReconcilerMetrics()
+ reg.MustRegister(channelMedia.Collectors()...)
+
if opts.Pool != nil {
reg.MustRegister(NewDBCollector(opts.Pool))
}
@@ -70,10 +74,11 @@ func NewRegistry(opts RegistryOptions) *Registry {
}
return &Registry{
- Gatherer: reg,
- HTTP: httpMetrics,
- Business: businessMetrics,
- Sampler: sampler,
+ Gatherer: reg,
+ HTTP: httpMetrics,
+ Business: businessMetrics,
+ ChannelMedia: channelMedia,
+ Sampler: sampler,
}
}
diff --git a/server/internal/service/attribution_stamp_test.go b/server/internal/service/attribution_stamp_test.go
index 3b15228964..5549c7d527 100644
--- a/server/internal/service/attribution_stamp_test.go
+++ b/server/internal/service/attribution_stamp_test.go
@@ -1266,3 +1266,88 @@ func TestEnqueueChatTaskStampsChatEvidence(t *testing.T) {
t.Errorf("trigger_evidence_ref_id = %s, want chat session %s", util.UUIDToString(evidenceRef), chatSessionID)
}
}
+
+func TestEnqueueChatTaskDefersForChannelMediaAndPromotesWhenReady(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var chatSessionID, priorMessageID, messageID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id)
+ VALUES ($1, $2, $3) RETURNING id`, workspaceID, agentID, userID).Scan(&chatSessionID); err != nil {
+ t.Fatalf("seed chat session: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
+ })
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content)
+ VALUES ($1, 'user', 'first') RETURNING id`, chatSessionID).Scan(&priorMessageID); err != nil {
+ t.Fatalf("seed prior message: %v", err)
+ }
+
+ svc := &TaskService{Queries: q, TxStarter: pool, Bus: events.New()}
+ priorTask, err := svc.EnqueueChatTask(ctx, db.ChatSession{
+ ID: util.MustParseUUID(chatSessionID),
+ AgentID: util.MustParseUUID(agentID),
+ }, util.MustParseUUID(userID), false)
+ if err != nil {
+ t.Fatalf("enqueue prior chat task: %v", err)
+ }
+ deadline := time.Now().Add(time.Minute)
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content, channel_media_pending_until)
+ VALUES ($1, 'user', '[Image]', $2) RETURNING id`, chatSessionID, deadline).Scan(&messageID); err != nil {
+ t.Fatalf("seed pending media message: %v", err)
+ }
+
+ task, err := svc.EnqueueChatTask(ctx, db.ChatSession{
+ ID: util.MustParseUUID(chatSessionID),
+ AgentID: util.MustParseUUID(agentID),
+ }, util.MustParseUUID(userID), false)
+ if err != nil {
+ t.Fatalf("EnqueueChatTask: %v", err)
+ }
+ if task.Status != "deferred" || !task.FireAt.Valid {
+ t.Fatalf("task = status %q fire_at %v, want durable deferred task", task.Status, task.FireAt)
+ }
+ if !task.ChatInputTaskID.Valid || task.ChatInputTaskID.Bytes != task.ID.Bytes {
+ t.Fatalf("task input owner = %s, want self %s", util.UUIDToString(task.ChatInputTaskID), util.UUIDToString(task.ID))
+ }
+ if task.FireAt.Time.Before(deadline.Add(-time.Second)) || task.FireAt.Time.After(deadline.Add(time.Second)) {
+ t.Fatalf("task fire_at = %v, want media deadline %v", task.FireAt.Time, deadline)
+ }
+ var linkedTaskID pgtype.UUID
+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, messageID).Scan(&linkedTaskID); err != nil {
+ t.Fatalf("load sealed media message: %v", err)
+ }
+ if !linkedTaskID.Valid || linkedTaskID.Bytes != task.ID.Bytes {
+ t.Fatalf("message task_id = %s, want %s", util.UUIDToString(linkedTaskID), util.UUIDToString(task.ID))
+ }
+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, priorMessageID).Scan(&linkedTaskID); err != nil {
+ t.Fatalf("load prior sealed message: %v", err)
+ }
+ if !linkedTaskID.Valid || linkedTaskID.Bytes != priorTask.ID.Bytes {
+ t.Fatalf("prior message task_id = %s, want unchanged owner %s", util.UUIDToString(linkedTaskID), util.UUIDToString(priorTask.ID))
+ }
+
+ if err := q.ClearChatMessageChannelMediaPending(ctx, db.ClearChatMessageChannelMediaPendingParams{
+ ID: util.MustParseUUID(messageID),
+ ChatSessionID: util.MustParseUUID(chatSessionID),
+ }); err != nil {
+ t.Fatalf("clear pending media: %v", err)
+ }
+ if err := svc.PromoteChannelChatTasksIfMediaReady(ctx, util.MustParseUUID(chatSessionID)); err != nil {
+ t.Fatalf("PromoteChannelChatTasksIfMediaReady: %v", err)
+ }
+ 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)
+ }
+}
diff --git a/server/internal/service/channel_media_reconciler.go b/server/internal/service/channel_media_reconciler.go
new file mode 100644
index 0000000000..5a173e3d7a
--- /dev/null
+++ b/server/internal/service/channel_media_reconciler.go
@@ -0,0 +1,372 @@
+package service
+
+import (
+ "context"
+ "log/slog"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/jackc/pgx/v5/pgtype"
+
+ "github.com/multica-ai/multica/server/internal/metrics"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+// The channel-media intent ledger's reconciler settings are fixed constants,
+// not configuration: whether they ever need tuning is decided from the
+// reconciler metrics.
+//
+// What the state machine fences, and what the schedule fences:
+//
+// - bind vs. delete is fenced by STATE. Once a claim flips a row to
+// 'deleting', neither a new upload nor BindMediaRefs can resurrect or
+// attach that key, so the post-claim reference check cannot race a late
+// COMMIT. No timing assumption is involved.
+// - a PUT the client already abandoned cannot be ordered against a DELETE at
+// all: the store may materialize the object after the delete completes.
+// That is fenced by the TOMBSTONE schedule instead of by a single timing
+// bet: after deleting an unreferenced object the row is kept and the
+// object re-deleted on a widening schedule, so a late materialization is
+// reclaimed by a later pass. Escaping requires the object to appear only
+// after the whole schedule has elapsed (see channelMediaTombstoneRedelete).
+// Every pass re-checks the reference first: reclaiming an orphan must
+// never outrank keeping an object something durably reads.
+//
+// The settle delay therefore carries no correctness weight for bind/commit and
+// only sets how long the reconciler waits before treating a pending row as
+// abandoned; the tested invariant is settle >> every media/HTTP/DB budget in
+// the pipeline (see cmd/server channel media invariant test).
+//
+// Every deadline below is a DURATION handed to SQL, never a timestamp computed
+// here: Postgres derives settle cutoffs, lease expiry, backoff and re-delete
+// times from its own now(), so replicas with drifting clocks all read the same
+// clock. An app-side timestamp would let a fast replica settle rows whose
+// upload is still in flight, or hand out a lease that is already expired.
+const (
+ // ChannelMediaReconcileSettleDelay is how long a 'pending' row must sit
+ // before the reconciler considers it abandoned. Exported for the
+ // invariant test.
+ ChannelMediaReconcileSettleDelay = 15 * time.Minute
+ // channelMediaReconcileSweepInterval paces the reconciler loop.
+ channelMediaReconcileSweepInterval = time.Minute
+ // channelMediaReconcileLease bounds how long a claimed row stays owned by
+ // a worker before another replica may reclaim it (crash recovery).
+ channelMediaReconcileLease = 2 * time.Minute
+ // channelMediaReconcileBatchLimit bounds one sweep's claim (and thus its
+ // object-storage work) — the reconciler's concurrency is one batch,
+ // processed sequentially.
+ channelMediaReconcileBatchLimit = 50
+ // Backoff for failed object-storage deletes: base << (attempt-1), capped.
+ channelMediaReconcileBackoffBase = time.Minute
+ channelMediaReconcileBackoffCap = time.Hour
+ // channelMediaReconcileDeleteTimeout bounds ONE object-storage DELETE.
+ // The SDK's default HTTP client has no overall request timeout, so a
+ // black-holed connection would otherwise wedge the sequential sweep loop
+ // forever (single-replica deployments have no other worker to take over).
+ // Kept well under the lease so a timed-out delete releases with backoff
+ // before any replica could reclaim the row.
+ channelMediaReconcileDeleteTimeout = 30 * time.Second
+)
+
+// channelMediaTombstoneRedelete is the widening re-delete schedule for a
+// tombstoned row, indexed by the row's tombstone_pass. A PUT abandoned by its
+// client can still materialize the object after the delete, so each entry
+// triggers another idempotent delete; the row is dropped only after the last
+// one. Total coverage ~31h, versus the ~seconds a store keeps an abandoned
+// request alive.
+var channelMediaTombstoneRedelete = []time.Duration{
+ 15 * time.Minute,
+ time.Hour,
+ 6 * time.Hour,
+ 24 * time.Hour,
+}
+
+// MediaObjectDeleter is the single storage capability the reconciler needs —
+// Delete with the error surfaced so failures go to backoff instead of being
+// assumed successful. *storage.S3Storage and *storage.LocalStorage satisfy it.
+type MediaObjectDeleter interface {
+ DeleteObject(ctx context.Context, key string) error
+}
+
+// ChannelMediaReconciler settles the media intent ledger: rows written before
+// each upload and cleared inside the attachment-bind transaction. Whatever is
+// left — upload errors, resolve deadlines, bind failures, ambiguous commits,
+// crashes — is claimed here ('pending' → 'deleting' under a lease), checked
+// for a durable attachment reference AFTER the claim (race-free: a bind can
+// no longer succeed on a claimed key), and then either kept (referenced) or
+// deleted from object storage. It runs as an independent worker so
+// object-storage latency spikes cannot starve any other sweeper.
+type ChannelMediaReconciler struct {
+ Queries *db.Queries
+ Storage MediaObjectDeleter
+ Logger *slog.Logger
+ Metrics *metrics.ChannelMediaReconcilerMetrics
+
+ // deleteTimeout is overridable for deterministic tests.
+ deleteTimeout time.Duration
+}
+
+func (r *ChannelMediaReconciler) logger() *slog.Logger {
+ if r.Logger != nil {
+ return r.Logger
+ }
+ return slog.Default()
+}
+
+// pgInterval carries a duration to SQL so Postgres computes the deadline
+// itself. Every settle/lease/retry decision compares against the database
+// clock, so a replica whose own clock has drifted cannot settle a row early,
+// hand out a lease that is born expired, or compress the tombstone schedule.
+func pgInterval(d time.Duration) pgtype.Interval {
+ return pgtype.Interval{Microseconds: d.Microseconds(), Valid: true}
+}
+
+// Run loops RunOnce until ctx ends. Started as its own goroutine from
+// cmd/server; deliberately not coupled to any other sweeper's cadence.
+func (r *ChannelMediaReconciler) Run(ctx context.Context) {
+ ticker := time.NewTicker(channelMediaReconcileSweepInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-ticker.C:
+ r.RunOnce(ctx)
+ }
+ }
+}
+
+// RunOnce claims one batch of due ledger rows and settles each. All errors
+// are per-row and non-fatal: a row that cannot be settled now backs off and
+// is retried on a later sweep (or by another replica after lease expiry).
+func (r *ChannelMediaReconciler) RunOnce(ctx context.Context) {
+ if r.Storage == nil {
+ // The wiring only builds a reconciler when a storage backend exists,
+ // but a panic here would take down the whole process from a bare
+ // goroutine — keep the invariant local. Claiming without a deleter
+ // would strand rows in 'deleting' until their lease expires, so do
+ // not claim at all.
+ r.logger().Error("channel media reconciler: no storage backend; skipping sweep")
+ return
+ }
+ leaseToken := pgtype.UUID{Bytes: uuid.New(), Valid: true}
+ rows, err := r.Queries.ClaimChannelMediaPendingObjectsForReconcile(ctx, db.ClaimChannelMediaPendingObjectsForReconcileParams{
+ LeaseToken: leaseToken,
+ Lease: pgInterval(channelMediaReconcileLease),
+ SettleDelay: pgInterval(ChannelMediaReconcileSettleDelay),
+ BatchLimit: channelMediaReconcileBatchLimit,
+ })
+ if err != nil {
+ r.logger().Warn("channel media reconciler: claim failed", "error", err)
+ return
+ }
+ for _, row := range rows {
+ r.settle(ctx, row, leaseToken)
+ }
+ if r.Metrics != nil {
+ if counts, err := r.Queries.CountChannelMediaPendingObjects(ctx); err == nil {
+ r.Metrics.Backlog.Set(float64(counts.PendingObjects))
+ r.Metrics.Tombstones.Set(float64(counts.TombstonedObjects))
+ }
+ }
+}
+
+func (r *ChannelMediaReconciler) settle(ctx context.Context, row db.ChannelMediaPendingObject, leaseToken pgtype.UUID) {
+ // Heartbeat the shared batch lease before this row's work: the lease only
+ // ever needs to cover ONE row's worst case (delete timeout << lease, see
+ // the invariant test), not the whole sequential batch. Losing the renewal
+ // means another replica already reclaimed the row after an expiry — skip
+ // it; touching it now would duplicate its delete and fight the new
+ // owner's attempt/backoff accounting.
+ renewed, err := r.Queries.RenewChannelMediaPendingObjectLease(ctx, db.RenewChannelMediaPendingObjectLeaseParams{
+ StorageKey: row.StorageKey,
+ WorkspaceID: row.WorkspaceID,
+ LeaseToken: leaseToken,
+ Lease: pgInterval(channelMediaReconcileLease),
+ })
+ if err != nil {
+ r.logger().Warn("channel media reconciler: lease renew failed; skipping row",
+ "storage_key", row.StorageKey, "error", err)
+ return
+ }
+ if renewed == 0 {
+ r.logger().Info("channel media reconciler: row reclaimed by another worker; skipping",
+ "storage_key", row.StorageKey, "workspace_id", row.WorkspaceID)
+ return
+ }
+ // The reference check runs AFTER the claim flipped the row to 'deleting':
+ // from that point BindMediaRefs cannot attach this key, so a negative
+ // answer is terminal, not a snapshot race. It runs on tombstone passes too:
+ // the object a tombstone re-deletes and the object an attachment reads are
+ // the same key, so skipping the check would let a re-delete manufacture the
+ // dangling attachment this whole ledger exists to prevent.
+ referenced, err := r.Queries.ChannelMediaObjectIsReferenced(ctx, db.ChannelMediaObjectIsReferencedParams{
+ ChatMessageID: row.ChatMessageID,
+ WorkspaceID: row.WorkspaceID,
+ StorageUrl: row.StorageUrl,
+ })
+ if err != nil {
+ r.release(ctx, row, leaseToken, err)
+ return
+ }
+ if referenced {
+ if row.State == tombstonedState {
+ // Unreachable by design — the object key is per (chat message,
+ // resource), so a re-ingest gets its own key and a bind can never
+ // attach a key that has left 'pending'. Reaching it means one of
+ // those invariants broke, and the safe answer to a broken invariant
+ // is to keep the object and raise an anomaly, never to delete a live
+ // object and break the attachment reading it.
+ r.logger().Error("channel media reconciler: tombstoned object is referenced by an attachment; keeping it",
+ "storage_key", row.StorageKey,
+ "workspace_id", row.WorkspaceID,
+ "chat_message_id", row.ChatMessageID,
+ "storage_url", row.StorageUrl,
+ "tombstone_pass", row.TombstonePass)
+ if r.Metrics != nil {
+ r.Metrics.TombstoneReferenced.Inc()
+ }
+ }
+ // The bind landed (its transaction just lost the pending-row race to
+ // an earlier reconciler claim of a slow message, or a redelivered
+ // intent outlived the bind). Keep the object, clear the row.
+ if r.clearRow(ctx, row, leaseToken) {
+ r.logger().Info("channel media reconciler: kept referenced object",
+ "storage_key", row.StorageKey,
+ "workspace_id", row.WorkspaceID,
+ "chat_message_id", row.ChatMessageID)
+ if r.Metrics != nil {
+ r.Metrics.RowsReferenced.Inc()
+ }
+ }
+ return
+ }
+ // Unreferenced: hand off to the shared delete + tombstone tail.
+ r.settleDeletedObject(ctx, row, leaseToken)
+}
+
+// settleDeletedObject deletes the object and then either tombstones the row
+// for a later re-delete pass or, once the schedule is exhausted, clears it.
+// Shared by the first (unreferenced) settle and every tombstone revisit.
+func (r *ChannelMediaReconciler) settleDeletedObject(ctx context.Context, row db.ChannelMediaPendingObject, leaseToken pgtype.UUID) {
+ // The delete runs OUTSIDE any transaction (no DB connection or row lock
+ // held across storage I/O), gated by the lease and bounded by its own
+ // timeout so one stalled connection cannot wedge the sequential sweep.
+ delTimeout := r.deleteTimeout
+ if delTimeout == 0 {
+ delTimeout = channelMediaReconcileDeleteTimeout
+ }
+ delCtx, delCancel := context.WithTimeout(ctx, delTimeout)
+ err := r.Storage.DeleteObject(delCtx, row.StorageKey)
+ delCancel()
+ if err != nil {
+ if r.Metrics != nil {
+ r.Metrics.DeleteFailures.Inc()
+ }
+ r.release(ctx, row, leaseToken, err)
+ return
+ }
+ // The delete succeeded, but an abandoned PUT may still materialize this
+ // object afterwards. Keep the row as a tombstone and re-delete on the
+ // widening schedule; drop it only once the schedule is exhausted.
+ if next, idx, ok := r.nextTombstonePass(row); ok {
+ if r.tombstoneRow(ctx, row, leaseToken, next, idx) {
+ msg := "channel media reconciler: deleted unreferenced object; tombstoned for re-delete"
+ if row.State == tombstonedState {
+ // Re-delete passes are idempotent: usually nothing was there.
+ msg = "channel media reconciler: tombstone re-delete pass done"
+ }
+ r.logger().Info(msg,
+ "storage_key", row.StorageKey,
+ "workspace_id", row.WorkspaceID,
+ "chat_message_id", row.ChatMessageID,
+ "attempt", row.Attempt,
+ "tombstone_pass", idx,
+ "next_redelete_in", next)
+ if r.Metrics != nil && row.State != tombstonedState {
+ // Count the object once, on the delete that first removed it.
+ r.Metrics.ObjectsDeleted.Inc()
+ }
+ }
+ return
+ }
+ if r.clearRow(ctx, row, leaseToken) {
+ r.logger().Info("channel media reconciler: tombstone schedule exhausted; ledger row cleared",
+ "storage_key", row.StorageKey,
+ "workspace_id", row.WorkspaceID,
+ "chat_message_id", row.ChatMessageID,
+ "attempt", row.Attempt)
+ }
+}
+
+const tombstonedState = "tombstoned"
+
+// nextTombstonePass returns the delay before this row's next re-delete pass
+// and the schedule position to record, or ok=false when the schedule is
+// exhausted and the row may be dropped. A row deleted for the first time
+// (state 'deleting') starts at index 0; a tombstone advances from the
+// tombstone_pass its last successful delete recorded, so a failed re-delete
+// in between (which only writes last_error/attempt) cannot restart the walk.
+func (r *ChannelMediaReconciler) nextTombstonePass(row db.ChannelMediaPendingObject) (delay time.Duration, idx int, ok bool) {
+ idx = 0
+ if row.State == tombstonedState {
+ idx = int(row.TombstonePass) + 1
+ }
+ if idx >= len(channelMediaTombstoneRedelete) {
+ return 0, 0, false
+ }
+ return channelMediaTombstoneRedelete[idx], idx, true
+}
+
+func (r *ChannelMediaReconciler) tombstoneRow(ctx context.Context, row db.ChannelMediaPendingObject, leaseToken pgtype.UUID, next time.Duration, idx int) bool {
+ n, err := r.Queries.TombstoneChannelMediaPendingObject(ctx, db.TombstoneChannelMediaPendingObjectParams{
+ StorageKey: row.StorageKey,
+ WorkspaceID: row.WorkspaceID,
+ LeaseToken: leaseToken,
+ RedeleteDelay: pgInterval(next),
+ TombstonePass: int32(idx),
+ })
+ if err != nil {
+ r.logger().Warn("channel media reconciler: tombstone failed", "storage_key", row.StorageKey, "error", err)
+ return false
+ }
+ return n > 0
+}
+
+// release keeps the row in 'deleting' (a bind must still never attach it),
+// drops the lease, and backs off the next attempt.
+func (r *ChannelMediaReconciler) release(ctx context.Context, row db.ChannelMediaPendingObject, leaseToken pgtype.UUID, cause error) {
+ backoff := channelMediaReconcileBackoffBase << min(row.Attempt-1, 10)
+ if backoff > channelMediaReconcileBackoffCap || backoff <= 0 {
+ backoff = channelMediaReconcileBackoffCap
+ }
+ r.logger().Warn("channel media reconciler: settle failed; backing off",
+ "storage_key", row.StorageKey,
+ "workspace_id", row.WorkspaceID,
+ "attempt", row.Attempt,
+ "backoff", backoff,
+ "error", cause)
+ if err := r.Queries.ReleaseChannelMediaPendingObject(ctx, db.ReleaseChannelMediaPendingObjectParams{
+ StorageKey: row.StorageKey,
+ WorkspaceID: row.WorkspaceID,
+ LeaseToken: leaseToken,
+ Backoff: pgInterval(backoff),
+ LastError: pgtype.Text{String: cause.Error(), Valid: true},
+ }); err != nil {
+ // The lease expiry reclaims the row regardless.
+ r.logger().Warn("channel media reconciler: release failed", "storage_key", row.StorageKey, "error", err)
+ }
+}
+
+func (r *ChannelMediaReconciler) clearRow(ctx context.Context, row db.ChannelMediaPendingObject, leaseToken pgtype.UUID) bool {
+ n, err := r.Queries.DeleteChannelMediaPendingObject(ctx, db.DeleteChannelMediaPendingObjectParams{
+ StorageKey: row.StorageKey,
+ WorkspaceID: row.WorkspaceID,
+ LeaseToken: leaseToken,
+ })
+ if err != nil {
+ r.logger().Warn("channel media reconciler: clear row failed", "storage_key", row.StorageKey, "error", err)
+ return false
+ }
+ return n > 0
+}
diff --git a/server/internal/service/channel_media_reconciler_test.go b/server/internal/service/channel_media_reconciler_test.go
new file mode 100644
index 0000000000..ce64e1d7fc
--- /dev/null
+++ b/server/internal/service/channel_media_reconciler_test.go
@@ -0,0 +1,718 @@
+package service
+
+import (
+ "context"
+ "errors"
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgtype"
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/prometheus/client_golang/prometheus/testutil"
+
+ "github.com/multica-ai/multica/server/internal/metrics"
+ "github.com/multica-ai/multica/server/internal/util"
+ db "github.com/multica-ai/multica/server/pkg/db/generated"
+)
+
+type fakeObjectDeleter struct {
+ mu sync.Mutex
+ deleted []string
+ err error
+ onDelete func(key string)
+}
+
+func (f *fakeObjectDeleter) DeleteObject(_ context.Context, key string) error {
+ f.mu.Lock()
+ hook := f.onDelete
+ f.mu.Unlock()
+ if hook != nil {
+ hook(key)
+ }
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if f.err != nil {
+ return f.err
+ }
+ f.deleted = append(f.deleted, key)
+ return nil
+}
+
+func (f *fakeObjectDeleter) deletedKeys() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]string(nil), f.deleted...)
+}
+
+type reconcilerFixture struct {
+ pool *pgxpool.Pool
+ workspaceID string
+ sessionID string
+ messageID string
+}
+
+func seedReconcilerFixture(t *testing.T, pool *pgxpool.Pool) reconcilerFixture {
+ t.Helper()
+ ctx := context.Background()
+ suffix := time.Now().UnixNano()
+ f := reconcilerFixture{pool: pool}
+
+ var userID, runtimeID, agentID string
+ if err := pool.QueryRow(ctx, `INSERT INTO "user" (name, email) VALUES ($1, $2) RETURNING id`,
+ "Reconciler test", fmt.Sprintf("media-reconciler-%[email protected]", suffix)).Scan(&userID); err != nil {
+ t.Fatalf("create user: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `INSERT INTO workspace (name, slug, description) VALUES ($1, $2, '') RETURNING id`,
+ "Reconciler test", fmt.Sprintf("media-reconciler-%d", suffix)).Scan(&f.workspaceID); err != nil {
+ t.Fatalf("create workspace: %v", err)
+ }
+ t.Cleanup(func() {
+ cleanupCtx := context.Background()
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM channel_media_pending_object WHERE workspace_id = $1`, f.workspaceID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM workspace WHERE id = $1`, f.workspaceID)
+ _, _ = pool.Exec(cleanupCtx, `DELETE FROM "user" WHERE id = $1`, userID)
+ })
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent_runtime (workspace_id, name, runtime_mode, provider, owner_id)
+ VALUES ($1, $2, 'local', 'multica_daemon', $3) RETURNING id`,
+ f.workspaceID, fmt.Sprintf("media-reconciler-rt-%d", suffix), userID).Scan(&runtimeID); err != nil {
+ t.Fatalf("create runtime: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO agent (workspace_id, name, runtime_mode, runtime_id, owner_id)
+ VALUES ($1, $2, 'local', $3, $4) RETURNING id`,
+ f.workspaceID, fmt.Sprintf("media-reconciler-agent-%d", suffix), runtimeID, userID).Scan(&agentID); err != nil {
+ t.Fatalf("create agent: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id, title)
+ VALUES ($1, $2, $3, 'reconciler test') RETURNING id`,
+ f.workspaceID, agentID, userID).Scan(&f.sessionID); err != nil {
+ t.Fatalf("create chat session: %v", err)
+ }
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content, channel_ingested)
+ VALUES ($1, 'user', '[Image]', TRUE) RETURNING id`, f.sessionID).Scan(&f.messageID); err != nil {
+ t.Fatalf("create chat message: %v", err)
+ }
+ return f
+}
+
+// seedLedgerRow inserts a ledger row with a controllable age and state.
+func (f reconcilerFixture) seedLedgerRow(t *testing.T, key, url, state string, age time.Duration) {
+ t.Helper()
+ if _, err := f.pool.Exec(context.Background(), `
+ INSERT INTO channel_media_pending_object (storage_key, workspace_id, chat_message_id, storage_url, state, created_at, next_attempt_at)
+ VALUES ($1, $2, $3, $4, $5, now() - $6::interval, now() - $6::interval)
+ `, key, f.workspaceID, f.messageID, url, state, age.String()); err != nil {
+ t.Fatalf("seed ledger row: %v", err)
+ }
+}
+
+func (f reconcilerFixture) rowState(t *testing.T, key string) (state string, attempt int, exists bool) {
+ t.Helper()
+ err := f.pool.QueryRow(context.Background(), `
+ SELECT state, attempt FROM channel_media_pending_object WHERE storage_key = $1
+ `, key).Scan(&state, &attempt)
+ if err != nil {
+ return "", 0, false
+ }
+ return state, attempt, true
+}
+
+func (f reconcilerFixture) tombstonePass(t *testing.T, key string) int {
+ t.Helper()
+ var pass int
+ if err := f.pool.QueryRow(context.Background(), `
+ SELECT tombstone_pass FROM channel_media_pending_object WHERE storage_key = $1
+ `, key).Scan(&pass); err != nil {
+ t.Fatalf("read tombstone_pass: %v", err)
+ }
+ return pass
+}
+
+// makeDue moves a row's next_attempt_at into the past so the next sweep claims
+// it, without waiting out the real schedule.
+func (f reconcilerFixture) makeDue(t *testing.T, key string) {
+ t.Helper()
+ if _, err := f.pool.Exec(context.Background(), `
+ UPDATE channel_media_pending_object SET next_attempt_at = now() - interval '1 second' WHERE storage_key = $1
+ `, key); err != nil {
+ t.Fatalf("make row due: %v", err)
+ }
+}
+
+// deadlines reads the row's lease/retry deadlines together with the DATABASE's
+// own now(), so a test can assert which clock produced them.
+func (f reconcilerFixture) deadlines(t *testing.T, key string) (lease, next, dbNow time.Time) {
+ t.Helper()
+ var l, n pgtype.Timestamptz
+ if err := f.pool.QueryRow(context.Background(), `
+ SELECT lease_expires_at, next_attempt_at, now() FROM channel_media_pending_object WHERE storage_key = $1
+ `, key).Scan(&l, &n, &dbNow); err != nil {
+ t.Fatalf("read deadlines: %v", err)
+ }
+ return l.Time, n.Time, dbNow
+}
+
+func (f reconcilerFixture) bindAttachment(t *testing.T, url string) {
+ t.Helper()
+ if _, err := f.pool.Exec(context.Background(), `
+ INSERT INTO attachment (workspace_id, chat_session_id, chat_message_id, uploader_type, uploader_id, filename, url, content_type, size_bytes)
+ SELECT $1, $2, $3, 'member', creator_id, 'img.png', $4, 'image/png', 1
+ FROM chat_session WHERE id = $2
+ `, f.workspaceID, f.sessionID, f.messageID, url); err != nil {
+ t.Fatalf("bind attachment: %v", err)
+ }
+}
+
+// The reconciler's three terminal states: a referenced object is kept (row
+// cleared), an unreferenced settled object is deleted (row cleared), and a
+// row younger than the settle delay is untouched.
+func TestChannelMediaReconciler_SettlesThreeStates(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ deleter := &fakeObjectDeleter{}
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: deleter}
+
+ f.seedLedgerRow(t, "ws/lark/referenced", "https://cdn.test/referenced", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+ f.bindAttachment(t, "https://cdn.test/referenced")
+ f.seedLedgerRow(t, "ws/lark/orphan", "https://cdn.test/orphan", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+ f.seedLedgerRow(t, "ws/lark/young", "https://cdn.test/young", "pending", time.Minute)
+
+ rec.RunOnce(context.Background())
+
+ if _, _, exists := f.rowState(t, "ws/lark/referenced"); exists {
+ t.Fatal("referenced row must be cleared")
+ }
+ // The deleted orphan is kept as a tombstone (scheduled re-delete) rather
+ // than cleared, so an abandoned PUT materializing later is still reclaimed.
+ if state, _, exists := f.rowState(t, "ws/lark/orphan"); !exists || state != "tombstoned" {
+ t.Fatalf("orphan row = (%q, %v), want a 'tombstoned' row after its delete", state, exists)
+ }
+ if state, _, exists := f.rowState(t, "ws/lark/young"); !exists || state != "pending" {
+ t.Fatalf("young row = (%q, %v), want untouched 'pending'", state, exists)
+ }
+ deleted := deleter.deletedKeys()
+ if len(deleted) != 1 || deleted[0] != "ws/lark/orphan" {
+ t.Fatalf("deleted keys = %v, want only the orphan", deleted)
+ }
+}
+
+// A worker that claimed rows and crashed: the rows sit in 'deleting' with an
+// expired lease and must be reclaimable by the next sweep.
+func TestChannelMediaReconciler_ReclaimsExpiredLease(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ deleter := &fakeObjectDeleter{}
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: deleter}
+
+ f.seedLedgerRow(t, "ws/lark/crashed", "https://cdn.test/crashed", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+ if _, err := pool.Exec(context.Background(), `
+ UPDATE channel_media_pending_object
+ SET state = 'deleting', lease_token = $2, lease_expires_at = now() - interval '1 minute'
+ WHERE storage_key = $1
+ `, "ws/lark/crashed", util.MustParseUUID("99999999-9999-4999-8999-999999999999")); err != nil {
+ t.Fatalf("simulate crashed claim: %v", err)
+ }
+
+ rec.RunOnce(context.Background())
+
+ if state, _, exists := f.rowState(t, "ws/lark/crashed"); !exists || state != "tombstoned" {
+ t.Fatalf("expired-lease row = (%q, %v), want reclaimed and settled to 'tombstoned'", state, exists)
+ }
+ if deleted := deleter.deletedKeys(); len(deleted) != 1 || deleted[0] != "ws/lark/crashed" {
+ t.Fatalf("deleted keys = %v, want the reclaimed key", deleted)
+ }
+}
+
+// A failed object-storage DELETE keeps the row in 'deleting' (bind must never
+// attach it), releases the lease, and backs off; a later sweep after
+// next_attempt_at retries and settles it.
+func TestChannelMediaReconciler_DeleteFailureBacksOffThenRetries(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ deleter := &fakeObjectDeleter{err: errors.New("storage unavailable")}
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: deleter}
+
+ f.seedLedgerRow(t, "ws/lark/flaky", "https://cdn.test/flaky", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+ rec.RunOnce(context.Background())
+
+ state, attempt, exists := f.rowState(t, "ws/lark/flaky")
+ if !exists || state != "deleting" || attempt != 1 {
+ t.Fatalf("row after failed delete = (%q, attempt=%d, %v), want ('deleting', 1, true)", state, attempt, exists)
+ }
+ var due bool
+ if err := pool.QueryRow(context.Background(), `
+ SELECT next_attempt_at > now() FROM channel_media_pending_object WHERE storage_key = $1
+ `, "ws/lark/flaky").Scan(&due); err != nil || !due {
+ t.Fatalf("failed delete must back off next_attempt_at (future=%v, err=%v)", due, err)
+ }
+
+ // Immediately re-running must NOT retry (backoff in effect).
+ rec.RunOnce(context.Background())
+ if _, attempt2, _ := f.rowState(t, "ws/lark/flaky"); attempt2 != 1 {
+ t.Fatalf("backoff violated: attempt = %d, want still 1", attempt2)
+ }
+
+ // Force the backoff to expire; the retry (with a healthy store) settles.
+ if _, err := pool.Exec(context.Background(), `
+ UPDATE channel_media_pending_object SET next_attempt_at = now() WHERE storage_key = $1
+ `, "ws/lark/flaky"); err != nil {
+ t.Fatalf("expire backoff: %v", err)
+ }
+ deleter.mu.Lock()
+ deleter.err = nil
+ deleter.mu.Unlock()
+ rec.RunOnce(context.Background())
+ if state, _, exists := f.rowState(t, "ws/lark/flaky"); !exists || state != "tombstoned" {
+ t.Fatalf("retried delete row = (%q, %v), want settled to 'tombstoned'", state, exists)
+ }
+}
+
+// Bind-wins interleaving at the DB level: a 'pending' row is NOT claimable by
+// the reconciler once the bind transaction deleted it; and the reconciler's
+// claim query never touches rows in other workspaces' scope implicitly — the
+// claim is keyed off due-time and state only, but every settle decision joins
+// through the row's own workspace_id.
+func TestChannelMediaReconciler_LeavesFreshPendingToBind(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ deleter := &fakeObjectDeleter{}
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: deleter}
+
+ // The row a live bind is about to claim: younger than settle.
+ f.seedLedgerRow(t, "ws/lark/inflight", "https://cdn.test/inflight", "pending", time.Second)
+ rec.RunOnce(context.Background())
+ if state, _, exists := f.rowState(t, "ws/lark/inflight"); !exists || state != "pending" {
+ t.Fatalf("in-flight row = (%q, %v), want untouched so the bind can claim it", state, exists)
+ }
+ // The bind claims it exactly like BindMediaRefs does (state-guarded).
+ tag, err := pool.Exec(context.Background(), `
+ DELETE FROM channel_media_pending_object WHERE storage_key = $1 AND state = 'pending'
+ `, "ws/lark/inflight")
+ if err != nil || tag.RowsAffected() != 1 {
+ t.Fatalf("bind-side claim failed: rows=%d err=%v", tag.RowsAffected(), err)
+ }
+ if len(deleter.deletedKeys()) != 0 {
+ t.Fatalf("nothing should have been deleted: %v", deleter.deletedKeys())
+ }
+}
+
+func TestChannelMediaReconciler_SettleInvariantDwarfsPipelineBudgets(t *testing.T) {
+ // The settle delay is an operational buffer with NO correctness weight —
+ // correctness comes from the 'deleting' state flip. This invariant only
+ // guarantees the reconciler is never doing wasted work while a healthy
+ // pipeline is still running: it must dwarf every inline budget.
+ const maxPipelineBudget = 45 * time.Second // engine media budget / lark download cap (see cmd/server invariant test for the cross-package assertion)
+ if ChannelMediaReconcileSettleDelay < 10*maxPipelineBudget {
+ t.Fatalf("settle %v must be >= 10x the largest pipeline budget %v", ChannelMediaReconcileSettleDelay, maxPipelineBudget)
+ }
+ if channelMediaReconcileLease <= 0 || channelMediaReconcileLease >= ChannelMediaReconcileSettleDelay {
+ t.Fatalf("lease %v must be positive and well under settle %v", channelMediaReconcileLease, ChannelMediaReconcileSettleDelay)
+ }
+ // The lease is heartbeated per row, so it only ever needs to cover ONE
+ // row's worst case (a delete at its full timeout plus DB round-trips) —
+ // never the whole sequential batch. 2x margin keeps renewal comfortably
+ // ahead of expiry.
+ if channelMediaReconcileLease < 2*channelMediaReconcileDeleteTimeout {
+ t.Fatalf("lease %v must be >= 2x the per-delete timeout %v", channelMediaReconcileLease, channelMediaReconcileDeleteTimeout)
+ }
+}
+
+// Storage initialization can fail at boot (no S3, unwritable local dir) while
+// ledger rows pre-exist from an earlier boot where storage worked. A nil
+// deleter must never panic the worker — and must not claim rows either, or
+// they would sit stranded in 'deleting' until lease expiry.
+func TestChannelMediaReconciler_NilStorageSkipsSweepWithoutClaiming(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: nil}
+
+ f.seedLedgerRow(t, "ws/lark/nil-storage", "https://cdn.test/nil-storage", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+ rec.RunOnce(context.Background())
+
+ state, attempt, exists := f.rowState(t, "ws/lark/nil-storage")
+ if !exists || state != "pending" || attempt != 0 {
+ t.Fatalf("row = (%q, attempt=%d, %v), want untouched 'pending' when storage is missing", state, attempt, exists)
+ }
+}
+
+// Tenancy is enforced on every settle operation, not derived from the key
+// string: release and delete with the right lease but the wrong workspace
+// must touch nothing.
+func TestChannelMediaReconciler_WrongWorkspaceCannotReleaseOrDelete(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ q := db.New(pool)
+
+ key := "ws/lark/tenancy"
+ f.seedLedgerRow(t, key, "https://cdn.test/tenancy", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+ lease := util.MustParseUUID("88888888-8888-4888-8888-888888888888")
+ if _, err := pool.Exec(context.Background(), `
+ UPDATE channel_media_pending_object SET state = 'deleting', lease_token = $2 WHERE storage_key = $1
+ `, key, lease); err != nil {
+ t.Fatalf("claim row: %v", err)
+ }
+ otherWorkspace := util.MustParseUUID("77777777-7777-4777-8777-777777777777")
+
+ if err := q.ReleaseChannelMediaPendingObject(context.Background(), db.ReleaseChannelMediaPendingObjectParams{
+ StorageKey: key,
+ WorkspaceID: otherWorkspace,
+ LeaseToken: lease,
+ Backoff: pgInterval(time.Hour),
+ LastError: pgtype.Text{String: "cross-tenant", Valid: true},
+ }); err != nil {
+ t.Fatalf("release: %v", err)
+ }
+ n, err := q.DeleteChannelMediaPendingObject(context.Background(), db.DeleteChannelMediaPendingObjectParams{
+ StorageKey: key,
+ WorkspaceID: otherWorkspace,
+ LeaseToken: lease,
+ })
+ if err != nil {
+ t.Fatalf("delete: %v", err)
+ }
+ if n != 0 {
+ t.Fatalf("cross-workspace delete removed %d rows, want 0", n)
+ }
+
+ var state string
+ var leaseStillHeld bool
+ if err := pool.QueryRow(context.Background(), `
+ SELECT state, lease_token IS NOT NULL FROM channel_media_pending_object WHERE storage_key = $1
+ `, key).Scan(&state, &leaseStillHeld); err != nil {
+ t.Fatalf("load row: %v", err)
+ }
+ if state != "deleting" || !leaseStillHeld {
+ t.Fatalf("row = (state=%q, lease_held=%v), want untouched ('deleting', true)", state, leaseStillHeld)
+ }
+}
+
+// blockingDeleter hangs until its context ends — the black-holed-connection
+// shape. The per-delete timeout must bound it so one stalled DELETE cannot
+// wedge the sequential sweep, and the row must go to backoff.
+type blockingDeleter struct{}
+
+func (blockingDeleter) DeleteObject(ctx context.Context, _ string) error {
+ <-ctx.Done()
+ return ctx.Err()
+}
+
+func TestChannelMediaReconciler_StalledDeleteIsBoundedAndBacksOff(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: blockingDeleter{}, deleteTimeout: 50 * time.Millisecond}
+
+ f.seedLedgerRow(t, "ws/lark/stalled", "https://cdn.test/stalled", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+
+ start := time.Now()
+ rec.RunOnce(context.Background())
+ if elapsed := time.Since(start); elapsed > 5*time.Second {
+ t.Fatalf("stalled delete wedged the sweep for %v", elapsed)
+ }
+ state, attempt, exists := f.rowState(t, "ws/lark/stalled")
+ if !exists || state != "deleting" || attempt != 1 {
+ t.Fatalf("row = (%q, attempt=%d, %v), want released 'deleting' with backoff", state, attempt, exists)
+ }
+}
+
+// The batch shares one claim but the lease is heartbeated per row: a row
+// reclaimed by another replica mid-batch (its lease expired while earlier
+// deletes ran long) must be skipped — no duplicate delete, no clobbered
+// attempt/backoff on the new owner's row.
+func TestChannelMediaReconciler_SkipsRowReclaimedMidBatch(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ foreign := util.MustParseUUID("66666666-6666-4666-8666-666666666666")
+ deleter := &fakeObjectDeleter{}
+ // While row 1's delete runs, another replica reclaims row 2 (its shared
+ // lease "expired"): simulated by swapping in a foreign lease token.
+ deleter.onDelete = func(key string) {
+ if key != "ws/lark/first" {
+ return
+ }
+ if _, err := pool.Exec(context.Background(), `
+ UPDATE channel_media_pending_object
+ SET lease_token = $2, attempt = attempt + 1
+ WHERE storage_key = $1
+ `, "ws/lark/second", foreign); err != nil {
+ t.Errorf("simulate reclaim: %v", err)
+ }
+ }
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: deleter}
+
+ // Ordered by next_attempt_at: "first" is older, processed first.
+ f.seedLedgerRow(t, "ws/lark/first", "https://cdn.test/first", "pending", ChannelMediaReconcileSettleDelay+2*time.Minute)
+ f.seedLedgerRow(t, "ws/lark/second", "https://cdn.test/second", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+
+ rec.RunOnce(context.Background())
+
+ if deleted := deleter.deletedKeys(); len(deleted) != 1 || deleted[0] != "ws/lark/first" {
+ t.Fatalf("deleted keys = %v, want only the first row (second was reclaimed)", deleted)
+ }
+ state, attempt, exists := f.rowState(t, "ws/lark/second")
+ if !exists || state != "deleting" || attempt != 2 {
+ t.Fatalf("reclaimed row = (%q, attempt=%d, %v), want untouched under the new owner ('deleting', 2, true)", state, attempt, exists)
+ }
+ var token pgtype.UUID
+ if err := pool.QueryRow(context.Background(), `
+ SELECT lease_token FROM channel_media_pending_object WHERE storage_key = $1
+ `, "ws/lark/second").Scan(&token); err != nil {
+ t.Fatalf("load lease: %v", err)
+ }
+ if token != foreign {
+ t.Fatalf("lease token = %v, want the new owner's %v", token, foreign)
+ }
+}
+
+// reappearingDeleter models an object store where a PUT the client had already
+// abandoned materializes the object AFTER the reconciler's DELETE completed —
+// the interleaving no DELETE can be ordered against. present tracks whether
+// the object currently exists.
+type reappearingDeleter struct {
+ mu sync.Mutex
+ present bool
+ deleteCalls int
+ lateMaterial func(call int) bool
+}
+
+func (d *reappearingDeleter) DeleteObject(_ context.Context, _ string) error {
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ d.deleteCalls++
+ d.present = false
+ // The abandoned PUT lands right after this delete returned.
+ if d.lateMaterial != nil && d.lateMaterial(d.deleteCalls) {
+ d.present = true
+ }
+ return nil
+}
+
+func (d *reappearingDeleter) state(t *testing.T) (present bool, calls int) {
+ t.Helper()
+ d.mu.Lock()
+ defer d.mu.Unlock()
+ return d.present, d.deleteCalls
+}
+
+// The blocking gap the reviewer identified: DELETE completes, the ledger row
+// would be cleared, and only then does the abandoned PUT materialize the
+// object — leaving an orphan nothing could reclaim. The tombstone schedule
+// closes it: the row survives the delete and each due pass re-deletes, so a
+// late materialization is reclaimed by a later pass and no object survives.
+func TestChannelMediaReconciler_LatePutAfterDeleteIsReclaimedByTombstone(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ // The object reappears exactly once, right after the first delete.
+ deleter := &reappearingDeleter{present: true, lateMaterial: func(call int) bool { return call == 1 }}
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: deleter}
+ key := "ws/lark/late-put"
+ f.seedLedgerRow(t, key, "https://cdn.test/late-put", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+
+ // Pass 1: deletes the orphan; the abandoned PUT lands immediately after.
+ rec.RunOnce(context.Background())
+ present, calls := deleter.state(t)
+ if calls != 1 || !present {
+ t.Fatalf("after first pass: calls=%d present=%v, want 1/true (late PUT landed)", calls, present)
+ }
+ state, _, exists := f.rowState(t, key)
+ if !exists || state != "tombstoned" {
+ t.Fatalf("row = (%q, %v), want a surviving 'tombstoned' row to catch the late object", state, exists)
+ }
+
+ // Walk the whole re-delete schedule; each pass must re-delete.
+ for pass := 2; pass <= len(channelMediaTombstoneRedelete); pass++ {
+ if _, err := pool.Exec(context.Background(), `
+ UPDATE channel_media_pending_object SET next_attempt_at = now() - interval '1 second' WHERE storage_key = $1
+ `, key); err != nil {
+ t.Fatalf("make tombstone due: %v", err)
+ }
+ rec.RunOnce(context.Background())
+ if _, calls := deleter.state(t); calls != pass {
+ t.Fatalf("pass %d: delete calls = %d, want %d", pass, calls, pass)
+ }
+ }
+
+ // The late object is gone and the schedule is exhausted, so the row clears.
+ if present, _ := deleter.state(t); present {
+ t.Fatal("late-materialized object survived the tombstone schedule")
+ }
+ if _, err := pool.Exec(context.Background(), `
+ UPDATE channel_media_pending_object SET next_attempt_at = now() - interval '1 second' WHERE storage_key = $1
+ `, key); err != nil {
+ t.Fatalf("make tombstone due: %v", err)
+ }
+ rec.RunOnce(context.Background())
+ if state, _, exists := f.rowState(t, key); exists {
+ t.Fatalf("row = %q, want cleared once the re-delete schedule is exhausted", state)
+ }
+}
+
+// A tombstone whose object stayed gone still walks its schedule and then
+// clears, and the object-deleted metric counts the object once (not once per
+// re-delete pass).
+func TestChannelMediaReconciler_TombstoneSchedulesThenClears(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ deleter := &fakeObjectDeleter{}
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: deleter}
+ key := "ws/lark/tombstone-walk"
+ f.seedLedgerRow(t, key, "https://cdn.test/tombstone-walk", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+
+ for pass := 1; pass <= len(channelMediaTombstoneRedelete); pass++ {
+ rec.RunOnce(context.Background())
+ state, _, exists := f.rowState(t, key)
+ if !exists || state != "tombstoned" {
+ t.Fatalf("pass %d: row = (%q, %v), want 'tombstoned'", pass, state, exists)
+ }
+ if _, err := pool.Exec(context.Background(), `
+ UPDATE channel_media_pending_object SET next_attempt_at = now() - interval '1 second' WHERE storage_key = $1
+ `, key); err != nil {
+ t.Fatalf("make tombstone due: %v", err)
+ }
+ }
+ rec.RunOnce(context.Background())
+ if _, _, exists := f.rowState(t, key); exists {
+ t.Fatal("row must clear after the schedule is exhausted")
+ }
+ if got := len(deleter.deletedKeys()); got != len(channelMediaTombstoneRedelete)+1 {
+ t.Fatalf("delete calls = %d, want one per pass plus the final one", got)
+ }
+}
+
+// A tombstone re-delete targets the same key an attachment would read, so the
+// reference check runs on every pass. Finding a reference here is an invariant
+// violation (per-message keys plus the bind state guard make it unreachable),
+// and the answer to a broken invariant is to keep the object and raise an
+// anomaly — deleting it would manufacture the dangling attachment the whole
+// ledger exists to prevent.
+func TestChannelMediaReconciler_TombstoneKeepsReferencedObject(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ deleter := &fakeObjectDeleter{}
+ m := metrics.NewChannelMediaReconcilerMetrics()
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: deleter, Metrics: m}
+ key := "ws/lark/tombstone-vs-attachment"
+ url := "https://cdn.test/tombstone-vs-attachment"
+ f.seedLedgerRow(t, key, url, "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+
+ rec.RunOnce(context.Background())
+ if state, _, exists := f.rowState(t, key); !exists || state != "tombstoned" {
+ t.Fatalf("row = (%q, %v), want 'tombstoned'", state, exists)
+ }
+
+ // An attachment now reads this object — a state that should be impossible.
+ f.bindAttachment(t, url)
+ f.makeDue(t, key)
+ rec.RunOnce(context.Background())
+
+ if got := len(deleter.deletedKeys()); got != 1 {
+ t.Fatalf("delete calls = %d, want the referenced object left alone (only the first delete)", got)
+ }
+ if state, _, exists := f.rowState(t, key); exists {
+ t.Fatalf("row = %q, want it cleared once the object is known to be referenced", state)
+ }
+ if got := testutil.ToFloat64(m.TombstoneReferenced); got != 1 {
+ t.Fatalf("tombstone-referenced anomaly counter = %v, want 1", got)
+ }
+}
+
+// Every deadline the reconciler persists is computed by Postgres from its own
+// now(), not by the process: the queries take durations, so a replica whose
+// clock drifted cannot settle a row whose upload is still in flight, hand out
+// a lease that is born expired, or compress the tombstone schedule. This pins
+// that the persisted timestamps track the DATABASE clock.
+func TestChannelMediaReconciler_DeadlinesComeFromTheDatabaseClock(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ key := "ws/lark/db-clock"
+ f.seedLedgerRow(t, key, "https://cdn.test/db-clock", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+
+ // Read the lease while the settle is in flight — it is cleared on release.
+ var leaseAhead time.Duration
+ deleter := &fakeObjectDeleter{err: errors.New("storage down")}
+ deleter.onDelete = func(string) {
+ lease, _, dbNow := f.deadlines(t, key)
+ leaseAhead = lease.Sub(dbNow)
+ }
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: deleter}
+ rec.RunOnce(context.Background())
+
+ if leaseAhead <= 0 || leaseAhead > channelMediaReconcileLease {
+ t.Fatalf("lease expires %v after the database's now(), want (0, %v]", leaseAhead, channelMediaReconcileLease)
+ }
+ // The failed delete backed the row off by the base backoff, from now().
+ _, next, dbNow := f.deadlines(t, key)
+ if ahead := next.Sub(dbNow); ahead <= 0 || ahead > channelMediaReconcileBackoffBase {
+ t.Fatalf("backoff lands %v after the database's now(), want (0, %v]", ahead, channelMediaReconcileBackoffBase)
+ }
+
+ // And so does the tombstone's first re-delete pass.
+ deleter.err = nil
+ deleter.onDelete = nil
+ f.makeDue(t, key)
+ rec.RunOnce(context.Background())
+ _, next, dbNow = f.deadlines(t, key)
+ if ahead := next.Sub(dbNow); ahead <= 0 || ahead > channelMediaTombstoneRedelete[0] {
+ t.Fatalf("re-delete lands %v after the database's now(), want (0, %v]", ahead, channelMediaTombstoneRedelete[0])
+ }
+}
+
+// A failed re-delete must not restart the tombstone schedule. The failure
+// writes last_error, so a schedule position carried there would be erased and
+// the walk would begin again — with a store failing intermittently the row
+// would never reach the end of the schedule and never be dropped. The position
+// lives in its own column, so a failure only costs one backed-off retry.
+func TestChannelMediaReconciler_TombstonePassSurvivesDeleteFailure(t *testing.T) {
+ pool := newCancelFinalizePool(t)
+ f := seedReconcilerFixture(t, pool)
+ deleter := &fakeObjectDeleter{}
+ rec := &ChannelMediaReconciler{Queries: db.New(pool), Storage: deleter}
+ key := "ws/lark/tombstone-pass-survives"
+ f.seedLedgerRow(t, key, "https://cdn.test/tombstone-pass-survives", "pending", ChannelMediaReconcileSettleDelay+time.Minute)
+
+ // First settle deletes the object and starts the schedule at pass 0.
+ rec.RunOnce(context.Background())
+ if got := f.tombstonePass(t, key); got != 0 {
+ t.Fatalf("tombstone_pass = %d after the first delete, want 0", got)
+ }
+
+ // One re-delete pass lands, advancing the schedule.
+ f.makeDue(t, key)
+ rec.RunOnce(context.Background())
+ if got := f.tombstonePass(t, key); got != 1 {
+ t.Fatalf("tombstone_pass = %d after one re-delete, want 1", got)
+ }
+
+ // The next re-delete fails: the row backs off, keeps its position, and
+ // records the failure in last_error.
+ deleter.err = errors.New("storage unavailable")
+ f.makeDue(t, key)
+ rec.RunOnce(context.Background())
+ if state, _, exists := f.rowState(t, key); !exists || state != "tombstoned" {
+ t.Fatalf("row = (%q, %v), want the failed re-delete to leave a tombstone", state, exists)
+ }
+ if got := f.tombstonePass(t, key); got != 1 {
+ t.Fatalf("tombstone_pass = %d after a failed re-delete, want it held at 1", got)
+ }
+
+ // Recovery resumes the walk instead of restarting it.
+ deleter.err = nil
+ f.makeDue(t, key)
+ rec.RunOnce(context.Background())
+ if got := f.tombstonePass(t, key); got != 2 {
+ t.Fatalf("tombstone_pass = %d after recovery, want the schedule to resume at 2", got)
+ }
+
+ // And the remaining passes still terminate the row.
+ for range channelMediaTombstoneRedelete[2:] {
+ f.makeDue(t, key)
+ rec.RunOnce(context.Background())
+ }
+ if state, _, exists := f.rowState(t, key); exists {
+ t.Fatalf("row = %q, want it dropped once the schedule is exhausted", state)
+ }
+}
diff --git a/server/internal/service/task.go b/server/internal/service/task.go
index 73b7a14a2a..39248ad8fe 100644
--- a/server/internal/service/task.go
+++ b/server/internal/service/task.go
@@ -1427,8 +1427,10 @@ var ErrChatTaskAgentArchived = errors.New("chat task: agent archived")
// path returns a task row, not this error.
var ErrChatTaskAgentNoRuntime = errors.New("chat task: agent has no runtime")
-// EnqueueChatTask creates a queued task for a chat session.
-// Unlike issue tasks, chat tasks have no issue_id.
+// EnqueueChatTask creates a task-owned input batch for a chat session. Channel
+// media makes the task deferred until binding completes or its durable fallback
+// deadline expires; other chat tasks are queued immediately. Unlike issue
+// tasks, chat tasks have no issue_id.
//
// Errors split into two layers:
//
@@ -1480,12 +1482,28 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
}
attrSource, _, attrEvidenceKind, attrEvidenceRef := attributionCreateParams(attr)
runtimeMCPOverlay := s.buildRuntimeMCPOverlay(ctx, initiatorUserID, agent)
- task, err := s.Queries.CreateChatTask(ctx, db.CreateChatTaskParams{
+
+ tx, err := s.TxStarter.Begin(ctx)
+ if err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("begin chat task enqueue: %w", err)
+ }
+ defer tx.Rollback(ctx)
+ qtx := s.Queries.WithTx(tx)
+ mediaPendingUntil, err := qtx.GetChannelMediaPendingUntil(ctx, chatSession.ID)
+ if err != nil && !errors.Is(err, pgx.ErrNoRows) {
+ slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)
+ return db.AgentTaskQueue{}, fmt.Errorf("load channel media pending deadline: %w", err)
+ }
+ if errors.Is(err, pgx.ErrNoRows) {
+ mediaPendingUntil = pgtype.Timestamptz{}
+ }
+ task, err := qtx.CreateChatTask(ctx, db.CreateChatTaskParams{
AgentID: chatSession.AgentID,
RuntimeID: agent.RuntimeID,
Priority: 2, // medium priority for chat
ChatSessionID: chatSession.ID,
InitiatorUserID: initiatorUserID,
+ FireAt: mediaPendingUntil,
OriginatorUserID: initiatorUserID,
AccountableUserID: attr.AccountableUserID,
ForceFreshSession: pgtype.Bool{
@@ -1502,6 +1520,52 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
slog.Error("chat task enqueue failed", "chat_session_id", util.UUIDToString(chatSession.ID), "error", err)
return db.AgentTaskQueue{}, fmt.Errorf("create chat task: %w", err)
}
+ task, err = qtx.SetChatTaskInputOwnerSelf(ctx, task.ID)
+ if err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("set channel chat task input owner: %w", err)
+ }
+ if err := qtx.LinkUnownedChannelChatMessagesToTask(ctx, db.LinkUnownedChannelChatMessagesToTaskParams{
+ TaskID: task.ID,
+ ChatSessionID: chatSession.ID,
+ }); err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("seal channel chat task input: %w", err)
+ }
+ // The deadline read above ran before the seal; under READ COMMITTED a media
+ // message committed between the two statements is sealed into this task
+ // without deferring it, and the daemon could claim it before its media
+ // binds. Re-derive the deferral from the sealed batch itself.
+ switch corrected, err := qtx.DeferChatTaskForSealedPendingMedia(ctx, task.ID); {
+ case err == nil:
+ task = corrected
+ case !errors.Is(err, pgx.ErrNoRows):
+ return db.AgentTaskQueue{}, fmt.Errorf("defer chat task for sealed pending media: %w", err)
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return db.AgentTaskQueue{}, fmt.Errorf("commit chat task enqueue: %w", err)
+ }
+
+ if task.Status == "deferred" {
+ slog.Info("chat task deferred for channel media",
+ "task_id", util.UUIDToString(task.ID),
+ "chat_session_id", util.UUIDToString(chatSession.ID),
+ "agent_id", util.UUIDToString(chatSession.AgentID),
+ "fire_at", task.FireAt.Time,
+ )
+ // Fence the clear-vs-create race: media completion may have found no
+ // committed task after our deadline read. Re-check after commit so the
+ // task is promoted immediately when the marker has already cleared.
+ // The task is already durably committed, so a fence failure must not
+ // surface as an enqueue failure — the router would treat it as "no
+ // task" and clear the typing indicator while the run still happens.
+ // The claim-path deferred promoter re-queues it at fire_at regardless.
+ if err := s.PromoteChannelChatTasksIfMediaReady(ctx, chatSession.ID); err != nil {
+ slog.Warn("chat task media-ready fence failed; deferred task falls back to its deadline",
+ "task_id", util.UUIDToString(task.ID),
+ "chat_session_id", util.UUIDToString(chatSession.ID),
+ "error", err)
+ }
+ return task, nil
+ }
slog.Info("chat task enqueued", "task_id", util.UUIDToString(task.ID), "chat_session_id", util.UUIDToString(chatSession.ID), "agent_id", util.UUIDToString(chatSession.AgentID))
// See EnqueueTaskForIssue for ordering rationale.
@@ -1510,6 +1574,27 @@ func (s *TaskService) EnqueueChatTask(ctx context.Context, chatSession db.ChatSe
return task, nil
}
+// PromoteChannelChatTasksIfMediaReady queues channel tasks as soon as every
+// unexpired media marker in the session has been cleared. If the process dies
+// first, the normal deferred-task promoter queues them at their persisted
+// fire_at deadline, preserving the placeholder fallback across restarts.
+func (s *TaskService) PromoteChannelChatTasksIfMediaReady(ctx context.Context, sessionID pgtype.UUID) error {
+ tasks, err := s.Queries.PromoteChannelChatTasksIfMediaReady(ctx, sessionID)
+ if err != nil {
+ return fmt.Errorf("promote channel chat tasks after media: %w", err)
+ }
+ for _, task := range tasks {
+ slog.Info("channel media-ready chat task promoted",
+ "task_id", util.UUIDToString(task.ID),
+ "chat_session_id", util.UUIDToString(sessionID),
+ "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.
@@ -1808,6 +1893,17 @@ func (s *TaskService) CancelTaskWithResult(ctx context.Context, taskID pgtype.UU
}, nil
}
+// chatInputOwnerID resolves the id the task's user-message input batch is
+// keyed on: chat_input_task_id when set (auto-retry clones inherit their
+// parent's, so provenance checks reach the parent's sealed messages), falling
+// back to the task's own id for legacy rows.
+func chatInputOwnerID(task db.AgentTaskQueue) pgtype.UUID {
+ if task.ChatInputTaskID.Valid {
+ return task.ChatInputTaskID
+ }
+ return task.ID
+}
+
func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.AgentTaskQueue, opts CancelTaskOptions) *CancelledChatMessageResult {
if !task.ChatSessionID.Valid {
return nil
@@ -1818,7 +1914,25 @@ func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.
if err != nil {
return fmt.Errorf("list cancelled chat task messages: %w", err)
}
- if len(messages) == 0 && task.StartedAt.Valid && opts.ClientSupportsDraftRestore {
+ restorable := len(messages) == 0
+ if restorable {
+ // Channel-ingested user messages are the durable record of what
+ // the platform sender wrote — the sender has no Multica composer
+ // to restore a draft into. The gate is the immutable per-message
+ // channel_ingested stamp, NOT the channel_chat_session_binding
+ // row: archiving a session or rebinding an installation deletes
+ // the binding while the messages (and a still-cancellable task)
+ // remain. Keyed by the input-batch owner id so an auto-retry
+ // clone (which inherits chat_input_task_id) reaches the same
+ // verdict as its parent. A channel task settles as "Stopped."
+ // below instead of deleting its sealed input batch.
+ channelIngested, err := qtx.TaskHasChannelIngestedMessages(ctx, chatInputOwnerID(task))
+ if err != nil {
+ return fmt.Errorf("check cancelled chat channel provenance: %w", err)
+ }
+ restorable = !channelIngested
+ }
+ if restorable && task.StartedAt.Valid && opts.ClientSupportsDraftRestore {
// A started task's daemon learns of the cancellation by polling
// and may still be flushing its transcript tail, so "empty" is
// not trustworthy yet. Defer the judgment until the daemon acks
@@ -1838,7 +1952,7 @@ func (s *TaskService) finalizeCancelledChatMessage(ctx context.Context, task db.
}
return nil
}
- if len(messages) == 0 {
+ if restorable {
// Detach attachments BEFORE deleting the user message — the
// attachment FK is ON DELETE CASCADE, so deleting first would
// destroy rows the restored draft needs to re-bind.
@@ -1945,7 +2059,19 @@ func (s *TaskService) FinalizeDeferredCancelledChat(ctx context.Context, taskID
if err != nil {
return fmt.Errorf("list cancelled chat task messages: %w", err)
}
- if len(messages) == 0 {
+ restorable := len(messages) == 0
+ if restorable {
+ // Same immutable-provenance guard as finalizeCancelledChatMessage:
+ // channel tasks never restore-delete their sealed input. The sync
+ // path no longer defers such tasks; this covers markers created by
+ // an older replica during a rolling deploy.
+ channelIngested, err := qtx.TaskHasChannelIngestedMessages(ctx, chatInputOwnerID(claimed))
+ if err != nil {
+ return fmt.Errorf("check cancelled chat channel provenance: %w", err)
+ }
+ restorable = !channelIngested
+ }
+ if restorable {
// The transcript stayed empty through the daemon flush: same
// outcome as the synchronous empty branch, but the cancel HTTP
// response is long gone and the broadcast is best-effort. The
@@ -2806,19 +2932,22 @@ const chatNoResponseFallback = "The agent finished this turn without a text repl
// completed chat task inside the caller's completion transaction, returning the
// row (nil when none is written).
//
-// Task-owned direct (web/mobile) tasks — chat_input_task_id set — get the
-// explicit single-outcome contract: a non-empty final output becomes an ordinary
-// assistant message, and an empty/whitespace output becomes a visible
-// no_response outcome carrying a non-empty English fallback body. It never
-// auto-retries: an empty output is a legitimate terminal result (a tool-only
-// turn) and re-running it would repeat side effects already performed.
+// Direct (web/mobile) tasks get the explicit single-outcome contract: a
+// non-empty final output becomes an ordinary assistant message, and an
+// empty/whitespace output becomes a visible no_response outcome carrying a
+// non-empty English fallback body. It never auto-retries: an empty output is a
+// legitimate terminal result (a tool-only turn) and re-running it would repeat
+// side effects already performed.
//
-// Legacy and channel (Slack/Lark) tasks — chat_input_task_id NULL — keep the
-// prior behavior: a non-empty output writes an ordinary assistant message, but
-// an EMPTY output writes NO row, so chat:done carries empty content and the
-// channel outbound silently drops it. This preserves Slack/Lark empty-completion
-// semantics unchanged (MUL-4351 review): the no_response fallback body must never
-// be pushed to an external channel.
+// Channel (Slack/Lark) and legacy tasks keep the prior behavior: a non-empty
+// output writes an ordinary assistant message, but an EMPTY output writes NO
+// row, so chat:done carries empty content and the channel outbound silently
+// drops it (MUL-4351 review): the no_response fallback body must never be
+// pushed to an external channel. Channel tasks now own a sealed input batch
+// (chat_input_task_id set) just like direct tasks, so the discriminator is the
+// immutable channel_ingested stamp on the owned batch — keyed by the batch
+// owner id so an auto-retry clone (which inherits chat_input_task_id) reaches
+// the same verdict as its parent — while a NULL owner marks a legacy task.
func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Queries, task db.AgentTaskQueue, result []byte) (*db.ChatMessage, error) {
// result is the daemon request re-marshalled by the handler, so it is always
// valid JSON; an empty Output is the only case this branch cares about.
@@ -2854,10 +2983,21 @@ func (s *TaskService) writeChatCompletionOutcome(ctx context.Context, qtx *db.Qu
// Channel/legacy empty completion with nothing to show: emit no assistant
// row, only an empty chat:done for typing/lifecycle. Keeps the Slack/Lark
- // silent-drop path. Attachments still force a row — the agent produced a
- // deliverable the user must see.
- if isEmpty && pendingAttachments == 0 && !task.ChatInputTaskID.Valid {
- return nil, nil
+ // silent-drop path — the outbound patcher forwards any non-empty content
+ // verbatim, so the fallback body must never be written for a channel task.
+ // Attachments still force a row — the agent produced a deliverable the
+ // user must see.
+ if isEmpty && pendingAttachments == 0 {
+ if !task.ChatInputTaskID.Valid {
+ return nil, nil // legacy task
+ }
+ channelIngested, err := qtx.TaskHasChannelIngestedMessages(ctx, task.ChatInputTaskID)
+ if err != nil {
+ return nil, fmt.Errorf("check chat completion channel provenance: %w", err)
+ }
+ if channelIngested {
+ return nil, nil // channel task
+ }
}
params := db.CreateChatMessageParams{
diff --git a/server/internal/service/task_cancel_finalize_test.go b/server/internal/service/task_cancel_finalize_test.go
index 1560a5088e..5c0e10e42b 100644
--- a/server/internal/service/task_cancel_finalize_test.go
+++ b/server/internal/service/task_cancel_finalize_test.go
@@ -581,3 +581,104 @@ func TestListChatFinalizeDeferredExpired_HonorsGrace(t *testing.T) {
t.Error("backdated marker should be returned once past the grace period")
}
}
+
+// seedChannelIngest mirrors the channel append path: the user message carries
+// the immutable channel_ingested stamp and the session has a routing binding.
+func (f cancelFinalizeFixture) seedChannelIngest(t *testing.T, ctx context.Context) {
+ t.Helper()
+ if _, err := f.pool.Exec(ctx, `
+ UPDATE chat_message SET channel_ingested = TRUE WHERE id = $1
+ `, f.userMessageID); err != nil {
+ t.Fatalf("stamp channel_ingested: %v", err)
+ }
+ if _, err := f.pool.Exec(ctx, `
+ INSERT INTO channel_chat_session_binding (
+ chat_session_id, installation_id, channel_type, channel_chat_id, chat_type, config
+ )
+ VALUES ($1, gen_random_uuid(), 'feishu', $2, 'p2p', '{}'::jsonb)
+ `, f.chatSessionID, "oc_cancel_"+f.chatSessionID); err != nil {
+ t.Fatalf("create channel binding: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = f.pool.Exec(context.Background(), `DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1`, f.chatSessionID)
+ })
+}
+
+// unbindChannelSession deletes the routing binding the way archiving a session
+// or rebinding an installation does — the provenance gate must survive it.
+func (f cancelFinalizeFixture) unbindChannelSession(t *testing.T, ctx context.Context) {
+ t.Helper()
+ if _, err := f.pool.Exec(ctx, `
+ DELETE FROM channel_chat_session_binding WHERE chat_session_id = $1
+ `, f.chatSessionID); err != nil {
+ t.Fatalf("delete channel binding: %v", err)
+ }
+}
+
+// Channel-ingested user messages are the durable record of what the platform
+// sender wrote — the sender has no Multica composer to restore a draft into.
+// The gate is the immutable per-message channel_ingested stamp, so it must
+// hold even after archiving/rebinding deleted the session binding: cancelling
+// the sealed queued task keeps the messages and settles as "Stopped.".
+func TestCancelTask_ChannelIngested_ArchivedSessionKeepsSealedMessages(t *testing.T) {
+ ctx := context.Background()
+ pool := newCancelFinalizePool(t)
+ f := createCancelFinalizeFixture(t, ctx, pool, "queued", false)
+ f.seedChannelIngest(t, ctx)
+ f.unbindChannelSession(t, ctx)
+ svc := NewTaskService(db.New(pool), pool, nil, events.New())
+
+ result, err := svc.CancelTaskWithResult(ctx, util.MustParseUUID(f.taskID), CancelTaskOptions{ClientSupportsDraftRestore: true})
+ if err != nil {
+ t.Fatalf("cancel task: %v", err)
+ }
+ if result.CancelledChatMessage != nil {
+ t.Fatalf("channel task must not produce a restore result, got %+v", result.CancelledChatMessage)
+ }
+ if !f.userMessageExists(t, ctx) {
+ t.Error("channel user chat message must be preserved")
+ }
+ if got := f.assistantMessages(t, ctx); len(got) != 1 || got[0] != "Stopped." {
+ t.Errorf("assistant messages = %v, want [Stopped.]", got)
+ }
+ if restores := f.draftRestores(t, ctx); len(restores) != 0 {
+ t.Errorf("channel task must not create draft restores, got %d", len(restores))
+ }
+ if got := f.chatFinalizeDeferredAt(t, ctx); got != nil {
+ t.Errorf("channel task must not defer finalize, got %v", got)
+ }
+}
+
+// Started-empty channel task after archive/unbind: the sync path settles it as
+// "Stopped." without marking it deferred, and a marker left behind by an older
+// replica during a rolling deploy must still not delete the sealed input when
+// the deferred path claims it.
+func TestFinalizeDeferredCancelledChat_ChannelIngested_ArchivedSessionKeepsSealedMessages(t *testing.T) {
+ ctx := context.Background()
+ pool := newCancelFinalizePool(t)
+ f := createCancelFinalizeFixture(t, ctx, pool, "running", true)
+ f.seedChannelIngest(t, ctx)
+ f.unbindChannelSession(t, ctx)
+ svc := NewTaskService(db.New(pool), pool, nil, events.New())
+
+ if _, err := svc.CancelTaskWithResult(ctx, util.MustParseUUID(f.taskID), CancelTaskOptions{ClientSupportsDraftRestore: true}); err != nil {
+ t.Fatalf("cancel task: %v", err)
+ }
+ if got := f.chatFinalizeDeferredAt(t, ctx); got != nil {
+ t.Errorf("channel task must settle synchronously, deferred at %v", got)
+ }
+
+ if _, err := pool.Exec(ctx, `
+ UPDATE agent_task_queue SET chat_finalize_deferred_at = now() WHERE id = $1
+ `, f.taskID); err != nil {
+ t.Fatalf("mark deferred: %v", err)
+ }
+ svc.FinalizeDeferredCancelledChat(ctx, util.MustParseUUID(f.taskID))
+
+ if !f.userMessageExists(t, ctx) {
+ t.Error("channel user chat message must be preserved by the deferred path")
+ }
+ if restores := f.draftRestores(t, ctx); len(restores) != 0 {
+ t.Errorf("channel task must not create draft restores, got %d", len(restores))
+ }
+}
diff --git a/server/internal/service/task_channel_media_race_test.go b/server/internal/service/task_channel_media_race_test.go
new file mode 100644
index 0000000000..99df3192fc
--- /dev/null
+++ b/server/internal/service/task_channel_media_race_test.go
@@ -0,0 +1,137 @@
+package service
+
+import (
+ "context"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5"
+ "github.com/jackc/pgx/v5/pgconn"
+ "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"
+)
+
+// raceInjectTxStarter wraps the pool so the transaction handed to
+// EnqueueChatTask runs inject() immediately before the input-batch seal
+// statement executes. That reproduces, deterministically, a channel media
+// message whose append commits between the session-wide deadline read and
+// LinkUnownedChannelChatMessagesToTask — the READ COMMITTED window where the
+// seal sees a message the deadline read did not.
+type raceInjectTxStarter struct {
+ pool *pgxpool.Pool
+ inject func()
+}
+
+func (s *raceInjectTxStarter) Begin(ctx context.Context) (pgx.Tx, error) {
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return nil, err
+ }
+ return &raceInjectTx{Tx: tx, inject: s.inject}, nil
+}
+
+type raceInjectTx struct {
+ pgx.Tx
+ inject func()
+}
+
+func (t *raceInjectTx) Exec(ctx context.Context, sql string, args ...any) (pgconn.CommandTag, error) {
+ if strings.Contains(sql, "LinkUnownedChannelChatMessagesToTask") && t.inject != nil {
+ t.inject()
+ t.inject = nil
+ }
+ return t.Tx.Exec(ctx, sql, args...)
+}
+
+// TestEnqueueChatTaskDefersWhenMediaMessageCommitsDuringEnqueue pins the fix
+// for the enqueue-vs-append race: a media-pending message sealed into the task
+// after the deadline read must still leave the task deferred (not claimable)
+// until its media binds or the persisted deadline expires.
+func TestEnqueueChatTaskDefersWhenMediaMessageCommitsDuringEnqueue(t *testing.T) {
+ pool := newResolveOriginatorPool(t)
+ ctx := context.Background()
+ q := db.New(pool)
+ workspaceID, userID, agentID, _ := seedAttributionFixture(t, pool)
+
+ var chatSessionID string
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_session (workspace_id, agent_id, creator_id)
+ VALUES ($1, $2, $3) RETURNING id`, workspaceID, agentID, userID).Scan(&chatSessionID); err != nil {
+ t.Fatalf("seed chat session: %v", err)
+ }
+ t.Cleanup(func() {
+ _, _ = pool.Exec(context.Background(), `DELETE FROM chat_session WHERE id = $1`, chatSessionID)
+ })
+ // The message that armed this flush: plain text, no media marker.
+ if _, err := pool.Exec(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content)
+ VALUES ($1, 'user', 'look at this')`, chatSessionID); err != nil {
+ t.Fatalf("seed text message: %v", err)
+ }
+
+ deadline := time.Now().Add(time.Minute)
+ var mediaMessageID string
+ svc := &TaskService{
+ Queries: q,
+ TxStarter: &raceInjectTxStarter{pool: pool, inject: func() {
+ // A concurrent Handle appends an image message (with its media
+ // marker) and commits — after the deadline read, before the seal.
+ if err := pool.QueryRow(ctx, `
+ INSERT INTO chat_message (chat_session_id, role, content, channel_media_pending_until)
+ VALUES ($1, 'user', '[Image]', $2) RETURNING id`, chatSessionID, deadline).Scan(&mediaMessageID); err != nil {
+ t.Errorf("inject media message: %v", err)
+ }
+ }},
+ Bus: events.New(),
+ }
+
+ task, err := svc.EnqueueChatTask(ctx, db.ChatSession{
+ ID: util.MustParseUUID(chatSessionID),
+ AgentID: util.MustParseUUID(agentID),
+ }, util.MustParseUUID(userID), false)
+ if err != nil {
+ t.Fatalf("EnqueueChatTask: %v", err)
+ }
+ if mediaMessageID == "" {
+ t.Fatal("race injection did not run")
+ }
+
+ // The injected message must be sealed into this task's input batch...
+ var linkedTaskID pgtype.UUID
+ if err := pool.QueryRow(ctx, `SELECT task_id FROM chat_message WHERE id = $1`, mediaMessageID).Scan(&linkedTaskID); err != nil {
+ t.Fatalf("load sealed media message: %v", err)
+ }
+ if !linkedTaskID.Valid || linkedTaskID.Bytes != task.ID.Bytes {
+ t.Fatalf("media message task_id = %s, want %s", util.UUIDToString(linkedTaskID), util.UUIDToString(task.ID))
+ }
+ // ...and therefore the task must not be claimable before the media binds.
+ if task.Status != "deferred" || !task.FireAt.Valid {
+ t.Fatalf("task = status %q fire_at %v, want deferred until the sealed media deadline", task.Status, task.FireAt)
+ }
+ if task.FireAt.Time.Before(deadline.Add(-time.Second)) || task.FireAt.Time.After(deadline.Add(time.Second)) {
+ t.Fatalf("task fire_at = %v, want sealed media deadline %v", task.FireAt.Time, deadline)
+ }
+
+ // Media completion still promotes it through the normal path.
+ if err := q.ClearChatMessageChannelMediaPending(ctx, db.ClearChatMessageChannelMediaPendingParams{
+ ID: util.MustParseUUID(mediaMessageID),
+ ChatSessionID: util.MustParseUUID(chatSessionID),
+ }); err != nil {
+ t.Fatalf("clear pending media: %v", err)
+ }
+ if err := svc.PromoteChannelChatTasksIfMediaReady(ctx, util.MustParseUUID(chatSessionID)); err != nil {
+ t.Fatalf("PromoteChannelChatTasksIfMediaReady: %v", err)
+ }
+ var status string
+ if err := pool.QueryRow(ctx, `SELECT status FROM agent_task_queue WHERE id = $1`, task.ID).Scan(&status); err != nil {
+ t.Fatalf("load promoted task: %v", err)
+ }
+ if status != "queued" {
+ t.Fatalf("promoted task status = %q, want queued", status)
+ }
+}
diff --git a/server/internal/storage/local.go b/server/internal/storage/local.go
index 0c8bec8874..4dab8403db 100644
--- a/server/internal/storage/local.go
+++ b/server/internal/storage/local.go
@@ -1,6 +1,7 @@
package storage
import (
+ "bytes"
"context"
"encoding/json"
"fmt"
@@ -25,6 +26,11 @@ type LocalStorage struct {
// to the storage-key basename for the download filename.
const metaSuffix = ".meta.json"
+// tempSuffix is the on-disk extension of the staging file writeAtomic renames
+// into place. Deterministic per key so a crash leftover stays reclaimable —
+// see tempPath.
+const tempSuffix = ".tmp"
+
type localMeta struct {
Filename string `json:"filename"`
ContentType string `json:"content_type"`
@@ -90,8 +96,8 @@ func (s *LocalStorage) GetReader(ctx context.Context, key string) (io.ReadCloser
if key == "" {
return nil, fmt.Errorf("local GetReader: empty key")
}
- if strings.HasSuffix(key, metaSuffix) {
- return nil, fmt.Errorf("local GetReader: refusing to serve sidecar key %q", key)
+ if isInternalLocalPath(key) {
+ return nil, fmt.Errorf("local GetReader: refusing to serve internal key %q", key)
}
filePath := filepath.Join(s.uploadDir, key)
if !isUnder(s.uploadDir, filePath) {
@@ -105,18 +111,38 @@ func (s *LocalStorage) GetReader(ctx context.Context, key string) (io.ReadCloser
}
func (s *LocalStorage) Delete(ctx context.Context, key string) {
+ if err := s.DeleteObject(ctx, key); err != nil {
+ slog.Error("local storage Delete failed", "key", key, "error", err)
+ }
+}
+
+// DeleteObject is Delete with the error surfaced — the media reconciler needs
+// it to keep the ledger row and schedule a retry instead of assuming success.
+// A missing file is success (the delete is idempotent). The staging file is
+// removed too: a crash between write and rename leaves one behind, and this is
+// what reclaims it (the media ledger records the intent before the upload, so
+// the reconciler always reaches this delete for an abandoned key).
+func (s *LocalStorage) DeleteObject(_ context.Context, key string) error {
if key == "" {
- return
+ return nil
}
filePath := filepath.Join(s.uploadDir, key)
- if err := os.Remove(filePath); err != nil {
- if !os.IsNotExist(err) {
- slog.Error("local storage Delete failed", "key", key, "error", err)
+ for _, p := range []string{filePath, filePath + metaSuffix, tempPath(filePath)} {
+ if err := os.Remove(p); err != nil && !os.IsNotExist(err) {
+ return err
}
}
- if err := os.Remove(filePath + metaSuffix); err != nil && !os.IsNotExist(err) {
- slog.Error("local storage meta Delete failed", "key", key, "error", err)
+ return nil
+}
+
+// ObjectURL returns the URL a successful Upload/UploadStream of key would
+// return — a pure function of configuration, so the media intent ledger can
+// persist it BEFORE the upload.
+func (s *LocalStorage) ObjectURL(key string) string {
+ if s.baseURL != "" {
+ return fmt.Sprintf("%s/uploads/%s", s.baseURL, key)
}
+ return fmt.Sprintf("/uploads/%s", key)
}
func (s *LocalStorage) DeleteKeys(ctx context.Context, keys []string) {
@@ -127,11 +153,8 @@ func (s *LocalStorage) DeleteKeys(ctx context.Context, keys []string) {
func (s *LocalStorage) Upload(ctx context.Context, key string, data []byte, contentType string, filename string) (string, error) {
dest := filepath.Join(s.uploadDir, key)
- if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
- return "", fmt.Errorf("local storage MkdirAll: %w", err)
- }
- if err := os.WriteFile(dest, data, 0644); err != nil {
- return "", fmt.Errorf("local storage WriteFile: %w", err)
+ if err := writeAtomic(dest, bytes.NewReader(data)); err != nil {
+ return "", err
}
// Best-effort sidecar so ServeFile can restore the original filename in
// Content-Disposition. A failure here is logged but does not fail the
@@ -152,16 +175,101 @@ func (s *LocalStorage) Upload(ctx context.Context, key string, data []byte, cont
return fmt.Sprintf("/uploads/%s", key), nil
}
+func (s *LocalStorage) UploadStream(ctx context.Context, key string, data io.Reader, _ int64, contentType string, filename string) (string, error) {
+ dest := filepath.Join(s.uploadDir, key)
+ if err := writeAtomic(dest, data); err != nil {
+ return "", err
+ }
+ if filename != "" {
+ body, _ := json.Marshal(localMeta{Filename: filename, ContentType: contentType})
+ if err := os.WriteFile(dest+metaSuffix, body, 0644); err != nil {
+ slog.Error("local storage meta write failed", "key", key, "error", err)
+ }
+ }
+
+ if s.baseURL != "" {
+ return fmt.Sprintf("%s/uploads/%s", s.baseURL, key), nil
+ }
+ return fmt.Sprintf("/uploads/%s", key), nil
+}
+
+// writeAtomic writes src through a temp file in the destination directory and
+// renames it into place. Writing straight to dest would truncate an existing
+// object up front, so a write that fails mid-copy would destroy a
+// previously-successful upload of the same key (and the old cleanup even
+// removed it outright) — an attachment row could then point at a file that no
+// longer exists. With rename-into-place a failed write only discards its own
+// temp file and the existing object survives untouched. Both upload paths go
+// through here so neither can reintroduce the destructive shape.
+func writeAtomic(dest string, src io.Reader) error {
+ if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
+ return fmt.Errorf("local storage MkdirAll: %w", err)
+ }
+ tmp := tempPath(dest)
+ // 0644 at open, matching the mode the direct write used (os.CreateTemp
+ // would make it 0600 and need a chmod that some mounts refuse).
+ f, err := os.OpenFile(tmp, os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644)
+ if err != nil {
+ return fmt.Errorf("local storage create temp: %w", err)
+ }
+ if _, err := io.Copy(f, src); err != nil {
+ _ = f.Close()
+ _ = os.Remove(tmp)
+ return fmt.Errorf("local storage stream copy: %w", err)
+ }
+ if err := f.Close(); err != nil {
+ _ = os.Remove(tmp)
+ return fmt.Errorf("local storage Close: %w", err)
+ }
+ if err := os.Rename(tmp, dest); err != nil {
+ _ = os.Remove(tmp)
+ return fmt.Errorf("local storage Rename: %w", err)
+ }
+ return nil
+}
+
+// tempPath is the staging file writeAtomic renames into place. It is derived
+// from the object key rather than randomized (os.CreateTemp) so a crash
+// between the write and the rename leaves a file the delete path can still
+// find: DeleteObject removes it alongside the object, which means the media
+// intent ledger reclaims it too — the ledger row is written before the upload,
+// so the reconciler deletes the key and the leftover goes with it. A random
+// suffix would leave an orphan nothing could name, up to the 100 MiB resource
+// cap each, with no bound across crashes.
+//
+// The name is stable per key, so two concurrent writers of the SAME key would
+// share it. That does not occur here — media keys are per (chat message,
+// resource) and resolved once, and every other upload path mints a fresh UUID
+// key — and such writers already raced on the destination itself.
+func tempPath(dest string) string {
+ return filepath.Join(filepath.Dir(dest), "."+filepath.Base(dest)+tempSuffix)
+}
+
+// isInternalLocalPath reports whether key names one of the local backend's own
+// files — the .meta.json sidecar or a .<name>.tmp staging file — rather than an
+// object. Read paths take the key straight from the request URL, so both must
+// be unreachable: a staging file would otherwise expose a half-written body.
+// Object keys are server-generated (UUID or hash basenames) and never start
+// with a dot, so a user uploading "notes.tmp" (key "<uuid>.tmp") is unaffected.
+func isInternalLocalPath(key string) bool {
+ if strings.HasSuffix(key, metaSuffix) {
+ return true
+ }
+ base := filepath.Base(key)
+ return strings.HasPrefix(base, ".") && strings.HasSuffix(base, tempSuffix)
+}
+
func (s *LocalStorage) GetFilePath(key string) string {
return filepath.Join(s.uploadDir, key)
}
func (s *LocalStorage) ServeFile(w http.ResponseWriter, r *http.Request, filename string) {
- // The sidecar is an implementation detail of the local backend; refuse
- // to serve it directly so /uploads/<key>.meta.json doesn't become a
- // stable read API. Comes before any disk work so a path-traversal
- // attempt at a .meta.json sibling can't trigger an out-of-tree read.
- if strings.HasSuffix(filename, metaSuffix) {
+ // The sidecar and the staging file are implementation details of the local
+ // backend; refuse to serve them directly so /uploads/<key>.meta.json (or a
+ // half-written .<key>.tmp) doesn't become a stable read API. Comes before
+ // any disk work so a path-traversal attempt at a sibling can't trigger an
+ // out-of-tree read.
+ if isInternalLocalPath(filename) {
http.NotFound(w, r)
return
}
diff --git a/server/internal/storage/local_atomic_test.go b/server/internal/storage/local_atomic_test.go
new file mode 100644
index 0000000000..fdcd0a4c8b
--- /dev/null
+++ b/server/internal/storage/local_atomic_test.go
@@ -0,0 +1,196 @@
+package storage
+
+import (
+ "context"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+)
+
+type failingReader struct {
+ head string
+ consumed bool
+}
+
+func (r *failingReader) Read(p []byte) (int, error) {
+ if !r.consumed {
+ r.consumed = true
+ n := copy(p, r.head)
+ return n, nil
+ }
+ return 0, errors.New("injected stream failure")
+}
+
+// A failed UploadStream must never destroy an object a previous successful
+// upload of the same key produced: writing straight to the destination would
+// truncate it up front (and the old cleanup removed it outright), leaving any
+// attachment row that already points at it dangling.
+func TestLocalStorageUploadStreamFailureKeepsPreviousObject(t *testing.T) {
+ dir := t.TempDir()
+ s := &LocalStorage{uploadDir: dir}
+ key := "workspaces/ws/lark/dup"
+
+ if _, err := s.UploadStream(context.Background(), key, strings.NewReader("first-upload"), 12, "image/png", "a.png"); err != nil {
+ t.Fatalf("first UploadStream: %v", err)
+ }
+ if _, err := s.UploadStream(context.Background(), key, &failingReader{head: "partial"}, 7, "image/png", "a.png"); err == nil {
+ t.Fatal("second UploadStream must fail")
+ }
+
+ got, err := os.ReadFile(filepath.Join(dir, key))
+ if err != nil {
+ t.Fatalf("previous object must survive a failed re-upload: %v", err)
+ }
+ if string(got) != "first-upload" {
+ t.Fatalf("object content = %q, want the first upload intact", got)
+ }
+ // No temp files left behind.
+ entries, err := os.ReadDir(filepath.Dir(filepath.Join(dir, key)))
+ if err != nil {
+ t.Fatalf("read dir: %v", err)
+ }
+ for _, e := range entries {
+ if strings.Contains(e.Name(), ".tmp-") {
+ t.Fatalf("leftover temp file %q", e.Name())
+ }
+ }
+}
+
+// Both upload paths land 0644 objects. CreateTemp makes its file 0600, so
+// without the explicit mode the rename-into-place rewrite would have silently
+// narrowed permissions on deployments that serve the upload dir with a
+// front-end web server running as another user.
+func TestLocalStorageUploadsAreWorldReadable(t *testing.T) {
+ dir := t.TempDir()
+ s := &LocalStorage{uploadDir: dir}
+ if _, err := s.Upload(context.Background(), "buffered", []byte("a"), "text/plain", "a.txt"); err != nil {
+ t.Fatalf("Upload: %v", err)
+ }
+ if _, err := s.UploadStream(context.Background(), "streamed", strings.NewReader("a"), 1, "text/plain", "a.txt"); err != nil {
+ t.Fatalf("UploadStream: %v", err)
+ }
+ for _, key := range []string{"buffered", "streamed"} {
+ info, err := os.Stat(filepath.Join(dir, key))
+ if err != nil {
+ t.Fatalf("stat %s: %v", key, err)
+ }
+ if info.Mode().Perm() != 0644 {
+ t.Fatalf("%s mode = %o, want 0644", key, info.Mode().Perm())
+ }
+ }
+}
+
+// A crash between the staging write and the rename leaves the temp file
+// behind — no defer can cover that. The name is derived from the object key,
+// so the delete path reclaims it: the media ledger records the intent before
+// the upload, so the reconciler always reaches DeleteObject for an abandoned
+// key. A randomized temp name would leave an orphan nothing could name.
+func TestLocalStorageDeleteObjectReclaimsCrashLeftoverTemp(t *testing.T) {
+ dir := t.TempDir()
+ s := &LocalStorage{uploadDir: dir}
+ key := "workspaces/ws/lark/crashed"
+ dest := filepath.Join(dir, key)
+ if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ // The crash shape: a staging file, no object, no sidecar.
+ leftover := tempPath(dest)
+ if err := os.WriteFile(leftover, []byte("half-written body"), 0644); err != nil {
+ t.Fatalf("plant leftover: %v", err)
+ }
+
+ if err := s.DeleteObject(context.Background(), key); err != nil {
+ t.Fatalf("DeleteObject: %v", err)
+ }
+ if _, err := os.Stat(leftover); !os.IsNotExist(err) {
+ t.Fatalf("crash leftover survived the delete path (stat err = %v)", err)
+ }
+}
+
+// The staging file must not be readable through the object read paths: keys
+// come straight from the request URL, so a half-written body would otherwise
+// be exposed under a guessable name.
+func TestLocalStorageRefusesToServeStagingFile(t *testing.T) {
+ dir := t.TempDir()
+ s := &LocalStorage{uploadDir: dir}
+ key := "workspaces/ws/lark/staged"
+ dest := filepath.Join(dir, key)
+ if err := os.MkdirAll(filepath.Dir(dest), 0755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if err := os.WriteFile(tempPath(dest), []byte("half"), 0644); err != nil {
+ t.Fatalf("plant staging file: %v", err)
+ }
+ stagingKey := "workspaces/ws/lark/." + filepath.Base(key) + ".tmp"
+ if _, err := s.GetReader(context.Background(), stagingKey); err == nil {
+ t.Fatal("GetReader must refuse the staging file")
+ }
+ // A user-supplied ".tmp" extension is still a normal object: the key is a
+ // generated UUID, so it never collides with the dot-prefixed staging name.
+ if _, err := s.Upload(context.Background(), "workspaces/ws/0198-abc.tmp", []byte("real"), "application/octet-stream", "notes.tmp"); err != nil {
+ t.Fatalf("Upload of a .tmp-extension object: %v", err)
+ }
+ rc, err := s.GetReader(context.Background(), "workspaces/ws/0198-abc.tmp")
+ if err != nil {
+ t.Fatalf("a .tmp-extension object must stay readable: %v", err)
+ }
+ rc.Close()
+}
+
+// The buffered Upload now goes through the same temp-file rename as the
+// stream path. A byte slice cannot fail mid-copy, so what is observable here
+// is the tail: a failed write leaves no temp litter behind and no damage to a
+// previous object. (The truncate-up-front hazard itself is pinned on the
+// stream path, which is the one that can fail mid-body.)
+func TestLocalStorageUploadFailureLeavesNoTempFile(t *testing.T) {
+ dir := t.TempDir()
+ s := &LocalStorage{uploadDir: dir}
+ key := "workspaces/ws/lark/buffered-dup"
+ if _, err := s.Upload(context.Background(), key, []byte("first-upload"), "image/png", "a.png"); err != nil {
+ t.Fatalf("first Upload: %v", err)
+ }
+ // A destination the rename cannot replace (a non-empty directory) is the
+ // portable way to fail the write after the temp file is fully written.
+ blocked := filepath.Join(dir, "blocked")
+ if err := os.MkdirAll(filepath.Join(blocked, "child"), 0755); err != nil {
+ t.Fatalf("mkdir: %v", err)
+ }
+ if _, err := s.Upload(context.Background(), "blocked", []byte("nope"), "image/png", "a.png"); err == nil {
+ t.Fatal("Upload onto a non-empty directory must fail")
+ }
+ entries, err := os.ReadDir(dir)
+ if err != nil {
+ t.Fatalf("read dir: %v", err)
+ }
+ for _, e := range entries {
+ if strings.Contains(e.Name(), ".tmp-") {
+ t.Fatalf("leftover temp file %q", e.Name())
+ }
+ }
+ got, err := os.ReadFile(filepath.Join(dir, key))
+ if err != nil || string(got) != "first-upload" {
+ t.Fatalf("previous object = %q (err %v), want it intact", got, err)
+ }
+}
+
+// Sanity: a successful stream still lands the full body and stays readable.
+func TestLocalStorageUploadStreamAtomicSuccess(t *testing.T) {
+ dir := t.TempDir()
+ s := &LocalStorage{uploadDir: dir}
+ key := "workspaces/ws/lark/ok"
+ if _, err := s.UploadStream(context.Background(), key, strings.NewReader("payload"), 7, "text/plain", "p.txt"); err != nil {
+ t.Fatalf("UploadStream: %v", err)
+ }
+ rc, err := s.GetReader(context.Background(), key)
+ if err != nil {
+ t.Fatalf("GetReader: %v", err)
+ }
+ defer rc.Close()
+ body, _ := io.ReadAll(rc)
+ if string(body) != "payload" {
+ t.Fatalf("body = %q", body)
+ }
+}
diff --git a/server/internal/storage/s3.go b/server/internal/storage/s3.go
index 0a481c1da0..74cd163519 100644
--- a/server/internal/storage/s3.go
+++ b/server/internal/storage/s3.go
@@ -12,6 +12,7 @@ import (
"time"
"github.com/aws/aws-sdk-go-v2/aws"
+ "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/aws/aws-sdk-go-v2/service/s3"
@@ -239,16 +240,29 @@ func (s *S3Storage) PresignGetWithContentDisposition(ctx context.Context, key st
// Delete removes an object from S3. Errors are logged but not fatal.
func (s *S3Storage) Delete(ctx context.Context, key string) {
+ if err := s.DeleteObject(ctx, key); err != nil {
+ slog.Error("s3 DeleteObject failed", "key", key, "error", err)
+ }
+}
+
+// DeleteObject is Delete with the error surfaced — the media reconciler needs
+// it to keep the ledger row and schedule a retry instead of assuming success.
+func (s *S3Storage) DeleteObject(ctx context.Context, key string) error {
if key == "" {
- return
+ return nil
}
_, err := s.client.DeleteObject(ctx, &s3.DeleteObjectInput{
Bucket: aws.String(s.bucket),
Key: aws.String(key),
})
- if err != nil {
- slog.Error("s3 DeleteObject failed", "key", key, "error", err)
- }
+ return err
+}
+
+// ObjectURL returns the URL a successful Upload/UploadStream of key would
+// return. It is a pure function of configuration, so the media intent ledger
+// can persist the URL BEFORE the upload for the durable reference check.
+func (s *S3Storage) ObjectURL(key string) string {
+ return s.uploadedURL(key)
}
// DeleteKeys removes multiple objects from S3. Best-effort, errors are logged.
@@ -274,6 +288,34 @@ func (s *S3Storage) Upload(ctx context.Context, key string, data []byte, content
return s.uploadedURL(key), nil
}
+func (s *S3Storage) UploadStream(ctx context.Context, key string, data io.Reader, sizeBytes int64, contentType string, filename string) (string, error) {
+ if sizeBytes <= 0 {
+ return "", fmt.Errorf("s3 PutObject: content length is required for streaming upload")
+ }
+ input := &s3.PutObjectInput{
+ Bucket: aws.String(s.bucket),
+ Key: aws.String(key),
+ Body: data,
+ ContentLength: aws.Int64(sizeBytes),
+ ContentType: aws.String(contentType),
+ ContentDisposition: aws.String(ContentDisposition(contentType, filename)),
+ CacheControl: aws.String("max-age=432000,public"),
+ StorageClass: s.storageClass(),
+ }
+ _, err := s.client.PutObject(ctx, input, func(opts *s3.Options) {
+ // A non-seekable stream cannot be rewound for SigV4 payload hashing.
+ // S3 supports UNSIGNED-PAYLOAD for authenticated requests. Avoid the
+ // optional trailing-checksum path as well: it requires another rewind
+ // or aws-chunked framing that S3-compatible backends handle unevenly.
+ opts.APIOptions = append(opts.APIOptions, v4.SwapComputePayloadSHA256ForUnsignedPayloadMiddleware)
+ opts.RequestChecksumCalculation = aws.RequestChecksumCalculationWhenRequired
+ })
+ if err != nil {
+ return "", fmt.Errorf("s3 PutObject: %w", err)
+ }
+ return s.uploadedURL(key), nil
+}
+
// uploadedURL returns the URL stored for client consumption after an upload.
// Priority: CDN domain > custom endpoint > AWS S3 region-qualified host. The CDN
// domain wins even when a custom endpoint is set so S3-compatible backends
diff --git a/server/internal/storage/s3_test.go b/server/internal/storage/s3_test.go
index aee5a21245..58ecc029ad 100644
--- a/server/internal/storage/s3_test.go
+++ b/server/internal/storage/s3_test.go
@@ -2,6 +2,9 @@ package storage
import (
"context"
+ "io"
+ "net/http"
+ "net/http/httptest"
"net/url"
"strings"
"testing"
@@ -12,6 +15,67 @@ import (
"github.com/aws/aws-sdk-go-v2/service/s3"
)
+func TestS3StorageUploadStreamUsesFixedLengthRequest(t *testing.T) {
+ type observedRequest struct {
+ contentLength int64
+ decodedLength string
+ encoding string
+ transfer []string
+ body string
+ }
+ observed := make(chan observedRequest, 1)
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ body, err := io.ReadAll(r.Body)
+ if err != nil {
+ t.Errorf("read request body: %v", err)
+ }
+ observed <- observedRequest{
+ contentLength: r.ContentLength,
+ decodedLength: r.Header.Get("X-Amz-Decoded-Content-Length"),
+ encoding: r.Header.Get("Content-Encoding"),
+ transfer: append([]string(nil), r.TransferEncoding...),
+ body: string(body),
+ }
+ w.WriteHeader(http.StatusOK)
+ }))
+ t.Cleanup(server.Close)
+
+ client := s3.New(s3.Options{
+ Region: "us-east-1",
+ Credentials: aws.NewCredentialsCache(credentials.NewStaticCredentialsProvider("AKID", "SECRET", "")),
+ BaseEndpoint: aws.String(server.URL),
+ UsePathStyle: true,
+ })
+ store := &S3Storage{
+ client: client,
+ bucket: "test-bucket",
+ region: "us-east-1",
+ endpointURL: server.URL,
+ usePathStyle: true,
+ }
+ payload := "streamed payload"
+ nonSeekable := io.LimitReader(strings.NewReader(payload), int64(len(payload)))
+ if _, err := store.UploadStream(context.Background(), "uploads/media.bin", nonSeekable, int64(len(payload)), "application/octet-stream", "media.bin"); err != nil {
+ t.Fatalf("UploadStream: %v", err)
+ }
+
+ got := <-observed
+ if got.contentLength != int64(len(payload)) || len(got.transfer) != 0 {
+ t.Fatalf("request is not a fixed-length upload: content_length=%d decoded_length=%q encoding=%q transfer=%v",
+ got.contentLength, got.decodedLength, got.encoding, got.transfer)
+ }
+ if got.body != payload {
+ t.Fatalf("request body = %q, want %q", got.body, payload)
+ }
+}
+
+func TestS3StorageUploadStreamRejectsUnknownLength(t *testing.T) {
+ store := &S3Storage{}
+ if _, err := store.UploadStream(context.Background(), "uploads/media.bin", strings.NewReader("payload"), 0, "application/octet-stream", "media.bin"); err == nil {
+ t.Fatal("UploadStream accepted an unknown content length")
+ }
+}
+
func TestS3StorageKeyFromURL_CustomEndpointPreservesNestedKey(t *testing.T) {
s := &S3Storage{
bucket: "test-bucket",
diff --git a/server/internal/storage/storage.go b/server/internal/storage/storage.go
index 3ceb115d3a..4dd963c8ee 100644
--- a/server/internal/storage/storage.go
+++ b/server/internal/storage/storage.go
@@ -9,8 +9,15 @@ import (
type Storage interface {
Upload(ctx context.Context, key string, data []byte, contentType string, filename string) (string, error)
Delete(ctx context.Context, key string)
+ // DeleteObject is Delete with the error surfaced — the channel-media
+ // reconciler schedules retries on failure instead of assuming success.
+ DeleteObject(ctx context.Context, key string) error
DeleteKeys(ctx context.Context, keys []string)
KeyFromURL(rawURL string) string
+ // ObjectURL is the URL a successful Upload of key would return — a pure
+ // function of configuration, so the media intent ledger can persist it
+ // BEFORE the upload.
+ ObjectURL(key string) string
CdnDomain() string
// GetReader streams an object back to the caller. Used by the attachment
// preview proxy (GET /api/attachments/{id}/content) to bypass CloudFront
diff --git a/server/migrations/225_chat_message_channel_media_pending.down.sql b/server/migrations/225_chat_message_channel_media_pending.down.sql
new file mode 100644
index 0000000000..944c9780c7
--- /dev/null
+++ b/server/migrations/225_chat_message_channel_media_pending.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE chat_message
+ DROP COLUMN channel_media_pending_until;
diff --git a/server/migrations/225_chat_message_channel_media_pending.up.sql b/server/migrations/225_chat_message_channel_media_pending.up.sql
new file mode 100644
index 0000000000..2eb2aef800
--- /dev/null
+++ b/server/migrations/225_chat_message_channel_media_pending.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE chat_message
+ ADD COLUMN channel_media_pending_until TIMESTAMPTZ;
diff --git a/server/migrations/226_chat_message_channel_ingested.down.sql b/server/migrations/226_chat_message_channel_ingested.down.sql
new file mode 100644
index 0000000000..be0368b78d
--- /dev/null
+++ b/server/migrations/226_chat_message_channel_ingested.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE chat_message
+ DROP COLUMN channel_ingested;
diff --git a/server/migrations/226_chat_message_channel_ingested.up.sql b/server/migrations/226_chat_message_channel_ingested.up.sql
new file mode 100644
index 0000000000..e2eff7d2c8
--- /dev/null
+++ b/server/migrations/226_chat_message_channel_ingested.up.sql
@@ -0,0 +1,7 @@
+-- Immutable provenance for channel-ingested (Feishu/Slack) user messages.
+-- The cancel draft-restore path gates on this instead of the deletable
+-- channel_chat_session_binding row: archiving a session or rebinding an
+-- installation deletes the binding but must never expose the original
+-- inbound messages to restore-deletion.
+ALTER TABLE chat_message
+ ADD COLUMN channel_ingested BOOLEAN NOT NULL DEFAULT FALSE;
diff --git a/server/migrations/227_channel_media_pending_object.down.sql b/server/migrations/227_channel_media_pending_object.down.sql
new file mode 100644
index 0000000000..f3e1d651fc
--- /dev/null
+++ b/server/migrations/227_channel_media_pending_object.down.sql
@@ -0,0 +1 @@
+DROP TABLE channel_media_pending_object;
diff --git a/server/migrations/227_channel_media_pending_object.up.sql b/server/migrations/227_channel_media_pending_object.up.sql
new file mode 100644
index 0000000000..963e5c4b33
--- /dev/null
+++ b/server/migrations/227_channel_media_pending_object.up.sql
@@ -0,0 +1,52 @@
+-- Intent ledger for channel media objects (two-system atomicity, PR #5580).
+-- A row is written BEFORE the object is uploaded and cleared inside the same
+-- transaction that inserts the attachment rows, so "did my side effect
+-- happen?" is never adjudicated inline: every ambiguous outcome (upload
+-- error, unknown commit result, crash between upload and bind) simply leaves
+-- the row for the asynchronous reconciler, which settles it long after any
+-- in-flight PUT or COMMIT can still land.
+--
+-- state machine: 'pending' (intent recorded; bind may still claim it) →
+-- 'deleting' (a reconciler holds the lease; bind must never attach this key) →
+-- 'tombstoned' (the object was deleted, but the row is kept so late
+-- materializations are re-deleted; see below).
+-- The reconciler checks for a durable attachment reference only AFTER winning
+-- the claim — at that point a bind can no longer succeed on the key, so the
+-- check cannot race a late COMMIT. Every tombstone pass re-checks before
+-- re-deleting: reclaiming an orphan must never outrank keeping an object an
+-- attachment durably reads.
+--
+-- The tombstone exists because a DELETE cannot be ordered against a PUT the
+-- client already abandoned: the store may still materialize that object after
+-- the delete. Clearing the row immediately would leave such an object with no
+-- ledger row and nothing to reclaim it, which would make the settle delay the
+-- de-facto correctness barrier for the PUT/DELETE race. Instead the row stays
+-- as a tombstone and the object is re-deleted on a widening schedule
+-- (tombstone_pass-indexed), so a late materialization is caught by a later
+-- pass.
+-- storage_key is the logical primary key, attached in migration 229 via a
+-- CONCURRENTLY-built unique index (228) per the repo convention that every
+-- migration index — including a new table's unique index — is created
+-- concurrently in its own single-statement migration (see 207-209 for the
+-- same three-step pattern on client_usage_daily).
+CREATE TABLE channel_media_pending_object (
+ storage_key TEXT NOT NULL,
+ workspace_id UUID NOT NULL,
+ chat_message_id UUID NOT NULL,
+ storage_url TEXT NOT NULL,
+ -- Ops diagnostics only (per-installation debugging); no logic keys on it.
+ installation_id UUID,
+ state TEXT NOT NULL DEFAULT 'pending'
+ CHECK (state IN ('pending', 'deleting', 'tombstoned')),
+ lease_token UUID,
+ lease_expires_at TIMESTAMPTZ,
+ attempt INT NOT NULL DEFAULT 0,
+ next_attempt_at TIMESTAMPTZ NOT NULL DEFAULT now(),
+ last_error TEXT,
+ -- Position in the tombstone re-delete schedule. Its own column rather
+ -- than a marker inside last_error: a failed re-delete writes last_error,
+ -- which would erase the schedule position and restart the walk, so a
+ -- store failing intermittently could keep a tombstone alive forever.
+ tombstone_pass INT NOT NULL DEFAULT 0,
+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()
+);
diff --git a/server/migrations/228_channel_media_pending_object_key_index.down.sql b/server/migrations/228_channel_media_pending_object_key_index.down.sql
new file mode 100644
index 0000000000..0b4f8c7767
--- /dev/null
+++ b/server/migrations/228_channel_media_pending_object_key_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS channel_media_pending_object_storage_key_uidx;
diff --git a/server/migrations/228_channel_media_pending_object_key_index.up.sql b/server/migrations/228_channel_media_pending_object_key_index.up.sql
new file mode 100644
index 0000000000..7f8a9f426f
--- /dev/null
+++ b/server/migrations/228_channel_media_pending_object_key_index.up.sql
@@ -0,0 +1,6 @@
+-- Unique index backing channel_media_pending_object's primary key (attached
+-- in 228 USING INDEX) and the intent upsert's ON CONFLICT (storage_key).
+-- Kept in its own single-statement migration so CONCURRENTLY runs outside an
+-- implicit transaction block (repo convention; see migrations 119 and 208).
+CREATE UNIQUE INDEX CONCURRENTLY channel_media_pending_object_storage_key_uidx
+ ON channel_media_pending_object (storage_key);
diff --git a/server/migrations/229_channel_media_pending_object_primary_key.down.sql b/server/migrations/229_channel_media_pending_object_primary_key.down.sql
new file mode 100644
index 0000000000..609be7277f
--- /dev/null
+++ b/server/migrations/229_channel_media_pending_object_primary_key.down.sql
@@ -0,0 +1,2 @@
+ALTER TABLE channel_media_pending_object
+ DROP CONSTRAINT IF EXISTS channel_media_pending_object_pkey;
diff --git a/server/migrations/229_channel_media_pending_object_primary_key.up.sql b/server/migrations/229_channel_media_pending_object_primary_key.up.sql
new file mode 100644
index 0000000000..cc758898c1
--- /dev/null
+++ b/server/migrations/229_channel_media_pending_object_primary_key.up.sql
@@ -0,0 +1,2 @@
+ALTER TABLE channel_media_pending_object
+ ADD CONSTRAINT channel_media_pending_object_pkey PRIMARY KEY USING INDEX channel_media_pending_object_storage_key_uidx;
diff --git a/server/migrations/230_channel_media_pending_object_claim_index.down.sql b/server/migrations/230_channel_media_pending_object_claim_index.down.sql
new file mode 100644
index 0000000000..7e59406c8d
--- /dev/null
+++ b/server/migrations/230_channel_media_pending_object_claim_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX CONCURRENTLY IF EXISTS idx_channel_media_pending_object_claim;
diff --git a/server/migrations/230_channel_media_pending_object_claim_index.up.sql b/server/migrations/230_channel_media_pending_object_claim_index.up.sql
new file mode 100644
index 0000000000..92da137604
--- /dev/null
+++ b/server/migrations/230_channel_media_pending_object_claim_index.up.sql
@@ -0,0 +1,6 @@
+-- Serves the reconciler's claim scan (state + due time). The migration runner
+-- executes files outside an explicit transaction, so CONCURRENTLY is kept in
+-- its own single-statement migration to avoid Postgres' implicit transaction
+-- block for multi-statement query strings (same convention as migration 119).
+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_channel_media_pending_object_claim
+ ON channel_media_pending_object (state, next_attempt_at);
diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.go
index 606b5a2c5d..58470fa956 100644
--- a/server/pkg/db/generated/channel.sql.go
+++ b/server/pkg/db/generated/channel.sql.go
@@ -73,6 +73,34 @@ func (q *Queries) BackfillChannelInstallationRegionToFeishuLark(ctx context.Cont
return result.RowsAffected(), nil
}
+const channelMediaObjectIsReferenced = `-- name: ChannelMediaObjectIsReferenced :one
+SELECT EXISTS (
+ SELECT 1 FROM attachment
+ WHERE chat_message_id = $1
+ AND workspace_id = $2
+ AND url = $3
+) AS referenced
+`
+
+type ChannelMediaObjectIsReferencedParams struct {
+ ChatMessageID pgtype.UUID `json:"chat_message_id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ StorageUrl string `json:"storage_url"`
+}
+
+// The post-claim reference check: an attachment row carrying this object's
+// URL on the intended message. Only meaningful AFTER the claim flipped the
+// row to 'deleting' — from that point a bind can no longer succeed on the
+// key, so a negative answer is terminal, not a snapshot race. Re-run on every
+// tombstone pass as well: a positive answer there is an invariant violation,
+// and the object is kept and reported rather than deleted.
+func (q *Queries) ChannelMediaObjectIsReferenced(ctx context.Context, arg ChannelMediaObjectIsReferencedParams) (bool, error) {
+ row := q.db.QueryRow(ctx, channelMediaObjectIsReferenced, arg.ChatMessageID, arg.WorkspaceID, arg.StorageUrl)
+ var referenced bool
+ err := row.Scan(&referenced)
+ return referenced, err
+}
+
const claimChannelInboundDedup = `-- name: ClaimChannelInboundDedup :one
INSERT INTO channel_inbound_message_dedup (installation_id, message_id, claim_token)
@@ -112,6 +140,122 @@ func (q *Queries) ClaimChannelInboundDedup(ctx context.Context, arg ClaimChannel
return i, err
}
+const claimChannelMediaPendingObjectsForBind = `-- name: ClaimChannelMediaPendingObjectsForBind :many
+DELETE FROM channel_media_pending_object
+WHERE storage_key = ANY($1::text[])
+ AND workspace_id = $2
+ AND state = 'pending'
+RETURNING storage_key
+`
+
+type ClaimChannelMediaPendingObjectsForBindParams struct {
+ StorageKeys []string `json:"storage_keys"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+}
+
+// Runs inside the attachment-insert transaction: commit landed ⇔ the intents
+// are gone, atomically, so an ambiguous COMMIT never needs adjudication. Only
+// 'pending' rows can be claimed — a key the reconciler moved to 'deleting'
+// is NOT returned, and the caller must skip attaching that object (the
+// placeholder stays; the reconciler will delete the object).
+func (q *Queries) ClaimChannelMediaPendingObjectsForBind(ctx context.Context, arg ClaimChannelMediaPendingObjectsForBindParams) ([]string, error) {
+ rows, err := q.db.Query(ctx, claimChannelMediaPendingObjectsForBind, arg.StorageKeys, arg.WorkspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []string{}
+ for rows.Next() {
+ var storage_key string
+ if err := rows.Scan(&storage_key); err != nil {
+ return nil, err
+ }
+ items = append(items, storage_key)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
+const claimChannelMediaPendingObjectsForReconcile = `-- name: ClaimChannelMediaPendingObjectsForReconcile :many
+UPDATE channel_media_pending_object AS obj
+SET state = CASE WHEN obj.state = 'tombstoned' THEN 'tombstoned' ELSE 'deleting' END,
+ lease_token = $1,
+ lease_expires_at = now() + $2::interval,
+ attempt = obj.attempt + 1
+FROM (
+ SELECT cand.storage_key FROM channel_media_pending_object AS cand
+ WHERE cand.next_attempt_at <= now()
+ AND (
+ (cand.state = 'pending' AND cand.created_at <= now() - $3::interval)
+ OR (cand.state = 'deleting' AND (cand.lease_expires_at IS NULL OR cand.lease_expires_at <= now()))
+ -- Tombstones: the object was deleted, but a PUT the client abandoned
+ -- may still materialize it afterwards, so each due tombstone gets
+ -- another idempotent delete before the row is finally dropped.
+ OR (cand.state = 'tombstoned' AND (cand.lease_expires_at IS NULL OR cand.lease_expires_at <= now()))
+ )
+ ORDER BY cand.next_attempt_at
+ LIMIT $4
+ FOR UPDATE SKIP LOCKED
+) AS due
+WHERE obj.storage_key = due.storage_key
+RETURNING obj.storage_key, obj.workspace_id, obj.chat_message_id, obj.storage_url, obj.installation_id, obj.state, obj.lease_token, obj.lease_expires_at, obj.attempt, obj.next_attempt_at, obj.last_error, obj.tombstone_pass, obj.created_at
+`
+
+type ClaimChannelMediaPendingObjectsForReconcileParams struct {
+ LeaseToken pgtype.UUID `json:"lease_token"`
+ Lease pgtype.Interval `json:"lease"`
+ SettleDelay pgtype.Interval `json:"settle_delay"`
+ BatchLimit int32 `json:"batch_limit"`
+}
+
+// Short-transaction claim: flips due rows to 'deleting' under a fresh lease.
+// Due means (a) 'pending' rows older than the settle delay — an operational
+// buffer only; correctness comes from the state flip, after which a bind can
+// never succeed on the key — or (b) 'deleting' rows whose lease expired (a
+// crashed or failed worker). FOR UPDATE SKIP LOCKED keeps replicas from
+// claiming the same rows; the object-storage DELETE happens outside any
+// transaction, gated by the lease token.
+func (q *Queries) ClaimChannelMediaPendingObjectsForReconcile(ctx context.Context, arg ClaimChannelMediaPendingObjectsForReconcileParams) ([]ChannelMediaPendingObject, error) {
+ rows, err := q.db.Query(ctx, claimChannelMediaPendingObjectsForReconcile,
+ arg.LeaseToken,
+ arg.Lease,
+ arg.SettleDelay,
+ arg.BatchLimit,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []ChannelMediaPendingObject{}
+ for rows.Next() {
+ var i ChannelMediaPendingObject
+ if err := rows.Scan(
+ &i.StorageKey,
+ &i.WorkspaceID,
+ &i.ChatMessageID,
+ &i.StorageUrl,
+ &i.InstallationID,
+ &i.State,
+ &i.LeaseToken,
+ &i.LeaseExpiresAt,
+ &i.Attempt,
+ &i.NextAttemptAt,
+ &i.LastError,
+ &i.TombstonePass,
+ &i.CreatedAt,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const consumeChannelBindingToken = `-- name: ConsumeChannelBindingToken :one
UPDATE channel_binding_token
SET consumed_at = now()
@@ -139,6 +283,28 @@ func (q *Queries) ConsumeChannelBindingToken(ctx context.Context, tokenHash stri
return i, err
}
+const countChannelMediaPendingObjects = `-- name: CountChannelMediaPendingObjects :one
+SELECT
+ count(*) FILTER (WHERE state <> 'tombstoned') AS pending_objects,
+ count(*) FILTER (WHERE state = 'tombstoned') AS tombstoned_objects
+FROM channel_media_pending_object
+`
+
+type CountChannelMediaPendingObjectsRow struct {
+ PendingObjects int64 `json:"pending_objects"`
+ TombstonedObjects int64 `json:"tombstoned_objects"`
+}
+
+// Ledger backlog gauge for the reconciler's observability. Tombstones are
+// reported separately: they are bounded bookkeeping for already-deleted
+// objects, not a backlog of objects awaiting reclaim.
+func (q *Queries) CountChannelMediaPendingObjects(ctx context.Context) (CountChannelMediaPendingObjectsRow, error) {
+ row := q.db.QueryRow(ctx, countChannelMediaPendingObjects)
+ var i CountChannelMediaPendingObjectsRow
+ err := row.Scan(&i.PendingObjects, &i.TombstonedObjects)
+ return i, err
+}
+
const createChannelBindingToken = `-- name: CreateChannelBindingToken :one
INSERT INTO channel_binding_token (
@@ -450,6 +616,31 @@ func (q *Queries) DeleteChannelInstallationsByArchivedRuntimeAgents(ctx context.
return err
}
+const deleteChannelMediaPendingObject = `-- name: DeleteChannelMediaPendingObject :execrows
+DELETE FROM channel_media_pending_object
+WHERE storage_key = $1
+ AND workspace_id = $2
+ AND lease_token = $3
+`
+
+type DeleteChannelMediaPendingObjectParams struct {
+ StorageKey string `json:"storage_key"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+}
+
+// Drops a claimed row for good: a durable attachment reference was found, or
+// the tombstone's re-delete schedule is exhausted. Lease-token guarded so an
+// expired-lease reclaim by another
+// replica cannot be clobbered; workspace_id explicit per the tenancy rule.
+func (q *Queries) DeleteChannelMediaPendingObject(ctx context.Context, arg DeleteChannelMediaPendingObjectParams) (int64, error) {
+ result, err := q.db.Exec(ctx, deleteChannelMediaPendingObject, arg.StorageKey, arg.WorkspaceID, arg.LeaseToken)
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const deleteChannelOutboundCardMessagesBySession = `-- name: DeleteChannelOutboundCardMessagesBySession :exec
DELETE FROM channel_outbound_card_message
WHERE chat_session_id = $1
@@ -1225,6 +1416,51 @@ func (q *Queries) RecordChannelInboundDrop(ctx context.Context, arg RecordChanne
return err
}
+const recordChannelMediaPendingObject = `-- name: RecordChannelMediaPendingObject :one
+
+INSERT INTO channel_media_pending_object (
+ storage_key, workspace_id, chat_message_id, storage_url, installation_id
+)
+VALUES ($1, $2, $3, $4, $5)
+ON CONFLICT (storage_key) DO UPDATE
+SET created_at = now(), next_attempt_at = now(),
+ chat_message_id = EXCLUDED.chat_message_id,
+ storage_url = EXCLUDED.storage_url
+WHERE channel_media_pending_object.state = 'pending'
+ AND channel_media_pending_object.workspace_id = EXCLUDED.workspace_id
+RETURNING storage_key
+`
+
+type RecordChannelMediaPendingObjectParams struct {
+ StorageKey string `json:"storage_key"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ChatMessageID pgtype.UUID `json:"chat_message_id"`
+ StorageUrl string `json:"storage_url"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+}
+
+// =====================
+// channel_media_pending_object (media intent ledger)
+// =====================
+// Records upload intent BEFORE the PUT. A redelivered attempt refreshes the
+// settle window, but only while the row is still 'pending' — a key the
+// reconciler owns ('deleting') must never be resurrected — and only within
+// the SAME workspace: a cross-workspace key collision (impossible via the
+// derived key, but tenancy must never trust the key string) updates nothing
+// and returns no row, so the caller skips the upload entirely.
+func (q *Queries) RecordChannelMediaPendingObject(ctx context.Context, arg RecordChannelMediaPendingObjectParams) (string, error) {
+ row := q.db.QueryRow(ctx, recordChannelMediaPendingObject,
+ arg.StorageKey,
+ arg.WorkspaceID,
+ arg.ChatMessageID,
+ arg.StorageUrl,
+ arg.InstallationID,
+ )
+ var storage_key string
+ err := row.Scan(&storage_key)
+ return storage_key, err
+}
+
const releaseChannelInboundDedup = `-- name: ReleaseChannelInboundDedup :execrows
DELETE FROM channel_inbound_message_dedup
WHERE installation_id = $1
@@ -1250,6 +1486,41 @@ func (q *Queries) ReleaseChannelInboundDedup(ctx context.Context, arg ReleaseCha
return result.RowsAffected(), nil
}
+const releaseChannelMediaPendingObject = `-- name: ReleaseChannelMediaPendingObject :exec
+UPDATE channel_media_pending_object
+SET lease_token = NULL,
+ lease_expires_at = NULL,
+ next_attempt_at = now() + $1::interval,
+ last_error = $2
+WHERE storage_key = $3
+ AND workspace_id = $4
+ AND lease_token = $5
+`
+
+type ReleaseChannelMediaPendingObjectParams struct {
+ Backoff pgtype.Interval `json:"backoff"`
+ LastError pgtype.Text `json:"last_error"`
+ StorageKey string `json:"storage_key"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+}
+
+// Object-storage DELETE failed: keep the row in 'deleting' (bind must still
+// never attach it), release the lease, and back off the next attempt.
+// workspace_id is redundant with the storage_key PK but explicit per the
+// tenancy rule: every query constrains the workspace column, never trusting
+// the key string.
+func (q *Queries) ReleaseChannelMediaPendingObject(ctx context.Context, arg ReleaseChannelMediaPendingObjectParams) error {
+ _, err := q.db.Exec(ctx, releaseChannelMediaPendingObject,
+ arg.Backoff,
+ arg.LastError,
+ arg.StorageKey,
+ arg.WorkspaceID,
+ arg.LeaseToken,
+ )
+ return err
+}
+
const releaseChannelWSLease = `-- name: ReleaseChannelWSLease :exec
UPDATE channel_installation
SET ws_lease_token = NULL,
@@ -1270,6 +1541,41 @@ func (q *Queries) ReleaseChannelWSLease(ctx context.Context, arg ReleaseChannelW
return err
}
+const renewChannelMediaPendingObjectLease = `-- name: RenewChannelMediaPendingObjectLease :execrows
+UPDATE channel_media_pending_object
+SET lease_expires_at = now() + $1::interval
+WHERE storage_key = $2
+ AND workspace_id = $3
+ AND lease_token = $4
+`
+
+type RenewChannelMediaPendingObjectLeaseParams struct {
+ Lease pgtype.Interval `json:"lease"`
+ StorageKey string `json:"storage_key"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+}
+
+// Per-row heartbeat: the batch shares one claim, so the lease must be
+// extended before EACH row's settle work — otherwise a few storage deletes
+// running at their full timeout could outlive the lease mid-batch and a
+// second replica would reclaim the tail, duplicating deletes and inflating
+// attempt/backoff. Zero rows affected means another worker already reclaimed
+// this row: the caller must skip it. workspace_id explicit per the tenancy
+// rule.
+func (q *Queries) RenewChannelMediaPendingObjectLease(ctx context.Context, arg RenewChannelMediaPendingObjectLeaseParams) (int64, error) {
+ result, err := q.db.Exec(ctx, renewChannelMediaPendingObjectLease,
+ arg.Lease,
+ arg.StorageKey,
+ arg.WorkspaceID,
+ arg.LeaseToken,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const setChannelInstallationConfig = `-- name: SetChannelInstallationConfig :exec
UPDATE channel_installation
SET config = $2, updated_at = now()
@@ -1305,6 +1611,55 @@ func (q *Queries) SetChannelInstallationStatus(ctx context.Context, arg SetChann
return err
}
+const tombstoneChannelMediaPendingObject = `-- name: TombstoneChannelMediaPendingObject :execrows
+UPDATE channel_media_pending_object
+SET state = 'tombstoned',
+ lease_token = NULL,
+ lease_expires_at = NULL,
+ next_attempt_at = now() + $1::interval,
+ -- The pass index lives in its own column: a failed re-delete writes
+ -- last_error, so carrying the schedule position there would reset the
+ -- walk on every failure and a flaky store could keep the row alive
+ -- indefinitely. The delete that got here succeeded, so any previous
+ -- failure text is stale.
+ tombstone_pass = $2,
+ last_error = NULL
+WHERE storage_key = $3
+ AND workspace_id = $4
+ AND lease_token = $5
+`
+
+type TombstoneChannelMediaPendingObjectParams struct {
+ RedeleteDelay pgtype.Interval `json:"redelete_delay"`
+ TombstonePass int32 `json:"tombstone_pass"`
+ StorageKey string `json:"storage_key"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+}
+
+// The object was deleted, but the row is KEPT as a tombstone: a PUT the client
+// abandoned before the delete may still materialize the object afterwards, and
+// no DELETE can be ordered against it. Each due tombstone re-runs the
+// reference check and, only if still unreferenced, triggers another idempotent
+// delete, so a late materialization is reclaimed by a later pass while an
+// object something durably reads is never removed;
+// only after the re-delete schedule is exhausted is the row dropped
+// (DeleteChannelMediaPendingObject). Lease-token guarded like every other
+// settle write; workspace_id explicit per the tenancy rule.
+func (q *Queries) TombstoneChannelMediaPendingObject(ctx context.Context, arg TombstoneChannelMediaPendingObjectParams) (int64, error) {
+ result, err := q.db.Exec(ctx, tombstoneChannelMediaPendingObject,
+ arg.RedeleteDelay,
+ arg.TombstonePass,
+ arg.StorageKey,
+ arg.WorkspaceID,
+ arg.LeaseToken,
+ )
+ if err != nil {
+ return 0, err
+ }
+ return result.RowsAffected(), nil
+}
+
const updateChannelChatSessionBindingReplyTarget = `-- name: UpdateChannelChatSessionBindingReplyTarget :exec
UPDATE channel_chat_session_binding
SET last_message_id = $2,
diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.go
index 3cdc402fbc..5e7bb35906 100644
--- a/server/pkg/db/generated/chat.sql.go
+++ b/server/pkg/db/generated/chat.sql.go
@@ -31,6 +31,22 @@ func (q *Queries) ChatSessionHasUserMessage(ctx context.Context, chatSessionID p
return has_user_message, err
}
+const clearChatMessageChannelMediaPending = `-- name: ClearChatMessageChannelMediaPending :exec
+UPDATE chat_message
+SET channel_media_pending_until = NULL
+WHERE id = $1 AND chat_session_id = $2
+`
+
+type ClearChatMessageChannelMediaPendingParams struct {
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+}
+
+func (q *Queries) ClearChatMessageChannelMediaPending(ctx context.Context, arg ClearChatMessageChannelMediaPendingParams) error {
+ _, err := q.db.Exec(ctx, clearChatMessageChannelMediaPending, arg.ID, arg.ChatSessionID)
+ return err
+}
+
const clearChatSessionProjectByProject = `-- name: ClearChatSessionProjectByProject :exec
UPDATE chat_session
SET project_id = NULL
@@ -89,19 +105,36 @@ func (q *Queries) CreateChatDraftRestore(ctx context.Context, arg CreateChatDraf
}
const createChatMessage = `-- name: CreateChatMessage :one
-INSERT INTO chat_message (chat_session_id, role, content, task_id, failure_reason, elapsed_ms, message_kind)
-VALUES ($1, $2, $3, $4, $5, $6, COALESCE($7::text, 'message'))
-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind
+INSERT INTO chat_message (
+ chat_session_id, role, content, task_id, failure_reason, elapsed_ms,
+ message_kind, channel_media_pending_until, channel_ingested
+)
+VALUES (
+ $1, $2, $3, $4, $5, $6,
+ COALESCE($7::text, 'message'),
+ -- The media deadline is DB-clock time: every consumer compares it against
+ -- SQL now() (GetChannelMediaPendingUntil, the deferred promote, the
+ -- trailing-message guard), so the writer must use the same clock. The
+ -- caller passes a relative budget in seconds; an application-clock
+ -- timestamp here would let a skewed app node shrink or stretch the
+ -- fallback window.
+ CASE WHEN $8::float8 IS NULL THEN NULL
+ ELSE now() + make_interval(secs => $8::float8) END,
+ COALESCE($9::boolean, FALSE)
+)
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested
`
type CreateChatMessageParams struct {
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- Role string `json:"role"`
- Content string `json:"content"`
- TaskID pgtype.UUID `json:"task_id"`
- FailureReason pgtype.Text `json:"failure_reason"`
- ElapsedMs pgtype.Int8 `json:"elapsed_ms"`
- MessageKind pgtype.Text `json:"message_kind"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Role string `json:"role"`
+ Content string `json:"content"`
+ TaskID pgtype.UUID `json:"task_id"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ ElapsedMs pgtype.Int8 `json:"elapsed_ms"`
+ MessageKind pgtype.Text `json:"message_kind"`
+ ChannelMediaPendingSecs pgtype.Float8 `json:"channel_media_pending_secs"`
+ ChannelIngested pgtype.Bool `json:"channel_ingested"`
}
// message_kind defaults to 'message' via COALESCE so every existing caller
@@ -116,6 +149,8 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
arg.FailureReason,
arg.ElapsedMs,
arg.MessageKind,
+ arg.ChannelMediaPendingSecs,
+ arg.ChannelIngested,
)
var i ChatMessage
err := row.Scan(
@@ -128,6 +163,8 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa
&i.FailureReason,
&i.ElapsedMs,
&i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
)
return i, err
}
@@ -182,36 +219,41 @@ const createChatTask = `-- name: CreateChatTask :one
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
- runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id
+ runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
+ fire_at
)
VALUES (
- $1, $2, NULL, 'queued', $3, $4, $5,
- $6,
+ $1, $2, NULL,
+ CASE WHEN $6::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,
+ $3, $4, $5,
$7,
- COALESCE($8::boolean, FALSE),
- $9,
+ $8,
+ COALESCE($9::boolean, FALSE),
$10,
$11,
$12,
- $13
+ $13,
+ $14,
+ $6::timestamptz
)
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
`
type CreateChatTaskParams struct {
- AgentID pgtype.UUID `json:"agent_id"`
- RuntimeID pgtype.UUID `json:"runtime_id"`
- Priority int32 `json:"priority"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
- OriginatorUserID pgtype.UUID `json:"originator_user_id"`
- AccountableUserID pgtype.UUID `json:"accountable_user_id"`
- ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
- RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
- RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
- OriginatorSource pgtype.Text `json:"originator_source"`
- TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
- TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
+ AgentID pgtype.UUID `json:"agent_id"`
+ RuntimeID pgtype.UUID `json:"runtime_id"`
+ Priority int32 `json:"priority"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ InitiatorUserID pgtype.UUID `json:"initiator_user_id"`
+ FireAt pgtype.Timestamptz `json:"fire_at"`
+ OriginatorUserID pgtype.UUID `json:"originator_user_id"`
+ AccountableUserID pgtype.UUID `json:"accountable_user_id"`
+ ForceFreshSession pgtype.Bool `json:"force_fresh_session"`
+ RuntimeMcpOverlay []byte `json:"runtime_mcp_overlay"`
+ RuntimeConnectedApps []byte `json:"runtime_connected_apps"`
+ OriginatorSource pgtype.Text `json:"originator_source"`
+ TriggerEvidenceKind pgtype.Text `json:"trigger_evidence_kind"`
+ TriggerEvidenceRefID pgtype.UUID `json:"trigger_evidence_ref_id"`
}
// The chat sender (initiator) is a direct_human originator and accountable;
@@ -224,6 +266,7 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
arg.Priority,
arg.ChatSessionID,
arg.InitiatorUserID,
+ arg.FireAt,
arg.OriginatorUserID,
arg.AccountableUserID,
arg.ForceFreshSession,
@@ -287,6 +330,84 @@ func (q *Queries) CreateChatTask(ctx context.Context, arg CreateChatTaskParams)
return i, err
}
+const deferChatTaskForSealedPendingMedia = `-- name: DeferChatTaskForSealedPendingMedia :one
+UPDATE agent_task_queue AS task
+SET status = 'deferred', fire_at = pending.max_until
+FROM (
+ SELECT max(message.channel_media_pending_until) AS max_until
+ FROM chat_message AS message
+ WHERE message.task_id = $1
+ AND message.role = 'user'
+ AND message.channel_media_pending_until > now()
+) AS pending
+WHERE task.id = $1
+ AND pending.max_until IS NOT NULL
+ AND (task.fire_at IS NULL OR task.fire_at < pending.max_until)
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing
+`
+
+// Closes the enqueue-vs-append race: under READ COMMITTED a media message can
+// commit between GetChannelMediaPendingUntil and the batch seal above, landing
+// an unexpired media marker inside a task the deadline read decided was
+// 'queued'. Re-derive the deferral from the sealed batch itself, in the same
+// transaction, so a task is never claimable while its own input still has an
+// unexpired marker. No row (ErrNoRows) means no correction was needed.
+func (q *Queries) DeferChatTaskForSealedPendingMedia(ctx context.Context, taskID pgtype.UUID) (AgentTaskQueue, error) {
+ row := q.db.QueryRow(ctx, deferChatTaskForSealedPendingMedia, taskID)
+ 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,
+ )
+ return i, err
+}
+
const deleteChatDraftRestore = `-- name: DeleteChatDraftRestore :execrows
DELETE FROM chat_draft_restore
WHERE id = $1 AND chat_session_id = $2
@@ -380,7 +501,7 @@ func (q *Queries) DeleteChatSession(ctx context.Context, arg DeleteChatSessionPa
const deleteUserChatMessageByTask = `-- name: DeleteUserChatMessageByTask :one
DELETE FROM chat_message
WHERE task_id = $1 AND role = 'user'
-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind
+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested
`
func (q *Queries) DeleteUserChatMessageByTask(ctx context.Context, taskID pgtype.UUID) (ChatMessage, error) {
@@ -396,12 +517,33 @@ func (q *Queries) DeleteUserChatMessageByTask(ctx context.Context, taskID pgtype
&i.FailureReason,
&i.ElapsedMs,
&i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
)
return i, err
}
+const getChannelMediaPendingUntil = `-- name: GetChannelMediaPendingUntil :one
+SELECT channel_media_pending_until
+FROM chat_message
+WHERE chat_session_id = $1
+ AND role = 'user'
+ AND channel_media_pending_until > now()
+ORDER BY channel_media_pending_until DESC
+LIMIT 1
+`
+
+// The latest unexpired media deadline gates a channel task. Using a durable
+// task fire_at means a process restart still produces the placeholder fallback.
+func (q *Queries) GetChannelMediaPendingUntil(ctx context.Context, chatSessionID pgtype.UUID) (pgtype.Timestamptz, error) {
+ row := q.db.QueryRow(ctx, getChannelMediaPendingUntil, chatSessionID)
+ var channel_media_pending_until pgtype.Timestamptz
+ err := row.Scan(&channel_media_pending_until)
+ return channel_media_pending_until, err
+}
+
const getChatMessage = `-- name: GetChatMessage :one
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested FROM chat_message
WHERE id = $1
`
@@ -418,6 +560,8 @@ func (q *Queries) GetChatMessage(ctx context.Context, id pgtype.UUID) (ChatMessa
&i.FailureReason,
&i.ElapsedMs,
&i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
)
return i, err
}
@@ -523,7 +667,7 @@ func (q *Queries) GetLastChatTaskSession(ctx context.Context, chatSessionID pgty
}
const getMostRecentUserChatMessage = `-- name: GetMostRecentUserChatMessage :one
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested FROM chat_message
WHERE chat_session_id = $1 AND role = 'user'
ORDER BY created_at DESC
LIMIT 1
@@ -547,6 +691,8 @@ func (q *Queries) GetMostRecentUserChatMessage(ctx context.Context, chatSessionI
&i.FailureReason,
&i.ElapsedMs,
&i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
)
return i, err
}
@@ -627,6 +773,34 @@ func (q *Queries) LinkChatMessageToTask(ctx context.Context, arg LinkChatMessage
return err
}
+const linkUnownedChannelChatMessagesToTask = `-- name: LinkUnownedChannelChatMessagesToTask :exec
+UPDATE chat_message AS message
+SET task_id = $1
+WHERE message.chat_session_id = $2
+ AND message.role = 'user'
+ AND message.task_id IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM chat_message AS prior
+ WHERE prior.chat_session_id = $2
+ AND prior.role != 'user'
+ AND (prior.created_at, prior.id) > (message.created_at, message.id)
+ )
+`
+
+type LinkUnownedChannelChatMessagesToTaskParams struct {
+ TaskID pgtype.UUID `json:"task_id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+}
+
+// Seals the trailing channel-message batch to its task. The task row and these
+// links are committed together, so an older in-flight task cannot absorb a
+// newer media message and a later assistant row cannot hide that message.
+func (q *Queries) LinkUnownedChannelChatMessagesToTask(ctx context.Context, arg LinkUnownedChannelChatMessagesToTaskParams) error {
+ _, err := q.db.Exec(ctx, linkUnownedChannelChatMessagesToTask, arg.TaskID, arg.ChatSessionID)
+ return err
+}
+
const listAllChatSessionsByCreator = `-- name: ListAllChatSessionsByCreator :many
SELECT cs.id, cs.workspace_id, cs.agent_id, cs.creator_id, cs.title, cs.session_id, cs.work_dir, cs.status, cs.created_at, cs.updated_at, cs.unread_since, cs.runtime_id, cs.last_read_at, cs.is_agent_intro, cs.pinned_at, cs.project_id,
CASE WHEN cs.status = 'archived' THEN 0
@@ -766,7 +940,7 @@ func (q *Queries) ListChatDraftRestoresBySession(ctx context.Context, chatSessio
}
const listChatInputMessages = `-- name: ListChatInputMessages :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested FROM chat_message
WHERE task_id = $1 AND role = 'user'
ORDER BY created_at ASC, id ASC
`
@@ -797,6 +971,8 @@ func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID)
&i.FailureReason,
&i.ElapsedMs,
&i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
); err != nil {
return nil, err
}
@@ -809,9 +985,9 @@ func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID)
}
const listChatMessages = `-- name: ListChatMessages :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested FROM chat_message
WHERE chat_session_id = $1
-ORDER BY created_at ASC
+ORDER BY created_at ASC, id ASC
`
func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUID) ([]ChatMessage, error) {
@@ -833,6 +1009,8 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI
&i.FailureReason,
&i.ElapsedMs,
&i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
); err != nil {
return nil, err
}
@@ -845,7 +1023,7 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI
}
const listChatMessagesPage = `-- name: ListChatMessagesPage :many
-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind FROM chat_message
+SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested FROM chat_message
WHERE chat_session_id = $1
AND (
$3::timestamptz IS NULL
@@ -886,6 +1064,8 @@ func (q *Queries) ListChatMessagesPage(ctx context.Context, arg ListChatMessages
&i.FailureReason,
&i.ElapsedMs,
&i.MessageKind,
+ &i.ChannelMediaPendingUntil,
+ &i.ChannelIngested,
); err != nil {
return nil, err
}
@@ -1242,6 +1422,96 @@ func (q *Queries) MarkChatSessionRead(ctx context.Context, id pgtype.UUID) error
return err
}
+const promoteChannelChatTasksIfMediaReady = `-- name: PromoteChannelChatTasksIfMediaReady :many
+UPDATE agent_task_queue AS task
+SET status = 'queued', fire_at = NULL
+WHERE task.chat_session_id = $1
+ AND task.status = 'deferred'
+ AND task.issue_id IS NULL
+ AND task.parent_task_id IS NULL
+ AND task.escalation_for_task_id IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM chat_message AS message
+ WHERE message.chat_session_id = $1
+ AND message.role = 'user'
+ AND message.channel_media_pending_until > now()
+ )
+RETURNING task.id, task.agent_id, task.issue_id, task.status, task.priority, task.dispatched_at, task.started_at, task.completed_at, task.result, task.error, task.created_at, task.context, task.runtime_id, task.session_id, task.work_dir, task.trigger_comment_id, task.chat_session_id, task.autopilot_run_id, task.attempt, task.max_attempts, task.parent_task_id, task.failure_reason, task.trigger_summary, task.force_fresh_session, task.is_leader_task, task.wait_reason, task.initiator_user_id, task.handoff_note, task.prepare_lease_expires_at, task.squad_id, task.runtime_mcp_overlay, task.escalation_for_task_id, task.fire_at, task.originator_user_id, task.runtime_connected_apps, task.coalesced_comment_ids, task.delivered_comment_ids, task.chat_input_task_id, task.chat_finalize_deferred_at, task.originator_source, task.delegated_from_task_id, task.retry_of_task_id, task.rerun_of_task_id, task.rule_version_id, task.trigger_evidence_kind, task.trigger_evidence_ref_id, task.accountable_user_id, task.session_rollout_missing
+`
+
+// Media completion may race with the 3s run batcher. Promote every original
+// channel task waiting for this session only after all unexpired media markers
+// are gone; retry/escalation/direct-chat deferred tasks are excluded.
+func (q *Queries) PromoteChannelChatTasksIfMediaReady(ctx context.Context, chatSessionID pgtype.UUID) ([]AgentTaskQueue, error) {
+ rows, err := q.db.Query(ctx, promoteChannelChatTasksIfMediaReady, chatSessionID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []AgentTaskQueue{}
+ for rows.Next() {
+ var i AgentTaskQueue
+ if err := rows.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,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const setChatSessionArchived = `-- name: SetChatSessionArchived :one
UPDATE chat_session
SET status = CASE WHEN $2::bool THEN 'archived' ELSE 'active' END,
@@ -1334,9 +1604,10 @@ RETURNING id, agent_id, issue_id, status, priority, dispatched_at, started_at, c
// Stamps a freshly-created direct-chat task as the owner of its own input batch
// (chat_input_task_id = id), so a later claim loads exactly the user messages
// tagged with this task id (ListChatInputMessages) rather than scanning trailing
-// history. Runs in the same transaction as CreateChatTask + the user message
-// insert on the direct-send path. Channel and legacy tasks skip this call and
-// keep chat_input_task_id NULL, so a rolling deploy never replays their history.
+// history. Runs in the same transaction as CreateChatTask + message ownership:
+// direct-send inserts one owned message, while channel enqueue seals its
+// trailing unowned batch. Legacy tasks keep chat_input_task_id NULL and retain
+// the trailing-history fallback during rolling deploys.
func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID) (AgentTaskQueue, error) {
row := q.db.QueryRow(ctx, setChatTaskInputOwnerSelf, id)
var i AgentTaskQueue
@@ -1393,6 +1664,31 @@ func (q *Queries) SetChatTaskInputOwnerSelf(ctx context.Context, id pgtype.UUID)
return i, err
}
+const taskHasChannelIngestedMessages = `-- name: TaskHasChannelIngestedMessages :one
+SELECT EXISTS (
+ SELECT 1 FROM chat_message
+ WHERE task_id = $1
+ AND role = 'user'
+ AND channel_ingested
+) AS channel_ingested
+`
+
+// Immutable channel provenance for a task's user-message input batch:
+// channel_ingested is stamped inside the channel append transaction and never
+// mutated afterwards, so it survives session archiving and installation
+// rebinds that delete the channel_chat_session_binding row. Callers pass the
+// batch OWNER id (chat_input_task_id, which auto-retry clones inherit), not
+// necessarily the task's own id. The cancel restore-delete and the
+// empty-completion silent-drop both gate on this — a channel sender has no
+// Multica composer for a restored draft, and the no_response fallback body
+// must never be pushed to an external channel.
+func (q *Queries) TaskHasChannelIngestedMessages(ctx context.Context, taskID pgtype.UUID) (bool, error) {
+ row := q.db.QueryRow(ctx, taskHasChannelIngestedMessages, taskID)
+ var channel_ingested bool
+ err := row.Scan(&channel_ingested)
+ return channel_ingested, err
+}
+
const touchChatSession = `-- name: TouchChatSession :exec
UPDATE chat_session SET updated_at = now()
WHERE id = $1
diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.go
index ec1a5e80de..254f8ab582 100644
--- a/server/pkg/db/generated/models.go
+++ b/server/pkg/db/generated/models.go
@@ -320,6 +320,22 @@ type ChannelInstallation struct {
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
}
+type ChannelMediaPendingObject struct {
+ StorageKey string `json:"storage_key"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ ChatMessageID pgtype.UUID `json:"chat_message_id"`
+ StorageUrl string `json:"storage_url"`
+ InstallationID pgtype.UUID `json:"installation_id"`
+ State string `json:"state"`
+ LeaseToken pgtype.UUID `json:"lease_token"`
+ LeaseExpiresAt pgtype.Timestamptz `json:"lease_expires_at"`
+ Attempt int32 `json:"attempt"`
+ NextAttemptAt pgtype.Timestamptz `json:"next_attempt_at"`
+ LastError pgtype.Text `json:"last_error"`
+ TombstonePass int32 `json:"tombstone_pass"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+}
+
type ChannelOutboundCardMessage struct {
ID pgtype.UUID `json:"id"`
ChatSessionID pgtype.UUID `json:"chat_session_id"`
@@ -353,15 +369,17 @@ type ChatDraftRestore struct {
}
type ChatMessage struct {
- ID pgtype.UUID `json:"id"`
- ChatSessionID pgtype.UUID `json:"chat_session_id"`
- Role string `json:"role"`
- Content string `json:"content"`
- TaskID pgtype.UUID `json:"task_id"`
- CreatedAt pgtype.Timestamptz `json:"created_at"`
- FailureReason pgtype.Text `json:"failure_reason"`
- ElapsedMs pgtype.Int8 `json:"elapsed_ms"`
- MessageKind string `json:"message_kind"`
+ ID pgtype.UUID `json:"id"`
+ ChatSessionID pgtype.UUID `json:"chat_session_id"`
+ Role string `json:"role"`
+ Content string `json:"content"`
+ TaskID pgtype.UUID `json:"task_id"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ FailureReason pgtype.Text `json:"failure_reason"`
+ ElapsedMs pgtype.Int8 `json:"elapsed_ms"`
+ MessageKind string `json:"message_kind"`
+ ChannelMediaPendingUntil pgtype.Timestamptz `json:"channel_media_pending_until"`
+ ChannelIngested bool `json:"channel_ingested"`
}
type ChatPinnedAgent struct {
diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sql
index 3464c93a77..be28b5ccd0 100644
--- a/server/pkg/db/queries/channel.sql
+++ b/server/pkg/db/queries/channel.sql
@@ -632,3 +632,157 @@ WHERE expires_at < $1;
-- installation — a link that never actually reaches the live bot.
DELETE FROM channel_binding_token
WHERE installation_id = $1;
+
+-- =====================
+-- channel_media_pending_object (media intent ledger)
+-- =====================
+
+-- name: RecordChannelMediaPendingObject :one
+-- Records upload intent BEFORE the PUT. A redelivered attempt refreshes the
+-- settle window, but only while the row is still 'pending' — a key the
+-- reconciler owns ('deleting') must never be resurrected — and only within
+-- the SAME workspace: a cross-workspace key collision (impossible via the
+-- derived key, but tenancy must never trust the key string) updates nothing
+-- and returns no row, so the caller skips the upload entirely.
+INSERT INTO channel_media_pending_object (
+ storage_key, workspace_id, chat_message_id, storage_url, installation_id
+)
+VALUES ($1, $2, $3, $4, sqlc.narg(installation_id))
+ON CONFLICT (storage_key) DO UPDATE
+SET created_at = now(), next_attempt_at = now(),
+ chat_message_id = EXCLUDED.chat_message_id,
+ storage_url = EXCLUDED.storage_url
+WHERE channel_media_pending_object.state = 'pending'
+ AND channel_media_pending_object.workspace_id = EXCLUDED.workspace_id
+RETURNING storage_key;
+
+-- name: ClaimChannelMediaPendingObjectsForBind :many
+-- Runs inside the attachment-insert transaction: commit landed ⇔ the intents
+-- are gone, atomically, so an ambiguous COMMIT never needs adjudication. Only
+-- 'pending' rows can be claimed — a key the reconciler moved to 'deleting'
+-- is NOT returned, and the caller must skip attaching that object (the
+-- placeholder stays; the reconciler will delete the object).
+DELETE FROM channel_media_pending_object
+WHERE storage_key = ANY(@storage_keys::text[])
+ AND workspace_id = @workspace_id
+ AND state = 'pending'
+RETURNING storage_key;
+
+-- name: ClaimChannelMediaPendingObjectsForReconcile :many
+-- Short-transaction claim: flips due rows to 'deleting' under a fresh lease.
+-- Due means (a) 'pending' rows older than the settle delay — an operational
+-- buffer only; correctness comes from the state flip, after which a bind can
+-- never succeed on the key — or (b) 'deleting' rows whose lease expired (a
+-- crashed or failed worker). FOR UPDATE SKIP LOCKED keeps replicas from
+-- claiming the same rows; the object-storage DELETE happens outside any
+-- transaction, gated by the lease token.
+UPDATE channel_media_pending_object AS obj
+SET state = CASE WHEN obj.state = 'tombstoned' THEN 'tombstoned' ELSE 'deleting' END,
+ lease_token = @lease_token,
+ lease_expires_at = now() + @lease::interval,
+ attempt = obj.attempt + 1
+FROM (
+ SELECT cand.storage_key FROM channel_media_pending_object AS cand
+ WHERE cand.next_attempt_at <= now()
+ AND (
+ (cand.state = 'pending' AND cand.created_at <= now() - @settle_delay::interval)
+ OR (cand.state = 'deleting' AND (cand.lease_expires_at IS NULL OR cand.lease_expires_at <= now()))
+ -- Tombstones: the object was deleted, but a PUT the client abandoned
+ -- may still materialize it afterwards, so each due tombstone gets
+ -- another idempotent delete before the row is finally dropped.
+ OR (cand.state = 'tombstoned' AND (cand.lease_expires_at IS NULL OR cand.lease_expires_at <= now()))
+ )
+ ORDER BY cand.next_attempt_at
+ LIMIT @batch_limit
+ FOR UPDATE SKIP LOCKED
+) AS due
+WHERE obj.storage_key = due.storage_key
+RETURNING obj.*;
+
+-- name: RenewChannelMediaPendingObjectLease :execrows
+-- Per-row heartbeat: the batch shares one claim, so the lease must be
+-- extended before EACH row's settle work — otherwise a few storage deletes
+-- running at their full timeout could outlive the lease mid-batch and a
+-- second replica would reclaim the tail, duplicating deletes and inflating
+-- attempt/backoff. Zero rows affected means another worker already reclaimed
+-- this row: the caller must skip it. workspace_id explicit per the tenancy
+-- rule.
+UPDATE channel_media_pending_object
+SET lease_expires_at = now() + @lease::interval
+WHERE storage_key = @storage_key
+ AND workspace_id = @workspace_id
+ AND lease_token = @lease_token;
+
+-- name: ReleaseChannelMediaPendingObject :exec
+-- Object-storage DELETE failed: keep the row in 'deleting' (bind must still
+-- never attach it), release the lease, and back off the next attempt.
+-- workspace_id is redundant with the storage_key PK but explicit per the
+-- tenancy rule: every query constrains the workspace column, never trusting
+-- the key string.
+UPDATE channel_media_pending_object
+SET lease_token = NULL,
+ lease_expires_at = NULL,
+ next_attempt_at = now() + @backoff::interval,
+ last_error = @last_error
+WHERE storage_key = @storage_key
+ AND workspace_id = @workspace_id
+ AND lease_token = @lease_token;
+
+-- name: TombstoneChannelMediaPendingObject :execrows
+-- The object was deleted, but the row is KEPT as a tombstone: a PUT the client
+-- abandoned before the delete may still materialize the object afterwards, and
+-- no DELETE can be ordered against it. Each due tombstone re-runs the
+-- reference check and, only if still unreferenced, triggers another idempotent
+-- delete, so a late materialization is reclaimed by a later pass while an
+-- object something durably reads is never removed;
+-- only after the re-delete schedule is exhausted is the row dropped
+-- (DeleteChannelMediaPendingObject). Lease-token guarded like every other
+-- settle write; workspace_id explicit per the tenancy rule.
+UPDATE channel_media_pending_object
+SET state = 'tombstoned',
+ lease_token = NULL,
+ lease_expires_at = NULL,
+ next_attempt_at = now() + @redelete_delay::interval,
+ -- The pass index lives in its own column: a failed re-delete writes
+ -- last_error, so carrying the schedule position there would reset the
+ -- walk on every failure and a flaky store could keep the row alive
+ -- indefinitely. The delete that got here succeeded, so any previous
+ -- failure text is stale.
+ tombstone_pass = @tombstone_pass,
+ last_error = NULL
+WHERE storage_key = @storage_key
+ AND workspace_id = @workspace_id
+ AND lease_token = @lease_token;
+
+-- name: DeleteChannelMediaPendingObject :execrows
+-- Drops a claimed row for good: a durable attachment reference was found, or
+-- the tombstone's re-delete schedule is exhausted. Lease-token guarded so an
+-- expired-lease reclaim by another
+-- replica cannot be clobbered; workspace_id explicit per the tenancy rule.
+DELETE FROM channel_media_pending_object
+WHERE storage_key = @storage_key
+ AND workspace_id = @workspace_id
+ AND lease_token = @lease_token;
+
+-- name: ChannelMediaObjectIsReferenced :one
+-- The post-claim reference check: an attachment row carrying this object's
+-- URL on the intended message. Only meaningful AFTER the claim flipped the
+-- row to 'deleting' — from that point a bind can no longer succeed on the
+-- key, so a negative answer is terminal, not a snapshot race. Re-run on every
+-- tombstone pass as well: a positive answer there is an invariant violation,
+-- and the object is kept and reported rather than deleted.
+SELECT EXISTS (
+ SELECT 1 FROM attachment
+ WHERE chat_message_id = @chat_message_id
+ AND workspace_id = @workspace_id
+ AND url = @storage_url
+) AS referenced;
+
+-- name: CountChannelMediaPendingObjects :one
+-- Ledger backlog gauge for the reconciler's observability. Tombstones are
+-- reported separately: they are bounded bookkeeping for already-deleted
+-- objects, not a backlog of objects awaiting reclaim.
+SELECT
+ count(*) FILTER (WHERE state <> 'tombstoned') AS pending_objects,
+ count(*) FILTER (WHERE state = 'tombstoned') AS tombstoned_objects
+FROM channel_media_pending_object;
diff --git a/server/pkg/db/queries/chat.sql b/server/pkg/db/queries/chat.sql
index 1a90d64ecd..8374a34615 100644
--- a/server/pkg/db/queries/chat.sql
+++ b/server/pkg/db/queries/chat.sql
@@ -188,15 +188,101 @@ WHERE id = $1;
-- message_kind defaults to 'message' via COALESCE so every existing caller
-- (which omits it) keeps writing ordinary messages; the empty-reply path passes
-- 'no_response' to mark a visible turn with no text output (MUL-4351).
-INSERT INTO chat_message (chat_session_id, role, content, task_id, failure_reason, elapsed_ms, message_kind)
-VALUES ($1, $2, $3, sqlc.narg(task_id), sqlc.narg(failure_reason), sqlc.narg(elapsed_ms), COALESCE(sqlc.narg(message_kind)::text, 'message'))
+INSERT INTO chat_message (
+ chat_session_id, role, content, task_id, failure_reason, elapsed_ms,
+ message_kind, channel_media_pending_until, channel_ingested
+)
+VALUES (
+ $1, $2, $3, sqlc.narg(task_id), sqlc.narg(failure_reason), sqlc.narg(elapsed_ms),
+ COALESCE(sqlc.narg(message_kind)::text, 'message'),
+ -- The media deadline is DB-clock time: every consumer compares it against
+ -- SQL now() (GetChannelMediaPendingUntil, the deferred promote, the
+ -- trailing-message guard), so the writer must use the same clock. The
+ -- caller passes a relative budget in seconds; an application-clock
+ -- timestamp here would let a skewed app node shrink or stretch the
+ -- fallback window.
+ CASE WHEN sqlc.narg(channel_media_pending_secs)::float8 IS NULL THEN NULL
+ ELSE now() + make_interval(secs => sqlc.narg(channel_media_pending_secs)::float8) END,
+ COALESCE(sqlc.narg(channel_ingested)::boolean, FALSE)
+)
RETURNING *;
+-- name: TaskHasChannelIngestedMessages :one
+-- Immutable channel provenance for a task's user-message input batch:
+-- channel_ingested is stamped inside the channel append transaction and never
+-- mutated afterwards, so it survives session archiving and installation
+-- rebinds that delete the channel_chat_session_binding row. Callers pass the
+-- batch OWNER id (chat_input_task_id, which auto-retry clones inherit), not
+-- necessarily the task's own id. The cancel restore-delete and the
+-- empty-completion silent-drop both gate on this — a channel sender has no
+-- Multica composer for a restored draft, and the no_response fallback body
+-- must never be pushed to an external channel.
+SELECT EXISTS (
+ SELECT 1 FROM chat_message
+ WHERE task_id = $1
+ AND role = 'user'
+ AND channel_ingested
+) AS channel_ingested;
+
+-- name: GetChannelMediaPendingUntil :one
+-- The latest unexpired media deadline gates a channel task. Using a durable
+-- task fire_at means a process restart still produces the placeholder fallback.
+SELECT channel_media_pending_until
+FROM chat_message
+WHERE chat_session_id = $1
+ AND role = 'user'
+ AND channel_media_pending_until > now()
+ORDER BY channel_media_pending_until DESC
+LIMIT 1;
+
+-- name: ClearChatMessageChannelMediaPending :exec
+UPDATE chat_message
+SET channel_media_pending_until = NULL
+WHERE id = $1 AND chat_session_id = $2;
+
-- name: LinkChatMessageToTask :exec
UPDATE chat_message
SET task_id = $2
WHERE id = $1 AND role = 'user';
+-- name: LinkUnownedChannelChatMessagesToTask :exec
+-- Seals the trailing channel-message batch to its task. The task row and these
+-- links are committed together, so an older in-flight task cannot absorb a
+-- newer media message and a later assistant row cannot hide that message.
+UPDATE chat_message AS message
+SET task_id = @task_id
+WHERE message.chat_session_id = @chat_session_id
+ AND message.role = 'user'
+ AND message.task_id IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM chat_message AS prior
+ WHERE prior.chat_session_id = @chat_session_id
+ AND prior.role != 'user'
+ AND (prior.created_at, prior.id) > (message.created_at, message.id)
+ );
+
+-- name: DeferChatTaskForSealedPendingMedia :one
+-- Closes the enqueue-vs-append race: under READ COMMITTED a media message can
+-- commit between GetChannelMediaPendingUntil and the batch seal above, landing
+-- an unexpired media marker inside a task the deadline read decided was
+-- 'queued'. Re-derive the deferral from the sealed batch itself, in the same
+-- transaction, so a task is never claimable while its own input still has an
+-- unexpired marker. No row (ErrNoRows) means no correction was needed.
+UPDATE agent_task_queue AS task
+SET status = 'deferred', fire_at = pending.max_until
+FROM (
+ SELECT max(message.channel_media_pending_until) AS max_until
+ FROM chat_message AS message
+ WHERE message.task_id = @task_id
+ AND message.role = 'user'
+ AND message.channel_media_pending_until > now()
+) AS pending
+WHERE task.id = @task_id
+ AND pending.max_until IS NOT NULL
+ AND (task.fire_at IS NULL OR task.fire_at < pending.max_until)
+RETURNING task.*;
+
-- name: DeleteUserChatMessageByTask :one
DELETE FROM chat_message
WHERE task_id = $1 AND role = 'user'
@@ -205,7 +291,7 @@ RETURNING *;
-- name: ListChatMessages :many
SELECT * FROM chat_message
WHERE chat_session_id = $1
-ORDER BY created_at ASC;
+ORDER BY created_at ASC, id ASC;
-- name: ListChatInputMessages :many
-- Loads the immutable user-message input batch owned by a direct-chat task.
@@ -240,10 +326,13 @@ WHERE id = $1;
INSERT INTO agent_task_queue (
agent_id, runtime_id, issue_id, status, priority, chat_session_id,
initiator_user_id, originator_user_id, accountable_user_id, force_fresh_session, runtime_mcp_overlay,
- runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id
+ runtime_connected_apps, originator_source, trigger_evidence_kind, trigger_evidence_ref_id,
+ fire_at
)
VALUES (
- $1, $2, NULL, 'queued', $3, $4, $5,
+ $1, $2, NULL,
+ CASE WHEN sqlc.narg('fire_at')::timestamptz IS NULL THEN 'queued' ELSE 'deferred' END,
+ $3, $4, $5,
sqlc.narg(originator_user_id),
sqlc.narg(accountable_user_id),
COALESCE(sqlc.narg('force_fresh_session')::boolean, FALSE),
@@ -251,17 +340,39 @@ VALUES (
sqlc.narg(runtime_connected_apps),
sqlc.narg(originator_source),
sqlc.narg(trigger_evidence_kind),
- sqlc.narg(trigger_evidence_ref_id)
+ sqlc.narg(trigger_evidence_ref_id),
+ sqlc.narg('fire_at')::timestamptz
)
RETURNING *;
+-- name: PromoteChannelChatTasksIfMediaReady :many
+-- Media completion may race with the 3s run batcher. Promote every original
+-- channel task waiting for this session only after all unexpired media markers
+-- are gone; retry/escalation/direct-chat deferred tasks are excluded.
+UPDATE agent_task_queue AS task
+SET status = 'queued', fire_at = NULL
+WHERE task.chat_session_id = @chat_session_id
+ AND task.status = 'deferred'
+ AND task.issue_id IS NULL
+ AND task.parent_task_id IS NULL
+ AND task.escalation_for_task_id IS NULL
+ AND NOT EXISTS (
+ SELECT 1
+ FROM chat_message AS message
+ WHERE message.chat_session_id = @chat_session_id
+ AND message.role = 'user'
+ AND message.channel_media_pending_until > now()
+ )
+RETURNING task.*;
+
-- name: SetChatTaskInputOwnerSelf :one
-- Stamps a freshly-created direct-chat task as the owner of its own input batch
-- (chat_input_task_id = id), so a later claim loads exactly the user messages
-- tagged with this task id (ListChatInputMessages) rather than scanning trailing
--- history. Runs in the same transaction as CreateChatTask + the user message
--- insert on the direct-send path. Channel and legacy tasks skip this call and
--- keep chat_input_task_id NULL, so a rolling deploy never replays their history.
+-- history. Runs in the same transaction as CreateChatTask + message ownership:
+-- direct-send inserts one owned message, while channel enqueue seals its
+-- trailing unowned batch. Legacy tasks keep chat_input_task_id NULL and retain
+-- the trailing-history fallback during rolling deploys.
UPDATE agent_task_queue
SET chat_input_task_id = id
WHERE id = $1