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): allow model changes in completed report chats (#104618)

Dylan Martin36f9c4590ba7
diff --git a/products/desktop/docs/TESTING.md b/products/desktop/docs/TESTING.md
index 44028c01681b..65921cf0bdc5 100644
--- a/products/desktop/docs/TESTING.md
+++ b/products/desktop/docs/TESTING.md
@@ -57,6 +57,14 @@ Run the focus and submission checks with:
pnpm --filter @posthog/ui test src/features/sessions/components/CommentComposer.integration.test.tsx
```
+## Continue a completed report chat
+
+Open a report whose linked cloud task has completed. In the chat, select
+Advanced > Model and choose a model from another provider. Check that the
+reasoning and permission controls match the selected model. Send a message.
+The new run must use that model and retain the previous conversation.
+An active run keeps the models supported by its current runtime.
+
## Composer text selection
In the new-session and session composers, select text and release the mouse outside the editor.
diff --git a/products/desktop/packages/core/src/sessions/cloudRunOptions.test.ts b/products/desktop/packages/core/src/sessions/cloudRunOptions.test.ts
index 53f6a69fbc1e..8d2729570131 100644
--- a/products/desktop/packages/core/src/sessions/cloudRunOptions.test.ts
+++ b/products/desktop/packages/core/src/sessions/cloudRunOptions.test.ts
@@ -48,6 +48,43 @@ describe("getCloudRuntimeOptions", () => {
const session = (overrides: Partial<AgentSession>): AgentSession =>
({ configOptions: [], ...overrides }) as unknown as AgentSession;
+ it.each([
+ [true, "completed", "codex"],
+ [true, "in_progress", "claude"],
+ [false, undefined, "claude"],
+ ] as const)(
+ "selects the next runtime only for a completed cloud run (%s, %s)",
+ (isCloud, cloudStatus, adapter) => {
+ const result = getCloudRuntimeOptions(
+ session({
+ isCloud,
+ cloudStatus,
+ adapter: "claude",
+ configOptions: [
+ {
+ id: "model",
+ name: "Model",
+ type: "select",
+ category: "model",
+ currentValue: "gpt-5.6-sol",
+ options: [{ value: "gpt-5.6-sol", name: "GPT-5.6 Sol" }],
+ },
+ ],
+ }),
+ {
+ runtime_adapter: "claude",
+ reasoning_effort: "max",
+ state: { initial_permission_mode: "acceptEdits" },
+ } as unknown as TaskRun,
+ );
+ expect(result.adapter).toBe(adapter);
+ if (adapter === "codex") {
+ expect(result.reasoningLevel).toBeUndefined();
+ expect(result.initialPermissionMode).toBeUndefined();
+ }
+ },
+ );
+
it("prefers the session config option, then the previous run", () => {
const result = getCloudRuntimeOptions(
session({
diff --git a/products/desktop/packages/core/src/sessions/cloudRunOptions.ts b/products/desktop/packages/core/src/sessions/cloudRunOptions.ts
index 4beec4d0ac5a..db7d36442b30 100644
--- a/products/desktop/packages/core/src/sessions/cloudRunOptions.ts
+++ b/products/desktop/packages/core/src/sessions/cloudRunOptions.ts
@@ -5,10 +5,12 @@ import {
type ExecutionMode,
getConfigOptionByCategory,
isSupportedReasoningEffort,
+ isTerminalStatus,
type PrAuthorshipMode,
type SupportedReasoningEffort,
} from "@posthog/shared";
import type { TaskRun } from "@posthog/shared/domain-types";
+import { harnessForModelValue } from "../task-detail/configOptions";
/**
* Pure derivations of a cloud run's options from the host run state / session
@@ -98,21 +100,41 @@ export function getCloudRuntimeOptions(
);
const modeOption = getConfigOptionByCategory(session.configOptions, "mode");
const previousMode = previousRun?.state?.initial_permission_mode;
-
+ const model =
+ typeof modelOption?.currentValue === "string"
+ ? modelOption.currentValue
+ : (previousRun?.model ?? undefined);
+ const isResume = session.isCloud && isTerminalStatus(session.cloudStatus);
+ const adapter =
+ (isResume && model
+ ? harnessForModelValue(modelOption, model)
+ : undefined) ??
+ session.adapter ??
+ previousRun?.runtime_adapter ??
+ undefined;
+ const adapterChanged =
+ adapter !== (session.adapter ?? previousRun?.runtime_adapter);
+ const reasoningLevel =
+ typeof thoughtLevelOption?.currentValue === "string"
+ ? thoughtLevelOption.currentValue
+ : adapterChanged
+ ? undefined
+ : (previousRun?.reasoning_effort ?? undefined);
return {
- adapter: session.adapter ?? previousRun?.runtime_adapter ?? undefined,
- model:
- typeof modelOption?.currentValue === "string"
- ? modelOption.currentValue
- : (previousRun?.model ?? undefined),
+ adapter,
+ model,
reasoningLevel:
- typeof thoughtLevelOption?.currentValue === "string"
- ? thoughtLevelOption.currentValue
- : (previousRun?.reasoning_effort ?? undefined),
+ isResume &&
+ adapter &&
+ model &&
+ reasoningLevel &&
+ !isSupportedReasoningEffort(adapter, model, reasoningLevel)
+ ? undefined
+ : reasoningLevel,
initialPermissionMode:
typeof modeOption?.currentValue === "string"
? (modeOption.currentValue as ExecutionMode)
- : typeof previousMode === "string"
+ : !adapterChanged && typeof previousMode === "string"
? (previousMode as ExecutionMode)
: undefined,
};
diff --git a/products/desktop/packages/core/src/sessions/cloudSessionConfig.test.ts b/products/desktop/packages/core/src/sessions/cloudSessionConfig.test.ts
index 0b97ebbfcbfd..b7b22665b949 100644
--- a/products/desktop/packages/core/src/sessions/cloudSessionConfig.test.ts
+++ b/products/desktop/packages/core/src/sessions/cloudSessionConfig.test.ts
@@ -1,12 +1,43 @@
-import type { StoredLogEntry } from "@posthog/shared";
+import {
+ getConfigOptionByCategory,
+ type StoredLogEntry,
+} from "@posthog/shared";
import { describe, expect, it } from "vitest";
import {
addMissingCloudRuntimeConfigOptions,
buildCloudDefaultConfigOptions,
+ buildCloudResumeConfigOptions,
extractLatestConfigOptionsFromEntries,
getCloudReasoningConfigOptionId,
} from "./cloudSessionConfig";
+it.each([
+ ["codex", "gpt-5.6-sol", "auto", "max"],
+ ["claude", "claude-sonnet-4-6", "acceptEdits", "high"],
+ ["claude", "moonshotai/kimi-k3", "acceptEdits", undefined],
+] as const)(
+ "updates controls for %s model %s",
+ (adapter, model, mode, effort) => {
+ const options = buildCloudResumeConfigOptions(
+ addMissingCloudRuntimeConfigOptions(
+ buildCloudDefaultConfigOptions("acceptEdits", "claude"),
+ "claude",
+ model,
+ "max",
+ ),
+ adapter,
+ model,
+ );
+ expect(getConfigOptionByCategory(options, "mode")?.currentValue).toBe(mode);
+ expect(getConfigOptionByCategory(options, "model")?.currentValue).toBe(
+ model,
+ );
+ expect(
+ getConfigOptionByCategory(options, "thought_level")?.currentValue,
+ ).toBe(effort);
+ },
+);
+
function configUpdateEntry(
configOptions: unknown,
sessionUpdate = "config_option_update",
diff --git a/products/desktop/packages/core/src/sessions/cloudSessionConfig.ts b/products/desktop/packages/core/src/sessions/cloudSessionConfig.ts
index c340613ac497..2fe1d7355d9d 100644
--- a/products/desktop/packages/core/src/sessions/cloudSessionConfig.ts
+++ b/products/desktop/packages/core/src/sessions/cloudSessionConfig.ts
@@ -1,5 +1,11 @@
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
-import type { Adapter, StoredLogEntry } from "@posthog/shared";
+import {
+ type Adapter,
+ getConfigOptionByCategory,
+ getReasoningEffortOptions,
+ type StoredLogEntry,
+} from "@posthog/shared";
+import { clampEffortToAvailable } from "../task-detail/previewConfig";
import {
getAvailableModesForAdapter,
getDefaultExecutionModeForAdapter,
@@ -9,6 +15,40 @@ export function getCloudReasoningConfigOptionId(adapter: Adapter): string {
return adapter === "codex" ? "reasoning_effort" : "effort";
}
+/** A completed run has no agent to rebuild controls after a model change. */
+export function buildCloudResumeConfigOptions(
+ configOptions: SessionConfigOption[],
+ adapter: Adapter,
+ model: string,
+): SessionConfigOption[] {
+ const mode = getConfigOptionByCategory(configOptions, "mode")?.currentValue;
+ const effort = getConfigOptionByCategory(
+ configOptions,
+ "thought_level",
+ )?.currentValue;
+ const efforts = getReasoningEffortOptions(adapter, model);
+ const extras = configOptions.filter((option) => option.category === "model");
+ if (efforts?.length) {
+ extras.push({
+ id: getCloudReasoningConfigOptionId(adapter),
+ name: adapter === "codex" ? "Reasoning" : "Effort",
+ type: "select",
+ category: "thought_level",
+ currentValue:
+ clampEffortToAvailable(
+ typeof effort === "string" ? effort : "high",
+ efforts.map((option) => option.value),
+ ) ?? "high",
+ options: efforts,
+ });
+ }
+ return buildCloudDefaultConfigOptions(
+ typeof mode === "string" ? mode : undefined,
+ adapter,
+ extras,
+ );
+}
+
/**
* Pure derivations of cloud session config options. No store or host access —
* just shaping the config-option list the mode switcher renders.
diff --git a/products/desktop/packages/core/src/sessions/sessionService.ts b/products/desktop/packages/core/src/sessions/sessionService.ts
index c5c6a59d03ab..fe872a193c3e 100644
--- a/products/desktop/packages/core/src/sessions/sessionService.ts
+++ b/products/desktop/packages/core/src/sessions/sessionService.ts
@@ -32,6 +32,7 @@ import {
getCloudUrlFromRegion,
getConfigOptionByCategory,
getReasoningEffortOptions,
+ isAnthropicModelId,
isFatalSessionError,
isJsonRpcNotification,
isJsonRpcRequest,
@@ -76,6 +77,10 @@ import type {
} from "../notification/agentSessionNotifications";
import { extractPostHogObjectReferences } from "../posthog-objects/references";
import type { SpeechKind, SpeechSource } from "../speech/identifiers";
+import {
+ harnessForModelValue,
+ isValidConfigValue,
+} from "../task-detail/configOptions";
import {
CONTEXT_WINDOW_OPTION_CATEGORY,
FAST_MODE_OPTION_CATEGORY,
@@ -102,6 +107,7 @@ import {
import {
addMissingCloudRuntimeConfigOptions,
buildCloudDefaultConfigOptions,
+ buildCloudResumeConfigOptions,
extractLatestConfigOptionsFromEntries,
} from "./cloudSessionConfig";
import {
@@ -6157,6 +6163,37 @@ export class SessionService {
return true;
}
+ if (session.isCloud && isTerminalStatus(session.cloudStatus)) {
+ if (session.isPromptPending) return false;
+ const option = configOptions[optionIndex];
+ if (!isValidConfigValue(option, value)) return false;
+ if (
+ option.category === "model" &&
+ session.claudeModelAccess === "own-subscription" &&
+ !isAnthropicModelId(value)
+ )
+ return false;
+
+ let nextOptions = configOptions.map((opt) =>
+ opt.id === configId && opt.type === "select"
+ ? { ...opt, currentValue: value }
+ : opt,
+ );
+ if (option.category === "model") {
+ nextOptions = buildCloudResumeConfigOptions(
+ nextOptions,
+ harnessForModelValue(option, value) ?? session.adapter ?? "claude",
+ value,
+ );
+ }
+ // The next prompt starts a new run. The old sandbox can no longer accept settings.
+ this.d.store.updateSession(session.taskRunId, {
+ configOptions: nextOptions,
+ });
+ this.d.setPersistedConfigOptions(session.taskRunId, nextOptions);
+ return true;
+ }
+
// Optimistic update
const updatedOptions = configOptions.map((opt) =>
opt.id === configId
@@ -6492,13 +6529,18 @@ export class SessionService {
adapter: Adapter,
initialModel?: string,
initialReasoningEffort?: string,
+ allHarnessModels = false,
): Promise<void> {
- const cacheKey = `${apiHost}::${adapter}`;
+ const cacheKey = `${apiHost}::${adapter}::${allHarnessModels}`;
let entry = this.previewConfigOptionsCache.get(cacheKey);
if (!entry || Date.now() - entry.fetchedAt > 300_000) {
if (entry) this.previewConfigOptionsCache.delete(cacheKey);
const promise = this.d.trpc.agent.getPreviewConfigOptions
- .query({ apiHost, adapter })
+ .query({
+ apiHost,
+ adapter,
+ ...(allHarnessModels ? { allHarnessModels: true } : {}),
+ })
.catch((err: unknown) => {
this.d.log.warn(
"Failed to fetch preview config options for cloud session",
@@ -6522,6 +6564,21 @@ export class SessionService {
const previewOptions = await entry.promise;
const session = this.d.store.getSessions()[taskRunId];
if (!session || session.adapter !== adapter) return;
+ if (!allHarnessModels && isTerminalStatus(session.cloudStatus)) {
+ return this.fetchAndApplyCloudPreviewOptions(
+ taskRunId,
+ apiHost,
+ adapter,
+ initialModel,
+ initialReasoningEffort,
+ true,
+ );
+ }
+ if (
+ allHarnessModels &&
+ (!isTerminalStatus(session.cloudStatus) || session.isPromptPending)
+ )
+ return;
const existingOptions = session.configOptions ?? [];
const existingModelOption = getConfigOptionByCategory(
@@ -6624,18 +6681,50 @@ export class SessionService {
if (preferredModel && modelEffortOptions === null) {
previewCategories.add("thought_level");
}
- const merged = [
+ let merged = [
...existingOptions.filter(
(option) => !previewCategories.has(option.category),
),
...extras,
];
+ if (allHarnessModels && preferredModel) {
+ merged = buildCloudResumeConfigOptions(
+ merged,
+ harnessForModelValue(
+ getConfigOptionByCategory(merged, "model"),
+ preferredModel,
+ ) ?? adapter,
+ preferredModel,
+ );
+ }
if (JSON.stringify(existingOptions) === JSON.stringify(merged)) return;
this.d.store.updateSession(taskRunId, { configOptions: merged });
}
+ async prepareCloudResume(taskId: string): Promise<void> {
+ const session = this.d.store.getSessionByTaskId(taskId);
+ if (!session?.isCloud || !isTerminalStatus(session.cloudStatus)) return;
+ try {
+ const auth = await this.getCloudCommandAuth();
+ if (!auth) return;
+ await this.fetchAndApplyCloudPreviewOptions(
+ session.taskRunId,
+ auth.apiHost,
+ session.adapter ?? "claude",
+ undefined,
+ undefined,
+ true,
+ );
+ } catch (error) {
+ this.d.log.warn("Failed to load models for cloud continuation", {
+ taskId,
+ error,
+ });
+ }
+ }
+
/**
* Start watching a cloud task via main-process CloudTaskService.
*
diff --git a/products/desktop/packages/core/src/task-detail/configOptions.ts b/products/desktop/packages/core/src/task-detail/configOptions.ts
index d6f97d35e3c0..d4224e4633fd 100644
--- a/products/desktop/packages/core/src/task-detail/configOptions.ts
+++ b/products/desktop/packages/core/src/task-detail/configOptions.ts
@@ -1,4 +1,5 @@
import type { SessionConfigOption } from "@agentclientprotocol/sdk";
+import type { PiThinkingLevel } from "@posthog/agent/pi/types";
import {
type Adapter,
adapterForModelId,
@@ -7,7 +8,6 @@ import {
isSelectGroup,
selectOptionHarness,
} from "@posthog/shared";
-import type { PiThinkingLevel } from "../pi-runtime/piSessionController";
type RawOptionItem = {
value?: string;
diff --git a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
index 25be223122ef..c1907dd8d86f 100644
--- a/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
+++ b/products/desktop/packages/ui/src/features/sessions/components/SessionView.tsx
@@ -1,5 +1,6 @@
import { Pause, Warning } from "@phosphor-icons/react";
import type { FileAttachment } from "@posthog/core/message-editor/content";
+import { getCloudRuntimeOptions } from "@posthog/core/sessions/cloudRunOptions";
import { hasSessionPromptEvent } from "@posthog/core/sessions/sessionEvents";
import {
createLatestPlanTracker,
@@ -11,7 +12,11 @@ import {
FAST_MODE_OPTION_CATEGORY,
} from "@posthog/core/task-detail/previewConfig";
import { useService } from "@posthog/di/react";
-import { type AcpMessage, FAST_MODE_FLAG } from "@posthog/shared";
+import {
+ type AcpMessage,
+ FAST_MODE_FLAG,
+ isTerminalStatus,
+} from "@posthog/shared";
import type { Task } from "@posthog/shared/domain-types";
import {
spendStopMessage,
@@ -61,7 +66,6 @@ import { useCancelQueuedMessageEdit } from "@posthog/ui/features/sessions/hooks/
import { useSessionEventsResidency } from "@posthog/ui/features/sessions/hooks/useSessionEventsResidency";
import { useToggleMessagingMode } from "@posthog/ui/features/sessions/hooks/useToggleMessagingMode";
import {
- useAdapterForTask,
useConfigOptionForTask,
useModeConfigOptionForTask,
useModelConfigOptionForTask,
@@ -177,7 +181,26 @@ export function SessionView({
CONTEXT_WINDOW_OPTION_CATEGORY,
);
const sessionModelOption = useModelConfigOptionForTask(taskId);
- const adapter = useAdapterForTask(taskId);
+ const adapter = useSessionSelector(taskId, (session) =>
+ session ? (getCloudRuntimeOptions(session).adapter ?? "claude") : "claude",
+ );
+ const isCloudRunTerminal = useSessionSelector(
+ taskId,
+ (session) => !!session?.isCloud && isTerminalStatus(session.cloudStatus),
+ );
+ const processedLineCount = useSessionSelector(taskId, (session) =>
+ isCloudRunTerminal ? session?.processedLineCount : undefined,
+ );
+ const claudeModelAccess = useSessionSelector(
+ taskId,
+ (session) => session?.claudeModelAccess,
+ );
+ // Log hydration can replace the model list after the run ends.
+ // biome-ignore lint/correctness/useExhaustiveDependencies: reload after the final transcript arrives
+ useEffect(() => {
+ if (taskId && isCloudRunTerminal)
+ void sessionService.prepareCloudResume(taskId);
+ }, [taskId, isCloudRunTerminal, processedLineCount, sessionService]);
const fastModeFlagEnabled = useFeatureFlag(FAST_MODE_FLAG);
const liveFastModeOption = useConfigOptionForTask(
taskId,
@@ -818,11 +841,15 @@ export function SessionView({
thoughtOption={thoughtOption}
modelOption={sessionModelOption}
adapter={adapter}
+ modelAccess={claudeModelAccess}
contextWindowOption={contextWindowOption}
fastModeOption={fastModeOption}
onChange={handleThoughtChange}
onConfigOptionChange={handleConfigOptionChange}
- disabled={!isRunning}
+ disabled={
+ !isRunning ||
+ (isCloudRunTerminal && !!isPromptPending)
+ }
/>
) : null
}
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 6ce76d97bb80..bde2cbfa7c13 100644
--- a/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
+++ b/products/desktop/packages/ui/src/features/sessions/sessionServiceHost.test.ts
@@ -7889,104 +7889,107 @@ describe("SessionService", () => {
},
);
- it("preserves codex runtime selection when resuming a terminal cloud run", async () => {
- const service = getSessionService();
- mockSettingsState.spokenNotifications = true;
- mockFeatureFlags.isEnabled.mockReturnValue(true);
- mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
- createMockSession({
- isCloud: true,
- cloudStatus: "completed",
- cloudBranch: "feature/codex-run",
- adapter: "codex",
- configOptions: [
- {
- id: "model",
- name: "Model",
- type: "select",
- category: "model",
- currentValue: "gpt-5.4",
- options: [],
- },
- {
- id: "effort",
- name: "Effort",
- type: "select",
- category: "thought_level",
- currentValue: "high",
- options: [],
+ it.each(["claude", "codex"] as const)(
+ "resumes a completed %s run with the selected Codex model",
+ async (previousAdapter) => {
+ const service = getSessionService();
+ mockSettingsState.spokenNotifications = true;
+ mockFeatureFlags.isEnabled.mockReturnValue(true);
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
+ createMockSession({
+ isCloud: true,
+ cloudStatus: "completed",
+ cloudBranch: "feature/codex-run",
+ adapter: previousAdapter,
+ configOptions: [
+ {
+ id: "model",
+ name: "Model",
+ type: "select",
+ category: "model",
+ currentValue: "gpt-5.4",
+ options: [{ value: "gpt-5.4", name: "GPT-5.4" }],
+ },
+ {
+ id: "effort",
+ name: "Effort",
+ type: "select",
+ category: "thought_level",
+ currentValue: "high",
+ options: [],
+ },
+ ],
+ }),
+ );
+ mockGetConfigOptionByCategory.mockImplementation(
+ (
+ configOptions: Array<{ category?: string }> | undefined,
+ category?: string,
+ ) => configOptions?.find((opt) => opt.category === category),
+ );
+ mockAuthenticatedClient.getTaskRun.mockResolvedValue({
+ id: "run-123",
+ task: "task-123",
+ team: 123,
+ branch: "feature/codex-run",
+ runtime_adapter: previousAdapter,
+ model: previousAdapter === "claude" ? "claude-sonnet-4-6" : "gpt-5.4",
+ reasoning_effort: "high",
+ environment: "cloud",
+ status: "completed",
+ log_url: "https://example.com/logs/run-123",
+ error_message: null,
+ 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.mockResolvedValue(
+ createMockTask({
+ latest_run: {
+ id: "run-456",
+ task: "task-123",
+ team: 123,
+ branch: "feature/codex-run",
+ runtime_adapter: "codex",
+ model: "gpt-5.4",
+ reasoning_effort: "high",
+ environment: "cloud",
+ status: "queued",
+ log_url: "https://example.com/logs/run-456",
+ error_message: null,
+ output: {},
+ state: {},
+ created_at: "2026-04-14T00:06:00Z",
+ updated_at: "2026-04-14T00:06:00Z",
+ completed_at: null,
},
- ],
- }),
- );
- mockGetConfigOptionByCategory.mockImplementation(
- (
- configOptions: Array<{ category?: string }> | undefined,
- category?: string,
- ) => configOptions?.find((opt) => opt.category === category),
- );
- mockAuthenticatedClient.getTaskRun.mockResolvedValue({
- id: "run-123",
- task: "task-123",
- team: 123,
- branch: "feature/codex-run",
- runtime_adapter: "codex",
- model: "gpt-5.4",
- reasoning_effort: "high",
- environment: "cloud",
- status: "completed",
- log_url: "https://example.com/logs/run-123",
- error_message: null,
- 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.mockResolvedValue(
- createMockTask({
- latest_run: {
- id: "run-456",
- task: "task-123",
- team: 123,
- branch: "feature/codex-run",
- runtime_adapter: "codex",
- model: "gpt-5.4",
- reasoning_effort: "high",
- environment: "cloud",
- status: "queued",
- log_url: "https://example.com/logs/run-456",
- error_message: null,
- output: {},
- state: {},
- created_at: "2026-04-14T00:06:00Z",
- updated_at: "2026-04-14T00:06:00Z",
- completed_at: null,
- },
- }),
- );
+ }),
+ );
- const result = await service.sendPrompt(
- "task-123",
- "Continue with Codex",
- );
+ const result = await service.sendPrompt(
+ "task-123",
+ "Continue with Codex",
+ );
- expect(result.stopReason).toBe("queued");
- expect(mockSessionStoreSetters.setTaskStarting).toHaveBeenCalledWith(
- "task-123",
- );
- expect(mockAuthenticatedClient.runTaskInCloud).toHaveBeenCalledWith(
- "task-123",
- "feature/codex-run",
- expect.objectContaining({
- adapter: "codex",
- model: "gpt-5.4",
- reasoningLevel: "high",
- resumeFromRunId: "run-123",
- }),
- );
- });
+ expect(result.stopReason).toBe("queued");
+ expect(mockSessionStoreSetters.setTaskStarting).toHaveBeenCalledWith(
+ "task-123",
+ );
+ expect(mockAuthenticatedClient.runTaskInCloud).toHaveBeenCalledWith(
+ "task-123",
+ "feature/codex-run",
+ expect.objectContaining({
+ adapter: "codex",
+ model: "gpt-5.4",
+ reasoningLevel: "high",
+ resumeFromRunId: "run-123",
+ }),
+ );
+ },
+ );
it.each([false, true])(
"checks the token before uploading resume attachments (missing: %s)",
@@ -9868,6 +9871,161 @@ describe("SessionService", () => {
});
describe("setSessionConfigOption", () => {
+ it.each(["completed", "failed", "cancelled"] as const)(
+ "saves the next model without contacting a %s sandbox",
+ async (cloudStatus) => {
+ const service = getSessionService();
+ let session = createMockSession({
+ isCloud: true,
+ cloudStatus,
+ adapter: "claude",
+ configOptions: [
+ {
+ id: "model",
+ name: "Model",
+ type: "select",
+ category: "model",
+ currentValue: "claude-sonnet-4-6",
+ options: [{ value: "gpt-5.6-sol", name: "GPT-5.6 Sol" }],
+ },
+ {
+ id: "effort",
+ name: "Effort",
+ type: "select",
+ category: "thought_level",
+ currentValue: "high",
+ options: [{ value: "high", name: "High" }],
+ },
+ ],
+ });
+ mockSessionStoreSetters.getSessionByTaskId.mockImplementation(
+ () => session,
+ );
+ mockSessionStoreSetters.updateSession.mockImplementation(
+ (_runId, updates) => {
+ session = { ...session, ...updates };
+ },
+ );
+ expect(
+ await service.setSessionConfigOption(
+ "task-123",
+ "model",
+ "gpt-5.6-sol",
+ ),
+ ).toBe(true);
+ expect(session.configOptions).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ category: "model",
+ currentValue: "gpt-5.6-sol",
+ }),
+ expect.objectContaining({
+ id: "reasoning_effort",
+ currentValue: "high",
+ }),
+ ]),
+ );
+ expect(
+ mockSessionConfigStore.setPersistedConfigOptions,
+ ).toHaveBeenLastCalledWith("run-123", session.configOptions);
+ expect(mockTrpcCloudTask.sendCommand.mutate).not.toHaveBeenCalled();
+ expect(mockTrpcAgent.setConfigOption.mutate).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([
+ { isPromptPending: true },
+ { claudeModelAccess: "own-subscription" as const },
+ ])(
+ "rejects a model change while resuming or using Anthropic billing (%j)",
+ async (overrides) => {
+ const service = getSessionService();
+ mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(
+ createMockSession({
+ isCloud: true,
+ cloudStatus: "completed",
+ adapter: "claude",
+ ...overrides,
+ configOptions: [
+ {
+ id: "model",
+ name: "Model",
+ type: "select",
+ category: "model",
+ currentValue: "claude-sonnet-4-6",
+ options: [{ value: "gpt-5.6-sol", name: "GPT-5.6 Sol" }],
+ },
+ ],
+ }),
+ );
+ expect(
+ await service.setSessionConfigOption(
+ "task-123",
+ "model",
+ "gpt-5.6-sol",
+ ),
+ ).toBe(false);
+ expect(mockSessionStoreSetters.updateSession).not.toHaveBeenCalled();
+ },
+ );
+
+ it("loads models from all runtimes for a completed cloud session", async () => {
+ const service = getSessionService();
+ let session = createMockSession({
+ isCloud: true,
+ cloudStatus: "completed",
+ adapter: "claude",
+ });
+ mockSessionStoreSetters.getSessionByTaskId.mockImplementation(
+ () => session,
+ );
+ mockSessionStoreSetters.getSessions.mockImplementation(() => ({
+ "run-123": session,
+ }));
+ mockSessionStoreSetters.updateSession.mockImplementation(
+ (_runId, updates) => {
+ session = { ...session, ...updates };
+ },
+ );
+ mockTrpcAgent.getPreviewConfigOptions.query.mockResolvedValue([
+ {
+ id: "model",
+ name: "Model",
+ type: "select",
+ category: "model",
+ currentValue: "claude-sonnet-4-6",
+ options: [
+ {
+ group: "anthropic",
+ name: "Anthropic",
+ options: [
+ { value: "claude-sonnet-4-6", name: "Claude Sonnet 4.6" },
+ ],
+ },
+ {
+ group: "openai",
+ name: "OpenAI",
+ options: [{ value: "gpt-5.6-sol", name: "GPT-5.6 Sol" }],
+ },
+ ],
+ },
+ ]);
+ await service.prepareCloudResume("task-123");
+ expect(mockTrpcAgent.getPreviewConfigOptions.query).toHaveBeenCalledWith(
+ expect.objectContaining({ adapter: "claude", allHarnessModels: true }),
+ );
+ expect(session.configOptions).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ category: "model",
+ options: expect.arrayContaining([
+ expect.objectContaining({ group: "openai" }),
+ ]),
+ }),
+ ]),
+ );
+ });
+
it("does nothing if no session exists", async () => {
const service = getSessionService();
mockSessionStoreSetters.getSessionByTaskId.mockReturnValue(undefined);