Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7573 fix(lark): clear the Typing reaction without trusting in-process state (#8656)
苗大3bacc41f8488
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex be618070c0..90624e6772 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -44,7 +44,7 @@ This keeps Docker simple while still isolating schema and data.- Node.js `22`- `pnpm` `10.28.2`-- Go `1.26.6`+- Go `1.26.9`- Docker## Important Rulesdiff --git a/README.md b/README.mdindex 7aa8c9d37d..4fd378aa9e 100644--- a/README.md+++ b/README.md@@ -246,7 +246,7 @@ The docs are also available in [简体中文](https://multica.ai/docs/zh), [日Contributors: start with the [Contributing Guide](CONTRIBUTING.md).-**Prerequisites:** [Node.js](https://nodejs.org/) 22, [pnpm](https://pnpm.io/) 10.28.2, [Go](https://go.dev/) 1.26.6, [Docker](https://www.docker.com/)+**Prerequisites:** [Node.js](https://nodejs.org/) 22, [pnpm](https://pnpm.io/) 10.28.2, [Go](https://go.dev/) 1.26.9, [Docker](https://www.docker.com/)```bashmake devdiff --git a/README.zh.md b/README.zh.mdindex e3df62aba8..5317472c33 100644--- a/README.zh.md+++ b/README.zh.md@@ -238,7 +238,7 @@ Multica 不自带模型。它驱动的是你本来就装好、登录好的那些想参与贡献,先看[贡献指南](CONTRIBUTING.md)。-**环境要求:**[Node.js](https://nodejs.org/) 22、[pnpm](https://pnpm.io/) 10.28.2、[Go](https://go.dev/) 1.26.6、[Docker](https://www.docker.com/)+**环境要求:**[Node.js](https://nodejs.org/) 22、[pnpm](https://pnpm.io/) 10.28.2、[Go](https://go.dev/) 1.26.9、[Docker](https://www.docker.com/)```bashmake devdiff --git a/SELF_HOSTING_ADVANCED.md b/SELF_HOSTING_ADVANCED.mdindex 97db85239f..4a59f3d242 100644--- a/SELF_HOSTING_ADVANCED.md+++ b/SELF_HOSTING_ADVANCED.md@@ -428,7 +428,7 @@ If you are upgrading from a binary that pre-dates MUL-2957 (or the auto-hook faiIf you prefer to build and run services manually:-**Prerequisites:** Go 1.26.6, Node.js 22, pnpm 10.28.2, PostgreSQL 17 — a stock install is enough, see [Database Setup](#database-setup).+**Prerequisites:** Go 1.26.9, Node.js 22, pnpm 10.28.2, PostgreSQL 17 — a stock install is enough, see [Database Setup](#database-setup).```bash# Start your PostgreSQL (or use: docker compose up -d postgres)diff --git a/docs/lark-typing-cleanup.md b/docs/lark-typing-cleanup.mdnew file mode 100644index 0000000000..a9212c0e3f--- /dev/null+++ b/docs/lark-typing-cleanup.md@@ -0,0 +1,104 @@+# Lark Typing reaction cleanup++Before sending an Add request, the server records each input in+`channel_typing_reaction`, including the source message, session, workspace,+installation and encrypted credential snapshot. A failed registration prevents+the Add. Cleanup records survive deletion of the original session or installation.++Terminal processing enumerates every input in the shared ledger, including+coalesced inputs that are not the reply delivery's trigger. Cleanup ownership is+monotonic: an Add returning after another replica observes termination cannot+restore an active state. Failed flushes persist an input cutoff and context+revision before detached ingestion, so taskless settlement also works when it+precedes Add registration. Later inputs and rolled-back transactions do not+authorize cleanup of the wrong turn.++Known reaction IDs are deleted precisely. Both sweeps require the reaction's+operator type to be `app` and its operator ID to match the installation's App ID;+other apps and humans are preserved. An empty sweep cannot acknowledge an+unfinished Add before its retention deadline. Legacy unregistered reactions retain+the delivery-anchor fallback, which cannot reconstruct every historical input.++A taskless indicator expires two minutes after registration. This recovers the+badge when a hard crash loses an in-memory debounce timer after Add succeeds.+It does not settle the input, cancel a task, or autonomously restart a lost run;+the channel engine can process that input on subsequent traffic. A long burst+can therefore lose its oldest taskless indicators before flushing. Inputs with+active tasks and newer inputs keep their own indicators, within the seven-day+maximum lifetime below.++## Retry and retention limits++- The worker runs every 30 seconds, claims at most 100 rows using `SKIP LOCKED`,+ and applies a 30-second to one-hour backoff. Its pass has a ten-second budget;+ each remote operation has a two-second budget. It does not hold database locks+ across remote calls.+- Claims advance retry counters before remote execution. A claimed row that does+ not fit the pass budget is deferred too; the counter measures claims, not HTTP+ attempts. Backlog latency and throughput are not guaranteed.+- All indicators have a seven-day maximum lifetime from registration, including+ running tasks, uncertain Adds and permanent credential failures. No new remote+ retries are claimed after that deadline. An in-flight call has at most a+ two-second budget. A late Add result cannot resurrect an expired ledger row.+- Confirmed cleanup erases its encrypted snapshot immediately. Expiry erases the+ snapshot and records `abandoned_at`, leaving `cleaned_at` null: this is an+ explicit failed terminal outcome, not a claim that the remote badge disappeared.+ A deleted workspace retains credentials only within the same remaining window;+ it does not restart the retention clock. Revoked credentials, permanently failed+ APIs or arbitrarily late remote writes can leave a badge requiring manual removal.+- Expiration and pruning each get an independent two-second database budget before+ remote retries, every 30 seconds. Each handles at most 1,000 rows with+ `SKIP LOCKED`. Non-secret success/failure tombstones are pruned seven days after+ their terminal timestamp. Physical redaction requires a healthy running worker+ and database: downtime, locks or maintenance backlog can delay it beyond the+ logical deadline. Database backups follow the operator's separate retention+ policy. Do not describe this as a guaranteed wall-clock erasure SLA.+- Each workspace has at most 1,000 pending ledger slots. A unique partial index+ arbitrates concurrent registration; a full quota or a slot collision skips the+ cosmetic Add without blocking input processing. Migration abandons/redacts any+ existing pending rows beyond that quota. Active tasks themselves are unaffected.+ Operators should treat repeated quota skips as a capacity incident, not normal+ successful processing. Increasing this cap requires an explicit capacity review.++Expiry emits a warning with workspace ID and count; maintenance failures emit an+error; quota/contention skips and failed remote withdrawals emit warnings without+credentials. Alert on these events and on an increasing overdue-redaction count.+The following read-only query reports the durable operational state without+exposing snapshots:++```sql+SELECT workspace_id,+ count(*) FILTER (WHERE cleaned_at IS NULL AND abandoned_at IS NULL) AS pending,+ count(*) FILTER (WHERE cleaned_at IS NULL AND abandoned_at IS NULL+ AND created_at <= now() - interval '7 days') AS overdue_redaction,+ count(*) FILTER (WHERE abandoned_at IS NOT NULL) AS abandoned,+ min(created_at) FILTER (WHERE cleaned_at IS NULL AND abandoned_at IS NULL) AS oldest_pending+FROM channel_typing_reaction GROUP BY workspace_id;+```++Remote retry claims still advance the backoff before execution; a 100-row batch+can exceed the ten-second pass budget. Attempt counters count claims, not HTTP+calls, and retry throughput is not guaranteed. This cannot starve the independent+credential/GC passes, but requires workload-based capacity validation before rollout.++## Migrations and rollback++Migration 565 adds the ledger and taskless settlement flag. Migrations 566–568+build the three indexes concurrently and register invalid-index cleanup hooks.+Migration 569 adds the retention outcome and quota slots; 570–572 build quota,+expiry and abandoned-record indexes with the same interrupted-build recovery.+Interrupted builds are dropped and rebuilt before being marked applied; valid+indexes are preserved on retry. There are no new foreign keys or cascading deletes.++Validate upgrades using the complete historical schema, retained input rows,+repeated `up`, and interrupted-index recovery. Four migrations against a minimal+table fixture alone do not establish full upgrade compatibility.++Application rollback preserves the schema, ledger and encryption keys. An older+server may not enforce the new quota/expiry policy. Keep a compatible cleanup+worker running or perform an explicitly reviewed offline redaction before retiring+it; image rollback alone does not preserve these new retention guarantees.+Bare `migrate down` rolls back all+applied migrations in the directory, not just these eight, and must not be used as+an application rollback shortcut. Review pending cleanup records before any+separately planned schema removal.diff --git a/scripts/dev.sh b/scripts/dev.shindex 40e374bf86..312de856f9 100755--- a/scripts/dev.sh+++ b/scripts/dev.sh@@ -13,7 +13,7 @@ command -v docker >/dev/null 2>&1 || missing+=("docker")if [ ${#missing[@]} -gt 0 ]; thenecho "✗ Missing prerequisites: ${missing[*]}"- echo " Please install: Node.js 22, pnpm 10.28.2, Go 1.26.6, Docker"+ echo " Please install: Node.js 22, pnpm 10.28.2, Go 1.26.9, Docker"exit 1fidiff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 088c1f31db..b754ad06d2 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -154,6 +154,12 @@ var concurrentIndexCleanups = map[string]string{"556_wakeup_system_rule_index": "issue_wakeup_system_rule_idx","559_issue_child_event_id": "issue_child_event_id_idx","560_issue_child_event_pending": "issue_child_event_pending_idx",+ "566_channel_typing_reaction_id_idx": "channel_typing_reaction_id_idx",+ "567_channel_typing_reaction_retry_idx": "channel_typing_reaction_retry_idx",+ "568_channel_typing_reaction_gc_idx": "channel_typing_reaction_gc_idx",+ "570_channel_typing_quota_idx": "channel_typing_reaction_quota_idx",+ "571_channel_typing_expiry_idx": "channel_typing_reaction_expiry_idx",+ "572_channel_typing_abandoned_idx": "channel_typing_reaction_abandoned_idx","510_wakeup_id": "issue_wakeup_id_idx","511_wakeup_issue": "issue_wakeup_issue_idx","512_wakeup_due": "issue_wakeup_due_idx",diff --git a/server/cmd/migrate/migrate_typing_cleanup_test.go b/server/cmd/migrate/migrate_typing_cleanup_test.gonew file mode 100644index 0000000000..b7d5e5227a--- /dev/null+++ b/server/cmd/migrate/migrate_typing_cleanup_test.go@@ -0,0 +1,157 @@+package main++import (+ "context"+ "errors"+ "fmt"+ "math/rand/v2"+ "os"+ "path/filepath"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgconn"+)++// FIXME(test-integration): Exercises PostgreSQL interrupted concurrent builds and+// the production migration hooks; requires the isolated test database.+func TestTypingCleanupRepairsInterruptedIndexes(t *testing.T) {+ versions := []string{+ "565_channel_typing_cleanup",+ "566_channel_typing_reaction_id_idx",+ "567_channel_typing_reaction_retry_idx",+ "568_channel_typing_reaction_gc_idx",+ "569_channel_typing_limits",+ "570_channel_typing_quota_idx",+ "571_channel_typing_expiry_idx",+ "572_channel_typing_abandoned_idx",+ }+ files := make([]string, len(versions))+ for i, version := range versions {+ files[i] = filepath.Join("..", "..", "migrations", version+".up.sql")+ }+ for i, index := range []string{+ "channel_typing_reaction_id_idx",+ "channel_typing_reaction_retry_idx",+ "channel_typing_reaction_gc_idx",+ "channel_typing_reaction_quota_idx",+ "channel_typing_reaction_expiry_idx",+ "channel_typing_reaction_abandoned_idx",+ } {+ t.Run(index, func(t *testing.T) {+ buildPosition := i + 1+ if i >= 3 {+ buildPosition+++ }+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)+ defer cancel()+ admin := openTestPool(t)+ schema := fmt.Sprintf("typing_index_%d_%d", time.Now().UnixNano(), rand.Uint32())+ schemaIdent := pgx.Identifier{schema}.Sanitize()+ if _, err := admin.Exec(ctx, "CREATE SCHEMA "+schemaIdent); err != nil {+ t.Fatal(err)+ }+ t.Cleanup(func() {+ cleanupCtx, cleanupCancel := context.WithTimeout(context.Background(), 10*time.Second)+ defer cleanupCancel()+ if _, err := admin.Exec(cleanupCtx, "DROP SCHEMA "+schemaIdent+" CASCADE"); err != nil {+ t.Errorf("drop isolated schema: %v", err)+ }+ })+ // Scope every connection so the real SQL and production hooks are+ // exercised unchanged, including their unqualified relation names.+ pool := openTestPoolWithSearchPath(t, schema)+ if _, err := pool.Exec(ctx, "CREATE TABLE chat_message (id uuid NOT NULL)"); err != nil {+ t.Fatal(err)+ }+ tableSQL, err := os.ReadFile(files[0])+ if err != nil {+ t.Fatal(err)+ }+ if _, err := pool.Exec(ctx, string(tableSQL)); err != nil {+ t.Fatal(err)+ }+ limitsSQL, err := os.ReadFile(files[4])+ if err != nil {+ t.Fatal(err)+ }+ if _, err := pool.Exec(ctx, string(limitsSQL)); err != nil {+ t.Fatal(err)+ }+ buildSQL, err := os.ReadFile(files[buildPosition])+ if err != nil {+ t.Fatal(err)+ }+ // Hold a writer lock so the actual concurrent build is interrupted+ // after its catalog entry exists. No pg_catalog mutation or mock DDL.+ blocker, err := pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer blocker.Rollback(context.Background())+ if _, err := blocker.Exec(ctx, "LOCK TABLE channel_typing_reaction IN ROW EXCLUSIVE MODE"); err != nil {+ t.Fatal(err)+ }+ builder, err := pool.Acquire(ctx)+ if err != nil {+ t.Fatal(err)+ }+ // Close instead of returning a connection with changed session state.+ conn := builder.Hijack()+ defer conn.Close(context.Background())+ if _, err := conn.Exec(ctx, "SET statement_timeout = '2s'"); err != nil {+ t.Fatal(err)+ }+ _, buildErr := conn.Exec(ctx, string(buildSQL))+ var pgErr *pgconn.PgError+ if !errors.As(buildErr, &pgErr) || pgErr.Code != "57014" {+ t.Fatalf("want interrupted build (57014), got %v", buildErr)+ }+ if err := blocker.Rollback(ctx); err != nil {+ t.Fatal(err)+ }+ assertIndexValidity(t, pool, schema, index, false)+ indexOID := func() uint32 {+ t.Helper()+ var oid uint32+ if err := pool.QueryRow(ctx, "SELECT to_regclass($1)::oid", index).Scan(&oid); err != nil {+ t.Fatal(err)+ }+ return oid+ }+ invalidOID := indexOID()+ opts := runOptions{+ Direction: "up", Files: files,+ SchemaMigrationsTable: schema + ".schema_migrations",+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: preMigrationHooks,+ }+ if err := runMigrations(ctx, pool, opts); err != nil {+ t.Fatal(err)+ }+ assertIndexReadyAndValid(t, pool, schema, index, true)+ rebuiltOID := indexOID()+ if rebuiltOID == invalidOID {+ t.Fatal("INVALID index was not dropped and rebuilt")+ }+ var applied int+ if err := pool.QueryRow(ctx, "SELECT count(*) FROM schema_migrations WHERE version = ANY($1)", versions).Scan(&applied); err != nil || applied != len(versions) {+ t.Fatalf("want all migrations recorded, got %d: %v", applied, err)+ }+ // Cover a completed build whose migration stamp was interrupted:+ // the hook must preserve the valid index on retry.+ if _, err := pool.Exec(ctx, "DELETE FROM schema_migrations WHERE version = $1", versions[buildPosition]); err != nil {+ t.Fatal(err)+ }+ if err := runMigrations(ctx, pool, opts); err != nil {+ t.Fatal(err)+ }+ if indexOID() != rebuiltOID {+ t.Fatal("retry replaced an already-valid index")+ }+ assertIndexReadyAndValid(t, pool, schema, index, true)+ t.Log("interrupted INVALID index dropped and rebuilt; all migrations recorded; valid retry preserves index")+ })+ }+}diff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex 6f6773cf89..a2432fe75d 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -793,6 +793,10 @@ func main() {go h.ChannelSupervisor.Run(sweepCtx)}+ if h.LarkTyping != nil {+ go h.LarkTyping.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.diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex adca0985dd..42b49d8b16 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -615,10 +615,11 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Buspatcher.Register(bus)// Typing indicator: shows a "processing" reaction on the user's- // message while the agent is working, then removes it before the- // reply is sent. Best-effort; failures are logged only.+ // message while the agent is working. Terminal cleanup has its own+ // budget, with a durable retry worker for failed or missed cleanup.typingIndicator := lark.NewTypingIndicatorManager(larkClient, installSvc, cs, slog.Default())patcher.SetTypingIndicatorManager(typingIndicator)+ h.LarkTyping = typingIndicator// Inbound pipeline seams: lark_inbound_audit logger and the// shared channel-agnostic chat-session service. They back thediff --git a/server/go.mod b/server/go.modindex cd664420bc..f138abf5b2 100644--- a/server/go.mod+++ b/server/go.mod@@ -1,6 +1,6 @@module github.com/multica-ai/multica/server-go 1.26.6+go 1.26.9require (github.com/aws/aws-sdk-go-v2 v1.47.0@@ -71,7 +71,7 @@ require (github.com/tidwall/sjson v1.2.5 // indirectgo.uber.org/atomic v1.11.0 // indirectgolang.org/x/mod v0.41.0 // indirect- golang.org/x/net v0.59.0 // indirect+ golang.org/x/net v0.60.0 // indirectgolang.org/x/telemetry v0.0.0-20260910141331-15ceca2b0a1f // indirectgolang.org/x/text v0.42.0 // indirectgolang.org/x/tools v0.50.0 // indirectdiff --git a/server/go.sum b/server/go.sumindex 269da211a2..ed102b84b7 100644--- a/server/go.sum+++ b/server/go.sum@@ -170,8 +170,8 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=golang.org/x/mod v0.41.0 h1:qJmnOUb4YB+FsEuM3HcWucdZASCPGhsX6uljO6pog0c=golang.org/x/mod v0.41.0/go.mod h1:Ek9pY8RKWXwsWvd3rQiHYtMqkjSUV+s1Rj7j4H5Ur6o=-golang.org/x/net v0.59.0 h1:5zfYln+w5XCxwrnMMJPufRgNoXEaGxl0wo5GqPXyues=-golang.org/x/net v0.59.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=+golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU=+golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg=golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk=golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0=golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo=diff --git a/server/internal/events/bus.go b/server/internal/events/bus.goindex 3636cadbc4..95e035afb9 100644--- a/server/internal/events/bus.go+++ b/server/internal/events/bus.go@@ -5,6 +5,14 @@ import ("sync")+// ChannelReactionTarget retains the non-secret cleanup anchor when a transaction+// deletes the delivery row. It is internal bus metadata, never a client payload.+type ChannelReactionTarget struct {+ ChannelType string+ InstallationID string+ MessageID string+}+// Event represents a domain event published by handlers or services.type Event struct {Type string // e.g. "issue:created", "inbox:new"@@ -17,8 +25,9 @@ type Event struct {// event to a more specific scope than `workspace:{WorkspaceID}`. When set// these tell the listener which Redis stream / Hub room to publish on// without re-deserializing Payload. See MUL-1138 phase 1.- TaskID string- ChatSessionID string+ TaskID string+ ChatSessionID string+ ChannelReactionTarget *ChannelReactionTarget `json:"-"`}// Handler is a function that processes an event.diff --git a/server/internal/handler/chat.go b/server/internal/handler/chat.goindex bf19540531..c375a29c19 100644--- a/server/internal/handler/chat.go+++ b/server/internal/handler/chat.go@@ -14,6 +14,7 @@ import ("github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/analytics"+ "github.com/multica-ai/multica/server/internal/events"obsmetrics "github.com/multica-ai/multica/server/internal/metrics""github.com/multica-ai/multica/server/internal/middleware""github.com/multica-ai/multica/server/internal/service"@@ -584,6 +585,7 @@ func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request)// request unarchives and nil for a web-only chat; BroadcastCancelledTasks// is a no-op on an empty slice.var cancelled []db.AgentTaskQueue+ var reactionTargets map[string]*events.ChannelReactionTargetif req.Archived {// Read the binding BEFORE the delete below, which is what erases the@@ -636,6 +638,11 @@ func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusInternalServerError, "failed to read chat session channel binding")return}+ reactionTargets, err = service.CaptureChannelReactionTargets(r.Context(), qtx, cancelled)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to capture channel reaction targets")+ return+ }if err := qtx.DeleteChannelChatSessionBindingBySession(r.Context(), session.ID); err != nil {writeError(w, http.StatusInternalServerError, "failed to clear chat session channel binding")return@@ -655,7 +662,7 @@ func (h *Handler) SetChatSessionArchived(w http.ResponseWriter, r *http.Request)// clients drop the row instead of showing it queued until the next// refresh, and wakes the runtime so a queued successor is claimed now// rather than at the daemon's next poll.- h.TaskService.BroadcastCancelledTasks(r.Context(), workspaceID, cancelled)+ h.TaskService.BroadcastCancelledTasks(r.Context(), workspaceID, cancelled, reactionTargets)resolvedSessionID := uuidToString(updated.ID)status := updated.Status@@ -727,6 +734,12 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {return}+ reactionTargets, err := service.CaptureChannelReactionTargets(r.Context(), qtx, cancelled)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to capture channel reaction targets")+ return+ }+// channel_chat_session_binding used to carry a chat_session FK with// ON DELETE CASCADE; MUL-3515 §4 dropped every channel_* foreign key, so// prune the binding here in the same tx that deletes its chat_session.@@ -787,7 +800,7 @@ func (h *Handler) DeleteChatSession(w http.ResponseWriter, r *http.Request) {// The workspace has to come from the session we just deleted: the tasks were// cancelled and returned before the delete, so they still carry its id, but// the row they would be resolved through is gone by now.- h.TaskService.BroadcastCancelledTasks(r.Context(), workspaceID, cancelled)+ h.TaskService.BroadcastCancelledTasks(r.Context(), workspaceID, cancelled, reactionTargets)resolvedSessionID := uuidToString(session.ID)h.publishChat(protocol.EventChatSessionDeleted, workspaceID, "member", userID, resolvedSessionID, protocol.ChatSessionDeletedPayload{diff --git a/server/internal/handler/chat_reaction_target_test.go b/server/internal/handler/chat_reaction_target_test.gonew file mode 100644index 0000000000..02246d81ca--- /dev/null+++ b/server/internal/handler/chat_reaction_target_test.go@@ -0,0 +1,84 @@+package handler++import (+ "context"+ "encoding/json"+ "errors"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/jackc/pgx/v5"+ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++func TestChatSessionRemovalCarriesReactionTargetsAfterCommit(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ for _, action := range []string{"delete", "archive"} {+ t.Run(action, func(t *testing.T) {+ f := newArchiveCancelFixture(t, "reaction targets "+action)+ installationID := dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": testWorkspaceID, "agent_id": f.agentID,+ "channel_type": "feishu", "installer_user_id": testUserID,+ })+ bindingID := dbfx.Insert(t, "channel_chat_session_binding", testutil.Cols{+ "chat_session_id": f.sessionID, "installation_id": installationID,+ "channel_type": "feishu", "channel_chat_id": "reaction-room", "chat_type": "group",+ })+ expected := map[string]string{f.queuedTaskID: "queued-trigger", f.runningTaskID: "running-trigger"}+ for taskID, messageID := range expected {+ dbfx.InsertNoID(t, "channel_task_delivery", testutil.Cols{+ "task_id": taskID, "binding_id": bindingID, "installation_id": installationID,+ "channel_type": "feishu", "channel_chat_id": "reaction-room", "chat_type": "group",+ "channel_message_id": messageID, "route_revision": 1,+ }, "task_id = $1", taskID)+ }+ seen := make(chan events.Event, 2)+ testHandler.Bus.Subscribe(protocol.EventTaskCancelled, func(e events.Event) {+ if e.ChatSessionID != f.sessionID {+ return+ }+ // Observe through the pool, not the transaction: the event must be post-commit.+ _, err := testHandler.Queries.GetChannelTaskDelivery(context.Background(), parseUUID(e.TaskID))+ if !errors.Is(err, pgx.ErrNoRows) {+ t.Errorf("cancel published before delivery deletion committed: %v", err)+ }+ seen <- e+ })+ if action == "archive" {+ f.archive(t)+ } else {+ req := httptest.NewRequest(http.MethodDelete, "/api/chat/sessions/"+f.sessionID, nil)+ req.Header.Set("X-User-ID", testUserID)+ req = withChatTestWorkspaceCtx(t, withURLParam(req, "sessionId", f.sessionID))+ w := httptest.NewRecorder()+ testHandler.DeleteChatSession(w, req)+ if w.Code != http.StatusNoContent {+ t.Fatalf("delete: %d %s", w.Code, w.Body.String())+ }+ }+ if len(seen) != len(expected) {+ t.Fatalf("got %d cancellation events, want %d", len(seen), len(expected))+ }+ for range expected {+ e := <-seen+ target := e.ChannelReactionTarget+ if target == nil || target.ChannelType != "feishu" || target.InstallationID != installationID || target.MessageID != expected[e.TaskID] {+ t.Fatalf("task %s lost its frozen reaction target: %+v", e.TaskID, target)+ }+ payload, err := json.Marshal(e)+ if err != nil {+ t.Fatal(err)+ }+ if strings.Contains(string(payload), target.MessageID) || strings.Contains(string(payload), installationID) {+ t.Fatalf("internal cleanup metadata leaked into serialized event: %s", payload)+ }+ }+ })+ }+}diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 25b478822f..bfe72f9bf7 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -318,6 +318,8 @@ type Handler struct {// where the storage backend exists; main.go starts it as an independent// worker goroutine. Nil when no storage backend is configured.ChannelMediaReconciler *service.ChannelMediaReconciler+ // LarkTyping owns the durable reaction cleanup worker, started under sweepCtx.+ LarkTyping *lark.TypingIndicatorManager// 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/handler/workspace_delete_manifest_test.go b/server/internal/handler/workspace_delete_manifest_test.goindex 584c7d0887..cb9ede8950 100644--- a/server/internal/handler/workspace_delete_manifest_test.go+++ b/server/internal/handler/workspace_delete_manifest_test.go@@ -47,6 +47,7 @@ var workspaceDeletionManifest = map[string]workspaceDeleteAction{"channel_outbound_message": workspaceDelete,"channel_reply_delivery": workspaceDelete,"channel_task_delivery": workspaceDelete,+ "channel_typing_reaction": workspaceDeleteSettle, // Source deletion makes retained anchors eligible for the cleanup worker."channel_user_binding": workspaceDelete,"chat_draft_restore": workspaceDelete,"chat_message": workspaceDelete,diff --git a/server/internal/handler/workspace_typing_cleanup_test.go b/server/internal/handler/workspace_typing_cleanup_test.gonew file mode 100644index 0000000000..b7811e1451--- /dev/null+++ b/server/internal/handler/workspace_typing_cleanup_test.go@@ -0,0 +1,127 @@+package handler++import (+ "context"+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func TestDeleteWorkspace_RetainsTypingCleanupUntilAcknowledged(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ for _, outcome := range []string{"acknowledged", "expired"} {+ t.Run(outcome, func(t *testing.T) {+ ctx := context.Background()+ wsID := dbfx.Insert(t, "workspace", testutil.Cols{+ "name": "Typing cleanup", "slug": "handler-delete-typing-cleanup",+ })+ dbfx.Exec(t, `INSERT INTO member (workspace_id, user_id, role) VALUES ($1, $2, 'owner')`, wsID, testUserID)+ agentID := dbfx.Insert(t, "agent", testutil.Cols{+ "workspace_id": wsID, "name": "Typing cleanup", "owner_id": testUserID, "runtime_mode": "cloud",+ })+ sessionID := dbfx.Insert(t, "chat_session", testutil.Cols{+ "workspace_id": wsID, "agent_id": agentID, "creator_id": testUserID,+ })+ installationID := dbfx.Insert(t, "channel_installation", testutil.Cols{+ "workspace_id": wsID, "agent_id": agentID, "channel_type": "feishu", "installer_user_id": testUserID,+ })+ dbfx.Insert(t, "channel_chat_session_binding", testutil.Cols{+ "chat_session_id": sessionID, "installation_id": installationID,+ "channel_type": "feishu", "channel_chat_id": "typing-cleanup-room", "chat_type": "group",+ })+ messageID := dbfx.Insert(t, "chat_message", testutil.Cols{+ "chat_session_id": sessionID, "role": "user", "content": "pending input", "channel_ingested": true,+ })+ const snapshot = `{"app_id":"test-app","app_secret_enc":"test-encrypted-snapshot"}`+ reactionID := dbfx.Insert(t, "channel_typing_reaction", testutil.Cols{+ "id": testutil.Raw("gen_random_uuid()"), "workspace_id": wsID,+ "chat_session_id": sessionID, "chat_message_id": messageID, "installation_id": installationID,+ "channel_message_id": "remote-input", "installation_snapshot": snapshot,+ "reaction_id": "remote-reaction", "add_finished": true,+ })+ queries := db.New(testPool)+ rows, err := queries.ClaimChannelTypingReactionCleanup(ctx, parseUUID(sessionID))+ if err != nil || len(rows) != 0 {+ t.Fatalf("active input must not be claimed: rows=%d err=%v", len(rows), err)+ }++ req := withURLParam(newRequest(http.MethodDelete, "/api/workspaces/"+wsID, nil), "id", wsID)+ testutil.Call(t, testHandler.DeleteWorkspace, req).Want(http.StatusNoContent)+ for table, id := range map[string]string{+ "workspace": wsID, "chat_session": sessionID, "channel_installation": installationID, "chat_message": messageID,+ } {+ var exists bool+ dbfx.QueryRow(t, `SELECT EXISTS (SELECT 1 FROM `+table+` WHERE id = $1)`, id).Scan(&exists)+ if exists {+ t.Fatalf("%s source survived workspace deletion", table)+ }+ }++ // A fresh worker can claim without joining to the now-deleted workspace,+ // session or installation. The external anchor and encrypted snapshot survive.+ queries = db.New(testPool)+ rows, err = queries.ClaimChannelTypingReactionCleanup(ctx, parseUUID(sessionID))+ if err != nil || len(rows) != 1 {+ t.Fatalf("deleted workspace cleanup: rows=%d err=%v", len(rows), err)+ }+ row := rows[0]+ if row.ID != parseUUID(reactionID) || row.ChannelMessageID != "remote-input" || row.ReactionID != "remote-reaction" || !row.CleanupRequired || row.CleanedAt.Valid {+ t.Fatalf("cleanup anchor was lost or prematurely acknowledged: %+v", row)+ }+ var snapshotPreserved bool+ dbfx.QueryRow(t, `SELECT installation_snapshot = $2::jsonb FROM channel_typing_reaction WHERE id = $1`, reactionID, snapshot).Scan(&snapshotPreserved)+ if !snapshotPreserved {+ t.Fatal("cleanup lost the encrypted installation snapshot")+ }+ // Pruning must retain unacknowledged cleanup even when source data is gone.+ if err := queries.PruneChannelTypingReactionCleanup(ctx); err != nil {+ t.Fatal(err)+ }+ var pending bool+ dbfx.QueryRow(t, `SELECT EXISTS (SELECT 1 FROM channel_typing_reaction WHERE id = $1 AND cleaned_at IS NULL)`, reactionID).Scan(&pending)+ if !pending {+ t.Fatal("pruning dropped pending workspace cleanup")+ }+ if outcome == "expired" {+ dbfx.Exec(t, "UPDATE channel_typing_reaction SET created_at=now()-interval '8 days' WHERE id=$1", reactionID)+ expired, err := queries.ExpireChannelTypingReactionCleanup(ctx)+ if err != nil {+ t.Fatal(err)+ }+ found := false+ for _, row := range expired {+ if row.ID == parseUUID(reactionID) {+ found = true+ }+ }+ if !found {+ t.Fatal("deleted workspace credential retention has no terminal outcome")+ }+ var redacted, abandoned, cleaned bool+ dbfx.QueryRow(t, `SELECT installation_snapshot='{}'::jsonb, abandoned_at IS NOT NULL, cleaned_at IS NOT NULL FROM channel_typing_reaction WHERE id=$1`, reactionID).Scan(&redacted, &abandoned, &cleaned)+ if !redacted || !abandoned || cleaned {+ t.Fatal("expiry must erase credentials and record failure, not success")+ }+ rows, err := queries.ClaimChannelTypingReactionCleanup(ctx, parseUUID(sessionID))+ if err != nil || len(rows) != 0 {+ t.Fatalf("expired deletion still retries: %v %v", rows, err)+ }+ return+ }+ if err := queries.AcknowledgeChannelTypingReactionCleanup(ctx, db.AcknowledgeChannelTypingReactionCleanupParams{+ ID: row.ID, ReactionID: row.ReactionID,+ }); err != nil {+ t.Fatal(err)+ }+ var cleaned bool+ dbfx.QueryRow(t, `SELECT cleaned_at IS NOT NULL FROM channel_typing_reaction WHERE id = $1`, reactionID).Scan(&cleaned)+ if !cleaned {+ t.Fatal("cleanup could not be acknowledged after workspace deletion")+ }+ })+ }+}diff --git a/server/internal/integrations/channel/engine/resolvers.go b/server/internal/integrations/channel/engine/resolvers.goindex cd8aeb9e80..44579aa4e8 100644--- a/server/internal/integrations/channel/engine/resolvers.go+++ b/server/internal/integrations/channel/engine/resolvers.go@@ -55,10 +55,12 @@ const (// consumed by the outbound side (OutboundReplier / typing). It mirrors the// legacy lark.DispatchResult.type Result struct {- Outcome Outcome- DropReason DropReason- InstallationID pgtype.UUID- ChatSessionID pgtype.UUID+ Outcome Outcome+ DropReason DropReason+ InstallationID pgtype.UUID+ ChatSessionID pgtype.UUID+ // ChatMessageID identifies this persisted input, including before debounce creates a task.+ ChatMessageID pgtype.UUIDChannelBindingID pgtype.UUIDChannelRouteRevision int64// Sender is the platform-native sender id (e.g. Lark open_id), so the@@ -386,14 +388,14 @@ type OutboundReplier interface {// it.type TypingNotifier interface {// OnIngested shows the indicator for a successfully ingested message.- OnIngested(ctx context.Context, inst ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID)+ OnIngested(ctx context.Context, inst ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID, chatMessageID pgtype.UUID)// OnSettled clears the indicator for a session whose run trigger produced no// task (agent offline / archived, or an enqueue failure). In that case no// task lifecycle event is ever published, so the platform's own bus-driven// clear (on chat-done / task-failed) would never fire and the indicator would// stick. The Router calls this from the debounced flush. Idempotent: a// session with no indicator is a no-op.- OnSettled(ctx context.Context, sessionID pgtype.UUID)+ OnSettled(ctx context.Context, sessionID pgtype.UUID, scope TypingSettlement)}// ResolverSet is the per-platform bundle the Router runs the pipeline through.@@ -445,3 +447,10 @@ type SessionReader interface {GetChatSession(ctx context.Context, id pgtype.UUID) (db.ChatSession, error)GetWorkspace(ctx context.Context, id pgtype.UUID) (db.Workspace, error)}++// TypingSettlement identifies the failed flush's immutable input boundary.+// It excludes later arrivals and other context generations in the same session.+type TypingSettlement struct {+ WorkspaceID, InstallationID, ThroughMessageID pgtype.UUID+ ContextRevision int64+}diff --git a/server/internal/integrations/channel/engine/router.go b/server/internal/integrations/channel/engine/router.goindex d049cb5a50..71f2bcaab3 100644--- a/server/internal/integrations/channel/engine/router.go+++ b/server/internal/integrations/channel/engine/router.go@@ -274,7 +274,7 @@ func (r *Router) Handle(ctx context.Context, msg channel.InboundMessage) error {go func() {tctx, cancel := context.WithTimeout(context.Background(), r.replyTimeout)defer cancel()- set.Typing.OnIngested(tctx, inst, msg, res.ChatSessionID)+ set.Typing.OnIngested(tctx, inst, msg, res.ChatSessionID, res.ChatMessageID)}()}r.scheduleReply(set, inst, msg, res)@@ -564,6 +564,7 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channeOutcome: OutcomeIngested,InstallationID: inst.ID,ChatSessionID: sessionID,+ ChatMessageID: appendRes.MessageID,ChannelBindingID: appendRes.BindingID,ChannelRouteRevision: appendRes.RouteRevision,Sender: msg.Source.SenderID,@@ -674,12 +675,12 @@ func (r *Router) processClaimed(ctx context.Context, set ResolverSet, msg channeif revision == appendRes.ContextRevision {r.scheduleRunWithFresh(set, inst, msg, sessionID, identity.UserID,- res.ChannelBindingID, res.ChannelRouteRevision, forceFresh, revision,+ res.ChannelBindingID, res.ChannelRouteRevision, forceFresh, revision, appendRes.MessageID,)} else if pending.InitiatorUserID.Valid {r.scheduleRecoveredRun(set, inst, msg, sessionID, pending.InitiatorUserID,- res.ChannelBindingID, res.ChannelRouteRevision, revision,+ res.ChannelBindingID, res.ChannelRouteRevision, revision, appendRes.MessageID,)} else {slog.Warn("skipping recovered channel context without initiator snapshot",@@ -915,10 +916,11 @@ func (r *Router) scheduleRunWithFresh(routeRevision int64,fresh bool,contextRevision int64,+ throughMessageID pgtype.UUID,) {r.scheduleRunMode(set, inst, msg, sessionID, initiatorUserID, bindingID,- routeRevision, fresh, contextRevision, true,+ routeRevision, fresh, contextRevision, true, throughMessageID,)}@@ -928,10 +930,11 @@ func (r *Router) scheduleRecoveredRun(msg channel.InboundMessage,sessionID, initiatorUserID, bindingID pgtype.UUID,routeRevision, contextRevision int64,+ throughMessageID pgtype.UUID,) {r.scheduleRunMode(set, inst, msg, sessionID, initiatorUserID, bindingID,- routeRevision, false, contextRevision, false,+ routeRevision, false, contextRevision, false, throughMessageID,)}@@ -944,11 +947,12 @@ func (r *Router) scheduleRunMode(fresh bool,contextRevision int64,replace bool,+ throughMessageID pgtype.UUID,) {if r.batcher == nil {r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, bindingID,- routeRevision, fresh, contextRevision,+ routeRevision, fresh, contextRevision, throughMessageID,)return}@@ -959,7 +963,7 @@ func (r *Router) scheduleRunMode(// batch key; the pre-boundary flush remains armed independently.r.flushChatRun(set, inst, msg, sessionID, initiatorUserID, bindingID,- routeRevision, fresh, contextRevision,+ routeRevision, fresh, contextRevision, throughMessageID,)}if replace {@@ -984,6 +988,7 @@ func (r *Router) flushChatRun(routeRevision int64,forceFresh bool,contextRevision int64,+ throughMessageID pgtype.UUID,) {ctx, cancel := context.WithTimeout(context.Background(), chatRunFlushTimeout)defer cancel()@@ -992,7 +997,7 @@ func (r *Router) flushChatRun(if err != nil {r.logger.Error("channel router: flush reload chat session failed","chat_session_id", uuidString(sessionID), "err", err.Error())- r.clearTyping(ctx, set, sessionID)+ r.clearTyping(ctx, set, sessionID, TypingSettlement{WorkspaceID: inst.WorkspaceID, InstallationID: inst.ID, ThroughMessageID: throughMessageID, ContextRevision: contextRevision})return}if _, err := r.tasks.EnqueueChannelChatTask(@@ -1002,7 +1007,7 @@ func (r *Router) flushChatRun(// the platform's bus-driven typing clear can never fire. Clear the// indicator here (before any notice) so the "processing" reaction does// not stick on the user's message.- r.clearTyping(ctx, set, sessionID)+ r.clearTyping(ctx, set, sessionID, TypingSettlement{WorkspaceID: inst.WorkspaceID, InstallationID: inst.ID, ThroughMessageID: throughMessageID, ContextRevision: contextRevision})switch {case errors.Is(err, service.ErrChatTaskAgentNoRuntime):r.emitFlushReply(ctx, set, inst, msg, sessionID, bindingID, routeRevision, OutcomeAgentOffline)@@ -1018,9 +1023,9 @@ func (r *Router) flushChatRun(// clearTyping asks the platform to drop the "processing" indicator for a session// whose flush produced no task run. A nil TypingNotifier (platform without the// feature) is a no-op.-func (r *Router) clearTyping(ctx context.Context, set ResolverSet, sessionID pgtype.UUID) {+func (r *Router) clearTyping(ctx context.Context, set ResolverSet, sessionID pgtype.UUID, scope TypingSettlement) {if set.Typing != nil {- set.Typing.OnSettled(ctx, sessionID)+ set.Typing.OnSettled(ctx, sessionID, scope)}}diff --git a/server/internal/integrations/channel/engine/router_test.go b/server/internal/integrations/channel/engine/router_test.goindex 5de2571f24..a3750e9250 100644--- a/server/internal/integrations/channel/engine/router_test.go+++ b/server/internal/integrations/channel/engine/router_test.go@@ -216,20 +216,27 @@ func (f *fakeReplier) calls() []Result {}type fakeTyping struct {- mu sync.Mutex- count int- settled int+ settledScope TypingSettlement+ sequence []string+ messageID pgtype.UUID+ mu sync.Mutex+ count int+ settled int}-func (f *fakeTyping) OnIngested(_ context.Context, _ ResolvedInstallation, _ channel.InboundMessage, _ pgtype.UUID) {+func (f *fakeTyping) OnIngested(_ context.Context, _ ResolvedInstallation, _ channel.InboundMessage, _ pgtype.UUID, chatMessageID pgtype.UUID) {f.mu.Lock()defer f.mu.Unlock()f.count+++ f.messageID = chatMessageID+ f.sequence = append(f.sequence, "ingested")}-func (f *fakeTyping) OnSettled(_ context.Context, _ pgtype.UUID) {+func (f *fakeTyping) OnSettled(_ context.Context, _ pgtype.UUID, scope TypingSettlement) {f.mu.Lock()defer f.mu.Unlock()f.settled+++ f.settledScope = scope+ f.sequence = append(f.sequence, "settled")}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 }@@ -783,6 +790,12 @@ func TestRouter_Ingested_InTxMark_FinalizeNone(t *testing.T) {if !waitFor(time.Second, func() bool { return h.typing.calls() == 1 }) {t.Fatalf("ingest must show the typing indicator")}+ h.typing.mu.Lock()+ messageID := h.typing.messageID+ h.typing.mu.Unlock()+ if messageID != h.binder.appendResult.MessageID {+ t.Fatalf("typing lost persisted input identity: %v", messageID)+ }// Media resolution runs on its own goroutine (r.mediaWg), and the binding// happens only after it returns, so both of these are downstream of work// that Handle does not wait for. Reading them bare raced with that@@ -1003,8 +1016,8 @@ func TestRouter_ContextGenerationsUseIndependentBatchWindows(t *testing.T) {sessionID := h.binder.ensureIDinitiator := h.ident.id.UserID- h.router.scheduleRunWithFresh(h.router.sets[channel.TypeFeishu], h.inst.inst, msg, sessionID, initiator, pgtype.UUID{}, 1, false, 1)- h.router.scheduleRunWithFresh(h.router.sets[channel.TypeFeishu], h.inst.inst, msg, sessionID, initiator, pgtype.UUID{}, 1, false, 2)+ h.router.scheduleRunWithFresh(h.router.sets[channel.TypeFeishu], h.inst.inst, msg, sessionID, initiator, pgtype.UUID{}, 1, false, 1, pgtype.UUID{})+ h.router.scheduleRunWithFresh(h.router.sets[channel.TypeFeishu], h.inst.inst, msg, sessionID, initiator, pgtype.UUID{}, 1, false, 2, pgtype.UUID{})if got := h.router.batcher.pendingCount(); got != 2 {t.Fatalf("pending generation windows = %d, want 2", got)}@@ -1086,7 +1099,8 @@ func TestRouter_RecoveryDoesNotDelayLiveOlderGeneration(t *testing.T) {h.router.batcher = newTestBatcher(timers)msg := p2pMessage(t)h.router.scheduleRunWithFresh(h.router.sets[channel.TypeFeishu], h.inst.inst, msg,- h.binder.ensureID, h.ident.id.UserID, pgtype.UUID{}, 1, false, 1)+ h.binder.ensureID, h.ident.id.UserID, pgtype.UUID{}, 1, false, 1, pgtype.UUID{},+ )h.binder.appendResult.ContextRevision = 2h.binder.appendResult.PendingContexts = []PendingContext{@@ -1577,11 +1591,23 @@ func TestRouter_FlushOffline_RepliesAgentOffline(t *testing.T) {}) {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.+ // Inline failed enqueue precedes the detached ingestion hook. Its persisted+ // settlement boundary must suppress that later Add without a task event.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())}+ if !waitFor(time.Second, func() bool { return h.typing.calls() == 1 }) {+ t.Fatal("detached ingestion hook did not run")+ }+ h.typing.mu.Lock()+ defer h.typing.mu.Unlock()+ if h.typing.settledScope.ThroughMessageID != h.binder.appendResult.MessageID || h.typing.settledScope.WorkspaceID != h.inst.inst.WorkspaceID || h.typing.settledScope.InstallationID != h.inst.inst.ID {+ t.Fatalf("failed flush lost its durable input boundary: %+v", h.typing.settledScope)+ }+ if len(h.typing.sequence) != 2 || h.typing.sequence[0] != "settled" || h.typing.sequence[1] != "ingested" {+ t.Fatalf("unexpected inline flush/async Add ordering: %+v", h.typing.sequence)+ }+}func TestRouter_FlushArchived_ClearsTyping(t *testing.T) {diff --git a/server/internal/integrations/dingtalk/ack.go b/server/internal/integrations/dingtalk/ack.goindex 56e23e4fbd..a34e9a0e37 100644--- a/server/internal/integrations/dingtalk/ack.go+++ b/server/internal/integrations/dingtalk/ack.go@@ -57,7 +57,7 @@ func NewAckNotifier(client *Client, decrypt Decrypter, logger *slog.Logger, inpureturn &ackNotifier{client: client, decrypt: decrypt, logger: logger, inputs: inputs, active: make(map[string][]*ackState)}}-func (n *ackNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID) {+func (n *ackNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID, chatMessageID pgtype.UUID) {if !sessionID.Valid || msg.MessageID == "" || msg.Source.ChatID == "" {return}@@ -96,7 +96,7 @@ func (n *ackNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstal// session ID, so it cannot distinguish overlapping failed/pending generations.// Task terminal events instead use onInputsSettled with their owned input IDs.// This hook never marks input Done.-func (n *ackNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID) {+func (n *ackNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID, scope engine.TypingSettlement) {key := util.UUIDToString(sessionID)n.mu.Lock()states := n.active[key]diff --git a/server/internal/integrations/dingtalk/ack_archive_test.go b/server/internal/integrations/dingtalk/ack_archive_test.goindex afc008c323..4d4f1d9ff4 100644--- a/server/internal/integrations/dingtalk/ack_archive_test.go+++ b/server/internal/integrations/dingtalk/ack_archive_test.go@@ -21,7 +21,7 @@ func TestOutboundArchiveClearsPendingReceiptsOnlyForItsAgent(t *testing.T) {sid := sessionUUID(92)add := func(inst engine.ResolvedInstallation, name string, input byte, session byte) {n.client.rememberReplySource(inst.ID, sessionUUID(input), sessionUUID(session), groupReactionMessage(name))- n.OnIngested(context.Background(), inst, groupReactionMessage(name), sessionUUID(session))+ n.OnIngested(context.Background(), inst, groupReactionMessage(name), sessionUUID(session), sessionUUID(session))}add(inst, "pending", 1, 92)add(inst, "another-session", 2, 93)@@ -35,7 +35,7 @@ func TestOutboundArchiveClearsPendingReceiptsOnlyForItsAgent(t *testing.T) {bus.Publish(e)// A repeated hook for an archived input stays retired, even after restore.bus.Publish(events.Event{Type: protocol.EventAgentRestored, Payload: e.Payload})- n.OnIngested(context.Background(), inst, groupReactionMessage("pending"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("pending"), sid, sid)add(inst, "after-restore", 4, 92)want := []string{"add:pending:" + emotionAcknowledged, "add:another-session:" + emotionAcknowledged, "add:other-agent:" + emotionAcknowledged}if !slices.Equal((*actions)[:3], want) {@@ -72,7 +72,10 @@ func TestOutboundArchiveRecallsAddThatFinishesAfterArchive(t *testing.T) {mu.Unlock()return nil}- go func() { defer close(done); n.OnIngested(context.Background(), inst, msg, sessionUUID(92)) }()+ go func() {+ defer close(done)+ n.OnIngested(context.Background(), inst, msg, sessionUUID(92), sessionUUID(92))+ }()select {case <-started:case <-time.After(time.Second):@@ -95,7 +98,7 @@ func TestOutboundArchiveRecallsAddThatFinishesAfterArchive(t *testing.T) {func TestOutboundArchiveIgnoresInvalidPayload(t *testing.T) {for _, payload := range []any{nil, make(chan int), map[string]any{"agent": "wrong type"}, map[string]any{"agent": map[string]any{"id": "not-a-uuid"}}} {n, actions := newTestAckWithMessageIDs(time.Now)- n.OnIngested(context.Background(), engine.ResolvedInstallation{AgentID: sessionUUID(80)}, groupReactionMessage("pending"), sessionUUID(92))+ n.OnIngested(context.Background(), engine.ResolvedInstallation{AgentID: sessionUUID(80)}, groupReactionMessage("pending"), sessionUUID(92), sessionUUID(92))NewOutbound(nil, nil, n.client, n, nil).handleAgentArchived(events.Event{Payload: payload})if !slices.Equal(*actions, []string{"add:pending:" + emotionAcknowledged}) {t.Fatalf("invalid archive cleared receipt: %v", *actions)@@ -106,7 +109,7 @@ func TestOutboundArchiveIgnoresInvalidPayload(t *testing.T) {func TestOutboundArchiveWithoutNotifierOrAgentIsNoOp(t *testing.T) {NewOutbound(nil, nil, nil, nil, nil).handleAgentArchived(events.Event{})n, actions := newTestAckWithMessageIDs(time.Now)- n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage("pending"), sessionUUID(92))+ n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage("pending"), sessionUUID(92), sessionUUID(92))n.onAgentArchived(context.Background(), engine.ResolvedInstallation{}.AgentID)if !slices.Equal(*actions, []string{"add:pending:" + emotionAcknowledged}) {t.Fatalf("missing archive owner cleared receipt: %v", *actions)diff --git a/server/internal/integrations/dingtalk/ack_batch_test.go b/server/internal/integrations/dingtalk/ack_batch_test.goindex ffcdf1b34b..cd6a570b4a 100644--- a/server/internal/integrations/dingtalk/ack_batch_test.go+++ b/server/internal/integrations/dingtalk/ack_batch_test.go@@ -78,7 +78,7 @@ func TestAckBatchUsesSealedOwnershipAndInputOrder(t *testing.T) {slices.Reverse(order)}for _, name := range order {- n.OnIngested(ctx, inst, groupReactionMessage(name), sid)+ n.OnIngested(ctx, inst, groupReactionMessage(name), sid, sid)}if !slices.Equal(actions, tc.want) {t.Fatalf("actions=%v want=%v", actions, tc.want)@@ -105,11 +105,11 @@ func TestAckBatchDoesNotMoveAcrossTaskBoundary(t *testing.T) {q.rows[id] = db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true, ChannelContextRevision: pgtype.Int8{Int64: 1, Valid: true}}n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage(name))}- n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid, sid)a := q.rows[sessionUUID(92)]a.TaskID = sessionUUID(94)q.rows[a.ID] = a- n.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid, sid)if len(visible) != 2 {t.Fatalf("new batch removed old receipt: %v", visible)}@@ -132,7 +132,7 @@ func TestAckTerminalBeforeIngestDoesNotRecreateReceipt(t *testing.T) {// Even the local source capture may follow a fast terminal event.n.onInputsSettled(context.Background(), sid, []db.ChatMessage{row})n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage("a"))- n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid, sid)if calls != 0 || len(n.active) != 0 {t.Fatalf("late hook recreated receipt: calls=%d active=%v", calls, n.active)}@@ -156,7 +156,7 @@ func TestAckBatchRetriesWhenInputSealsDuringLookup(t *testing.T) {q.rows[id] = db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true}n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage(name))}- n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid, sid)q.read = func(id pgtype.UUID) {if id == sessionUUID(92) {q.read = nil@@ -166,7 +166,7 @@ func TestAckBatchRetriesWhenInputSealsDuringLookup(t *testing.T) {}}}- n.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid, sid)if len(visible) != 1 || !visible["b"] {t.Fatalf("sealing race left wrong receipts: %v", visible)}@@ -198,13 +198,16 @@ func TestAckBatchRecallsSupersededInFlightAdd(t *testing.T) {}return nil}- go func() { defer close(done); n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid) }()+ go func() {+ defer close(done)+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid, sid)+ }()select {case <-started:case <-time.After(time.Second):t.Fatal("add did not begin")}- n.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid, sid)close(release)select {case <-done:@@ -227,7 +230,7 @@ func TestAckBatchQueryFailureSkipsReceipt(t *testing.T) {t.Fatal("query failure guessed a batch")return nil}- n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid, sid)if len(n.active) != 0 {t.Fatal("failed query retained receipt")}@@ -255,7 +258,7 @@ func TestAckBatchRetriesFailedRecallOnNextMessage(t *testing.T) {id := sessionUUID(byte(92 + i))q.rows[id] = db.ChatMessage{ID: id, ChatSessionID: sid, Role: "user", ChannelIngested: true}n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage(name))- n.OnIngested(context.Background(), inst, groupReactionMessage(name), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage(name), sid, sid)if name == "b" && len(visible) != 2 {t.Fatalf("fixture did not leave failed recall visible: %v", visible)}@@ -279,7 +282,7 @@ func TestAckTerminalDuringBatchLookupDoesNotRecreateReceipt(t *testing.T) {t.Fatal("terminal event during lookup recreated receipt")return nil}- n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid, sid)}func TestAckBatchRejectsUnattributableInput(t *testing.T) {@@ -310,7 +313,7 @@ func TestAckBatchRejectsUnattributableInput(t *testing.T) {t.Fatal("unattributable input received reaction")return nil}- n.OnIngested(context.Background(), inst, msg, sid)+ n.OnIngested(context.Background(), inst, msg, sid, sid)})}}@@ -381,7 +384,7 @@ func TestAckConcurrentBatchKeepsLastInput(t *testing.T) {hooks.Add(1)go func() {defer hooks.Done()- n.OnIngested(ctx, inst, msg, sid)+ n.OnIngested(ctx, inst, msg, sid, sid)}()}hooks.Wait()diff --git a/server/internal/integrations/dingtalk/ack_failure_boundaries_test.go b/server/internal/integrations/dingtalk/ack_failure_boundaries_test.goindex 5aec5de483..609e6b9db1 100644--- a/server/internal/integrations/dingtalk/ack_failure_boundaries_test.go+++ b/server/internal/integrations/dingtalk/ack_failure_boundaries_test.go@@ -31,7 +31,7 @@ func TestAckBatchLookupFailuresKeepExistingReceipt(t *testing.T) {q.rows[id] = db.ChatMessage{ID: id, ChatSessionID: sid, ChannelIngested: true, Role: "user", CreatedAt: pgtype.Timestamptz{Time: time.Unix(int64(i), 0), Valid: true}}n.client.rememberReplySource(inst.ID, id, sid, groupReactionMessage(name))}- n.OnIngested(context.Background(), inst, groupReactionMessage("existing"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("existing"), sid, sid)reads := 0q.read = func(pgtype.UUID) {reads++@@ -39,13 +39,13 @@ func TestAckBatchLookupFailuresKeepExistingReceipt(t *testing.T) {q.err = errors.New("database unavailable")}}- n.OnIngested(context.Background(), inst, groupReactionMessage("new"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("new"), sid, sid)if reads != failureRead || !slices.Equal(*actions, []string{"add:existing:" + emotionAcknowledged}) {t.Fatalf("failed lookup moved receipt: reads=%d actions=%v", reads, *actions)}// A failed optional lookup must not poison the next accepted hook.q.read, q.err = nil, nil- n.OnIngested(context.Background(), inst, groupReactionMessage("new"), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage("new"), sid, sid)want := []string{"add:existing:" + emotionAcknowledged, "recall:existing:" + emotionAcknowledged, "add:new:" + emotionAcknowledged}if !slices.Equal(*actions, want) {t.Fatalf("recovered lookup: actions=%v want=%v", *actions, want)@@ -82,7 +82,7 @@ func TestOutboundTerminalOwnerFailureKeepsReceipts(t *testing.T) {inst := engine.ResolvedInstallation{ID: sessionUUID(90)}for i, name := range []string{"existing", "new"} {n.client.rememberReplySource(inst.ID, sessionUUID(byte(92+i)), sid, groupReactionMessage(name))- n.OnIngested(context.Background(), inst, groupReactionMessage(name), sid)+ n.OnIngested(context.Background(), inst, groupReactionMessage(name), sid, sid)}before := append([]string(nil), (*actions)...)q := &terminalOwnerQueries{task: tc.task, taskErr: tc.err}diff --git a/server/internal/integrations/dingtalk/ack_test.go b/server/internal/integrations/dingtalk/ack_test.goindex 2cfb0b9b07..7ae4e11955 100644--- a/server/internal/integrations/dingtalk/ack_test.go+++ b/server/internal/integrations/dingtalk/ack_test.go@@ -52,10 +52,10 @@ func TestAckNotifierClearsSessionWithoutMarkingOtherInputsDone(t *testing.T) {ctx := context.Background()sid := sessionUUID(1)inst := engine.ResolvedInstallation{ID: sessionUUID(9)}- n.OnIngested(ctx, inst, groupReactionMessage("a"), sid)- n.OnIngested(ctx, inst, groupReactionMessage("b"), sid)- n.OnIngested(ctx, inst, groupReactionMessage("other"), sessionUUID(2))- n.OnSettled(ctx, sid)+ n.OnIngested(ctx, inst, groupReactionMessage("a"), sid, sid)+ n.OnIngested(ctx, inst, groupReactionMessage("b"), sid, sid)+ n.OnIngested(ctx, inst, groupReactionMessage("other"), sessionUUID(2), sessionUUID(2))+ n.OnSettled(ctx, sid, engine.TypingSettlement{})n.client.rememberReplySource(inst.ID, sessionUUID(10), sid, groupReactionMessage("a"))n.OnReplyDelivered(ctx, inst, sessionUUID(10))want := []string{"add:a:收到", "add:b:收到", "add:other:收到", "recall:a:收到", "recall:b:收到", "add:a:Done"}@@ -67,8 +67,8 @@ func TestAckNotifierDuplicateIngestDoesNotDuplicateReaction(t *testing.T) {n, actions := newTestAck(time.Now)ctx := context.Background()sid := sessionUUID(1)- n.OnIngested(ctx, engine.ResolvedInstallation{}, groupReactionMessage("a"), sid)- n.OnIngested(ctx, engine.ResolvedInstallation{}, groupReactionMessage("a"), sid)+ n.OnIngested(ctx, engine.ResolvedInstallation{}, groupReactionMessage("a"), sid, sid)+ n.OnIngested(ctx, engine.ResolvedInstallation{}, groupReactionMessage("a"), sid, sid)if len(*actions) != 1 {t.Fatalf("duplicate reactions: %v", *actions)}@@ -85,10 +85,10 @@ func TestAckNotifierFailedAddStillAttemptsBoundedRecall(t *testing.T) {}ctx, cancel := context.WithCancel(context.Background())sid := sessionUUID(1)- n.OnIngested(ctx, engine.ResolvedInstallation{}, groupReactionMessage("a"), sid)+ n.OnIngested(ctx, engine.ResolvedInstallation{}, groupReactionMessage("a"), sid, sid)cancel()- n.OnSettled(ctx, sid)- n.OnSettled(context.Background(), sid)+ n.OnSettled(ctx, sid, engine.TypingSettlement{})+ n.OnSettled(context.Background(), sid, engine.TypingSettlement{})if calls != 2 || len(n.active) != 0 {t.Fatalf("calls=%d active=%d", calls, len(n.active))}@@ -117,14 +117,14 @@ func TestAckNotifierRecallsAddThatFinishesAfterClear(t *testing.T) {sid := sessionUUID(1)go func() {defer close(done)- n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage("a"), sid)+ n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage("a"), sid, sid)}()select {case <-started:case <-time.After(time.Second):t.Fatal("add did not start")}- n.OnSettled(context.Background(), sid)+ n.OnSettled(context.Background(), sid, engine.TypingSettlement{})close(release)select {case <-done:@@ -139,9 +139,9 @@ func TestAckNotifierRecallsAddThatFinishesAfterClear(t *testing.T) {}func TestAckNotifierInvalidCoordinatesDoNothing(t *testing.T) {n, actions := newTestAck(time.Now)- n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage("a"), pgtype.UUID{})- n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage(""), sessionUUID(1))- n.OnIngested(context.Background(), engine.ResolvedInstallation{}, channel.InboundMessage{MessageID: "a"}, sessionUUID(1))+ n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage("a"), pgtype.UUID{}, pgtype.UUID{})+ n.OnIngested(context.Background(), engine.ResolvedInstallation{}, groupReactionMessage(""), sessionUUID(1), sessionUUID(1))+ n.OnIngested(context.Background(), engine.ResolvedInstallation{}, channel.InboundMessage{MessageID: "a"}, sessionUUID(1), sessionUUID(1))n.OnReplyDelivered(context.Background(), engine.ResolvedInstallation{}, pgtype.UUID{})if len(*actions) != 0 {t.Fatalf("invalid coordinates sent: %v", *actions)diff --git a/server/internal/integrations/dingtalk/outbound_db_test.go b/server/internal/integrations/dingtalk/outbound_db_test.goindex d76ef4ba11..1a35c84733 100644--- a/server/internal/integrations/dingtalk/outbound_db_test.go+++ b/server/internal/integrations/dingtalk/outbound_db_test.go@@ -115,7 +115,7 @@ func testOutboundSealedInput(t *testing.T, scenario string, restart bool) {if err != nil {t.Fatal(err)}- ack.OnIngested(ctx, inst, first, sid)+ ack.OnIngested(ctx, inst, first, sid, sid)const firstBody = "> **Quoted author:**\n>\n> [quoted content unavailable]\n\nfirst question"var persisted stringif err := pool.QueryRow(ctx, "SELECT content FROM chat_message WHERE id = $1", appended.MessageID).Scan(&persisted); err != nil || persisted != firstBody {@@ -147,7 +147,7 @@ func testOutboundSealedInput(t *testing.T, scenario string, restart bool) {if _, err := set.Session.AppendMessage(ctx, engine.AppendParams{SessionID: sid, Sender: userID, InstallationID: inst.ID, Message: second}); err != nil {t.Fatal(err)}- ack.OnIngested(ctx, inst, second, sid)+ ack.OnIngested(ctx, inst, second, sid, sid)wantReceipts := 2if scenario == "merged" {wantReceipts = 1diff --git a/server/internal/integrations/dingtalk/outbound_test.go b/server/internal/integrations/dingtalk/outbound_test.goindex 7691abf590..7f8df26a39 100644--- a/server/internal/integrations/dingtalk/outbound_test.go+++ b/server/internal/integrations/dingtalk/outbound_test.go@@ -217,7 +217,7 @@ func TestOutboundTerminalReactionLifecycle(t *testing.T) {actions = append(actions, verb+msg.MessageID+":"+name)return nil}- ack.OnIngested(context.Background(), engine.ResolvedInstallation{ID: q.installation.ID}, groupReactionMessage("source"), sid)+ ack.OnIngested(context.Background(), engine.ResolvedInstallation{ID: q.installation.ID}, groupReactionMessage("source"), sid, sid)o := NewOutbound(q, nil, client, ack, nil)err = o.processEvent(ctx, events.Event{Type: tc.eventType, TaskID: util.UUIDToString(taskID), ChatSessionID: util.UUIDToString(sid), Payload: tc.payload})if (err != nil) != tc.sendFails {@@ -252,9 +252,9 @@ func TestOutboundTerminalWithoutDeliverySettlesOnlyOwnedInput(t *testing.T) {for i, name := range []string{"a", "b", "other"} {ack.client.rememberReplySource(inst.ID, sessionUUID(byte(70+i)), sid, groupReactionMessage(name))}- ack.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid)- ack.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid)- ack.OnIngested(context.Background(), inst, groupReactionMessage("other"), sessionUUID(62))+ ack.OnIngested(context.Background(), inst, groupReactionMessage("a"), sid, sid)+ ack.OnIngested(context.Background(), inst, groupReactionMessage("b"), sid, sid)+ ack.OnIngested(context.Background(), inst, groupReactionMessage("other"), sessionUUID(62), sessionUUID(62))q := missingDeliveryInputQueries{deliveryOnlyOutboundQueries{task: db.AgentTaskQueue{ChatInputTaskID: sessionUUID(63)},input: []db.ChatMessage{{ID: sessionUUID(70), ChannelIngested: true}},@@ -297,7 +297,7 @@ func TestOutboundPartialReplyFailureDoesNotMarkDone(t *testing.T) {}ack, actions := newTestAckWithMessageIDs(time.Now)ack.client.rememberReplySource(q.installation.ID, q.input[0].ID, sid, groupReactionMessage("source"))- ack.OnIngested(context.Background(), engine.ResolvedInstallation{ID: q.installation.ID}, groupReactionMessage("source"), sid)+ ack.OnIngested(context.Background(), engine.ResolvedInstallation{ID: q.installation.ID}, groupReactionMessage("source"), sid, sid)err = NewOutbound(q, nil, client, ack, nil).processEvent(context.Background(), events.Event{Type: protocol.EventChatDone, TaskID: util.UUIDToString(tid), ChatSessionID: util.UUIDToString(sid), Payload: protocol.ChatDonePayload{Content: strings.Repeat("answer\n", 6000)},})diff --git a/server/internal/integrations/dingtalk/reaction_interest_test.go b/server/internal/integrations/dingtalk/reaction_interest_test.goindex ff43561edf..d6deca1733 100644--- a/server/internal/integrations/dingtalk/reaction_interest_test.go+++ b/server/internal/integrations/dingtalk/reaction_interest_test.go@@ -131,7 +131,7 @@ func TestTerminalBeforeSourceCaptureFencesLateReaction(t *testing.T) {t.Fatal("late callback recreated terminal reaction")return nil}- n.OnIngested(context.Background(), inst, msg, sid)+ n.OnIngested(context.Background(), inst, msg, sid, sid)if q.taskReads != 1 || q.inputReads != 1 || len(n.active) != 0 {t.Fatalf("terminal fence not exercised: task=%d input=%d active=%v", q.taskReads, q.inputReads, n.active)}@@ -246,7 +246,7 @@ func TestActiveReceiptRemainsDiscoverableAfterSourceEviction(t *testing.T) {return nil}n.client.rememberReplySource(inst.ID, id, sid, msg)- n.OnIngested(context.Background(), inst, msg, sid)+ n.OnIngested(context.Background(), inst, msg, sid, sid)for i := 0; i < maxReplySources; i++ {n.client.rememberReplySource(inst.ID, dbid.NewV7(), sessionUUID(54), groupReactionMessage("other"))}@@ -290,7 +290,7 @@ func TestIngestKeepsTerminalInterestAcrossSourceEviction(t *testing.T) {t.Fatal("eviction allowed terminal reaction to reappear")return nil}- n.OnIngested(context.Background(), inst, msg, sid)+ n.OnIngested(context.Background(), inst, msg, sid, sid)if q.inputReads != 1 || len(n.active) != 0 || n.client.hasReplySession(sid) {t.Fatal("in-flight interest was lost or leaked")}diff --git a/server/internal/integrations/dingtalk/reply_boundaries_test.go b/server/internal/integrations/dingtalk/reply_boundaries_test.goindex 695ccdbb02..85ae829141 100644--- a/server/internal/integrations/dingtalk/reply_boundaries_test.go+++ b/server/internal/integrations/dingtalk/reply_boundaries_test.go@@ -26,8 +26,8 @@ func TestAckNotifierCredentialFailuresAreOptional(t *testing.T) {t.Run(tc.name, func(t *testing.T) {d := newDingtalkSendServer(t)n := NewAckNotifier(NewClient(nil, d.srv.URL), tc.decrypt, nil, nil)- n.OnIngested(context.Background(), engine.ResolvedInstallation{Platform: tc.platform}, groupReactionMessage("source"), sessionUUID(91))- n.OnSettled(context.Background(), sessionUUID(91))+ n.OnIngested(context.Background(), engine.ResolvedInstallation{Platform: tc.platform}, groupReactionMessage("source"), sessionUUID(91), sessionUUID(91))+ n.OnSettled(context.Background(), sessionUUID(91), engine.TypingSettlement{})if len(d.sendBodies) != 0 || len(n.active) != 0 {t.Fatal("unusable credentials sent a reaction or prevented local cleanup")}diff --git a/server/internal/integrations/lark/client.go b/server/internal/integrations/lark/client.goindex 8d53f984df..df42a9c3a1 100644--- a/server/internal/integrations/lark/client.go+++ b/server/internal/integrations/lark/client.go@@ -145,6 +145,20 @@ type TokenCacheInvalidator interface {InvalidateTokenCache(appID string)}+// ReactionLister is implemented by an APIClient that can list the reactions+// already sitting on a message (GET /im/v1/messages/{message_id}/reactions).+// The typing-indicator sweep uses it to find and delete the bot's own Typing+// reactions without consulting any in-process state, which is what keeps the+// badge removable after a restart or on another replica.+//+// It is deliberately separate from APIClient rather than a method on it,+// mirroring TokenCacheInvalidator: only clients that can read Lark implement+// it, and fakes that only exercise the add/delete pair are not forced to grow+// list plumbing. Callers type-assert and skip the sweep when it is absent.+type ReactionLister interface {+ ListMessageReactions(ctx context.Context, p ListMessageReactionsParams) ([]MessageReaction, error)+}+// ListMessagesParams selects a bounded, recent window of messages in a// single Lark chat for the group-context prefetch. Only the fields the// enricher needs today are exposed (ChatID, ThreadID, PageSize, EndTime);@@ -344,6 +358,26 @@ type DeleteReactionParams struct {ReactionID string}+// ListMessageReactionsParams is the input shape for listing the reactions+// already on a message. EmojiType filters server-side (Lark's+// reaction_type query parameter); empty lists every reaction.+type ListMessageReactionsParams struct {+ InstallationID InstallationCredentials+ MessageID string+ EmojiType string+}++// MessageReaction is one reaction on a message as Lark lists it. OperatorType+// is "app" when the installed bot added it and "user" when a human did — the+// distinction that lets the typing-indicator sweep delete only the badges the+// bot itself put on.+type MessageReaction struct {+ ReactionID string+ OperatorType string+ OperatorID string+ EmojiType string+}+// InstallationCredentials is the per-installation transport context the// client needs to authenticate against Lark on behalf of a workspace's// bot. Passing these explicitly to each call (rather than constructingdiff --git a/server/internal/integrations/lark/feishu_resolvers.go b/server/internal/integrations/lark/feishu_resolvers.goindex 6bd001ba5f..03a3043b5c 100644--- a/server/internal/integrations/lark/feishu_resolvers.go+++ b/server/internal/integrations/lark/feishu_resolvers.go@@ -320,19 +320,19 @@ func dispatchResultFromEngine(res engine.Result) DispatchResult {type feishuTypingNotifier struct{ mgr *TypingIndicatorManager }-func (r *feishuTypingNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID) {+func (r *feishuTypingNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID, chatMessageID pgtype.UUID) {larkInst, ok := inst.Platform.(Installation)if !ok {return}lm, _ := larkMsgFromRaw(msg)- r.mgr.Add(ctx, larkInst, sessionID, msg.MessageID, lm.CreateTime)+ r.mgr.Add(ctx, larkInst, sessionID, msg.MessageID, lm.CreateTime, chatMessageID)}// OnSettled clears the reaction when the run trigger enqueued no task (agent// offline / archived, or an enqueue failure) — the Patcher's bus-driven clear on// chat-done / task-failed never fires for those, so without this the Typing// reaction sticks.-func (r *feishuTypingNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID) {- r.mgr.Clear(ctx, sessionID)+func (r *feishuTypingNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID, scope engine.TypingSettlement) {+ r.mgr.Settle(ctx, sessionID, scope)}diff --git a/server/internal/integrations/lark/http_client.go b/server/internal/integrations/lark/http_client.goindex 12df677269..ece913366c 100644--- a/server/internal/integrations/lark/http_client.go+++ b/server/internal/integrations/lark/http_client.go@@ -1002,6 +1002,81 @@ func (c *httpAPIClient) DeleteMessageReaction(ctx context.Context, p DeleteReactreturn nil}+// larkListReactionsMaxPageSize is Lark's page-size cap for the message+// reaction list endpoint.+const larkListReactionsMaxPageSize = 50++// larkListReactionsMaxPages bounds the pagination loop. A Typing badge is a+// handful of reactions at most; the bound only exists so a misbehaving+// has_more cannot turn the sweep into an unbounded poll loop on the+// synchronous bus-delivery path.+const larkListReactionsMaxPages = 10++// ListMessageReactions lists the reactions on a message via+// GET /open-apis/im/v1/messages/{message_id}/reactions, optionally filtered+// server-side by emoji type (Lark's reaction_type query parameter). All pages+// are followed (bounded by larkListReactionsMaxPages) so the caller sees every+// reaction, not just the first window.+func (c *httpAPIClient) ListMessageReactions(ctx context.Context, p ListMessageReactionsParams) ([]MessageReaction, error) {+ if p.MessageID == "" {+ return nil, errors.New("lark http client: missing message_id")+ }+ base := "/open-apis/im/v1/messages/" + url.PathEscape(p.MessageID) + "/reactions"++ var out []MessageReaction+ pageToken := ""+ for page := 0; page < larkListReactionsMaxPages; page++ {+ q := url.Values{}+ q.Set("page_size", strconv.Itoa(larkListReactionsMaxPageSize))+ if p.EmojiType != "" {+ q.Set("reaction_type", p.EmojiType)+ }+ if pageToken != "" {+ q.Set("page_token", pageToken)+ }+ var resp struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ Items []struct {+ ReactionID string `json:"reaction_id"`+ Operator struct {+ OperatorType string `json:"operator_type"`+ OperatorID string `json:"operator_id"`+ } `json:"operator"`+ ReactionType struct {+ EmojiType string `json:"emoji_type"`+ } `json:"reaction_type"`+ } `json:"items"`+ HasMore bool `json:"has_more"`+ PageToken string `json:"page_token"`+ } `json:"data"`+ }+ if err := c.doAuthedJSON(ctx, p.InstallationID, http.MethodGet, base+"?"+q.Encode(), nil, &resp); err != nil {+ return nil, fmt.Errorf("lark http client: list message reactions: %w", err)+ }+ if resp.Code != 0 {+ if isTokenError(resp.Code) {+ c.invalidateToken(p.InstallationID.AppID)+ }+ return nil, fmt.Errorf("lark http client: list message reactions: code=%d msg=%q", resp.Code, resp.Msg)+ }+ for _, it := range resp.Data.Items {+ out = append(out, MessageReaction{+ ReactionID: it.ReactionID,+ OperatorType: it.Operator.OperatorType,+ OperatorID: it.Operator.OperatorID,+ EmojiType: it.ReactionType.EmojiType,+ })+ }+ if !resp.Data.HasMore || resp.Data.PageToken == "" {+ return out, nil+ }+ pageToken = resp.Data.PageToken+ }+ return out, nil+}+// BatchGetUsers resolves user open_ids to display names via// GET /open-apis/contact/v3/users/batch?user_ids=…&user_id_type=open_id.// It mirrors fetchBotUnionID's single-user contact lookup, batched. Onlydiff --git a/server/internal/integrations/lark/http_client_test.go b/server/internal/integrations/lark/http_client_test.goindex e94335f8d0..9201efb58f 100644--- a/server/internal/integrations/lark/http_client_test.go+++ b/server/internal/integrations/lark/http_client_test.go@@ -1528,6 +1528,106 @@ func TestBindingPromptTemplate_Shape(t *testing.T) {}}+// ListMessageReactions backs the typing-indicator sweep: it must filter+// server-side by emoji type, follow every page Lark offers (a badge beyond the+// first window must still be found), and carry each item's operator and emoji+// fields through so the caller can tell the bot's own reactions from a human's.+func TestHTTPClient_ListMessageReactions_FollowsPages(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok", 7200)++ requests := 0+ fake.mux.HandleFunc("/open-apis/im/v1/messages/", func(w http.ResponseWriter, r *http.Request) {+ requests+++ if r.Method != http.MethodGet {+ t.Errorf("list reactions: want GET, got %s", r.Method)+ }+ if !strings.HasSuffix(r.URL.Path, "/om_trigger/reactions") {+ t.Errorf("list reactions: unexpected path %q", r.URL.Path)+ }+ q := r.URL.Query()+ if got := q.Get("reaction_type"); got != "Typing" {+ t.Errorf("list reactions: reaction_type = %q, want Typing", got)+ }+ if got := q.Get("page_size"); got != "50" {+ t.Errorf("list reactions: page_size = %q, want 50", got)+ }+ switch q.Get("page_token") {+ case "":+ writeJSON(w, map[string]any{+ "code": 0,+ "msg": "ok",+ "data": map[string]any{+ "items": []map[string]any{{+ "reaction_id": "r-page1",+ "operator": map[string]any{"operator_type": "app", "operator_id": "cli_app_xx"},+ "reaction_type": map[string]any{"emoji_type": "Typing"},+ }},+ "has_more": true,+ "page_token": "cursor-2",+ },+ })+ case "cursor-2":+ writeJSON(w, map[string]any{+ "code": 0,+ "msg": "ok",+ "data": map[string]any{+ "items": []map[string]any{{+ "reaction_id": "r-page2",+ "operator": map[string]any{"operator_type": "user", "operator_id": "ou_human"},+ "reaction_type": map[string]any{"emoji_type": "Typing"},+ }},+ "has_more": false,+ },+ })+ default:+ t.Errorf("list reactions: unexpected page_token %q", q.Get("page_token"))+ }+ })++ c := newTestClient(fake, time.Now)+ got, err := c.ListMessageReactions(context.Background(), ListMessageReactionsParams{+ InstallationID: testCreds(),+ MessageID: "om_trigger",+ EmojiType: "Typing",+ })+ if err != nil {+ t.Fatalf("list message reactions: %v", err)+ }+ if requests != 2 {+ t.Errorf("expected both pages to be fetched, got %d requests", requests)+ }+ if len(got) != 2 || got[0].ReactionID != "r-page1" || got[1].ReactionID != "r-page2" {+ t.Fatalf("unexpected reactions: %+v", got)+ }+ if got[0].OperatorType != "app" || got[0].OperatorID != "cli_app_xx" || got[0].EmojiType != "Typing" {+ t.Errorf("page-1 item fields not carried through: %+v", got[0])+ }+ if got[1].OperatorType != "user" {+ t.Errorf("page-2 operator_type not carried through: %+v", got[1])+ }+}++func TestHTTPClient_ListMessageReactions_BusinessError(t *testing.T) {+ fake := newLarkFake(t)+ fake.stubToken("tok", 7200)+ fake.mux.HandleFunc("/open-apis/im/v1/messages/", func(w http.ResponseWriter, r *http.Request) {+ writeJSON(w, map[string]any{"code": 230013, "msg": "invalid message id"})+ })++ c := newTestClient(fake, time.Now)+ _, err := c.ListMessageReactions(context.Background(), ListMessageReactionsParams{+ InstallationID: testCreds(),+ MessageID: "om_bad",+ })+ if err == nil {+ t.Fatal("expected error on non-zero Lark code")+ }+ if !strings.Contains(err.Error(), "230013") {+ t.Errorf("error should surface the Lark code; got %v", err)+ }+}+// fakeClock is a minimal monotonic clock for tests that need to drive// the cache TTL deterministically.type fakeClock struct{ now time.Time }diff --git a/server/internal/integrations/lark/outbound.go b/server/internal/integrations/lark/outbound.goindex 5194435949..ea42cc8aed 100644--- a/server/internal/integrations/lark/outbound.go+++ b/server/internal/integrations/lark/outbound.go@@ -12,6 +12,7 @@ import ("github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/events""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")@@ -266,12 +267,8 @@ func (p *Patcher) SetTypingIndicatorManager(m *TypingIndicatorManager) {// event with no workspace is dropped before it reaches the bus. It now// takes the workspace from its caller. Archiving an agent also publishes// task:cancelled for chat tasks after commit, clearing their reactions-// through this subscription. An ending during Add can still clear-// nothing, because Add records its state only after the Lark call-// returns, so the badge lands after the clear with nothing left to-// take it off. This race predates task:cancelled — chat-done-// and task-failed race the add the same way — and closing it needs a-// per-session generation the add can check when its call returns.+// through this subscription. Clear marks in-flight adds as ended so a+// late Add removes its own reaction when the HTTP call returns.//// We deliberately do NOT subscribe to EventTaskQueued / EventTaskRunning// (no thinking-card lifecycle anymore — adds noise without value) or to@@ -311,37 +308,24 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {// Issue / autopilot tasks have no chat_session.return nil}- // A cancelled run has no reply to place, so the only thing owed to the user- // is taking the Typing badge off. That runs before every lookup below,- // because each of them can answer "no" for a run that still has a badge on- // screen:- //- // - the binding is gone by the time a session delete's cancels are- // broadcast (they fire after the transaction that dropped it commits);- //- // - the origin classification answers "does this answer belong on Lark",- // and a task cancelled for owning an empty input batch — the failure- // #6611 fixed the cause of — reports no channel-ingested messages, so a- // clear behind it would be skipped on exactly the run that most needs- // it. A cancellation has no answer to misroute, so the question does not- // arise.- //- // Nothing is posted here, so neither gate is protecting anything: the badge- // is Lark's own, and Clear only touches sessions this process put one on.- // The clear is keyed by session rather than by turn, so cancelling one of- // two turns in a session takes the badge off both; the worst that costs is a- // missing badge on a turn still running.+ // Cleanup runs after reply delivery (including failed sends and early+ // returns), with its own budget. A slow reaction API cannot consume the+ // reply's context deadline. The bus still waits for bounded cleanup.+ if p.typingIndicator != nil {+ defer func() {+ cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), typingCleanupTimeout)+ defer cancel()+ covered := p.typingIndicator.Reconcile(cleanupCtx, chatSessionID)+ p.sweepTypingForTask(cleanupCtx, taskID, e.ChannelReactionTarget, covered)+ }()+ }if e.Type == protocol.EventTaskCancelled {- if p.typingIndicator != nil {- p.typingIndicator.Clear(ctx, chatSessionID)- }return nil}delivery, err := p.queries.GetChannelTaskDelivery(ctx, taskID)if err != nil {if errors.Is(err, pgx.ErrNoRows) {- // Direct Multica task or violated snapshot invariant — fail closed.return nil}return fmt.Errorf("lookup lark task delivery: %w", err)@@ -393,13 +377,6 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {agentName = agent.Name}- // Clear the "processing" reaction before the reply is visible so the- // user sees a clean transition. Best-effort: a failure here is logged- // but does not block the actual reply.- if p.typingIndicator != nil {- p.typingIndicator.Clear(ctx, chatSessionID)- }-switch e.Type {case protocol.EventChatDone:return p.sendChatReply(ctx, creds, binding, mentionOpenID(binding), e.Payload)@@ -409,6 +386,55 @@ func (p *Patcher) processEvent(ctx context.Context, e events.Event) error {return nil}+// sweepTypingForTask uses the frozen trigger message. Session deletion carries+// that anchor on the internal event before deleting the delivery row.+func (p *Patcher) sweepTypingForTask(ctx context.Context, taskID pgtype.UUID, target *events.ChannelReactionTarget, covered map[string]bool) {+ delivery, err := p.queries.GetChannelTaskDelivery(ctx, taskID)+ if errors.Is(err, pgx.ErrNoRows) && target != nil {+ installationID, parseErr := util.ParseUUID(target.InstallationID)+ if parseErr != nil {+ return+ }+ delivery = db.ChannelTaskDelivery{+ ChannelType: target.ChannelType, InstallationID: installationID,+ ChannelMessageID: pgtype.Text{String: target.MessageID, Valid: target.MessageID != ""},+ }+ err = nil+ }+ if err != nil {+ if !errors.Is(err, pgx.ErrNoRows) {+ p.cfg.Logger.Warn("lark patcher: typing sweep delivery lookup failed",+ "task_id", uuidString(taskID),+ "error", err,+ )+ }+ return+ }+ if delivery.ChannelType != channelTypeFeishu || !delivery.ChannelMessageID.Valid || delivery.ChannelMessageID.String == "" {+ return+ }+ if covered[uuidString(delivery.InstallationID)+"/"+delivery.ChannelMessageID.String] {+ return+ }+ inst, err := p.queries.GetLarkInstallation(ctx, delivery.InstallationID)+ if err != nil {+ p.cfg.Logger.Warn("lark patcher: typing sweep installation lookup failed",+ "task_id", uuidString(taskID),+ "error", err,+ )+ return+ }+ creds, err := p.installationCredentials(inst)+ if err != nil {+ p.cfg.Logger.Warn("lark patcher: typing sweep credentials resolution failed",+ "task_id", uuidString(taskID),+ "error", err,+ )+ return+ }+ p.typingIndicator.SweepMessage(ctx, creds, delivery.ChannelMessageID.String)+}+// mentionOpenID returns the Feishu open_id to @-mention on this reply, or ""// for "send without a mention".//diff --git a/server/internal/integrations/lark/outbound_test.go b/server/internal/integrations/lark/outbound_test.goindex de445fdebd..bce66a6da4 100644--- a/server/internal/integrations/lark/outbound_test.go+++ b/server/internal/integrations/lark/outbound_test.go@@ -866,7 +866,7 @@ func TestPatcherClearsTypingOnTaskCancelled(t *testing.T) {bus := events.New()p.Register(bus)- typing.Add(context.Background(), q.installation, q.binding.ChatSessionID, "om_trigger", "")+ typing.Add(context.Background(), q.installation, q.binding.ChatSessionID, "om_trigger", "", q.binding.ChatSessionID)if len(typingAPI.addCalled) != 1 {t.Fatalf("setup: expected the Typing reaction to be added, got %d", len(typingAPI.addCalled))}@@ -928,7 +928,7 @@ func TestPatcherClearsTypingAfterSessionDeleteRemovedTheBinding(t *testing.T) {p.Register(bus)sessionID := q.binding.ChatSessionID- typing.Add(context.Background(), q.installation, sessionID, "om_trigger", "")+ typing.Add(context.Background(), q.installation, sessionID, "om_trigger", "", sessionID)if len(typingAPI.addCalled) != 1 {t.Fatalf("setup: expected the Typing reaction to be added, got %d", len(typingAPI.addCalled))}@@ -968,6 +968,137 @@ func TestPatcherClearsTypingAfterSessionDeleteRemovedTheBinding(t *testing.T) {}}+// ---- the stateless sweep: restart- and replica-proof clearing ----++// The in-memory state lives and dies with the process that ran Add. A restart+// between the question and the answer — or a second replica handling the+// completion event — empties the map while the badge is still on screen, and+// the reply that follows clears nothing. The sweep closes that hole: it finds+// the Typing reaction through Lark alone, on the trigger message the delivery+// row froze, so the reply landing is enough to take the badge off.+func TestPatcherSweepsTypingOnChatDoneAfterRestartEmptiedTheState(t *testing.T) {+ p, q, api := newTestPatcher(t)+ q.binding.LastMessageID = pgtype.Text{String: "om_trigger", Valid: true}+ taskID := uuidFromString(t, "ee777777-ee77-ee77-ee77-eeeeeeeeeeee")+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}+ q.taskChannelIngested = true++ // A fresh manager: no Add ever ran in this process, the map is empty.+ typingAPI := &fakeTypingAPIClient{+ listReturn: []MessageReaction{+ {ReactionID: "r-stale", OperatorType: "app", OperatorID: "cli_test_app", EmojiType: typingEmoji},+ },+ }+ typing := NewTypingIndicatorManager(typingAPI, fakeTypingCreds{secret: "shh"},+ &fakeTypingQueries{binding: q.binding, installation: q.installation}, newDiscardLogger())+ p.SetTypingIndicatorManager(typing)++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{Content: "the reply arrived"},+ })++ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.textSent) != 1 {+ t.Fatalf("the reply itself must still go out; textSent=%d", len(api.textSent))+ }+ if len(typingAPI.listCalled) != 1 || typingAPI.listCalled[0] != "om_trigger" {+ t.Fatalf("the trigger message's reactions were not listed; lists=%v", typingAPI.listCalled)+ }+ if len(typingAPI.deleteCalled) != 1 ||+ typingAPI.deleteCalled[0].messageID != "om_trigger" ||+ typingAPI.deleteCalled[0].reactionID != "r-stale" {+ t.Fatalf("the reply arrived but the Typing badge is still on om_trigger — "++ "the user sees a processing spinner under an answered question "++ "(deletes=%+v)", typingAPI.deleteCalled)+ }+}++// The same hole on the cancellation path: a user pressing cancel on another+// replica (or after a restart) must still take the badge off, through the+// delivery row's frozen trigger message.+func TestPatcherSweepsTypingOnTaskCancelledThroughTheDeliveryRow(t *testing.T) {+ p, q, api := newTestPatcher(t)+ q.binding.LastMessageID = pgtype.Text{String: "om_trigger", Valid: true}+ taskID := uuidFromString(t, "ee666666-ee66-ee66-ee66-eeeeeeeeeeee")+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}+ q.taskChannelIngested = false++ typingAPI := &fakeTypingAPIClient{+ listReturn: []MessageReaction{+ {ReactionID: "r-stale", OperatorType: "app", OperatorID: "cli_test_app", EmojiType: typingEmoji},+ },+ }+ typing := NewTypingIndicatorManager(typingAPI, fakeTypingCreds{secret: "shh"},+ &fakeTypingQueries{binding: q.binding, installation: q.installation}, newDiscardLogger())+ p.SetTypingIndicatorManager(typing)++ p.handleEvent(events.Event{+ Type: protocol.EventTaskCancelled,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: map[string]any{+ "task_id": uuidString(taskID),+ "chat_session_id": uuidString(q.binding.ChatSessionID),+ "status": "cancelled",+ },+ })++ if len(typingAPI.deleteCalled) != 1 || typingAPI.deleteCalled[0].reactionID != "r-stale" {+ t.Fatalf("the run was cancelled with no state on file and the badge stayed on "++ "om_trigger; deletes=%+v", typingAPI.deleteCalled)+ }+ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.sent) != 0 || len(api.textSent) != 0 || len(api.patched) != 0 {+ t.Errorf("a cancelled run must post nothing; sent=%d textSent=%d patched=%d",+ len(api.sent), len(api.textSent), len(api.patched))+ }+}++// A web-UI turn shares the session with Lark turns but delivers nothing to+// Lark, so its early return sits before the send path. The in-memory clear+// must run on the way out anyway: it is the only thing that can take a badge+// off in this process, and skipping it lets a stranded badge ride until some+// later Lark turn.+func TestPatcherClearsTypingStateWhenTaskIsNotChannelIngested(t *testing.T) {+ p, q, api := newTestPatcher(t)+ taskID := uuidFromString(t, "ee555555-ee55-ee55-ee55-eeeeeeeeeeee")+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}+ q.taskChannelIngested = false++ typingAPI := &fakeTypingAPIClient{addReturn: "reaction-web-turn"}+ typing := NewTypingIndicatorManager(typingAPI, fakeTypingCreds{secret: "shh"},+ &fakeTypingQueries{binding: q.binding, installation: q.installation}, newDiscardLogger())+ p.SetTypingIndicatorManager(typing)++ typing.Add(context.Background(), q.installation, q.binding.ChatSessionID, "om_earlier_turn", "", q.binding.ChatSessionID)+ if len(typingAPI.addCalled) != 1 {+ t.Fatalf("setup: expected the Typing reaction to be added, got %d", len(typingAPI.addCalled))+ }++ p.handleEvent(events.Event{+ Type: protocol.EventChatDone,+ TaskID: uuidString(taskID),+ ChatSessionID: uuidString(q.binding.ChatSessionID),+ Payload: protocol.ChatDonePayload{Content: "answered in Multica only"},+ })++ if len(typingAPI.deleteCalled) != 1 || typingAPI.deleteCalled[0].reactionID != "reaction-web-turn" {+ t.Fatalf("a web-UI turn on a Lark-bound session skipped the clear; deletes=%+v",+ typingAPI.deleteCalled)+ }+ api.mu.Lock()+ defer api.mu.Unlock()+ if len(api.sent) != 0 || len(api.textSent) != 0 || len(api.patched) != 0 {+ t.Errorf("a non-channel-ingested turn must not deliver to Lark; sent=%d textSent=%d patched=%d",+ len(api.sent), len(api.textSent), len(api.patched))+ }+}+// ---- native @-mention of the triggering member (#8234) ----// groupPatcherWithSender wires the shared setup for the mention tests: adiff --git a/server/internal/integrations/lark/typing_cleanup.go b/server/internal/integrations/lark/typing_cleanup.gonew file mode 100644index 0000000000..0501a99c0c--- /dev/null+++ b/server/internal/integrations/lark/typing_cleanup.go@@ -0,0 +1,213 @@+package lark++import (+ "context"+ "encoding/json"+ "errors"+ "fmt"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type typingLedgerQueries interface {+ RegisterChannelTypingReaction(context.Context, db.RegisterChannelTypingReactionParams) (db.ChannelTypingReaction, error)+ FinishChannelTypingReactionAdd(context.Context, db.FinishChannelTypingReactionAddParams) (db.ChannelTypingReaction, error)+ AcknowledgeChannelTypingReactionCleanup(context.Context, db.AcknowledgeChannelTypingReactionCleanupParams) error+ ClaimChannelTypingReactionCleanup(context.Context, pgtype.UUID) ([]db.ChannelTypingReaction, error)+ SettleChannelTypingInputs(context.Context, db.SettleChannelTypingInputsParams) error+ SkipChannelTypingReactionAdd(context.Context, pgtype.UUID) error+ PruneChannelTypingReactionCleanup(context.Context) error+ ExpireChannelTypingReactionCleanup(context.Context) ([]db.ExpireChannelTypingReactionCleanupRow, error)+ ListRequestedChannelTypingReactions(context.Context, []pgtype.UUID) ([]pgtype.UUID, error)+}++// Settle persists the failed flush's input boundary before removing reactions.+// It covers inputs whose detached Add has not even registered yet.+func (m *TypingIndicatorManager) Settle(ctx context.Context, sessionID pgtype.UUID, scope engine.TypingSettlement) {+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), typingCleanupTimeout)+ defer cancel()+ if err := m.queries.SettleChannelTypingInputs(ctx, db.SettleChannelTypingInputsParams{+ ThroughMessageID: scope.ThroughMessageID, ChatSessionID: sessionID,+ WorkspaceID: scope.WorkspaceID, InstallationID: scope.InstallationID, ContextRevision: pgtype.Int8{Int64: scope.ContextRevision, Valid: true},+ }); err != nil {+ m.log.Warn("lark typing: persist taskless settlement", "err", err)+ return+ }+ m.Reconcile(ctx, sessionID)+}++// Reconcile claims all terminal inputs, not just the task's delivery trigger.+// A null session selects due work across all workspaces for the system worker.+// The ledger survives source deletion; eligibility is based on committed rows,+// so rolled-back cancellation/deletion never grants cleanup ownership.+func (m *TypingIndicatorManager) Reconcile(ctx context.Context, sessionID pgtype.UUID) map[string]bool {+ defer m.pruneLocal(ctx)+ covered := make(map[string]bool)+ rows, err := m.queries.ClaimChannelTypingReactionCleanup(ctx, sessionID)+ if err != nil {+ m.log.Warn("lark typing: claim cleanup", "err", err)+ return covered+ }+ for _, row := range rows {+ if ctx.Err() != nil {+ break+ } // Claimed but unfinished work remains due after its lease.+ covered[uuidString(row.InstallationID)+"/"+row.ChannelMessageID] = true+ m.mu.Lock()+ key := uuidString(row.ChatSessionID)+ for _, state := range append([]*TypingIndicatorState(nil), m.states[key]...) {+ if state.LedgerID == row.ID {+ state.ended = true+ m.removeState(key, state)+ }+ }+ m.mu.Unlock()+ callCtx, cancel := context.WithTimeout(ctx, typingCleanupTimeout)+ m.cleanupReaction(callCtx, row)+ cancel()+ }+ return covered+}++func (m *TypingIndicatorManager) cleanupReaction(ctx context.Context, row db.ChannelTypingReaction) {+ var snapshot Installation+ if err := json.Unmarshal(row.InstallationSnapshot, &snapshot); err != nil {+ m.log.Warn("lark typing: read cleanup snapshot", "err", err)+ return+ }+ creds := m.credentialsForInstallation(ctx, uuidString(row.ChatSessionID), row.InstallationID, snapshot)+ if creds == nil {+ return+ }+ var err error+ if row.ReactionID != "" {+ err = m.client.DeleteMessageReaction(ctx, DeleteReactionParams{InstallationID: *creds, MessageID: row.ChannelMessageID, ReactionID: row.ReactionID})+ // A different replica may already have deleted this exact reaction. Prove+ // absence rather than retrying forever on the API's already-missing error.+ if err != nil {+ if lister, ok := m.client.(ReactionLister); ok {+ reactions, listErr := lister.ListMessageReactions(ctx, ListMessageReactionsParams{InstallationID: *creds, MessageID: row.ChannelMessageID, EmojiType: typingEmoji})+ if listErr == nil {+ found := false+ for _, r := range reactions {+ if r.ReactionID == row.ReactionID {+ found = true+ }+ }+ if !found {+ err = nil+ }+ }+ }+ }+ } else {+ err = m.sweepForCleanup(ctx, *creds, row.ChannelMessageID)+ }+ if err != nil {+ m.log.Warn("lark typing: cleanup retained for retry", "cleanup_id", uuidString(row.ID), "attempt", row.Attempts, "err", err)+ return+ }+ if err = m.queries.AcknowledgeChannelTypingReactionCleanup(ctx, db.AcknowledgeChannelTypingReactionCleanupParams{ID: row.ID, ReactionID: row.ReactionID}); err != nil {+ m.log.Warn("lark typing: cleanup acknowledgement failed; retry retained", "cleanup_id", uuidString(row.ID), "err", err)+ }+}++func (m *TypingIndicatorManager) sweepForCleanup(ctx context.Context, creds InstallationCredentials, messageID string) error {+ if creds.AppID == "" {+ return fmt.Errorf("reaction owner App ID unavailable")+ }+ lister, ok := m.client.(ReactionLister)+ if !ok {+ return fmt.Errorf("reaction listing unavailable")+ }+ reactions, err := lister.ListMessageReactions(ctx, ListMessageReactionsParams{InstallationID: creds, MessageID: messageID, EmojiType: typingEmoji})+ if err != nil {+ return err+ }+ for _, r := range reactions {+ if r.OperatorType != "app" || r.OperatorID != creds.AppID || r.EmojiType != typingEmoji {+ continue+ }+ err = errors.Join(err, m.client.DeleteMessageReaction(ctx, DeleteReactionParams{InstallationID: creds, MessageID: messageID, ReactionID: r.ReactionID}))+ }+ return err+}++// Run retries durable cleanup after transient errors, lost bus events and+// process restarts. Claims use a 30s-1h capped backoff and SKIP LOCKED; each+// pass is bounded. Expiration and GC have a separate budget, so slow remote+// calls cannot indefinitely retain credential snapshots or terminal records.+func (m *TypingIndicatorManager) Run(ctx context.Context) {+ ticker := time.NewTicker(30 * time.Second)+ defer ticker.Stop()+ for {+ m.maintainCleanup(ctx)+ passCtx, cancel := context.WithTimeout(ctx, 10*time.Second)+ m.Reconcile(passCtx, pgtype.UUID{})+ cancel()+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ }+ }+}++func (m *TypingIndicatorManager) maintainCleanup(ctx context.Context) {+ expireCtx, cancel := context.WithTimeout(ctx, typingCleanupTimeout)+ rows, err := m.queries.ExpireChannelTypingReactionCleanup(expireCtx)+ cancel()+ if err != nil && ctx.Err() == nil {+ m.log.Error("lark typing: credential expiry maintenance failed", "err", err)+ }+ counts := make(map[pgtype.UUID]int)+ for _, row := range rows {+ counts[row.WorkspaceID]+++ }+ for workspaceID, count := range counts {+ m.log.Warn("lark typing: cleanup abandoned at retention deadline; credentials erased", "workspace_id", uuidString(workspaceID), "count", count)+ }+ pruneCtx, pruneCancel := context.WithTimeout(ctx, typingCleanupTimeout)+ defer pruneCancel()+ if err := m.queries.PruneChannelTypingReactionCleanup(pruneCtx); err != nil && ctx.Err() == nil {+ m.log.Warn("lark typing: prune terminal cleanup", "err", err)+ }+}++// A different replica can acknowledge cleanup without touching our local map.+// Evict those stale views even when no remote retry is left to claim.+func (m *TypingIndicatorManager) pruneLocal(ctx context.Context) {+ m.mu.RLock()+ var ids []pgtype.UUID+ for _, states := range m.states {+ for _, state := range states {+ ids = append(ids, state.LedgerID)+ }+ }+ m.mu.RUnlock()+ if len(ids) == 0 {+ return+ }+ ended, err := m.queries.ListRequestedChannelTypingReactions(ctx, ids)+ if err != nil {+ m.log.Warn("lark typing: refresh local cleanup state", "err", err)+ return+ }+ closed := make(map[pgtype.UUID]bool, len(ended))+ for _, id := range ended {+ closed[id] = true+ }+ m.mu.Lock()+ defer m.mu.Unlock()+ for key, states := range m.states {+ for _, state := range append([]*TypingIndicatorState(nil), states...) {+ if closed[state.LedgerID] {+ state.ended = true+ m.removeState(key, state)+ }+ }+ }+}diff --git a/server/internal/integrations/lark/typing_cleanup_db_test.go b/server/internal/integrations/lark/typing_cleanup_db_test.gonew file mode 100644index 0000000000..b70ac245a3--- /dev/null+++ b/server/internal/integrations/lark/typing_cleanup_db_test.go@@ -0,0 +1,184 @@+package lark++import (+ "context"+ "errors"+ "sync"+ "testing"++ "github.com/jackc/pgx/v5/pgtype"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type retryTypingAPI struct {+ *crossProcessReactionAPI+ failureMu sync.Mutex+ fail bool+}++func (a *retryTypingAPI) DeleteMessageReaction(ctx context.Context, p DeleteReactionParams) error {+ a.failureMu.Lock()+ fail := a.fail+ a.failureMu.Unlock()+ if fail {+ return errors.New("remote unavailable")+ }+ return a.crossProcessReactionAPI.DeleteMessageReaction(ctx, p)+}++// FIXME(test-integration): Failed withdrawal must retain a restart-safe anchor,+// even after all session/installation source rows disappear.+func TestTypingWithdrawalRetryAfterSourceDeletionDB(t *testing.T) {+ f := newTypingDBFixture(t)+ f.Exec(t, "UPDATE agent_task_queue SET status='cancelled' WHERE id=$1", f.taskID)+ api := &retryTypingAPI{crossProcessReactionAPI: &crossProcessReactionAPI{fakeTypingAPIClient: &fakeTypingAPIClient{}, remote: map[string][]MessageReaction{"retry-input": {{ReactionID: "human", OperatorType: "user", EmojiType: typingEmoji}}}}, fail: true}+ a := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ a.Add(context.Background(), f.inst, f.sessionID, "retry-input", "", f.messageID)+ var pending int+ f.QueryRow(t, "SELECT count(*) FROM channel_typing_reaction WHERE workspace_id=$1 AND cleanup_required AND cleaned_at IS NULL AND reaction_id<>''", f.inst.WorkspaceID).Scan(&pending)+ if pending != 1 || len(api.remote["retry-input"]) != 2 {+ t.Fatalf("failed withdrawal lost compensation: pending=%d remote=%+v", pending, api.remote)+ }+ f.Exec(t, "DELETE FROM channel_chat_session_binding WHERE chat_session_id=$1", f.sessionID)+ f.Exec(t, "DELETE FROM chat_message WHERE chat_session_id=$1", f.sessionID)+ f.Exec(t, "DELETE FROM chat_session WHERE id=$1", f.sessionID)+ f.Exec(t, "DELETE FROM channel_installation WHERE id=$1", f.inst.ID)+ b := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ // First worker failure leases the record instead of spinning or dropping it.+ b.Reconcile(context.Background(), f.sessionID)+ f.QueryRow(t, "SELECT count(*) FROM channel_typing_reaction WHERE workspace_id=$1 AND cleaned_at IS NULL AND attempts=1 AND retry_after>now()", f.inst.WorkspaceID).Scan(&pending)+ if pending != 1 {+ t.Fatal("worker failure was not durably rescheduled")+ }+ api.failureMu.Lock()+ api.fail = false+ api.failureMu.Unlock()+ f.Exec(t, "UPDATE channel_typing_reaction SET retry_after=now() WHERE workspace_id=$1", f.inst.WorkspaceID)+ b.Reconcile(context.Background(), f.sessionID)+ f.QueryRow(t, "SELECT count(*) FROM channel_typing_reaction WHERE workspace_id=$1 AND cleaned_at IS NOT NULL", f.inst.WorkspaceID).Scan(&pending)+ if pending != 1 || len(api.remote["retry-input"]) != 1 || api.remote["retry-input"][0].ReactionID != "human" {+ t.Fatalf("restart compensation failed: ack=%d remote=%+v", pending, api.remote)+ }+}++// FIXME(test-integration): Eligibility must be post-commit and input scoped.+func TestTypingCleanupPreservesRollbackAndNextInputDB(t *testing.T) {+ f := newTypingDBFixture(t)+ next := f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": "next", "channel_ingested": true})+ api := &crossProcessReactionAPI{fakeTypingAPIClient: &fakeTypingAPIClient{}, remote: make(map[string][]MessageReaction)}+ a := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ a.Add(context.Background(), f.inst, f.sessionID, "old", "", f.messageID)+ a.Add(context.Background(), f.inst, f.sessionID, "next", "", uuidFromString(t, next))+ tx, err := f.Pool.Begin(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(context.Background())+ if _, err = tx.Exec(context.Background(), "UPDATE agent_task_queue SET status='cancelled' WHERE id=$1", f.taskID); err != nil {+ t.Fatal(err)+ }+ b := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ b.Reconcile(context.Background(), f.sessionID)+ if len(api.remote["old"]) != 1 || len(api.remote["next"]) != 1 {+ t.Fatalf("uncommitted terminal state removed reactions: %+v", api.remote)+ }+ if err = tx.Rollback(context.Background()); err != nil {+ t.Fatal(err)+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='cancelled' WHERE id=$1", f.taskID)+ b.Reconcile(context.Background(), f.sessionID)+ a.Reconcile(context.Background(), f.sessionID) // Also evict A's already-acknowledged local view.+ if states := a.states[uuidString(f.sessionID)]; len(states) != 1 || states[0].MessageID != "next" {+ t.Fatalf("local cleanup lost next input or retained old: %+v", states)+ }+ if len(api.remote["old"]) != 0 || len(api.remote["next"]) != 1 {+ t.Fatalf("committed cleanup damaged next input: %+v", api.remote)+ }+}++type lostTypingFinish struct{ *ChannelStore }++func (q lostTypingFinish) FinishChannelTypingReactionAdd(context.Context, db.FinishChannelTypingReactionAddParams) (db.ChannelTypingReaction, error) {+ return db.ChannelTypingReaction{}, errors.New("database unavailable after remote Add")+}++// FIXME(test-integration): Unknown HTTP outcomes are swept, never acknowledged+// as complete merely because one early list was empty.+func TestTypingUnrecordedAddRetainsRecoveryAnchorDB(t *testing.T) {+ f := newTypingDBFixture(t)+ api := &retryTypingAPI{crossProcessReactionAPI: &crossProcessReactionAPI{fakeTypingAPIClient: &fakeTypingAPIClient{}, remote: make(map[string][]MessageReaction)}, fail: true}+ a := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, lostTypingFinish{f.store}, newDiscardLogger())+ a.Add(context.Background(), f.inst, f.sessionID, "unknown", "", f.messageID)+ f.Exec(t, "UPDATE channel_typing_reaction SET created_at=now()-interval '2 minutes',retry_after=now() WHERE workspace_id=$1", f.inst.WorkspaceID)+ api.failureMu.Lock()+ api.fail = false+ api.failureMu.Unlock()+ b := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ b.Reconcile(context.Background(), f.sessionID)+ if len(api.remote["unknown"]) != 0 {+ t.Fatal("unfinished Add was not compensated")+ }+ var retained int+ f.QueryRow(t, "SELECT count(*) FROM channel_typing_reaction WHERE workspace_id=$1 AND cleanup_required AND cleaned_at IS NULL AND NOT add_finished AND retry_after>now()", f.inst.WorkspaceID).Scan(&retained)+ if retained != 1 {+ t.Fatal("uncertain Add must retain its anchor for subsequent remote changes")+ }+}++// FIXME(test-integration): A forged settlement scope cannot mutate another+// workspace; an aborted settlement transaction must leave the input live.+func TestTypingSettlementWorkspaceAndRollbackDB(t *testing.T) {+ f := newTypingDBFixture(t)+ f.Exec(t, "UPDATE chat_message SET task_id=NULL WHERE id=$1", f.messageID)+ arg := db.SettleChannelTypingInputsParams{ChatSessionID: f.sessionID, ThroughMessageID: f.messageID, WorkspaceID: f.inst.WorkspaceID, InstallationID: f.inst.ID, ContextRevision: pgtype.Int8{Int64: 1, Valid: true}}+ tx, err := f.Pool.Begin(context.Background())+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(context.Background())+ if err = f.store.WithTx(tx).SettleChannelTypingInputs(context.Background(), arg); err != nil {+ t.Fatal(err)+ }+ if err = tx.Rollback(context.Background()); err != nil {+ t.Fatal(err)+ }+ arg.WorkspaceID = f.taskID+ if err = f.store.SettleChannelTypingInputs(context.Background(), arg); err != nil {+ t.Fatal(err)+ }+ var settled bool+ f.QueryRow(t, "SELECT channel_typing_settled FROM chat_message WHERE id=$1", f.messageID).Scan(&settled)+ if settled {+ t.Fatal("rollback or foreign workspace settled the input")+ }+}++// FIXME(test-integration): Every sealed input is enumerable independently of+// delivery, while a new unowned input in the same session remains active.+func TestTypingCleanupAllBatchInputsDB(t *testing.T) {+ f := newTypingDBFixture(t)+ api := &crossProcessReactionAPI{fakeTypingAPIClient: &fakeTypingAPIClient{}, remote: make(map[string][]MessageReaction)}+ a := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ for i, name := range []string{"first", "middle", "trigger"} {+ id := f.messageID+ if i > 0 {+ id = uuidFromString(t, f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": name, "task_id": f.taskID, "channel_ingested": true}))+ }+ api.remote[name] = []MessageReaction{{ReactionID: "human", OperatorType: "user", EmojiType: typingEmoji}}+ a.Add(context.Background(), f.inst, f.sessionID, name, "", id)+ }+ next := f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": "next", "channel_ingested": true})+ a.Add(context.Background(), f.inst, f.sessionID, "next", "", uuidFromString(t, next))+ f.Exec(t, "UPDATE agent_task_queue SET status='completed' WHERE id=$1", f.taskID)+ b := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ b.Reconcile(context.Background(), f.sessionID)+ for _, name := range []string{"first", "middle", "trigger"} {+ if r := api.remote[name]; len(r) != 1 || r[0].ReactionID != "human" {+ t.Fatalf("batch input %s retains app or loses human: %+v", name, r)+ }+ }+ if len(api.remote["next"]) != 1 {+ t.Fatal("next input reaction removed")+ }+}diff --git a/server/internal/integrations/lark/typing_cleanup_test.go b/server/internal/integrations/lark/typing_cleanup_test.gonew file mode 100644index 0000000000..45dc8578f9--- /dev/null+++ b/server/internal/integrations/lark/typing_cleanup_test.go@@ -0,0 +1,84 @@+package lark++import (+ "context"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++func (f *fakeTypingQueries) RegisterChannelTypingReaction(_ context.Context, p db.RegisterChannelTypingReactionParams) (db.ChannelTypingReaction, error) {+ f.ledgerMu.Lock()+ defer f.ledgerMu.Unlock()+ if f.ledger == nil {+ f.ledger = make(map[pgtype.UUID]db.ChannelTypingReaction)+ }+ r := db.ChannelTypingReaction{ID: p.ID, WorkspaceID: p.WorkspaceID, ChatSessionID: p.ChatSessionID, ChatMessageID: p.ChatMessageID, InstallationID: p.InstallationID, ChannelMessageID: p.ChannelMessageID, InstallationSnapshot: p.InstallationSnapshot}+ f.ledger[p.ID] = r+ return r, nil+}+func (f *fakeTypingQueries) FinishChannelTypingReactionAdd(_ context.Context, p db.FinishChannelTypingReactionAddParams) (db.ChannelTypingReaction, error) {+ f.ledgerMu.Lock()+ defer f.ledgerMu.Unlock()+ r, ok := f.ledger[p.ID]+ if !ok {+ return r, pgx.ErrNoRows+ }+ r.ReactionID = p.ReactionID+ r.AddFinished = true+ r.CleanupRequired = r.CleanupRequired || p.CleanupRequired+ r.CleanedAt = pgtype.Timestamptz{}+ f.ledger[p.ID] = r+ return r, nil+}+func (f *fakeTypingQueries) AcknowledgeChannelTypingReactionCleanup(_ context.Context, p db.AcknowledgeChannelTypingReactionCleanupParams) error {+ f.ledgerMu.Lock()+ defer f.ledgerMu.Unlock()+ r := f.ledger[p.ID]+ if r.AddFinished && r.ReactionID != "" && r.ReactionID == p.ReactionID {+ r.CleanedAt = pgtype.Timestamptz{Time: time.Now(), Valid: true}+ f.ledger[p.ID] = r+ }+ return nil+}++// Existing event unit fixtures supply terminal events directly rather than+// mutating DB tasks. Real eligibility is covered by the DB regression matrix.+func (f *fakeTypingQueries) ClaimChannelTypingReactionCleanup(_ context.Context, session pgtype.UUID) ([]db.ChannelTypingReaction, error) {+ f.ledgerMu.Lock()+ defer f.ledgerMu.Unlock()+ var rows []db.ChannelTypingReaction+ for id, r := range f.ledger {+ if !r.CleanedAt.Valid && (!session.Valid || r.ChatSessionID == session) {+ r.CleanupRequired = true+ f.ledger[id] = r+ rows = append(rows, r)+ }+ }+ return rows, nil+}+func (f *fakeTypingQueries) SettleChannelTypingInputs(context.Context, db.SettleChannelTypingInputsParams) error {+ return nil+}+func (f *fakeTypingQueries) SkipChannelTypingReactionAdd(context.Context, pgtype.UUID) error {+ return nil+}+func (f *fakeTypingQueries) PruneChannelTypingReactionCleanup(context.Context) error { return nil }++func (f *fakeTypingQueries) ListRequestedChannelTypingReactions(_ context.Context, ids []pgtype.UUID) ([]pgtype.UUID, error) {+ f.ledgerMu.Lock()+ defer f.ledgerMu.Unlock()+ var closed []pgtype.UUID+ for _, id := range ids {+ if f.ledger[id].CleanupRequired {+ closed = append(closed, id)+ }+ }+ return closed, nil+}++func (f *fakeTypingQueries) ExpireChannelTypingReactionCleanup(context.Context) ([]db.ExpireChannelTypingReactionCleanupRow, error) {+ return nil, nil+}diff --git a/server/internal/integrations/lark/typing_coalesced_regression_test.go b/server/internal/integrations/lark/typing_coalesced_regression_test.gonew file mode 100644index 0000000000..291612bd69--- /dev/null+++ b/server/internal/integrations/lark/typing_coalesced_regression_test.go@@ -0,0 +1,133 @@+package lark++import (+ "context"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type qaCoalescedCheckBarrier struct {+ TypingIndicatorQueries+ checked chan bool+ release chan struct{}+}++func (q *qaCoalescedCheckBarrier) IsChannelMessageTypingActive(ctx context.Context, arg db.IsChannelMessageTypingActiveParams) (bool, error) {+ active, err := q.TypingIndicatorQueries.IsChannelMessageTypingActive(ctx, arg)+ if err != nil {+ return active, err+ }+ q.checked <- active+ select {+ case <-q.release:+ return active, nil+ case <-ctx.Done():+ return false, ctx.Err()+ }+}++// A real committed DB read is paused after it observes active=true. Process B+// then terminates the task and sweeps its single delivery trigger, which is not+// the other input from the same sealed debounce batch.+// FIXME(test-integration): Preserves QA's exact post-SELECT barrier and its+// delivery-trigger control, including source deletion before terminal delivery.+func TestTypingTrueCheckThenCrossProcessTerminalDB(t *testing.T) {+ for _, removal := range []string{"retained", "deleted", "archived"} {+ t.Run(removal, func(t *testing.T) {+ t.Run("actual_delivery_trigger", func(t *testing.T) { qaRunTrueCheckThenTerminal(t, true, removal) })+ t.Run("coalesced_non_trigger", func(t *testing.T) { qaRunTrueCheckThenTerminal(t, false, removal) })+ })+ }+}++func qaRunTrueCheckThenTerminal(t *testing.T, actualTrigger bool, removal string) {+ f := newTypingDBFixture(t)+ f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": "delivery trigger in same batch", "task_id": f.taskID, "channel_ingested": true})+ p, patcherQueries, _ := newTestPatcher(t)+ patcherQueries.installation = f.inst+ patcherQueries.binding.ChatSessionID = f.sessionID+ patcherQueries.binding.InstallationID = f.inst.ID+ patcherQueries.binding.LastMessageID = pgtype.Text{String: "delivery-trigger", Valid: true}+ api := &crossProcessReactionAPI{+ fakeTypingAPIClient: &fakeTypingAPIClient{},+ remote: map[string][]MessageReaction{+ "coalesced-input": {{ReactionID: "human-typing", OperatorType: "user", EmojiType: typingEmoji}},+ "delivery-trigger": {{ReactionID: "trigger-app", OperatorType: "app", OperatorID: f.inst.AppID, EmojiType: typingEmoji}},+ },+ }+ platformMessage := "coalesced-input"+ wantTriggerRemaining := 0+ if actualTrigger {+ platformMessage = "delivery-trigger"+ wantTriggerRemaining = 1+ api.remote[platformMessage] = []MessageReaction{{ReactionID: "human-typing", OperatorType: "user", EmojiType: typingEmoji}}+ }+ barrier := &qaCoalescedCheckBarrier{TypingIndicatorQueries: f.store, checked: make(chan bool, 1), release: make(chan struct{})}+ managerA := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, barrier, newDiscardLogger())+ managerB := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, f.store, newDiscardLogger())+ p.SetTypingIndicatorManager(managerB)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ var release sync.Once+ defer release.Do(func() { close(barrier.release) })+ done := make(chan struct{})+ go func() {+ defer close(done)+ managerA.Add(ctx, f.inst, f.sessionID, platformMessage, "", f.messageID)+ }()+ select {+ case active := <-barrier.checked:+ if !active {+ t.Fatal("precondition: real DB must report old input active before termination")+ }+ case <-ctx.Done():+ t.Fatal("real DB lifecycle check did not complete")+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='cancelled' WHERE id=$1", f.taskID)+ event := events.Event{Type: protocol.EventTaskCancelled, TaskID: uuidString(f.taskID), ChatSessionID: uuidString(f.sessionID)}+ if removal == "deleted" {+ f.Exec(t, "DELETE FROM channel_chat_session_binding WHERE chat_session_id=$1", f.sessionID)+ f.Exec(t, "DELETE FROM chat_message WHERE chat_session_id=$1", f.sessionID)+ f.Exec(t, "DELETE FROM chat_session WHERE id=$1", f.sessionID)+ patcherQueries.deliveryErr = pgx.ErrNoRows+ event.ChannelReactionTarget = &events.ChannelReactionTarget{ChannelType: channelTypeFeishu, InstallationID: uuidString(f.inst.ID), MessageID: "delivery-trigger"}+ } else if removal == "archived" {+ f.Exec(t, "UPDATE chat_session SET status='archived' WHERE id=$1", f.sessionID)+ }+ p.handleEvent(event)+ api.mu.Lock()+ triggerLeft, deletes, lists := len(api.remote["delivery-trigger"]), api.deletes, api.lists+ api.mu.Unlock()+ wantCleanups := 2+ if actualTrigger {+ wantCleanups = 1+ }+ if triggerLeft != wantTriggerRemaining || deletes != wantCleanups || lists != wantCleanups {+ t.Fatalf("precondition: B must remove actual delivery trigger: trigger=%d deletes=%d lists=%d", triggerLeft, deletes, lists)+ }+ release.Do(func() { close(barrier.release) })+ select {+ case <-done:+ case <-ctx.Done():+ t.Fatal("Add did not complete")+ }+ active, err := f.store.IsChannelMessageTypingActive(ctx, db.IsChannelMessageTypingActiveParams{MessageID: f.messageID, ChatSessionID: f.sessionID, WorkspaceID: f.inst.WorkspaceID, InstallationID: f.inst.ID, ChannelType: channelTypeFeishu})+ if err != nil || active {+ t.Fatalf("precondition: committed terminal input must now be inactive: active=%v err=%v", active, err)+ }+ api.mu.Lock()+ defer api.mu.Unlock()+ remaining := api.remote[platformMessage]+ t.Logf("after active SELECT -> B terminal sweep -> A return: lists=%d deletes=%d trigger=%d coalesced=%+v A_states=%d B_states=%d db_active=%v", api.lists, api.deletes, len(api.remote["delivery-trigger"]), remaining, len(managerA.states[uuidString(f.sessionID)]), len(managerB.states[uuidString(f.sessionID)]), active)+ if len(remaining) != 1 || remaining[0].ReactionID != "human-typing" {+ t.Fatalf("terminal cleanup must remove app reaction and preserve human Typing: want [human-typing], got %+v", remaining)+ }+}diff --git a/server/internal/integrations/lark/typing_cross_process_test.go b/server/internal/integrations/lark/typing_cross_process_test.gonew file mode 100644index 0000000000..02856cc947--- /dev/null+++ b/server/internal/integrations/lark/typing_cross_process_test.go@@ -0,0 +1,143 @@+package lark++import (+ "context"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// Two independent managers share the remote API and durable DB, never local state.+type crossProcessReactionAPI struct {+ *fakeTypingAPIClient+ mu sync.Mutex+ started chan struct{}+ release chan struct{}+ remote map[string][]MessageReaction+ lists int+ deletes int+}++func (a *crossProcessReactionAPI) AddMessageReaction(ctx context.Context, p AddReactionParams) (string, error) {+ if p.MessageID == "late-trigger" {+ close(a.started)+ select {+ case <-a.release:+ case <-ctx.Done():+ return "", ctx.Err()+ }+ }+ reactionID := "reaction-" + p.MessageID+ a.mu.Lock()+ a.remote[p.MessageID] = append(a.remote[p.MessageID], MessageReaction{ReactionID: reactionID, OperatorType: "app", OperatorID: p.InstallationID.AppID, EmojiType: typingEmoji})+ a.mu.Unlock()+ return reactionID, nil+}++func (a *crossProcessReactionAPI) ListMessageReactions(_ context.Context, p ListMessageReactionsParams) ([]MessageReaction, error) {+ a.mu.Lock()+ defer a.mu.Unlock()+ a.lists+++ return append([]MessageReaction(nil), a.remote[p.MessageID]...), nil+}++func (a *crossProcessReactionAPI) DeleteMessageReaction(_ context.Context, p DeleteReactionParams) error {+ a.mu.Lock()+ defer a.mu.Unlock()+ a.deletes+++ for i, reaction := range a.remote[p.MessageID] {+ if reaction.ReactionID == p.ReactionID {+ a.remote[p.MessageID] = append(a.remote[p.MessageID][:i], a.remote[p.MessageID][i+1:]...)+ break+ }+ }+ return nil+}++// FIXME(test-integration): Both QA orderings use a real shared DB and deterministic HTTP barriers.+func TestTypingCrossProcessLateAddAfterTerminalSweepDB(t *testing.T) {+ for _, deleted := range []bool{false, true} {+ name := "delivery_retained"+ if deleted {+ name = "session_deleted_captured_target"+ }+ t.Run(name, func(t *testing.T) {+ f := newTypingDBFixture(t)+ p, q, _ := newTestPatcher(t)+ q.installation = f.inst+ q.binding.ChatSessionID = f.sessionID+ q.binding.InstallationID = f.inst.ID+ q.binding.LastMessageID = pgtype.Text{String: "late-trigger", Valid: true}+ if deleted {+ q.deliveryErr = pgx.ErrNoRows+ }+ api := &crossProcessReactionAPI{fakeTypingAPIClient: &fakeTypingAPIClient{}, started: make(chan struct{}), release: make(chan struct{}), remote: map[string][]MessageReaction{"late-trigger": {{ReactionID: "human-typing", OperatorType: "user", EmojiType: typingEmoji}}}}+ managerA := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, f.store, newDiscardLogger())+ managerB := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, f.store, newDiscardLogger())+ p.SetTypingIndicatorManager(managerB)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ var release sync.Once+ defer release.Do(func() { close(api.release) })+ done := make(chan struct{})+ go func() {+ defer close(done)+ managerA.Add(ctx, q.installation, q.binding.ChatSessionID, "late-trigger", "", f.messageID)+ }()+ select {+ case <-api.started:+ case <-ctx.Done():+ t.Fatal("Add did not start")+ }+ f.Exec(t, "UPDATE agent_task_queue SET status='cancelled' WHERE id=$1", f.taskID)+ if deleted {+ f.Exec(t, "DELETE FROM channel_chat_session_binding WHERE chat_session_id=$1", f.sessionID)+ f.Exec(t, "DELETE FROM chat_message WHERE chat_session_id=$1", f.sessionID)+ f.Exec(t, "DELETE FROM chat_session WHERE id=$1", f.sessionID)+ }+ e := events.Event{Type: protocol.EventTaskCancelled, TaskID: uuidString(f.taskID), ChatSessionID: uuidString(q.binding.ChatSessionID)}+ if deleted {+ e.ChannelReactionTarget = &events.ChannelReactionTarget{ChannelType: channelTypeFeishu, InstallationID: uuidString(q.installation.ID), MessageID: "late-trigger"}+ }+ p.handleEvent(e)+ api.mu.Lock()+ lists, deletes := api.lists, api.deletes+ t.Logf("terminal completed before Add: lists=%d deletes=%d remote=%d", lists, deletes, len(api.remote["late-trigger"]))+ api.mu.Unlock()+ if lists != 1 || deletes != 0 {+ t.Fatalf("B must finish its app-empty sweep while A is blocked: lists=%d deletes=%d", lists, deletes)+ }+ if !deleted {+ nextTask := f.Task(t, uuidString(f.inst.AgentID), dbfx.Cols{"chat_session_id": f.sessionID, "status": "running", "runtime_id": f.runtimeID})+ nextMessage := f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": "next", "task_id": nextTask, "channel_ingested": true})+ managerA.Add(ctx, f.inst, f.sessionID, "next-trigger", "", uuidFromString(t, nextMessage))+ }+ release.Do(func() { close(api.release) })+ select {+ case <-done:+ case <-ctx.Done():+ t.Fatal("Add did not finish")+ }+ api.mu.Lock()+ defer api.mu.Unlock()+ states := managerA.states[uuidString(f.sessionID)]+ t.Logf("after late Add: lists=%d deletes=%d old_message_reactions=%+v process_A_states=%d process_B_states=%d", api.lists, api.deletes, api.remote["late-trigger"], len(states), len(managerB.states[uuidString(f.sessionID)]))+ if reactions := api.remote["late-trigger"]; len(reactions) != 1 || reactions[0].ReactionID != "human-typing" || api.deletes != 1 {+ t.Fatalf("late Add must delete exactly its own reaction and preserve human Typing: %+v deletes=%d", reactions, api.deletes)+ }+ if deleted {+ if len(states) != 0 {+ t.Fatalf("deleted session retains local state: %+v", states)+ }+ } else if len(states) != 1 || states[0].MessageID != "next-trigger" || len(api.remote["next-trigger"]) != 1 {+ t.Fatalf("late cleanup damaged next turn: states=%+v remote=%+v", states, api.remote)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/typing_indicator.go b/server/internal/integrations/lark/typing_indicator.goindex b7edf792ba..5adff7c5c3 100644--- a/server/internal/integrations/lark/typing_indicator.go+++ b/server/internal/integrations/lark/typing_indicator.go@@ -2,14 +2,19 @@ package larkimport ("context"+ "encoding/json""errors""log/slog""strconv"+ "strings""sync""time""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"++ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/dbid")// typingEmoji is the Lark emoji_type used for the "processing" indicator.@@ -21,37 +26,22 @@ const typingEmoji = "Typing"// reconnect replays old events. Aligned with OpenClaw's 2-minute bound.const typingIndicatorMaxAge = 2 * time.Minute-// TypingIndicatorState holds the identifiers needed to remove a reaction, plus-// the installation whose app credentials added it. The installation id is-// recorded at add time because that is the last moment it is certainly-// resolvable: it is reachable from the session's channel_chat_session_binding-// row, and a session delete drops that row while the cancel it triggers is-// still on its way to the Patcher.-type TypingIndicatorState struct {- MessageID string- ReactionID string- InstallationID pgtype.UUID+// typingCleanupTimeout bounds best-effort cleanup independently of reply delivery.+const typingCleanupTimeout = 2 * time.Second- // installSnapshot is the installation row as it stood when the reaction was- // added, kept for the one case where the id is no longer enough: a runtime- // teardown deletes the installation inside the same transaction that- // cancels the tasks (handler/runtime.go,- // DeleteChannelInstallationsBySystemRuntimeAgents), so by the time the- // cancel reaches Clear there is no row to resolve.- //- // It is a FALLBACK, never the primary. A live lookup picks up a credential- // rotation between add and clear; a snapshot cannot, so it is consulted- // only when the row is genuinely gone.- //- // It does not weaken "no decrypted secret lives in the state map": what is- // held here is the same encrypted blob the database holds, and- // DecryptAppSecret still runs at clear time.- installSnapshot Installation+// TypingIndicatorState is a process-local view of one durable cleanup record.+// It never owns the only copy of a remote reaction's cleanup anchor.+type TypingIndicatorState struct {+ LedgerID pgtype.UUID+ MessageID, ReactionID string+ ended bool // guarded by mu; Reconcile may end an Add before HTTP returns.}// TypingIndicatorQueries is the narrow DB surface the manager needs.type TypingIndicatorQueries interface {+ typingLedgerQueriesGetLarkInstallation(ctx context.Context, id pgtype.UUID) (Installation, error)+ IsChannelMessageTypingActive(ctx context.Context, arg db.IsChannelMessageTypingActiveParams) (bool, error)}// TypingIndicatorManager owns the "processing" reaction lifecycle for@@ -89,14 +79,15 @@ func NewTypingIndicatorManager(client APIClient, credentials CredentialsResolver}// Add sends a Typing reaction to the given message and records the state-// under the chat session. It is synchronous — the caller decides whether+// under the chat session. chatMessageID is the immutable persisted user input,+// not the platform message ID or the latest task in the session. It is synchronous — the caller decides whether// to run it in a detached goroutine. Errors are logged and swallowed.//// createTime is Lark's epoch-millisecond string (InboundMessage.CreateTime).// Messages older than typingIndicatorMaxAge are silently skipped so that// WebSocket replays and stale reconnects do not surface misleading "processing"// badges on long-finished conversations.-func (m *TypingIndicatorManager) Add(ctx context.Context, inst Installation, chatSessionID pgtype.UUID, messageID string, createTime string) {+func (m *TypingIndicatorManager) Add(ctx context.Context, inst Installation, chatSessionID pgtype.UUID, messageID string, createTime string, chatMessageID pgtype.UUID) {if messageID == "" {return}@@ -118,12 +109,60 @@ func (m *TypingIndicatorManager) Add(ctx context.Context, inst Installation, chareturn}- reactionID, err := m.client.AddMessageReaction(ctx, AddReactionParams{+ // The external anchor must be committed before HTTP can create a badge.+ // No registration means no Add: terminal workers must never miss an input.+ snapshot, err := json.Marshal(Installation{ID: inst.ID, WorkspaceID: inst.WorkspaceID, AppID: inst.AppID, AppSecretEncrypted: inst.AppSecretEncrypted, TenantKey: inst.TenantKey, Region: inst.Region})+ if err != nil {+ m.log.Warn("lark typing: encode installation snapshot", "err", err)+ return+ }+ registrationCtx, registrationCancel := context.WithTimeout(context.WithoutCancel(ctx), typingCleanupTimeout)+ row, err := m.queries.RegisterChannelTypingReaction(registrationCtx, db.RegisterChannelTypingReactionParams{+ ID: dbid.NewV7(), WorkspaceID: inst.WorkspaceID, ChatSessionID: chatSessionID,+ ChatMessageID: chatMessageID, InstallationID: inst.ID, ChannelMessageID: messageID, InstallationSnapshot: snapshot,+ })+ registrationCancel()+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ m.log.Warn("lark typing: Add skipped; input unavailable or workspace quota occupied", "workspace_id", uuidString(inst.WorkspaceID))+ return+ }+ m.log.Warn("lark typing: register cleanup anchor", "message_id", messageID, "err", err)+ return+ }+ if row.CleanupRequired {+ skipCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), typingCleanupTimeout)+ defer cancel()+ if err := m.queries.SkipChannelTypingReactionAdd(skipCtx, row.ID); err != nil {+ m.log.Warn("lark typing: acknowledge skipped add", "err", err)+ }+ return+ }++ key := uuidString(chatSessionID)+ state := &TypingIndicatorState{LedgerID: row.ID, MessageID: messageID}+ m.mu.Lock()+ m.states[key] = append(m.states[key], state)+ m.mu.Unlock()++ addCtx, addCancel := context.WithTimeout(ctx, typingCleanupTimeout)+ reactionID, err := m.client.AddMessageReaction(addCtx, AddReactionParams{InstallationID: creds,MessageID: messageID,EmojiType: typingEmoji,})+ addCancel()if err != nil {+ m.mu.Lock()+ m.removeState(key, state)+ m.mu.Unlock()+ finishCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), typingCleanupTimeout)+ defer cancel()+ // A transport failure does not prove the remote side did not add it.+ // Keep the anchor in the durable retry queue, including across restart.+ if _, finishErr := m.queries.FinishChannelTypingReactionAdd(finishCtx, db.FinishChannelTypingReactionAddParams{ID: row.ID, CleanupRequired: true}); finishErr != nil {+ m.log.Warn("lark typing: record uncertain Add", "err", finishErr)+ }m.log.Warn("lark typing indicator: add reaction failed","chat_session_id", uuidString(chatSessionID),"message_id", messageID,@@ -132,15 +171,50 @@ func (m *TypingIndicatorManager) Add(ctx context.Context, inst Installation, chareturn}- key := uuidString(chatSessionID)- m.mu.Lock()- m.states[key] = append(m.states[key], &TypingIndicatorState{- MessageID: messageID,- ReactionID: reactionID,- InstallationID: inst.ID,- installSnapshot: inst,+ // The terminal event may have been handled by another process while the+ // remote Add was in flight. Re-read this exact persisted input after the+ // remote write so a committed terminal state retracts the late result.+ // A session's latest+ // task/delivery is not sufficient: debounce can seal several inputs and a+ // newer turn may already exist. Missing/deleted inputs are no longer live.+ checkCtx, checkCancel := context.WithTimeout(context.WithoutCancel(ctx), typingCleanupTimeout)+ active, checkErr := m.queries.IsChannelMessageTypingActive(checkCtx, db.IsChannelMessageTypingActiveParams{+ MessageID: chatMessageID, ChatSessionID: chatSessionID,+ WorkspaceID: inst.WorkspaceID, InstallationID: inst.ID,+ ChannelType: channelTypeFeishu,})+ checkCancel()+ if checkErr != nil {+ // An unverified processing badge must not survive indefinitely.+ m.log.Warn("lark typing indicator: input lifecycle lookup failed", "message_id", messageID, "err", checkErr)+ }++ m.mu.Lock()+ ended := state.ended || !active || checkErr != nil+ m.mu.Unlock()+ finishCtx, finishCancel := context.WithTimeout(context.WithoutCancel(ctx), typingCleanupTimeout)+ finished, finishErr := m.queries.FinishChannelTypingReactionAdd(finishCtx, db.FinishChannelTypingReactionAddParams{ID: row.ID, ReactionID: reactionID, CleanupRequired: ended})+ finishCancel()+ if finishErr != nil {+ m.log.Warn("lark typing: record Add result; durable unfinished anchor remains", "err", finishErr)+ row.ReactionID = reactionID+ row.CleanupRequired = true+ finished = row+ }+ m.mu.Lock()+ ended = ended || state.ended || finished.CleanupRequired || finishErr != nil+ if ended {+ m.removeState(key, state)+ } else {+ state.ReactionID = reactionID+ }m.mu.Unlock()+ if ended {+ cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), typingCleanupTimeout)+ defer cancel()+ m.cleanupReaction(cleanupCtx, finished)+ return+ }m.log.Debug("lark typing indicator: reaction added","chat_session_id", key,@@ -149,69 +223,77 @@ func (m *TypingIndicatorManager) Add(ctx context.Context, inst Installation, cha)}-// Clear removes every tracked Typing reaction for the chat session and-// drops the state entry. It is synchronous so the reaction is gone before-// the agent's reply is sent, giving the user a clean visual transition.-// Individual delete failures are logged but do not abort the loop.+// removeState removes only this Add's entry, preserving later inputs. mu must be held.+func (m *TypingIndicatorManager) removeState(key string, state *TypingIndicatorState) {+ for i, pending := range m.states[key] {+ if pending == state {+ m.states[key] = append(m.states[key][:i], m.states[key][i+1:]...)+ if len(m.states[key]) == 0 {+ delete(m.states, key)+ }+ return+ }+ }+}++// SweepMessage removes every Typing reaction the bot itself put on a message,+// found by listing the message's reactions from Lark rather than by consulting+// the in-memory state. This is the authoritative half of the lifecycle: the+// state map only exists in the process that ran Add, so a restart between add+// and clear or a second replica handling completion leaves the map empty+// while the badge is still on screen. In-flight adds are handled separately+// by the durable pending-Add record. The sweep also retries reactions whose+// exact deletion failed during reconciliation.//-// Credentials come from the installation each state recorded, not from the-// session's binding, because a clear can outlive that binding: deleting a chat-// session drops the binding row inside the same transaction that cancels the-// session's tasks, and the task:cancelled events that reach the Patcher are-// broadcast after that transaction commits. A binding lookup would miss, and-// since the state has already been taken here, there would be nothing left to-// clear from. Installation rows survive a session delete.+// Both operator type and App ID must match. Other applications' reactions are+// not ours to delete and must not turn an otherwise successful sweep into a retry.//-// They do NOT survive a runtime teardown, which deletes them in the same-// transaction — so each state also carries the installation as it stood at add-// time, consulted only when the row is gone. See TypingIndicatorState.-func (m *TypingIndicatorManager) Clear(ctx context.Context, chatSessionID pgtype.UUID) {- key := uuidString(chatSessionID)- m.mu.Lock()- states := m.states[key]- delete(m.states, key)- m.mu.Unlock()-- if len(states) == 0 {+// credentials came from the caller, which resolves them from the same+// installation that added the reaction; errors are logged and swallowed — the+// indicator is best-effort and must never fail a reply. A client that does not+// implement ReactionLister (the stub, minimal fakes) skips the sweep.+func (m *TypingIndicatorManager) SweepMessage(ctx context.Context, creds InstallationCredentials, messageID string) {+ if messageID == "" || creds.AppID == "" {return}-- // One session's reactions normally share an installation, so the resolved- // credentials are memoised; a session rebound to another installation- // mid-run still clears every reaction through the app that added it. A nil- // entry records an installation that failed to resolve, so it is not- // retried once per reaction.- resolved := make(map[string]*InstallationCredentials, 1)- for _, s := range states {- if s.ReactionID == "" {- continue- }- instKey := uuidString(s.InstallationID)- creds, seen := resolved[instKey]- if !seen {- creds = m.credentialsForInstallation(ctx, key, s.InstallationID, s.installSnapshot)- resolved[instKey] = creds- }- if creds == nil {+ lister, ok := m.client.(ReactionLister)+ if !ok {+ m.log.Debug("lark typing indicator: client cannot list reactions, skipping sweep",+ "message_id", messageID,+ )+ return+ }+ reactions, err := lister.ListMessageReactions(ctx, ListMessageReactionsParams{+ InstallationID: creds,+ MessageID: messageID,+ EmojiType: typingEmoji,+ })+ if err != nil {+ m.log.Warn("lark typing indicator: sweep list reactions failed",+ "message_id", messageID,+ "err", err,+ )+ return+ }+ for _, r := range reactions {+ if !strings.EqualFold(r.EmojiType, typingEmoji) || r.OperatorType != "app" || r.OperatorID != creds.AppID {continue}if err := m.client.DeleteMessageReaction(ctx, DeleteReactionParams{- InstallationID: *creds,- MessageID: s.MessageID,- ReactionID: s.ReactionID,+ InstallationID: creds,+ MessageID: messageID,+ ReactionID: r.ReactionID,}); err != nil {- m.log.Warn("lark typing indicator: delete reaction failed",- "chat_session_id", key,- "message_id", s.MessageID,- "reaction_id", s.ReactionID,+ m.log.Warn("lark typing indicator: sweep delete reaction failed",+ "message_id", messageID,+ "reaction_id", r.ReactionID,"err", err,)continue}- m.log.Debug("lark typing indicator: reaction removed",- "chat_session_id", key,- "message_id", s.MessageID,- "reaction_id", s.ReactionID,+ m.log.Debug("lark typing indicator: sweep removed reaction",+ "message_id", messageID,+ "reaction_id", r.ReactionID,)}}diff --git a/server/internal/integrations/lark/typing_indicator_test.go b/server/internal/integrations/lark/typing_indicator_test.goindex d4876f35d2..d5e836d43f 100644--- a/server/internal/integrations/lark/typing_indicator_test.go+++ b/server/internal/integrations/lark/typing_indicator_test.go@@ -4,17 +4,23 @@ import ("context""errors""strconv"+ "sync""testing""time""github.com/jackc/pgx/v5""github.com/jackc/pgx/v5/pgtype"+ db "github.com/multica-ai/multica/server/pkg/db/generated")// fakeTypingAPIClient records reaction calls and can be programmed to fail.type fakeTypingAPIClient struct {+ mu sync.MutexaddCalled []addReactionCalldeleteCalled []deleteReactionCall+ listCalled []string+ listReturn []MessageReaction+ listErr erroraddErr errordeleteErr erroraddReturn string@@ -64,21 +70,47 @@ func (f *fakeTypingAPIClient) BatchGetUsers(context.Context, InstallationCredentreturn nil, nil}func (f *fakeTypingAPIClient) AddMessageReaction(_ context.Context, p AddReactionParams) (string, error) {+ f.mu.Lock()+ defer f.mu.Unlock()f.addCalled = append(f.addCalled, addReactionCall{p.InstallationID, p.MessageID, p.EmojiType})return f.addReturn, f.addErr}func (f *fakeTypingAPIClient) DeleteMessageReaction(_ context.Context, p DeleteReactionParams) error {+ f.mu.Lock()+ defer f.mu.Unlock()f.deleteCalled = append(f.deleteCalled, deleteReactionCall{p.InstallationID, p.MessageID, p.ReactionID})return f.deleteErr}+func (f *fakeTypingAPIClient) ListMessageReactions(_ context.Context, p ListMessageReactionsParams) ([]MessageReaction, error) {+ f.mu.Lock()+ defer f.mu.Unlock()+ f.listCalled = append(f.listCalled, p.MessageID)+ return f.listReturn, f.listErr+}++// noListerClient wraps an APIClient without promoting any extra methods, so it+// satisfies APIClient but not ReactionLister — the shape of a client that+// cannot answer "what is already on this message".+type noListerClient struct{ APIClient }+type fakeTypingQueries struct {+ ledgerMu sync.Mutex+ ledger map[pgtype.UUID]db.ChannelTypingReaction+ active func(context.Context, db.IsChannelMessageTypingActiveParams) (bool, error)binding ChatSessionBindinginstallation InstallationbindingErr errorinstallErr error}+func (f *fakeTypingQueries) IsChannelMessageTypingActive(ctx context.Context, arg db.IsChannelMessageTypingActiveParams) (bool, error) {+ if f.active != nil {+ return f.active(ctx, arg)+ }+ return true, nil+}+func (f *fakeTypingQueries) GetLarkChatSessionBindingBySession(context.Context, pgtype.UUID) (ChatSessionBinding, error) {return f.binding, f.bindingErr}@@ -100,7 +132,7 @@ func TestTypingIndicatorAddRecordsState(t *testing.T) {inst := Installation{AppID: "cli_test", Region: "feishu"}session := pgtype.UUID{Bytes: [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, Valid: true}- mgr.Add(context.Background(), inst, session, "msg-1", "")+ mgr.Add(context.Background(), inst, session, "msg-1", "", session)if len(api.addCalled) != 1 {t.Fatalf("expected 1 add call, got %d", len(api.addCalled))@@ -125,7 +157,7 @@ func TestTypingIndicatorAddSkipsOnEmptyMessageID(t *testing.T) {inst := Installation{AppID: "cli_test", Region: "feishu"}session := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}- mgr.Add(context.Background(), inst, session, "", "")+ mgr.Add(context.Background(), inst, session, "", "", session)if len(api.addCalled) != 0 {t.Fatalf("expected 0 add calls, got %d", len(api.addCalled))@@ -140,7 +172,7 @@ func TestTypingIndicatorAddSkipsOldMessages(t *testing.T) {session := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}oldTime := time.Now().Add(-3 * time.Minute).UnixMilli()- mgr.Add(context.Background(), inst, session, "msg-old", strconv.FormatInt(oldTime, 10))+ mgr.Add(context.Background(), inst, session, "msg-old", strconv.FormatInt(oldTime, 10), session)if len(api.addCalled) != 0 {t.Fatalf("expected 0 add calls for old message, got %d", len(api.addCalled))@@ -154,7 +186,7 @@ func TestTypingIndicatorAddLogsOnAPIError(t *testing.T) {inst := Installation{AppID: "cli_test", Region: "feishu"}session := pgtype.UUID{Bytes: [16]byte{1}, Valid: true}- mgr.Add(context.Background(), inst, session, "msg-1", "")+ mgr.Add(context.Background(), inst, session, "msg-1", "", session)if len(api.addCalled) != 1 {t.Fatalf("expected 1 add call, got %d", len(api.addCalled))@@ -169,7 +201,7 @@ func TestTypingIndicatorAddLogsOnAPIError(t *testing.T) {}}-func TestTypingIndicatorClearDeletesReactions(t *testing.T) {+func TestTypingIndicatorReconcileDeletesReactions(t *testing.T) {api := &fakeTypingAPIClient{addReturn: "reaction-abc"}queries := &fakeTypingQueries{binding: ChatSessionBinding{@@ -186,12 +218,12 @@ func TestTypingIndicatorClearDeletesReactions(t *testing.T) {inst := Installation{AppID: "cli_test", Region: "feishu"}session := pgtype.UUID{Bytes: [16]byte{1, 2, 3, 4}, Valid: true}- mgr.Add(context.Background(), inst, session, "msg-1", "")+ mgr.Add(context.Background(), inst, session, "msg-1", "", session)if len(api.addCalled) != 1 {t.Fatal("add should have been called")}- mgr.Clear(context.Background(), session)+ mgr.Reconcile(context.Background(), session)if len(api.deleteCalled) != 1 {t.Fatalf("expected 1 delete call, got %d", len(api.deleteCalled))@@ -209,7 +241,7 @@ func TestTypingIndicatorClearDeletesReactions(t *testing.T) {}}-func TestTypingIndicatorClearNoOpWhenEmpty(t *testing.T) {+func TestTypingIndicatorReconcileNoOpWhenEmpty(t *testing.T) {api := &fakeTypingAPIClient{}queries := &fakeTypingQueries{binding: ChatSessionBinding{@@ -224,14 +256,14 @@ func TestTypingIndicatorClearNoOpWhenEmpty(t *testing.T) {mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, queries, newDiscardLogger())session := pgtype.UUID{Bytes: [16]byte{1, 2, 3, 4}, Valid: true}- mgr.Clear(context.Background(), session)+ mgr.Reconcile(context.Background(), session)if len(api.deleteCalled) != 0 {t.Fatalf("expected 0 delete calls when empty, got %d", len(api.deleteCalled))}}-func TestTypingIndicatorClearLogsOnDeleteError(t *testing.T) {+func TestTypingIndicatorReconcileLogsOnDeleteError(t *testing.T) {api := &fakeTypingAPIClient{addReturn: "reaction-xyz", deleteErr: errors.New("delete failed")}queries := &fakeTypingQueries{binding: ChatSessionBinding{@@ -248,8 +280,8 @@ func TestTypingIndicatorClearLogsOnDeleteError(t *testing.T) {inst := Installation{AppID: "cli_test", Region: "feishu"}session := pgtype.UUID{Bytes: [16]byte{1, 2, 3, 4}, Valid: true}- mgr.Add(context.Background(), inst, session, "msg-1", "")- mgr.Clear(context.Background(), session)+ mgr.Add(context.Background(), inst, session, "msg-1", "", session)+ mgr.Reconcile(context.Background(), session)if len(api.deleteCalled) != 1 {t.Fatalf("expected 1 delete call attempt, got %d", len(api.deleteCalled))@@ -273,14 +305,14 @@ func TestTypingIndicatorMultipleMessagesPerSession(t *testing.T) {inst := Installation{AppID: "cli_test", Region: "feishu"}session := pgtype.UUID{Bytes: [16]byte{1, 2, 3, 4}, Valid: true}- mgr.Add(context.Background(), inst, session, "msg-a", "")- mgr.Add(context.Background(), inst, session, "msg-b", "")+ mgr.Add(context.Background(), inst, session, "msg-a", "", session)+ mgr.Add(context.Background(), inst, session, "msg-b", "", session)if len(api.addCalled) != 2 {t.Fatalf("expected 2 add calls, got %d", len(api.addCalled))}- mgr.Clear(context.Background(), session)+ mgr.Reconcile(context.Background(), session)if len(api.deleteCalled) != 2 {t.Fatalf("expected 2 delete calls, got %d", len(api.deleteCalled))@@ -307,13 +339,13 @@ func TestTypingIndicatorConcurrentAddAndClear(t *testing.T) {done := make(chan struct{})go func() {for i := 0; i < 50; i++ {- mgr.Add(context.Background(), inst, session, "msg", "")+ mgr.Add(context.Background(), inst, session, "msg", "", session)}close(done)}()go func() {for i := 0; i < 50; i++ {- mgr.Clear(context.Background(), session)+ mgr.Reconcile(context.Background(), session)}}()<-done@@ -325,7 +357,7 @@ func TestTypingIndicatorConcurrentAddAndClear(t *testing.T) {// the time the cancel arrives. The reaction is still on the message and the// state has already been taken off the map, so the snapshot recorded at add// time is the only thing left that can remove it.-func TestTypingIndicatorClearsAfterTheInstallationIsDeleted(t *testing.T) {+func TestTypingIndicatorReconcilesAfterTheInstallationIsDeleted(t *testing.T) {api := &fakeTypingAPIClient{addReturn: "reaction-123"}queries := &fakeTypingQueries{}mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, queries, newDiscardLogger())@@ -337,7 +369,7 @@ func TestTypingIndicatorClearsAfterTheInstallationIsDeleted(t *testing.T) {}session := pgtype.UUID{Bytes: [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, Valid: true}- mgr.Add(context.Background(), inst, session, "msg-1", "")+ mgr.Add(context.Background(), inst, session, "msg-1", "", session)if len(api.addCalled) != 1 {t.Fatalf("setup: the reaction should be on the message; adds = %d", len(api.addCalled))}@@ -345,7 +377,7 @@ func TestTypingIndicatorClearsAfterTheInstallationIsDeleted(t *testing.T) {// The teardown transaction has committed.queries.installErr = pgx.ErrNoRows- mgr.Clear(context.Background(), session)+ mgr.Reconcile(context.Background(), session)if len(api.deleteCalled) != 1 {t.Fatalf("the runtime was torn down and its installation deleted, but the reaction is still "+@@ -369,12 +401,115 @@ func TestTypingIndicatorDoesNotFallBackOnATransientLookupFailure(t *testing.T) {}session := pgtype.UUID{Bytes: [16]byte{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16}, Valid: true}- mgr.Add(context.Background(), inst, session, "msg-1", "")+ mgr.Add(context.Background(), inst, session, "msg-1", "", session)queries.installErr = errors.New("connection reset")- mgr.Clear(context.Background(), session)+ mgr.Reconcile(context.Background(), session)if len(api.deleteCalled) != 0 {t.Fatalf("a transient lookup failure fell back to the snapshot; deletes = %d", len(api.deleteCalled))}}++// ---- SweepMessage: the restart- and replica-proof half of the lifecycle ----++// The sweep is what clears the badge when the state map has nothing on file:+// it must list the message's Typing reactions from Lark, delete the ones the+// bot itself added, and leave everyone else's alone — a human who reacted with+// the same emoji owns that reaction, and a bot cannot delete it anyway.+func TestTypingIndicatorSweepDeletesOnlyTheBotTypingReactions(t *testing.T) {+ api := &fakeTypingAPIClient{+ listReturn: []MessageReaction{+ {ReactionID: "r-bot", OperatorType: "app", OperatorID: "cli_test", EmojiType: typingEmoji},+ {ReactionID: "r-human", OperatorType: "user", EmojiType: typingEmoji},+ {ReactionID: "r-bot-lower", OperatorType: "app", OperatorID: "cli_test", EmojiType: "typing"},+ {ReactionID: "r-bot-smile", OperatorType: "app", OperatorID: "cli_test", EmojiType: "SMILE"},+ },+ }+ mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, &fakeTypingQueries{}, newDiscardLogger())++ mgr.SweepMessage(context.Background(), InstallationCredentials{AppID: "cli_test"}, "om_trigger")++ if len(api.listCalled) != 1 || api.listCalled[0] != "om_trigger" {+ t.Fatalf("expected one list call for om_trigger, got %v", api.listCalled)+ }+ if len(api.deleteCalled) != 2 {+ t.Fatalf("expected the two bot-authored Typing reactions to be deleted, deletes = %+v", api.deleteCalled)+ }+ deleted := map[string]bool{}+ for _, d := range api.deleteCalled {+ deleted[d.reactionID] = true+ if d.messageID != "om_trigger" {+ t.Errorf("deleted reaction %s from the wrong message %q", d.reactionID, d.messageID)+ }+ }+ if !deleted["r-bot"] || !deleted["r-bot-lower"] {+ t.Errorf("bot-authored Typing reactions survived the sweep: %+v", deleted)+ }+ if deleted["r-human"] || deleted["r-bot-smile"] {+ t.Errorf("the sweep deleted reactions it did not own: %+v", deleted)+ }+}++// A restart or a second replica empties the state map without touching Lark;+// the sweep must clear the badge anyway, because it answers only to Lark.+func TestTypingIndicatorSweepClearsWithoutAnyRecordedState(t *testing.T) {+ api := &fakeTypingAPIClient{+ listReturn: []MessageReaction{+ {ReactionID: "r-from-another-process", OperatorType: "app", OperatorID: "cli_test", EmojiType: typingEmoji},+ },+ }+ mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, &fakeTypingQueries{}, newDiscardLogger())++ // No Add ever ran in this process: the map is empty by construction.+ mgr.SweepMessage(context.Background(), InstallationCredentials{AppID: "cli_test"}, "om_left_behind")++ if len(api.deleteCalled) != 1 || api.deleteCalled[0].reactionID != "r-from-another-process" {+ t.Fatalf("the badge added by another process was not swept: deletes = %+v", api.deleteCalled)+ }+}++// A client that cannot list reactions (the stub, minimal fakes) must skip the+// sweep quietly instead of panicking or firing blind deletes.+func TestTypingIndicatorSweepSkipsWhenClientCannotList(t *testing.T) {+ inner := &fakeTypingAPIClient{}+ api := &noListerClient{APIClient: inner}+ mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, &fakeTypingQueries{}, newDiscardLogger())++ mgr.SweepMessage(context.Background(), InstallationCredentials{AppID: "cli_test"}, "om_trigger")++ if len(inner.listCalled) != 0 || len(inner.deleteCalled) != 0 {+ t.Fatalf("a client without ReactionLister must not be consulted; lists = %d deletes = %d",+ len(inner.listCalled), len(inner.deleteCalled))+ }+}++// A failed list must not turn into deletes of a stale picture of the message.+func TestTypingIndicatorSweepDoesNotDeleteWhenTheListFails(t *testing.T) {+ api := &fakeTypingAPIClient{listErr: errors.New("lark 5xx")}+ mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, &fakeTypingQueries{}, newDiscardLogger())++ mgr.SweepMessage(context.Background(), InstallationCredentials{AppID: "cli_test"}, "om_trigger")++ if len(api.deleteCalled) != 0 {+ t.Fatalf("deleted reactions without a successful list; deletes = %+v", api.deleteCalled)+ }+}++func TestTypingAddRetractsUnverifiedInputWithIndependentContext(t *testing.T) {+ api := &fakeTypingAPIClient{addReturn: "unverified-reaction"}+ queries := &fakeTypingQueries{active: func(ctx context.Context, _ db.IsChannelMessageTypingActiveParams) (bool, error) {+ if ctx.Err() != nil {+ t.Fatalf("lifecycle check inherited expired Add context: %v", ctx.Err())+ }+ return false, errors.New("database unavailable")+ }}+ manager := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, queries, newDiscardLogger())+ ctx, cancel := context.WithCancel(context.Background())+ cancel() // Model a successful response delivered after the caller cancelled.+ session := uuidFromString(t, "ee777777-ee77-ee77-ee77-eeeeeeeeeeee")+ manager.Add(ctx, Installation{AppID: "cli_test", Region: "feishu"}, session, "trigger", "", session)+ if len(api.deleteCalled) != 1 || api.deleteCalled[0].reactionID != "unverified-reaction" || len(manager.states) != 0 {+ t.Fatalf("unverified Add survived: deletes=%+v states=%+v", api.deleteCalled, manager.states)+ }+}diff --git a/server/internal/integrations/lark/typing_lifecycle_db_test.go b/server/internal/integrations/lark/typing_lifecycle_db_test.gonew file mode 100644index 0000000000..25976162c5--- /dev/null+++ b/server/internal/integrations/lark/typing_lifecycle_db_test.go@@ -0,0 +1,140 @@+package lark++import (+ "context"+ "os"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/jackc/pgx/v5/pgxpool"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type typingDBFixture struct {+ *dbfx.Fixture+ runtimeID string+ store *ChannelStore+ inst Installation+ sessionID, messageID, taskID pgtype.UUID+}++func newTypingDBFixture(t *testing.T) *typingDBFixture {+ t.Helper()+ dsn := os.Getenv("DATABASE_URL")+ if dsn == "" {+ t.Skip("DATABASE_URL required for durable typing lifecycle regression")+ }+ pool, err := pgxpool.New(context.Background(), dsn)+ if err != nil {+ t.Fatal(err)+ }+ t.Cleanup(pool.Close)+ fx := dbfx.New(pool, "", "")+ suffix := uuid.NewString()+ fx.UserID = fx.User(t, "Typing tester", "typing-"+suffix+"@multica.test")+ fx.WorkspaceID = fx.Workspace(t, "Typing workspace", "typing-"+suffix)+ runtimeID := fx.Runtime(t, "Typing runtime")+ agentID := fx.Agent(t, "Typing agent", runtimeID)+ instID := fx.Insert(t, "channel_installation", dbfx.Cols{+ "workspace_id": fx.WorkspaceID, "agent_id": agentID, "channel_type": "feishu",+ "installer_user_id": fx.UserID, "config": dbfx.Raw(`'{"app_id":"typing-app-` + suffix + `","region":"feishu"}'::jsonb`),+ })+ sid := fx.ChatSession(t, agentID)+ fx.Insert(t, "channel_chat_session_binding", dbfx.Cols{+ "chat_session_id": sid, "installation_id": instID, "channel_type": "feishu", "channel_chat_id": "typing-room", "chat_type": "group",+ })+ task := fx.Task(t, agentID, dbfx.Cols{"chat_session_id": sid, "status": "running", "runtime_id": runtimeID})+ message := fx.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": sid, "role": "user", "content": "work", "task_id": task, "channel_ingested": true})+ store := NewChannelStore(db.New(pool))+ inst, err := store.GetLarkInstallation(context.Background(), uuidFromString(t, instID))+ if err != nil {+ t.Fatal(err)+ }+ fx.Cleanup(t, "DELETE FROM channel_typing_reaction WHERE workspace_id=$1", fx.WorkspaceID)+ return &typingDBFixture{Fixture: fx, runtimeID: runtimeID, store: store, inst: inst, sessionID: uuidFromString(t, sid), messageID: uuidFromString(t, message), taskID: uuidFromString(t, task)}+}++// FIXME(test-integration): The shared committed input/task relation, including+// debounce and rollback, is the cross-process lifecycle contract.+func TestTypingInputLifecycleDB(t *testing.T) {+ for _, scenario := range []string{"pending debounce", "running", "completed", "failed", "cancelled", "missing task", "deleted input", "deleted session", "archived session", "revoked installation", "foreign workspace", "foreign installation", "foreign task workspace", "foreign task session", "web input", "rollback", "next turn", "coalesced inputs"} {+ t.Run(scenario, func(t *testing.T) {+ f := newTypingDBFixture(t)+ ctx := context.Background()+ arg := db.IsChannelMessageTypingActiveParams{MessageID: f.messageID, ChatSessionID: f.sessionID, WorkspaceID: f.inst.WorkspaceID, InstallationID: f.inst.ID, ChannelType: channelTypeFeishu}+ want := false+ switch scenario {+ case "pending debounce":+ f.Exec(t, "UPDATE chat_message SET task_id=NULL WHERE id=$1", f.messageID)+ want = true+ case "running":+ want = true+ case "completed", "failed", "cancelled":+ f.Exec(t, "UPDATE agent_task_queue SET status=$2 WHERE id=$1", f.taskID, scenario)+ case "missing task":+ f.Exec(t, "DELETE FROM agent_task_queue WHERE id=$1", f.taskID)+ case "deleted input":+ f.Exec(t, "DELETE FROM chat_message WHERE id=$1", f.messageID)+ case "deleted session":+ f.Exec(t, "DELETE FROM chat_session WHERE id=$1", f.sessionID)+ case "archived session":+ f.Exec(t, "UPDATE chat_session SET status='archived' WHERE id=$1", f.sessionID)+ case "revoked installation":+ f.Exec(t, "UPDATE channel_installation SET status='revoked' WHERE id=$1", f.inst.ID)+ case "foreign workspace":+ arg.WorkspaceID = uuidFromString(t, uuid.NewString())+ case "foreign installation":+ arg.InstallationID = uuidFromString(t, uuid.NewString())+ case "foreign task workspace":+ other := f.Workspace(t, "Other", "other-"+uuid.NewString())+ otherAgent := dbfx.New(f.Pool, other, f.UserID).Agent(t, "Other agent", "")+ f.Exec(t, "UPDATE agent_task_queue SET agent_id=$2 WHERE id=$1", f.taskID, otherAgent)+ case "foreign task session":+ other := f.ChatSession(t, uuidString(f.inst.AgentID))+ f.Exec(t, "UPDATE agent_task_queue SET chat_session_id=$2 WHERE id=$1", f.taskID, other)+ case "web input":+ f.Exec(t, "UPDATE chat_message SET channel_ingested=false WHERE id=$1", f.messageID)+ case "rollback":+ tx, err := f.Pool.Begin(ctx)+ if err != nil {+ t.Fatal(err)+ }+ defer tx.Rollback(ctx)+ if _, err = tx.Exec(ctx, "UPDATE agent_task_queue SET status='cancelled' WHERE id=$1", f.taskID); err != nil {+ t.Fatal(err)+ }+ // A separate process must not observe an uncommitted terminal state.+ live, err := f.store.IsChannelMessageTypingActive(ctx, arg)+ if err != nil || !live {+ t.Fatalf("uncommitted cancellation leaked: active=%v err=%v", live, err)+ }+ if err = tx.Rollback(ctx); err != nil {+ t.Fatal(err)+ }+ want = true+ case "next turn":+ f.Exec(t, "UPDATE agent_task_queue SET status='completed' WHERE id=$1", f.taskID)+ nextTask := f.Task(t, uuidString(f.inst.AgentID), dbfx.Cols{"chat_session_id": f.sessionID, "status": "running", "runtime_id": f.runtimeID})+ next := f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": "next", "task_id": nextTask, "channel_ingested": true})+ nextArg := arg+ nextArg.MessageID = uuidFromString(t, next)+ live, err := f.store.IsChannelMessageTypingActive(ctx, nextArg)+ if err != nil || !live {+ t.Fatalf("next input not active: %v %v", live, err)+ }+ case "coalesced inputs":+ // The delivery trigger is only one message in a sealed batch. Every+ // other input must still follow the same terminal task without delivery.+ other := f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": "coalesced", "task_id": f.taskID, "channel_ingested": true})+ arg.MessageID = uuidFromString(t, other)+ f.Exec(t, "UPDATE agent_task_queue SET status='completed' WHERE id=$1", f.taskID)+ }+ active, err := f.store.IsChannelMessageTypingActive(ctx, arg)+ if err != nil || active != want {+ t.Fatalf("active=%v want=%v err=%v", active, want, err)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/typing_lifecycle_regression_test.go b/server/internal/integrations/lark/typing_lifecycle_regression_test.gonew file mode 100644index 0000000000..cbd3c0c636--- /dev/null+++ b/server/internal/integrations/lark/typing_lifecycle_regression_test.go@@ -0,0 +1,175 @@+package lark++import (+ "context"+ "errors"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ "github.com/multica-ai/multica/server/internal/events"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type blockedTypingAdd struct {+ *fakeTypingAPIClient+ started chan struct{}+ release chan struct{}+}++func (a *blockedTypingAdd) AddMessageReaction(ctx context.Context, p AddReactionParams) (string, error) {+ if p.MessageID != "trigger" {+ return a.fakeTypingAPIClient.AddMessageReaction(ctx, p)+ }+ close(a.started)+ <-a.release+ return "late-reaction", nil+}++func (a *blockedTypingAdd) DeleteMessageReaction(ctx context.Context, p DeleteReactionParams) error {+ if err := ctx.Err(); err != nil {+ return err+ }+ return a.fakeTypingAPIClient.DeleteMessageReaction(ctx, p)+}++func TestPatcherTerminalEventDuringTypingAdd(t *testing.T) {+ for _, eventType := range []string{protocol.EventChatDone, protocol.EventTaskFailed, protocol.EventTaskCancelled} {+ t.Run(eventType, func(t *testing.T) {+ p, q, _ := newTestPatcher(t)+ q.taskChannelIngested = true+ q.binding.LastMessageID = pgtype.Text{String: "trigger", Valid: true}+ taskID := uuidFromString(t, "ee777777-ee77-ee77-ee77-eeeeeeeeeeee")+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}+ api := &blockedTypingAdd{fakeTypingAPIClient: &fakeTypingAPIClient{addReturn: "next-reaction"}, started: make(chan struct{}), release: make(chan struct{})}+ mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, &fakeTypingQueries{installation: q.installation}, newDiscardLogger())+ p.SetTypingIndicatorManager(mgr)+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ var release sync.Once+ defer release.Do(func() { close(api.release) })+ done := make(chan struct{})+ go func() {+ defer close(done)+ mgr.Add(ctx, q.installation, q.binding.ChatSessionID, "trigger", "", q.binding.ChatSessionID)+ }()+ select {+ case <-api.started:+ case <-ctx.Done():+ t.Fatal("Add did not start")+ }+ p.handleEvent(events.Event{Type: eventType, TaskID: uuidString(taskID), ChatSessionID: uuidString(q.binding.ChatSessionID), Payload: protocol.ChatDonePayload{Content: "answer"}})+ if len(api.listCalled) != 1 || len(api.deleteCalled) != 0 {+ t.Fatal("terminal event must finish its empty sweep while Add is blocked")+ }+ // A later turn must survive cleanup of the older in-flight generation.+ mgr.Add(ctx, q.installation, q.binding.ChatSessionID, "next-trigger", "", q.binding.ChatSessionID)+ cancel() // Late cleanup must also survive cancellation of the add context.+ release.Do(func() { close(api.release) })+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ t.Fatal("Add did not finish")+ }+ if len(api.deleteCalled) != 1 || api.deleteCalled[0].reactionID != "late-reaction" {+ t.Fatalf("late Add left its badge: %+v", api.deleteCalled)+ }+ states := mgr.states[uuidString(q.binding.ChatSessionID)]+ if len(states) != 1 || states[0].MessageID != "next-trigger" {+ t.Fatalf("late cleanup damaged next turn: %+v", states)+ }+ })+ }+}++type deadlineTypingLister struct {+ *fakeTypingAPIClient+ replies *fakeAPIClient+ t *testing.T+ timedOut bool+}++func (a *deadlineTypingLister) ListMessageReactions(ctx context.Context, _ ListMessageReactionsParams) ([]MessageReaction, error) {+ a.replies.mu.Lock()+ sent := len(a.replies.textSent)+ a.replies.mu.Unlock()+ if sent != 1 {+ a.t.Errorf("slow sweep started before reply delivery: replies=%d", sent)+ }+ <-ctx.Done()+ a.timedOut = errors.Is(ctx.Err(), context.DeadlineExceeded)+ return nil, ctx.Err()+}++func TestPatcherSlowSweepCannotConsumeReplyBudget(t *testing.T) {+ p, q, replies := newTestPatcher(t)+ taskID := uuidFromString(t, "ee777777-ee77-ee77-ee77-eeeeeeeeeeee")+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}+ q.taskChannelIngested = true+ q.binding.LastMessageID = pgtype.Text{String: "trigger", Valid: true}+ api := &deadlineTypingLister{fakeTypingAPIClient: &fakeTypingAPIClient{}, replies: replies, t: t}+ p.SetTypingIndicatorManager(NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, &fakeTypingQueries{installation: q.installation}, newDiscardLogger()))+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)+ defer cancel()+ if err := p.processEvent(ctx, events.Event{Type: protocol.EventChatDone, TaskID: uuidString(taskID), ChatSessionID: uuidString(q.binding.ChatSessionID), Payload: protocol.ChatDonePayload{Content: "answer"}}); err != nil {+ t.Fatal(err)+ }+ if !api.timedOut {+ t.Fatal("list call did not reach its independent deadline")+ }+ if ctx.Err() != nil {+ t.Fatalf("sweep exhausted reply context: %v", ctx.Err())+ }+ if len(replies.textSent) != 1 {+ t.Fatal("reply lost")+ }+}++func TestPatcherClearsTypingBeforeTerminalGates(t *testing.T) {+ for _, eventType := range []string{protocol.EventChatDone, protocol.EventTaskFailed} {+ for _, gate := range []string{"inactive installation", "missing delivery"} {+ t.Run(eventType+"/"+gate, func(t *testing.T) {+ p, q, replies := newTestPatcher(t)+ taskID := uuidFromString(t, "ee777777-ee77-ee77-ee77-eeeeeeeeeeee")+ q.task = db.AgentTaskQueue{ChatInputTaskID: taskID}+ q.taskChannelIngested = true+ api := &fakeTypingAPIClient{addReturn: "held-reaction"}+ mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, &fakeTypingQueries{installation: q.installation}, newDiscardLogger())+ p.SetTypingIndicatorManager(mgr)+ mgr.Add(context.Background(), q.installation, q.binding.ChatSessionID, "trigger", "", q.binding.ChatSessionID)+ if gate == "inactive installation" {+ q.installation.Status = "revoked"+ } else {+ q.deliveryErr = pgx.ErrNoRows+ }+ p.handleEvent(events.Event{Type: eventType, TaskID: uuidString(taskID), ChatSessionID: uuidString(q.binding.ChatSessionID), Payload: protocol.ChatDonePayload{Content: "answer"}})+ if len(api.deleteCalled) != 1 || api.deleteCalled[0].reactionID != "held-reaction" {+ t.Fatalf("badge survived terminal gate: %+v", api.deleteCalled)+ }+ if len(mgr.states) != 0 {+ t.Fatal("terminal state retained")+ }+ if len(replies.textSent)+len(replies.sent)+len(replies.mdCardSent) != 0 {+ t.Fatal("terminal gate unexpectedly sent a reply")+ }+ })+ }+ }+}++func TestPatcherSessionDeleteSweepsCapturedTargetWithoutLocalState(t *testing.T) {+ p, q, replies := newTestPatcher(t)+ q.deliveryErr = pgx.ErrNoRows // Both binding and delivery disappeared at commit.+ api := &fakeTypingAPIClient{listReturn: []MessageReaction{{ReactionID: "remote-reaction", OperatorType: "app", OperatorID: "cli_test_app", EmojiType: typingEmoji}}}+ p.SetTypingIndicatorManager(NewTypingIndicatorManager(api, fakeTypingCreds{secret: "shh"}, &fakeTypingQueries{}, newDiscardLogger()))+ p.handleEvent(events.Event{Type: protocol.EventTaskCancelled, TaskID: "ee777777-ee77-ee77-ee77-eeeeeeeeeeee", ChatSessionID: uuidString(q.binding.ChatSessionID), ChannelReactionTarget: &events.ChannelReactionTarget{ChannelType: channelTypeFeishu, InstallationID: uuidString(q.installation.ID), MessageID: "deleted-session-trigger"}})+ if len(api.deleteCalled) != 1 || api.deleteCalled[0].messageID != "deleted-session-trigger" {+ t.Fatalf("cross-process session delete stranded reaction: %+v", api.deleteCalled)+ }+ if len(replies.textSent)+len(replies.sent) != 0 {+ t.Fatal("cancel sent a reply")+ }+}diff --git a/server/internal/integrations/lark/typing_retention_test.go b/server/internal/integrations/lark/typing_retention_test.gonew file mode 100644index 0000000000..1063e91e9b--- /dev/null+++ b/server/internal/integrations/lark/typing_retention_test.go@@ -0,0 +1,124 @@+package lark++import (+ "context"+ "sync"+ "testing"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// FIXME(test-integration): Recreate the durable state left by a hard crash+// after successful Add but before the in-memory debounce timer creates a task.+func TestTypingTasklessCrashRecoveryDB(t *testing.T) {+ f := newTypingDBFixture(t)+ f.Exec(t, "UPDATE chat_message SET task_id=NULL WHERE id=$1", f.messageID)+ api := &crossProcessReactionAPI{fakeTypingAPIClient: &fakeTypingAPIClient{}, remote: make(map[string][]MessageReaction)}+ first := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ first.Add(context.Background(), f.inst, f.sessionID, "crashed", "", f.messageID)+ f.Exec(t, "UPDATE channel_typing_reaction SET created_at=now()-interval '3 minutes' WHERE chat_message_id=$1", f.messageID)+ next := f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": "next", "channel_ingested": true})+ first.Add(context.Background(), f.inst, f.sessionID, "next", "", uuidFromString(t, next))+ running := f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": "running", "task_id": f.taskID, "channel_ingested": true})+ first.Add(context.Background(), f.inst, f.sessionID, "running", "", uuidFromString(t, running))+ f.Exec(t, "UPDATE channel_typing_reaction SET created_at=now()-interval '3 minutes' WHERE chat_message_id=$1", running)+ // A fresh process has no local states or timers, only the shared database.+ fresh := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ fresh.Reconcile(context.Background(), pgtype.UUID{})+ if len(api.remote["crashed"]) != 0 || len(api.remote["next"]) != 1 || len(api.remote["running"]) != 1 {+ t.Fatalf("wrong cleanup scope: %+v", api.remote)+ }+ var settled bool+ f.QueryRow(t, "SELECT channel_typing_settled FROM chat_message WHERE id=$1", f.messageID).Scan(&settled)+ if settled {+ t.Fatal("visual expiry must not settle or prevent future input processing")+ }+}++// FIXME(test-integration): Cleanup retention is bounded even without source rows,+// a working credential, a successful API call, or a known Add response.+func TestTypingRetentionErasesCredentialsAndStopsRetriesDB(t *testing.T) {+ for _, known := range []bool{false, true} {+ t.Run(map[bool]string{false: "unknown_add", true: "permanent_failure"}[known], func(t *testing.T) {+ f := newTypingDBFixture(t)+ id, ws := uuid.NewString(), uuid.NewString()+ reaction := ""+ if known {+ reaction = "remote-reaction"+ }+ f.Exec(t, `INSERT INTO channel_typing_reaction(id,workspace_id,chat_session_id,chat_message_id,installation_id,channel_message_id,installation_snapshot,reaction_id,add_finished,cleanup_required,created_at,attempts,quota_slot)+ VALUES($1,$2,$3,$4,$5,'deleted','{"app_secret_enc":"synthetic-ciphertext"}',$6,$7,true,now()-interval '8 days',10000,1)`, id, ws, f.sessionID, f.messageID, f.inst.ID, reaction, known)+ f.Cleanup(t, "DELETE FROM channel_typing_reaction WHERE id=$1", id)+ api := &fakeTypingAPIClient{}+ fresh := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ // Eligibility stops at the deadline even if maintenance has not run yet.+ fresh.Reconcile(context.Background(), f.sessionID)+ if len(api.deleteCalled)+len(api.listCalled) != 0 {+ t.Fatal("expired credentials used for remote cleanup")+ }+ fresh.maintainCleanup(context.Background())+ var abandoned, redacted, cleaned bool+ f.QueryRow(t, `SELECT abandoned_at IS NOT NULL,installation_snapshot='{}'::jsonb,cleaned_at IS NOT NULL FROM channel_typing_reaction WHERE id=$1`, id).Scan(&abandoned, &redacted, &cleaned)+ if !abandoned || !redacted || cleaned {+ t.Fatalf("failed cleanup not preserved distinctly: abandoned=%v redacted=%v cleaned=%v", abandoned, redacted, cleaned)+ }+ _, err := f.store.FinishChannelTypingReactionAdd(context.Background(), db.FinishChannelTypingReactionAddParams{ID: uuidFromString(t, id), ReactionID: "late", CleanupRequired: true})+ if err != pgx.ErrNoRows {+ t.Fatalf("late Add resurrected expired ledger: %v", err)+ }+ fresh.Reconcile(context.Background(), f.sessionID)+ if len(api.deleteCalled)+len(api.listCalled) != 0 {+ t.Fatal("abandoned cleanup retried")+ }+ f.Exec(t, "UPDATE channel_typing_reaction SET abandoned_at=now()-interval '8 days' WHERE id=$1", id)+ fresh.maintainCleanup(context.Background())+ var exists bool+ f.QueryRow(t, "SELECT EXISTS(SELECT 1 FROM channel_typing_reaction WHERE id=$1)", id).Scan(&exists)+ if exists {+ t.Fatal("expired non-secret tombstone was not pruned")+ }+ })+ }+}++// FIXME(test-integration): The unique quota index arbitrates concurrent replicas;+// the losing Add is skipped instead of creating an untracked remote reaction.+func TestTypingWorkspaceQuotaConcurrentDB(t *testing.T) {+ f := newTypingDBFixture(t)+ f.Exec(t, `INSERT INTO channel_typing_reaction(id,workspace_id,chat_session_id,chat_message_id,installation_id,channel_message_id,installation_snapshot,quota_slot)+ SELECT gen_random_uuid(),$1,$2,$3,$4,'occupied','{}',slot FROM generate_series(1,999) slot`, f.inst.WorkspaceID, f.sessionID, f.messageID, f.inst.ID)+ api := &crossProcessReactionAPI{fakeTypingAPIClient: &fakeTypingAPIClient{}, remote: make(map[string][]MessageReaction)}+ start := make(chan struct{})+ var wg sync.WaitGroup+ for i := 0; i < 8; i++ {+ wg.Add(1)+ go func() {+ defer wg.Done()+ <-start+ NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger()).Add(context.Background(), f.inst, f.sessionID, uuid.NewString(), "", f.messageID)+ }()+ }+ close(start)+ wg.Wait()+ var pending int+ f.QueryRow(t, "SELECT count(*) FROM channel_typing_reaction WHERE workspace_id=$1 AND cleaned_at IS NULL AND abandoned_at IS NULL", f.inst.WorkspaceID).Scan(&pending)+ if pending != 1000 || len(api.remote) != 1 {+ t.Fatalf("quota bypass: pending=%d remoteAdds=%d", pending, len(api.remote))+ }+ other := newTypingDBFixture(t)+ NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, other.store, newDiscardLogger()).Add(context.Background(), other.inst, other.sessionID, "neighbor", "", other.messageID)+ if len(api.remote["neighbor"]) != 1 {+ t.Fatal("workspace quota affected neighbor")+ }+ f.Exec(t, "UPDATE channel_typing_reaction SET created_at=now()-interval '8 days' WHERE workspace_id=$1", f.inst.WorkspaceID)+ m := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ m.maintainCleanup(context.Background())+ m.Add(context.Background(), f.inst, f.sessionID, "after-expiry", "", f.messageID)+ if len(api.remote["after-expiry"]) != 1 {+ t.Fatal("terminal slots were not released")+ }+}diff --git a/server/internal/integrations/lark/typing_settled_regression_test.go b/server/internal/integrations/lark/typing_settled_regression_test.gonew file mode 100644index 0000000000..98a86a1f3b--- /dev/null+++ b/server/internal/integrations/lark/typing_settled_regression_test.go@@ -0,0 +1,37 @@+package lark++import (+ "context"+ "github.com/multica-ai/multica/server/internal/integrations/channel"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ "testing"+)++// The router's inline failed enqueue invokes OnSettled before Handle launches+// the detached OnIngested. No task exists to supply a later terminal event.+func TestTypingSettledBeforeAddRegistrationDB(t *testing.T) {+ f := newTypingDBFixture(t)+ f.Exec(t, "UPDATE chat_message SET task_id=NULL WHERE id=$1", f.messageID)+ f.Exec(t, "DELETE FROM agent_task_queue WHERE id=$1", f.taskID)+ api := &crossProcessReactionAPI{fakeTypingAPIClient: &fakeTypingAPIClient{}, remote: make(map[string][]MessageReaction)}+ mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "test"}, f.store, newDiscardLogger())+ notifier := &feishuTypingNotifier{mgr: mgr}+ next := f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": "next", "channel_ingested": true})+ cancelled, cancel := context.WithCancel(context.Background())+ cancel()+ notifier.OnSettled(cancelled, f.sessionID, engine.TypingSettlement{WorkspaceID: f.inst.WorkspaceID, InstallationID: f.inst.ID, ThroughMessageID: f.messageID, ContextRevision: 1})+ notifier.OnIngested(context.Background(), engine.ResolvedInstallation{ID: f.inst.ID, WorkspaceID: f.inst.WorkspaceID, Platform: f.inst}, channel.InboundMessage{MessageID: "taskless-input"}, f.sessionID, f.messageID)+ notifier.OnIngested(context.Background(), engine.ResolvedInstallation{ID: f.inst.ID, WorkspaceID: f.inst.WorkspaceID, Platform: f.inst}, channel.InboundMessage{MessageID: "next-input"}, f.sessionID, uuidFromString(t, next))+ if len(api.remote["next-input"]) != 1 {+ t.Fatal("settling previous input removed next debounce input")+ }+ var tasks int+ f.QueryRow(t, "SELECT count(*) FROM agent_task_queue WHERE chat_session_id=$1", f.sessionID).Scan(&tasks)+ if tasks != 0 {+ t.Fatalf("taskless settlement unexpectedly created %d tasks", tasks)+ }+ if len(api.remote["taskless-input"]) != 0 {+ t.Fatalf("settled input without a task retained reaction: %+v", api.remote)+ }+}diff --git a/server/internal/integrations/lark/typing_sweep_ownership_test.go b/server/internal/integrations/lark/typing_sweep_ownership_test.gonew file mode 100644index 0000000000..1b7de52c6d--- /dev/null+++ b/server/internal/integrations/lark/typing_sweep_ownership_test.go@@ -0,0 +1,31 @@+package lark++import (+ "context"+ "testing"+)++func TestTypingSweepsPreserveForeignAppAndHuman(t *testing.T) {+ for _, durable := range []bool{false, true} {+ t.Run(map[bool]string{false: "fallback", true: "durable"}[durable], func(t *testing.T) {+ api := &fakeTypingAPIClient{listReturn: []MessageReaction{+ {ReactionID: "ours", OperatorType: "app", OperatorID: "cli_ours", EmojiType: typingEmoji},+ {ReactionID: "foreign", OperatorType: "app", OperatorID: "cli_other", EmojiType: typingEmoji},+ {ReactionID: "unknown", OperatorType: "app", EmojiType: typingEmoji},+ {ReactionID: "human", OperatorType: "user", OperatorID: "ou_user", EmojiType: typingEmoji},+ }}+ m := NewTypingIndicatorManager(api, fakeTypingCreds{}, &fakeTypingQueries{}, newDiscardLogger())+ creds := InstallationCredentials{AppID: "cli_ours"}+ if durable {+ if err := m.sweepForCleanup(context.Background(), creds, "message"); err != nil {+ t.Fatal(err)+ }+ } else {+ m.SweepMessage(context.Background(), creds, "message")+ }+ if len(api.deleteCalled) != 1 || api.deleteCalled[0].reactionID != "ours" {+ t.Fatalf("foreign reaction targeted: %+v", api.deleteCalled)+ }+ })+ }+}diff --git a/server/internal/integrations/lark/typing_withdrawal_regression_test.go b/server/internal/integrations/lark/typing_withdrawal_regression_test.gonew file mode 100644index 0000000000..b8a25c72f0--- /dev/null+++ b/server/internal/integrations/lark/typing_withdrawal_regression_test.go@@ -0,0 +1,105 @@+package lark++import (+ "context"+ "errors"+ "sync"+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+ dbfx "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++type qaR2CheckQueries struct {+ *ChannelStore+ oldID pgtype.UUID+ fail bool+ t *testing.T+}++func (q *qaR2CheckQueries) IsChannelMessageTypingActive(ctx context.Context, p db.IsChannelMessageTypingActiveParams) (bool, error) {+ if p.MessageID == q.oldID {+ deadline, ok := ctx.Deadline()+ if ctx.Err() != nil || !ok || time.Until(deadline) > typingCleanupTimeout {+ q.t.Errorf("lifecycle check lacks independent bounded context")+ }+ if q.fail {+ return true, errors.New("QA database check unavailable")+ }+ }+ return q.ChannelStore.IsChannelMessageTypingActive(ctx, p)+}++type qaR2DeleteBarrier struct {+ *crossProcessReactionAPI+ started, release chan struct{}+ t *testing.T+}++func (a *qaR2DeleteBarrier) DeleteMessageReaction(ctx context.Context, p DeleteReactionParams) error {+ if p.MessageID == "checked-trigger" {+ deadline, ok := ctx.Deadline()+ if ctx.Err() != nil || !ok || time.Until(deadline) > typingCleanupTimeout {+ a.t.Errorf("reaction withdrawal lacks independent bounded context")+ }+ close(a.started)+ select {+ case <-a.release:+ case <-ctx.Done():+ return ctx.Err()+ }+ }+ return a.crossProcessReactionAPI.DeleteMessageReaction(ctx, p)+}++func TestQAR2WithdrawalPreservesNextDebounceInput(t *testing.T) {+ for _, failure := range []bool{false, true} {+ name := "committed_terminal"+ if failure {+ name = "database_check_error"+ }+ t.Run(name, func(t *testing.T) {+ f := newTypingDBFixture(t)+ if !failure {+ f.Exec(t, "UPDATE agent_task_queue SET status='completed' WHERE id=$1", f.taskID)+ }+ next := f.Insert(t, "chat_message", dbfx.Cols{"chat_session_id": f.sessionID, "role": "user", "content": "next debounce input", "channel_ingested": true})+ api := &qaR2DeleteBarrier{crossProcessReactionAPI: &crossProcessReactionAPI{fakeTypingAPIClient: &fakeTypingAPIClient{}, remote: map[string][]MessageReaction{"checked-trigger": {{ReactionID: "human-typing", OperatorType: "user", EmojiType: typingEmoji}}}}, started: make(chan struct{}), release: make(chan struct{}), t: t}+ queries := &qaR2CheckQueries{ChannelStore: f.store, oldID: f.messageID, fail: failure, t: t}+ mgr := NewTypingIndicatorManager(api, fakeTypingCreds{secret: "fixture"}, queries, newDiscardLogger())+ var once sync.Once+ defer once.Do(func() { close(api.release) })+ done := make(chan struct{})+ ctx, cancel := context.WithCancel(context.Background())+ cancel() // HTTP fake models a successful Add delivered after caller cancellation.+ go func() { defer close(done); mgr.Add(ctx, f.inst, f.sessionID, "checked-trigger", "", f.messageID) }()+ select {+ case <-api.started:+ case <-time.After(5 * time.Second):+ t.Fatal("old reaction withdrawal did not start")+ }+ mgr.Add(context.Background(), f.inst, f.sessionID, "next-trigger", "", uuidFromString(t, next))+ once.Do(func() { close(api.release) })+ select {+ case <-done:+ case <-time.After(5 * time.Second):+ t.Fatal("old withdrawal did not finish")+ }+ api.mu.Lock()+ defer api.mu.Unlock()+ if old := api.remote["checked-trigger"]; len(old) != 1 || old[0].ReactionID != "human-typing" {+ t.Fatalf("old reaction or human reaction incorrect: %+v", old)+ }+ states := mgr.states[uuidString(f.sessionID)]+ if len(api.remote["next-trigger"]) != 1 || len(states) != 1 || states[0].MessageID != "next-trigger" {+ t.Fatalf("next debounce input lost: remote=%+v states=%+v", api.remote, states)+ }+ if api.deletes != 1 {+ t.Fatalf("withdrawals=%d want 1", api.deletes)+ }+ t.Log("old app reaction removed; human Typing and next taskless input reaction/state retained; query and withdrawal independent of cancelled Add context")+ })+ }+}diff --git a/server/internal/integrations/slack/resolvers.go b/server/internal/integrations/slack/resolvers.goindex d47d7ae087..b7caaf02db 100644--- a/server/internal/integrations/slack/resolvers.go+++ b/server/internal/integrations/slack/resolvers.go@@ -413,7 +413,7 @@ type slackTypingNotifier struct{ mgr *TypingIndicatorManager }// the bot is processing it. The resolved installation carries the bot token in// its Config blob — the InstallationResolver stashed the db.ChannelInstallation// row in Platform, the documented adapter boundary the core never reads.-func (n *slackTypingNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID) {+func (n *slackTypingNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID, chatMessageID pgtype.UUID) {ci, ok := inst.Platform.(db.ChannelInstallation)if !ok {return@@ -424,6 +424,6 @@ func (n *slackTypingNotifier) OnIngested(ctx context.Context, inst engine.Resolv// OnSettled clears the reaction when the run trigger enqueued no task (agent// offline / archived, or an enqueue failure) — the bus-driven clear on// chat-done / task-failed never fires for those, so without this the 👀 sticks.-func (n *slackTypingNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID) {+func (n *slackTypingNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID, scope engine.TypingSettlement) {n.mgr.Clear(ctx, sessionID)}diff --git a/server/internal/integrations/slack/typing_indicator_test.go b/server/internal/integrations/slack/typing_indicator_test.goindex 9dda7988ea..b4dcaf7e67 100644--- a/server/internal/integrations/slack/typing_indicator_test.go+++ b/server/internal/integrations/slack/typing_indicator_test.go@@ -4,6 +4,7 @@ import ("context""errors""fmt"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine""testing""time"@@ -152,7 +153,7 @@ func TestSlackTypingNotifier_OnSettledClears(t *testing.T) {m := newTestTyping(q, fr)m.Add(context.Background(), db.ChannelInstallation{ID: uid(1), Config: slackInstallConfigJSON()}, sessionID, "C1", freshTS())- (&slackTypingNotifier{mgr: m}).OnSettled(context.Background(), sessionID)+ (&slackTypingNotifier{mgr: m}).OnSettled(context.Background(), sessionID, engine.TypingSettlement{})if len(fr.removed) != 1 || fr.removed[0].Channel != "C1" {t.Fatalf("OnSettled must clear the reaction, removed = %+v", fr.removed)}diff --git a/server/internal/integrations/telegram/resolvers.go b/server/internal/integrations/telegram/resolvers.goindex 9a05d100d4..5daa707bbc 100644--- a/server/internal/integrations/telegram/resolvers.go+++ b/server/internal/integrations/telegram/resolvers.go@@ -318,7 +318,7 @@ func NewTypingNotifier(decrypt Decrypter, apiBase string, client *http.Client, lreturn &typingNotifier{decrypt: decrypt, apiBase: apiBase, client: client, logger: logger}}-func (n *typingNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID) {+func (n *typingNotifier) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID, chatMessageID pgtype.UUID) {row, ok := inst.Platform.(db.ChannelInstallation)if !ok {return@@ -341,4 +341,5 @@ func (n *typingNotifier) OnIngested(ctx context.Context, inst engine.ResolvedIns}}-func (n *typingNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID) {}+func (n *typingNotifier) OnSettled(ctx context.Context, sessionID pgtype.UUID, scope engine.TypingSettlement) {+}diff --git a/server/internal/integrations/wecom/stream_bubble_db_test.go b/server/internal/integrations/wecom/stream_bubble_db_test.goindex 8d822e8d8f..f5817e5ced 100644--- a/server/internal/integrations/wecom/stream_bubble_db_test.go+++ b/server/internal/integrations/wecom/stream_bubble_db_test.go@@ -78,7 +78,7 @@ func (r *bubbleReplica) asked(t *testing.T, turn boundTurn, reqID string) {Source: channel.Source{ChannelType: TypeWecom, ChatID: turn.chatID, ChatType: channel.ChatTypeP2P, SenderID: "USER_1"},Raw: raw,},- sessionID)+ sessionID, sessionID)r.bus.Publish(events.Event{Type: protocol.EventTaskQueued,ChatSessionID: turn.sessionID,diff --git a/server/internal/integrations/wecom/stream_bubble_test.go b/server/internal/integrations/wecom/stream_bubble_test.goindex 5839ce2db1..6502e72071 100644--- a/server/internal/integrations/wecom/stream_bubble_test.go+++ b/server/internal/integrations/wecom/stream_bubble_test.go@@ -319,7 +319,7 @@ func (r *bubbleRig) ask(t *testing.T, reqID string) {Source: channel.Source{ChannelType: TypeWecom, ChatID: "CHAT_1", ChatType: channel.ChatTypeP2P, SenderID: "USER_1"},Raw: raw,},- bubbleSessionID(t))+ bubbleSessionID(t), bubbleSessionID(t))}// reconnect swaps the installation's live socket the way the Supervisor doesdiff --git a/server/internal/integrations/wecom/stream_round_identity_test.go b/server/internal/integrations/wecom/stream_round_identity_test.goindex ddc0d76729..63a77ba146 100644--- a/server/internal/integrations/wecom/stream_round_identity_test.go+++ b/server/internal/integrations/wecom/stream_round_identity_test.go@@ -13,6 +13,7 @@ package wecomimport ("context"+ "github.com/multica-ai/multica/server/internal/integrations/channel/engine""testing""time")@@ -187,7 +188,7 @@ func TestAFlushThatStartedNoRunClosesTheBubbleWithNoRun(t *testing.T) {rig.ran(t, "REQ-S1", "task-1") // running, boundrig.ask(t, "REQ-S2") // the flush that found no runtime- rig.typing.OnSettled(context.Background(), sessionID)+ rig.typing.OnSettled(context.Background(), sessionID, engine.TypingSettlement{})frames := rig.conn.streamFrames(t)if len(frames) != 3 {@@ -213,7 +214,7 @@ func TestASettledFlushLeavesARoundWaitingForItsRetry(t *testing.T) {rig.ran(t, "REQ-RETRY-SETTLE", "task-1")rig.failed(t, "task-1", true) // the attempt is being retried; the round waits- rig.typing.OnSettled(context.Background(), bubbleSessionID(t))+ rig.typing.OnSettled(context.Background(), bubbleSessionID(t), engine.TypingSettlement{})if got := len(rig.conn.streamFrames(t)); got != 1 {t.Fatalf("got %d stream frames, want 1 (the opening one) — a settled flush closed the "+diff --git a/server/internal/integrations/wecom/typing_indicator.go b/server/internal/integrations/wecom/typing_indicator.goindex a1846ef1e5..7a33bf1738 100644--- a/server/internal/integrations/wecom/typing_indicator.go+++ b/server/internal/integrations/wecom/typing_indicator.go@@ -185,7 +185,7 @@ func NewTypingIndicator(cfg TypingIndicatorConfig) *TypingIndicatorManager {// nothing here needs to be quick for the ACK's sake — but everything here is// best-effort: a bubble that fails to open costs the user a few seconds of// uncertainty, and the answer still arrives as a plain message.-func (m *TypingIndicatorManager) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID) {+func (m *TypingIndicatorManager) OnIngested(ctx context.Context, inst engine.ResolvedInstallation, msg channel.InboundMessage, sessionID pgtype.UUID, chatMessageID pgtype.UUID) {if m.senders == nil || m.streams == nil || !sessionID.Valid {return}@@ -294,7 +294,7 @@ func (m *TypingIndicatorManager) OnIngested(ctx context.Context, inst engine.Res//// No bubble, nothing to say: the replier's notice is the whole of what the// user is told, and there is no round left to address a second line to.-func (m *TypingIndicatorManager) OnSettled(ctx context.Context, sessionID pgtype.UUID) {+func (m *TypingIndicatorManager) OnSettled(ctx context.Context, sessionID pgtype.UUID, scope engine.TypingSettlement) {if m.senders == nil || m.streams == nil || !sessionID.Valid {return}diff --git a/server/internal/service/channel_reaction_target.go b/server/internal/service/channel_reaction_target.gonew file mode 100644index 0000000000..0cf9dfac72--- /dev/null+++ b/server/internal/service/channel_reaction_target.go@@ -0,0 +1,40 @@+package service++import (+ "context"+ "errors"+ "fmt"++ "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/util"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+)++// CaptureChannelReactionTargets runs in the cancellation transaction, before+// deleting bindings and delivery rows. Pass its result to BroadcastCancelledTasks+// after commit, so a different process can clean up without any Add state.+func CaptureChannelReactionTargets(ctx context.Context, q interface {+ GetChannelTaskDelivery(context.Context, pgtype.UUID) (db.ChannelTaskDelivery, error)+}, tasks []db.AgentTaskQueue) (map[string]*events.ChannelReactionTarget, error) {+ targets := make(map[string]*events.ChannelReactionTarget)+ for _, task := range tasks {+ delivery, err := q.GetChannelTaskDelivery(ctx, task.ID)+ if errors.Is(err, pgx.ErrNoRows) {+ continue+ }+ if err != nil {+ return nil, fmt.Errorf("capture channel reaction target: %w", err)+ }+ if !delivery.ChannelMessageID.Valid || delivery.ChannelMessageID.String == "" {+ continue+ }+ targets[util.UUIDToString(task.ID)] = &events.ChannelReactionTarget{+ ChannelType: delivery.ChannelType,+ InstallationID: util.UUIDToString(delivery.InstallationID),+ MessageID: delivery.ChannelMessageID.String,+ }+ }+ return targets, nil+}diff --git a/server/internal/service/task.go b/server/internal/service/task.goindex 0f890d5e6c..1d4e5c6bc2 100644--- a/server/internal/service/task.go+++ b/server/internal/service/task.go@@ -2743,11 +2743,20 @@ func (s *TaskService) CancelTasksByTriggerComment(ctx context.Context, commentID// showing a run that no longer exists. Each caller already knows the workspace// — it is the one whose session, member or runtime is being torn down — so the// lookup is not needed and cannot fail.-func (s *TaskService) BroadcastCancelledTasks(ctx context.Context, workspaceID string, cancelled []db.AgentTaskQueue) {+//+// reactionTargets optionally carries anchors captured before deleting the+// channel delivery rows. They stay on the internal event, outside its payload.+func (s *TaskService) BroadcastCancelledTasks(ctx context.Context, workspaceID string, cancelled []db.AgentTaskQueue, reactionTargets ...map[string]*events.ChannelReactionTarget) {for _, t := range cancelled {s.captureTaskCancelled(ctx, t)s.ReconcileAgentStatus(ctx, t.AgentID)- s.publishTaskEvent(protocol.EventTaskCancelled, workspaceID, t)+ if workspaceID != "" {+ e := taskEvent(protocol.EventTaskCancelled, workspaceID, t)+ if len(reactionTargets) > 0 {+ e.ChannelReactionTarget = reactionTargets[0][util.UUIDToString(t.ID)]+ }+ s.Bus.Publish(e)+ }}s.notifyTasksFinished(cancelled)}diff --git a/server/migrations/565_channel_typing_cleanup.down.sql b/server/migrations/565_channel_typing_cleanup.down.sqlnew file mode 100644index 0000000000..96b342575b--- /dev/null+++ b/server/migrations/565_channel_typing_cleanup.down.sql@@ -0,0 +1,2 @@+DROP TABLE IF EXISTS channel_typing_reaction;+ALTER TABLE chat_message DROP COLUMN IF EXISTS channel_typing_settled;diff --git a/server/migrations/565_channel_typing_cleanup.up.sql b/server/migrations/565_channel_typing_cleanup.up.sqlnew file mode 100644index 0000000000..6ab139bf1a--- /dev/null+++ b/server/migrations/565_channel_typing_cleanup.up.sql@@ -0,0 +1,21 @@+-- Durable per-input settlement survives an OnSettled callback before Add starts.+ALTER TABLE chat_message ADD COLUMN IF NOT EXISTS channel_typing_settled boolean NOT NULL DEFAULT false;++-- No foreign keys: cleanup anchors must survive session, task and installation+-- deletion. The snapshot contains encrypted installation credentials only.+CREATE TABLE IF NOT EXISTS channel_typing_reaction (+ id uuid NOT NULL,+ workspace_id uuid NOT NULL,+ chat_session_id uuid NOT NULL,+ chat_message_id uuid NOT NULL,+ installation_id uuid NOT NULL,+ channel_message_id text NOT NULL,+ installation_snapshot jsonb NOT NULL,+ reaction_id text NOT NULL DEFAULT '',+ add_finished boolean NOT NULL DEFAULT false,+ cleanup_required boolean NOT NULL DEFAULT false,+ cleaned_at timestamptz,+ retry_after timestamptz NOT NULL DEFAULT now(),+ attempts integer NOT NULL DEFAULT 0,+ created_at timestamptz NOT NULL DEFAULT now()+);diff --git a/server/migrations/566_channel_typing_reaction_id_idx.down.sql b/server/migrations/566_channel_typing_reaction_id_idx.down.sqlnew file mode 100644index 0000000000..6805fe1656--- /dev/null+++ b/server/migrations/566_channel_typing_reaction_id_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS channel_typing_reaction_id_idx;diff --git a/server/migrations/566_channel_typing_reaction_id_idx.up.sql b/server/migrations/566_channel_typing_reaction_id_idx.up.sqlnew file mode 100644index 0000000000..51c9e4beed--- /dev/null+++ b/server/migrations/566_channel_typing_reaction_id_idx.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS channel_typing_reaction_id_idx ON channel_typing_reaction (id);diff --git a/server/migrations/567_channel_typing_reaction_retry_idx.down.sql b/server/migrations/567_channel_typing_reaction_retry_idx.down.sqlnew file mode 100644index 0000000000..f88b5f4528--- /dev/null+++ b/server/migrations/567_channel_typing_reaction_retry_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS channel_typing_reaction_retry_idx;diff --git a/server/migrations/567_channel_typing_reaction_retry_idx.up.sql b/server/migrations/567_channel_typing_reaction_retry_idx.up.sqlnew file mode 100644index 0000000000..48e2a82180--- /dev/null+++ b/server/migrations/567_channel_typing_reaction_retry_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS channel_typing_reaction_retry_idx ON channel_typing_reaction (retry_after, chat_session_id) WHERE cleaned_at IS NULL;diff --git a/server/migrations/568_channel_typing_reaction_gc_idx.down.sql b/server/migrations/568_channel_typing_reaction_gc_idx.down.sqlnew file mode 100644index 0000000000..235a935d28--- /dev/null+++ b/server/migrations/568_channel_typing_reaction_gc_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS channel_typing_reaction_gc_idx;diff --git a/server/migrations/568_channel_typing_reaction_gc_idx.up.sql b/server/migrations/568_channel_typing_reaction_gc_idx.up.sqlnew file mode 100644index 0000000000..ec77fbac4f--- /dev/null+++ b/server/migrations/568_channel_typing_reaction_gc_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS channel_typing_reaction_gc_idx ON channel_typing_reaction (cleaned_at) WHERE cleaned_at IS NOT NULL;diff --git a/server/migrations/569_channel_typing_limits.down.sql b/server/migrations/569_channel_typing_limits.down.sqlnew file mode 100644index 0000000000..b179ea1104--- /dev/null+++ b/server/migrations/569_channel_typing_limits.down.sql@@ -0,0 +1,2 @@+ALTER TABLE channel_typing_reaction DROP COLUMN IF EXISTS quota_slot;+ALTER TABLE channel_typing_reaction DROP COLUMN IF EXISTS abandoned_at;diff --git a/server/migrations/569_channel_typing_limits.up.sql b/server/migrations/569_channel_typing_limits.up.sqlnew file mode 100644index 0000000000..44a21cdc58--- /dev/null+++ b/server/migrations/569_channel_typing_limits.up.sql@@ -0,0 +1,18 @@+ALTER TABLE channel_typing_reaction ADD COLUMN IF NOT EXISTS abandoned_at timestamptz;+ALTER TABLE channel_typing_reaction ADD COLUMN IF NOT EXISTS quota_slot integer;++-- Give existing pending rows a bounded share of each workspace's quota.+-- Excess rows become explicit failed outcomes; never retain their credentials.+WITH ranked AS (+ SELECT id, row_number() OVER (PARTITION BY workspace_id ORDER BY created_at DESC, id) AS slot+ FROM channel_typing_reaction WHERE cleaned_at IS NULL AND abandoned_at IS NULL+)+UPDATE channel_typing_reaction r SET+ quota_slot = CASE WHEN ranked.slot <= 1000 THEN ranked.slot::integer END,+ abandoned_at = CASE WHEN ranked.slot > 1000 THEN now() END,+ cleanup_required = cleanup_required OR ranked.slot > 1000,+ installation_snapshot = CASE WHEN ranked.slot > 1000 THEN '{}'::jsonb ELSE installation_snapshot END+FROM ranked WHERE r.id = ranked.id;++UPDATE channel_typing_reaction SET installation_snapshot = '{}'::jsonb+WHERE cleaned_at IS NOT NULL;diff --git a/server/migrations/570_channel_typing_quota_idx.down.sql b/server/migrations/570_channel_typing_quota_idx.down.sqlnew file mode 100644index 0000000000..c8dbcfbcfc--- /dev/null+++ b/server/migrations/570_channel_typing_quota_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS channel_typing_reaction_quota_idx;diff --git a/server/migrations/570_channel_typing_quota_idx.up.sql b/server/migrations/570_channel_typing_quota_idx.up.sqlnew file mode 100644index 0000000000..c176ff4a0e--- /dev/null+++ b/server/migrations/570_channel_typing_quota_idx.up.sql@@ -0,0 +1 @@+CREATE UNIQUE INDEX CONCURRENTLY IF NOT EXISTS channel_typing_reaction_quota_idx ON channel_typing_reaction (workspace_id, quota_slot) WHERE cleaned_at IS NULL AND abandoned_at IS NULL;diff --git a/server/migrations/571_channel_typing_expiry_idx.down.sql b/server/migrations/571_channel_typing_expiry_idx.down.sqlnew file mode 100644index 0000000000..63c1298bdc--- /dev/null+++ b/server/migrations/571_channel_typing_expiry_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS channel_typing_reaction_expiry_idx;diff --git a/server/migrations/571_channel_typing_expiry_idx.up.sql b/server/migrations/571_channel_typing_expiry_idx.up.sqlnew file mode 100644index 0000000000..63d489de3f--- /dev/null+++ b/server/migrations/571_channel_typing_expiry_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS channel_typing_reaction_expiry_idx ON channel_typing_reaction (created_at, id) WHERE cleaned_at IS NULL AND abandoned_at IS NULL;diff --git a/server/migrations/572_channel_typing_abandoned_idx.down.sql b/server/migrations/572_channel_typing_abandoned_idx.down.sqlnew file mode 100644index 0000000000..a521fff482--- /dev/null+++ b/server/migrations/572_channel_typing_abandoned_idx.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS channel_typing_reaction_abandoned_idx;diff --git a/server/migrations/572_channel_typing_abandoned_idx.up.sql b/server/migrations/572_channel_typing_abandoned_idx.up.sqlnew file mode 100644index 0000000000..64edc5fee3--- /dev/null+++ b/server/migrations/572_channel_typing_abandoned_idx.up.sql@@ -0,0 +1 @@+CREATE INDEX CONCURRENTLY IF NOT EXISTS channel_typing_reaction_abandoned_idx ON channel_typing_reaction (abandoned_at) WHERE abandoned_at IS NOT NULL;diff --git a/server/pkg/db/generated/channel.sql.go b/server/pkg/db/generated/channel.sql.goindex df7204eb65..00f9b4c356 100644--- a/server/pkg/db/generated/channel.sql.go+++ b/server/pkg/db/generated/channel.sql.go@@ -1987,6 +1987,59 @@ func (q *Queries) GetChannelUserBindingByUserID(ctx context.Context, arg GetChanreturn i, err}+const isChannelMessageTypingActive = `-- name: IsChannelMessageTypingActive :one+SELECT EXISTS (+ SELECT 1 FROM chat_message AS message+ JOIN chat_session AS session ON session.id = message.chat_session_id+ JOIN channel_chat_session_binding AS binding ON binding.chat_session_id = session.id+ JOIN channel_installation AS installation ON installation.id = binding.installation_id+ LEFT JOIN agent_task_queue AS task ON task.id = message.task_id+ LEFT JOIN agent AS task_agent ON task_agent.id = task.agent_id+ WHERE message.id = $1+ AND session.id = $2+ AND session.workspace_id = $3+ AND installation.workspace_id = $3+ AND installation.id = $4+ AND installation.channel_type = $5+ AND binding.channel_type = $5+ AND installation.status = 'active'+ AND session.status = 'active'+ AND binding.retired_at IS NULL+ AND message.role = 'user'+ AND message.channel_ingested+ AND NOT message.channel_typing_settled+ AND (message.task_id IS NULL OR (+ task_agent.workspace_id = $3+ AND task.chat_session_id = session.id+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ ))+)+`++type IsChannelMessageTypingActiveParams struct {+ MessageID pgtype.UUID `json:"message_id"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ ChannelType string `json:"channel_type"`+}++// Revalidate the exact input after a remote reaction Add. A pending debounce+// input has no task yet; a sealed input follows its immutable owning task.+// Do not use the binding's latest message or another turn's active task.+func (q *Queries) IsChannelMessageTypingActive(ctx context.Context, arg IsChannelMessageTypingActiveParams) (bool, error) {+ row := q.db.QueryRow(ctx, isChannelMessageTypingActive,+ arg.MessageID,+ arg.ChatSessionID,+ arg.WorkspaceID,+ arg.InstallationID,+ arg.ChannelType,+ )+ var exists bool+ err := row.Scan(&exists)+ return exists, err+}+const listActiveChannelInstallations = `-- name: ListActiveChannelInstallations :manySELECT ci.id, ci.workspace_id, ci.agent_id, ci.channel_type, ci.config, ci.status, ci.ws_lease_token, ci.ws_lease_expires_at, ci.installer_user_id, ci.installed_at, ci.created_at, ci.updated_at FROM channel_installation ciJOIN workspace w ON w.id = ci.workspace_iddiff --git a/server/pkg/db/generated/channel_typing.sql.go b/server/pkg/db/generated/channel_typing.sql.gonew file mode 100644index 0000000000..95f3d0b99d--- /dev/null+++ b/server/pkg/db/generated/channel_typing.sql.go@@ -0,0 +1,338 @@+// Code generated by sqlc. DO NOT EDIT.+// versions:+// sqlc v1.31.1+// source: channel_typing.sql++package db++import (+ "context"++ "github.com/jackc/pgx/v5/pgtype"+)++const acknowledgeChannelTypingReactionCleanup = `-- name: AcknowledgeChannelTypingReactionCleanup :exec+UPDATE channel_typing_reaction+SET cleaned_at = CASE WHEN add_finished AND reaction_id <> '' THEN now() ELSE NULL END,+ retry_after = GREATEST(retry_after, now() + interval '30 seconds'),+ installation_snapshot = CASE WHEN add_finished AND reaction_id <> '' THEN '{}'::jsonb ELSE installation_snapshot END+WHERE id = $1 AND reaction_id = $2 AND cleanup_required AND abandoned_at IS NULL+`++type AcknowledgeChannelTypingReactionCleanupParams struct {+ ID pgtype.UUID `json:"id"`+ ReactionID string `json:"reaction_id"`+}++// An unfinished Add may still create a reaction after an empty sweep. Retain+// its anchor; only a known successful Add response can close cleanup forever.+func (q *Queries) AcknowledgeChannelTypingReactionCleanup(ctx context.Context, arg AcknowledgeChannelTypingReactionCleanupParams) error {+ _, err := q.db.Exec(ctx, acknowledgeChannelTypingReactionCleanup, arg.ID, arg.ReactionID)+ return err+}++const claimChannelTypingReactionCleanup = `-- name: ClaimChannelTypingReactionCleanup :many+WITH candidates AS (+ SELECT r.id FROM channel_typing_reaction r+ WHERE r.cleaned_at IS NULL AND r.abandoned_at IS NULL AND r.retry_after <= now()+ AND r.created_at > now() - interval '7 days'+ AND ($1::uuid IS NULL OR r.chat_session_id = $1)+ AND (r.cleanup_required OR (NOT r.add_finished AND r.created_at < now() - interval '1 minute') OR NOT EXISTS (+ SELECT 1 FROM chat_message m+ JOIN chat_session s ON s.id = m.chat_session_id+ JOIN channel_installation i ON i.id = r.installation_id+ JOIN channel_chat_session_binding b ON b.chat_session_id = s.id AND b.installation_id = i.id+ LEFT JOIN agent_task_queue t ON t.id = m.task_id+ LEFT JOIN agent a ON a.id = t.agent_id+ WHERE m.id = r.chat_message_id AND s.id = r.chat_session_id+ AND s.workspace_id = r.workspace_id AND i.workspace_id = r.workspace_id+ AND i.channel_type = 'feishu' AND b.channel_type = 'feishu'+ AND s.status = 'active' AND i.status = 'active' AND b.retired_at IS NULL+ AND m.channel_ingested AND m.role = 'user' AND NOT m.channel_typing_settled+ -- A taskless badge has a bounded visual lifetime even if a crashed+ -- debouncer never flushes. Do not settle the input or cancel a future run.+ AND ((m.task_id IS NULL AND r.created_at > now() - interval '2 minutes') OR (t.chat_session_id = s.id AND a.workspace_id = r.workspace_id+ AND t.status IN ('queued','dispatched','running','waiting_local_directory','deferred')))+ ))+ ORDER BY r.retry_after, r.id LIMIT 100+ FOR UPDATE OF r SKIP LOCKED+)+UPDATE channel_typing_reaction r SET cleanup_required = true,+ attempts = attempts + 1,+ retry_after = now() + LEAST(3600, 30 * power(2, LEAST(r.attempts, 7))) * interval '1 second'+FROM candidates c WHERE r.id = c.id RETURNING r.id, r.workspace_id, r.chat_session_id, r.chat_message_id, r.installation_id, r.channel_message_id, r.installation_snapshot, r.reaction_id, r.add_finished, r.cleanup_required, r.cleaned_at, r.retry_after, r.attempts, r.created_at, r.abandoned_at, r.quota_slot+`++// The DB is the shared source of eligibility. Missing source rows after a+// committed deletion are terminal too. No transaction takes remote I/O locks.+func (q *Queries) ClaimChannelTypingReactionCleanup(ctx context.Context, chatSessionID pgtype.UUID) ([]ChannelTypingReaction, error) {+ rows, err := q.db.Query(ctx, claimChannelTypingReactionCleanup, chatSessionID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ChannelTypingReaction{}+ for rows.Next() {+ var i ChannelTypingReaction+ if err := rows.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ChatSessionID,+ &i.ChatMessageID,+ &i.InstallationID,+ &i.ChannelMessageID,+ &i.InstallationSnapshot,+ &i.ReactionID,+ &i.AddFinished,+ &i.CleanupRequired,+ &i.CleanedAt,+ &i.RetryAfter,+ &i.Attempts,+ &i.CreatedAt,+ &i.AbandonedAt,+ &i.QuotaSlot,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const expireChannelTypingReactionCleanup = `-- name: ExpireChannelTypingReactionCleanup :many+WITH candidates AS (+ SELECT id FROM channel_typing_reaction+ WHERE cleaned_at IS NULL AND abandoned_at IS NULL AND created_at <= now() - interval '7 days'+ ORDER BY created_at, id LIMIT 1000 FOR UPDATE SKIP LOCKED+)+UPDATE channel_typing_reaction r SET abandoned_at = now(), cleanup_required = true,+ installation_snapshot = '{}'::jsonb+FROM candidates c WHERE r.id = c.id+RETURNING r.id, r.workspace_id+`++type ExpireChannelTypingReactionCleanupRow struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+}++// Independent maintenance, including active/uncertain Adds: the cosmetic badge+// has a seven-day maximum lifetime. Remote failure is NOT reported as success.+func (q *Queries) ExpireChannelTypingReactionCleanup(ctx context.Context) ([]ExpireChannelTypingReactionCleanupRow, error) {+ rows, err := q.db.Query(ctx, expireChannelTypingReactionCleanup)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ExpireChannelTypingReactionCleanupRow{}+ for rows.Next() {+ var i ExpireChannelTypingReactionCleanupRow+ if err := rows.Scan(&i.ID, &i.WorkspaceID); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const finishChannelTypingReactionAdd = `-- name: FinishChannelTypingReactionAdd :one+UPDATE channel_typing_reaction SET reaction_id = $1, add_finished = true,+ cleanup_required = cleanup_required OR $2::boolean,+ cleaned_at = NULL, retry_after = now()+WHERE id = $3 AND abandoned_at IS NULL AND created_at > now() - interval '7 days'+RETURNING id, workspace_id, chat_session_id, chat_message_id, installation_id, channel_message_id, installation_snapshot, reaction_id, add_finished, cleanup_required, cleaned_at, retry_after, attempts, created_at, abandoned_at, quota_slot+`++type FinishChannelTypingReactionAddParams struct {+ ReactionID string `json:"reaction_id"`+ CleanupRequired bool `json:"cleanup_required"`+ ID pgtype.UUID `json:"id"`+}++// cleanup_required is monotonic. A stale active read cannot undo another+// replica's terminal decision; late HTTP completion re-arms compensation.+func (q *Queries) FinishChannelTypingReactionAdd(ctx context.Context, arg FinishChannelTypingReactionAddParams) (ChannelTypingReaction, error) {+ row := q.db.QueryRow(ctx, finishChannelTypingReactionAdd, arg.ReactionID, arg.CleanupRequired, arg.ID)+ var i ChannelTypingReaction+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ChatSessionID,+ &i.ChatMessageID,+ &i.InstallationID,+ &i.ChannelMessageID,+ &i.InstallationSnapshot,+ &i.ReactionID,+ &i.AddFinished,+ &i.CleanupRequired,+ &i.CleanedAt,+ &i.RetryAfter,+ &i.Attempts,+ &i.CreatedAt,+ &i.AbandonedAt,+ &i.QuotaSlot,+ )+ return i, err+}++const listRequestedChannelTypingReactions = `-- name: ListRequestedChannelTypingReactions :many+SELECT id FROM channel_typing_reaction WHERE id = ANY($1::uuid[]) AND cleanup_required+`++func (q *Queries) ListRequestedChannelTypingReactions(ctx context.Context, ids []pgtype.UUID) ([]pgtype.UUID, error) {+ rows, err := q.db.Query(ctx, listRequestedChannelTypingReactions, ids)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []pgtype.UUID{}+ for rows.Next() {+ var id pgtype.UUID+ if err := rows.Scan(&id); err != nil {+ return nil, err+ }+ items = append(items, id)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const pruneChannelTypingReactionCleanup = `-- name: PruneChannelTypingReactionCleanup :exec+WITH candidates AS (+ SELECT id FROM channel_typing_reaction+ WHERE cleaned_at < now() - interval '7 days' OR abandoned_at < now() - interval '7 days'+ LIMIT 1000 FOR UPDATE SKIP LOCKED+)+DELETE FROM channel_typing_reaction r USING candidates c WHERE r.id = c.id+`++// Each terminal outcome remains inspectable for seven days without credentials.+func (q *Queries) PruneChannelTypingReactionCleanup(ctx context.Context) error {+ _, err := q.db.Exec(ctx, pruneChannelTypingReactionCleanup)+ return err+}++const registerChannelTypingReaction = `-- name: RegisterChannelTypingReaction :one+INSERT INTO channel_typing_reaction (+ id, workspace_id, chat_session_id, chat_message_id, installation_id,+ channel_message_id, installation_snapshot, cleanup_required, quota_slot+)+SELECT $1, $2, $3, $4, $5,+ $6, $7, message.channel_typing_settled, slot.value+FROM chat_message AS message+JOIN chat_session AS session ON session.id = message.chat_session_id+JOIN channel_installation AS installation ON installation.id = $5+CROSS JOIN LATERAL (+ SELECT value FROM generate_series(1, 1000) AS value+ WHERE NOT EXISTS (SELECT 1 FROM channel_typing_reaction r+ WHERE r.workspace_id = $2 AND r.quota_slot = value+ AND r.cleaned_at IS NULL AND r.abandoned_at IS NULL)+ ORDER BY value LIMIT 1+) slot+WHERE message.id = $4+ AND session.id = $3 AND session.workspace_id = $2+ AND installation.workspace_id = $2 AND installation.channel_type = 'feishu'+ AND message.channel_ingested AND message.role = 'user'+ON CONFLICT DO NOTHING RETURNING id, workspace_id, chat_session_id, chat_message_id, installation_id, channel_message_id, installation_snapshot, reaction_id, add_finished, cleanup_required, cleaned_at, retry_after, attempts, created_at, abandoned_at, quota_slot+`++type RegisterChannelTypingReactionParams struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ ChatMessageID pgtype.UUID `json:"chat_message_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ ChannelMessageID string `json:"channel_message_id"`+ InstallationSnapshot []byte `json:"installation_snapshot"`+}++// Commit the complete external anchor BEFORE issuing Add. A terminal observer+// can enumerate every input, independently of the one delivery trigger.+// A concurrent registration can take the same slot. Fail closed: a cosmetic+// badge may be skipped, but an untracked Add or a quota overrun is never safe.+func (q *Queries) RegisterChannelTypingReaction(ctx context.Context, arg RegisterChannelTypingReactionParams) (ChannelTypingReaction, error) {+ row := q.db.QueryRow(ctx, registerChannelTypingReaction,+ arg.ID,+ arg.WorkspaceID,+ arg.ChatSessionID,+ arg.ChatMessageID,+ arg.InstallationID,+ arg.ChannelMessageID,+ arg.InstallationSnapshot,+ )+ var i ChannelTypingReaction+ err := row.Scan(+ &i.ID,+ &i.WorkspaceID,+ &i.ChatSessionID,+ &i.ChatMessageID,+ &i.InstallationID,+ &i.ChannelMessageID,+ &i.InstallationSnapshot,+ &i.ReactionID,+ &i.AddFinished,+ &i.CleanupRequired,+ &i.CleanedAt,+ &i.RetryAfter,+ &i.Attempts,+ &i.CreatedAt,+ &i.AbandonedAt,+ &i.QuotaSlot,+ )+ return i, err+}++const settleChannelTypingInputs = `-- name: SettleChannelTypingInputs :exec+UPDATE chat_message AS message SET channel_typing_settled = true+FROM chat_message AS cutoff, chat_session AS session, channel_installation AS installation+WHERE cutoff.id = $1 AND cutoff.chat_session_id = $2+ AND session.id = $2 AND session.workspace_id = $3+ AND installation.id = $4 AND installation.workspace_id = $3+ AND installation.channel_type = 'feishu'+ AND EXISTS (SELECT 1 FROM channel_chat_session_binding b WHERE b.chat_session_id = session.id+ AND b.installation_id = installation.id AND b.channel_type = 'feishu')+ AND message.chat_session_id = session.id AND message.task_id IS NULL+ AND message.channel_ingested AND message.role = 'user'+ AND COALESCE(message.channel_context_revision, 1) = $5+ AND (message.created_at, message.id) <= (cutoff.created_at, cutoff.id)+`++type SettleChannelTypingInputsParams struct {+ ThroughMessageID pgtype.UUID `json:"through_message_id"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ ContextRevision pgtype.Int8 `json:"context_revision"`+}++// The flush owns only this context's unowned inputs up to its captured cutoff.+// Later inputs, even in the same session, are not settled by this failed run.+func (q *Queries) SettleChannelTypingInputs(ctx context.Context, arg SettleChannelTypingInputsParams) error {+ _, err := q.db.Exec(ctx, settleChannelTypingInputs,+ arg.ThroughMessageID,+ arg.ChatSessionID,+ arg.WorkspaceID,+ arg.InstallationID,+ arg.ContextRevision,+ )+ return err+}++const skipChannelTypingReactionAdd = `-- name: SkipChannelTypingReactionAdd :exec+UPDATE channel_typing_reaction SET add_finished = true, cleanup_required = true,+ cleaned_at = now(), installation_snapshot = '{}'::jsonb WHERE id = $1 AND abandoned_at IS NULL+`++// No HTTP Add was issued for an already-settled input.+func (q *Queries) SkipChannelTypingReactionAdd(ctx context.Context, id pgtype.UUID) error {+ _, err := q.db.Exec(ctx, skipChannelTypingReactionAdd, id)+ return err+}diff --git a/server/pkg/db/generated/chat.sql.go b/server/pkg/db/generated/chat.sql.goindex 94ccc385a7..05f8710e1d 100644--- a/server/pkg/db/generated/chat.sql.go+++ b/server/pkg/db/generated/chat.sql.go@@ -262,7 +262,7 @@ VALUES ($11,COALESCE($12::uuid, gen_random_uuid()))-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids, channel_typing_settled`type CreateChatMessageParams struct {@@ -317,6 +317,7 @@ func (q *Queries) CreateChatMessage(ctx context.Context, arg CreateChatMessagePa&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,)return i, err}@@ -516,7 +517,7 @@ VALUES ($3::timestamptz + interval '1 microsecond',COALESCE($4::uuid, gen_random_uuid()))-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids, channel_typing_settled`type CreateMikaOnboardingOpeningParams struct {@@ -564,6 +565,7 @@ func (q *Queries) CreateMikaOnboardingOpening(ctx context.Context, arg CreateMik&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,)return i, err}@@ -737,7 +739,7 @@ DELETE FROM chat_messageWHERE task_id = $1AND role = 'user'AND message_kind <> 'onboarding_kickoff'-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids, channel_typing_settled`// Deletes the MEMBER-TYPED input of a cancelled/edited turn.@@ -772,6 +774,7 @@ func (q *Queries) DeleteUserChatMessageByTask(ctx context.Context, taskID pgtype&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,)return i, err}@@ -814,7 +817,7 @@ func (q *Queries) GetChannelMediaPendingUntil(ctx context.Context, arg GetChanne}const getChatMessage = `-- name: GetChatMessage :one-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids 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, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids, channel_typing_settled FROM chat_messageWHERE id = $1`@@ -839,12 +842,13 @@ func (q *Queries) GetChatMessage(ctx context.Context, id pgtype.UUID) (ChatMessa&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,)return i, err}const getChatMessageByTaskAssistant = `-- name: GetChatMessageByTaskAssistant :one-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids 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, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids, channel_typing_settled FROM chat_messageWHERE task_id = $1 AND role = 'assistant'ORDER BY created_at DESCLIMIT 1@@ -873,6 +877,7 @@ func (q *Queries) GetChatMessageByTaskAssistant(ctx context.Context, taskID pgty&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,)return i, err}@@ -1077,7 +1082,7 @@ func (q *Queries) GetLastChatTaskSession(ctx context.Context, arg GetLastChatTas}const getLatestAssistantChatMessageForSession = `-- name: GetLatestAssistantChatMessageForSession :one-SELECT id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids 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, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids, channel_typing_settled FROM chat_messageWHERE chat_session_id = $1 AND role = 'assistant' AND task_id IS NOT NULLORDER BY created_at DESCLIMIT 1@@ -1108,6 +1113,7 @@ func (q *Queries) GetLatestAssistantChatMessageForSession(ctx context.Context, c&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,)return i, err}@@ -1895,7 +1901,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, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids 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, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids, channel_typing_settled FROM chat_messageWHERE task_id = $1 AND role = 'user'ORDER BY created_at ASC, id ASC`@@ -1934,6 +1940,7 @@ func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID)&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,); err != nil {return nil, err}@@ -1946,7 +1953,7 @@ func (q *Queries) ListChatInputMessages(ctx context.Context, taskID pgtype.UUID)}const listChatMessages = `-- name: ListChatMessages :many-SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids FROM chat_message AS message+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids, message.channel_typing_settled FROM chat_message AS messageWHERE message.chat_session_id = $1AND message.message_kind != 'channel_command'AND NOT (@@ -2018,6 +2025,7 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,); err != nil {return nil, err}@@ -2030,7 +2038,7 @@ func (q *Queries) ListChatMessages(ctx context.Context, chatSessionID pgtype.UUI}const listChatMessagesForLegacyTask = `-- name: ListChatMessagesForLegacyTask :many-SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids FROM chat_message AS message+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids, message.channel_typing_settled FROM chat_message AS messageWHERE message.chat_session_id = $1AND NOT (message.role = 'user'@@ -2091,6 +2099,7 @@ func (q *Queries) ListChatMessagesForLegacyTask(ctx context.Context, chatSession&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,); err != nil {return nil, err}@@ -2103,7 +2112,7 @@ func (q *Queries) ListChatMessagesForLegacyTask(ctx context.Context, chatSession}const listChatMessagesPage = `-- name: ListChatMessagesPage :many-SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids FROM chat_message AS message+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids, message.channel_typing_settled FROM chat_message AS messageWHERE message.chat_session_id = $1AND message.message_kind != 'channel_command'AND NOT (@@ -2180,6 +2189,7 @@ func (q *Queries) ListChatMessagesPage(ctx context.Context, arg ListChatMessages&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,); err != nil {return nil, err}@@ -2192,7 +2202,7 @@ func (q *Queries) ListChatMessagesPage(ctx context.Context, arg ListChatMessages}const listChatMessagesPageForChannelContext = `-- name: ListChatMessagesPageForChannelContext :many-SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids+SELECT message.id, message.chat_session_id, message.role, message.content, message.task_id, message.created_at, message.failure_reason, message.elapsed_ms, message.message_kind, message.channel_media_pending_until, message.channel_ingested, message.quick_actions, message.channel_context_revision, message.channel_outbound_type, message.channel_outbound_installation_id, message.channel_outbound_chat_id, message.channel_outbound_message_ids, message.channel_typing_settledFROM chat_message AS messageLEFT JOIN agent_task_queue AS owner ON owner.id = message.task_idWHERE message.chat_session_id = $1@@ -2267,6 +2277,7 @@ func (q *Queries) ListChatMessagesPageForChannelContext(ctx context.Context, arg&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,); err != nil {return nil, err}@@ -3363,7 +3374,7 @@ WHERE id = (ORDER BY inner_msg.created_at DESCLIMIT 1)-RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids+RETURNING id, chat_session_id, role, content, task_id, created_at, failure_reason, elapsed_ms, message_kind, channel_media_pending_until, channel_ingested, quick_actions, channel_context_revision, channel_outbound_type, channel_outbound_installation_id, channel_outbound_chat_id, channel_outbound_message_ids, channel_typing_settled`type SetChatMessageQuickActionsByTaskParams struct {@@ -3392,6 +3403,7 @@ func (q *Queries) SetChatMessageQuickActionsByTask(ctx context.Context, arg SetC&i.ChannelOutboundInstallationID,&i.ChannelOutboundChatID,&i.ChannelOutboundMessageIds,+ &i.ChannelTypingSettled,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 2cd4893996..87a89e51a5 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -475,6 +475,25 @@ type ChannelTaskDelivery struct {ChannelSenderID pgtype.Text `json:"channel_sender_id"`}+type ChannelTypingReaction struct {+ ID pgtype.UUID `json:"id"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ ChatSessionID pgtype.UUID `json:"chat_session_id"`+ ChatMessageID pgtype.UUID `json:"chat_message_id"`+ InstallationID pgtype.UUID `json:"installation_id"`+ ChannelMessageID string `json:"channel_message_id"`+ InstallationSnapshot []byte `json:"installation_snapshot"`+ ReactionID string `json:"reaction_id"`+ AddFinished bool `json:"add_finished"`+ CleanupRequired bool `json:"cleanup_required"`+ CleanedAt pgtype.Timestamptz `json:"cleaned_at"`+ RetryAfter pgtype.Timestamptz `json:"retry_after"`+ Attempts int32 `json:"attempts"`+ CreatedAt pgtype.Timestamptz `json:"created_at"`+ AbandonedAt pgtype.Timestamptz `json:"abandoned_at"`+ QuotaSlot pgtype.Int4 `json:"quota_slot"`+}+type ChannelUserBinding struct {ID pgtype.UUID `json:"id"`WorkspaceID pgtype.UUID `json:"workspace_id"`@@ -513,6 +532,7 @@ type ChatMessage struct {ChannelOutboundInstallationID pgtype.UUID `json:"channel_outbound_installation_id"`ChannelOutboundChatID pgtype.Text `json:"channel_outbound_chat_id"`ChannelOutboundMessageIds []string `json:"channel_outbound_message_ids"`+ ChannelTypingSettled bool `json:"channel_typing_settled"`}type ChatPinnedAgent struct {diff --git a/server/pkg/db/queries/channel.sql b/server/pkg/db/queries/channel.sqlindex 775844130a..7457f3f5d6 100644--- a/server/pkg/db/queries/channel.sql+++ b/server/pkg/db/queries/channel.sql@@ -1518,3 +1518,34 @@ WHERE channel_reply_delivery.phase <> 'settled'-- would be dropped as "already settled".AND EXCLUDED.attempt_depth >= channel_reply_delivery.attempt_depthRETURNING *;++-- name: IsChannelMessageTypingActive :one+-- Revalidate the exact input after a remote reaction Add. A pending debounce+-- input has no task yet; a sealed input follows its immutable owning task.+-- Do not use the binding's latest message or another turn's active task.+SELECT EXISTS (+ SELECT 1 FROM chat_message AS message+ JOIN chat_session AS session ON session.id = message.chat_session_id+ JOIN channel_chat_session_binding AS binding ON binding.chat_session_id = session.id+ JOIN channel_installation AS installation ON installation.id = binding.installation_id+ LEFT JOIN agent_task_queue AS task ON task.id = message.task_id+ LEFT JOIN agent AS task_agent ON task_agent.id = task.agent_id+ WHERE message.id = @message_id+ AND session.id = @chat_session_id+ AND session.workspace_id = @workspace_id+ AND installation.workspace_id = @workspace_id+ AND installation.id = @installation_id+ AND installation.channel_type = @channel_type+ AND binding.channel_type = @channel_type+ AND installation.status = 'active'+ AND session.status = 'active'+ AND binding.retired_at IS NULL+ AND message.role = 'user'+ AND message.channel_ingested+ AND NOT message.channel_typing_settled+ AND (message.task_id IS NULL OR (+ task_agent.workspace_id = @workspace_id+ AND task.chat_session_id = session.id+ AND task.status IN ('queued', 'dispatched', 'running', 'waiting_local_directory', 'deferred')+ ))+);diff --git a/server/pkg/db/queries/channel_typing.sql b/server/pkg/db/queries/channel_typing.sqlnew file mode 100644index 0000000000..6504cb6ca7--- /dev/null+++ b/server/pkg/db/queries/channel_typing.sql@@ -0,0 +1,123 @@+-- name: RegisterChannelTypingReaction :one+-- Commit the complete external anchor BEFORE issuing Add. A terminal observer+-- can enumerate every input, independently of the one delivery trigger.+INSERT INTO channel_typing_reaction (+ id, workspace_id, chat_session_id, chat_message_id, installation_id,+ channel_message_id, installation_snapshot, cleanup_required, quota_slot+)+SELECT @id, @workspace_id, @chat_session_id, @chat_message_id, @installation_id,+ @channel_message_id, @installation_snapshot, message.channel_typing_settled, slot.value+FROM chat_message AS message+JOIN chat_session AS session ON session.id = message.chat_session_id+JOIN channel_installation AS installation ON installation.id = @installation_id+CROSS JOIN LATERAL (+ SELECT value FROM generate_series(1, 1000) AS value+ WHERE NOT EXISTS (SELECT 1 FROM channel_typing_reaction r+ WHERE r.workspace_id = @workspace_id AND r.quota_slot = value+ AND r.cleaned_at IS NULL AND r.abandoned_at IS NULL)+ ORDER BY value LIMIT 1+) slot+WHERE message.id = @chat_message_id+ AND session.id = @chat_session_id AND session.workspace_id = @workspace_id+ AND installation.workspace_id = @workspace_id AND installation.channel_type = 'feishu'+ AND message.channel_ingested AND message.role = 'user'+-- A concurrent registration can take the same slot. Fail closed: a cosmetic+-- badge may be skipped, but an untracked Add or a quota overrun is never safe.+ON CONFLICT DO NOTHING RETURNING *;++-- name: FinishChannelTypingReactionAdd :one+-- cleanup_required is monotonic. A stale active read cannot undo another+-- replica's terminal decision; late HTTP completion re-arms compensation.+UPDATE channel_typing_reaction SET reaction_id = @reaction_id, add_finished = true,+ cleanup_required = cleanup_required OR @cleanup_required::boolean,+ cleaned_at = NULL, retry_after = now()+WHERE id = @id AND abandoned_at IS NULL AND created_at > now() - interval '7 days'+RETURNING *;++-- name: AcknowledgeChannelTypingReactionCleanup :exec+-- An unfinished Add may still create a reaction after an empty sweep. Retain+-- its anchor; only a known successful Add response can close cleanup forever.+UPDATE channel_typing_reaction+SET cleaned_at = CASE WHEN add_finished AND reaction_id <> '' THEN now() ELSE NULL END,+ retry_after = GREATEST(retry_after, now() + interval '30 seconds'),+ installation_snapshot = CASE WHEN add_finished AND reaction_id <> '' THEN '{}'::jsonb ELSE installation_snapshot END+WHERE id = @id AND reaction_id = @reaction_id AND cleanup_required AND abandoned_at IS NULL;++-- name: ClaimChannelTypingReactionCleanup :many+-- The DB is the shared source of eligibility. Missing source rows after a+-- committed deletion are terminal too. No transaction takes remote I/O locks.+WITH candidates AS (+ SELECT r.id FROM channel_typing_reaction r+ WHERE r.cleaned_at IS NULL AND r.abandoned_at IS NULL AND r.retry_after <= now()+ AND r.created_at > now() - interval '7 days'+ AND (sqlc.narg('chat_session_id')::uuid IS NULL OR r.chat_session_id = sqlc.narg('chat_session_id'))+ AND (r.cleanup_required OR (NOT r.add_finished AND r.created_at < now() - interval '1 minute') OR NOT EXISTS (+ SELECT 1 FROM chat_message m+ JOIN chat_session s ON s.id = m.chat_session_id+ JOIN channel_installation i ON i.id = r.installation_id+ JOIN channel_chat_session_binding b ON b.chat_session_id = s.id AND b.installation_id = i.id+ LEFT JOIN agent_task_queue t ON t.id = m.task_id+ LEFT JOIN agent a ON a.id = t.agent_id+ WHERE m.id = r.chat_message_id AND s.id = r.chat_session_id+ AND s.workspace_id = r.workspace_id AND i.workspace_id = r.workspace_id+ AND i.channel_type = 'feishu' AND b.channel_type = 'feishu'+ AND s.status = 'active' AND i.status = 'active' AND b.retired_at IS NULL+ AND m.channel_ingested AND m.role = 'user' AND NOT m.channel_typing_settled+ -- A taskless badge has a bounded visual lifetime even if a crashed+ -- debouncer never flushes. Do not settle the input or cancel a future run.+ AND ((m.task_id IS NULL AND r.created_at > now() - interval '2 minutes') OR (t.chat_session_id = s.id AND a.workspace_id = r.workspace_id+ AND t.status IN ('queued','dispatched','running','waiting_local_directory','deferred')))+ ))+ ORDER BY r.retry_after, r.id LIMIT 100+ FOR UPDATE OF r SKIP LOCKED+)+UPDATE channel_typing_reaction r SET cleanup_required = true,+ attempts = attempts + 1,+ retry_after = now() + LEAST(3600, 30 * power(2, LEAST(r.attempts, 7))) * interval '1 second'+FROM candidates c WHERE r.id = c.id RETURNING r.*;++-- name: SettleChannelTypingInputs :exec+-- The flush owns only this context's unowned inputs up to its captured cutoff.+-- Later inputs, even in the same session, are not settled by this failed run.+UPDATE chat_message AS message SET channel_typing_settled = true+FROM chat_message AS cutoff, chat_session AS session, channel_installation AS installation+WHERE cutoff.id = @through_message_id AND cutoff.chat_session_id = @chat_session_id+ AND session.id = @chat_session_id AND session.workspace_id = @workspace_id+ AND installation.id = @installation_id AND installation.workspace_id = @workspace_id+ AND installation.channel_type = 'feishu'+ AND EXISTS (SELECT 1 FROM channel_chat_session_binding b WHERE b.chat_session_id = session.id+ AND b.installation_id = installation.id AND b.channel_type = 'feishu')+ AND message.chat_session_id = session.id AND message.task_id IS NULL+ AND message.channel_ingested AND message.role = 'user'+ AND COALESCE(message.channel_context_revision, 1) = @context_revision+ AND (message.created_at, message.id) <= (cutoff.created_at, cutoff.id);++-- name: PruneChannelTypingReactionCleanup :exec+-- Each terminal outcome remains inspectable for seven days without credentials.+WITH candidates AS (+ SELECT id FROM channel_typing_reaction+ WHERE cleaned_at < now() - interval '7 days' OR abandoned_at < now() - interval '7 days'+ LIMIT 1000 FOR UPDATE SKIP LOCKED+)+DELETE FROM channel_typing_reaction r USING candidates c WHERE r.id = c.id;++-- name: ExpireChannelTypingReactionCleanup :many+-- Independent maintenance, including active/uncertain Adds: the cosmetic badge+-- has a seven-day maximum lifetime. Remote failure is NOT reported as success.+WITH candidates AS (+ SELECT id FROM channel_typing_reaction+ WHERE cleaned_at IS NULL AND abandoned_at IS NULL AND created_at <= now() - interval '7 days'+ ORDER BY created_at, id LIMIT 1000 FOR UPDATE SKIP LOCKED+)+UPDATE channel_typing_reaction r SET abandoned_at = now(), cleanup_required = true,+ installation_snapshot = '{}'::jsonb+FROM candidates c WHERE r.id = c.id+RETURNING r.id, r.workspace_id;++-- name: SkipChannelTypingReactionAdd :exec+-- No HTTP Add was issued for an already-settled input.+UPDATE channel_typing_reaction SET add_finished = true, cleanup_required = true,+ cleaned_at = now(), installation_snapshot = '{}'::jsonb WHERE id = $1 AND abandoned_at IS NULL;++-- name: ListRequestedChannelTypingReactions :many+SELECT id FROM channel_typing_reaction WHERE id = ANY(@ids::uuid[]) AND cleanup_required;