Skip to content

A local-first multi-agent app development platform, built on PenguinHarness

feat(web,server,core,cli): chat UX batch — startup password notice, session process list, draft conversations, panel swap sequencing (#241)

Yaowei Zheng25c5e9520672
diff --git a/README.md b/README.md
index 929445e8..9657a372 100644
--- a/README.md
+++ b/README.md
@@ -119,7 +119,7 @@ Two ways in — both work on the same `~/.penguin/data` root, so a desktop insta
- **⌨️ CLI** — a one-line installer (or npm / offline package) puts the `penguin` command on the machine; `penguin web` then serves the full Web experience in your browser at `http://127.0.0.1:7364` (multi-session chat, agent / skill / model management, usage stats, Trace observability, evaluation center). The online installers bundle their own Node runtime — unpack and run; upgrades and reinstalls never touch your data.
> [!NOTE]
-> On a CLI install, the first Web login is `admin`, with the initial password printed on the server's first start (of the form `penguin-1234`) — change it right after. Models are configured on the in-app **Models** page.
+> On a CLI install, the first Web login is `admin`, with the initial password (of the form `penguin-1234`) printed as a framed notice on every server start until it is changed — change it right after. Models are configured on the in-app **Models** page.
### 🖥️ Desktop app
diff --git a/README.zh.md b/README.zh.md
index bc8262d5..db344611 100644
--- a/README.zh.md
+++ b/README.zh.md
@@ -119,7 +119,7 @@ https://github.com/user-attachments/assets/aec49ae9-b743-467b-b247-37bedfeaa36e
- **⌨️ 命令行**——一行命令(或 npm / 离线包)装出 `penguin` 命令,`penguin web` 即在浏览器打开完整 Web 体验 `http://127.0.0.1:7364`(多会话对话、Agent / 技能 / 模型管理、用量统计、轨迹观测、评估中心)。在线安装器自带 Node 运行时,解压即用;升级与重装不触碰数据。
> [!NOTE]
-> 命令行安装后,Web 首次登录用户名为 `admin`,初始密码在服务端首次启动时打印(形如 `penguin-1234`),登录后请尽快修改;模型在应用内「模型」页配置。
+> 命令行安装后,Web 首次登录用户名为 `admin`,初始密码(形如 `penguin-1234`)在改掉之前每次启动服务端都会以边框提示打印,登录后请尽快修改;模型在应用内「模型」页配置。
### 🖥️ 桌面端应用
diff --git a/packages/cli/src/commands/serve.ts b/packages/cli/src/commands/serve.ts
index 233657bb..141915fb 100644
--- a/packages/cli/src/commands/serve.ts
+++ b/packages/cli/src/commands/serve.ts
@@ -17,6 +17,10 @@
import { spawn } from "node:child_process";
import path from "node:path";
import { DEFAULT_SERVER_PORT, resolveRoot } from "@prismshadow/penguin-core";
+import {
+ readInitialAdminPassword,
+ renderInitialPasswordNotice,
+} from "@prismshadow/penguin-server/initial-password";
import { liveServerLock } from "@prismshadow/penguin-server/lock";
import type { Command } from "commander";
import type { Messages, WebProbeFailureKind } from "../i18n.js";
@@ -276,6 +280,16 @@ export function registerServeCommands(program: Command, t: Messages): void {
const existing = await existingInstanceUrl();
if (existing !== null) {
process.stdout.write(t.webAlreadyRunning(existing) + "\n");
+ // The running server prints the initial-password reminder only into ITS OWN
+ // console; someone attaching from a fresh terminal would never see it. The data
+ // root's stored plaintext exists exactly while the admin password is still the
+ // initial one (the server removes it on change), so its presence alone gates the
+ // reminder here. The fresh-start path below needs nothing: the server module
+ // runs in this same process and prints the notice itself.
+ const initialPassword = readInitialAdminPassword(process.env.PENGUIN_HOME ?? resolveRoot());
+ if (initialPassword !== null) {
+ process.stdout.write(renderInitialPasswordNotice("admin", initialPassword) + "\n");
+ }
if (opts.open) openBrowser(existing);
return;
}
diff --git a/packages/core/src/environment/environment.ts b/packages/core/src/environment/environment.ts
index bdcb1ede..3dae3ce5 100644
--- a/packages/core/src/environment/environment.ts
+++ b/packages/core/src/environment/environment.ts
@@ -27,6 +27,7 @@ import path from "node:path";
import { partialToolCallOutput, toolCallOutput } from "../omnimessage/index.js";
import type { OmniMessage, StopReason } from "../omnimessage/index.js";
import type {
+ BackgroundCommandInfo,
EnvironmentConfig,
EnvironmentInterface,
ToolConfig,
@@ -135,6 +136,23 @@ export class Environment implements EnvironmentInterface {
this.subagentSessions.dispose();
}
+ /** Background command processes registered by exec_command (still-listed exited ones included; the host UI filters as it sees fit). */
+ listBackgroundCommands(): BackgroundCommandInfo[] {
+ return this.commandSessions.list().map(({ processId, session }) => ({
+ processId,
+ pid: session.pid,
+ cmd: session.cmd,
+ cwd: session.cwd,
+ startedAt: session.startedAt,
+ running: session.running,
+ }));
+ }
+
+ /** Kills one background command process (whole process group) and drops it from the registry; false when the id is unknown. */
+ killBackgroundCommand(processId: string): boolean {
+ return this.commandSessions.kill(processId);
+ }
+
/**
* Lists tools available to the current Session, for context_engine to initialize GenerativeModel.
* Only lists tools that have been assembled (i.e. supported by the registry) — tool names
diff --git a/packages/core/src/environment/tools/background/registry.ts b/packages/core/src/environment/tools/background/registry.ts
index f7820f00..6d4937b6 100644
--- a/packages/core/src/environment/tools/background/registry.ts
+++ b/packages/core/src/environment/tools/background/registry.ts
@@ -124,6 +124,16 @@ export class BackgroundRegistry<T extends BackgroundTask> {
return t;
}
+ /**
+ * Snapshot of all registered sessions with their ids, registration order. Deliberately
+ * does NOT refresh access times: enumeration is observability (a host UI listing
+ * processes), and counting it as use would keep every idle session alive forever.
+ */
+ list(): Array<{ id: string; task: T }> {
+ if (this.disposed) return [];
+ return [...this.tasks].map(([id, task]) => ({ id, task }));
+ }
+
/** Removes a session from the registry and finalizes it. */
remove(id: string): void {
const t = this.tasks.get(id);
diff --git a/packages/core/src/environment/tools/command/session-manager.ts b/packages/core/src/environment/tools/command/session-manager.ts
index 39a25182..ed2a1aa9 100644
--- a/packages/core/src/environment/tools/command/session-manager.ts
+++ b/packages/core/src/environment/tools/command/session-manager.ts
@@ -187,6 +187,18 @@ export class CommandSessionManager {
this.registry.remove(processId);
}
+ /** Snapshot of the registered background command sessions (id + session), registration order. */
+ list(): Array<{ processId: string; session: ManagedSession }> {
+ return this.registry.list().map(({ id, task }) => ({ processId: id, session: task }));
+ }
+
+ /** Kills a background process by id (SIGTERM→SIGKILL on the whole group) and drops it from the registry; false when the id is unknown. */
+ kill(processId: string): boolean {
+ if (this.registry.get(processId) === undefined) return false;
+ this.registry.remove(processId);
+ return true;
+ }
+
/** Disposes: removes the fallback registration and kills all sessions (the process 'exit' fallback is hooked up by the registry itself). Idempotent. */
dispose(): void {
this.registry.dispose();
diff --git a/packages/core/src/environment/tools/command/session.ts b/packages/core/src/environment/tools/command/session.ts
index 64c7b13c..7c947d61 100644
--- a/packages/core/src/environment/tools/command/session.ts
+++ b/packages/core/src/environment/tools/command/session.ts
@@ -75,6 +75,13 @@ export class ManagedSession {
/** Timestamp of the last access (used for LRU / idle reaping). */
lastUsed: number = Date.now();
+ /** The command string as handed to the session shell (list display for the host UI). */
+ readonly cmd: string;
+ /** Working directory the command was spawned in. */
+ readonly cwd: string;
+ /** Spawn timestamp (epoch ms). */
+ readonly startedAt: number = Date.now();
+
private readonly child: ChildProcess;
private readonly buffer = new CappedTextBuffer(OUTPUT_BUFFER_CAP, "earlier output");
private exited = false;
@@ -86,6 +93,8 @@ export class ManagedSession {
private readonly wakeSignal = new WakeSignal();
constructor(opts: SpawnOptions) {
+ this.cmd = opts.cmd;
+ this.cwd = opts.cwd;
const shell = sessionShell();
this.child = spawn(shell.command, [...shell.args, opts.cmd], {
cwd: opts.cwd,
@@ -178,6 +187,10 @@ export class ManagedSession {
get running(): boolean {
return !this.exited;
}
+ /** OS pid of the shell leading the process group; null when the spawn itself failed. */
+ get pid(): number | null {
+ return typeof this.child.pid === "number" ? this.child.pid : null;
+ }
get exit(): ProcessExit | null {
return this.exitInfo;
}
diff --git a/packages/core/src/interfaces.ts b/packages/core/src/interfaces.ts
index 3a53c65f..b07286af 100644
--- a/packages/core/src/interfaces.ts
+++ b/packages/core/src/interfaces.ts
@@ -342,6 +342,21 @@ export interface ToolExecutionRequest {
approve?: ApproveFn;
}
+/**
+ * One background command process owned by the environment (an exec_command promoted past
+ * its yield window): the registry handle plus display metadata for a host UI's process
+ * list. `pid` is the shell leading the process group (null when the spawn itself failed);
+ * `startedAt` is epoch milliseconds.
+ */
+export interface BackgroundCommandInfo {
+ processId: string;
+ pid: number | null;
+ cmd: string;
+ cwd: string;
+ startedAt: number;
+ running: boolean;
+}
+
/**
* Environment interface: executes approved tool calls within the Workspace.
* `executeTool` yields `partial_tool_call_output` as an async generator and ends with exactly one
@@ -357,6 +372,10 @@ export interface EnvironmentInterface {
executeTool(request: ToolExecutionRequest): AsyncGenerator<OmniMessage>;
/** Looks up a tool's permission level (for frontend permission-mode decisions); returns undefined for unknown tools. */
toolPermission(name: string): ToolPermission | undefined;
+ /** Background command processes this environment currently owns (host UI process list). Optional — standalone embedders may not track any. */
+ listBackgroundCommands?(): BackgroundCommandInfo[];
+ /** Kills one background command process by id (whole process group); false when the id is unknown. Optional, like listBackgroundCommands. */
+ killBackgroundCommand?(processId: string): boolean;
/** Releases runtime resources held by the environment (e.g. managed long-running command sessions); called by the host when the Session ends. Optional, idempotent. */
dispose?(): void;
}
diff --git a/packages/core/src/session.ts b/packages/core/src/session.ts
index 7717db25..e89d92af 100644
--- a/packages/core/src/session.ts
+++ b/packages/core/src/session.ts
@@ -22,7 +22,12 @@ import type { OmniMessage, SessionMetaPayload, TokenCounts } from "./omnimessage
import { imagesToScratchpadPaths } from "./internal/session-support.js";
import { runGoalLoop } from "./goal/goal-loop.js";
import { goalFinishedOf } from "./goal/goal-stream.js";
-import type { EnvironmentInterface, LLMInterface, ToolPermission } from "./interfaces.js";
+import type {
+ BackgroundCommandInfo,
+ EnvironmentInterface,
+ LLMInterface,
+ ToolPermission,
+} from "./interfaces.js";
import { generateTitleWithLLM } from "./internal/session-title.js";
import type { SessionTitleResult } from "./internal/session-title.js";
import { ContextEngine } from "./engine/context-engine.js";
@@ -419,6 +424,20 @@ export class Session {
return this.meta;
}
+ /**
+ * Background command processes owned by this Session's Environment (exec_commands
+ * promoted past their yield window): the host UI's process list. Empty for
+ * environments that don't track any.
+ */
+ listBackgroundCommands(): BackgroundCommandInfo[] {
+ return this.environment.listBackgroundCommands?.() ?? [];
+ }
+
+ /** Kills one of this Session's background command processes (whole process group); false when the id is unknown. */
+ killBackgroundCommand(processId: string): boolean {
+ return this.environment.killBackgroundCommand?.(processId) ?? false;
+ }
+
/**
* Releases runtime resources held by the Session: kills long-running command sessions
* managed by the Environment. The host calls this when the Session ends (CLI exit, Web
diff --git a/packages/docs/content/quickstart.en.md b/packages/docs/content/quickstart.en.md
index 8ce24afe..76045e49 100644
--- a/packages/docs/content/quickstart.en.md
+++ b/packages/docs/content/quickstart.en.md
@@ -30,7 +30,7 @@ penguin config model add --provider deepseek --model-id deepseek-v4-flash --api-
penguin web
```
-The service runs at http://127.0.0.1:7364 and opens your browser (`--no-open` to skip). First login is `admin` — the server prints the initial password (of the form `penguin-1234`) on first start; change it right away. `penguin server` starts the same process headless.
+The service runs at http://127.0.0.1:7364 and opens your browser (`--no-open` to skip). First login is `admin` — the server prints the initial password (of the form `penguin-1234`) in a framed notice on every start until it is changed; change it right away. `penguin server` starts the same process headless.
## One-shot run
diff --git a/packages/docs/content/quickstart.zh.md b/packages/docs/content/quickstart.zh.md
index 1dc26cce..83c08e64 100644
--- a/packages/docs/content/quickstart.zh.md
+++ b/packages/docs/content/quickstart.zh.md
@@ -30,7 +30,7 @@ penguin config model add --provider deepseek --model-id deepseek-v4-flash --api-
penguin web
```
-服务运行在 http://127.0.0.1:7364 并自动打开浏览器(`--no-open` 跳过)。首次登录使用 `admin`,初始密码(形如 `penguin-1234`)在服务端首次启动时打印,请立即修改密码。`penguin server` 启动同一进程的 headless 版本。
+服务运行在 http://127.0.0.1:7364 并自动打开浏览器(`--no-open` 跳过)。首次登录使用 `admin`,初始密码(形如 `penguin-1234`)在改掉之前每次启动服务端都会以边框提示打印,请立即修改密码。`penguin server` 启动同一进程的 headless 版本。
## 单次运行
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 0ed34eab..87ca63df 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -35,7 +35,7 @@ packages/server/src
- Cookie session: `penguin_session` (HttpOnly, SameSite=Lax), valid for 7 days with sliding renewal;
- Passwords are stored as scrypt hashes; the server keeps only the sha256 of the session token, never the plaintext;
-- No open registration: the built-in admin `admin` is seeded at startup with a random initial password (of the form `penguin-1234`) printed once to the server console — `PENGUIN_SEED_ADMIN_PASSWORD` pins it for automation — and all other accounts are created by an admin;
+- No open registration: the built-in admin `admin` is seeded at startup with a random initial password (of the form `penguin-1234`) — kept in `<root>/initial-admin-password` and re-printed to the server console on every start until it is changed; `PENGUIN_SEED_ADMIN_PASSWORD` pins it for automation — and all other accounts are created by an admin;
- Same-origin only — no CORS middleware is enabled.
```bash
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index a913ab47..eda4860f 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -35,7 +35,7 @@ packages/server/src
- Cookie 会话:`penguin_session`(HttpOnly、SameSite=Lax),有效期 7 天,滑动续期;
- 密码以 scrypt 哈希存储;服务端只保存会话 Token 的 sha256,不落明文;
-- 不开放注册:启动时种子化内置管理员 `admin`,初始密码随机生成(形如 `penguin-1234`)并仅在种子当次打印到服务端控制台——自动化可用 `PENGUIN_SEED_ADMIN_PASSWORD` 固定——其余账号由管理员创建;
+- 不开放注册:启动时种子化内置管理员 `admin`,初始密码随机生成(形如 `penguin-1234`),在改掉之前保存在 `<root>/initial-admin-password` 中并于每次启动时打印到服务端控制台——自动化可用 `PENGUIN_SEED_ADMIN_PASSWORD` 固定——其余账号由管理员创建;
- 仅限同源访问,未启用 CORS 中间件。
```bash
diff --git a/packages/docs/content/web-app.en.md b/packages/docs/content/web-app.en.md
index e0cfb73a..33f36575 100644
--- a/packages/docs/content/web-app.en.md
+++ b/packages/docs/content/web-app.en.md
@@ -23,7 +23,7 @@ penguin web
# open http://127.0.0.1:7364
```
-The initial account is `admin`; its initial password (of the form `penguin-1234`) is printed in the server startup output on first start. There is no self-registration: accounts are created by an admin on the user-management page, and every new user automatically gets an independent initial Project named `<userId>-default_project`. While the initial password is still in use, a banner prompts the user to change it.
+The initial account is `admin`; its initial password (of the form `penguin-1234`) is printed in the server startup output — as a framed notice on every start — until it is changed. There is no self-registration: accounts are created by an admin on the user-management page, and every new user automatically gets an independent initial Project named `<userId>-default_project`. While the initial password is still in use, a banner prompts the user to change it.
Logins persist for 7 days with sliding renewal; an admin password reset invalidates all of that user's login sessions.
diff --git a/packages/docs/content/web-app.zh.md b/packages/docs/content/web-app.zh.md
index 0efd506a..bb2251e5 100644
--- a/packages/docs/content/web-app.zh.md
+++ b/packages/docs/content/web-app.zh.md
@@ -23,7 +23,7 @@ penguin web
# 打开 http://127.0.0.1:7364
```
-初始账号为 `admin`,初始密码(形如 `penguin-1234`)在服务端首次启动时打印。系统不开放自助注册:账号由管理员在用户管理页创建;每个新用户会自动获得一个独立的初始 Project,命名为 `<userId>-default_project`。仍在使用初始密码时,页面会以横幅提示尽快修改。
+初始账号为 `admin`,初始密码(形如 `penguin-1234`)在改掉之前每次启动服务端都会以边框提示打印。系统不开放自助注册:账号由管理员在用户管理页创建;每个新用户会自动获得一个独立的初始 Project,命名为 `<userId>-default_project`。仍在使用初始密码时,页面会以横幅提示尽快修改。
登录状态保持 7 天(滑动续期);管理员重置密码会使该用户的全部登录会话失效。
diff --git a/packages/server/package.json b/packages/server/package.json
index 63c9fe95..9fc14cce 100644
--- a/packages/server/package.json
+++ b/packages/server/package.json
@@ -21,6 +21,10 @@
"./lock": {
"types": "./dist/lock.d.ts",
"import": "./dist/lock.js"
+ },
+ "./initial-password": {
+ "types": "./dist/initial-password.d.ts",
+ "import": "./dist/initial-password.js"
}
},
"main": "./dist/index.js",
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index e2f49902..8580124c 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -888,6 +888,25 @@ export interface RetryNowResponse {
skipped: boolean;
}
+/**
+ * One background command process started by the Session (an exec_command promoted past
+ * its yield window). Served from the ACTIVE runtime only: a session whose runtime entry
+ * is gone truthfully reports an empty list.
+ */
+export interface SessionProcessInfo {
+ processId: string;
+ /** OS pid of the process-group leader; null when the spawn itself failed. */
+ pid: number | null;
+ cmd: string;
+ cwd: string;
+ startedAt: string;
+ running: boolean;
+}
+
+export interface SessionProcessesResponse {
+ processes: SessionProcessInfo[];
+}
+
// ---------------------------------------------------------------------------
// SSE server events (OmniMessage uses the default event, only server_event here)
// ---------------------------------------------------------------------------
diff --git a/packages/server/src/app.ts b/packages/server/src/app.ts
index 97ce256d..0334c429 100644
--- a/packages/server/src/app.ts
+++ b/packages/server/src/app.ts
@@ -33,7 +33,8 @@ import { UsersRepo } from "./db/repos/users.js";
import type { UserRow } from "./db/repos/users.js";
import { authMiddleware, jsonOnlyWrites } from "./auth/middleware.js";
import type { AppEnv } from "./auth/middleware.js";
-import { AuthService } from "./auth/service.js";
+import { ADMIN_USER_ID, AuthService } from "./auth/service.js";
+import { clearInitialAdminPassword } from "./initial-password.js";
import { handleError, HttpError, errorBody } from "./http/errors.js";
import { adminUsersRoutes } from "./http/routes/admin.js";
import { adminSettingsRoutes } from "./http/routes/admin-settings.js";
@@ -249,12 +250,20 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
manager,
traceIndex,
});
+ // Any password update for the built-in admin makes the persisted initial-password
+ // plaintext stale (either the password is no longer initial, or a reset replaced it
+ // with an admin-chosen value that is never persisted): drop the file so later startups
+ // stop re-printing a credential that no longer signs in.
+ const onPasswordChanged = (userId: string): void => {
+ if (userId === ADMIN_USER_ID) clearInitialAdminPassword(config.root);
+ };
const authService = new AuthService({
users: usersRepo,
authSessions: authSessionsRepo,
provisionInitialProject: (user, isAdmin) =>
projectService.provisionInitialProject(user, isAdmin),
seedAdminPassword: config.seedAdminPassword,
+ onPasswordChanged,
sessionTtlMs: config.authSessionTtlMs,
sessionRenewMs: config.authSessionRenewMs,
...(overrides.now ? { now: overrides.now } : {}),
@@ -264,6 +273,7 @@ export function buildAppDeps(config: ServerConfig, overrides: BuildDepsOverrides
authSessions: authSessionsRepo,
projects: projectsRepo,
projectService,
+ onPasswordChanged,
...(overrides.now ? { now: overrides.now } : {}),
});
const sessionService = new SessionService({
diff --git a/packages/server/src/auth/service.ts b/packages/server/src/auth/service.ts
index 1efbb3a8..013472a4 100644
--- a/packages/server/src/auth/service.ts
+++ b/packages/server/src/auth/service.ts
@@ -81,6 +81,12 @@ export interface AuthServiceDeps {
provisionInitialProject: (user: UserRow, isAdmin: boolean) => Promise<void>;
/** Fixed initial password for the seeded admin (config.seedAdminPassword); null generates a random one at seed time. */
seedAdminPassword: string | null;
+ /**
+ * Fired after any successful password update (self change / desktop set). The server
+ * wires it to drop the stored initial-password plaintext once it goes stale (see
+ * initial-password.ts); standalone/test constructions may omit it.
+ */
+ onPasswordChanged?: (userId: string) => void;
sessionTtlMs: number;
sessionRenewMs: number;
now?: () => Date;
@@ -130,6 +136,11 @@ export class AuthService {
return password;
}
+ /** Whether the built-in admin still runs on its initial password (drives the startup reminder notice). */
+ adminPasswordIsInitial(): boolean {
+ return this.deps.users.findById(ADMIN_USER_ID)?.passwordIsInitial === true;
+ }
+
/** Consecutive login failures per userId (see the throttling comment on the constants). */
private readonly loginFailures = new Map<string, { failures: number; lastFailureAt: number }>();
@@ -195,6 +206,7 @@ export class AuthService {
throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
}
this.deps.users.updatePassword(userId, await hashPassword(newPassword), false);
+ this.deps.onPasswordChanged?.(userId);
}
/**
@@ -208,6 +220,7 @@ export class AuthService {
throw new HttpError(400, "invalid_password", "Password must be at least 8 characters.");
}
this.deps.users.updatePassword(userId, await hashPassword(newPassword), false);
+ this.deps.onPasswordChanged?.(userId);
}
logout(token: string): void {
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index f6c068ae..13b7d722 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -22,6 +22,7 @@ import type {
ServerEvent,
SessionCategory,
SessionCreateResponse,
+ SessionProcessesResponse,
SessionResponse,
SessionsResponse,
RetryNowResponse,
@@ -776,6 +777,41 @@ export function sessionsRoutes(deps: AppDeps): Hono<AppEnv> {
return c.body(null, aborted ? 202 : 204);
});
+ // —— Background processes (the details popover's interactive list) ——
+
+ // Processes the conversation started (exec_commands promoted to background). Served
+ // from the ACTIVE runtime only: an evicted or never-loaded session truthfully reports
+ // none — the environment that owned them is gone, and resurrecting an entry could only
+ // ever produce an empty list anyway.
+ app.get("/:sessionId/processes", (c) => {
+ const row = resolveSession(c);
+ const processes = deps.manager.listProcesses(row.sessionId).map((p) => ({
+ processId: p.processId,
+ pid: p.pid,
+ cmd: p.cmd,
+ cwd: p.cwd,
+ startedAt: new Date(p.startedAt).toISOString(),
+ running: p.running,
+ }));
+ return c.json({ processes } satisfies SessionProcessesResponse);
+ });
+
+ // Stop one background process (SIGTERM to the whole group, SIGKILL after a grace
+ // period). 404 when the id is gone — already exited and reaped, or the runtime was
+ // evicted; the UI just refreshes its list either way.
+ app.post("/:sessionId/processes/:processId/kill", (c) => {
+ const row = resolveSession(c);
+ const killed = deps.manager.killProcess(row.sessionId, pathParam(c, "processId"));
+ if (!killed) {
+ throw new HttpError(
+ 404,
+ "process_not_found",
+ "Process does not exist or has already exited.",
+ );
+ }
+ return c.body(null, 204);
+ });
+
// "Retry now" on the reconnect countdown: skip the remaining backoff wait and fire the
// next retry immediately (attempt counter unchanged). Benign either way — 200 with
// skipped:false when no reconnect wait is in progress, so a timing race (the wait
diff --git a/packages/server/src/index.ts b/packages/server/src/index.ts
index dfcf52c1..5c6ebebc 100644
--- a/packages/server/src/index.ts
+++ b/packages/server/src/index.ts
@@ -14,7 +14,14 @@ import path from "node:path";
import { config as loadDotenv } from "dotenv";
import { serve } from "@hono/node-server";
import { buildAppDeps, createApp } from "./app.js";
+import { ADMIN_USER_ID } from "./auth/service.js";
import { resolveServerConfig } from "./config.js";
+import {
+ clearInitialAdminPassword,
+ readInitialAdminPassword,
+ renderInitialPasswordNotice,
+ storeInitialAdminPassword,
+} from "./initial-password.js";
import { applyProxySettings, installGlobalProxyDispatcher } from "./net/proxy.js";
import { loopbackHostRoles } from "./services/preview-token.js";
import { acquireServerLock, liveServerLock, releaseServerLock } from "./lock.js";
@@ -60,15 +67,29 @@ const app = createApp(deps);
// Built-in admin seed (idempotent): creates admin and adopts default_project when the
// users table is empty. The returned initial password (random unless pinned via
-// PENGUIN_SEED_ADMIN_PASSWORD) is printed here once — the only place it is ever shown.
+// PENGUIN_SEED_ADMIN_PASSWORD) is persisted in the data root while it remains the
+// initial one, and EVERY startup re-prints the framed reminder until the password is
+// changed (any password update for admin removes the file — see initial-password.ts).
+// Never printed (or persisted) in desktop mode: the seed there is fully random by design
+// (config.ts) and sign-in goes through the shell's one-shot token, so showing it would
+// only leak a credential into a log nobody needs.
const seededAdminPassword = await deps.authService.seedAdmin();
-// Never printed in desktop mode: the seed there is fully random by design (config.ts)
-// and sign-in goes through the shell's one-shot token, so showing it would only leak a
-// credential into a log nobody needs.
-if (seededAdminPassword !== null && config.desktopToken === null) {
- console.log(
- `Seeded built-in admin "admin" — initial password: ${seededAdminPassword} (change it after first sign-in)`,
- );
+if (config.desktopToken === null) {
+ if (seededAdminPassword !== null) {
+ storeInitialAdminPassword(config.root, seededAdminPassword);
+ }
+ if (deps.authService.adminPasswordIsInitial()) {
+ const initialPassword = seededAdminPassword ?? readInitialAdminPassword(config.root);
+ // Roots seeded before the password was persisted have no file: stay silent — the
+ // plaintext is unrecoverable, and a reminder with nothing to type is pure nagging.
+ if (initialPassword !== null) {
+ console.log(renderInitialPasswordNotice(ADMIN_USER_ID, initialPassword));
+ }
+ } else {
+ // Heal: the flag was cleared while the file survived (e.g. the password was changed
+ // under a build that predates the file) — a stale plaintext must not outlive it.
+ clearInitialAdminPassword(config.root);
+ }
}
// Schedule scheduler: startup reconciliation (missed, don't backfill) + periodic scan; only active while the server is running.
diff --git a/packages/server/src/initial-password.ts b/packages/server/src/initial-password.ts
new file mode 100644
index 00000000..b05554f7
--- /dev/null
+++ b/packages/server/src/initial-password.ts
@@ -0,0 +1,79 @@
+/**
+ * Initial-admin-password persistence (`<root>/initial-admin-password`) and the startup
+ * reminder notice.
+ *
+ * The seeded admin password used to be printed exactly once, at first seed; if that line
+ * scrolled away unread, the credential was unrecoverable. The plaintext is now kept in
+ * the data root FOR AS LONG AS the admin password remains the initial one, so every
+ * server start — and `penguin web` attaching to an already-running instance — can
+ * re-print it inside a hard-to-miss ASCII frame together with the change-it reminder.
+ *
+ * The file is removed the moment the admin's password is updated by any path (self
+ * change, desktop set, or an admin reset picking a new value — the reset re-arms the
+ * initial FLAG, but the file's content would be stale, and an admin-chosen password is
+ * never persisted). Only the auto-generated / PENGUIN_SEED_ADMIN_PASSWORD seed value is
+ * ever stored, with owner-only permissions; the SQLite db next to it already holds
+ * strictly more sensitive data. Legacy roots seeded before this file existed simply have
+ * no file: the reminder then stays silent (the plaintext is genuinely unrecoverable).
+ *
+ * Published as `@prismshadow/penguin-server/initial-password` (side-effect-free, like
+ * ./lock) so the CLI can print the same notice when it attaches to a live instance.
+ */
+import fs from "node:fs";
+import path from "node:path";
+
+export function initialAdminPasswordPath(root: string): string {
+ return path.join(root, "initial-admin-password");
+}
+
+/** Persists the seeded plaintext (owner-only file). Best-effort: the seed itself must not fail on an exotic filesystem — the reminder just degrades to first-start-only. */
+export function storeInitialAdminPassword(root: string, password: string): void {
+ try {
+ fs.writeFileSync(initialAdminPasswordPath(root), `${password}\n`, { mode: 0o600 });
+ } catch {
+ // e.g. a read-only root: the password was still printed once by the seed path.
+ }
+}
+
+/** The stored plaintext, or null when absent/unreadable/empty. */
+export function readInitialAdminPassword(root: string): string | null {
+ try {
+ const value = fs.readFileSync(initialAdminPasswordPath(root), "utf8").trim();
+ return value === "" ? null : value;
+ } catch {
+ return null;
+ }
+}
+
+/** Removes the stored plaintext (idempotent, best-effort). */
+export function clearInitialAdminPassword(root: string): void {
+ try {
+ fs.rmSync(initialAdminPasswordPath(root), { force: true });
+ } catch {
+ // Best-effort: a leftover file only re-prints a password that no longer works.
+ }
+}
+
+/** Interior padding (spaces) between the frame bars and the text on each side. */
+const NOTICE_PADDING = 3;
+
+/**
+ * The framed reminder block, ready for console.log. Plain ASCII (`+`/`-`/`|`) rather
+ * than box-drawing characters: the server may run under terminals and log collectors
+ * with non-UTF-8 code pages (legacy Windows consoles above all), and a misrendered frame
+ * would bury exactly the line it exists to highlight. Width follows the longest line, so
+ * a long pinned password widens the frame instead of breaking it.
+ */
+export function renderInitialPasswordNotice(userId: string, password: string): string {
+ const lines = [
+ `Web sign-in: ${userId} / ${password}`,
+ "",
+ "This is the initial password and it has not been changed yet.",
+ "Please sign in and change it soon (user menu -> Change password).",
+ ];
+ const width = Math.max(...lines.map((line) => line.length));
+ const bar = `+${"-".repeat(width + NOTICE_PADDING * 2)}+`;
+ const pad = " ".repeat(NOTICE_PADDING);
+ const body = lines.map((line) => `|${pad}${line.padEnd(width)}${pad}|`);
+ return [bar, ...body, bar].join("\n");
+}
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index 06116d84..38989de2 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -40,6 +40,7 @@ import {
} from "@prismshadow/penguin-core";
import type {
ApproveFn,
+ BackgroundCommandInfo,
CompactAvailability,
OmniMessage,
ProxyEnvPolicy,
@@ -105,6 +106,12 @@ export interface RuntimeSession {
material?: { userText: string; assistantText: string };
signal?: AbortSignal;
}): Promise<SessionTitleResult>;
+ /** Background command processes owned by the Session's environment (core `Session.listBackgroundCommands`). Optional: test fakes may omit it. */
+ listBackgroundCommands?(): BackgroundCommandInfo[];
+ /** Kills one background command process (core `Session.killBackgroundCommand`); false when the id is unknown. Optional, like listBackgroundCommands. */
+ killBackgroundCommand?(processId: string): boolean;
+ /** Releases environment resources — kills the remaining background processes (core `Session.dispose`). Optional, idempotent. */
+ dispose?(): void;
}
/** The underlying loader behind get-or-resume-or-heal. */
@@ -864,6 +871,37 @@ export class SessionManager {
return true;
}
+ /**
+ * Background command processes of a LOADED session (empty when the entry is not in
+ * the active table — a resumed entry starts with a fresh environment and can only
+ * ever report an empty list, so nothing is resurrected just to answer a poll).
+ */
+ listProcesses(sessionId: string): BackgroundCommandInfo[] {
+ return this.entries.get(sessionId)?.session.listBackgroundCommands?.() ?? [];
+ }
+
+ /** Kills one background command process of a loaded session; false when the session isn't loaded or the id is unknown. */
+ killProcess(sessionId: string, processId: string): boolean {
+ const entry = this.entries.get(sessionId);
+ if (!entry) return false;
+ const killed = entry.session.killBackgroundCommand?.(processId) ?? false;
+ if (killed) entry.lastActivityMs = Date.now();
+ return killed;
+ }
+
+ /**
+ * Disposes a just-removed entry's runtime — after its in-flight drive (if any)
+ * settles, so interrupt cleanup never races a dying environment. Deleting a Session /
+ * Agent / Project is the one intent that must also end the background processes the
+ * conversation started (a dev server surviving its deleted conversation is
+ * unreachable from every UI, running forever).
+ */
+ private disposeRemoved(entry: RuntimeEntry): void {
+ const dispose = (): void => entry.session.dispose?.();
+ if (entry.running) void entry.running.then(dispose, dispose);
+ else dispose();
+ }
+
/**
* Before deleting a Project, converge all its active runs and clear them out of the
* active table. Returns the in-flight drive Promises of the affected entries: the
@@ -878,6 +916,7 @@ export class SessionManager {
entry.abort?.abort();
if (entry.running) runnings.push(entry.running);
this.entries.delete(key);
+ this.disposeRemoved(entry);
}
return runnings;
}
@@ -900,6 +939,7 @@ export class SessionManager {
entry.abort?.abort();
if (entry.running) runnings.push(entry.running);
this.entries.delete(key);
+ this.disposeRemoved(entry);
}
return runnings;
}
@@ -926,6 +966,7 @@ export class SessionManager {
entry.approvals.denyAll();
entry.abort?.abort();
this.entries.delete(sessionId);
+ this.disposeRemoved(entry);
return entry.running ? [entry.running] : [];
}
@@ -964,6 +1005,11 @@ export class SessionManager {
for (const [key, entry] of this.entries) {
if (entry.status !== "idle" || entry.approvals.size !== 0 || entry.running !== null) continue;
if (entry.followUps.length > 0) continue; // queued follow-ups must not be evicted with the entry
+ // A live background process (e.g. a dev server the conversation started) pins the
+ // entry: eviction would strand the process — a resumed entry starts with a fresh
+ // environment, so the process list and its stop control would go blind while the
+ // OS process kept running. Exited-but-listed processes don't pin anything.
+ if (entry.session.listBackgroundCommands?.().some((p) => p.running)) continue;
if (now - entry.lastActivityMs <= idleMs) continue;
this.entries.delete(key);
}
diff --git a/packages/server/src/services/admin-service.ts b/packages/server/src/services/admin-service.ts
index cf386cb2..5e0bf43c 100644
--- a/packages/server/src/services/admin-service.ts
+++ b/packages/server/src/services/admin-service.ts
@@ -25,6 +25,13 @@ export interface AdminServiceDeps {
authSessions: AuthSessionsRepo;
projects: ProjectsRepo;
projectService: ProjectService;
+ /**
+ * Fired after a password reset. The server wires it to drop the stored
+ * initial-password plaintext once it goes stale (a reset re-arms the initial FLAG,
+ * but with an admin-chosen value the stored seed no longer matches — see
+ * initial-password.ts); test constructions may omit it.
+ */
+ onPasswordChanged?: (userId: string) => void;
now?: () => Date;
}
@@ -81,6 +88,7 @@ export class AdminService {
}
this.deps.users.updatePassword(userId, await hashPassword(password), true);
this.deps.authSessions.deleteByUser(userId);
+ this.deps.onPasswordChanged?.(userId);
}
/** Delete user: the built-in admin cannot be deleted; owned Projects (including data directories) are deleted along with it. */
diff --git a/packages/server/test/initial-password.test.ts b/packages/server/test/initial-password.test.ts
new file mode 100644
index 00000000..df86fe68
--- /dev/null
+++ b/packages/server/test/initial-password.test.ts
@@ -0,0 +1,109 @@
+/**
+ * Initial-admin-password persistence and reminder notice: file roundtrip, notice shape,
+ * and the app wiring that drops the stored plaintext the moment it goes stale (self
+ * change / admin reset of the admin), while other users' password events leave it alone.
+ */
+import fs from "node:fs";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import {
+ initialAdminPasswordPath,
+ readInitialAdminPassword,
+ renderInitialPasswordNotice,
+ storeInitialAdminPassword,
+ clearInitialAdminPassword,
+} from "../src/initial-password.js";
+import {
+ apiClient,
+ createTestApp,
+ loginAdmin,
+ provisionUser,
+ TEST_ADMIN_PASSWORD,
+} from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+
+describe("initial password file", () => {
+ let t: TestApp;
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ it("stores, reads back and clears the plaintext in the data root", () => {
+ expect(readInitialAdminPassword(t.root)).toBeNull();
+ storeInitialAdminPassword(t.root, "penguin-1234");
+ expect(fs.existsSync(path.join(t.root, "initial-admin-password"))).toBe(true);
+ expect(readInitialAdminPassword(t.root)).toBe("penguin-1234");
+ clearInitialAdminPassword(t.root);
+ expect(readInitialAdminPassword(t.root)).toBeNull();
+ // Idempotent on an already-missing file.
+ clearInitialAdminPassword(t.root);
+ expect(readInitialAdminPassword(t.root)).toBeNull();
+ });
+
+ it("treats an empty or whitespace-only file as absent", () => {
+ fs.writeFileSync(initialAdminPasswordPath(t.root), " \n");
+ expect(readInitialAdminPassword(t.root)).toBeNull();
+ });
+
+ it("self password change drops the stored plaintext for admin", async () => {
+ storeInitialAdminPassword(t.root, t.adminPassword);
+ const admin = await loginAdmin(t.app);
+ const res = await apiClient(t.app, admin.cookie).put("/api/me/password", {
+ oldPassword: TEST_ADMIN_PASSWORD,
+ newPassword: "changed-password-1",
+ });
+ expect(res.status).toBe(204);
+ expect(readInitialAdminPassword(t.root)).toBeNull();
+ expect(t.deps.authService.adminPasswordIsInitial()).toBe(false);
+ });
+
+ it("admin password reset of the admin drops the stored plaintext; resets of other users keep it", async () => {
+ storeInitialAdminPassword(t.root, t.adminPassword);
+ const admin = await loginAdmin(t.app);
+ await provisionUser(t.app, "alice", "password-123");
+ // Resetting ANOTHER user leaves the admin's stored seed in place.
+ const other = await apiClient(t.app, admin.cookie).post("/api/admin/users/alice/password", {
+ password: "password-456",
+ });
+ expect(other.status).toBe(204);
+ expect(readInitialAdminPassword(t.root)).toBe(t.adminPassword);
+ // Resetting the ADMIN itself replaces the password with an admin-chosen value the
+ // file no longer matches: the stale plaintext must go, even though the initial FLAG
+ // is re-armed by the reset.
+ const self = await apiClient(t.app, admin.cookie).post(
+ `/api/admin/users/${admin.user.userId}/password`,
+ { password: "password-789" },
+ );
+ expect(self.status).toBe(204);
+ expect(readInitialAdminPassword(t.root)).toBeNull();
+ expect(t.deps.authService.adminPasswordIsInitial()).toBe(true);
+ });
+});
+
+describe("renderInitialPasswordNotice", () => {
+ it("frames the credentials and the reminder in an aligned ASCII box", () => {
+ const notice = renderInitialPasswordNotice("admin", "penguin-1234");
+ const lines = notice.split("\n");
+ expect(lines.length).toBeGreaterThanOrEqual(5);
+ expect(lines[0]).toMatch(/^\+-+\+$/);
+ expect(lines.at(-1)).toBe(lines[0]);
+ // Every row is exactly as wide as the frame, so the right edge lines up.
+ for (const line of lines) expect(line.length).toBe(lines[0]!.length);
+ for (const line of lines.slice(1, -1)) expect(line).toMatch(/^\|.*\|$/);
+ expect(notice).toContain("admin / penguin-1234");
+ expect(notice).toContain("change it soon");
+ // Plain ASCII only: box-drawing characters misrender on legacy code pages.
+ expect([...notice].every((ch) => ch.codePointAt(0)! < 128)).toBe(true);
+ });
+
+ it("widens with a long pinned password instead of breaking the frame", () => {
+ const long = "a-very-long-pinned-password-for-automation-use-only";
+ const lines = renderInitialPasswordNotice("admin", long).split("\n");
+ for (const line of lines) expect(line.length).toBe(lines[0]!.length);
+ expect(lines.some((line) => line.includes(long))).toBe(true);
+ });
+});
diff --git a/packages/server/tsup.config.ts b/packages/server/tsup.config.ts
index 794fa73d..10b02392 100644
--- a/packages/server/tsup.config.ts
+++ b/packages/server/tsup.config.ts
@@ -1,9 +1,15 @@
import { defineConfig } from "tsup";
export default defineConfig({
- // Explicitly name entries to preserve the dist/api/types.js and dist/lock.js subpaths
- // (exports "./api" and "./lock" point to them; lock is side-effect-free for pre-checks).
- entry: { index: "src/index.ts", "api/types": "src/api/types.ts", lock: "src/lock.ts" },
+ // Explicitly name entries to preserve the dist/api/types.js, dist/lock.js and
+ // dist/initial-password.js subpaths (exports "./api", "./lock" and "./initial-password"
+ // point to them; lock and initial-password are side-effect-free for CLI pre-checks).
+ entry: {
+ index: "src/index.ts",
+ "api/types": "src/api/types.ts",
+ lock: "src/lock.ts",
+ "initial-password": "src/initial-password.ts",
+ },
format: ["esm"],
target: "node22",
dts: true,
diff --git a/packages/web/e2e/chat.spec.mjs b/packages/web/e2e/chat.spec.mjs
index 3635a637..098c2222 100644
--- a/packages/web/e2e/chat.spec.mjs
+++ b/packages/web/e2e/chat.spec.mjs
@@ -62,9 +62,10 @@ test("chat + tool approval + stats/cost/copy + traces + files", async ({ page })
// Live header statistics: the elapsed chip ticks once per second while the task runs (the
// pending approval below keeps it running), so its text must advance with no further server
- // event. Scoped to the header stats container (div.hidden …): the per-reply footer reuses
- // the same 用时 ("elapsed") label once the turn's stats line lands.
- const headerElapsed = page.locator('div.hidden span[title="用时"]');
+ // event. Scoped to the toolbar's details trigger (the chips now double as the "Session 信息"
+ // button at the far right): the per-reply footer reuses the same 用时 ("elapsed") label once
+ // the turn's stats line lands.
+ const headerElapsed = page.locator('button[title="Session 信息"] span[title="用时"]');
const elapsedBefore = await headerElapsed.textContent();
await expect(headerElapsed).not.toHaveText(elapsedBefore);
diff --git a/packages/web/e2e/draft-park.spec.mjs b/packages/web/e2e/draft-park.spec.mjs
new file mode 100644
index 00000000..9f7678fa
--- /dev/null
+++ b/packages/web/e2e/draft-park.spec.mjs
@@ -0,0 +1,72 @@
+/**
+ * Parked draft conversations (draft-sessions.ts): typing in the new-chat composer and
+ * clicking "New chat" again parks the text as a draft row in the sidebar list; opening
+ * the row resumes the full draft at /chat/draft-…; sending it creates the real session
+ * and removes the row; deleting from the row's hover action discards it after a confirm.
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "parkuser";
+const P = "password123";
+
+test("new-chat click parks typed text as a sendable draft conversation", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+
+ await page.goto(`${BASE}/chat/new`);
+ const ta = page.getByPlaceholder(/输入消息/);
+ await ta.waitFor();
+ await ta.fill("draft to park: build me a metronome");
+
+ // Clicking "New chat" parks the typed text: a 草稿 group appears with the row, and the
+ // composer comes back empty.
+ await page.getByRole("button", { name: "新建对话" }).first().click();
+ const draftGroup = page.getByRole("button", { name: /折叠|展开/ }).filter({ hasText: "草稿" });
+ await expect(draftGroup).toBeVisible();
+ const row = page.getByText("draft to park: build me a metronome").first();
+ await expect(row).toBeVisible();
+ await expect(ta).toHaveValue("");
+
+ // Opening the row resumes the draft (route /chat/draft-…, text restored).
+ await row.click();
+ await expect(page).toHaveURL(/\/chat\/draft-[0-9a-f]{8}$/);
+ await expect(page.getByPlaceholder(/输入消息/)).toHaveValue(
+ "draft to park: build me a metronome",
+ );
+
+ // Sending converts it into a real session and the draft row disappears.
+ await page.getByRole("button", { name: "发送", exact: true }).click();
+ await expect(page).toHaveURL(/\/chat\/session-/, { timeout: 15_000 });
+ await expect(page.getByText("draft to park: build me a metronome").first()).toBeVisible(); // the sent message
+ await expect(draftGroup).toHaveCount(0); // group hides once the list is empty
+
+ // Park another one and delete it from the row (confirm dialog).
+ await page.getByRole("button", { name: "新建对话" }).first().click();
+ await page.getByPlaceholder(/输入消息/).fill("second parked draft");
+ await page.getByRole("button", { name: "新建对话" }).first().click();
+ const row2 = page.getByText("second parked draft").first();
+ await expect(row2).toBeVisible();
+ await row2.hover();
+ await page.getByRole("button", { name: "删除草稿" }).first().click();
+ await page.getByRole("dialog").getByRole("button", { name: "删除", exact: true }).click();
+ await expect(page.getByText("second parked draft")).toHaveCount(0);
+});
diff --git a/packages/web/e2e/mock-llm.mjs b/packages/web/e2e/mock-llm.mjs
index 47194737..ea36b200 100644
--- a/packages/web/e2e/mock-llm.mjs
+++ b/packages/web/e2e/mock-llm.mjs
@@ -10,6 +10,9 @@
* - parent asked to delegate ("run a subagent") -> tool_use(run_subagent)
* - a repeat delegation later in the same conversation ("run another subagent", keyed on the
* LAST message so history can't shadow it) -> tool_use(run_subagent) again
+ * - "background server test" -> tool_use(exec_command) whose command outlives its yield
+ * window (processes.spec: the promoted background process shows in the session's
+ * process list and can be stopped from there)
* - "slow stream test" -> tool_use(exec_command) with a command that prints one line
* every 200ms for ~8s (reload-midstream.spec reloads while its output streams)
* - "slow text test" -> a long text streamed one delta every 200ms for ~8s
@@ -296,6 +299,19 @@ const server = http.createServer((req, res) => {
return;
}
+ // Background-process test case (processes.spec): an exec_command that outlives its
+ // yield window — the engine promotes it to a background process with a process_id,
+ // which the session's process list (details popover) must surface and be able to stop.
+ // The tiny yield keeps the turn snappy; `sleep 600` stands in for a dev server.
+ if (flat.includes("background server test") && !hasToolResult) {
+ block(res, 0, { type: "tool_use", id: "toolu_bg_1", name: "exec_command", input: {} }, [
+ { type: "input_json_delta", partial_json: '{"cmd": "sleep 600",' },
+ { type: "input_json_delta", partial_json: ' "yield_time_ms": 300}' },
+ ]);
+ messageStop(res, "tool_use", 14);
+ return;
+ }
+
// Slow tool-output test case (reload-midstream.spec): a real exec_command whose output
// streams one line every 200ms for ~8s — long enough to reload the page mid-stream and
// watch the output keep growing afterwards.
diff --git a/packages/web/e2e/processes.spec.mjs b/packages/web/e2e/processes.spec.mjs
new file mode 100644
index 00000000..e54c9d27
--- /dev/null
+++ b/packages/web/e2e/processes.spec.mjs
@@ -0,0 +1,90 @@
+/**
+ * Session background-process list (details popover):
+ * a task whose exec_command outlives its yield window becomes a background process —
+ * the header's stats trigger gains a running-services count, the details card lists the
+ * process (cmd + pid + start time) with a stop button, stopping it clears both, and the
+ * card's other rows (model / workspace / created / per-line stats / trace file path)
+ * render in their new layout. The mock's "background server test" branch drives it
+ * (`sleep 600` with a 300ms yield — see mock-llm.mjs).
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "procuser";
+const P = "password123";
+
+test("background process appears in the details card and can be stopped", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+
+ const projects = await (await page.request.get(`${BASE}/api/projects`)).json();
+ const projectId = projects.projects[0].projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ pricing: { cacheRead: 1, cacheWrite: 5, output: 10 },
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+
+ // allow-all: the exec runs without a manual approval stop.
+ const sess = await (
+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {
+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },
+ })
+ ).json();
+ const sessionId = sess.session.sessionId;
+
+ await page.goto(`${BASE}/chat/${sessionId}`);
+ const ta = page.getByPlaceholder(/输入消息/);
+ await ta.waitFor();
+ await ta.fill("background server test");
+ await page.getByRole("button", { name: "发送" }).click();
+
+ // The turn finishes with the command promoted to background: the stats trigger (far
+ // right; it doubles as the "Session 信息" details button) gains the services count.
+ const detailsBtn = page.locator('button[title="Session 信息"]');
+ await expect(detailsBtn.locator('span[title="1 个运行中的服务"]')).toBeVisible({
+ timeout: 30_000,
+ });
+
+ // Open the details card by clicking the stats themselves (no separate info icon at
+ // this width — the chips are the trigger).
+ await detailsBtn.click();
+
+ // New layout: a bulleted list with one stat per line, tokens first with the cache hit
+ // rate in parens (from the recorded usage row).
+ await expect(page.getByText(/总 Token/).first()).toBeVisible();
+ await expect(page.getByText(/缓存命中率 \d+%/).first()).toBeVisible();
+ // Trace file row names the actual .jsonl path.
+ await expect(page.getByText("轨迹文件")).toBeVisible();
+ await expect(page.getByText(/\.jsonl/).first()).toBeVisible();
+
+ // The process list row: the command, its pid line, and a working stop button.
+ await expect(page.getByText("会话进程")).toBeVisible();
+ const row = page.locator("li", { hasText: "sleep 600" }).first();
+ await expect(row).toBeVisible();
+ await expect(row.getByText(/pid \d+/)).toBeVisible();
+ await row.getByRole("button", { name: "停止" }).click();
+
+ // The kill drops the process from the registry: the row disappears on the follow-up
+ // refresh and the header count goes with it.
+ await expect(page.getByText("会话进程")).toHaveCount(0, { timeout: 10_000 });
+ await expect(detailsBtn.locator('span[title="1 个运行中的服务"]')).toHaveCount(0);
+
+ // The server-side list agrees (the registry entry is gone, not merely marked exited).
+ const procs = await (
+ await page.request.get(`${BASE}/api/sessions/${sessionId}/processes`)
+ ).json();
+ expect(procs.processes).toEqual([]);
+});
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index ee75f6dc..b69bb8f3 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -57,6 +57,7 @@ import type {
SessionCreateResponse,
SessionPatchRequest,
SessionResponse,
+ SessionProcessesResponse,
SessionsResponse,
SessionTracesResponse,
SkillArchiveInstallRequest,
@@ -376,6 +377,17 @@ export const postRetryNow = (sessionId: string) =>
body: {},
});
+/** Background processes the conversation started (details popover list); an evicted/never-loaded runtime reports an empty list. */
+export const getSessionProcesses = (sessionId: string) =>
+ apiFetch<SessionProcessesResponse>(`/api/sessions/${encodeURIComponent(sessionId)}/processes`);
+
+/** Stops one background process (404 process_not_found when it already exited or the runtime is gone — callers just refresh). */
+export const killSessionProcess = (sessionId: string, processId: string) =>
+ apiFetch<void>(
+ `/api/sessions/${encodeURIComponent(sessionId)}/processes/${encodeURIComponent(processId)}/kill`,
+ { method: "POST", body: {} },
+ );
+
/** Mid-run steering: queues a message for the running Task (delivered between turns as a standalone `[user_steering]` user message); 409 not_running when no Task is in progress. */
export const postSteer = (sessionId: string, body: SteerRequest) =>
apiFetch<void>(`/api/sessions/${encodeURIComponent(sessionId)}/steer`, {
diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsx
index 6cfb0bc7..f43d0aaf 100644
--- a/packages/web/src/components/layout/app-layout.tsx
+++ b/packages/web/src/components/layout/app-layout.tsx
@@ -18,6 +18,7 @@ import { GlyphIcon } from "../ui/glyph-icon";
import { NAV_ICONS } from "../ui/icons";
import { NEW_CHAT_ICON, Sidebar } from "./sidebar";
import { DRAFT_SESSION_ID } from "../../features/chat/chat-page";
+import { parkActiveDraft } from "../../features/chat/draft-sessions";
import { ChangePasswordDialog } from "../account/change-password-dialog";
/** "Last conversation" glyph (chat lines + resume arrow), used only by the rail. */
@@ -40,7 +41,7 @@ const railItemClass = (active: boolean) =>
function CollapsedRail({ onExpand }: { onExpand: () => void }) {
const { user } = useAuth();
const navigate = useNavigate();
- const { agents, setCurrentAgentId } = useProject();
+ const { agents, currentProject, setCurrentAgentId } = useProject();
const { sessions, loading } = useSessions();
/**
* Passive (active=false): never triggers a fetch — the rail mirrors whatever the lazy
@@ -64,8 +65,9 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
navigate(`/chat/${lastSession.sessionId}`);
};
- /** Mirrors the pinned sidebar's "New chat": default_agent draft, falling back to the first Agent (an unresolved list defers resolution to the draft page). */
+ /** Mirrors the pinned sidebar's "New chat": parks any typed-but-unsent draft text first (draft-sessions.ts), then a default_agent draft, falling back to the first Agent (an unresolved list defers resolution to the draft page). */
const newChat = () => {
+ if (user && currentProject) parkActiveDraft(user.userId, currentProject.projectId);
const agentId = (agents.find((a) => a.agentId === "default_agent") ?? agents[0])?.agentId;
if (agentId) setCurrentAgentId(agentId);
navigate(`/chat/${DRAFT_SESSION_ID}`, agentId ? { state: { agentId } } : undefined);
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index f54755c7..dab8245f 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -73,6 +73,13 @@ import { Segmented } from "../ui/segmented";
import { SkeletonList } from "../ui/skeleton";
import { DRAFT_SESSION_ID } from "../../features/chat/chat-page";
import { clearDraft, sessionDraftKey } from "../../features/chat/draft-cache";
+import {
+ draftSessionTitle,
+ parkActiveDraft,
+ removeDraftSession,
+ useDraftSessions,
+} from "../../features/chat/draft-sessions";
+import type { DraftSessionEntry } from "../../features/chat/draft-sessions";
import { CreateProjectDialog, ProjectSettingsDialog } from "./project-dialogs";
import { ChangePasswordDialog } from "../account/change-password-dialog";
import { ProxySettingsDialog } from "../account/proxy-settings-dialog";
@@ -130,6 +137,9 @@ function saveGroupSet(storageKey: string | null, next: ReadonlySet<string>): voi
*/
const folderKey = (groupKey: string, category: FolderCategory) => `${category}\0${groupKey}`;
+/** Collapse-state key of the parked-drafts group ("\0" keeps it clear of Agent ids and Workspace paths). */
+const DRAFTS_GROUP_KEY = "\0drafts";
+
/** Session status dot: running pulses green, compacting shows an amber dot; idle shows nothing. */
function StatusDot({ session }: { session: SessionInfo }) {
if (session.status === "running") {
@@ -271,6 +281,10 @@ export function Sidebar({
/** Session pending delete confirmation (null = none). */
const [deletingSession, setDeletingSession] = useState<SessionInfo | null>(null);
const [deletingBusy, setDeletingBusy] = useState(false);
+ /** Parked draft conversation pending delete confirmation (null = none). */
+ const [deletingDraft, setDeletingDraft] = useState<DraftSessionEntry | null>(null);
+ /** Parked draft conversations of this user × Project, newest first (reactive module store). */
+ const draftEntries = useDraftSessions(user?.userId ?? null, currentProjectId);
/** Session currently being renamed (null = none) and the title being typed. */
const [renamingSession, setRenamingSession] = useState<SessionInfo | null>(null);
const [renameText, setRenameText] = useState("");
@@ -467,6 +481,10 @@ export function Sidebar({
* ("" = a temporary workspace), pre-filling the draft's Workspace selection the same way.
*/
const newChat = (agentId?: string, workspace?: string) => {
+ // Typed-but-unsent text in the ACTIVE new-chat draft becomes a parked draft
+ // conversation first (a row in the list below, sendable anytime — draft-sessions.ts),
+ // so this click always lands on an empty composer and never silently shelves content.
+ if (user && currentProjectId) parkActiveDraft(user.userId, currentProjectId);
if (agentId) setCurrentAgentId(agentId);
const state = {
...(agentId ? { agentId } : {}),
@@ -476,6 +494,16 @@ export function Sidebar({
onNavigate?.();
};
+ /** Confirmed parked-draft deletion: drops the entry; a deleted draft that is open falls back to the plain new-chat page. */
+ const confirmDeleteDraft = () => {
+ if (!deletingDraft) return;
+ if (user && currentProjectId) {
+ removeDraftSession(user.userId, currentProjectId, deletingDraft.id);
+ }
+ if (activeSessionId === deletingDraft.id) navigate(`/chat/${DRAFT_SESSION_ID}`);
+ setDeletingDraft(null);
+ };
+
/** Target of the menu's "New chat": default_agent, falling back to the first Agent (if the list isn't ready yet, resolution is deferred to the draft page). */
const defaultAgentId = (agents.find((a) => a.agentId === "default_agent") ?? agents[0])?.agentId;
@@ -812,6 +840,39 @@ export function Sidebar({
<GroupModeToggle value={groupMode} onChange={setGroupMode} />
</div>
+ {/* Parked draft conversations (unsent new chats, newest first): pinned above both
+ grouping modes — they belong to no Agent or Workspace until sent. Hidden
+ entirely while there are none. */}
+ {draftEntries.length > 0 && (
+ <div className="pt-2.5">
+ <GroupHeader
+ open={!collapsedGroups.has(DRAFTS_GROUP_KEY)}
+ onToggle={() => toggleGroup(DRAFTS_GROUP_KEY)}
+ icon={
+ <span className="shrink-0 text-gray-400 dark:text-gray-500">
+ <Icon d={NEW_CHAT_ICON} size={14} />
+ </span>
+ }
+ label={S.chat.draftGroup}
+ uppercase
+ count={draftEntries.length}
+ />
+ {!collapsedGroups.has(DRAFTS_GROUP_KEY) && (
+ <ul className="space-y-0.5">
+ {draftEntries.map((entry) => (
+ <DraftRow
+ key={entry.id}
+ entry={entry}
+ active={entry.id === activeSessionId}
+ onOpen={() => go(`/chat/${entry.id}`)}
+ onDelete={() => setDeletingDraft(entry)}
+ />
+ ))}
+ </ul>
+ )}
+ </div>
+ )}
+
{groupMode === "agent" ? (
loading && agents.length === 0 ? (
<SkeletonList rows={5} />
@@ -1216,10 +1277,81 @@ export function Sidebar({
: ""}
</p>
</ConfirmModal>
+
+ {/* Delete parked-draft confirmation: purely local (localStorage entry), but the typed
+ content is gone for good, which deserves the same explicit stop as a session. */}
+ <ConfirmModal
+ open={deletingDraft !== null}
+ title={S.chat.deleteDraft}
+ confirmLabel={S.common.delete}
+ onClose={() => setDeletingDraft(null)}
+ onConfirm={confirmDeleteDraft}
+ >
+ <p className="text-sm text-gray-600 dark:text-gray-300">
+ {deletingDraft
+ ? S.chat.deleteDraftConfirm(draftSessionTitle(deletingDraft) || S.chat.draftUntitled)
+ : ""}
+ </p>
+ </ConfirmModal>
</div>
);
}
+/** Single parked-draft row: first line of the unsent text + hover delete (opening resumes the draft at `/chat/<draft-id>`). */
+function DraftRow({
+ entry,
+ active,
+ onOpen,
+ onDelete,
+}: {
+ entry: DraftSessionEntry;
+ active: boolean;
+ onOpen: () => void;
+ onDelete: () => void;
+}) {
+ const title = draftSessionTitle(entry) || S.chat.draftUntitled;
+ return (
+ <li>
+ <div
+ className={`group flex items-center rounded-md pr-1 transition-colors duration-150 ${
+ active
+ ? "bg-gray-200/70 dark:bg-gray-800"
+ : "hover:bg-gray-200/50 dark:hover:bg-gray-800/70"
+ }`}
+ >
+ <button
+ type="button"
+ onClick={onOpen}
+ className="flex min-w-0 flex-1 items-center gap-1.5 px-2.5 py-1.5 text-left"
+ >
+ <Truncated
+ text={title}
+ className={`min-w-0 flex-1 text-sm ${
+ active
+ ? "font-medium text-gray-900 dark:text-gray-100"
+ : "text-gray-700 dark:text-gray-300"
+ }`}
+ />
+ </button>
+ <div className="flex shrink-0 items-center">
+ <button
+ type="button"
+ title={S.chat.deleteDraft}
+ aria-label={S.chat.deleteDraft}
+ onClick={onDelete}
+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 opacity-0 transition-all duration-150 hover:bg-gray-300/60 hover:text-red-600 focus-visible:opacity-100 group-hover:opacity-100 dark:hover:bg-gray-700 dark:hover:text-red-400"
+ >
+ <Icon
+ d="M4 6h16M9 6V4.5A1.5 1.5 0 0 1 10.5 3h3A1.5 1.5 0 0 1 15 4.5V6M6 6v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V6M10 10.5v6M14 10.5v6"
+ size={14}
+ />
+ </button>
+ </div>
+ </div>
+ </li>
+ );
+}
+
/**
* Group-header pin toggle, shared by both grouping modes: revealed on header hover (or
* keyboard focus) while unpinned; once pinned it stays visible, doubling as the subtle
diff --git a/packages/web/src/features/agents/agents-page.tsx b/packages/web/src/features/agents/agents-page.tsx
index 17b8336a..46f07636 100644
--- a/packages/web/src/features/agents/agents-page.tsx
+++ b/packages/web/src/features/agents/agents-page.tsx
@@ -22,6 +22,7 @@ import { apiErrorText } from "../../lib/api-error";
import { SEMANTIC_ID_PATTERN } from "../../lib/semantic-id";
import { formatDateTime, formatRelativeDays } from "../../lib/format";
import { useDocumentTitle } from "../../lib/use-document-title";
+import { useAuth } from "../../state/auth";
import { useLocale } from "../../state/locale";
import { agentDisplayName, useProject } from "../../state/project";
import { Button } from "../../components/ui/button";
@@ -35,6 +36,7 @@ import { AgentAvatar } from "../../components/ui/agent-avatar";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { STAT_ICONS } from "../../lib/stat-icons";
import { DRAFT_SESSION_ID } from "../chat/chat-page";
+import { parkActiveDraft } from "../chat/draft-sessions";
import { ActivitySparkline } from "./activity-sparkline";
/** Built-in Agent shipped with every Project (default_agent only; the server also rejects deletion, so no delete entry point is shown here). */
@@ -77,6 +79,7 @@ export function AgentsPage() {
const navigate = useNavigate();
useDocumentTitle(S.nav.agents);
const { locale } = useLocale();
+ const { user } = useAuth();
const { currentProject, agents, agentsLoading, reloadAgents, setCurrentAgentId } = useProject();
const [createOpen, setCreateOpen] = useState(false);
const [agentId, setAgentId] = useState("");
@@ -138,6 +141,8 @@ export function AgentsPage() {
* rather than the previous one from the cache.
*/
const newChat = (agentId: string) => {
+ // Typed-but-unsent draft text becomes a parked draft conversation first (draft-sessions.ts).
+ if (user && projectId) parkActiveDraft(user.userId, projectId);
setCurrentAgentId(agentId);
navigate(`/chat/${DRAFT_SESSION_ID}`, { state: { agentId } });
};
diff --git a/packages/web/src/features/agents/skills-tab.tsx b/packages/web/src/features/agents/skills-tab.tsx
index faec1b8b..537ff182 100644
--- a/packages/web/src/features/agents/skills-tab.tsx
+++ b/packages/web/src/features/agents/skills-tab.tsx
@@ -37,6 +37,7 @@ import { SkillIcon, skillTileColor } from "../skills/skill-icon-view";
import { localizedShortText } from "../chat/skill-use";
import { DRAFT_SESSION_ID } from "../chat/chat-page";
import { draftKey, loadDraft, saveDraft } from "../chat/draft-cache";
+import { parkActiveDraft } from "../chat/draft-sessions";
import { buildImportPrompt } from "./skill-import-source";
/** <label> version of the button look (matches Button secondary sm; the Button component only renders <button>) — same as the Overview tab's snapshot-import label. */
@@ -185,6 +186,9 @@ export function SkillsTab({ agentId }: { agentId: string }) {
*/
const openChat = () => {
if (userId && projectId && trimmedSource) {
+ // Typed-but-unsent draft text becomes a parked draft conversation instead of being
+ // clobbered by the canned import prompt (draft-sessions.ts).
+ parkActiveDraft(userId, projectId);
const key = draftKey(userId, projectId);
saveDraft(key, {
...loadDraft(key),
diff --git a/packages/web/src/features/benchmark/benchmark-case-browser.tsx b/packages/web/src/features/benchmark/benchmark-case-browser.tsx
index 58a3c6ca..4518a546 100644
--- a/packages/web/src/features/benchmark/benchmark-case-browser.tsx
+++ b/packages/web/src/features/benchmark/benchmark-case-browser.tsx
@@ -70,6 +70,10 @@ interface MaterialGroupProps extends Props {
label: string;
hiddenLabel?: string;
defaultOpen?: boolean;
+ /** Auto-preview this group's root readme.md on first load. Exactly one group (the statement)
+ * may carry it: both groups now open by default, and two racing auto-previews would leave the
+ * preview pane on whichever listing happened to resolve last. */
+ autoPreviewReadme?: boolean;
onPreview: (material: CaseMaterial, path: string) => void;
}
@@ -129,6 +133,7 @@ function MaterialGroup({
label,
hiddenLabel,
defaultOpen = false,
+ autoPreviewReadme = false,
onPreview,
}: MaterialGroupProps) {
const [open, setOpen] = useState(defaultOpen);
@@ -152,7 +157,7 @@ function MaterialGroup({
.then((data) => {
if (cancelled) return;
setListing({ base: path, res: data });
- if (path === "" && !initialReadmeOpened.current) {
+ if (autoPreviewReadme && path === "" && !initialReadmeOpened.current) {
initialReadmeOpened.current = true;
const readme = data.entries.find(
(entry) => entry.kind === "file" && entry.name.toLowerCase() === "readme.md",
@@ -166,7 +171,17 @@ function MaterialGroup({
return () => {
cancelled = true;
};
- }, [projectId, agentId, benchmarkId, caseSummary.id, material, onPreview, open, path]);
+ }, [
+ projectId,
+ agentId,
+ benchmarkId,
+ caseSummary.id,
+ material,
+ autoPreviewReadme,
+ onPreview,
+ open,
+ path,
+ ]);
const crumbs = path === "" ? [] : path.split("/");
@@ -383,6 +398,7 @@ export function BenchmarkCaseBrowser({ projectId, agentId, benchmarkId, caseSumm
material="statement"
label={S.benchmark.taskMaterials}
defaultOpen
+ autoPreviewReadme
onPreview={previewPath}
/>
<MaterialGroup
@@ -393,6 +409,7 @@ export function BenchmarkCaseBrowser({ projectId, agentId, benchmarkId, caseSumm
material="rubric"
label={S.benchmark.rubric}
hiddenLabel={S.benchmark.agentHidden}
+ defaultOpen
onPreview={previewPath}
/>
</div>
diff --git a/packages/web/src/features/chat/chat-input.tsx b/packages/web/src/features/chat/chat-input.tsx
index eef78665..dcaaab1f 100644
--- a/packages/web/src/features/chat/chat-input.tsx
+++ b/packages/web/src/features/chat/chat-input.tsx
@@ -83,7 +83,7 @@ import { AgentAvatar } from "../../components/ui/agent-avatar";
import { Dropdown } from "../../components/ui/dropdown";
import { GlyphIcon } from "../../components/ui/glyph-icon";
import { noAutofill } from "../../components/ui/input";
-import { toastError } from "../../components/ui/toast";
+import { toastError, toastInfo } from "../../components/ui/toast";
import { SkillIcon } from "../skills/skill-icon-view";
import { ZoomableImage } from "../../components/ui/image-zoom";
import { ProviderLogo } from "../../components/ui/provider-logo";
@@ -2526,11 +2526,20 @@ export function ChatInput({
disabled={busy}
/>
) : (
- <span
+ /* Read-only display in session state: both the logo and the name come from the
+ Session DTO's paired fields (no prefix parsing). A button rather than a plain
+ span: the model is locked here, and clicking it explains the one way to switch
+ (the /model command) instead of doing nothing. */
+ <button
+ type="button"
title={modelRef?.modelId ?? ""}
- className="flex h-8 min-w-0 max-w-44 shrink items-center gap-1.5 px-1 text-gray-400 dark:text-gray-500"
+ // Short accessible name (the toast carries the full hint): the long copy
+ // contains the literal "发送"/"Send", which would collide with the send
+ // button's accessible name for assistive tech and name-based test queries.
+ aria-label={`${S.chat.model} ${modelRef?.modelId ?? ""}`}
+ onClick={() => toastInfo(S.chat.modelLockedHint)}
+ className="flex h-8 min-w-0 max-w-44 shrink cursor-help items-center gap-1.5 rounded-md px-1 text-gray-400 transition-colors duration-150 hover:text-gray-600 dark:text-gray-500 dark:hover:text-gray-300"
>
- {/* Read-only display in session state: both the logo and the name come from the Session DTO's paired fields (no prefix parsing). */}
<ProviderLogo
provider={modelRef?.provider ?? "custom"}
className="h-4 w-4 shrink-0"
@@ -2541,7 +2550,7 @@ export function ChatInput({
return m ? modelLabel(m) : (modelRef?.modelId ?? "…");
})()}
</span>
- </span>
+ </button>
)}
{/* One action button, never two: while running an empty composer means "Stop"
(abort), and typing turns the very same button into "Send" — which, mid-run,
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 2c22e4b6..0b8efe74 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -16,12 +16,13 @@
*/
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { ReactNode } from "react";
-import { useNavigate, useParams } from "react-router";
+import { useLocation, useNavigate, useParams } from "react-router";
import type {
AgentSummary,
ApprovalMode,
ModelRefDto,
ModelsResponse,
+ SessionProcessInfo,
SkillMetadataItem,
TaskCreateRequest,
TaskInputPart,
@@ -42,6 +43,7 @@ import { approvalKey, isModelAuthDead } from "../../lib/omni/stream-model";
import type { StreamModel } from "../../lib/omni/stream-model";
import { bucketCostUsd, liveSessionElapsedMs } from "../../lib/omni/task-stats";
import type { TaskStatsTracker } from "../../lib/omni/task-stats";
+import { useAuth } from "../../state/auth";
import { useTheme } from "../../state/theme";
import { useProject } from "../../state/project";
import { useSessions } from "../../state/sessions";
@@ -51,7 +53,6 @@ import { Skeleton } from "../../components/ui/skeleton";
import { Truncated } from "../../components/ui/truncated";
import { Dropdown } from "../../components/ui/dropdown";
import { EmptyState } from "../../components/ui/empty-state";
-import { NAV_ICONS } from "../../components/ui/icons";
import { toastError } from "../../components/ui/toast";
import { MessageStream } from "./message-stream";
import type { StreamRenderContext } from "./message-stream";
@@ -59,6 +60,7 @@ import { latestTaskHasSubagent, taskStartCount } from "./agent-topology";
import { ChatInput } from "./chat-input";
import { ConversationOutline, OutlineMenuButton, useOutlineRailFit } from "./conversation-outline";
import { DraftView } from "./draft-view";
+import { parkActiveDraft } from "./draft-sessions";
import { CHAT_DEFAULTS_CHANGED_EVENT, chatDefaultsChangedDetail } from "./chat-defaults-event";
import { advanceCostStat, applyUsageFetch, createCostStatHold } from "./header-stats";
import type { CostStatDisplay } from "./header-stats";
@@ -91,8 +93,22 @@ const STAT_ICONS = {
elapsed: "M12 21a9 9 0 1 0 0-18 9 9 0 0 0 0 18zm0-14v5l3 2",
// Files (folder)
folder: "M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",
+ // Running services (server rack: two stacked units with an indicator dot each)
+ services:
+ "M3 5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5zm0 11a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3zM7 6.5h.01M7 17.5h.01",
} as const;
+/** How often the background-process list refreshes while it can still change (a run may promote a command at any time; a running process can exit on its own). */
+const PROCESS_POLL_MS = 15_000;
+
+/**
+ * Docked panel swap sequencing: how long the outgoing panel gets to retract before the
+ * incoming one slides in. Matches the panels' own `transition-[width] duration-200`
+ * (files-panel.tsx / subagents-panel.tsx) — shorter would cut the retract off, longer
+ * would leave a dead gap.
+ */
+const PANEL_SWAP_MS = 200;
+
/** Iconized stat item: a symbol + a value, with the title giving the full meaning. */
function StatChip({ icon, value, label }: { icon: string; value: ReactNode; label: string }) {
return (
@@ -189,10 +205,15 @@ function headerStats(model: StreamModel, cost: CostStatDisplay): HeaderStats {
* Route id for a draft chat (`/chat/new`): the Session hasn't been persisted yet — the user may
* still want to change the model or configure a key first. The actual Session is only created
* once **the first message is sent** (once created, the model is locked into its meta).
- * Real session ids always start with `session-`, so there's no collision with this constant.
+ * Real session ids always start with `session-`, so there's no collision with this constant —
+ * nor with parked draft conversations, whose route ids start with `draft-` (draft-sessions.ts).
*/
export const DRAFT_SESSION_ID = "new";
+/** Parked-draft route id (`/chat/draft-…` — a draft conversation row in the sidebar list), or null. */
+export const parkedDraftIdOf = (routeSessionId: string | null): string | null =>
+ routeSessionId !== null && routeSessionId.startsWith("draft-") ? routeSessionId : null;
+
/**
* Server-enforced ceiling on paths per files/stat call (STAT_MAX_PATHS in the sessions routes,
* which 400s above it). A Task-level summary aggregates candidates across the whole Task and can
@@ -202,7 +223,9 @@ const STAT_PATHS_PER_REQUEST = 100;
export function ChatPage() {
const navigate = useNavigate();
+ const location = useLocation();
const params = useParams<{ sessionId?: string }>();
+ const { user } = useAuth();
const { currency } = useTheme();
const { currentProject, currentAgent, setCurrentAgentId, reloadAgents, agents } = useProject();
const projectId = currentProject?.projectId ?? null;
@@ -229,6 +252,21 @@ export function ChatPage() {
const [infoOpen, setInfoOpen] = useState(false);
const [modeSaving, setModeSaving] = useState(false);
const [models, setModels] = useState<ModelsResponse | null>(null);
+ // Background processes the conversation started (details popover list + the header's
+ // running-services count), refreshed by the polling effect below; procBusy marks the
+ // row whose stop request is in flight.
+ const [processes, setProcesses] = useState<SessionProcessInfo[]>([]);
+ const [procBusy, setProcBusy] = useState<string | null>(null);
+ // Session Token buckets from the last usage fetch (the popover's tokens-line breakdown):
+ // server-recorded values — they can trail the live chip mid-run and reconcile on idle.
+ const [usageBuckets, setUsageBuckets] = useState<{
+ cacheRead: number;
+ cacheWrite: number;
+ output: number;
+ } | null>(null);
+ // Latest trace file path (single-session GET only — list rows don't carry it), fetched
+ // when the details popover opens; null = none yet (brand-new session) or still loading.
+ const [tracePath, setTracePath] = useState<string | null>(null);
// Per-turn thinking level, local per-session UI state: "" = untouched — the picker then
// displays the Agent config's level and postTask omits thinkingLevel (auto-follow: the
// server/core fallback applies, so mid-session Agent-config edits keep taking effect).
@@ -246,21 +284,58 @@ export function ChatPage() {
// chips via onOpenSubagent, or a future caller) closes the other as a side effect of
// setOpen(true). Closing never cascades. The hooks stay uncoordinated on purpose — they don't
// know about each other; only this page, which owns both, does.
+ //
+ // Docked swaps are SEQUENCED, not simultaneous: with both width transitions running at
+ // once the total width is constant, so the closing panel's left-anchored content never
+ // moves — the incoming panel just wipes over it, which reads as "the old panel never
+ // retracted". Closing the old one fully first (its width animates while the chat column
+ // takes the space back), then sliding the new one in, makes both motions legible. A new
+ // swap/toggle cancels the pending open; mobile Sheets keep the instant switch — they
+ // overlay rather than share width, so the sequencing would only add dead time.
+ const panelSwapTimer = useRef<number | null>(null);
+ const cancelPanelSwap = () => {
+ if (panelSwapTimer.current !== null) {
+ window.clearTimeout(panelSwapTimer.current);
+ panelSwapTimer.current = null;
+ }
+ };
+ useEffect(() => cancelPanelSwap, []);
+ /** Opens `open` after retracting `closeFirst` when a docked swap needs sequencing; instant otherwise. */
+ const swapPanels = (
+ closeFirst: { open: boolean; isDocked: boolean; setOpen: (v: boolean) => void },
+ open: (v: boolean) => void,
+ ) => {
+ closeFirst.setOpen(false);
+ if (closeFirst.open && closeFirst.isDocked) {
+ panelSwapTimer.current = window.setTimeout(() => {
+ panelSwapTimer.current = null;
+ open(true);
+ }, PANEL_SWAP_MS);
+ } else {
+ open(true);
+ }
+ };
const filesPanel: FilesPanelState = {
...filesPanelRaw,
setOpen: (next: boolean) => {
- if (next) subagentsPanelRaw.setOpen(false);
- filesPanelRaw.setOpen(next);
+ cancelPanelSwap();
+ if (next) swapPanels(subagentsPanelRaw, filesPanelRaw.setOpen);
+ else filesPanelRaw.setOpen(false);
},
};
const subagentsPanel: SubagentsPanelState = {
...subagentsPanelRaw,
setOpen: (next: boolean) => {
- if (next) filesPanelRaw.setOpen(false);
- subagentsPanelRaw.setOpen(next);
+ cancelPanelSwap();
+ if (next) swapPanels(filesPanelRaw, subagentsPanelRaw.setOpen);
+ else subagentsPanelRaw.setOpen(false);
},
};
- const draft = routeSessionId === DRAFT_SESSION_ID;
+ // Parked draft conversations (`/chat/draft-…`) render the same DraftView as `/chat/new`,
+ // just bound to their own stored entry — every "this is a draft, not a Session" branch
+ // below treats the two alike.
+ const parkedDraftId = parkedDraftIdOf(routeSessionId);
+ const draft = routeSessionId === DRAFT_SESSION_ID || parkedDraftId !== null;
const selected = draft ? null : (sessions.find((s) => s.sessionId === routeSessionId) ?? null);
// Currently effective model (session state, the model reference comes from the Session DTO): model selection in draft state is handled internally by DraftView.
const activeModelRef = selected
@@ -359,6 +434,8 @@ export function ChatPage() {
// ONLY automatic close of either panel.
useEffect(() => {
if (!draft) return;
+ // A swap's pending delayed open must not fire into the fresh draft after this reset.
+ cancelPanelSwap();
filesPanelRaw.setOpen(false);
subagentsPanelRaw.setOpen(false);
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -499,14 +576,18 @@ export function ChatPage() {
// create the same path, so its summary must re-check instead of inheriting stale false state.
const statCacheRef = useRef(new Map<string, true | Promise<boolean>>());
- // Session switch: resets the usage-fetch marker, the file-card existence cache, and the
- // per-turn thinking level (it's per-session UI state), avoiding stale data from the previous
- // Session (Files panel state resets itself keyed on sessionId inside use-files-panel, and the
- // cost hold re-keys itself on sessionId inside advanceCostStat).
+ // Session switch: resets the usage-fetch marker, the file-card existence cache, the
+ // per-turn thinking level (it's per-session UI state), and the popover's per-session
+ // data (process list / token buckets / trace path), avoiding stale data from the
+ // previous Session (Files panel state resets itself keyed on sessionId inside
+ // use-files-panel, and the cost hold re-keys itself on sessionId inside advanceCostStat).
useEffect(() => {
usageAppliedRef.current = null;
setTurnThinkingLevel("");
statCacheRef.current = new Map();
+ setProcesses([]);
+ setUsageBuckets(null);
+ setTracePath(null);
}, [routeSessionId]);
// Batched existence check for file summaries: cache stable positive results and share in-flight
@@ -556,9 +637,13 @@ export function ChatPage() {
// task-state change re-runs the effect and discards an in-flight response fetched under the
// previous run state (whose total would misalign with the live buckets it is snapshotted
// against — see applyUsageFetch).
+ // infoOpen is a refresh trigger on top of the original conditions: opening the details
+ // popover mid-run re-fetches once, so its token breakdown isn't a whole Task stale
+ // (applyUsageFetch is designed for mid-run reconciles — see header-stats.ts).
useEffect(() => {
if (!projectId || !selected) return;
- if (usageAppliedRef.current === selected.sessionId && stream.taskState !== "idle") return;
+ if (usageAppliedRef.current === selected.sessionId && stream.taskState !== "idle" && !infoOpen)
+ return;
let cancelled = false;
api
.getUsage(projectId, { groupBy: "session", agentId: selected.agentId })
@@ -567,13 +652,87 @@ export function ChatPage() {
usageAppliedRef.current = selected.sessionId;
const row = res.groups.find((g) => g.key === selected.sessionId);
applyUsageFetch(costHoldRef.current, selected.sessionId, row ?? null);
+ setUsageBuckets(
+ row ? { cacheRead: row.cacheRead, cacheWrite: row.cacheWrite, output: row.output } : null,
+ );
bumpUsageStamp((n) => n + 1);
})
.catch(() => undefined);
return () => {
cancelled = true;
};
- }, [projectId, selected, stream.taskState]);
+ }, [projectId, selected, stream.taskState, infoOpen]);
+
+ // Background-process list: fetched on session entry, then kept fresh while it can still
+ // change — during a run (a foreground command may promote to background at any moment),
+ // while any listed process is still running (it can exit on its own), and while the
+ // details popover shows the list. Otherwise no timer runs: an idle session with no
+ // processes has nothing to poll for. Fail-soft — a failed poll keeps the last list.
+ const runningProcessCount = processes.filter((p) => p.running).length;
+ const processesCanChange =
+ stream.taskState !== "idle" || runningProcessCount > 0 || (infoOpen && processes.length > 0);
+ useEffect(() => {
+ if (!selectedSessionId) return;
+ let cancelled = false;
+ const refresh = () => {
+ api
+ .getSessionProcesses(selectedSessionId)
+ .then((res) => {
+ if (!cancelled) setProcesses(res.processes);
+ })
+ .catch(() => undefined);
+ };
+ refresh();
+ if (!processesCanChange) {
+ return () => {
+ cancelled = true;
+ };
+ }
+ const timer = window.setInterval(refresh, PROCESS_POLL_MS);
+ return () => {
+ cancelled = true;
+ window.clearInterval(timer);
+ };
+ }, [selectedSessionId, stream.taskState, processesCanChange]);
+
+ // Stop one background process: the kill also removes it from the server-side registry,
+ // so the follow-up refresh drops the row (a 404 means it already exited/was reaped —
+ // same outcome, not an error worth surfacing).
+ const onKillProcess = useCallback(
+ async (processId: string) => {
+ if (!selected || procBusy !== null) return;
+ setProcBusy(processId);
+ try {
+ await api.killSessionProcess(selected.sessionId, processId);
+ } catch (e) {
+ if (!(e instanceof ApiError && e.status === 404)) toastError(apiErrorText(e));
+ } finally {
+ setProcBusy(null);
+ api
+ .getSessionProcesses(selected.sessionId)
+ .then((res) => setProcesses(res.processes))
+ .catch(() => undefined);
+ }
+ },
+ [selected, procBusy],
+ );
+
+ // Trace file path for the popover's trace row: the single-session GET is the only
+ // surface carrying it, so fetch lazily on open (and once per session — the path only
+ // ever moves forward when a new trace file starts, which a reopen picks up).
+ useEffect(() => {
+ if (!infoOpen || !selectedSessionId) return;
+ let cancelled = false;
+ api
+ .getSession(selectedSessionId)
+ .then((res) => {
+ if (!cancelled) setTracePath(res.session.tracePath ?? null);
+ })
+ .catch(() => undefined);
+ return () => {
+ cancelled = true;
+ };
+ }, [infoOpen, selectedSessionId]);
// Model config (context window + credential guide): fetched once per Project.
//
@@ -869,9 +1028,13 @@ export function ChatPage() {
}, [selected, syncHealedSessionId]);
// "New Chat" = enter draft state: no Session is created until the first message is sent.
+ // Typed-but-unsent text in the ACTIVE new-chat draft first becomes a parked draft
+ // conversation (a sidebar row, sendable anytime) instead of lingering invisibly in the
+ // cache — the sidebar's own new-chat entries do the same (sidebar.tsx).
const newChat = useCallback(() => {
+ if (user && projectId) parkActiveDraft(user.userId, projectId);
navigate(`/chat/${DRAFT_SESSION_ID}`);
- }, [navigate]);
+ }, [user, projectId, navigate]);
// Auth-dead notice primary CTA: the Models page is where the credential is actually fixed.
const openModels = useCallback(() => {
@@ -956,6 +1119,14 @@ export function ChatPage() {
currency,
}),
);
+ // Cache hit rate over the recorded input buckets (cacheRead = hits, cacheWrite =
+ // uncached input) — the details card's tokens-line parenthetical. Null until a usage
+ // row with any input has applied, so a fresh session shows no "0%" out of thin air.
+ const recordedInput = usageBuckets ? usageBuckets.cacheRead + usageBuckets.cacheWrite : 0;
+ const cacheHitRate =
+ usageBuckets && recordedInput > 0
+ ? `${Math.round((100 * usageBuckets.cacheRead) / recordedInput)}%`
+ : null;
const modelInfo = models?.models.find((m) => sameModelRef(m, activeModelRef));
const contextWindow = modelInfo?.contextWindow;
// Assumed supported by default: only models explicitly marked vision=false show a blocking hint when adding images.
@@ -1055,26 +1226,6 @@ export function ChatPage() {
)}
</div>
- {/* Stats: Token / cost / elapsed time (icon + title for the full meaning) */}
- <div className="hidden items-center gap-3 sm:flex">
- <StatChip
- icon={STAT_ICONS.tokens}
- value={hs.tokensText}
- label={`${S.chat.statTokens}(Token)`}
- />
- {/* When there's no cost (the Model has no pricing configured), don't render this stat
- at all, rather than showing a "—" — that would take up space while saying
- nothing, only making people think the cost is zero or something's broken. */}
- {hs.costText != null && (
- <StatChip
- icon={STAT_ICONS.cost}
- value={`${hs.costText}${hs.costUncosted ? " *" : ""}`}
- label={`${S.common.cost}(${currency})${hs.costUncosted ? ` · ${S.usage.uncostedNote}` : ""}`}
- />
- )}
- <StatChip icon={STAT_ICONS.elapsed} value={hs.elapsedNode} label={S.chat.statElapsed} />
- </div>
-
{/* Subagents panel toggle: latest-Task call graph + child conversations dock on the right (use-subagents-panel.ts); opening closes the Files panel (wrapped setOpen). */}
<button
type="button"
@@ -1155,32 +1306,90 @@ export function ChatPage() {
/>
)}
- {/* Details popup: Model / Workspace / created time / stats */}
+ {/* Details entry, at the toolbar's far right — the stats ARE the trigger: wide
+ viewports show the live chips (Token / cost / elapsed, plus the running-services
+ count while any process is alive) and clicking them opens the details card; narrow
+ viewports collapse the whole thing to the single info icon. There is no separate
+ info icon while the chips are visible. */}
<Dropdown
open={infoOpen}
setOpen={setInfoOpen}
- menuClass="right-0 top-full mt-1 w-80 max-w-[calc(100vw-1.5rem)] origin-top-right"
+ menuClass="right-0 top-full mt-1 w-96 max-w-[calc(100vw-1.5rem)] origin-top-right"
button={
<button
type="button"
title={S.chat.infoPanel}
+ aria-label={S.chat.infoPanel}
+ aria-expanded={infoOpen}
onClick={() => setInfoOpen(!infoOpen)}
- className="flex h-7 w-7 shrink-0 items-center justify-center rounded-md text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ className={`flex h-7 shrink-0 items-center rounded-md transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800 ${
+ infoOpen ? "bg-gray-100 dark:bg-gray-800" : ""
+ }`}
>
- <svg
- width="16"
- height="16"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.7"
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-hidden
- >
- <circle cx="12" cy="12" r="9" />
- <path d="M12 11v5m0-8h.01" />
- </svg>
+ {/* Wide: the chip row (icon + title per chip carries the full meaning). */}
+ <span className="hidden items-center gap-3 px-2 sm:flex">
+ <StatChip
+ icon={STAT_ICONS.tokens}
+ value={hs.tokensText}
+ label={`${S.chat.statTokens}(Token)`}
+ />
+ {/* When there's no cost (the Model has no pricing configured), don't render
+ this stat at all, rather than showing a "—" — that would take up space
+ while saying nothing, only making people think the cost is zero or
+ something's broken. */}
+ {hs.costText != null && (
+ <StatChip
+ icon={STAT_ICONS.cost}
+ value={`${hs.costText}${hs.costUncosted ? " *" : ""}`}
+ label={`${S.common.cost}(${currency})${hs.costUncosted ? ` · ${S.usage.uncostedNote}` : ""}`}
+ />
+ )}
+ <StatChip
+ icon={STAT_ICONS.elapsed}
+ value={hs.elapsedNode}
+ label={S.chat.statElapsed}
+ />
+ {/* Right of the time, only while the conversation has live background
+ processes: their count, in the live-status green. */}
+ {runningProcessCount > 0 && (
+ <span
+ title={S.chat.runningServices(runningProcessCount)}
+ className="flex shrink-0 items-center gap-1 font-mono text-xs text-emerald-600 dark:text-emerald-400"
+ >
+ <svg
+ width="14"
+ height="14"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.7"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden
+ >
+ <path d={STAT_ICONS.services} />
+ </svg>
+ {runningProcessCount}
+ </span>
+ )}
+ </span>
+ {/* Narrow: the info icon alone (the chips would crowd the title out). */}
+ <span className="flex h-7 w-7 items-center justify-center text-gray-500 sm:hidden dark:text-gray-400">
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.7"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ aria-hidden
+ >
+ <circle cx="12" cy="12" r="9" />
+ <path d="M12 11v5m0-8h.01" />
+ </svg>
+ </span>
</button>
}
>
@@ -1213,46 +1422,103 @@ export function ChatPage() {
<p className="text-xs font-medium text-gray-500 dark:text-gray-400">
{S.chat.sessionStats}
</p>
- {/* Same as above: if there's no cost, the whole item is omitted, not left as "Cost —". */}
- <p className="font-mono text-xs">
- {S.chat.statTokens} {hs.tokensText}
- {hs.costText != null && ` · ${S.common.cost} ${hs.costText}`} ·{" "}
- {S.chat.statElapsed} {hs.elapsedNode}
- </p>
+ {/* A bulleted list, one stat per line. The tokens bullet carries the cache
+ hit rate in parentheses (cacheRead ÷ all recorded input); the rate comes
+ from the usage fetch, so it can trail the live total mid-run and
+ reconciles on idle. No-cost sessions omit the cost bullet entirely, as
+ the chip does. */}
+ <ul className="list-inside list-disc space-y-0.5 font-mono text-xs">
+ <li>
+ {S.chat.statTotalTokens} {hs.tokensText}
+ {cacheHitRate !== null &&
+ `${S.chat.statParenOpen}${S.chat.statCacheHit(cacheHitRate)}${S.chat.statParenClose}`}
+ </li>
+ {hs.costText != null && (
+ <li>
+ {S.common.cost} {hs.costText}
+ {hs.costUncosted ? " *" : ""}
+ </li>
+ )}
+ <li>
+ {S.chat.statElapsed} {hs.elapsedNode}
+ </li>
+ </ul>
</div>
- </div>
- {/* Jump to this Session's Trace: SPA-navigates to the Trace page deep-linked to
- the owning Agent AND this Session (?agentId= focuses/expands the Agent group,
- ?sessionId= auto-selects — a Session beyond the first loaded page resolves via
- the Trace page's full-fetch fallback). Only reachable for a real Session: this
- whole header renders behind the `selected` guard, so a draft never shows it. */}
- <div className="border-t border-gray-100 py-1 dark:border-gray-800">
- <button
- type="button"
- onClick={() => {
- setInfoOpen(false);
- navigate(
- `/traces?agentId=${encodeURIComponent(selected.agentId)}&sessionId=${encodeURIComponent(selected.sessionId)}`,
- );
- }}
- className="flex w-full items-center gap-2 px-3.5 py-2 text-left text-sm transition-colors duration-150 hover:bg-gray-100 dark:hover:bg-gray-800"
- >
- <svg
- width="15"
- height="15"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- strokeWidth="1.7"
- strokeLinecap="round"
- strokeLinejoin="round"
- aria-hidden
- className="shrink-0 text-gray-400 dark:text-gray-500"
- >
- <path d={NAV_ICONS.traces} />
- </svg>
- {S.chat.viewTrace}
- </button>
+ {/* Background processes the conversation started (e.g. a dev server on
+ localhost:3000): live rows carry a stop button — the kill signals the whole
+ process group and the row drops on the follow-up refresh. Hidden entirely
+ while there are none. */}
+ {processes.length > 0 && (
+ <div>
+ <p className="text-xs font-medium text-gray-500 dark:text-gray-400">
+ {S.chat.processList}
+ </p>
+ <ul className="mt-1 space-y-1.5">
+ {processes.map((p) => (
+ <li key={p.processId} className="flex items-center gap-2">
+ <span
+ aria-hidden
+ className={`h-1.5 w-1.5 shrink-0 rounded-full ${
+ p.running
+ ? "animate-pulse bg-emerald-500"
+ : "bg-gray-300 dark:bg-gray-600"
+ }`}
+ />
+ <span className="min-w-0 flex-1">
+ <span className="block truncate font-mono text-xs" title={p.cmd}>
+ {p.cmd}
+ </span>
+ <span className="block text-[11px] text-gray-400 dark:text-gray-500">
+ {formatDateTime(p.startedAt)}
+ {p.pid !== null && ` · pid ${p.pid}`}
+ </span>
+ </span>
+ {p.running ? (
+ <button
+ type="button"
+ disabled={procBusy !== null}
+ onClick={() => void onKillProcess(p.processId)}
+ className="shrink-0 rounded-md border border-gray-200 px-2 py-0.5 text-xs text-gray-600 transition-colors duration-150 hover:border-red-200 hover:bg-red-50 hover:text-red-600 disabled:cursor-default disabled:opacity-60 dark:border-gray-700 dark:text-gray-300 dark:hover:border-red-900 dark:hover:bg-red-950/40 dark:hover:text-red-400"
+ >
+ {procBusy === p.processId ? S.common.loading : S.chat.processStop}
+ </button>
+ ) : (
+ <span className="shrink-0 text-[11px] text-gray-400 dark:text-gray-500">
+ {S.chat.processExited}
+ </span>
+ )}
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+ {/* Trace file, same section anatomy as the rows above (label + mono value):
+ the path itself is the click target and SPA-navigates to the Trace page
+ deep-linked to the owning Agent AND this Session (?agentId= focuses/expands
+ the Agent group, ?sessionId= auto-selects — a Session beyond the first
+ loaded page resolves via the Trace page's full-fetch fallback). Hidden
+ until a trace exists (a brand-new session has no file to open); only
+ reachable for a real Session — this whole header renders behind the
+ `selected` guard, so a draft never shows it. */}
+ {tracePath !== null && (
+ <div>
+ <p className="text-xs font-medium text-gray-500 dark:text-gray-400">
+ {S.chat.traceFile}
+ </p>
+ <button
+ type="button"
+ onClick={() => {
+ setInfoOpen(false);
+ navigate(
+ `/traces?agentId=${encodeURIComponent(selected.agentId)}&sessionId=${encodeURIComponent(selected.sessionId)}`,
+ );
+ }}
+ className="break-all text-left font-mono text-xs leading-5 text-gray-600 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-900 dark:text-gray-300 dark:decoration-gray-600 dark:hover:text-gray-100"
+ >
+ {tracePath}
+ </button>
+ </div>
+ )}
</div>
</Dropdown>
</div>
@@ -1264,9 +1530,17 @@ export function ChatPage() {
{draft ? (
// Draft state: DraftView's vertically centered input card + Agent / Workspace
// selection panel; the Session is only created once the first message is sent. Keyed
- // by Project: switching Project remounts and switches to that Project's draft cache
- // (Agent selection happens inside the draft itself, so it's no longer part of the key).
- <DraftView key={`draft:${projectId}`} projectId={projectId} models={models} />
+ // by Project (switching Project remounts onto that Project's draft cache) and by the
+ // parked-draft id — falling back to location.key for `/chat/new`, so clicking "New
+ // chat" while already on the draft page (which just parked the typed text) remounts
+ // onto the freshly cleared cache. (Agent selection happens inside the draft itself,
+ // so it's not part of the key.)
+ <DraftView
+ key={`draft:${projectId}:${parkedDraftId ?? location.key}`}
+ projectId={projectId}
+ models={models}
+ {...(parkedDraftId !== null ? { draftId: parkedDraftId } : {})}
+ />
) : (
// Keyed by Session: the whole block does a light fade-in when switching sessions.
<div
diff --git a/packages/web/src/features/chat/draft-cache.ts b/packages/web/src/features/chat/draft-cache.ts
index 415348bd..66478a35 100644
--- a/packages/web/src/features/chat/draft-cache.ts
+++ b/packages/web/src/features/chat/draft-cache.ts
@@ -75,36 +75,40 @@ function parseModelRef(value: unknown): { provider: string; modelId: string } |
export function parseDraft(raw: string | null): DraftCache {
if (!raw) return {};
try {
- const parsed: unknown = JSON.parse(raw);
- if (typeof parsed !== "object" || parsed === null) return {};
- const o = parsed as Record<string, unknown>;
- const out: DraftCache = {};
- if (typeof o.text === "string") out.text = o.text;
- if (typeof o.agentId === "string") out.agentId = o.agentId;
- if (typeof o.workspace === "string") out.workspace = o.workspace;
- const modelRef = parseModelRef(o.modelRef);
- if (modelRef) out.modelRef = modelRef;
- if (typeof o.handoffAgentId === "string") out.handoffAgentId = o.handoffAgentId;
- const switchModelRef = parseModelRef(o.switchModelRef);
- if (switchModelRef) out.switchModelRef = switchModelRef;
- if (Array.isArray(o.skills)) {
- // Elements are validated one by one: non-string items are filtered out; if empty after
- // filtering, the whole field is omitted.
- const skills = o.skills.filter((s): s is string => typeof s === "string");
- if (skills.length > 0) out.skills = skills;
- }
- if (
- typeof o.approvalMode === "string" &&
- APPROVAL_MODES.includes(o.approvalMode as ApprovalMode)
- ) {
- out.approvalMode = o.approvalMode as ApprovalMode;
- }
- return out;
+ return draftFromUnknown(JSON.parse(raw));
} catch {
return {};
}
}
+/** Field-by-field validation of an already-parsed value (shared with the parked-drafts store, whose entries embed a draft object). */
+export function draftFromUnknown(parsed: unknown): DraftCache {
+ if (typeof parsed !== "object" || parsed === null) return {};
+ const o = parsed as Record<string, unknown>;
+ const out: DraftCache = {};
+ if (typeof o.text === "string") out.text = o.text;
+ if (typeof o.agentId === "string") out.agentId = o.agentId;
+ if (typeof o.workspace === "string") out.workspace = o.workspace;
+ const modelRef = parseModelRef(o.modelRef);
+ if (modelRef) out.modelRef = modelRef;
+ if (typeof o.handoffAgentId === "string") out.handoffAgentId = o.handoffAgentId;
+ const switchModelRef = parseModelRef(o.switchModelRef);
+ if (switchModelRef) out.switchModelRef = switchModelRef;
+ if (Array.isArray(o.skills)) {
+ // Elements are validated one by one: non-string items are filtered out; if empty after
+ // filtering, the whole field is omitted.
+ const skills = o.skills.filter((s): s is string => typeof s === "string");
+ if (skills.length > 0) out.skills = skills;
+ }
+ if (
+ typeof o.approvalMode === "string" &&
+ APPROVAL_MODES.includes(o.approvalMode as ApprovalMode)
+ ) {
+ out.approvalMode = o.approvalMode as ApprovalMode;
+ }
+ return out;
+}
+
export function loadDraft(key: string, storage: DraftStorage = localStorage): DraftCache {
try {
return parseDraft(storage.getItem(key));
diff --git a/packages/web/src/features/chat/draft-sessions.ts b/packages/web/src/features/chat/draft-sessions.ts
new file mode 100644
index 00000000..abf20880
--- /dev/null
+++ b/packages/web/src/features/chat/draft-sessions.ts
@@ -0,0 +1,217 @@
+/**
+ * Parked draft conversations ("email drafts" for new chats), localStorage-backed like the
+ * active draft cache (draft-cache.ts) and keyed per "user × Project" (#68 — same
+ * cross-account isolation).
+ *
+ * Clicking "New chat" while the ACTIVE new-chat draft holds typed text no longer leaves
+ * that text invisibly parked in the cache: parkActiveDraft moves it into this list, the
+ * sidebar shows it as a draft conversation row (route `/chat/<draft-id>`), and opening
+ * the row resumes the full draft — selections included — ready to send anytime. Sending
+ * or deleting removes the entry; the ACTIVE draft slot (draftKey) keeps only the model
+ * carry-over, so the next new chat starts empty on the same model
+ * (switch-becomes-default, exactly like a successful send).
+ *
+ * Ids are `draft-<8 hex>`: real Session ids start with `session-` and the new-chat route
+ * uses the literal `new`, so the chat route dispatches on the prefix alone.
+ *
+ * The in-memory copy is a module-level store (useSyncExternalStore) so the sidebar list
+ * and the draft page react to every mutation in this tab; parseDraft validates each
+ * entry's content field-by-field on load, exactly like the caches it mirrors.
+ */
+import { useSyncExternalStore } from "react";
+import { clearDraft, draftFromUnknown, draftKey, loadDraft, saveDraft } from "./draft-cache";
+import type { DraftCache, DraftStorage } from "./draft-cache";
+
+export interface DraftSessionEntry {
+ /** Route id (`draft-<8 hex>`). */
+ id: string;
+ /** Park time (ISO) — the list's stable sort key; content edits don't reorder rows. */
+ savedAt: string;
+ draft: DraftCache;
+}
+
+/** Storage key for one user × Project's parked drafts (a JSON array of entries). */
+export const draftSessionsKey = (userId: string, projectId: string): string =>
+ `penguin.chatDrafts.${userId}.${projectId}`;
+
+/** Newest-first cap: localStorage is shared budget, and fifty abandoned drafts is already hoarding. */
+const MAX_DRAFTS = 50;
+
+/**
+ * Fired (synchronously) by parkActiveDraft before it reads the active cache: a mounted
+ * draft page flushes its debounce-pending text on this event, so the park never captures
+ * a keystroke-stale cache and the page's unmount flush never resurrects parked text.
+ */
+export const DRAFT_FLUSH_EVENT = "penguin:draft-flush";
+
+function parseEntries(raw: string | null): DraftSessionEntry[] {
+ if (!raw) return [];
+ try {
+ const parsed: unknown = JSON.parse(raw);
+ if (!Array.isArray(parsed)) return [];
+ const out: DraftSessionEntry[] = [];
+ for (const item of parsed) {
+ if (typeof item !== "object" || item === null) continue;
+ const o = item as Record<string, unknown>;
+ if (typeof o.id !== "string" || !o.id.startsWith("draft-")) continue;
+ out.push({
+ id: o.id,
+ savedAt: typeof o.savedAt === "string" ? o.savedAt : "",
+ draft: draftFromUnknown(o.draft),
+ });
+ }
+ return out;
+ } catch {
+ return [];
+ }
+}
+
+// —— Module-level store: storage key → entries, every subscriber re-renders on change ——
+
+const cache = new Map<string, DraftSessionEntry[]>();
+const listeners = new Set<() => void>();
+const EMPTY: DraftSessionEntry[] = [];
+
+function storageOf(injected?: DraftStorage): DraftStorage | null {
+ if (injected) return injected;
+ try {
+ return localStorage;
+ } catch {
+ return null; // No storage at all (privacy mode edge): drafts silently disabled.
+ }
+}
+
+function readEntries(key: string, storage?: DraftStorage): DraftSessionEntry[] {
+ const hit = cache.get(key);
+ if (hit) return hit;
+ const s = storageOf(storage);
+ let entries: DraftSessionEntry[] = EMPTY;
+ if (s) {
+ try {
+ entries = parseEntries(s.getItem(key));
+ } catch {
+ entries = EMPTY;
+ }
+ }
+ cache.set(key, entries);
+ return entries;
+}
+
+function writeEntries(key: string, entries: DraftSessionEntry[], storage?: DraftStorage): void {
+ cache.set(key, entries);
+ const s = storageOf(storage);
+ if (s) {
+ try {
+ if (entries.length === 0) s.removeItem(key);
+ else s.setItem(key, JSON.stringify(entries));
+ } catch {
+ // Quota/private mode: the in-memory copy still serves this tab.
+ }
+ }
+ for (const listener of listeners) listener();
+}
+
+function subscribe(listener: () => void): () => void {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+}
+
+/** Reactive list of a user × Project's parked drafts, newest first (EMPTY constant when signed out / none). */
+export function useDraftSessions(
+ userId: string | null,
+ projectId: string | null,
+): DraftSessionEntry[] {
+ return useSyncExternalStore(
+ subscribe,
+ () => (userId && projectId ? readEntries(draftSessionsKey(userId, projectId)) : EMPTY),
+ () => EMPTY,
+ );
+}
+
+const randomDraftId = (): string => `draft-${crypto.randomUUID().replace(/-/g, "").slice(0, 8)}`;
+
+/**
+ * Moves the ACTIVE new-chat draft into the parked list when it holds typed text;
+ * returns the new entry's id, or null when there was nothing worth parking. The active
+ * slot keeps only the model carry-over (mirroring discardDraft on a successful send).
+ * Dispatches DRAFT_FLUSH_EVENT first so a mounted draft page's debounce-pending
+ * keystrokes reach the cache before it is read.
+ */
+export function parkActiveDraft(
+ userId: string,
+ projectId: string,
+ storage?: DraftStorage,
+): string | null {
+ if (!storage && typeof window !== "undefined") {
+ window.dispatchEvent(new Event(DRAFT_FLUSH_EVENT));
+ }
+ const activeKey = draftKey(userId, projectId);
+ // A defaulted parameter only evaluates `localStorage` when the argument is undefined,
+ // which never happens outside a browser (tests always inject a storage).
+ const draft = loadDraft(activeKey, storage);
+ if (!draft.text || draft.text.trim() === "") return null;
+ const key = draftSessionsKey(userId, projectId);
+ const entry: DraftSessionEntry = {
+ id: randomDraftId(),
+ savedAt: new Date().toISOString(),
+ draft,
+ };
+ writeEntries(key, [entry, ...readEntries(key, storage)].slice(0, MAX_DRAFTS), storage);
+ if (draft.modelRef) saveDraft(activeKey, { modelRef: draft.modelRef }, storage);
+ else clearDraft(activeKey, storage);
+ return entry.id;
+}
+
+/** One parked entry by id, or null. */
+export function getDraftSession(
+ userId: string,
+ projectId: string,
+ id: string,
+ storage?: DraftStorage,
+): DraftSessionEntry | null {
+ return readEntries(draftSessionsKey(userId, projectId), storage).find((e) => e.id === id) ?? null;
+}
+
+/** Replaces a parked entry's content in place (savedAt untouched — edits don't reorder the list). Unknown ids are a no-op: the entry was deleted elsewhere. */
+export function saveDraftSession(
+ userId: string,
+ projectId: string,
+ id: string,
+ draft: DraftCache,
+ storage?: DraftStorage,
+): void {
+ const key = draftSessionsKey(userId, projectId);
+ const entries = readEntries(key, storage);
+ if (!entries.some((e) => e.id === id)) return;
+ writeEntries(
+ key,
+ entries.map((e) => (e.id === id ? { ...e, draft } : e)),
+ storage,
+ );
+}
+
+/** Drops a parked entry (sent or deleted). Idempotent. */
+export function removeDraftSession(
+ userId: string,
+ projectId: string,
+ id: string,
+ storage?: DraftStorage,
+): void {
+ const key = draftSessionsKey(userId, projectId);
+ const entries = readEntries(key, storage);
+ if (!entries.some((e) => e.id === id)) return;
+ writeEntries(
+ key,
+ entries.filter((e) => e.id !== id),
+ storage,
+ );
+}
+
+/** Row title: the first non-empty line of the draft text, capped (the row truncates further via CSS). */
+export function draftSessionTitle(entry: DraftSessionEntry): string {
+ const line = (entry.draft.text ?? "")
+ .split("\n")
+ .map((l) => l.trim())
+ .find((l) => l !== "");
+ return (line ?? "").slice(0, 80);
+}
diff --git a/packages/web/src/features/chat/draft-view.tsx b/packages/web/src/features/chat/draft-view.tsx
index 706327a9..4e51331b 100644
--- a/packages/web/src/features/chat/draft-view.tsx
+++ b/packages/web/src/features/chat/draft-view.tsx
@@ -67,6 +67,12 @@ import { EXAMPLE_FOLDERS } from "./example-tasks";
import type { ExampleFolderId, ExampleTask, ExampleTaskId } from "./example-tasks";
import { clearDraft, draftKey, loadDraft, saveDraft } from "./draft-cache";
import type { DraftCache } from "./draft-cache";
+import {
+ DRAFT_FLUSH_EVENT,
+ getDraftSession,
+ removeDraftSession,
+ saveDraftSession,
+} from "./draft-sessions";
import {
CHAT_DEFAULTS_CHANGED_EVENT,
chatDefaultsChangedDetail,
@@ -126,10 +132,13 @@ const FOLDER_GLYPHS: Record<ExampleFolderId, string> = {
export function DraftView({
projectId,
models,
+ draftId,
}: {
projectId: string;
/** Project model config (already fetched by ChatPage): candidate list and default model. */
models: ModelsResponse | null;
+ /** Parked draft conversation id (`/chat/draft-…` — see draft-sessions.ts); absent = the ordinary active draft (`/chat/new`). */
+ draftId?: string;
}) {
const navigate = useNavigate();
const location = useLocation();
@@ -141,13 +150,26 @@ export function DraftView({
// key that isn't account-scoped.
const userId = useAuth().user?.userId ?? null;
- // The cache is read only once, on mount: the component remounts keyed by Project,
- // so switching Projects automatically switches to the corresponding draft; switching
- // accounts always goes through logout (clearing the user unmounts the whole route
- // tree), so logging back in is likewise a fresh mount.
- const [cached] = useState<DraftCache>(() =>
- userId ? loadDraft(draftKey(userId, projectId)) : {},
+ // The cache is read only once, on mount: the component remounts keyed by Project (and
+ // by parked-draft id), so switching Projects or parked drafts automatically switches to
+ // the corresponding content; switching accounts always goes through logout (clearing
+ // the user unmounts the whole route tree), so logging back in is likewise a fresh
+ // mount. A parked draft reads its own entry instead of the active slot.
+ const [parkedMissing] = useState(
+ () =>
+ draftId !== undefined && (!userId || getDraftSession(userId, projectId, draftId) === null),
);
+ const [cached] = useState<DraftCache>(() => {
+ if (!userId) return {};
+ if (draftId !== undefined) return getDraftSession(userId, projectId, draftId)?.draft ?? {};
+ return loadDraft(draftKey(userId, projectId));
+ });
+
+ // A parked id that no longer exists (deleted in the sidebar, stale bookmark): fall
+ // back to the plain new-chat draft instead of editing into a void.
+ useEffect(() => {
+ if (parkedMissing) navigate("/chat/new", { replace: true });
+ }, [parkedMissing, navigate]);
const [agentId, setAgentId] = useState<string | null>(
cached.agentId ?? currentAgent?.agentId ?? null,
@@ -468,8 +490,10 @@ export function DraftView({
if (agentId) data.agentId = agentId;
if (modelRef) data.modelRef = modelRef;
if (skillsRef.current.length > 0) data.skills = skillsRef.current;
- saveDraft(draftKey(userId, projectId), data);
- }, [cancelPendingSave, userId, projectId, agentId, workspace, approvalMode, modelRef]);
+ // A parked draft writes back into its own list entry; the active draft into its slot.
+ if (draftId !== undefined) saveDraftSession(userId, projectId, draftId, data);
+ else saveDraft(draftKey(userId, projectId), data);
+ }, [cancelPendingSave, userId, projectId, draftId, agentId, workspace, approvalMode, modelRef]);
// The timer and unmount cleanup read persistNow via a ref to always get the **latest version**: a stale closure would write back outdated options.
const persistRef = useRef(persistNow);
@@ -508,6 +532,23 @@ export function DraftView({
[],
);
+ // parkActiveDraft ("New chat" clicked while text is typed here) reads the active cache
+ // synchronously right after firing this event: flush the debounce window so the park
+ // captures the latest keystrokes — and so this instance's unmount flush, which would
+ // otherwise fire AFTER the park, has nothing left to write back into the just-cleared
+ // active slot. A parked instance flushes into its own entry (harmless).
+ useEffect(() => {
+ const onFlush = (): void => {
+ if (saveTimer.current !== null) {
+ window.clearTimeout(saveTimer.current);
+ saveTimer.current = null;
+ persistRef.current();
+ }
+ };
+ window.addEventListener(DRAFT_FLUSH_EVENT, onFlush);
+ return () => window.removeEventListener(DRAFT_FLUSH_EVENT, onFlush);
+ }, []);
+
/**
* Discard the draft after a successful send: first cancels the pending save timer, otherwise
* it would write the just-cleared draft back. The **model selection carries over** as the
@@ -519,10 +560,20 @@ export function DraftView({
cancelPendingSave();
// Clear the preselected skills too: any subsequent write (e.g. the unmount flush) must not resurrect a selection that's already been sent.
skillsRef.current = [];
+ // The unmount flush routes through persistNow, which would otherwise write the
+ // just-sent content back (into the parked entry, resurrecting a deleted row): with
+ // the text gone the flush becomes an idempotent empty-shell write.
+ textRef.current = "";
if (!userId) return;
+ if (draftId !== undefined) {
+ // A sent parked draft simply disappears from the list; the ACTIVE slot is not
+ // touched — it may hold a different conversation-in-the-making.
+ removeDraftSession(userId, projectId, draftId);
+ return;
+ }
if (modelRef) saveDraft(draftKey(userId, projectId), { modelRef });
else clearDraft(draftKey(userId, projectId));
- }, [cancelPendingSave, userId, projectId, modelRef]);
+ }, [cancelPendingSave, userId, projectId, draftId, modelRef]);
const selectAgent = (a: AgentSummary) => {
touchedRef.current.agent = true; // an explicit pick outranks a late-arriving project default
diff --git a/packages/web/src/features/chat/message-stream.tsx b/packages/web/src/features/chat/message-stream.tsx
index 7effe7d3..2b4f1bda 100644
--- a/packages/web/src/features/chat/message-stream.tsx
+++ b/packages/web/src/features/chat/message-stream.tsx
@@ -294,6 +294,30 @@ export function MessageStream({
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [version, follow, older?.prependedCount]);
+ // The container and the content can also resize OUTSIDE stream commits: the app shell's
+ // notice banner (initial-password reminder) mounting after /api/me resolves shrinks the
+ // scroll viewport, and a late-loading image grows the transcript. Neither fires a scroll
+ // event nor bumps `version`, so while following, the view silently ended up a banner's
+ // height above the bottom right after opening a conversation. Re-snap on any such resize
+ // under the same guards as the commit snap; lastHeightRef stays in sync so a later
+ // prepend's anchor offset isn't inflated by off-commit growth the anchor already saw.
+ useEffect(() => {
+ const el = scrollRef.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ const ro = new ResizeObserver(() => {
+ lastHeightRef.current = el.scrollHeight;
+ if (follow.stick && !returningRef.current) el.scrollTop = el.scrollHeight;
+ syncJump();
+ });
+ ro.observe(el);
+ // The content wrapper is the scroll container's only child and stays mounted for this
+ // component's whole lifetime, so observing it once covers all content growth.
+ if (el.firstElementChild) ro.observe(el.firstElementChild);
+ return () => ro.disconnect();
+ // syncJump is recreated per render; the observer only needs the stable follow object.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [follow]);
+
/** Back-to-bottom: glide down to the live bottom (reduced motion gets an instant jump); follow re-engages on arrival. */
const jumpToLatest = () => {
const el = scrollRef.current;
diff --git a/packages/web/src/features/skills/skills-page.tsx b/packages/web/src/features/skills/skills-page.tsx
index c802eed3..29dc228a 100644
--- a/packages/web/src/features/skills/skills-page.tsx
+++ b/packages/web/src/features/skills/skills-page.tsx
@@ -54,6 +54,7 @@ import { Skeleton, SkeletonCard } from "../../components/ui/skeleton";
import { toastError, toastSuccess } from "../../components/ui/toast";
import { DRAFT_SESSION_ID } from "../chat/chat-page";
import { draftKey, loadDraft, saveDraft } from "../chat/draft-cache";
+import { parkActiveDraft } from "../chat/draft-sessions";
import { localizedShortText, localizedText } from "../chat/skill-use";
import { SkillIcon, skillTileColor } from "./skill-icon-view";
@@ -232,6 +233,9 @@ export function SkillsPage() {
*/
const quickInvoke = (name: string) => {
if (userId && projectId) {
+ // Typed-but-unsent draft text becomes a parked draft conversation instead of being
+ // clobbered by the canned invocation body (draft-sessions.ts).
+ parkActiveDraft(userId, projectId);
const key = draftKey(userId, projectId);
saveDraft(key, {
...loadDraft(key),
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index 91046e6a..e0f6b4cf 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -869,9 +869,18 @@ Scenarios:
"This model cannot view images directly: on send, images are saved to the session scratchpad and passed as file paths (viewed via describe_image)",
infoPanel: "Session info",
sessionStats: "Stats",
- /** Info-dropdown jump to the Trace page, deep-linked to the current Session. */
- viewTrace: "View trace",
+ /** Info-dropdown trace row: labels the Session's trace file path (clicking deep-links to the Trace page). */
+ traceFile: "Trace file",
+ /** Info-dropdown list of background processes the conversation started, and its per-row actions. */
+ processList: "Processes",
+ processStop: "Stop",
+ processExited: "exited",
+ /** Header chip title: count of the conversation's still-running background processes. */
+ runningServices: (n: number) => (n === 1 ? "1 running service" : `${n} running services`),
statTokens: "Total Tokens",
+ /** Info-dropdown stats list: the tokens bullet's label and its cache-hit-rate parenthetical (rate = cacheRead ÷ all input, e.g. "68%"). */
+ statTotalTokens: "Total Tokens",
+ statCacheHit: (pct: string) => `cache hit rate ${pct}`,
statElapsed: "Elapsed",
statInput: "Input tokens",
statCached: "cached",
@@ -924,6 +933,9 @@ Scenarios:
? `Switched model (was ${prevModel}) — continued from the earlier conversation`
: "Switched model — continued from the earlier conversation",
modelSwitchAutoMessage: "Continue this conversation on the new model",
+ /** Toast when the session-state (locked) model display is clicked: points at the `/model` command. */
+ modelLockedHint:
+ "This session's model is locked — type /model to switch (sending continues this conversation in a new session)",
scheduledFrom: (name: string) => `Triggered by scheduled task "${name}"`,
emptyGreeting: "Start a new conversation",
compactionRunning: (mode: string) => `Compaction in progress (${mode})…`,
@@ -950,6 +962,12 @@ Scenarios:
renameSessionLabel: "Title",
deleteSessionConfirm: (title: string) =>
`Delete "${title}"? Its messages and Trace will be removed permanently.`,
+ /** Parked draft conversations (unsent new chats living in the sidebar list — see draft-sessions.ts). */
+ draftGroup: "Drafts",
+ draftUntitled: "(untitled draft)",
+ deleteDraft: "Delete draft",
+ deleteDraftConfirm: (title: string) =>
+ `Delete draft "${title}"? Unsent content will be discarded.`,
archiveSession: "Archive",
unarchiveSession: "Unarchive",
/** Sidebar group "reveal/load next page" row (display cap + server paging). */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index fdf94498..68f91337 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -847,9 +847,18 @@ Benchmark:
"当前模型不支持直接查看图片:发送时图片将保存到会话临时目录,以文件路径转交(模型经 describe_image 查看)",
infoPanel: "Session 信息",
sessionStats: "统计",
- /** Info-dropdown jump to the Trace page, deep-linked to the current Session. */
- viewTrace: "查看轨迹",
+ /** Info-dropdown trace row: labels the Session's trace file path (clicking deep-links to the Trace page). */
+ traceFile: "轨迹文件",
+ /** Info-dropdown list of background processes the conversation started, and its per-row actions. */
+ processList: "会话进程",
+ processStop: "停止",
+ processExited: "已退出",
+ /** Header chip title: count of the conversation's still-running background processes. */
+ runningServices: (n: number) => `${n} 个运行中的服务`,
statTokens: "Token 累计",
+ /** Info-dropdown stats list: the tokens bullet's label and its cache-hit-rate parenthetical (rate = cacheRead ÷ all input, e.g. "68%"). */
+ statTotalTokens: "总 Token",
+ statCacheHit: (pct: string) => `缓存命中率 ${pct}`,
statElapsed: "用时",
statInput: "输入 tokens",
statCached: "已缓存",
@@ -904,6 +913,8 @@ Benchmark:
prevModel ? `已切换模型(原为 ${prevModel}),延续原会话` : "已切换模型,延续原会话",
/** First message body auto-sent when `/model` is staged and the composer is empty (same convention as skillsAutoMessage). */
modelSwitchAutoMessage: "换用新模型继续这段对话",
+ /** Toast when the session-state (locked) model display is clicked: points at the `/model` command. */
+ modelLockedHint: "会话的模型已锁定:输入 /model 指令可切换模型(发送时开启新会话延续本对话)",
scheduledFrom: (name: string) => `由定时任务「${name}」触发`,
emptyGreeting: "开始一段新对话",
compactionRunning: (mode: string) => `压缩进行中(${mode})…`,
@@ -928,6 +939,11 @@ Benchmark:
renameSessionLabel: "标题",
deleteSessionConfirm: (title: string) =>
`确定删除「${title}」?该对话的消息与 Trace 将被移除,且不可恢复。`,
+ /** Parked draft conversations (unsent new chats living in the sidebar list — see draft-sessions.ts). */
+ draftGroup: "草稿",
+ draftUntitled: "(无标题草稿)",
+ deleteDraft: "删除草稿",
+ deleteDraftConfirm: (title: string) => `确定删除草稿「${title}」?未发送的内容将被丢弃。`,
archiveSession: "归档",
unarchiveSession: "取消归档",
/** Sidebar group "reveal/load next page" row (display cap + server paging). */
diff --git a/packages/web/test/draft-sessions.test.ts b/packages/web/test/draft-sessions.test.ts
new file mode 100644
index 00000000..aafe52ad
--- /dev/null
+++ b/packages/web/test/draft-sessions.test.ts
@@ -0,0 +1,143 @@
+/**
+ * Parked draft conversations (draft-sessions.ts): parking moves the ACTIVE new-chat
+ * draft into the per-user×Project list (model carry-over stays behind, like a
+ * successful send), entries round-trip through validated storage, and corrupted
+ * storage degrades to an empty list instead of crashing.
+ *
+ * Note: the module keeps an in-memory mirror keyed by storage key, so every test uses
+ * its own user id to stay isolated from the others' keys.
+ */
+import { describe, expect, it } from "vitest";
+import { draftKey, loadDraft, saveDraft } from "../src/features/chat/draft-cache";
+import type { DraftStorage } from "../src/features/chat/draft-cache";
+import {
+ draftSessionsKey,
+ draftSessionTitle,
+ getDraftSession,
+ parkActiveDraft,
+ removeDraftSession,
+ saveDraftSession,
+} from "../src/features/chat/draft-sessions";
+
+/** In-memory storage (vitest runs in a Node environment, no localStorage). */
+function memStorage(): DraftStorage & { map: Map<string, string> } {
+ const map = new Map<string, string>();
+ return {
+ map,
+ getItem: (k) => map.get(k) ?? null,
+ setItem: (k, v) => void map.set(k, v),
+ removeItem: (k) => void map.delete(k),
+ };
+}
+
+describe("parkActiveDraft", () => {
+ it("moves a typed active draft into the parked list and keeps only the model carry-over", () => {
+ const s = memStorage();
+ saveDraft(
+ draftKey("u-park", "proj"),
+ {
+ text: "half-written prompt",
+ agentId: "default_agent",
+ workspace: "/srv/repo",
+ approvalMode: "read-only",
+ modelRef: { provider: "anthropic", modelId: "claude-sonnet-5" },
+ skills: ["ship-it"],
+ },
+ s,
+ );
+ const id = parkActiveDraft("u-park", "proj", s);
+ expect(id).toMatch(/^draft-[0-9a-f]{8}$/);
+ const entry = getDraftSession("u-park", "proj", id!, s);
+ expect(entry?.draft.text).toBe("half-written prompt");
+ expect(entry?.draft.agentId).toBe("default_agent");
+ expect(entry?.draft.skills).toEqual(["ship-it"]);
+ // The active slot keeps exactly the model pick (switch-becomes-default), nothing else.
+ expect(loadDraft(draftKey("u-park", "proj"), s)).toEqual({
+ modelRef: { provider: "anthropic", modelId: "claude-sonnet-5" },
+ });
+ });
+
+ it("parks nothing when the active draft has no typed text (empty or whitespace)", () => {
+ const s = memStorage();
+ expect(parkActiveDraft("u-empty", "proj", s)).toBeNull();
+ saveDraft(draftKey("u-empty", "proj"), { text: " \n", agentId: "a" }, s);
+ expect(parkActiveDraft("u-empty", "proj", s)).toBeNull();
+ // The untouched draft (selections only) stays where it was.
+ expect(loadDraft(draftKey("u-empty", "proj"), s).agentId).toBe("a");
+ });
+
+ it("newest parked draft sorts first", () => {
+ const s = memStorage();
+ saveDraft(draftKey("u-order", "proj"), { text: "first" }, s);
+ const first = parkActiveDraft("u-order", "proj", s)!;
+ saveDraft(draftKey("u-order", "proj"), { text: "second" }, s);
+ const second = parkActiveDraft("u-order", "proj", s)!;
+ const raw = JSON.parse(s.map.get(draftSessionsKey("u-order", "proj"))!) as { id: string }[];
+ expect(raw.map((e) => e.id)).toEqual([second, first]);
+ });
+});
+
+describe("saveDraftSession / removeDraftSession", () => {
+ it("updates an entry's content in place and is a no-op for unknown ids", () => {
+ const s = memStorage();
+ saveDraft(draftKey("u-save", "proj"), { text: "v1" }, s);
+ const id = parkActiveDraft("u-save", "proj", s)!;
+ const savedAt = getDraftSession("u-save", "proj", id, s)!.savedAt;
+ saveDraftSession("u-save", "proj", id, { text: "v2 edited" }, s);
+ const entry = getDraftSession("u-save", "proj", id, s)!;
+ expect(entry.draft.text).toBe("v2 edited");
+ expect(entry.savedAt).toBe(savedAt); // edits don't reorder the list
+ // Unknown id (deleted elsewhere): nothing is created.
+ saveDraftSession("u-save", "proj", "draft-deadbeef", { text: "ghost" }, s);
+ expect(getDraftSession("u-save", "proj", "draft-deadbeef", s)).toBeNull();
+ });
+
+ it("removes entries idempotently and clears the storage key when the list empties", () => {
+ const s = memStorage();
+ saveDraft(draftKey("u-rm", "proj"), { text: "bye" }, s);
+ const id = parkActiveDraft("u-rm", "proj", s)!;
+ removeDraftSession("u-rm", "proj", id, s);
+ expect(getDraftSession("u-rm", "proj", id, s)).toBeNull();
+ expect(s.map.has(draftSessionsKey("u-rm", "proj"))).toBe(false);
+ removeDraftSession("u-rm", "proj", id, s); // second remove: no throw, no write
+ });
+});
+
+describe("stored-list validation", () => {
+ it("corrupted storage degrades to an empty list; malformed entries are dropped field-by-field", () => {
+ const s = memStorage();
+ s.map.set(draftSessionsKey("u-bad", "proj"), "{not json");
+ expect(getDraftSession("u-bad", "proj", "draft-x", s)).toBeNull();
+ const s2 = memStorage();
+ s2.map.set(
+ draftSessionsKey("u-bad2", "proj"),
+ JSON.stringify([
+ { id: "not-a-draft-id", draft: { text: "dropped" } },
+ 42,
+ { id: "draft-ok", savedAt: 7, draft: { text: "kept", skills: [1, "real"] } },
+ ]),
+ );
+ const entry = getDraftSession("u-bad2", "proj", "draft-ok", s2);
+ expect(entry).not.toBeNull();
+ expect(entry?.savedAt).toBe(""); // non-string savedAt normalized
+ expect(entry?.draft.text).toBe("kept");
+ expect(entry?.draft.skills).toEqual(["real"]); // non-string skill filtered
+ expect(getDraftSession("u-bad2", "proj", "not-a-draft-id", s2)).toBeNull();
+ });
+});
+
+describe("draftSessionTitle", () => {
+ it("uses the first non-empty line, trimmed and capped", () => {
+ expect(
+ draftSessionTitle({
+ id: "draft-1",
+ savedAt: "",
+ draft: { text: "\n\n Hello world \nrest" },
+ }),
+ ).toBe("Hello world");
+ expect(draftSessionTitle({ id: "draft-2", savedAt: "", draft: {} })).toBe("");
+ expect(
+ draftSessionTitle({ id: "draft-3", savedAt: "", draft: { text: "x".repeat(200) } }),
+ ).toHaveLength(80);
+ });
+});