Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(desktop): render huge cloud transcripts and real send errors (#82979)

Charles Vien69176b4903df
diff --git a/products/desktop/packages/api-client/src/posthog-client.test.ts b/products/desktop/packages/api-client/src/posthog-client.test.ts
index 51e5525e6a5f..1b6aff898246 100644
--- a/products/desktop/packages/api-client/src/posthog-client.test.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.test.ts
@@ -5,6 +5,7 @@ import {
CloudUsageLimitError,
DESKTOP_BILLING_LIMIT_ERROR_CODE,
PostHogAPIClient,
+ SESSION_LOGS_PAGE_TIMEOUT_MS,
} from "./posthog-client";
describe("PostHogAPIClient", () => {
@@ -2030,11 +2031,19 @@ describe("PostHogAPIClient", () => {
}));
}
- function page(entries: unknown[], hasMore: boolean) {
+ function page(
+ entries: unknown[],
+ hasMore: boolean,
+ matchingCount?: number,
+ ) {
+ const headers = new Headers({ "X-Has-More": String(hasMore) });
+ if (matchingCount !== undefined) {
+ headers.set("X-Matching-Count", String(matchingCount));
+ }
return {
ok: true,
json: async () => entries,
- headers: new Headers({ "X-Has-More": String(hasMore) }),
+ headers,
};
}
@@ -2141,6 +2150,169 @@ describe("PostHogAPIClient", () => {
});
});
+ it("fetches the newest entries when the log exceeds the requested cap", async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(page(makeEntries(5000, "head"), true, 9000))
+ .mockResolvedValueOnce(page(makeEntries(5000, "tail-a"), true, 9000))
+ .mockResolvedValueOnce(page(makeEntries(1000, "tail-b"), false, 9000));
+ const client = makeClient(fetch);
+
+ const result = await client.getTaskRunSessionLogsResult(
+ "task-1",
+ "run-1",
+ { limit: 6000 },
+ );
+
+ expect(result.complete).toBe(true);
+ expect(result.truncatedHeadCount).toBe(3000);
+ expect(result.entries).toHaveLength(6000);
+ expect(
+ (result.entries[0] as { notification: { method: string } }).notification
+ .method,
+ ).toBe("tail-a-0");
+ expect(fetch).toHaveBeenCalledTimes(3);
+ expect(requestedParams(fetch.mock.calls[1][0])).toEqual({
+ limit: "5000",
+ offset: "3000",
+ });
+ expect(requestedParams(fetch.mock.calls[2][0])).toEqual({
+ limit: "1000",
+ offset: "8000",
+ });
+ });
+
+ it("does not refetch when the matching count equals the cap", async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValue(page(makeEntries(5000, "a"), false, 5000));
+ const client = makeClient(fetch);
+
+ const result = await client.getTaskRunSessionLogsResult(
+ "task-1",
+ "run-1",
+ { limit: 5000 },
+ );
+
+ expect(result.complete).toBe(true);
+ expect(result.truncatedHeadCount).toBe(0);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("retries a rejected page fetch once and keeps paginating", async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(page(makeEntries(50, "a"), true))
+ .mockRejectedValueOnce(new Error("socket hang up"))
+ .mockResolvedValueOnce(page(makeEntries(10, "b"), false));
+ const client = makeClient(fetch);
+
+ const result = await client.getTaskRunSessionLogsResult(
+ "task-1",
+ "run-1",
+ { limit: 100000 },
+ );
+
+ expect(result.complete).toBe(true);
+ expect(result.entries).toHaveLength(60);
+ expect(fetch).toHaveBeenCalledTimes(3);
+ expect(
+ (fetch.mock.calls[0][0] as { overrides: { signal: unknown } }).overrides
+ .signal,
+ ).toBeInstanceOf(AbortSignal);
+ });
+
+ it("does not retry a definite client error", async () => {
+ const fetch = vi.fn().mockRejectedValue(new ApiRequestError(404, "{}"));
+ const client = makeClient(fetch);
+
+ const result = await client.getTaskRunSessionLogsResult(
+ "task-1",
+ "run-1",
+ { limit: 100000 },
+ );
+
+ expect(result.complete).toBe(false);
+ expect(fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it("gives up after a second rejection on the same page", async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce(page(makeEntries(50, "a"), true))
+ .mockRejectedValue(new Error("socket hang up"));
+ const client = makeClient(fetch);
+
+ const result = await client.getTaskRunSessionLogsResult(
+ "task-1",
+ "run-1",
+ { limit: 100000 },
+ );
+
+ expect(result.complete).toBe(false);
+ expect(result.entries).toHaveLength(50);
+ expect(fetch).toHaveBeenCalledTimes(3);
+ });
+
+ it("retries a page whose body read fails", async () => {
+ const fetch = vi
+ .fn()
+ .mockResolvedValueOnce({
+ ok: true,
+ json: async () => {
+ throw new Error("terminated");
+ },
+ headers: new Headers({ "X-Has-More": "true" }),
+ })
+ .mockResolvedValueOnce(page(makeEntries(10, "a"), false));
+ const client = makeClient(fetch);
+
+ const result = await client.getTaskRunSessionLogsResult(
+ "task-1",
+ "run-1",
+ { limit: 100000 },
+ );
+
+ expect(result.complete).toBe(true);
+ expect(result.entries).toHaveLength(10);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ });
+
+ it("aborts a page whose body stalls after the headers arrive", async () => {
+ vi.useFakeTimers();
+ try {
+ const fetch = vi
+ .fn()
+ .mockImplementation((call: { overrides: { signal: AbortSignal } }) =>
+ Promise.resolve({
+ ok: true,
+ json: () =>
+ new Promise((_resolve, reject) => {
+ call.overrides.signal.addEventListener("abort", () =>
+ reject(call.overrides.signal.reason),
+ );
+ }),
+ headers: new Headers({ "X-Has-More": "false" }),
+ }),
+ );
+ const client = makeClient(fetch);
+
+ const pending = client.getTaskRunSessionLogsResult("task-1", "run-1", {
+ limit: 100000,
+ });
+ // Once for the first attempt, once for its retry.
+ await vi.advanceTimersByTimeAsync(SESSION_LOGS_PAGE_TIMEOUT_MS);
+ await vi.advanceTimersByTimeAsync(SESSION_LOGS_PAGE_TIMEOUT_MS);
+
+ const result = await pending;
+ expect(result.complete).toBe(false);
+ expect(result.entries).toHaveLength(0);
+ expect(fetch).toHaveBeenCalledTimes(2);
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
it("marks entries collected before a failed page as incomplete", async () => {
const fetch = vi
.fn()
@@ -2159,7 +2331,11 @@ describe("PostHogAPIClient", () => {
{ limit: 100000 },
);
- expect(result).toEqual({ entries: expect.any(Array), complete: false });
+ expect(result).toEqual({
+ entries: expect.any(Array),
+ complete: false,
+ truncatedHeadCount: 0,
+ });
expect(result.entries).toHaveLength(50);
expect(fetch).toHaveBeenCalledTimes(2);
});
diff --git a/products/desktop/packages/api-client/src/posthog-client.ts b/products/desktop/packages/api-client/src/posthog-client.ts
index ba5b0b6d1649..904484adc745 100644
--- a/products/desktop/packages/api-client/src/posthog-client.ts
+++ b/products/desktop/packages/api-client/src/posthog-client.ts
@@ -218,12 +218,18 @@ export const DESKTOP_BILLING_LIMIT_ERROR_CODE =
"posthog_code_billing_limit_exceeded";
export const SESSION_LOGS_MAX_PAGE_SIZE = 5000;
+export const SESSION_LOGS_PAGE_TIMEOUT_MS = 30_000;
export interface TaskRunSessionLogsResult {
entries: StoredLogEntry[];
complete: boolean;
+ truncatedHeadCount: number;
}
+type SessionLogsPage =
+ | { ok: true; entries: StoredLogEntry[]; headers: Headers }
+ | { ok: false; status: number; statusText: string };
+
export interface TaskListOptions {
repository?: string;
createdBy?: number;
@@ -3685,6 +3691,49 @@ export class PostHogAPIClient {
.entries;
}
+ // AbortController + setTimeout because Hermes, which runs this client on
+ // mobile, has no AbortSignal.timeout.
+ private async fetchSessionLogsPage(
+ url: URL,
+ path: string,
+ offset: number,
+ ): Promise<SessionLogsPage> {
+ for (let attempt = 0; ; attempt++) {
+ const controller = new AbortController();
+ const timer = setTimeout(
+ () =>
+ controller.abort(new Error("Session logs page request timed out")),
+ SESSION_LOGS_PAGE_TIMEOUT_MS,
+ );
+ try {
+ const response = await this.api.fetcher.fetch({
+ method: "get",
+ url,
+ path,
+ overrides: { signal: controller.signal },
+ });
+ if (!response.ok) {
+ return {
+ ok: false,
+ status: response.status,
+ statusText: response.statusText,
+ };
+ }
+ // Read the body here, while the timer is still armed: fetch resolves on
+ // headers, and a page body stalling after them is what wedges hydration.
+ const entries = (await response.json()) as StoredLogEntry[];
+ return { ok: true, entries, headers: response.headers };
+ } catch (err) {
+ const status = requestErrorStatus(err);
+ const retryable = status === undefined || status >= 500;
+ if (attempt > 0 || !retryable) throw err;
+ log.warn(`Retrying session logs page at offset ${offset}`, err);
+ } finally {
+ clearTimeout(timer);
+ }
+ }
+ }
+
async getTaskRunSessionLogsResult(
taskId: string,
runId: string,
@@ -3692,10 +3741,12 @@ export class PostHogAPIClient {
): Promise<TaskRunSessionLogsResult> {
const maxEntries = options?.limit ?? SESSION_LOGS_MAX_PAGE_SIZE;
const entries: StoredLogEntry[] = [];
+ let truncatedHeadCount = 0;
try {
const teamId = await this.getTeamId();
const path = `/api/projects/${teamId}/tasks/${taskId}/runs/${runId}/session_logs/`;
let offset = 0;
+ let isFirstPage = true;
while (entries.length < maxEntries) {
const url = new URL(`${this.api.baseUrl}${path}`);
url.searchParams.set(
@@ -3710,31 +3761,38 @@ export class PostHogAPIClient {
if (options?.after) {
url.searchParams.set("after", options.after);
}
- const response = await this.api.fetcher.fetch({
- method: "get",
- url,
- path,
- });
+ const page = await this.fetchSessionLogsPage(url, path, offset);
- if (!response.ok) {
+ if (!page.ok) {
log.warn(
- `Failed to fetch session logs page at offset ${offset}: ${response.status} ${response.statusText}`,
+ `Failed to fetch session logs page at offset ${offset}: ${page.status} ${page.statusText}`,
);
- return { entries, complete: false };
+ return { entries, complete: false, truncatedHeadCount };
}
- const page = (await response.json()) as StoredLogEntry[];
- entries.push(...page);
- const hasMore = response.headers.get("X-Has-More") === "true";
- if (!hasMore || page.length === 0) {
- return { entries, complete: true };
+ if (isFirstPage) {
+ isFirstPage = false;
+ const matchingCount = Number(page.headers.get("X-Matching-Count"));
+ if (Number.isFinite(matchingCount) && matchingCount > maxEntries) {
+ // Restart from the tail so the newest maxEntries survive the cap.
+ truncatedHeadCount = matchingCount - maxEntries;
+ offset = truncatedHeadCount;
+ continue;
+ }
+ }
+ entries.push(...page.entries);
+ const hasMore = page.headers.get("X-Has-More") === "true";
+ if (!hasMore || page.entries.length === 0) {
+ return { entries, complete: true, truncatedHeadCount };
}
- offset += page.length;
+ offset += page.entries.length;
}
- return { entries, complete: false };
+ // A deliberate tail fetch is complete; capping out without a matching
+ // count means unknown loss.
+ return { entries, complete: truncatedHeadCount > 0, truncatedHeadCount };
} catch (err) {
log.warn("Failed to fetch task run session logs", err);
- return { entries, complete: false };
+ return { entries, complete: false, truncatedHeadCount };
}
}
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index 12737e254c79..cb56f8737a5d 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -9,9 +9,11 @@ import type {
SessionConfigSelectOption,
SessionUpdate,
} from "@agentclientprotocol/sdk";
+import { requestErrorStatus } from "@posthog/api-client/fetcher";
import type {
CreateResourceCommentRequest,
ResourceComment,
+ TaskRunSessionLogsResult,
} from "@posthog/api-client/posthog-client";
import {
type AcpMessage,
@@ -4435,8 +4437,14 @@ export class SessionService {
// sandbox that hits the same provisioning failure — surface the error
// instead of looping.
if (session.cloudStatus === "failed" && session.status !== "connected") {
+ let errorMessage = session.cloudErrorMessage;
+ if (!errorMessage) {
+ await this.refreshCloudRunStatus(session);
+ errorMessage =
+ this.d.store.getSessions()[session.taskRunId]?.cloudErrorMessage;
+ }
throw new Error(
- session.cloudErrorMessage ??
+ errorMessage ??
"Cloud run couldn't start. Check that GitHub is connected for this project, then try again.",
);
}
@@ -4827,29 +4835,45 @@ export class SessionService {
runtimeOptions = getCloudRuntimeOptions(session, previousRun);
- // Backend derives the snapshot from resumeFromRunId and restores the sandbox.
- updatedTask = await authCredentials.client.runTaskInCloud(
- session.taskId,
- previousBaseBranch,
- {
- adapter: runtimeOptions.adapter,
- model: runtimeOptions.model,
- reasoningLevel: runtimeOptions.reasoningLevel,
- initialPermissionMode: runtimeOptions.initialPermissionMode,
- resumeFromRunId: session.taskRunId,
- pendingUserMessage: transport.messageText,
- pendingUserArtifactIds:
- artifactIds.length > 0 ? artifactIds : undefined,
- prAuthorshipMode,
- autoPublish: previousState.auto_publish === true || undefined,
- rtkEnabled: this.d.settings.rtkEnabledCloud,
- runSource: getCloudRunSource(previousState),
- signalReportId:
- typeof previousState.signal_report_id === "string"
- ? previousState.signal_report_id
- : undefined,
- },
- );
+ try {
+ // Backend derives the snapshot from resumeFromRunId and restores the sandbox.
+ updatedTask = await authCredentials.client.runTaskInCloud(
+ session.taskId,
+ previousBaseBranch,
+ {
+ adapter: runtimeOptions.adapter,
+ model: runtimeOptions.model,
+ reasoningLevel: runtimeOptions.reasoningLevel,
+ initialPermissionMode: runtimeOptions.initialPermissionMode,
+ resumeFromRunId: session.taskRunId,
+ pendingUserMessage: transport.messageText,
+ pendingUserArtifactIds:
+ artifactIds.length > 0 ? artifactIds : undefined,
+ prAuthorshipMode,
+ autoPublish: previousState.auto_publish === true || undefined,
+ rtkEnabled: this.d.settings.rtkEnabledCloud,
+ runSource: getCloudRunSource(previousState),
+ signalReportId:
+ typeof previousState.signal_report_id === "string"
+ ? previousState.signal_report_id
+ : undefined,
+ },
+ );
+ } catch (error) {
+ // Only the resume call gates on authorship: non-creators of a channeled
+ // task get a 404 (not a 403) here, so on a task the app can already read
+ // it means the control gate. 404s from the upload or run fetch above
+ // mean a missing resource, so those keep their real error.
+ if (
+ requestErrorStatus(error) === 404 &&
+ session.isTaskAuthor === false
+ ) {
+ throw new Error(
+ "Only the person who created this task can send it messages. Start a new session to continue the work yourself.",
+ );
+ }
+ throw error;
+ }
} catch (error) {
rollbackOptimisticPrompt();
throw error;
@@ -6483,6 +6507,21 @@ export class SessionService {
);
}
+ private logHydrationTruncation(
+ taskId: string,
+ runId: string,
+ result: TaskRunSessionLogsResult,
+ ): void {
+ if (result.truncatedHeadCount > 0) {
+ this.d.log.info("Session log hydration dropped oldest entries", {
+ taskId,
+ runId,
+ truncatedHeadCount: result.truncatedHeadCount,
+ hydratedCount: result.entries.length,
+ });
+ }
+ }
+
private async performCloudTaskSessionHydration(
taskId: string,
taskRunId: string,
@@ -6494,6 +6533,10 @@ export class SessionService {
let rawEntries: StoredLogEntry[];
let liveStreamLineCount: number;
let resumeLeafEntryStartIndex: number | undefined;
+ // How many entries the tail fetch dropped off the front of rawEntries. The
+ // stream cursors count from the start of the chain, and the engine's own
+ // totals still include those entries, so they have to be added back.
+ let truncatedHeadCount = 0;
const resumeFromRunId =
typeof runState?.resume_from_run_id === "string"
? runState.resume_from_run_id
@@ -6525,7 +6568,9 @@ export class SessionService {
});
return;
}
+ this.logHydrationTruncation(taskId, taskRunId, result);
rawEntries = result.entries;
+ truncatedHeadCount = result.truncatedHeadCount;
const markedLeafStart = rawEntries.findIndex(
(entry) => getEntryTaskRunMarker(entry) === taskRunId,
);
@@ -6558,6 +6603,11 @@ export class SessionService {
});
return;
}
+ this.logHydrationTruncation(taskId, resumeFromRunId, ancestorResult);
+ this.logHydrationTruncation(taskId, taskRunId, currentRunResult);
+ // rawEntries below starts at the ancestor window, so only the
+ // ancestor fetch's drop moves the front of the chain.
+ truncatedHeadCount = ancestorResult.truncatedHeadCount;
const ancestorEntries: StoredLogEntry[] = ancestorResult.entries;
const currentRunEntries: StoredLogEntry[] = currentRunResult.entries;
const ancestorKeys = ancestorEntries.map((entry) =>
@@ -6598,7 +6648,9 @@ export class SessionService {
});
return;
}
+ this.logHydrationTruncation(taskId, taskRunId, result);
rawEntries = result.entries;
+ truncatedHeadCount = result.truncatedHeadCount;
liveStreamLineCount = rawEntries.length;
// A terminal run whose persisted chain comes back empty can still
// have a complete S3 session log (persistence raced teardown); fall
@@ -6607,6 +6659,7 @@ export class SessionService {
const parsed = await this.fetchSessionLogs(logUrl, taskRunId);
if (parsed.rawEntries.length > 0) {
rawEntries = parsed.rawEntries;
+ truncatedHeadCount = 0;
liveStreamLineCount = parsed.totalLineCount;
}
}
@@ -6687,11 +6740,12 @@ export class SessionService {
};
}
+ const chainEntryCount = rawEntries.length + truncatedHeadCount;
// If live updates already populated a processed count, don't overwrite
// that newer state with the persisted baseline fetched during startup.
// Terminal hydration is different: it is the final transcript, so apply
// it whenever the persisted chain has more lines than the local stream.
- const effectiveLineCount = Math.max(liveStreamLineCount, rawEntries.length);
+ const effectiveLineCount = Math.max(liveStreamLineCount, chainEntryCount);
const alreadyApplied = isTerminalRun
? (session.processedLineCount ?? 0) >= effectiveLineCount
: session.processedLineCount !== undefined &&
@@ -6701,7 +6755,7 @@ export class SessionService {
this.surfacePersistedPendingPermissions(taskRunId, rawEntries);
this.pendingPermissionHydratedRuns.add(taskRunId);
return {
- historyEntryCount: rawEntries.length,
+ historyEntryCount: chainEntryCount,
liveStreamLineCount: session.processedLineCount ?? liveStreamLineCount,
};
}
@@ -6719,7 +6773,7 @@ export class SessionService {
events,
isCloud: true,
logUrl: logUrl ?? session.logUrl,
- cloudTranscriptEntryCount: rawEntries.length,
+ cloudTranscriptEntryCount: chainEntryCount,
// Terminal hydration records the whole chain as processed so nothing
// re-applies it; live resume runs keep the leaf-stream cursor.
processedLineCount: isTerminalRun
@@ -6736,7 +6790,7 @@ export class SessionService {
this.clearTerminalCloudPromptState(taskRunId);
}
return {
- historyEntryCount: rawEntries.length,
+ historyEntryCount: chainEntryCount,
liveStreamLineCount,
};
}
diff --git a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
index 658ceb2faf19..953d0e65d6e0 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -3,6 +3,7 @@ import type {
SessionConfigOption,
SessionConfigSelectGroup,
} from "@agentclientprotocol/sdk";
+import { ApiRequestError } from "@posthog/api-client/fetcher";
import type { AcpMessage } from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
import type { AgentSession } from "@posthog/ui/features/sessions/sessionStore";
@@ -499,6 +500,7 @@ describe("SessionService", () => {
mockAuthenticatedClient.getTaskRunSessionLogsResult.mockResolvedValue({
entries: [],
complete: true,
+ truncatedHeadCount: 0,
});
mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(undefined);
mockSessionStoreSetters.getSessions.mockReturnValue({});
@@ -1720,6 +1722,7 @@ describe("SessionService", () => {
mockAuthenticatedClient.getTaskRunSessionLogsResult.mockResolvedValue({
entries: finalEntries,
complete: true,
+ truncatedHeadCount: 0,
});
mockConvertStoredEntriesToEvents.mockReturnValueOnce(finalEvents);
@@ -1767,6 +1770,57 @@ describe("SessionService", () => {
);
});
+ it("counts a truncated head into the stream cursors", async () => {
+ const service = getSessionService();
+ const session = createMockSession({
+ taskId: "task-123",
+ taskRunId: "run-123",
+ cloudStatus: "in_progress",
+ isCloud: true,
+ events: [],
+ processedLineCount: 1,
+ });
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(session);
+ mockSessionStoreSetters.getSessions.mockReturnValue({
+ "run-123": session,
+ });
+ mockAuthenticatedClient.getTaskRunSessionLogsResult.mockResolvedValue({
+ entries: [
+ { timestamp: "2024-01-01T00:00:00Z", notification: {} },
+ { timestamp: "2024-01-01T00:01:00Z", notification: {} },
+ ],
+ complete: true,
+ truncatedHeadCount: 5,
+ });
+
+ service.watchCloudTask(
+ "task-123",
+ "run-123",
+ "https://api.anthropic.com",
+ 123,
+ undefined,
+ "https://example.com/logs/run-123",
+ undefined,
+ "claude",
+ undefined,
+ undefined,
+ undefined,
+ "completed",
+ );
+
+ // The cloud stream still counts the dropped entries, so a cursor of 2
+ // would make every later total look 5 entries ahead of the transcript.
+ await vi.waitFor(() => {
+ expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(
+ "run-123",
+ expect.objectContaining({
+ cloudTranscriptEntryCount: 7,
+ processedLineCount: 7,
+ }),
+ );
+ });
+ });
+
it("falls back to the run log URL when terminal chain hydration is empty", async () => {
const service = getSessionService();
const session = createMockSession({
@@ -1904,16 +1958,22 @@ describe("SessionService", () => {
let resolveFirstHydration!: (result: {
entries: Array<{ timestamp: string; notification: object }>;
complete: boolean;
+ truncatedHeadCount: number;
}) => void;
const firstHydration = new Promise<{
entries: Array<{ timestamp: string; notification: object }>;
complete: boolean;
+ truncatedHeadCount: number;
}>((resolve) => {
resolveFirstHydration = resolve;
});
mockAuthenticatedClient.getTaskRunSessionLogsResult
.mockReturnValueOnce(firstHydration)
- .mockResolvedValueOnce({ entries: [], complete: true });
+ .mockResolvedValueOnce({
+ entries: [],
+ complete: true,
+ truncatedHeadCount: 0,
+ });
service.watchCloudTask(
"task-123",
@@ -1964,7 +2024,11 @@ describe("SessionService", () => {
mockAuthenticatedClient.getTaskRunSessionLogsResult,
).toHaveBeenCalledTimes(3);
});
- resolveFirstHydration({ entries: [], complete: true });
+ resolveFirstHydration({
+ entries: [],
+ complete: true,
+ truncatedHeadCount: 0,
+ });
});
it("keeps the settled terminal cursor when a resume-chain hydration resolves late", async () => {
@@ -1996,10 +2060,12 @@ describe("SessionService", () => {
let resolveAncestor!: (r: {
entries: object[];
complete: boolean;
+ truncatedHeadCount: number;
}) => void;
let resolveCurrent!: (r: {
entries: object[];
complete: boolean;
+ truncatedHeadCount: number;
}) => void;
mockAuthenticatedClient.getTaskRunSessionLogsResult
.mockReturnValueOnce(
@@ -2041,8 +2107,16 @@ describe("SessionService", () => {
session.cloudStatus = "completed";
session.processedLineCount = 5;
- resolveAncestor({ entries: [entry("a"), entry("b")], complete: true });
- resolveCurrent({ entries: [entry("c")], complete: true });
+ resolveAncestor({
+ entries: [entry("a"), entry("b")],
+ complete: true,
+ truncatedHeadCount: 0,
+ });
+ resolveCurrent({
+ entries: [entry("c")],
+ complete: true,
+ truncatedHeadCount: 0,
+ });
// The late resume-chain write must not lower the settled cursor to its
// leaf-only count.
@@ -4162,6 +4236,7 @@ describe("SessionService", () => {
});
mockAuthenticatedClient.getTaskRunSessionLogsResult.mockResolvedValue({
complete: true,
+ truncatedHeadCount: 0,
entries: [
{
type: "notification",
@@ -4394,7 +4469,11 @@ describe("SessionService", () => {
{ timestamp: "2024-01-01T00:01:00Z", notification: {} },
];
mockAuthenticatedClient.getTaskRunSessionLogsResult
- .mockResolvedValueOnce({ entries: parentEntries, complete: true })
+ .mockResolvedValueOnce({
+ entries: parentEntries,
+ complete: true,
+ truncatedHeadCount: 0,
+ })
.mockResolvedValueOnce({
entries:
responseShape === "full"
@@ -4403,6 +4482,7 @@ describe("SessionService", () => {
? [parentEntries[1], ...leafEntries]
: leafEntries,
complete: true,
+ truncatedHeadCount: 0,
});
mockTrpcLogs.readLocalLogs.query.mockResolvedValue(
JSON.stringify(leafEntries[0]),
@@ -4591,8 +4671,16 @@ describe("SessionService", () => {
notification: {},
};
mockAuthenticatedClient.getTaskRunSessionLogsResult
- .mockResolvedValueOnce({ entries: [parentEntry], complete: true })
- .mockResolvedValueOnce({ entries: [parentEntry], complete: true });
+ .mockResolvedValueOnce({
+ entries: [parentEntry],
+ complete: true,
+ truncatedHeadCount: 0,
+ })
+ .mockResolvedValueOnce({
+ entries: [parentEntry],
+ complete: true,
+ truncatedHeadCount: 0,
+ });
mockTrpcLogs.readLocalLogs.query.mockResolvedValue("");
mockTrpcLogs.fetchS3Logs.query.mockResolvedValue("");
mockConvertStoredEntriesToEvents.mockReturnValueOnce([
@@ -4691,8 +4779,16 @@ describe("SessionService", () => {
notification: {},
};
mockAuthenticatedClient.getTaskRunSessionLogsResult
- .mockResolvedValueOnce({ entries: [parentEntry], complete: true })
- .mockResolvedValueOnce({ entries: [parentEntry], complete: true });
+ .mockResolvedValueOnce({
+ entries: [parentEntry],
+ complete: true,
+ truncatedHeadCount: 0,
+ })
+ .mockResolvedValueOnce({
+ entries: [parentEntry],
+ complete: true,
+ truncatedHeadCount: 0,
+ });
mockTrpcLogs.readLocalLogs.query.mockResolvedValue("");
mockTrpcLogs.fetchS3Logs.query.mockResolvedValue("");
mockConvertStoredEntriesToEvents.mockReturnValueOnce([
@@ -4807,6 +4903,7 @@ describe("SessionService", () => {
let resolveAncestor!: (result: {
entries: typeof ancestorEntries;
complete: boolean;
+ truncatedHeadCount: number;
}) => void;
mockAuthenticatedClient.getTaskRunSessionLogsResult
.mockImplementationOnce(
@@ -4818,6 +4915,7 @@ describe("SessionService", () => {
.mockResolvedValueOnce({
entries: [...ancestorEntries, leafEntry],
complete: true,
+ truncatedHeadCount: 0,
});
mockTrpcLogs.readLocalLogs.query.mockResolvedValue(
JSON.stringify(leafEntry),
@@ -4861,7 +4959,11 @@ describe("SessionService", () => {
});
expect(mockSessionStoreSetters.appendEvents).not.toHaveBeenCalled();
- resolveAncestor({ entries: ancestorEntries, complete: true });
+ resolveAncestor({
+ entries: ancestorEntries,
+ complete: true,
+ truncatedHeadCount: 0,
+ });
await vi.waitFor(() => {
expect(mockSessionStoreSetters.appendEvents).toHaveBeenCalledWith(
"run-456",
@@ -5021,6 +5123,7 @@ describe("SessionService", () => {
let resolveInherited!: (result: {
entries: typeof inheritedEntries;
complete: boolean;
+ truncatedHeadCount: number;
}) => void;
mockAuthenticatedClient.getTaskRunSessionLogsResult
.mockImplementationOnce(
@@ -5032,6 +5135,7 @@ describe("SessionService", () => {
.mockResolvedValueOnce({
entries: [...inheritedEntries, cEntry],
complete: true,
+ truncatedHeadCount: 0,
});
mockTrpcLogs.readLocalLogs.query.mockResolvedValue(
JSON.stringify(cEntry),
@@ -5067,7 +5171,11 @@ describe("SessionService", () => {
});
expect(mockSessionStoreSetters.appendEvents).not.toHaveBeenCalled();
- resolveInherited({ entries: inheritedEntries, complete: true });
+ resolveInherited({
+ entries: inheritedEntries,
+ complete: true,
+ truncatedHeadCount: 0,
+ });
await vi.waitFor(() => {
expect(mockSessionStoreSetters.appendEvents).toHaveBeenCalledWith(
"run-c",
@@ -5157,6 +5265,7 @@ describe("SessionService", () => {
let resolveAncestor!: (result: {
entries: typeof parentEntries;
complete: boolean;
+ truncatedHeadCount: number;
}) => void;
mockAuthenticatedClient.getTaskRunSessionLogsResult
.mockImplementationOnce(
@@ -5168,6 +5277,7 @@ describe("SessionService", () => {
.mockResolvedValueOnce({
entries: [...parentEntries, leafEntry],
complete: true,
+ truncatedHeadCount: 0,
});
mockConvertStoredEntriesToEvents.mockImplementation((entries) =>
entries.some(
@@ -5226,7 +5336,11 @@ describe("SessionService", () => {
});
expect(mockSessionStoreSetters.appendEvents).not.toHaveBeenCalled();
- resolveAncestor({ entries: parentEntries, complete: false });
+ resolveAncestor({
+ entries: parentEntries,
+ complete: false,
+ truncatedHeadCount: 0,
+ });
await vi.waitFor(() => {
expect(mockSessionStoreSetters.appendEvents).toHaveBeenCalledWith(
"run-456",
@@ -5239,6 +5353,7 @@ describe("SessionService", () => {
let resolveRetryAncestor!: (result: {
entries: typeof parentEntries;
complete: boolean;
+ truncatedHeadCount: number;
}) => void;
mockAuthenticatedClient.getTaskRunSessionLogsResult
.mockImplementationOnce(
@@ -5250,6 +5365,7 @@ describe("SessionService", () => {
.mockResolvedValueOnce({
entries: [...parentEntries, leafEntry],
complete: true,
+ truncatedHeadCount: 0,
});
mockTrpcLogs.readLocalLogs.query.mockResolvedValue(
JSON.stringify(leafEntry),
@@ -5275,7 +5391,11 @@ describe("SessionService", () => {
appendCountBeforeRetryUpdate,
);
- resolveRetryAncestor({ entries: parentEntries, complete: true });
+ resolveRetryAncestor({
+ entries: parentEntries,
+ complete: true,
+ truncatedHeadCount: 0,
+ });
await vi.waitFor(() => {
expect(mockSessionStoreSetters.updateSession).toHaveBeenCalledWith(
"run-456",
@@ -7029,6 +7149,41 @@ describe("SessionService", () => {
expect(mockAuthenticatedClient.runTaskInCloud).not.toHaveBeenCalled();
});
+ it("refetches the run for the real error when none is cached", async () => {
+ const service = getSessionService();
+ mockPreBootFailedSession();
+ mockAuthenticatedClient.getTaskRun.mockResolvedValue({
+ id: "run-123",
+ task: "task-123",
+ team: 123,
+ branch: null,
+ runtime_adapter: "claude",
+ model: "claude-sonnet-4-20250514",
+ reasoning_effort: null,
+ environment: "cloud",
+ status: "failed",
+ log_url: null,
+ error_message: "GitHub is not connected for this project",
+ output: {},
+ state: {},
+ created_at: "2026-04-14T00:00:00Z",
+ updated_at: "2026-04-14T00:00:00Z",
+ completed_at: "2026-04-14T00:05:00Z",
+ });
+ const stored: Record<string, AgentSession> = {};
+ mockSessionStoreSetters.updateSession.mockImplementation(
+ (id: string, patch: Partial<AgentSession>) => {
+ stored[id] = { ...(stored[id] ?? createMockSession()), ...patch };
+ },
+ );
+ mockSessionStoreSetters.getSessions.mockImplementation(() => stored);
+
+ await expect(service.sendPrompt("task-123", "retry?")).rejects.toThrow(
+ "GitHub is not connected for this project",
+ );
+ expect(mockAuthenticatedClient.runTaskInCloud).not.toHaveBeenCalled();
+ });
+
it("still resumes when a previously running agent failed mid-execution", async () => {
const service = getSessionService();
mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
@@ -7087,6 +7242,82 @@ describe("SessionService", () => {
expect(mockAuthenticatedClient.runTaskInCloud).toHaveBeenCalledTimes(1);
});
+ it.each([
+ {
+ name: "maps a resume 404 for a non-author to the creator-only error",
+ isTaskAuthor: false,
+ resumeError: new ApiRequestError(404, "{}"),
+ expected: /Only the person who created this task/,
+ },
+ {
+ name: "keeps the original 404 for the task author",
+ isTaskAuthor: true,
+ resumeError: new ApiRequestError(404, "{}"),
+ expected: /Failed request: \[404\]/,
+ },
+ {
+ name: "keeps a non-404 resume error for a non-author",
+ isTaskAuthor: false,
+ resumeError: new ApiRequestError(500, "{}"),
+ expected: /Failed request: \[500\]/,
+ },
+ ])("$name", async ({ isTaskAuthor, resumeError, expected }) => {
+ const service = getSessionService();
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
+ createMockSession({
+ isCloud: true,
+ cloudStatus: "failed",
+ status: "connected",
+ isTaskAuthor,
+ }),
+ );
+ mockAuthenticatedClient.getTaskRun.mockResolvedValue({
+ id: "run-123",
+ task: "task-123",
+ team: 123,
+ branch: null,
+ runtime_adapter: "claude",
+ model: "claude-sonnet-4-20250514",
+ reasoning_effort: null,
+ environment: "cloud",
+ status: "failed",
+ log_url: null,
+ error_message: "agent crashed",
+ output: {},
+ state: {},
+ created_at: "2026-04-14T00:00:00Z",
+ updated_at: "2026-04-14T00:00:00Z",
+ completed_at: "2026-04-14T00:05:00Z",
+ });
+ mockAuthenticatedClient.getTask.mockResolvedValue(createMockTask());
+ mockAuthenticatedClient.runTaskInCloud.mockRejectedValue(resumeError);
+
+ await expect(service.sendPrompt("task-123", "try again")).rejects.toThrow(
+ expected,
+ );
+ });
+
+ it("keeps a non-author 404 from the previous-run fetch as its real error", async () => {
+ const service = getSessionService();
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
+ createMockSession({
+ isCloud: true,
+ cloudStatus: "failed",
+ status: "connected",
+ isTaskAuthor: false,
+ }),
+ );
+ mockAuthenticatedClient.getTaskRun.mockRejectedValue(
+ new ApiRequestError(404, "{}"),
+ );
+ mockAuthenticatedClient.getTask.mockResolvedValue(createMockTask());
+
+ await expect(service.sendPrompt("task-123", "try again")).rejects.toThrow(
+ /Failed request: \[404\]/,
+ );
+ expect(mockAuthenticatedClient.runTaskInCloud).not.toHaveBeenCalled();
+ });
+
it("attempts automatic recovery on fatal error", async () => {
const service = getSessionService();
const mockSession = createMockSession({