Skip to content

Commit 68b2f49

Browse files
feat(ui): start new sessions in background
Co-authored-by: Takhoffman <[email protected]> Worked on by: - @Takhoffman
1 parent e2c92fc commit 68b2f49

17 files changed

Lines changed: 636 additions & 58 deletions

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -634,6 +634,7 @@ Chat error banners, including cloud runner failures, show short messages in full
634634
- The active split pane drives the sidebar selection and URL. Its title bar adds split and close controls; dividers resize columns and stacked panes, and the browser stores the layout locally across reloads.
635635
- On narrow screens, split view keeps the layout but renders only the active pane, including its header with the close control.
636636
- If you send a message while a model picker change for the same session is still saving, the composer waits for that session patch before calling `chat.send` so the send uses the selected model.
637+
- On the New Session page, press **Cmd+Enter** on macOS or **Ctrl+Enter** elsewhere to create and start the draft in a background session without leaving the page. The selected local, cloud-profile, or paired-device placement is preserved. With the **Modifier+Enter** send preference, use **Cmd/Ctrl+Shift+Enter** for background start; Cmd/Ctrl+Enter remains ordinary submit. Explicit Draft visibility keeps its create-only behavior. A completion notice offers to open the new session.
637638
- Typing `/new` creates and switches to the same fresh dashboard session as New Chat, except when `session.dmScope: "main"` is configured and the current parent is the agent's main session; then it resets the main session in place. Typing `/reset` keeps the Gateway's explicit in-place reset for the current session.
638639
- The chat model picker requests the Gateway's configured model view. If `agents.defaults.modelPolicy.allow` is non-empty, that policy drives the picker, including `provider/*` entries that keep provider-scoped catalogs dynamic. Otherwise the picker shows configured entries plus providers with usable auth; aliases and settings under `agents.defaults.models` do not restrict it. The full catalog stays available through the debug `models.list` RPC with `view: "all"`.
639640
- Chat and New Session block sending when the Gateway reports missing provider credentials or a confirmed authentication failure. Missing credentials point to **Model Setup**; authentication failures ask you to review the credential or sign-in. Temporary credential cooldowns and unknown model availability do not block sending or show an authentication banner; run errors remain visible in the transcript. Unavailable model choices stay disabled in the picker.

