Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.
fix(agent): confirm missing Room replies with TeamHub before failing
LeoXing1683bc0cd03c
diff --git a/apps/node-services/src/agent/AGENTS.md b/apps/node-services/src/agent/AGENTS.mdindex ec9fd2f0..218c00ae 100644--- a/apps/node-services/src/agent/AGENTS.md+++ b/apps/node-services/src/agent/AGENTS.md@@ -73,11 +73,15 @@ take precedence.scheduler, execution store, or Runtime executor beside it, and do notrestore TeamHub Run admission.- A Room Agent speaks only through TeamHub message writes, which the Computer- classifies as `message` activities (`reply-delivery.ts`). A Room Run whose- every write failed finishes failed with `reply_undelivered`. One that never- tried to write while a Human's Message that mentioned the Agent (a direct- chat always does) waits finishes failed with `reply_not_sent`. Its final- text is private scratch and is never posted for it.+ classifies as `message` activities (`reply-delivery.ts`). Before failing a+ Room Run for a missing reply, the Run loop checks TeamHub's persisted reply+ status (`GET /v0/agent-runtime/runs/reply-status`) so compound scripts,+ decision cards, presentation sequences, and reactions that activity+ classification missed are not misreported. A Room Run whose every write+ failed finishes failed with `reply_undelivered`. One that left no reply while+ a Human's Message that mentioned the Agent (a direct chat always does) waits+ finishes failed with `reply_not_sent`. Its final text is private scratch and+ is never posted for it.- Ordinary Room/Meta execution reads effective Agent configuration before a newLocal Run. Skill saves do not activate idle Contexts. If versions changed,reuse graceful activation to resume the same native history; running/steereddiff --git a/apps/node-services/src/agent/executor/context-runtime-state.ts b/apps/node-services/src/agent/executor/context-runtime-state.tsindex c124535e..caf58270 100644--- a/apps/node-services/src/agent/executor/context-runtime-state.ts+++ b/apps/node-services/src/agent/executor/context-runtime-state.ts@@ -136,6 +136,15 @@ export interface ContextRuntimeStatePort {noteQueuedRun?(): void;cancelLocalRun(runId: string): RuntimeStateAwaitable<RunCancellationStatus>;getLocalRun(runId: string): RuntimeStateAwaitable<LocalRun | null>;+ /**+ * Reports whether TeamHub persisted a visible reply for the Run, so an+ * apparent missing reply from activity classification can be confirmed+ * before failing the Run.+ */+ hasLocalRunReplied(+ runId: string,+ signal?: AbortSignal,+ ): RuntimeStateAwaitable<boolean>;enqueueSteer(groupId: string,messages: NonEmptyReadonlyArray<Message>,@@ -685,6 +694,19 @@ class TeamHubContextRuntimeState implements ContextRuntimeStatePort {};}+ async hasLocalRunReplied(+ runId: string,+ signal?: AbortSignal,+ ): Promise<boolean> {+ this.#assertOpen();+ const result = await this.#client.getRunReplyStatus(+ this.#contextKey,+ runId,+ signal,+ );+ return result.replied;+ }+async enqueueSteer(groupId: string,_messages: NonEmptyReadonlyArray<Message>,diff --git a/apps/node-services/src/agent/executor/run-loop.ts b/apps/node-services/src/agent/executor/run-loop.tsindex 87e44a13..c15fcee7 100644--- a/apps/node-services/src/agent/executor/run-loop.ts+++ b/apps/node-services/src/agent/executor/run-loop.ts@@ -1368,7 +1368,7 @@ export class RunLoop {const statusDrainStartedAt = performance.now();await this.#settleRuntimeStatusEvents(execution);const runtimeStatusDrainMs = performance.now() - statusDrainStartedAt;- const terminal = this.#completedTerminal(+ const terminal = await this.#completedTerminal(runId,finalResponse,replyDelivery,@@ -1731,15 +1731,34 @@ export class RunLoop {* Provider turn is not a succeeded Run when the Room has nothing to show:* the Agent tried to post and none landed, or a Human who mentioned it is* waiting and it never tried. Its final text is private scratch and is not- * posted for it. Task Runs report through their final response and keep it.+ * posted for it. Because activity classification inspects shell text for+ * display and can miss compound scripts or decision cards, TeamHub confirms+ * whether a visible reply landed before failing the Run. Task Runs report+ * through their final response and keep it.*/- #completedTerminal(+ async #completedTerminal(runId: string,finalResponse: string,replyDelivery: ReplyDelivery,- ): LocalRunTerminal {+ ): Promise<LocalRunTerminal> {const roomRun = this.#executionContextRef?.kind === "meta";- const undelivered = roomRun && replyDelivery.replyUndelivered;+ const suspectedUndelivered = roomRun && replyDelivery.replyUndelivered;+ const suspectedNotSent = roomRun && replyDelivery.replyNotSent;+ let confirmedReplied = false;+ if (suspectedUndelivered || suspectedNotSent) {+ try {+ confirmedReplied = await this.#state.hasLocalRunReplied(+ runId,+ this.#terminalRecoveryStop.signal,+ );+ } catch (error) {+ this.#logger.log("warn", "local_run.reply_check_failed", {+ runId,+ error,+ });+ }+ }+ const undelivered = suspectedUndelivered && !confirmedReplied;if (replyDelivery.hasFailures) {this.#logger.log("warn", "local_run.teamhub_messages_failed", {runId,@@ -1755,7 +1774,7 @@ export class RunLoop {failure: runFailure("reply_undelivered", this.#runtimeType),};}- if (roomRun && replyDelivery.replyNotSent) {+ if (suspectedNotSent && !confirmedReplied) {this.#logger.log("warn", "local_run.reply_not_sent", {runId,...replyDelivery.counts(),diff --git a/apps/node-services/src/agent/executor/teamhub-runtime-state-client.ts b/apps/node-services/src/agent/executor/teamhub-runtime-state-client.tsindex 911ede55..170d465b 100644--- a/apps/node-services/src/agent/executor/teamhub-runtime-state-client.ts+++ b/apps/node-services/src/agent/executor/teamhub-runtime-state-client.ts@@ -109,6 +109,11 @@ export interface TeamHubRuntimeStateClient {runId: string,signal?: AbortSignal,): Promise<RuntimeStateSchemas["AgentLocalRun"]>;+ getRunReplyStatus(+ contextKey: string,+ runId: string,+ signal?: AbortSignal,+ ): Promise<RuntimeStateSchemas["AgentLocalRunReplyStatus"]>;/** Contexts whose queued Run or Message steer waited past its wake hint. */listWaitingContexts(signal?: AbortSignal): Promise<readonly string[]>;claimRun(@@ -346,6 +351,11 @@ export const createTeamHubRuntimeStateClient = (),getRun: (contextKey, runId, signal) =>request<RuntimeLocalRun>(raw.getRun(contextKey, runId, signal), signal),+ getRunReplyStatus: (contextKey, runId, signal) =>+ request<RuntimeStateSchemas["AgentLocalRunReplyStatus"]>(+ raw.getRunReplyStatus(contextKey, runId, signal),+ signal,+ ),listWaitingContexts: async (signal) =>(await request<RuntimeStateSchemas["AgentRuntimeWaitingContexts"]>(diff --git a/apps/node-services/tests/agent/executor/context-runtime-state.test.ts b/apps/node-services/tests/agent/executor/context-runtime-state.test.tsindex d36e3782..075175f9 100644--- a/apps/node-services/tests/agent/executor/context-runtime-state.test.ts+++ b/apps/node-services/tests/agent/executor/context-runtime-state.test.ts@@ -1550,6 +1550,24 @@ describe("TeamHub Context Runtime state", () => {expect(workStateReads).toBe(1);await state.close();});++ it("reads Local Run reply delivery status from TeamHub", async () => {+ const getRunReplyStatus = vi.fn<+ TeamHubRuntimeStateClient["getRunReplyStatus"]+ >(async () => ({ replied: true }));+ const { state } = await terminalFixture({ getRunReplyStatus });+ const controller = new AbortController();++ await expect(+ state.hasLocalRunReplied("local-run-1", controller.signal),+ ).resolves.toBe(true);+ expect(getRunReplyStatus).toHaveBeenCalledExactlyOnceWith(+ '["meta","agent-reviewer","room","room-1"]',+ "local-run-1",+ controller.signal,+ );+ await state.close();+ });});const context = (targetResidency: "active" | "suspended"): RuntimeContext => ({diff --git a/apps/node-services/tests/agent/executor/run-loop.test.ts b/apps/node-services/tests/agent/executor/run-loop.test.tsindex 018b946d..682474ed 100644--- a/apps/node-services/tests/agent/executor/run-loop.test.ts+++ b/apps/node-services/tests/agent/executor/run-loop.test.ts@@ -335,6 +335,7 @@ describe("RunLoop", () => {input: Message = message("introduce yourself"),finalResponse = "I could not deliver the reply: TeamHub returned 404.",steered?: Message,+ hasLocalRunReplied?: ContextRuntimeStatePort["hasLocalRunReplied"],) => {const harness = createHarness(undefined,@@ -343,6 +344,9 @@ describe("RunLoop", () => {undefined,executionContextRef,);+ if (hasLocalRunReplied) {+ Object.assign(harness.state, { hasLocalRunReplied });+ }const run = new FakeRun(events);harness.provider.runs.push(run);const runId = enqueue(harness.state, input);@@ -517,14 +521,150 @@ describe("RunLoop", () => {});it("keeps a Room Run succeeded when it answered a Human mention with a message", async () => {+ const hasLocalRunReplied = vi.fn(async () => false);const { run } = await finishRun(messageWrite("send-1", "succeeded"),undefined,humanMention("mention"),"",+ undefined,+ hasLocalRunReplied,);expect(run?.terminal).toMatchObject({ type: "succeeded" });+ expect(hasLocalRunReplied).not.toHaveBeenCalled();+ });++ it("keeps a Room Run succeeded when TeamHub confirms a reply that activity tracking missed", async () => {+ const hasLocalRunReplied = vi.fn(async () => true);+ const { log, run } = await finishRun(+ [],+ undefined,+ humanMention("mention"),+ "Sent via compound command.",+ undefined,+ hasLocalRunReplied,+ );++ expect(run?.terminal).toMatchObject({ type: "succeeded" });+ expect(hasLocalRunReplied).toHaveBeenCalledExactlyOnceWith(+ run?.runId,+ expect.any(AbortSignal),+ );+ expect(log).not.toHaveBeenCalledWith(+ "warn",+ "local_run.reply_not_sent",+ expect.anything(),+ );+ });++ it("fails a Room Run as reply_not_sent when TeamHub confirms no reply landed", async () => {+ const hasLocalRunReplied = vi.fn(async () => false);+ const { log, run } = await finishRun(+ [],+ undefined,+ humanMention("mention"),+ "Private scratch.",+ undefined,+ hasLocalRunReplied,+ );++ expect(run).toMatchObject({+ status: "failed",+ terminal: {+ type: "failed",+ failure: { code: "reply_not_sent", runtime_type: "pi" },+ },+ });+ expect(hasLocalRunReplied).toHaveBeenCalledOnce();+ expect(log).toHaveBeenCalledWith(+ "warn",+ "local_run.reply_not_sent",+ expect.objectContaining({ runId: run?.runId }),+ );+ });++ it("falls back to reply_not_sent when the TeamHub reply check fails", async () => {+ const hasLocalRunReplied = vi.fn(async () => {+ throw new Error("teamhub unreachable");+ });+ const { log, run } = await finishRun(+ [],+ undefined,+ humanMention("mention"),+ "Done.",+ undefined,+ hasLocalRunReplied,+ );++ expect(run).toMatchObject({+ status: "failed",+ terminal: {+ type: "failed",+ failure: { code: "reply_not_sent", runtime_type: "pi" },+ },+ });+ expect(log).toHaveBeenCalledWith(+ "warn",+ "local_run.reply_check_failed",+ expect.objectContaining({ runId: run?.runId }),+ );+ expect(log).toHaveBeenCalledWith(+ "warn",+ "local_run.reply_not_sent",+ expect.objectContaining({ runId: run?.runId }),+ );+ });++ it("keeps a Room Run succeeded when TeamHub confirms a reply despite a failed message activity", async () => {+ const hasLocalRunReplied = vi.fn(async () => true);+ const { log, run } = await finishRun(+ messageWrite("send-1", "failed"),+ undefined,+ humanMention("mention"),+ "",+ undefined,+ hasLocalRunReplied,+ );++ expect(run?.terminal).toMatchObject({ type: "succeeded" });+ expect(hasLocalRunReplied).toHaveBeenCalledOnce();+ expect(log).toHaveBeenCalledWith(+ "warn",+ "local_run.teamhub_messages_failed",+ expect.objectContaining({+ runId: run?.runId,+ failedMessageWrites: 1,+ replyUndelivered: false,+ }),+ );+ });++ it("still fails as reply_undelivered when message writes failed and TeamHub reply check errors", async () => {+ const hasLocalRunReplied = vi.fn(async () => {+ throw new Error("teamhub unreachable");+ });+ const { log, run } = await finishRun(+ messageWrite("send-1", "failed"),+ undefined,+ humanMention("mention"),+ "",+ undefined,+ hasLocalRunReplied,+ );++ expect(run).toMatchObject({+ status: "failed",+ terminal: {+ type: "failed",+ failure: { code: "reply_undelivered", runtime_type: "pi" },+ },+ });+ expect(log).toHaveBeenCalledWith(+ "warn",+ "local_run.reply_check_failed",+ expect.objectContaining({ runId: run?.runId }),+ );});it.each([diff --git a/apps/node-services/tests/agent/executor/teamhub-runtime-state-client.test.ts b/apps/node-services/tests/agent/executor/teamhub-runtime-state-client.test.tsindex 2bcb8578..0cb2a3a5 100644--- a/apps/node-services/tests/agent/executor/teamhub-runtime-state-client.test.ts+++ b/apps/node-services/tests/agent/executor/teamhub-runtime-state-client.test.ts@@ -223,6 +223,30 @@ describe("TeamHubRuntimeStateClient retries", () => {);});+ it("queries whether a Local Run persisted a reply in TeamHub", async () => {+ const fetchRequest = vi.fn<typeof fetch>(async () =>+ jsonResponse({ replied: true }),+ );+ const client = runtimeStateClient(fetchRequest);++ await expect(+ client.getRunReplyStatus(+ '["meta","agent-reviewer","room","room-1"]',+ "run-1",+ ),+ ).resolves.toEqual({ replied: true });++ const [input, init] = fetchRequest.mock.calls[0]!;+ const url = new URL(requestUrlText(input));+ expect(url.pathname).toBe("/v0/agent-runtime/runs/reply-status");+ expect(url.searchParams.get("context_key")).toBe(+ '["meta","agent-reviewer","room","room-1"]',+ );+ expect(url.searchParams.get("local_run_id")).toBe("run-1");+ expect(init?.method).toBe("GET");+ expect(init?.body).toBeUndefined();+ });+it("retries the exact command after a 5xx and an interrupted 2xx body", async () => {const fetchRequest = vi.fn()diff --git a/apps/node-services/tests/agent/test-support/context-runtime-state.ts b/apps/node-services/tests/agent/test-support/context-runtime-state.tsindex 2cda3d04..eb9dc4a6 100644--- a/apps/node-services/tests/agent/test-support/context-runtime-state.ts+++ b/apps/node-services/tests/agent/test-support/context-runtime-state.ts@@ -169,6 +169,9 @@ export class TestContextRuntimeState implements ContextRuntimeStatePort {getLocalRun(runId: string): LocalRun | null {return structuredClone(this.state.runs.get(runId) ?? null);}+ hasLocalRunReplied(_runId: string, _signal?: AbortSignal): boolean {+ return false;+ }private requireRun(runId: string): LocalRun {const r = this.state.runs.get(runId);if (!r) throw new Error("Local Run is unavailable");diff --git a/apps/node-services/tests/agent/test-support/fake-activator.ts b/apps/node-services/tests/agent/test-support/fake-activator.tsindex 0ba2f5bc..02a3c851 100644--- a/apps/node-services/tests/agent/test-support/fake-activator.ts+++ b/apps/node-services/tests/agent/test-support/fake-activator.ts@@ -359,6 +359,10 @@ class FakeRuntimeState implements ContextRuntimeStatePort {return this.#state.getLocalRun(runId);}+ hasLocalRunReplied(runId: string, signal?: AbortSignal) {+ return this.#state.hasLocalRunReplied(runId, signal);+ }+enqueueSteer(groupId: string, messages: NonEmptyReadonlyArray<Message>) {return this.#state.enqueueSteer(groupId, messages);}diff --git a/apps/teamhub/internal/agentruntimestate/run_session.go b/apps/teamhub/internal/agentruntimestate/run_session.goindex b0da7079..c1ee6007 100644--- a/apps/teamhub/internal/agentruntimestate/run_session.go+++ b/apps/teamhub/internal/agentruntimestate/run_session.go@@ -362,6 +362,24 @@ func (s *Service) GetLocalRun(ctx context.Context, contextKey, runID string) (Loreturn localRunFromRow(ctx, queries, row)}+// GetLocalRunReplyStatus reports whether TeamHub persisted a visible reply for+// the Local Run in its collaboration Room.+func (s *Service) GetLocalRunReplyStatus(ctx context.Context, contextKey, runID string) (bool, error) {+ if s == nil || s.pool == nil || contextKey == "" || runID == "" {+ return false, ErrInvalid+ }+ replied, err := store.New(s.pool).GetAgentLocalRunReplyDelivered(ctx, store.GetAgentLocalRunReplyDeliveredParams{+ ContextKey: contextKey, RunID: runID,+ })+ if isNoRows(err) {+ return false, ErrNotFound+ }+ if err != nil {+ return false, err+ }+ return replied, nil+}+func (s *Service) ContextHasPendingWork(ctx context.Context, contextKey string) (bool, error) {if s == nil || s.pool == nil || contextKey == "" {return false, ErrInvaliddiff --git a/apps/teamhub/internal/agentruntimestate/run_session_test.go b/apps/teamhub/internal/agentruntimestate/run_session_test.goindex 28c51679..6e012fa4 100644--- a/apps/teamhub/internal/agentruntimestate/run_session_test.go+++ b/apps/teamhub/internal/agentruntimestate/run_session_test.go@@ -85,3 +85,26 @@ func TestRuntimeSessionExecutionResourcesEnvelope(t *testing.T) {})t.Run("missing native thread", func(t *testing.T) { check(t, map[string]any{}, "thread-1", nil, ErrConflict) })}++func TestGetLocalRunReplyStatusValidation(t *testing.T) {+ var nilService *Service+ if _, err := nilService.GetLocalRunReplyStatus(t.Context(), "ctx", "run-1"); !errors.Is(err, ErrInvalid) {+ t.Fatalf("nil service error=%v, want %v", err, ErrInvalid)+ }+ service := &Service{}+ for _, tc := range []struct {+ name string+ contextKey string+ runID string+ }{+ {name: "nil pool", contextKey: "ctx", runID: "run-1"},+ {name: "empty context key", contextKey: "", runID: "run-1"},+ {name: "empty run id", contextKey: "ctx", runID: ""},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if _, err := service.GetLocalRunReplyStatus(t.Context(), tc.contextKey, tc.runID); !errors.Is(err, ErrInvalid) {+ t.Fatalf("error=%v, want %v", err, ErrInvalid)+ }+ })+ }+}diff --git a/apps/teamhub/internal/app/contract_server_agent_runtime_state.go b/apps/teamhub/internal/app/contract_server_agent_runtime_state.goindex acb1c1f1..48229c1e 100644--- a/apps/teamhub/internal/app/contract_server_agent_runtime_state.go+++ b/apps/teamhub/internal/app/contract_server_agent_runtime_state.go@@ -201,6 +201,15 @@ func (a *App) getAgentLocalRun(c *gin.Context) {c.JSON(http.StatusOK, response)}+func (a *App) getAgentLocalRunReplyStatus(c *gin.Context) {+ params := contractParams[teamhubinternal.GetAgentLocalRunReplyStatusParams](c)+ replied, err := a.agentRuntimeState.GetLocalRunReplyStatus(c.Request.Context(), params.ContextKey, params.LocalRunId)+ if a.writeAgentRuntimeStateError(c, "get Local Run reply status", err) {+ return+ }+ c.JSON(http.StatusOK, teamhubinternal.AgentLocalRunReplyStatus{Replied: replied})+}+func (a *App) claimAgentLocalRun(c *gin.Context) {var request teamhubinternal.ClaimAgentLocalRunRequestif !a.decodeAgentRuntimeStateBody(c, &request) {diff --git a/apps/teamhub/internal/app/routes_internal.go b/apps/teamhub/internal/app/routes_internal.goindex 3169d359..a0ea7172 100644--- a/apps/teamhub/internal/app/routes_internal.go+++ b/apps/teamhub/internal/app/routes_internal.go@@ -39,6 +39,7 @@ func (a *App) agentServiceRoutes() []contractRoute {route(http.MethodPost, "/v0/agent-runtime/runs/claim", nil, agentService, a.claimAgentLocalRun),route(http.MethodPost, "/v0/agent-runtime/runs/finish", nil, agentService, a.finishAgentLocalRun),route(http.MethodPost, "/v0/agent-runtime/runs/operations", nil, agentService, a.recordAgentLocalRunOperation),+ route(http.MethodGet, "/v0/agent-runtime/runs/reply-status", teamhubinternal.GetAgentLocalRunReplyStatusParams{}, agentService, a.getAgentLocalRunReplyStatus),route(http.MethodPost, "/v0/agent-runtime/runs/requeue", nil, agentService, a.requeueAgentLocalRun),route(http.MethodGet, "/v0/agent-runtime/runs/waiting", nil, agentService, a.listAgentRuntimeWaitingContexts),route(http.MethodGet, "/v0/agent-runtime/session", teamhubinternal.GetAgentRuntimeSessionParams{}, agentService, a.getAgentRuntimeSession),diff --git a/apps/teamhub/internal/store/agent_runtime_state.sql.go b/apps/teamhub/internal/store/agent_runtime_state.sql.goindex 0a2a23d3..a48823b3 100644--- a/apps/teamhub/internal/store/agent_runtime_state.sql.go+++ b/apps/teamhub/internal/store/agent_runtime_state.sql.go@@ -731,6 +731,106 @@ func (q *Queries) GetAgentLocalRunContextKey(ctx context.Context, runID string)return context_key, err}+const getAgentLocalRunReplyDelivered = `-- name: GetAgentLocalRunReplyDelivered :one+WITH target_run AS (+ SELECT run.run_id, run.started_at, run.finished_at,+ context.tenant_id, context.agent_actor_id, context.room_id+ FROM agent_local_runs run+ JOIN agent_execution_contexts context ON context.context_key=run.context_key+ WHERE run.context_key=$1::text+ AND run.run_id=$2::text+),+room_scope AS (+ SELECT target_run.room_id AS id+ FROM target_run+ WHERE target_run.room_id IS NOT NULL+ UNION ALL+ SELECT thread.id+ FROM target_run+ JOIN rooms thread+ ON thread.parent_room_id=target_run.room_id+ AND thread.deleted_at IS NULL+ WHERE target_run.room_id IS NOT NULL+)+SELECT (+ EXISTS (+ SELECT 1+ FROM messages message+ WHERE message.local_run_id=target_run.run_id+ AND message.message_kind='conversation'+ )+ OR EXISTS (+ SELECT 1+ FROM agent_presentation_sequences sequence+ WHERE sequence.local_run_id=target_run.run_id+ )+ OR (+ target_run.started_at IS NOT NULL+ AND target_run.room_id IS NOT NULL+ AND EXISTS (+ SELECT 1+ FROM messages message+ WHERE message.tenant_id=target_run.tenant_id+ AND message.author_actor_id=target_run.agent_actor_id+ AND message.message_kind='conversation'+ AND message.local_run_id IS NULL+ AND message.created_at>=target_run.started_at+ AND (target_run.finished_at IS NULL OR message.created_at<=target_run.finished_at)+ AND message.room_id IN (SELECT id FROM room_scope)+ )+ )+ OR (+ target_run.started_at IS NOT NULL+ AND target_run.room_id IS NOT NULL+ AND EXISTS (+ SELECT 1+ FROM agent_presentation_sequences sequence+ WHERE sequence.tenant_id=target_run.tenant_id+ AND sequence.agent_actor_id=target_run.agent_actor_id+ AND sequence.local_run_id IS NULL+ AND sequence.created_at>=target_run.started_at+ AND (target_run.finished_at IS NULL OR sequence.created_at<=target_run.finished_at)+ AND sequence.room_id IN (SELECT id FROM room_scope)+ )+ )+ OR (+ target_run.started_at IS NOT NULL+ AND target_run.room_id IS NOT NULL+ AND EXISTS (+ SELECT 1+ FROM message_reactions reaction+ WHERE reaction.tenant_id=target_run.tenant_id+ AND reaction.actor_id=target_run.agent_actor_id+ AND reaction.created_at>=target_run.started_at+ AND (target_run.finished_at IS NULL OR reaction.created_at<=target_run.finished_at)+ AND reaction.room_id IN (SELECT id FROM room_scope)+ )+ )+)::boolean AS replied+FROM target_run+`++type GetAgentLocalRunReplyDeliveredParams struct {+ ContextKey string `json:"context_key"`+ RunID string `json:"run_id"`+}++// Checks whether TeamHub persisted a visible reply from the Run: a+// conversation Message or decision card attributed to the Run, a queued+// presentation sequence attributed to the Run, or an unattributed conversation+// Message, presentation sequence, or emoji Reaction written by the Agent in+// the Room or its Threads during the Run. Excluding rows attributed to another+// Run prevents delayed bubbles from an earlier sequence from satisfying this+// Run. The unattributed sequence and reaction branches have no (room_id,+// created_at) index; this query runs only on the suspected-missing-reply path+// and exits early on the indexed local_run_id checks for attributed replies.+func (q *Queries) GetAgentLocalRunReplyDelivered(ctx context.Context, arg GetAgentLocalRunReplyDeliveredParams) (bool, error) {+ row := q.db.QueryRow(ctx, getAgentLocalRunReplyDelivered, arg.ContextKey, arg.RunID)+ var replied bool+ err := row.Scan(&replied)+ return replied, err+}+const getAgentRunStatus = `-- name: GetAgentRunStatus :oneSELECT run.run_id,run.context_key,run.status,run.status_room_id::text AS status_room_id,run.created_at,run.updated_at,diff --git a/apps/teamhub/internal/store/queries/agent_runtime_state.sql b/apps/teamhub/internal/store/queries/agent_runtime_state.sqlindex 644109f0..88ef1f80 100644--- a/apps/teamhub/internal/store/queries/agent_runtime_state.sql+++ b/apps/teamhub/internal/store/queries/agent_runtime_state.sql@@ -638,6 +638,93 @@ FROM agent_local_runsWHERE context_key=sqlc.arg(context_key)::textAND run_id=sqlc.arg(run_id)::text;+-- name: GetAgentLocalRunReplyDelivered :one+-- Checks whether TeamHub persisted a visible reply from the Run: a+-- conversation Message or decision card attributed to the Run, a queued+-- presentation sequence attributed to the Run, or an unattributed conversation+-- Message, presentation sequence, or emoji Reaction written by the Agent in+-- the Room or its Threads during the Run. Excluding rows attributed to another+-- Run prevents delayed bubbles from an earlier sequence from satisfying this+-- Run. The unattributed sequence and reaction branches have no (room_id,+-- created_at) index; this query runs only on the suspected-missing-reply path+-- and exits early on the indexed local_run_id checks for attributed replies.+WITH target_run AS (+ SELECT run.run_id, run.started_at, run.finished_at,+ context.tenant_id, context.agent_actor_id, context.room_id+ FROM agent_local_runs run+ JOIN agent_execution_contexts context ON context.context_key=run.context_key+ WHERE run.context_key=sqlc.arg(context_key)::text+ AND run.run_id=sqlc.arg(run_id)::text+),+room_scope AS (+ SELECT target_run.room_id AS id+ FROM target_run+ WHERE target_run.room_id IS NOT NULL+ UNION ALL+ SELECT thread.id+ FROM target_run+ JOIN rooms thread+ ON thread.parent_room_id=target_run.room_id+ AND thread.deleted_at IS NULL+ WHERE target_run.room_id IS NOT NULL+)+SELECT (+ EXISTS (+ SELECT 1+ FROM messages message+ WHERE message.local_run_id=target_run.run_id+ AND message.message_kind='conversation'+ )+ OR EXISTS (+ SELECT 1+ FROM agent_presentation_sequences sequence+ WHERE sequence.local_run_id=target_run.run_id+ )+ OR (+ target_run.started_at IS NOT NULL+ AND target_run.room_id IS NOT NULL+ AND EXISTS (+ SELECT 1+ FROM messages message+ WHERE message.tenant_id=target_run.tenant_id+ AND message.author_actor_id=target_run.agent_actor_id+ AND message.message_kind='conversation'+ AND message.local_run_id IS NULL+ AND message.created_at>=target_run.started_at+ AND (target_run.finished_at IS NULL OR message.created_at<=target_run.finished_at)+ AND message.room_id IN (SELECT id FROM room_scope)+ )+ )+ OR (+ target_run.started_at IS NOT NULL+ AND target_run.room_id IS NOT NULL+ AND EXISTS (+ SELECT 1+ FROM agent_presentation_sequences sequence+ WHERE sequence.tenant_id=target_run.tenant_id+ AND sequence.agent_actor_id=target_run.agent_actor_id+ AND sequence.local_run_id IS NULL+ AND sequence.created_at>=target_run.started_at+ AND (target_run.finished_at IS NULL OR sequence.created_at<=target_run.finished_at)+ AND sequence.room_id IN (SELECT id FROM room_scope)+ )+ )+ OR (+ target_run.started_at IS NOT NULL+ AND target_run.room_id IS NOT NULL+ AND EXISTS (+ SELECT 1+ FROM message_reactions reaction+ WHERE reaction.tenant_id=target_run.tenant_id+ AND reaction.actor_id=target_run.agent_actor_id+ AND reaction.created_at>=target_run.started_at+ AND (target_run.finished_at IS NULL OR reaction.created_at<=target_run.finished_at)+ AND reaction.room_id IN (SELECT id FROM room_scope)+ )+ )+)::boolean AS replied+FROM target_run;+-- name: ListAgentLocalRunInputs :manySELECT input.*,relation.relation AS run_relation,relation.ordinal AS run_ordinaldiff --git a/apps/teamhub/tests/integration/agent_runtime_state_http_test.go b/apps/teamhub/tests/integration/agent_runtime_state_http_test.goindex af3b2e71..abb00e56 100644--- a/apps/teamhub/tests/integration/agent_runtime_state_http_test.go+++ b/apps/teamhub/tests/integration/agent_runtime_state_http_test.go@@ -255,6 +255,208 @@ func TestAgentRuntimeStateHTTPContractAndRecoveryChain(t *testing.T) {assertAgentRuntimeHTTPError(t, status, body, http.StatusConflict, "CONTEXT_FENCED")}+func TestAgentLocalRunReplyStatus(t *testing.T) {+ allowParallelIntegrationTest(t)+ databaseURL := newIntegrationDatabase(t)+ pool, err := pgxpool.New(t.Context(), databaseURL)+ if err != nil {+ t.Fatalf("open Agent Local Run reply status database: %v", err)+ }+ t.Cleanup(pool.Close)+ seedReadyFixtureComputers(t, pool)+ application, err := newTestApp(context.Background(), config.ForTest(func(c *config.Config) {+ c.DatabaseURL = databaseURL+ c.SessionTTL = time.Hour+ c.CookieName = "teamhub_session"+ c.TeamHubInternalToken = teamHubInternalToken+ c.NodeServicesInternalToken = nodeServicesInternalToken+ c.AgentRunTokenSecret = agentRunTokenSecret+ c.ArtifactStorageRoot = t.TempDir()+ c.ArtifactMaxBytes = 1 << 20+ }), skipping(app.SkillInstall), skipping(app.SkillPackageProbe),+ skipping(app.RoomDocumentJobs), skipping(app.AgentCredentialSweep), skipping(app.PersonalWikiJobs))+ if err != nil {+ t.Fatalf("start TeamHub for reply status test: %v", err)+ }+ t.Cleanup(application.Close)++ const (+ roomID = "http-reply-status-room"+ threadID = "http-reply-status-thread"+ epoch = "http-reply-status-epoch"+ )+ insertRuntimeRoomMembership(t, pool, roomID)+ insertRuntimeRoomMembershipForAgent(t, pool, threadID, "actor_acme_alice")+ for _, stmt := range []string{+ `INSERT INTO messages(id,tenant_id,room_id,author_actor_id,body,segments)+ VALUES('reply-status-root','tenant_acme','http-reply-status-room','actor_acme_alice','Root','[{"type":"text","content":"Root"}]')`,+ `UPDATE rooms SET parent_room_id='http-reply-status-room',root_message_id='reply-status-root'+ WHERE id='http-reply-status-thread' AND tenant_id='tenant_acme'`,+ `INSERT INTO messages(id,tenant_id,room_id,author_actor_id,body,segments)+ VALUES('reply-status-thread-msg','tenant_acme','http-reply-status-thread','actor_acme_alice','In thread','[{"type":"text","content":"In thread"}]')`,+ } {+ if _, err := pool.Exec(t.Context(), stmt); err != nil {+ t.Fatalf("seed reply status Room and Thread: %v", err)+ }+ }++ handler := application.Handler()+ status, body := agentRuntimeStateRequest(t, handler, http.MethodPost, "/v0/agent-runtime/contexts", teamHubInternalToken, map[string]any{+ "target_residency": "active",+ "ref": map[string]any{"kind": "meta", "agent_id": testRuntimeAgentID, "room_id": roomID},+ })+ if status != http.StatusOK {+ t.Fatalf("ensure Context status=%d body=%s", status, body)+ }+ var ensured struct {+ Context struct {+ ContextKey string `json:"context_key"`+ } `json:"context"`+ }+ decode(t, body, &ensured)+ contextKey := ensured.Context.ContextKey++ status, body = agentRuntimeStateRequest(t, handler, http.MethodPost, "/v0/agent-runtime/epochs", teamHubInternalToken, map[string]any{+ "epoch": epoch,+ })+ if status != http.StatusOK {+ t.Fatalf("start epoch status=%d body=%s", status, body)+ }++ queryReplyStatus := func(runID string) (int, []byte) {+ t.Helper()+ path := "/v0/agent-runtime/runs/reply-status?context_key=" + url.QueryEscape(contextKey) + "&local_run_id=" + url.QueryEscape(runID)+ return agentRuntimeStateRequest(t, handler, http.MethodGet, path, teamHubInternalToken, nil)+ }+ assertReplied := func(runID string, want bool) {+ t.Helper()+ code, raw := queryReplyStatus(runID)+ if code != http.StatusOK {+ t.Fatalf("reply status for %s status=%d body=%s", runID, code, raw)+ }+ var result teamhubinternal.AgentLocalRunReplyStatus+ decode(t, raw, &result)+ if result.Replied != want {+ t.Fatalf("reply status for %s replied=%v, want %v", runID, result.Replied, want)+ }+ }+ startRun := func(inputID string) string {+ t.Helper()+ code, raw := agentRuntimeStateRequest(t, handler, http.MethodPost, "/v0/agent-runtime/trusted-turns", teamHubInternalToken, map[string]any{+ "context_key": contextKey, "epoch": epoch,+ "inputs": []any{runtimeHTTPInput(inputID, "question")},+ })+ if code != http.StatusOK {+ t.Fatalf("submit turn %s status=%d body=%s", inputID, code, raw)+ }+ var submitted teamhubinternal.SubmitAgentTrustedTurnResult+ decode(t, raw, &submitted)+ code, raw = agentRuntimeStateRequest(t, handler, http.MethodPost, "/v0/agent-runtime/runs/claim", teamHubInternalToken, map[string]any{+ "context_key": contextKey, "epoch": epoch, "claim_id": "claim-" + inputID,+ })+ if code != http.StatusOK {+ t.Fatalf("claim run %s status=%d body=%s", inputID, code, raw)+ }+ return submitted.RunId+ }+ finishRun := func(runID string) {+ t.Helper()+ code, raw := agentRuntimeStateRequest(t, handler, http.MethodPost, "/v0/agent-runtime/runs/finish", teamHubInternalToken, map[string]any{+ "context_key": contextKey, "epoch": epoch, "run_id": runID,+ "terminal": map[string]any{"type": "succeeded"},+ })+ if code != http.StatusOK {+ t.Fatalf("finish run %s status=%d body=%s", runID, code, raw)+ }+ }++ // Missing Run returns 404 NOT_FOUND.+ status, body = queryReplyStatus("missing-run")+ assertAgentRuntimeHTTPError(t, status, body, http.StatusNotFound, "NOT_FOUND")++ // Seed an older finished Run and an older unattributed message before Run 1 starts.+ run0 := startRun("reply-run-0")+ finishRun(run0)+ if _, err := pool.Exec(t.Context(), `+ INSERT INTO messages(id,tenant_id,room_id,author_actor_id,body,segments,message_kind,created_at)+ VALUES('msg-before-run','tenant_acme',$1,'actor_acme_official','Old reply',+ '[{"type":"text","content":"Old reply"}]'::jsonb,'conversation',clock_timestamp()-interval '1 minute')`, roomID); err != nil {+ t.Fatalf("insert pre-run message: %v", err)+ }++ // Run 1: non-conversation messages and delayed messages attributed to another Run do not count;+ // an attributed conversation message does count.+ run1 := startRun("reply-run-1")+ assertReplied(run1, false)+ for _, stmt := range []struct {+ id string+ kind string+ localID string+ notice any+ }{+ {id: "msg-notice", kind: "room_notice", localID: run1, notice: `{"type":"member_added"}`},+ {id: "msg-runtime", kind: "agent_runtime", localID: run1, notice: nil},+ {id: "msg-other-run", kind: "conversation", localID: run0, notice: nil},+ } {+ if _, err := pool.Exec(t.Context(), `+ INSERT INTO messages(id,tenant_id,room_id,author_actor_id,body,segments,message_kind,local_run_id,notice,created_at)+ VALUES($1,'tenant_acme',$2,'actor_acme_official','Non-reply',+ '[{"type":"text","content":"Non-reply"}]'::jsonb,$3,$4,$5::jsonb,clock_timestamp())`,+ stmt.id, roomID, stmt.kind, stmt.localID, stmt.notice); err != nil {+ t.Fatalf("insert %s: %v", stmt.id, err)+ }+ }+ assertReplied(run1, false)+ insertRuntimeRunMessageFixture(t, pool, roomID, "msg-run1-reply", run1, "Direct reply")+ assertReplied(run1, true)+ finishRun(run1)++ // Run 2: attributed presentation sequence counts even before items deliver into messages.+ run2 := startRun("reply-run-2")+ assertReplied(run2, false)+ if _, err := pool.Exec(t.Context(), `+ INSERT INTO agent_presentation_sequences(id,tenant_id,room_id,agent_actor_id,local_run_id,status)+ VALUES('seq-run2','tenant_acme',$1,'actor_acme_official',$2,'pending')`, roomID, run2); err != nil {+ t.Fatalf("insert attributed sequence: %v", err)+ }+ assertReplied(run2, true)+ finishRun(run2)++ // Run 3: unattributed presentation sequence created during the Run counts.+ run3 := startRun("reply-run-3")+ assertReplied(run3, false)+ if _, err := pool.Exec(t.Context(), `+ INSERT INTO agent_presentation_sequences(id,tenant_id,room_id,agent_actor_id,local_run_id,status,created_at)+ VALUES('seq-run3-unattributed','tenant_acme',$1,'actor_acme_official',NULL,'pending',clock_timestamp())`, roomID); err != nil {+ t.Fatalf("insert unattributed sequence: %v", err)+ }+ assertReplied(run3, true)+ finishRun(run3)++ // Run 4: unattributed conversation message written during the Run counts.+ run4 := startRun("reply-run-4")+ assertReplied(run4, false)+ if _, err := pool.Exec(t.Context(), `+ INSERT INTO messages(id,tenant_id,room_id,author_actor_id,body,segments,message_kind,local_run_id,created_at)+ VALUES('msg-run4-unattributed','tenant_acme',$1,'actor_acme_official','Early reply',+ '[{"type":"text","content":"Early reply"}]'::jsonb,'conversation',NULL,clock_timestamp())`, roomID); err != nil {+ t.Fatalf("insert unattributed message: %v", err)+ }+ assertReplied(run4, true)+ finishRun(run4)++ // Run 5: emoji reaction in a Thread of the Room written during the Run counts.+ run5 := startRun("reply-run-5")+ assertReplied(run5, false)+ if _, err := pool.Exec(t.Context(), `+ INSERT INTO message_reactions(message_id,tenant_id,room_id,actor_id,reaction_id,created_at)+ VALUES('reply-status-thread-msg','tenant_acme',$1,'actor_acme_official','thumbs_up',clock_timestamp())`, threadID); err != nil {+ t.Fatalf("insert thread reaction: %v", err)+ }+ assertReplied(run5, true)+ finishRun(run5)+}+func agentRuntimeStateRequest(t *testing.T,handler http.Handler,diff --git a/contracts/generated/go/teamhubinternal/openapi.gen.go b/contracts/generated/go/teamhubinternal/openapi.gen.goindex 13ecbac6..4d9d5a34 100644--- a/contracts/generated/go/teamhubinternal/openapi.gen.go+++ b/contracts/generated/go/teamhubinternal/openapi.gen.go@@ -2214,6 +2214,12 @@ type AgentLocalRun struct {// AgentLocalRunStatus defines model for AgentLocalRun.Status.type AgentLocalRunStatus string+// AgentLocalRunReplyStatus defines model for AgentLocalRunReplyStatus.+type AgentLocalRunReplyStatus struct {+ // Replied Whether TeamHub persisted a visible reply from this Local Run: a conversation Message or decision card attributed to the Run, a queued presentation sequence attributed to the Run, or an unattributed conversation Message, presentation sequence, or emoji Reaction written by the Context's Agent in the Room or its Threads since the Run started.+ Replied bool `json:"replied"`+}+// AgentMemoryDocument defines model for AgentMemoryDocument.type AgentMemoryDocument struct {Cursors map[string]struct {@@ -4617,6 +4623,12 @@ type GetAgentLocalRunParams struct {LocalRunId LocalRunId `form:"local_run_id" json:"local_run_id"`}+// GetAgentLocalRunReplyStatusParams defines parameters for GetAgentLocalRunReplyStatus.+type GetAgentLocalRunReplyStatusParams struct {+ ContextKey ContextKey `form:"context_key" json:"context_key"`+ LocalRunId LocalRunId `form:"local_run_id" json:"local_run_id"`+}+// GetAgentRuntimeSessionParams defines parameters for GetAgentRuntimeSession.type GetAgentRuntimeSessionParams struct {ContextKey ContextKey `form:"context_key" json:"context_key"`diff --git a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts b/contracts/generated/typescript/src/generated/teamhub-internal/types.tsindex f48c798b..58113d94 100644--- a/contracts/generated/typescript/src/generated/teamhub-internal/types.ts+++ b/contracts/generated/typescript/src/generated/teamhub-internal/types.ts@@ -395,6 +395,22 @@ export interface paths {patch?: never;trace?: never;};+ "/v0/agent-runtime/runs/reply-status": {+ parameters: {+ query?: never;+ header?: never;+ path?: never;+ cookie?: never;+ };+ get: operations["getAgentLocalRunReplyStatus"];+ put?: never;+ post?: never;+ delete?: never;+ options?: never;+ head?: never;+ patch?: never;+ trace?: never;+ };"/v0/agent-runtime/runs/waiting": {parameters: {query?: never;@@ -2052,6 +2068,10 @@ export interface components {[key: string]: unknown;};};+ AgentLocalRunReplyStatus: {+ /** @description Whether TeamHub persisted a visible reply from this Local Run: a conversation Message or decision card attributed to the Run, a queued presentation sequence attributed to the Run, or an unattributed conversation Message, presentation sequence, or emoji Reaction written by the Context's Agent in the Room or its Threads since the Run started. */+ replied: boolean;+ };AgentRuntimeWaitingContexts: {context_keys: components["schemas"]["AgentRuntimeContextKey"][];};@@ -4155,6 +4175,33 @@ export interface operations {500: components["responses"]["InternalError"];};};+ getAgentLocalRunReplyStatus: {+ parameters: {+ query: {+ context_key: components["parameters"]["ContextKey"];+ local_run_id: components["parameters"]["LocalRunId"];+ };+ header?: never;+ path?: never;+ cookie?: never;+ };+ requestBody?: never;+ responses: {+ /** @description Whether TeamHub recorded a visible reply for the Local Run. */+ 200: {+ headers: {+ [name: string]: unknown;+ };+ content: {+ "application/json": components["schemas"]["AgentLocalRunReplyStatus"];+ };+ };+ 400: components["responses"]["BadRequest"];+ 401: components["responses"]["Unauthenticated"];+ 404: components["responses"]["NotFound"];+ 500: components["responses"]["InternalError"];+ };+ };listAgentRuntimeWaitingContexts: {parameters: {query?: never;diff --git a/contracts/generated/typescript/src/teamhub-internal/client.ts b/contracts/generated/typescript/src/teamhub-internal/client.tsindex b14cd00f..98198510 100644--- a/contracts/generated/typescript/src/teamhub-internal/client.ts+++ b/contracts/generated/typescript/src/teamhub-internal/client.ts@@ -344,6 +344,16 @@ export function createTeamHubAgentRuntimeStateClient(options: {) => post("trusted-turns", body, signal),getRun: (contextKey: string, runId: string, signal?: AbortSignal) =>get("run", { context_key: contextKey, local_run_id: runId }, signal),+ getRunReplyStatus: (+ contextKey: string,+ runId: string,+ signal?: AbortSignal,+ ) =>+ get(+ "runs/reply-status",+ { context_key: contextKey, local_run_id: runId },+ signal,+ ),listWaitingContexts: (signal?: AbortSignal) =>get("runs/waiting", {}, signal),claimRun: (body: ClaimAgentLocalRunRequest, signal?: AbortSignal) =>diff --git a/contracts/openapi/components/agent-runtime-state.yaml b/contracts/openapi/components/agent-runtime-state.yamlindex 628dc4c6..67e3c4d7 100644--- a/contracts/openapi/components/agent-runtime-state.yaml+++ b/contracts/openapi/components/agent-runtime-state.yaml@@ -658,6 +658,20 @@ components:terminal:type: objectadditionalProperties: true+ AgentLocalRunReplyStatus:+ type: object+ additionalProperties: false+ required: [replied]+ properties:+ replied:+ type: boolean+ description: >-+ Whether TeamHub persisted a visible reply from this Local Run: a+ conversation Message or decision card attributed to the Run, a+ queued presentation sequence attributed to the Run, or an+ unattributed conversation Message, presentation sequence, or emoji+ Reaction written by the Context's Agent in the Room or its Threads+ since the Run started.ClaimAgentLocalRunRequest:type: objectadditionalProperties: falsediff --git a/contracts/openapi/paths/teamhub-agent-runtime-state.yaml b/contracts/openapi/paths/teamhub-agent-runtime-state.yamlindex ccba27a9..8531c25d 100644--- a/contracts/openapi/paths/teamhub-agent-runtime-state.yaml+++ b/contracts/openapi/paths/teamhub-agent-runtime-state.yaml@@ -407,6 +407,29 @@ getRun:"500":$ref: "../components/common.yaml#/components/responses/InternalError"+getRunReplyStatus:+ get:+ tags: [Agent Runtime State]+ operationId: getAgentLocalRunReplyStatus+ parameters:+ - $ref: "#/components/parameters/ContextKey"+ - $ref: "#/components/parameters/LocalRunId"+ responses:+ "200":+ description: Whether TeamHub recorded a visible reply for the Local Run.+ content:+ application/json:+ schema:+ $ref: "../components/agent-runtime-state.yaml#/components/schemas/AgentLocalRunReplyStatus"+ "400":+ $ref: "../components/common.yaml#/components/responses/BadRequest"+ "401":+ $ref: "../components/common.yaml#/components/responses/Unauthenticated"+ "404":+ $ref: "../components/common.yaml#/components/responses/NotFound"+ "500":+ $ref: "../components/common.yaml#/components/responses/InternalError"+claimRun:post:tags: [Agent Runtime State]diff --git a/contracts/openapi/teamhub-internal/openapi.yaml b/contracts/openapi/teamhub-internal/openapi.yamlindex b8512277..1b8f9454 100644--- a/contracts/openapi/teamhub-internal/openapi.yaml+++ b/contracts/openapi/teamhub-internal/openapi.yaml@@ -188,6 +188,8 @@ paths:$ref: ../paths/teamhub-agent-runtime-state.yaml#/submitTrustedTurn/v0/agent-runtime/run:$ref: ../paths/teamhub-agent-runtime-state.yaml#/getRun+ /v0/agent-runtime/runs/reply-status:+ $ref: ../paths/teamhub-agent-runtime-state.yaml#/getRunReplyStatus/v0/agent-runtime/runs/waiting:$ref: ../paths/teamhub-agent-runtime-state.yaml#/waitingRuns/v0/agent-runtime/runs/claim:diff --git a/contracts/tests/teamhub-agent-callback-client.contract.test.ts b/contracts/tests/teamhub-agent-callback-client.contract.test.tsindex 291e9272..8e249c29 100644--- a/contracts/tests/teamhub-agent-callback-client.contract.test.ts+++ b/contracts/tests/teamhub-agent-callback-client.contract.test.ts@@ -86,22 +86,33 @@ describe("generated TeamHub Agent service epoch and Run client", () => {};await client.startEpoch(start);await client.claimRun(claim);+ await client.getRunReplyStatus(claim.context_key, "run-one");expect(requests.map(({ url }) => url)).toEqual(["https://teamhub.example/api/v0/agent-runtime/epochs","https://teamhub.example/api/v0/agent-runtime/runs/claim",+ `https://teamhub.example/api/v0/agent-runtime/runs/reply-status?context_key=${encodeURIComponent(claim.context_key)}&local_run_id=run-one`,+ ]);+ expect(requests.map(({ method }) => method)).toEqual([+ "POST",+ "POST",+ "GET",]);- expect(requests.map(({ method }) => method)).toEqual(["POST", "POST"]);expect(- requests.map(({ headers }) => Object.fromEntries(headers.entries())),+ requests+ .slice(0, 2)+ .map(({ headers }) => Object.fromEntries(headers.entries())),).toEqual(Array.from({ length: 2 }, () => ({authorization: "Bearer service-token","content-type": "application/json",})),);+ expect(Object.fromEntries(requests[2]!.headers.entries())).toEqual({+ authorization: "Bearer service-token",+ });expect(- await Promise.all(requests.map((request) => request.json())),+ await Promise.all(requests.slice(0, 2).map((request) => request.json())),).toEqual([start, claim]);});});