Skip to content

Commit d3d1b3d

Browse files
committed
fix(ui): show sessions while projects prepare
Create remote-project sessions before cloning, expose workspace preparation progress, and retain private restart-safe project intent until the workspace binds.
1 parent 20eef85 commit d3d1b3d

24 files changed

Lines changed: 1138 additions & 200 deletions

‎packages/gateway-protocol/src/schema/projects.test.ts‎

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -117,8 +117,18 @@ describe("project protocol schemas", () => {
117117
).toBe(false);
118118
});
119119

120-
it("accepts projectId as an additive sessions.create parameter", () => {
120+
it("accepts bounded project identity and remote URL as additive sessions.create parameters", () => {
121121
expect(validateSessionsCreateParams({ agentId: "main", projectId: "openclaw" })).toBe(true);
122122
expect(validateSessionsCreateParams({ agentId: "main", projectId: "" })).toBe(false);
123+
expect(
124+
validateSessionsCreateParams({
125+
agentId: "main",
126+
projectGitUrl: "https://github.com/openclaw/openclaw.git",
127+
}),
128+
).toBe(true);
129+
expect(validateSessionsCreateParams({ agentId: "main", projectGitUrl: "" })).toBe(false);
130+
expect(
131+
validateSessionsCreateParams({ agentId: "main", projectGitUrl: "x".repeat(2_049) }),
132+
).toBe(false);
123133
});
124134
});

