Skip to content

Commit 917fd92

Browse files
authored
feat(cli): openclaw resume attaches the TUI to a recent session (#120664)
* feat(cli): openclaw resume attaches the TUI to a recent session Implements docs/plan/runners.md milestone 2. * fix(cli): resume covers global sessions and preflights TTY * fix(cli): require a terminal before resume * fix(cli): adapt resume gateway disconnect state * fix(cli): preserve global resume ownership * test(cli): prove qualified global resume crosses the gateway boundary
1 parent 135278c commit 917fd92

19 files changed

Lines changed: 690 additions & 63 deletions

‎docs/cli/index.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ Setup commands by intent:
2424
| Setup and onboarding | [`openclaw`](/cli/openclaw) · [`setup`](/cli/setup) · [`onboard`](/cli/onboard) · [`configure`](/cli/configure) · [`config`](/cli/config) · [`completion`](/cli/completion) · [`doctor`](/cli/doctor) · [`dashboard`](/cli/dashboard) |
2525
| Reset, backup, and migration | [`backup`](/cli/backup) · [`migrate`](/cli/migrate) · [`reset`](/cli/reset) · [`uninstall`](/cli/uninstall) · [`update`](/cli/update) |
2626
| Messaging and agents | [`message`](/cli/message) · [`agent`](/cli/agent) · [`agents`](/cli/agents) · [`attach`](/cli/attach) · [`acp`](/cli/acp) · [`mcp`](/cli/mcp) |
27-
| Health and sessions | [`status`](/cli/status) · [`health`](/cli/health) · [`sessions`](/cli/sessions) · [`audit`](/cli/audit) |
27+
| Health and sessions | [`status`](/cli/status) · [`health`](/cli/health) · [`sessions`](/cli/sessions) · [`resume`](/cli/resume) · [`audit`](/cli/audit) |
2828
| Gateway and logs | [`gateway`](/cli/gateway) · [`logs`](/cli/logs) · [`system`](/cli/system) |
2929
| Models and inference | [`models`](/cli/models) · [`promos`](/cli/promos) · [`infer`](/cli/infer) · `capability` (alias for [`infer`](/cli/infer)) · [`memory`](/cli/memory) · [`commitments`](/cli/commitments) · [`wiki`](/cli/wiki) |
3030
| Network and nodes | [`directory`](/cli/directory) · [`nodes`](/cli/nodes) · [`devices`](/cli/devices) · [`node`](/cli/node) · [`worker`](/cli/worker) |
@@ -418,6 +418,7 @@ openclaw [--dev] [--profile <name>] <command>
418418
docs
419419
dns
420420
setup
421+
resume
421422
tui
422423
chat (alias: tui --local)
423424
terminal (alias: tui --local)

‎docs/cli/resume.md‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
---
2+
summary: "CLI reference for attaching the TUI to a recent Gateway session"
3+
read_when:
4+
- You want to continue an existing Gateway session in the terminal
5+
- You want to find a recent session by key, display name, or label
6+
- You connect the TUI to a remote Gateway
7+
title: "Resume"
8+
---
9+
10+
# `openclaw resume`
11+
12+
Attach the terminal UI to an existing Gateway session. The session stays on
13+
the Gateway; `resume` selects it and opens the existing [TUI](/cli/tui).
14+
15+
```bash
16+
openclaw resume
17+
openclaw resume <query>
18+
```
19+
20+
With no query, OpenClaw displays up to 50 sessions active in the last seven
21+
days. With a query, an exact session key wins; otherwise OpenClaw requires a
22+
unique substring or fuzzy match across session keys, display names, and labels.
23+
24+
The picker omits bare `global` rows because they do not identify an owning
25+
agent. To attach one, pass a fully qualified key such as
26+
`openclaw resume agent:main:global`.
27+
28+
If a query is ambiguous, OpenClaw prints the matching candidates and exits with
29+
status 1. If no recent session matches, it suggests the picker and
30+
[`openclaw sessions`](/cli/sessions), then exits with status 1.
31+
32+
## Options
33+
34+
| Flag | Default | Description |
35+
| ---------------------------- | -------------------------------- | ------------------------------------------------------------------- |
36+
| `--url <url>` | `gateway.remote.url` from config | Gateway WebSocket URL. |
37+
| `--token <token>` | (none) | Gateway token if required. |
38+
| `--password <pass>` | (none) | Gateway password if required. |
39+
| `--tls-fingerprint <sha256>` | `gateway.remote.tlsFingerprint` | Expected TLS certificate fingerprint for a pinned `wss://` Gateway. |
40+
41+
`resume` uses the same Gateway URL, authentication, and TLS resolution as
42+
[`openclaw tui`](/cli/tui). It never starts a Gateway automatically. If the
43+
configured Gateway is unavailable, start or repair it and rerun the command.
44+
45+
`resume` resolves configured Gateway auth SecretRefs for token/password auth
46+
when possible (`env`/`file`/`exec` providers).
47+
48+
Gateway target precedence is explicit `--url`, then `OPENCLAW_GATEWAY_URL`,
49+
then `gateway.remote.url` when `gateway.mode` is `remote`, then the local
50+
loopback Gateway. For that local Gateway, `OPENCLAW_GATEWAY_PORT` takes
51+
precedence over the active port recorded by a running Gateway, which takes
52+
precedence over the configured or default `gateway.port`.
53+
54+
## Examples
55+
56+
```bash
57+
# Choose from recent sessions
58+
openclaw resume
59+
60+
# Exact key
61+
openclaw resume agent:main:bugfix
62+
63+
# Unique display-name or label fragment
64+
openclaw resume bugfix
65+
66+
# Remote Gateway override
67+
openclaw resume bugfix --url wss://gateway.example.com --token <token>
68+
```
69+
70+
## Related
71+
72+
- [TUI](/cli/tui)
73+
- [Sessions](/cli/sessions)
74+
- [TUI guide](/web/tui)

‎docs/docs.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1888,6 +1888,7 @@
18881888
"pages": [
18891889
"cli/attach",
18901890
"cli/dashboard",
1891+
"cli/resume",
18911892
"cli/tui"
18921893
]
18931894
},

