Skip to content

Commit 1e42dbc

Browse files
authored
fix(sessions): preserve defaults and managed parent repositories in visible spawns (#132364)
* fix(sessions): accept inert defaults when spawning visible sessions Allow the one-shot mode and empty attachment options without weakening rejection of unsupported visible-session behavior. Add failing-before regression coverage and correct the model-facing guidance. Fixes #132348. * fix(sessions): inherit trusted parent repositories for worktree spawns Preserve explicit source selection and cross-agent defaults. Revalidate the exact parent session and managed worktree at creation commit boundaries, including deferred worktree intent. Align visible-spawn schema guidance and documentation with accepted inert defaults. Fixes #132398. * test(sessions): refresh visible spawn prompt snapshots * fix(sessions): clarify accepted empty attachment hints * test(sessions): prove deferred child workspace ownership
1 parent e67ccbb commit 1e42dbc

13 files changed

Lines changed: 527 additions & 96 deletions

‎docs/concepts/managed-worktrees.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,8 @@ The resulting managed worktree is owned by the session, and every agent run in t
6363

6464
`sessions.create` also accepts `worktreeBaseRef` and `worktreeName` alongside `worktree: true` to pick the base ref and the worktree name (the branch becomes `openclaw/<name>`); both stay at `operator.write`. If `worktreeName` is omitted, the session label or generated first-message title supplies the readable branch name, with a crustacean-themed fallback. For a new session with an initial message or task, creation returns the admitted session and run before worktree preparation finishes. The chat shows the submitted message and naming, checkout, and setup progress; failures remain visible and retryable in the same session. The agent starts only after the finalized worktree is bound. Creation without an initial turn still waits for preparation and returns the worktree in the create result. The bound checkout is persisted on the session row as `worktree: { id, branch, repoRoot }`, so session lists can show its checkout and branch. When session deletion cannot finish that cleanup, `worktreePreserved` identifies the active worktree record that needs attention and reports one bounded reason: owner mismatch, active use or competing cleanup, a foreign Git lock, snapshot failure, or another cleanup failure. These reasons describe cleanup and ownership, not whether the checkout is dirty or has unpushed commits.
6565

66+
Accepted child sessions retain their saved repository choice across parent archive, replacement, or worktree changes. A retry must still be authorized for the current child session and uses the current caller's setup permissions.
67+
6668
## Troubleshoot creation
6769

6870
If **New session** reports `git worktree add failed`, read the termination reason and the final Git error lines. `Preparing worktree` and `Updating files` are progress, not the cause of failure. Error messages collapse carriage-return progress redraws and bound the diagnostic tail so it cannot flood the banner.

‎docs/tools/subagents.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -215,7 +215,7 @@ In `prefer` mode, hidden sub-agents are for internal legwork that the user does
215215
Spawn under another configured agent id when allowed by `subagents.allowAgents`.
216216
</ParamField>
217217
<ParamField path="cwd" type="string">
218-
Optional task working directory for the child run. Native sub-agents still load bootstrap files from the target agent workspace; `cwd` only changes where runtime tools and CLI harnesses do the delegated work. For visible sessions, paths outside configured agent workspaces require `operator.admin`; omit `cwd` to use the target agent workspace.
218+
Optional task working directory for the child run. Native sub-agents still load bootstrap files from the target agent workspace; `cwd` only changes where runtime tools and CLI harnesses do the delegated work. For visible sessions, paths outside configured agent workspaces require `operator.admin`. With `worktree: true`, omitting `cwd` inherits the same-agent parent's managed repository when available; otherwise the target agent workspace is used.
219219
</ParamField>
220220
<ParamField path="runtime" type='"subagent" | "acp"' default="subagent">
221221
`acp` is only for external ACP harnesses (`claude`, `droid`, `gemini`, `opencode`, or explicitly requested Codex ACP/acpx) and for `agents.entries.*` entries whose `runtime.type` is `acp`.
@@ -241,7 +241,7 @@ In `prefer` mode, hidden sub-agents are for internal legwork that the user does
241241
<ParamField path="mode" type='"run" | "session"' default="run">
242242
If `thread: true` and `mode` is omitted, default becomes `session`. `mode: "session"` requires `thread: true`.
243243
If thread binding is unavailable for the requester channel, use `mode: "run"` instead.
244-
With `visible: true`, omit `mode`; visible sessions are persistent and do not support `mode: "run"`.
244+
With `visible: true`, omit `mode` or use the default `"run"`; the visible session remains persistent. `mode: "session"` is unavailable on this path.
245245
</ParamField>
246246
<ParamField path="cleanup" type='"delete" | "keep"' default="keep">
247247
`"delete"` archives the session immediately after announce (still keeps the transcript via rename).
@@ -275,7 +275,7 @@ their latest assistant turn back to the requester; external delivery stays with
275275
the parent/requester agent.
276276
</Warning>
277277

278-
With `visible: true`, `category`, `model`, `cwd`, and a same-agent `context: "fork"` are supported. Use this durable mode for coding, multi-step work, or results the user may revisit, steer, or keep; it appears in the sidebar when the web UI is available and still works without it. Pass `category` to place the new session in that sidebar group atomically; omitted or blank values leave it ungrouped. A sandboxed target restricts `cwd` to that agent's workspace. Non-admin callers may use `cwd` only inside a configured agent workspace. Omit `cwd` to use the target agent workspace; for another repository, ask the operator to start the session from a registered project. Do not replace a rejected persistent spawn with the synchronous `openclaw agent` CLI, whose command deadline defaults to 600 seconds. Thread binding, `mode`, thinking overrides, `lightContext`, `attachments`, and `attachAs` are unavailable on this path because visible sessions are persistent dashboard sessions created through `sessions.create`. The new dashboard child inherits the requester's effective tool-policy ceiling before its first turn. Session listing and addressing obey `tools.sessions.visibility`; the default `tree` scope covers the current session and its own spawn subtree, while the main session can reach every same-agent session unless `self` or the sandbox spawned-only clamp applies. See [Session tools](/concepts/session-tool#visibility) and [Managed worktrees](/concepts/managed-worktrees).
278+
With `visible: true`, `category`, `model`, `cwd`, and a same-agent `context: "fork"` are supported. Use this durable mode for coding, multi-step work, or results the user may revisit, steer, or keep; it appears in the sidebar when the web UI is available and still works without it. Pass `category` to place the new session in that sidebar group atomically; omitted or blank values leave it ungrouped. A sandboxed target restricts `cwd` to that agent's workspace. Non-admin callers may use `cwd` only inside a configured agent workspace. With `worktree: true`, omitting `cwd` inherits the same-agent parent's live managed repository and creates a separate worktree. Other spawns use the target agent workspace; for another repository, ask the operator to start the session from a registered project. Do not replace a rejected persistent spawn with the synchronous `openclaw agent` CLI, whose command deadline defaults to 600 seconds. Thread binding, `mode: "session"`, thinking overrides, `lightContext`, and attachment staging are unavailable on this path because visible sessions are persistent dashboard sessions created through `sessions.create`. The default `mode: "run"`, empty `attachments`, and an empty `attachAs.mountPath` are accepted without changing that behavior. The new dashboard child inherits the requester's effective tool-policy ceiling before its first turn. Session listing and addressing obey `tools.sessions.visibility`; the default `tree` scope covers the current session and its own spawn subtree, while the main session can reach every same-agent session unless `self` or the sandbox spawned-only clamp applies. See [Session tools](/concepts/session-tool#visibility) and [Managed worktrees](/concepts/managed-worktrees).
279279

280280
If a call fails with `Parameters require visible=true`, omit the named category or worktree options to keep the hidden or ACP runtime. To create a visible session instead, use `visible: true` with `runtime: "subagent"` and omit `mode`, `thread`, `thinking`, `lightContext`, `attachments`, `attachAs`, swarm options, and the ACP-only `streamTo` and `resumeSessionId`. Worktree names and base refs also require `worktree: true`. Adding `visible: true` alone does not make an ACP call compatible.
281281

‎src/agents/tool-description-presets.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -140,7 +140,7 @@ export function describeSessionsSpawnTool(options?: {
140140
? '`mode="run"` one-shot; `mode="session"` persistent/thread-bound only on supporting requester channel.'
141141
: '`mode="run"` one-shot background.',
142142
"`agentId` targets a configured agent; `model` overrides its model; `cleanup` delete|keep hidden child session; `sandbox` inherit|require.",
143-
'`visible=true`: durable visible session. Default for coding, multi-step work, or results user may revisit/steer/keep — not only when a thread is requested. Shows in web UI sidebar; works without UI: completion announces back, progress checkable. `category` explicitly groups it; omission or an empty string leaves it ungrouped. Subagent only; omit `mode` (no `mode="run"`), `thread`, `thinking`, `lightContext`, `attachments`, `attachAs`; inherits the caller tool-policy ceiling; may check out a git worktree via `worktree`/`worktreeName`/`worktreeBaseRef`. When its accepted result includes `sessionUrl`, channel acknowledgements put the session URL on the first line and `Owner: <label>` on the second line.',
143+
'`visible=true`: durable visible session. Default for coding, multi-step work, or results user may revisit/steer/keep — not only when a thread is requested. Shows in web UI sidebar; works without UI: completion announces back, progress checkable. `category` explicitly groups it; omission or an empty string leaves it ungrouped. Subagent only; omit `mode` (`mode="run"` is also accepted), `thread`, `thinking`, and `lightContext`; `attachments=[]` and omitted/blank `attachAs.mountPath` are accepted, but nonempty attachment staging is unsupported; inherits the caller tool-policy ceiling; may check out a git worktree via `worktree`/`worktreeName`/`worktreeBaseRef`. When its accepted result includes `sessionUrl`, channel acknowledgements put the session URL on the first line and `Owner: <label>` on the second line.',
144144
visibilityLine,
145145
...(options?.swarmEnabled
146146
? [

‎src/agents/tools/sessions-spawn-tool.test.ts‎

Lines changed: 50 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -518,23 +518,29 @@ describe("sessions_spawn tool", () => {
518518
};
519519

520520
expect(schema.properties?.visible?.description).toBe(
521-
"Durable visible session: coding/multi-step/keepable results; works without UI; subagent only; omit mode/thread/thinking/lightContext/attachments/attachAs.",
521+
"Durable visible session: coding/multi-step/keepable results; works without UI; subagent only. Default run mode and empty attachment fields are accepted; no thread/thinking/lightContext or attachment staging.",
522522
);
523523
expect(schema.properties?.cwd?.description).toContain(
524524
"outside configured agent workspaces require operator.admin",
525525
);
526526
expect(tool.description).toContain("`visible=true`: durable visible session");
527527
expect(tool.description).toContain("Default for coding, multi-step work");
528-
expect(tool.description).toContain('no `mode="run"`');
528+
expect(tool.description).toContain('`mode="run"` is also accepted');
529+
expect(tool.description).toContain(
530+
"`attachments=[]` and omitted/blank `attachAs.mountPath` are accepted",
531+
);
532+
expect(tool.description).toContain("nonempty attachment staging is unsupported");
529533
expect(tool.description).toContain("inherits the caller tool-policy ceiling");
530534
expect(tool.description).toContain("session URL on the first line");
531535
expect(tool.description).toContain("`Owner: <label>` on the second line");
532536
expect(tool.description).toContain("`tools.sessions.visibility`");
533537
expect(schema.properties?.runtime?.description).toContain("visible=true");
534-
expect(schema.properties?.mode?.description).toContain("Omit with visible=true");
538+
expect(schema.properties?.mode?.description).toContain('accept omitted/default "run"');
535539
expect(schema.properties?.lightContext?.description).toContain("unavailable with visible=true");
536-
expect(schema.properties?.attachments?.description).toContain("unavailable with visible=true");
537-
expect(schema.properties?.attachAs?.description).toContain("unavailable with visible=true");
540+
expect(schema.properties?.attachments?.description).toContain("accepts only an empty array");
541+
expect(schema.properties?.attachAs?.description).toContain(
542+
"only an omitted or blank mountPath",
543+
);
538544
expect(schema.properties?.category?.description).toContain("leave it ungrouped");
539545
expect(schema.properties?.mode?.enum).toEqual(["run"]);
540546
expect(schema.properties?.mode?.anyOf).toBeUndefined();
@@ -680,34 +686,46 @@ describe("sessions_spawn tool", () => {
680686
},
681687
);
682688

683-
it.each([{ category: undefined }, { category: "" }, { category: " \t\n " }])(
684-
"keeps a visible session ungrouped when category is $category",
685-
async ({ category }) => {
686-
const callGateway = vi.fn(async () => ({
687-
key: "agent:main:dashboard:child",
688-
runStarted: true,
689-
runId: "run-visible",
690-
}));
691-
const tool = createSessionsSpawnTool({
692-
agentSessionKey: "agent:main:main",
693-
config: { agents: { list: [{ id: "main" }] } },
694-
callGateway: callGateway as never,
695-
registerRun: vi.fn(),
696-
countActiveRuns: () => 0,
697-
});
689+
it.each([
690+
{ label: "omitted", optional: {} },
691+
{ label: "empty category", optional: { category: "" } },
692+
{ label: "whitespace category", optional: { category: " \t\n " } },
693+
{ label: "empty attachment hint", optional: { mode: "run", attachments: [], attachAs: {} } },
694+
{
695+
label: "empty attachment mount path",
696+
optional: { mode: "run", attachments: [], attachAs: { mountPath: "" } },
697+
},
698+
{
699+
label: "whitespace attachment mount path",
700+
optional: { mode: "run", attachments: [], attachAs: { mountPath: " \t\n " } },
701+
},
702+
])("creates an ungrouped visible session with $label optional values", async ({ optional }) => {
703+
const callGateway = vi.fn(async () => ({
704+
key: "agent:main:dashboard:child",
705+
runStarted: true,
706+
runId: "run-visible",
707+
}));
708+
const tool = createSessionsSpawnTool({
709+
agentSessionKey: "agent:main:main",
710+
config: { agents: { list: [{ id: "main" }] } },
711+
callGateway: callGateway as never,
712+
registerRun: vi.fn(),
713+
countActiveRuns: () => 0,
714+
});
698715

699-
await tool.execute("visible-ungrouped", {
700-
task: "inspect issue",
701-
visible: true,
702-
...(category !== undefined ? { category } : {}),
703-
});
716+
const result = await tool.execute("visible-ungrouped", {
717+
task: "inspect issue",
718+
visible: true,
719+
...optional,
720+
});
704721

705-
expect(callGateway).toHaveBeenCalledWith(
706-
"sessions.create",
707-
expect.not.objectContaining({ category: expect.anything() }),
708-
);
709-
},
710-
);
722+
expect(result.details).toMatchObject({ status: "accepted", runId: "run-visible" });
723+
expect(callGateway).toHaveBeenCalledOnce();
724+
expect(callGateway).toHaveBeenCalledWith(
725+
"sessions.create",
726+
expect.not.objectContaining({ category: expect.anything() }),
727+
);
728+
});
711729

712730
it("explains an out-of-workspace visible cwd denial without suggesting a CLI fallback", async () => {
713731
await withTestDir({ prefix: "openclaw-visible-spawn-external-cwd-" }, async (workspace) => {
@@ -1166,7 +1184,7 @@ describe("sessions_spawn tool", () => {
11661184
runtime: "acp",
11671185
thinking: "high",
11681186
thread: true,
1169-
mode: "run",
1187+
mode: "session",
11701188
lightContext: true,
11711189
attachments: [{ name: "note.txt", content: "hello" }],
11721190
attachAs: { mountPath: "inputs" },

‎src/agents/tools/sessions-spawn-tool.ts‎

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -190,7 +190,7 @@ function createSessionsSpawnToolSchema(params: {
190190
cwd: Type.Optional(
191191
Type.String({
192192
description:
193-
"Working directory for the child. With visible=true, paths outside configured agent workspaces require operator.admin; omit to use the target agent workspace.",
193+
"Child working directory. Visible paths outside configured agent workspaces require operator.admin. Omitted with worktree=true: inherit the same-agent parent managed repository; otherwise use the target agent workspace.",
194194
}),
195195
),
196196
...(params.threadAvailable
@@ -205,8 +205,8 @@ function createSessionsSpawnToolSchema(params: {
205205
: {}),
206206
mode: optionalStringEnum(spawnModes, {
207207
description: params.threadAvailable
208-
? '"run" one-shot; "session" persistent/thread-bound. Omit with visible=true.'
209-
: '"run" one-shot. Omit with visible=true; visible sessions are persistent.',
208+
? '"run" one-shot; "session" persistent/thread-bound. Visible sessions accept only omitted/default "run" and remain persistent.'
209+
: '"run" one-shot. Visible sessions accept omitted/default "run" and remain persistent.',
210210
}),
211211
cleanup: optionalStringEnum(["delete", "keep"] as const, {
212212
description: "Hidden session cleanup; visible=true always keeps the session.",
@@ -253,7 +253,10 @@ function createSessionsSpawnToolSchema(params: {
253253
encoding: Type.Optional(optionalStringEnum(["utf8", "base64"] as const)),
254254
mimeType: Type.Optional(Type.String()),
255255
}),
256-
{ maxItems: 50, description: "Inline snapshots; unavailable with visible=true." },
256+
{
257+
maxItems: 50,
258+
description: "Inline snapshots; visible=true accepts only an empty array.",
259+
},
257260
),
258261
),
259262
attachAs: Type.Optional(
@@ -263,7 +266,10 @@ function createSessionsSpawnToolSchema(params: {
263266
// Kept as a hint; implementation materializes into the child workspace.
264267
mountPath: Type.Optional(Type.String()),
265268
},
266-
{ description: "Attachment mount hint; unavailable with visible=true." },
269+
{
270+
description:
271+
"Attachment mount hint; visible=true accepts only an omitted or blank mountPath.",
272+
},
267273
),
268274
),
269275
...(params.acpAvailable

‎src/agents/tools/sessions-spawn-visible.ts‎

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { isRecord } from "@openclaw/normalization-core/record-coerce";
12
import { normalizeOptionalString } from "@openclaw/normalization-core/string-coerce";
23
import { Type } from "typebox";
34
import { readMissingScopeErrorDetails } from "../../../packages/gateway-protocol/src/gateway-error-details.js";
@@ -41,7 +42,7 @@ export const VISIBLE_SESSIONS_SPAWN_SCHEMA = {
4142
visible: Type.Optional(
4243
Type.Boolean({
4344
description:
44-
"Durable visible session: coding/multi-step/keepable results; works without UI; subagent only; omit mode/thread/thinking/lightContext/attachments/attachAs.",
45+
"Durable visible session: coding/multi-step/keepable results; works without UI; subagent only. Default run mode and empty attachment fields are accepted; no thread/thinking/lightContext or attachment staging.",
4546
}),
4647
),
4748
category: Type.Optional(
@@ -134,6 +135,8 @@ export async function maybeSpawnVisibleSession(params: {
134135
const modelOverride = normalizeToolModelOverride(readToolStringParam(params.raw, "model"));
135136
const requestedCwd = readToolStringParam(params.raw, "cwd");
136137
const spawnedCwd = requestedCwd ? resolveUserPath(requestedCwd) : undefined;
138+
// A visible session starts one run; empty attachment fields request no staging.
139+
const requestedMode = params.raw.mode === "run" ? undefined : params.raw.mode;
137140
const unsupported = [
138141
[
139142
"runtime",
@@ -150,20 +153,24 @@ export async function maybeSpawnVisibleSession(params: {
150153
params.raw.thread === true ? true : undefined,
151154
"visible sessions route to the dashboard, not a channel thread",
152155
],
153-
["mode", params.raw.mode, "visible sessions are persistent dashboard sessions"],
156+
["mode", requestedMode, "visible sessions are persistent dashboard sessions"],
154157
[
155158
"lightContext",
156159
params.raw.lightContext === true ? true : undefined,
157160
"bootstrap staging is not wired to the sessions.create path",
158161
],
159162
[
160163
"attachments",
161-
Array.isArray(params.raw.attachments) ? params.raw.attachments : undefined,
164+
Array.isArray(params.raw.attachments) && params.raw.attachments.length > 0
165+
? params.raw.attachments
166+
: undefined,
162167
"attachment staging is not wired to the sessions.create path",
163168
],
164169
[
165170
"attachAs",
166-
params.raw.attachAs,
171+
isRecord(params.raw.attachAs)
172+
? readToolStringParam(params.raw.attachAs, "mountPath")
173+
: params.raw.attachAs,
167174
"attachment staging is not wired to the sessions.create path",
168175
],
169176
] as const;

0 commit comments

Comments
 (0)