‎packages/gateway-protocol/src/schema/sessions-create.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,13 @@ export const SessionsCreateParamsSchema = closedObject({
5656
description: "Start in a registered project; operator.write.",
5757
}),
5858
),
59+
projectGitUrl: Type.Optional(
60+
Type.String({
61+
minLength: 1,
62+
maxLength: 2048,
63+
description: "Prepare a remote project before the initial agent turn; operator.write.",
64+
}),
65+
),
5966
worktree: Type.Optional(Type.Boolean()),
6067
worktreeBaseRef: Type.Optional(
6168
Type.String({

‎src/config/sessions/session-accessor.sqlite-session-row.test.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,12 @@ import {
77
openOpenClawAgentDatabase,
88
} from "../../state/openclaw-agent-db.js";
99
import { closeOpenClawStateDatabaseForTest } from "../../state/openclaw-state-db.js";
10-
import { upsertSessionEntryCore } from "./session-accessor.js";
11-
import type { SessionEntry } from "./types.js";
10+
import { loadSessionEntry, upsertSessionEntryCore } from "./session-accessor.js";
11+
import {
12+
projectPublicSessionEntry,
13+
projectPublicSessionEntryPatch,
14+
} from "./session-entry-projection.js";
15+
import type { InternalSessionEntry } from "./types.js";
1216

1317
const tempDirs = createTempDirTracker();
1418

@@ -19,7 +23,7 @@ afterEach(() => {
1923
});
2024

2125
describe("SQLite session row persistence", () => {
22-
it("keeps runtime-only resolved skills out of raw SQLite JSON without mutating the session", async () => {
26+
it("persists pending remote projects but excludes runtime-only resolved skills from SQLite JSON", async () => {
2327
const stateDir = fs.realpathSync(tempDirs.make("openclaw-sqlite-session-skills-"));
2428
const env = { ...process.env, OPENCLAW_STATE_DIR: stateDir };
2529
const sessionKey = "agent:main:runtime-skills";
@@ -32,9 +36,10 @@ describe("SQLite session row persistence", () => {
3236
source: "# Demo\n\n" + "runtime skill content ".repeat(100),
3337
}),
3438
];
35-
const entry: SessionEntry = {
39+
const entry: InternalSessionEntry = {
3640
sessionId: "runtime-skills-session",
3741
updatedAt: 42,
42+
pendingProjectGitUrl: "https://github.com/openclaw/openclaw.git",
3843
skillsSnapshot: {
3944
prompt: "compact skill prompt",
4045
skills: [{ name: "demo" }],
@@ -50,7 +55,13 @@ describe("SQLite session row persistence", () => {
5055
const row = database.db
5156
.prepare("SELECT entry_json FROM session_nodes WHERE session_key = ?")
5257
.get(sessionKey) as { entry_json: string };
53-
const persisted = JSON.parse(row.entry_json) as SessionEntry;
58+
const persisted = JSON.parse(row.entry_json) as InternalSessionEntry;
59+
expect(persisted.pendingProjectGitUrl).toBe("https://github.com/openclaw/openclaw.git");
60+
expect(loadSessionEntry({ agentId: "main", env, sessionKey })?.pendingProjectGitUrl).toBe(
61+
entry.pendingProjectGitUrl,
62+
);
63+
expect(projectPublicSessionEntry(entry)).not.toHaveProperty("pendingProjectGitUrl");
64+
expect(projectPublicSessionEntryPatch(entry)).not.toHaveProperty("pendingProjectGitUrl");
5465
expect(persisted.skillsSnapshot).toEqual({
5566
prompt: "compact skill prompt",
5667
skills: [{ name: "demo" }],

‎src/config/sessions/session-entry-projection.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ export const SESSION_ENTRY_PRIVATE_CLEAR_PATCH = {
1111
lastRunId: undefined,
1212
lifecycleRunId: undefined,
1313
mainRestartRecovery: undefined,
14+
pendingProjectGitUrl: undefined,
1415
sessionDiffBaselineCapture: undefined,
1516
} satisfies Partial<InternalSessionEntry>;
1617

@@ -19,6 +20,7 @@ const PRIVATE_SESSION_ENTRY_KEYS = [
1920
"lastRunId",
2021
"lifecycleRunId",
2122
"mainRestartRecovery",
23+
"pendingProjectGitUrl",
2224
"sessionDiffBaselineCapture",
2325
] as const satisfies readonly (keyof InternalSessionEntry)[];
2426

‎src/config/sessions/types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -631,6 +631,8 @@ export type InternalSessionEntryCore = SessionEntryCore & {
631631
lastRunId?: string;
632632
/** Run admitted by the session lane; overwritten at admission and checked by transcript writes. */
633633
activeWriterRunId?: string;
634+
/** Canonical remote repository awaiting preparation by this exact session generation. */
635+
pendingProjectGitUrl?: string;
634636
/** Private per-generation ownership for the pre-runtime checkout baseline capture. */
635637
sessionDiffBaselineCapture?: import("./session-diff-baseline-capture.js").SessionDiffBaselineCapture;
636638
mainRestartRecovery?: MainRestartRecoveryState;

‎src/gateway/server-chat-progress-snapshot.ts‎

Lines changed: 27 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,14 @@ export function updateChatRunProgressSnapshot(
2222
const toolCallId = typeof data.toolCallId === "string" ? data.toolCallId.trim() : "";
2323
const review = asNullableRecord(data.review) ?? undefined;
2424
const reviewId = typeof review?.id === "string" ? review.id.trim() : "";
25+
const isStartupStatus =
26+
event.stream === "run_status" &&
27+
[
28+
"preparing_workspace",
29+
"provisioning_environment",
30+
"preparing_context",
31+
"starting_model",
32+
].includes(phase);
2533
const preambleItemId =
2634
typeof data.itemId === "string" && data.itemId.trim()
2735
? data.itemId.trim()
@@ -53,7 +61,14 @@ export function updateChatRunProgressSnapshot(
5361
candidate.data.phase === "strict_review_required" &&
5462
candidate.data.reviewId === data.reviewId,
5563
);
56-
if (!isTool && !isPreamble && !isStandaloneGuardian && !isNotice && !resolvesStrictReview) {
64+
if (
65+
!isTool &&
66+
!isPreamble &&
67+
!isStartupStatus &&
68+
!isStandaloneGuardian &&
69+
!isNotice &&
70+
!resolvesStrictReview
71+
) {
5772
return snapshot;
5873
}
5974

@@ -75,6 +90,17 @@ export function updateChatRunProgressSnapshot(
7590
next.byteLength = next.events.reduce((total, candidate) => total + jsonUtf8Bytes(candidate), 0);
7691
};
7792

93+
if (isStartupStatus) {
94+
if (
95+
next.events.some((candidate) => candidate.stream === "tool" || candidate.stream === "item")
96+
) {
97+
return next;
98+
}
99+
removeWhere((candidate) => candidate.stream === "run_status");
100+
} else if (isTool || isPreamble) {
101+
removeWhere((candidate) => candidate.stream === "run_status");
102+
}
103+
78104
if (isTool) {
79105
removeWhere((candidate) => {
80106
if (candidate.stream !== "tool" || candidate.data?.toolCallId !== toolCallId) {

‎src/gateway/server-chat-state.test.ts‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,31 @@ describe("createChatRunState", () => {
5252
expect(state.registry.shift("run-b")?.clientRunId).toBe("client-b-2");
5353
});
5454

55+
it("retains only the latest startup status until observable run activity begins", () => {
56+
const state = createChatRunState();
57+
const event = (seq: number, stream: string, data: Record<string, unknown>) =>
58+
state.recordProgressEvent("run-1", {
59+
runId: "run-1",
60+
seq,
61+
stream,
62+
ts: 1_000 + seq,
63+
sessionKey: "main",
64+
data,
65+
});
66+
67+
event(1, "run_status", { phase: "preparing_workspace" });
68+
event(2, "run_status", { phase: "preparing_context" });
69+
expect(state.runs.get("run-1")?.progressSnapshot?.events).toMatchObject([
70+
{ seq: 2, stream: "run_status", data: { phase: "preparing_context" } },
71+
]);
72+
73+
event(3, "tool", { phase: "start", name: "read", toolCallId: "read-1" });
74+
event(4, "run_status", { phase: "starting_model" });
75+
expect(state.runs.get("run-1")?.progressSnapshot?.events).toMatchObject([
76+
{ seq: 3, stream: "tool", data: { phase: "start", toolCallId: "read-1" } },
77+
]);
78+
});
79+
5580
it("keeps completed owners and standalone notices reconstructable until bounded eviction", () => {
5681
const state = createChatRunState();
5782
const event = (seq: number, stream: string, data: Record<string, unknown>) =>

‎src/gateway/server-chat.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1413,6 +1413,7 @@ export function createAgentEventHandler({
14131413
!isAborted &&
14141414
((isToolEvent && !suppressHeartbeatToolEvents) ||
14151415
isItemEvent ||
1416+
evt.stream === "run_status" ||
14161417
evt.stream === "notice" ||
14171418
typeof evt.data?.reviewId === "string" ||
14181419
evt.data?.phase === "started" ||

‎src/gateway/server-methods/chat-send-agent-dispatch.ts‎

Lines changed: 34 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,7 @@ import {
4545
} from "./chat-server-timing.js";
4646
import type { createGatewayChatUserTurnController } from "./chat-user-turn-recorder.js";
4747
import { emitSessionsChanged } from "./session-change-event.js";
48+
import { prepareSessionProjectWorkspace } from "./session-create-project.js";
4849
import type { GatewayRequestHandlerOptions } from "./types.js";
4950

5051
type PreparedChatSendAttachments = Extract<
@@ -220,32 +221,49 @@ export function startChatDispatch(params: StartChatDispatchParams): void {
220221
measureDiagnosticsTimelineSpan(
221222
"gateway.chat_send.dispatch_inbound",
222223
async () => {
224+
// Preparation stays after the ACK but inside admitted dispatch, so the
225+
// same visible run owns workspace progress, cancellation, and errors.
226+
let assertWorkspaceRunOwnership: (() => void) | undefined;
227+
if (entry && Object.hasOwn(entry, "pendingProjectGitUrl")) {
228+
assertWorkspaceRunOwnership = await prepareSessionProjectWorkspace({
229+
admission,
230+
client,
231+
context,
232+
session,
233+
});
234+
assertWorkspaceRunOwnership();
235+
}
223236
if (replyContextFieldsPromise && !preAckReplyContextPromise) {
224-
applyChatSendReplyContextFields(ctx, await replyContextFieldsPromise);
237+
const replyContextFields = await replyContextFieldsPromise;
238+
assertWorkspaceRunOwnership?.();
239+
applyChatSendReplyContextFields(ctx, replyContextFields);
225240
messageInjectionAttempt = beginCapturedMessageInjection();
226241
}
227242
if (messageInjectionAttempt) {
228-
if (
229-
await finalizeAcceptedChatSendMessageInjection({
230-
attempt: messageInjectionAttempt,
231-
context,
232-
ctx,
233-
persistUserTurnTranscriptBestEffort: persistGatewayUserTurnTranscriptBestEffort,
234-
session,
235-
startedAt: admissionStartedAt,
236-
target: messageInjectionTarget!,
237-
})
238-
) {
243+
const injected = await finalizeAcceptedChatSendMessageInjection({
244+
attempt: messageInjectionAttempt,
245+
context,
246+
ctx,
247+
persistUserTurnTranscriptBestEffort: persistGatewayUserTurnTranscriptBestEffort,
248+
session,
249+
startedAt: admissionStartedAt,
250+
target: messageInjectionTarget!,
251+
});
252+
assertWorkspaceRunOwnership?.();
253+
if (injected) {
239254
acceptedMessageInjection = true;
240255
return {
241256
queuedFinal: false,
242257
counts: { tool: 0, block: 0, final: 0 },
243258
};
244259
}
245260
}
246-
applyChatSendManagedMedia(ctx, await pluginBoundMediaPromise);
247-
const dispatchInbound = () =>
248-
dispatchInboundMessageWithProjectedDispatcher({
261+
const pluginBoundMedia = await pluginBoundMediaPromise;
262+
assertWorkspaceRunOwnership?.();
263+
applyChatSendManagedMedia(ctx, pluginBoundMedia);
264+
const dispatchInbound = () => {
265+
assertWorkspaceRunOwnership?.();
266+
return dispatchInboundMessageWithProjectedDispatcher({
249267
ctx,
250268
cfg,
251269
toolsAllow,
@@ -369,6 +387,7 @@ export function startChatDispatch(params: StartChatDispatchParams): void {
369387
},
370388
},
371389
});
390+
};
372391
const dispatchResult = await (cronCreatorAuthority && externalAuthorityAdmission
373392
? externalAuthorityAdmission.run(
374393
cronCreatorAuthority,

0 commit comments

Comments
 (0)