‎docs/plan/runners.md‎

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,18 @@ Proposal, revision 1. Implementation in progress (autonomous build started
1313
2026-08-08; this section tracks live status — update it in every PR that
1414
advances a milestone).
1515

16-
| # | Milestone | Status | PRs |
17-
| --- | ---------------------------------------------------- | ----------- | --- |
18-
| 0 | This plan | in review | — |
19-
| 1a | Naming: session copy revert | not started | — |
20-
| 1b | Naming: devices consolidation | not started | — |
21-
| 1c | Cleanup: node-pairing → device-pairing merge | not started | — |
22-
| 2 | `openclaw resume` + web Continue in terminal | not started | — |
23-
| 3 | `oc-pair://` one-paste pairing | not started | — |
24-
| 4 | Picker + enrichment + projects read model | not started | — |
25-
| 5 | Device runners | not started | — |
26-
| 6 | Stop-and-continue moves | not started | — |
27-
| 7 | Deletions (ssh sandbox, openshell, exec-host clones) | not started | — |
16+
| # | Milestone | Status | PRs |
17+
| --- | ---------------------------------------------------- | ----------- | ------- |
18+
| 0 | This plan | landed | — |
19+
| 1a | Naming: session copy revert | landed | #120667 |
20+
| 1b | Naming: devices consolidation | landed | #120689 |
21+
| 1c | Cleanup: node-pairing → device-pairing merge | not started | — |
22+
| 2 | `openclaw resume` + web Continue in terminal | in progress | #120664 |
23+
| 3 | `oc-pair://` one-paste pairing | not started | — |
24+
| 4 | Picker + enrichment + projects read model | not started | — |
25+
| 5 | Device runners | not started | — |
26+
| 6 | Stop-and-continue moves | not started | — |
27+
| 7 | Deletions (ssh sandbox, openshell, exec-host clones) | not started | — |
2828