‎src/agents/code-mode.result-budget.test.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,6 +183,9 @@ describe("fresh producer results through persistence and model guards", () => {
183183
});
184184
try {
185185
const tools = runtime.compactTools([]).tools;
186+
if (runtime.toolSearchCatalogRef?.current) {
187+
runtime.toolSearchCatalogRef.current.counterScope = "result-budget";
188+
}
186189
const first = message(
187190
await tools[0]!.execute("first", {
188191
code: `text(${JSON.stringify(firstText)}); await yield_control(); await yield_control(); ${lastText ? `text(${JSON.stringify(lastText)});` : ""} ${fail ? 'throw new Error("DIAGNOSTIC" + "é".repeat(40000));' : `return ${JSON.stringify(value)};`}`,

‎ui/src/e2e/new-session-page.test-support.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ import { waitForCommittedComposerDraft } from "./settle.test-support.ts";
1616
export { controlUiSessionPath, controlUiSessionUrl, waitForConfirmModal };
1717

1818
const NEW_SESSION_FEATURE_METHODS = [
19+
"agent.wait",
1920
"chat.metadata",
2021
"chat.startup",
2122
"sessions.create",

‎ui/src/e2e/new-session-page.transition.e2e.test.ts‎

Lines changed: 128 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,10 @@
1-
import { mkdir } from "node:fs/promises";
1+
import { mkdir, rename } from "node:fs/promises";
22
import path from "node:path";
33
import { expect, it } from "vitest";
4+
import {
5+
controlUiBundledGatewayUrl,
6+
controlUiBundledSettingsStorageKey,
7+
} from "../test-helpers/control-ui-e2e.ts";
48
import {
59
controlUiSessionPath,
610
createNewSessionPageE2eSuite,
@@ -10,6 +14,7 @@ import {
1014
} from "./new-session-page.test-support.ts";
1115

1216
const suite = createNewSessionPageE2eSuite();
17+
const proofDir = path.join(suite.artifactDir, "new-session-transition");
1318
const SESSION_KEY = "agent:main:transition-proof-0f403cb8-3920-4cf1-8eb7-79f2f00ce488";
1419
const RUN_ID = "transition-proof-run";
1520
const captureProofEnabled = process.env.OPENCLAW_CAPTURE_UI_PROOF === "1";
@@ -18,14 +23,131 @@ async function captureProof(page: import("playwright").Page, fileName: string) {
1823
if (!captureProofEnabled) {
1924
return;
2025
}
21-
await mkdir(path.join(suite.artifactDir, "new-session-transition"), { recursive: true });
22-
await page.screenshot({
23-
fullPage: true,
24-
path: path.join(path.join(suite.artifactDir, "new-session-transition"), fileName),
25-
});
26+
await mkdir(proofDir, { recursive: true });
27+
await page.screenshot({ fullPage: true, path: path.join(proofDir, fileName) });
2628
}
2729

2830
suite.define(() => {
31+
it.each([
32+
{ label: "desktop", viewport: { height: 900, width: 1280 } },
33+
{ label: "mobile", viewport: { height: 844, width: 390 } },
34+
])("starts a draft in the background on $label", async ({ label, viewport }) => {
35+
const context = await suite.browser.newContext({
36+
locale: "en-US",
37+
...(captureProofEnabled ? { recordVideo: { dir: proofDir, size: viewport } } : {}),
38+
serviceWorkers: "block",
39+
viewport,
40+
});
41+
const page = await context.newPage();
42+
const video = page.video();
43+
const sessionKey = `agent:main:dashboard:background-${label}`;
44+
const runId = `run-background-${label}`;
45+
const gateway = await installMockGateway(page, {
46+
methodResponses: {
47+
"sessions.create": {
48+
key: sessionKey,
49+
entry: {
50+
model: "gpt-5.6-sol",
51+
modelProvider: "openai",
52+
sessionId: `session-background-${label}`,
53+
updatedAt: Date.now(),
54+
},
55+
runId,
56+
runStarted: true,
57+
},
58+
},
59+
});
60+
try {
61+
await page.goto(`${suite.server.baseUrl}new`);
62+
await gateway.deferNext("agent.wait");
63+
const composer = page.locator(".new-session-page__message");
64+
await composer.fill(`run this separately on ${label}`);
65+
await captureProof(page, `background-${label}-ready.png`);
66+
if (captureProofEnabled) {
67+
await page.waitForTimeout(400);
68+
}
69+
await composer.press("Control+Enter");
70+
71+
await expect(gateway.waitForRequest("sessions.create")).resolves.toMatchObject({
72+
params: { agentId: "main", message: `run this separately on ${label}` },
73+
});
74+
await expect.poll(() => new URL(page.url()).pathname).toBe("/new");
75+
await expect.poll(() => composer.inputValue()).toBe("");
76+
await expect
77+
.poll(() =>
78+
page.locator(`.sidebar-recent-session[data-session-key="${sessionKey}"]`).count(),
79+
)
80+
.toBe(1);
81+
await captureProof(page, `background-${label}-running.png`);
82+
if (captureProofEnabled) {
83+
await page.waitForTimeout(600);
84+
}
85+
86+
await expect(gateway.waitForRequest("agent.wait")).resolves.toMatchObject({
87+
params: { runId, timeoutMs: 30_000 },
88+
});
89+
await gateway.resolveDeferred("agent.wait", { endedAt: Date.now(), runId, status: "ok" });
90+
const toast = page.locator(".app-toast");
91+
await toast.getByText("Done").waitFor({ timeout: 10_000 });
92+
await captureProof(page, `background-${label}-complete.png`);
93+
if (captureProofEnabled) {
94+
await page.waitForTimeout(800);
95+
}
96+
await toast.getByRole("button", { name: "Open" }).click();
97+
await expect.poll(() => new URL(page.url()).pathname).toBe(controlUiSessionPath(sessionKey));
98+
await waitForCommittedChatRoute(page);
99+
await page.locator("openclaw-chat-page").waitFor();
100+
await captureProof(page, `background-${label}-opened.png`);
101+
if (captureProofEnabled) {
102+
await page.waitForTimeout(400);
103+
}
104+
} finally {
105+
await context.close();
106+
if (captureProofEnabled && video) {
107+
await rename(await video.path(), path.join(proofDir, `background-${label}.webm`));
108+
}
109+
}
110+
});
111+
112+
it("uses shifted Enter for background start in modifier mode", async () => {
113+
const context = await suite.browser.newContext({
114+
locale: "en-US",
115+
serviceWorkers: "block",
116+
viewport: { height: 900, width: 1280 },
117+
});
118+
const gatewayUrl = controlUiBundledGatewayUrl(suite.server.baseUrl);
119+
await context.addInitScript(
120+
({ key, url }) => {
121+
localStorage.setItem(
122+
key,
123+
JSON.stringify({ chatSendShortcut: "modifier-enter", gatewayUrl: url }),
124+
);
125+
},
126+
{ key: controlUiBundledSettingsStorageKey(suite.server.baseUrl), url: gatewayUrl },
127+
);
128+
const page = await context.newPage();
129+
const sessionKey = "agent:main:dashboard:modifier-background";
130+
const runId = "run-modifier-background";
131+
const gateway = await installMockGateway(page, {
132+
methodResponses: {
133+
"agent.wait": { endedAt: Date.now(), runId, status: "ok" },
134+
"sessions.create": { key: sessionKey, runId, runStarted: true },
135+
},
136+
});
137+
try {
138+
await page.goto(`${suite.server.baseUrl}new`);
139+
const composer = page.locator(".new-session-page__message");
140+
await composer.fill("start in the background");
141+
await composer.press("Control+Shift+Enter");
142+
await expect.poll(() => new URL(page.url()).pathname).toBe("/new");
143+
await expect(gateway.waitForRequest("sessions.create")).resolves.toMatchObject({
144+
params: { agentId: "main", message: "start in the background" },
145+
});
146+
} finally {
147+
await context.close();
148+
}
149+
});
150+
29151
it("creates and lists a session with the default mock Gateway", async () => {
30152
const context = await suite.browser.newContext({
31153
locale: "en-US",

‎ui/src/lib/toast.test.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,22 @@ describe("shared toast", () => {
3535
expect(host.querySelector(".app-toast__message")?.textContent).toBe("Second");
3636
});
3737

38+
it("keeps queued outcomes behind an unrelated replacement toast", async () => {
39+
const host = await mountHost();
40+
41+
showToast({ message: "First completion", fifo: true });
42+
showToast({ message: "Second completion", fifo: true });
43+
await host.updateComplete;
44+
expect(host.querySelector(".app-toast__message")?.textContent).toBe("First completion");
45+
46+
showToast({ message: "Critical observer notice" });
47+
await host.updateComplete;
48+
expect(host.querySelector(".app-toast__message")?.textContent).toBe("Critical observer notice");
49+
host.querySelector<HTMLButtonElement>(".app-toast__dismiss")?.click();
50+
await host.updateComplete;
51+
expect(host.querySelector(".app-toast__message")?.textContent).toBe("Second completion");
52+
});
53+
3854
it("uses the active modal's toast layer before the app layer", async () => {
3955
const appHost = await mountHost();
4056
const modal = document.createElement("openclaw-modal-dialog");

‎ui/src/lib/toast.ts‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ export type ToastOptions = {
2020
onAction?: () => void;
2121
onDismiss?: (reason: ToastDismissReason) => void;
2222
durationMs?: number;
23+
/** Wait behind the active toast instead of replacing it. */
24+
fifo?: boolean;
2325
};
2426

2527
const DEFAULT_TOAST_DURATION_MS = 6_000;
@@ -43,6 +45,7 @@ let queuedToast: ToastOptions | null = null;
4345
class OpenClawToastHost extends OpenClawLightDomContentsElement {
4446
@state() private toast: ToastOptions | null = null;
4547
@state() private active = false;
48+
private readonly toastQueue: ToastOptions[] = [];
4649
private dismissTimer: ReturnType<typeof globalThis.setTimeout> | null = null;
4750
private exitTimer: ReturnType<typeof globalThis.setTimeout> | null = null;
4851
private exitReason: ToastDismissReason | null = null;
@@ -77,6 +80,10 @@ class OpenClawToastHost extends OpenClawLightDomContentsElement {
7780
}
7881

7982
show(options: ToastOptions) {
83+
if (options.fifo && this.toast) {
84+
this.toastQueue.push(options);
85+
return;
86+
}
8087
this.finishDismiss(this.exitReason ?? "replaced");
8188
this.toast = options;
8289
this.active = true;
@@ -105,6 +112,12 @@ class OpenClawToastHost extends OpenClawLightDomContentsElement {
105112
this.exitReason = null;
106113
this.toast = null;
107114
toast?.onDismiss?.(reason);
115+
if (reason !== "replaced") {
116+
const next = this.toastQueue.shift();
117+
if (next) {
118+
this.show(next);
119+
}
120+
}
108121
}
109122

110123
private dismiss(reason: ToastDismissReason) {
Lines changed: 146 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,146 @@
1+
import type { GatewayBrowserClient } from "../../api/gateway.ts";
2+
import { selectApplicationSession } from "../../app/agent-selection.ts";
3+
import type { ApplicationContext } from "../../app/context.ts";
4+
import { t } from "../../i18n/index.ts";
5+
import { resolveSessionDisplayName } from "../../lib/session-display.ts";
6+
import { sessionNavigationTarget } from "../../lib/sessions/route-navigation.ts";
7+
import {
8+
areUiSessionKeysEquivalent,
9+
uiSessionEventMatches,
10+
} from "../../lib/sessions/session-key.ts";
11+
import { showToast } from "../../lib/toast.ts";
12+
13+
type AgentWaitResult = {
14+
status?: "error" | "ok" | "pending" | "timeout";
15+
endedAt?: number;
16+
error?: string;
17+
providerStarted?: boolean;
18+
stopReason?: string;
19+
};
20+
21+
const RETRY_DELAY_MS = 1_000;
22+
23+
const delayRetry = () =>
24+
new Promise<void>((resolve) => {
25+
globalThis.setTimeout(resolve, RETRY_DELAY_MS);
26+
});
27+
28+
async function notifyWhenBackgroundSessionEnds(params: {
29+
agentId: string;
30+
client: GatewayBrowserClient;
31+
context: ApplicationContext;
32+
key: string;
33+
runId: string;
34+
}): Promise<void> {
35+
let result: AgentWaitResult | undefined;
36+
while (!result) {
37+
try {
38+
const observed = await params.client.request<AgentWaitResult>(
39+
"agent.wait",
40+
{ runId: params.runId, timeoutMs: 30_000 },
41+
{ timeoutMs: null },
42+
);
43+
if (params.context.gateway.snapshot.client !== params.client) {
44+
return;
45+
}
46+
const observationalTimeout =
47+
observed.status === "timeout" &&
48+
observed.endedAt === undefined &&
49+
!observed.error &&
50+
!observed.stopReason &&
51+
observed.providerStarted !== true;
52+
if (observed.status === "pending") {
53+
await delayRetry();
54+
} else if (observationalTimeout) {
55+
const placement = params.context.placementStartup.get(params.key);
56+
if (placement?.phase === "failed") {
57+
result = { status: "error", error: placement.error };
58+
} else if (params.context.placementStartup.hasPendingTurn(params.key)) {
59+
await delayRetry();
60+
} else {
61+
result = observed;
62+
}
63+
} else {
64+
result = observed;
65+
}
66+
} catch {
67+
const gateway = params.context.gateway.snapshot;
68+
const reconnecting =
69+
gateway.phase === "connecting" ||
70+
gateway.phase === "starting" ||
71+
gateway.phase === "reconnecting";
72+
if (gateway.client !== params.client || !reconnecting) {
73+
return;
74+
}
75+
await delayRetry();
76+
}
77+
}
78+
79+
const gateway = params.context.gateway.snapshot;
80+
if (
81+
uiSessionEventMatches(
82+
{ ...gateway, sessionKey: gateway.sessionKey },
83+
params.key,
84+
params.agentId,
85+
)
86+
) {
87+
return;
88+
}
89+
const row = params.context.sessions.state.result?.sessions.find((session) =>
90+
areUiSessionKeysEquivalent(session.key, params.key),
91+
);
92+
const status =
93+
result.status === "ok"
94+
? t("sessionsView.statusDone")
95+
: result.status === "timeout"
96+
? t("sessionsView.statusTimeout")
97+
: result.stopReason === "rpc"
98+
? t("sessionsView.statusKilled")
99+
: t("sessionsView.statusFailed");
100+
showToast({
101+
fifo: true,
102+
message: `${resolveSessionDisplayName(params.key, row)}: ${status}`,
103+
actionLabel: t("sessionsView.openSession"),
104+
onAction: () => {
105+
selectApplicationSession({
106+
selection: params.context.agentSelection,
107+
gateway: params.context.gateway,
108+
sessionKey: params.key,
109+
agentId: params.agentId,
110+
});
111+
params.context.navigate(
112+
"chat",
113+
sessionNavigationTarget({
114+
context: params.context,
115+
face: "chat",
116+
sessionKey: params.key,
117+
agentId: params.agentId,
118+
}).options,
119+
);
120+
},
121+
});
122+
}
123+
124+
export function prepareBackgroundSessionCompletion(params: {
125+
enabled: boolean;
126+
agentId: string;
127+
client: GatewayBrowserClient;
128+
context: ApplicationContext;
129+
clearDraft: () => void;
130+
}): (key: string, runId?: string) => boolean {
131+
return (key, runId) => {
132+
const normalizedRunId = runId?.trim();
133+
if (!params.enabled || !normalizedRunId) {
134+
return false;
135+
}
136+
params.clearDraft();
137+
void notifyWhenBackgroundSessionEnds({
138+
agentId: params.agentId,
139+
client: params.client,
140+
context: params.context,
141+
key,
142+
runId: normalizedRunId,
143+
});
144+
return true;
145+
};
146+
}

0 commit comments

Comments
 (0)