2929
Proposal history: direction agreed 2026-08-08 after a
3030
code-evidence investigation (three deep-reads of the worker, exec, and node
@@ -163,6 +163,8 @@ Delta is ergonomics only:
163163
- No new protocol surface; `sessions.list` already carries what the resolver
164164
needs.
165165

166+
Follow-up: boundary-level resume test (gateway → session list → attach) needs a lightweight CLI-side gateway harness; the existing helper costs ~370s under the CLI vitest config.
167+
166168
### 2. One-paste device pairing (independent)
167169

168170
Reuse the shipped setup-code flow: `PairingSetupPayload = { url, urls?,

‎src/cli/command-catalog.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -482,6 +482,7 @@ export const cliCommandCatalog: readonly CliCommandCatalogEntry[] = [
482482
{ commandPath: ["secrets"], policy: { configGuard: "skip", networkProxy: "bypass" } },
483483
{ commandPath: ["security"], policy: { networkProxy: "bypass" } },
484484
{ commandPath: ["system"], policy: { networkProxy: "bypass" } },
485+
{ commandPath: ["resume"], policy: { networkProxy: "bypass" } },
485486
{ commandPath: ["terminal"], policy: { networkProxy: "bypass" } },
486487
{ commandPath: ["tui"], policy: { networkProxy: "bypass" } },
487488
{ commandPath: ["uninstall"], policy: { networkProxy: "bypass" } },

‎src/cli/program/register.subclis-core.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -194,6 +194,11 @@ const entrySpecs: readonly CommandGroupDescriptorSpec<SubCliRegistrar>[] = [
194194
loadModule: () => import("../tui-cli.js"),
195195
exportName: "registerTuiCli",
196196
},
197+
{
198+
commandNames: ["resume"],
199+
loadModule: () => import("../resume-cli.js"),
200+
exportName: "registerResumeCli",
201+
},
197202
{
198203
// automations is a commander alias on the cron command; the lazy
199204
// router only routes names listed here, so the alias must be owned too.

‎src/cli/program/register.subclis.test.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,15 @@ const { registerPluginsCli, registerPluginCliCommandsFromValidatedConfig } = vi.
5959
const { registerChannelsCli } = vi.hoisted(() => ({
6060
registerChannelsCli: vi.fn(async () => undefined),
6161
}));
62+
const { registerResumeCli, resumeAction } = vi.hoisted(() => {
63+
const action = vi.fn();
64+
return {
65+
registerResumeCli: vi.fn((program: Command) => {
66+
program.command("resume").action(action);
67+
}),
68+
resumeAction: action,
69+
};
70+
});
6271
const { addGatewayRunCommand, gatewayRunAction, registerGatewayCli } = vi.hoisted(() => {
6372
const runAction = vi.fn();
6473
return {
@@ -83,6 +92,7 @@ vi.mock("../capability-cli.js", () => ({ registerCapabilityCli }));
8392
vi.mock("../exec-approvals-cli.js", () => ({ registerExecApprovalsCli }));
8493
vi.mock("../plugins-cli.js", () => ({ registerPluginsCli }));
8594
vi.mock("../channels-cli.js", () => ({ registerChannelsCli }));
95+
vi.mock("../resume-cli.js", () => ({ registerResumeCli }));
8696
vi.mock("../../plugins/cli.js", () => ({ registerPluginCliCommandsFromValidatedConfig }));
8797
vi.mock("./private-qa-cli.js", async () => {
8898
const actual = await vi.importActual<typeof import("./private-qa-cli.js")>("./private-qa-cli.js");
@@ -127,6 +137,8 @@ describe("registerSubCliCommands", () => {
127137
registerPluginsCli.mockClear();
128138
registerPluginCliCommandsFromValidatedConfig.mockClear();
129139
registerChannelsCli.mockClear();
140+
registerResumeCli.mockClear();
141+
resumeAction.mockClear();
130142
addGatewayRunCommand.mockClear();
131143
gatewayRunAction.mockClear();
132144
registerGatewayCli.mockClear();
@@ -204,6 +216,17 @@ describe("registerSubCliCommands", () => {
204216
expect(inferAction).toHaveBeenCalledTimes(1);
205217
});
206218

219+
it("registers the resume placeholder and dispatches through its lazy registrar", async () => {
220+
const program = createRegisteredProgram(["node", "openclaw", "resume"], "openclaw");
221+
222+
expect(program.commands.map((cmd) => cmd.name())).toEqual(["resume", "completion"]);
223+
224+
await program.parseAsync(["resume"], { from: "user" });
225+
226+
expect(registerResumeCli).toHaveBeenCalledTimes(1);
227+
expect(resumeAction).toHaveBeenCalledTimes(1);
228+
});
229+
207230
it("registers the exec-approvals placeholder and dispatches through the approvals registrar", async () => {
208231
const program = createRegisteredProgram(["node", "openclaw", "exec-approvals"], "openclaw");
209232

‎src/cli/program/root-command-descriptions.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,7 @@ const JSON_NOT_APPLICABLE = {
111111
"mcp login",
112112
"attach",
113113
"tui",
114+
"resume",
114115
"update wizard",
115116
],
116117
},

‎src/cli/program/subcli-descriptors.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,11 @@ const subCliCommandCatalog = defineCommandDescriptorCatalog([
126126
description: "Open a terminal UI connected to the Gateway",
127127
hasSubcommands: false,
128128
},
129+
{
130+
name: "resume",
131+
description: "Resume a recent Gateway session in the TUI",
132+
hasSubcommands: false,
133+
},
129134
{
130135
name: "terminal",
131136
description: "Open a local terminal UI (alias for tui --local)",

‎src/cli/resume-cli.runtime.ts‎

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,167 @@
1+
// Resolves recent Gateway sessions and attaches the existing TUI to the selected key.
2+
import { cancel, isCancel } from "@clack/prompts";
3+
import { selectStyled } from "../../packages/terminal-core/src/prompt-select-styled.js";
4+
import { sanitizeTerminalText } from "../../packages/terminal-core/src/safe-text.js";
5+
import { parseAgentSessionKey } from "../routing/session-key.js";
6+
import { defaultRuntime } from "../runtime.js";
7+
import type { TuiSessionList } from "../tui/tui-backend.js";
8+
import {
9+
buildSessionChoices,
10+
loadRecentSessions,
11+
resolveResumeSession,
12+
type ResumeResolution,
13+
type SessionPickerChoice,
14+
} from "../tui/tui-session-picker.js";
15+
import type { ResumeCliOptions } from "./resume-cli.js";
16+
17+
const RESUME_INTERACTIVE_TERMINAL_GUIDANCE =
18+
"Attaching to a session requires an interactive terminal. Re-run `openclaw resume [query]` from an interactive terminal.";
19+
20+
function requireInteractiveResumeTerminal() {
21+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
22+
throw new Error(RESUME_INTERACTIVE_TERMINAL_GUIDANCE);
23+
}
24+
}
25+
26+
async function fetchResumeSessions(
27+
opts: ResumeCliOptions,
28+
options: { agentId?: string; includeGlobal?: boolean } = {},
29+
) {
30+
const { GatewayChatClient } = await import("../tui/gateway-chat.js");
31+
const client = await GatewayChatClient.connect(opts);
32+
try {
33+
await new Promise<void>((resolve, reject) => {
34+
let settled = false;
35+
const finish = (complete: () => void) => {
36+
if (settled) {
37+
return;
38+
}
39+
settled = true;
40+
complete();
41+
};
42+
client.onConnected = () => finish(resolve);
43+
client.onConnectError = (error) => finish(() => reject(error));
44+
client.onDisconnected = (reason) =>
45+
finish(() => reject(new Error(reason || "Gateway connection closed")));
46+
client.start();
47+
});
48+
return await loadRecentSessions(client, options);
49+
} catch (error) {
50+
const [{ formatTuiErrorMessage }, { resolveGatewayDisconnectState }] = await Promise.all([
51+
import("../tui/tui-formatters.js"),
52+
import("../tui/tui.js"),
53+
]);
54+
const details =
55+
error && typeof error === "object" && "details" in error ? error.details : undefined;
56+
const state = resolveGatewayDisconnectState({
57+
reason: formatTuiErrorMessage(error),
58+
details,
59+
});
60+
throw new Error(
61+
[
62+
state.connectionStatus,
63+
state.remediation ??
64+
"Ensure the Gateway is running and your --url/--token/--password are correct.",
65+
].join("\n"),
66+
{ cause: error },
67+
);
68+
} finally {
69+
await client.stop();
70+
}
71+
}
72+
73+
async function promptResumeSession(
74+
sessions: readonly TuiSessionList["sessions"][number][],
75+
): Promise<string | null> {
76+
const choices = buildSessionChoices(sessions);
77+
if (choices.length === 0) {
78+
throw new Error(
79+
"No recent sessions found. Run `openclaw sessions` to inspect sessions or `openclaw tui` to start one.",
80+
);
81+
}
82+
const selected = await selectStyled({
83+
message: "Resume a session",
84+
options: choices.map((choice) => ({
85+
value: choice.value,
86+
label: formatResumeCandidate(choice),
87+
hint: choice.description ? sanitizeTerminalText(choice.description) : undefined,
88+
})),
89+
});
90+
if (isCancel(selected)) {
91+
cancel("Cancelled.");
92+
return null;
93+
}
94+
return selected;
95+
}
96+
97+
function reportResumeFailure(
98+
query: string,
99+
resolution: Exclude<ResumeResolution, { kind: "match" }>,
100+
) {
101+
if (resolution.kind === "ambiguous") {
102+
defaultRuntime.error(`Session query ${JSON.stringify(query)} is ambiguous. Candidates:`);
103+
for (const candidate of resolution.candidates) {
104+
defaultRuntime.error(` ${formatResumeCandidate(candidate)}`);
105+
}
106+
defaultRuntime.error("Use a longer name or the exact session key.");
107+
return;
108+
}
109+
defaultRuntime.error(`No recent session matched ${JSON.stringify(query)}.`);
110+
defaultRuntime.error(
111+
"Run `openclaw resume` to choose from recent sessions or `openclaw sessions` to inspect all sessions.",
112+
);
113+
}
114+
115+
function formatResumeCandidate(candidate: SessionPickerChoice): string {
116+
const label = sanitizeTerminalText(candidate.label);
117+
const key = sanitizeTerminalText(candidate.value);
118+
return label === key ? key : `${label} [${key}]`;
119+
}
120+
121+
function resolveExplicitGlobalSessionKey(
122+
query: string | undefined,
123+
): { agentId: string; key: string } | undefined {
124+
const parsed = parseAgentSessionKey(query);
125+
return parsed?.rest === "global"
126+
? { agentId: parsed.agentId, key: `agent:${parsed.agentId}:global` }
127+
: undefined;
128+
}
129+
130+
/** Resolve or select one session and run the existing Gateway-backed TUI. */
131+
export async function runResumeCommand(query: string | undefined, opts: ResumeCliOptions) {
132+
requireInteractiveResumeTerminal();
133+
const trimmedQuery = query?.trim();
134+
const explicitGlobalSession = resolveExplicitGlobalSessionKey(trimmedQuery);
135+
const sessions = await fetchResumeSessions(
136+
opts,
137+
explicitGlobalSession
138+
? { agentId: explicitGlobalSession.agentId, includeGlobal: true }
139+
: undefined,
140+
);
141+
let sessionKey: string | null;
142+
if (explicitGlobalSession) {
143+
sessionKey = explicitGlobalSession.key;
144+
} else if (trimmedQuery) {
145+
const resolution = resolveResumeSession(sessions, trimmedQuery);
146+
if (resolution.kind !== "match") {
147+
reportResumeFailure(trimmedQuery, resolution);
148+
defaultRuntime.exit(1);
149+
return;
150+
}
151+
sessionKey = resolution.session.value;
152+
} else {
153+
sessionKey = await promptResumeSession(sessions);
154+
}
155+
if (!sessionKey) {
156+
return;
157+
}
158+
const { runTui } = await import("../tui/tui.js");
159+
await runTui({
160+
url: opts.url,
161+
token: opts.token,
162+
password: opts.password,
163+
tlsFingerprint: opts.tlsFingerprint,
164+
session: sessionKey,
165+
forceProcessExitOnReturn: true,
166+
});
167+
}

0 commit comments

Comments
 (0)