Skip to content

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

feat(web,server,core): a Session's source is always recorded, and the sidebar keeps every background conversation in one folder (上游 #999 移植)

lmlihenga5fb9b9dbeee
diff --git a/changelog/unreleased/2026-10-10-session-source-backward-compatibility.md b/changelog/unreleased/2026-10-10-session-source-backward-compatibility.md
new file mode 100644
index 00000000..4890d749
--- /dev/null
+++ b/changelog/unreleased/2026-10-10-session-source-backward-compatibility.md
@@ -0,0 +1,36 @@
+# Backward compatibility: Traces and callers from before the Session source was required
+
+- **Date:** 2026-10-10
+- **Type:** process
+- **Scope:** `core`, `server`, `web`, `cli`
+
+[中文版](2026-10-10-session-source-backward-compatibility.zh.md)
+
+This is ported from upstream PenguinHarness (#999, commit `e521a9de`).
+
+[A Session's source became required](2026-10-10-session-source.md), and `benchmark` was retired. Two things outlive the release: the Traces already on disk, and the callers that still send the retired value.
+
+## The old shape: a `session_meta` with no `source`, or with `benchmark`
+
+A Trace written before this release carries no `source` for a person's conversation and for a company mode desk or ticket Session alike, and `benchmark` for a Test Session that `penguin run --source benchmark` started. The server's derived `trace_sessions` cache holds the same values, or NULL. Traces are never rewritten. Every read of a Trace head narrows the value through `normalizeSessionSource` in `packages/core/src/omnimessage/source.ts`: no `source` reads as `user`, `benchmark` as `cli`. That covers the startup adoption of unindexed Traces, a resumed Session, which records the narrowed value in every context it opens afterwards, a subagent's forwarded meta, and a child Session's meta replayed in the Web App.
+
+Where the server also has the Session's index row, a head with no `source` reads by the row's `client` instead: `company` when the row is stamped `client = "org"` (company mode's organization runtime opened it, or its next pass stamped it), `user` otherwise. The rule is `readRecordedSource` in `packages/server/src/runtime/session-sources.ts`; the trace index keeps such a head's source as NULL so that the rule can apply. It covers the sessions list's classification, the single-Session read and the Agent Trace listing, so an old desk or ticket Session stays out of the session list like a new one. A resumed old desk still records `user` in the contexts it opens afterwards, since core sees only the Trace; the list reads the earliest head, which it never rewrites.
+
+Two callers still send the retired value, and both are accepted with the same meaning until the removal below:
+
+- `POST /api/projects/:projectId/agents/:agentId/sessions` with `source: "benchmark"`, from an older CLI or Web App, creates a `cli` Session.
+- `penguin run --source benchmark`, which installed copies of the agent-evaluation skill still pass, runs as if the flag were absent and prints a one-line note. Any other `--source` value is an error.
+
+A new-chat draft an older Web App left in the browser with the evaluation mark loses the mark when it loads and creates an ordinary conversation; no code is kept for it.
+
+**A user is not required to do anything.** Old conversations list in the folders their kind belongs to, old desk and ticket Sessions stay out of the session list, and an installed evaluation skill keeps working until it is updated.
+
+## When this can be removed
+
+At the 0.3.0 release preparation, by whoever prepares that release. Reading a Trace never rewrites its head, so a Session created before this release keeps a head without `source` for good: dropping the `undefined` branch alone would make every such conversation a malformed head, skipped by adoption and refused by resume. The preparer therefore settles one question with the user first: rewrite the old heads once (a migration that sets `source` from the narrowing, writing `company` where the index row is stamped `client = "org"` and `user` elsewhere), or keep that one branch permanently. The `org` rule goes with that branch and is settled by the same answer. The `benchmark` branch and the aliases below can go either way. The removal takes out:
+
+- the `compat(0.3.0)` branches of `normalizeSessionSource` (the `undefined` one only after the question above is settled); a head without a valid source is then a malformed head, skipped by adoption and refused by resume, as a head without `provider` is;
+- with the `undefined` branch, the `compat(0.3.0)` branch of `readRecordedSource` (`packages/server/src/runtime/session-sources.ts`) and the NULL the trace index keeps for a head without a source (`packages/server/src/services/trace-index.ts`, `packages/server/src/db/repos/trace-index.ts`); the reading of an `org` row that has not run yet (`unrunSource`) is not compatibility and stays;
+- the `benchmark` alias in the create route (`packages/server/src/http/routes/sessions.ts`);
+- the hidden `--source` option of `penguin run` (`packages/cli/src/commands/run.ts`) and its two messages in `packages/cli/src/i18n.ts`;
+- the cases for these in `packages/core/test/session-source.test.ts`, `packages/server/test/session-source.test.ts`, `packages/server/test/trace-index.test.ts` and `packages/cli/test/server-commands.test.ts`.
diff --git a/changelog/unreleased/2026-10-10-session-source-backward-compatibility.zh.md b/changelog/unreleased/2026-10-10-session-source-backward-compatibility.zh.md
new file mode 100644
index 00000000..b3f1d3a8
--- /dev/null
+++ b/changelog/unreleased/2026-10-10-session-source-backward-compatibility.zh.md
@@ -0,0 +1,36 @@
+# 向后兼容:会话来源成为必填之前的 Trace 与调用方
+
+- **Date:** 2026-10-10
+- **Type:** process
+- **Scope:** `core`, `server`, `web`, `cli`
+
+[English](2026-10-10-session-source-backward-compatibility.md)
+
+本条移植自上游 PenguinHarness(#999,提交 `e521a9de`)。
+
+[会话来源成为必填](2026-10-10-session-source.zh.md),`benchmark` 也已停用。有两样东西会延续到新版本:磁盘上已有的 Trace,以及仍在发送这个已停用取值的调用方。
+
+## 旧形态:没有 `source`、或为 `benchmark` 的 `session_meta`
+
+此前写下的 Trace,人发起的对话与公司模式的工位、工单会话都不带 `source`,`penguin run --source benchmark` 启动的被测会话带 `benchmark`。服务器派生的 `trace_sessions` 缓存里存的也是这些值,或为 NULL。Trace 从不改写。每次读取 Trace 开头时,都经 `packages/core/src/omnimessage/source.ts` 中的 `normalizeSessionSource` 收窄:没有 `source` 读作 `user`,`benchmark` 读作 `cli`。这覆盖了启动时对未入索引 Trace 的收编、恢复的 Session(之后开启的每个上下文都记录收窄后的值)、子 Agent 转发的 meta,以及 Web App 回放的子会话 meta。
+
+服务器同时拿得到 Session 的索引行时,没有 `source` 的开头改按该行的 `client` 读取:该行标有 `client = "org"`(由公司模式的组织运行时开出,或由它的下一轮扫描补上标记)时读作 `company`,否则读作 `user`。这条规则是 `packages/server/src/runtime/session-sources.ts` 中的 `readRecordedSource`;为让它生效,Trace 索引对这类开头的来源记为 NULL。它覆盖会话列表的分类、单个 Session 的读取与 Agent Trace 列表,因此旧的工位与工单会话和新的一样不出现在会话列表中。旧工位会话恢复后,之后开启的上下文仍记录 `user`,因为 core 只看得到 Trace;列表读取的是最早的开头,而它从不改写。
+
+有两个调用方仍会发送这个已停用的取值,在下文的移除之前都按同一含义接受:
+
+- 较旧的 CLI 或 Web App 以 `source: "benchmark"` 调用 `POST /api/projects/:projectId/agents/:agentId/sessions`,创建的是 `cli` 会话。
+- 已安装的 agent-evaluation Skill 副本仍会传 `penguin run --source benchmark`,运行时视同未传该参数,并打印一行提示。`--source` 的其他取值仍报错。
+
+较旧的 Web App 留在浏览器里、带评估标记的新对话草稿,加载时丢弃这个标记,创建的是普通对话;这一点不保留任何代码。
+
+**用户无需任何操作。** 旧会话列在其类别所属的折叠夹中,旧的工位与工单会话不出现在会话列表中;已安装的评估 Skill 在更新之前照常可用。
+
+## 何时可以移除
+
+在 0.3.0 发布准备时,由负责该次发布的人移除。读取 Trace 不会改写其开头,因此此版本之前创建的 Session,其开头永远不带 `source`:只删掉 `undefined` 分支,会让所有这类对话都成为格式错误的开头,收编时跳过、恢复时拒绝。所以负责发布的人须先与用户确定一件事:一次性改写旧的开头(按收窄结果补写 `source` 的迁移,索引行标有 `client = "org"` 的写 `company`,其余写 `user`),或永久保留这一个分支。`org` 规则随这个分支一起,由同一个答案决定。`benchmark` 分支与下列别名不受影响,照常移除。移除的内容:
+
+- `normalizeSessionSource` 中标有 `compat(0.3.0)` 的分支(`undefined` 分支须待上述问题确定后再处理);开头没有合法来源的 Trace 即视为格式错误,收编时跳过、恢复时拒绝,与没有 `provider` 的开头一样;
+- 随 `undefined` 分支一起:`readRecordedSource`(`packages/server/src/runtime/session-sources.ts`)中标有 `compat(0.3.0)` 的分支,以及 Trace 索引为没有来源的开头记下的 NULL(`packages/server/src/services/trace-index.ts`、`packages/server/src/db/repos/trace-index.ts`);对尚未运行过的 `org` 行的读法(`unrunSource`)不属于兼容处理,保留;
+- 创建路由中的 `benchmark` 别名(`packages/server/src/http/routes/sessions.ts`);
+- `penguin run` 隐藏的 `--source` 选项(`packages/cli/src/commands/run.ts`)及其在 `packages/cli/src/i18n.ts` 中的两条文案;
+- `packages/core/test/session-source.test.ts`、`packages/server/test/session-source.test.ts`、`packages/server/test/trace-index.test.ts` 与 `packages/cli/test/server-commands.test.ts` 中对应的用例。
diff --git a/changelog/unreleased/2026-10-10-session-source.md b/changelog/unreleased/2026-10-10-session-source.md
new file mode 100644
index 00000000..909150a2
--- /dev/null
+++ b/changelog/unreleased/2026-10-10-session-source.md
@@ -0,0 +1,23 @@
+# A Session's source is always recorded, and the sidebar keeps every background conversation in one folder
+
+- **Date:** 2026-10-10
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `cli`, `docs`
+
+[中文版](2026-10-10-session-source.zh.md)
+
+This is ported from upstream PenguinHarness (#999, commit `e521a9de`).
+
+Every Session's `session_meta` recorded what kind of conversation it was, in a required `source`: `user` for a person's conversation, `schedule` for a scheduled task's run, `subagent` for a `run_subagent` child, `cli` for one `penguin run` created, `company` for company mode's desk and ticket Sessions, and `api`, reserved for the Sessions the Agent API opens. `benchmark` was retired. The sidebar's Subagents, Scheduled and Evaluations folders were merged into one **Background** folder that holds the Sessions a program opened, each row marked with its source; company Sessions were left out of the session list altogether. How Traces written before this change are read is recorded in [backward compatibility](2026-10-10-session-source-backward-compatibility.md).
+
+## Details
+
+- Core recorded `source: "user"` when `createSession` was given none, and carried a resumed Session's source into every context it opened. `SessionSource` was defined once in core's OmniMessage types, and `normalizeSessionSource` narrowed a value read back from a Trace or a forwarded meta.
+- The Web App composer's conversations, forks and `penguin chat` were `user`; the server's `client` column, which program created the row, stayed a separate fact. A fork's Trace head recorded `user` whatever the Session it was cut from.
+- Company mode's organization runtime opened its desk and ticket Sessions as `company`, still stamped `client: "org"`; the children they spawn stayed `subagent`. A desk opened at a hire that had not run when the server restarted was rebuilt as `company` for its first run, and the list read such a row as `company` meanwhile.
+- `penguin run` created every Session as `cli`, the Test Sessions the agent-evaluation skill launches included, and the skill no longer passed `--source benchmark`. The flag left the help.
+- The sessions list's and the Agent Trace listing's `category` took `active`, `background` and `archived`, and `counts=1` returned those three totals: archived first, then `active` for a `user` Session or one not yet classified, `background` for `api`, `schedule`, `subagent` and `cli`. A `company` Session belonged to no category, archived or not: a list asked for a category, a Workspace group or counts left it out of the page, the totals, the per-Workspace totals and their stamps, and the paged Agent Trace listing left it out too; the plain list still served it, and company mode's own sessions route listed desks and tickets as before. `excludeOrg` stayed, since it also drops the children of company Sessions and the rows an organization names before its next pass stamps them. On creation, `source` accepted `"cli"` only; `api`, `schedule`, `subagent`, `company` and `user` were refused with a 400. `session_created` always carried the new Session's source.
+- The Web App's sidebar drew one Background folder below each group's active conversations (and one shared set in time grouping), loaded and paged per Agent and category like the other folders. Each of its rows carried a source mark with a tooltip: a plug for API, a calendar for Scheduled, two robots for Subagent, a `>_` prompt for CLI. The alarm clock kept marking a conversation with a scheduled task still to fire.
+- **Last conversation**, the chat page's auto-select and the jump after deleting the open conversation picked only a person's conversations, so a scheduled run no longer qualified, and a company Session never did.
+- The Evaluation Center's **Use** dialog stopped marking the conversation it composed: the evaluation conversation was an ordinary one, and the draft cache no longer kept the mark. This replaced the rule of [The Evaluations folder holds only the Test Sessions an agent starts](2026-10-10-evaluation-tasks-list.md), which kept `benchmark` for those Test Sessions: they became `cli` Sessions in the Background folder.
+- The gallery's mock list route and fixtures followed the three categories, and its company desk fixture became a `company` Session that no category lists.
diff --git a/changelog/unreleased/2026-10-10-session-source.zh.md b/changelog/unreleased/2026-10-10-session-source.zh.md
new file mode 100644
index 00000000..a1df15b2
--- /dev/null
+++ b/changelog/unreleased/2026-10-10-session-source.zh.md
@@ -0,0 +1,23 @@
+# 会话来源一律记录在案,侧栏把所有后台会话收进一个折叠夹
+
+- **Date:** 2026-10-10
+- **Type:** feature
+- **Scope:** `core`, `server`, `web`, `cli`, `docs`
+
+[English](2026-10-10-session-source.md)
+
+本条移植自上游 PenguinHarness(#999,提交 `e521a9de`)。
+
+每个 Session 的 `session_meta` 都以必填的 `source` 记录它是哪一类会话:`user` 是人发起的对话,`schedule` 是定时任务的一次运行,`subagent` 是 `run_subagent` 派生的子会话,`cli` 是 `penguin run` 创建的会话,`company` 是公司模式的工位与工单会话,`api` 留给 Agent API 开出的会话。`benchmark` 已停用。侧栏的子智能体、定时任务、评估任务三个折叠夹合并为一个**后台会话**折叠夹,收纳由程序开出的 Session,每行标出来源;公司模式的会话完全不出现在会话列表中。此前写下的 Trace 如何读取,记在[向后兼容](2026-10-10-session-source-backward-compatibility.zh.md)中。
+
+## 细节
+
+- `createSession` 未给来源时,core 记录 `source: "user"`;恢复的 Session 把来源带进它开启的每个上下文。`SessionSource` 只在 core 的 OmniMessage 类型中定义一次,`normalizeSessionSource` 负责收窄从 Trace 或转发的 meta 中读回的值。
+- Web App 输入框发起的对话、分叉出的会话和 `penguin chat` 都是 `user`;服务器的 `client` 列(创建该行的程序)仍是另一条信息。分叉会话的 Trace 开头一律记录 `user`,不论它从哪类会话分出。
+- 公司模式的组织运行时以 `company` 开出工位会话与工单会话,仍标 `client: "org"`;它们派生的子会话仍是 `subagent`。招聘时开出、服务器重启前还没运行过的工位会话,首次运行时按 `company` 重建;在此之前,列表也把这样的行读作 `company`。
+- `penguin run` 创建的每个 Session 都是 `cli`,包括 agent-evaluation Skill 启动的被测会话;该 Skill 不再传 `--source benchmark`,这个参数也从帮助中移除。
+- 会话列表与 Agent Trace 列表的 `category` 改为 `active`、`background`、`archived` 三种,`counts=1` 返回这三项总数:已归档优先,其余的 `user` 会话或尚未分类的行为 `active`,`api`、`schedule`、`subagent`、`cli` 为 `background`。`company` 会话不属于任何类别,归档与否都一样:按类别、按 Workspace 分组或带总数请求的列表,把它移出这一页、各项总数、按 Workspace 的总数及其时间戳,分页的 Agent Trace 列表同样不含它;不带这些参数的完整列表仍会返回它,公司模式自己的会话接口照旧列出工位与工单。`excludeOrg` 保留,因为它还会剔除公司模式会话派生的子会话,以及组织文件已列出、但下一轮扫描尚未打上标记的行。创建时 `source` 只接受 `"cli"`,`api`、`schedule`、`subagent`、`company`、`user` 均返回 400。`session_created` 一律带上新 Session 的来源。
+- Web App 侧栏在每个分组的活跃对话下方显示一个后台会话折叠夹(按时间分组时整个 Project 共用一组),与其他折叠夹一样按 Agent 与类别加载、分页。其中每行带一个来源图标与悬停提示:插头表示 API,日历表示定时任务,两个机器人表示子智能体,`>_` 提示符表示 CLI。闹钟仍只标记绑定了待触发定时任务的对话。
+- **最近一次对话**、对话页的自动选中,以及删除当前对话后的跳转,都只选人发起的对话,定时任务的运行不再计入,公司模式的会话也从不计入。
+- 评估中心的**使用**对话框不再标记它组装的对话:评估会话是一段普通对话,草稿缓存也不再保存这个标记。这取代了[「评估任务」子夹只收 Agent 启动的被测会话](2026-10-10-evaluation-tasks-list.zh.md)的规则:那条规则为被测会话保留 `benchmark`,现在它们是「后台会话」子夹里的 `cli` 会话。
+- 画廊的模拟列表接口与示例数据改用这三种类别,其中公司模式的工位会话示例改为不属于任何类别的 `company` 会话。
diff --git a/packages/cli/src/commands/run.ts b/packages/cli/src/commands/run.ts
index e83960a3..534076e5 100644
--- a/packages/cli/src/commands/run.ts
+++ b/packages/cli/src/commands/run.ts
@@ -3,7 +3,7 @@
*
* penguin run -m <msg> [--project-id <id>] [--agent-id <id>] [--workspace <path>]
* [--model-id <id> --provider <group>] [--approve <mode>]
- * [--thinking <level>] [--session <session_id>] [--source benchmark]
+ * [--thinking <level>] [--session <session_id>]
* [--background] [--goal [budget]] [--json] [--server <url>]
*
* The CLI is a thin client: it creates a Session over the API (or reuses `--session`),
@@ -15,10 +15,10 @@
* default_project / default_agent); Workspace = the CLI's cwd (resolved locally —
* server and CLI share the machine in the default flow); model = the Project default;
* approval mode allow-all (the historical run default).
- * - `--session` accepts a full id or a unique fragment; it excludes `--workspace`, the
- * model pair and `--source` (none can change after creation); `--approve` PATCHes the mode.
- * - `--source benchmark` marks a NEW Session as created by a Benchmark evaluation: the Web
- * App files it under the Evaluations folder of its session list.
+ * - Every Session it creates is recorded as a `cli` Session (`session_meta.source`), which the
+ * Web App lists in the Background folder; `penguin chat` creates `user` Sessions instead.
+ * - `--session` accepts a full id or a unique fragment; it excludes `--workspace` and the
+ * model pair (neither can change after creation); `--approve` PATCHes the mode.
* - `--background`: POST the task and exit immediately, printing the session id
* (`{"sessionId"}` under `--json`) — the task keeps running on the server.
* - `--json` (non-background): suppress rendering; print `{sessionId, status, text}`
@@ -27,6 +27,7 @@
* the stream wind down (the abort event maps to exit code 1).
* Docs: /docs/cli § "penguin run".
*/
+import { Option } from "commander";
import type { Command } from "commander";
import { VERSION } from "@lmliheng/penguin-core";
import { StreamRenderer, dim } from "../render.js";
@@ -65,7 +66,8 @@ export function registerRunCommand(program: Command, t: Messages): void {
.option("--approve <mode>", t.common.approve)
.option("--thinking <level>", t.common.thinking)
.option("--session <sessionId>", t.run.session)
- .option("--source <source>", t.run.source)
+ // compat(0.3.0): the retired `--source benchmark`, kept out of the help (see the action).
+ .addOption(new Option("--source <source>").hideHelp())
.option("--background", t.run.background)
.option("--timeout <duration>", t.common.timeout)
.option("--goal [budget]", t.run.goal)
@@ -96,18 +98,19 @@ export function registerRunCommand(program: Command, t: Messages): void {
return;
}
}
- // `benchmark` is the only origin a client may set: the server writes `subagent` and
- // `schedule` itself, so any other value is rejected here rather than sent.
- if (opts.source !== undefined && String(opts.source) !== "benchmark") {
- process.stderr.write(`${t.error(t.run.sourceInvalid(String(opts.source)))}\n`);
- process.exitCode = 1;
- return;
+ // compat(0.3.0): `--source` is gone, since every Session `penguin run` creates is `cli`.
+ // Installed copies of the agent-evaluation skill still pass `--source benchmark`, so that
+ // value is accepted as a no-op with a note; any other value stays an error.
+ if (opts.source !== undefined) {
+ if (String(opts.source) !== "benchmark") {
+ process.stderr.write(`${t.error(t.run.sourceInvalid(String(opts.source)))}\n`);
+ process.exitCode = 1;
+ return;
+ }
+ process.stderr.write(`${dim(t.run.sourceIgnored())}\n`);
}
- if (
- opts.session !== undefined &&
- (opts.workspace || opts.modelId || opts.provider || opts.source)
- ) {
- // Workspace, model and origin are fixed at creation; a reused Session keeps its own.
+ if (opts.session !== undefined && (opts.workspace || opts.modelId || opts.provider)) {
+ // Workspace and model are fixed at creation; a reused Session keeps its own.
process.stderr.write(`${t.error(t.run.sessionNoOverride())}\n`);
process.exitCode = 1;
return;
@@ -169,7 +172,7 @@ export function registerRunCommand(program: Command, t: Messages): void {
: caller
? { approvalMode: caller.approvalMode }
: {}),
- ...(opts.source !== undefined ? { source: "benchmark" as const } : {}),
+ source: "cli",
});
if (thinking === undefined && caller?.thinkingLevel !== undefined) {
callerThinking = caller.thinkingLevel;
diff --git a/packages/cli/src/i18n.ts b/packages/cli/src/i18n.ts
index 397f0717..f8199471 100644
--- a/packages/cli/src/i18n.ts
+++ b/packages/cli/src/i18n.ts
@@ -112,14 +112,14 @@ export interface Messages {
goal: string;
/** run's --session: reuse an existing Session (full id or unique fragment). */
session: string;
- /** run's --source: mark the NEW Session as created by a Benchmark evaluation. */
- source: string;
/** run's --background: POST the task and exit immediately, printing the session id. */
background: string;
- /** --session combined with --workspace / the model pair / --source: all fixed at creation. */
+ /** --session combined with --workspace / the model pair: both fixed at creation. */
sessionNoOverride(): string;
- /** --source given a value other than `benchmark` (the only origin a client may set). */
+ /** The retired --source given a value other than `benchmark`. Removed at 0.3.0 with the flag. */
sourceInvalid(value: string): string;
+ /** The retired `--source benchmark`, accepted as a no-op until 0.3.0: why it is ignored. */
+ sourceIgnored(): string;
/** --background never waits, so a wait budget cannot apply to it. */
timeoutWithBackground(): string;
};
@@ -1128,13 +1128,13 @@ const en: Messages = {
message: "Prompt for this Task",
goal: "Goal mode: loop until the goal completes; optional token budget (e.g. 500k, 2m)",
session: "Reuse an existing Session (full id or a unique fragment, e.g. the 8-hex tail)",
- source:
- "Mark the new session as created by a Benchmark evaluation (`benchmark`); the Web App files it under the Evaluations folder",
background: "Post the task and exit immediately, printing the session id",
sessionNoOverride: () =>
- "--session reuses an existing Session: --workspace, --model-id, --provider and --source cannot be combined with it (the Session keeps its own; /switch-model inside penguin chat --resume changes its model, compacting first).",
+ "--session reuses an existing Session: --workspace, --model-id and --provider cannot be combined with it (the Session keeps its own; /switch-model inside penguin chat --resume changes its model, compacting first).",
sourceInvalid: (value) =>
- `Invalid --source value "${value}". The only accepted value is benchmark.`,
+ `Invalid --source value "${value}". penguin run takes no --source: every Session it creates is a CLI Session.`,
+ sourceIgnored: () =>
+ "--source benchmark is no longer needed and is ignored: every Session penguin run creates is a CLI Session, listed in the Web App's Background folder.",
timeoutWithBackground: () =>
"--timeout bounds the wait, and --background does not wait: drop one of them.",
},
@@ -2135,11 +2135,13 @@ const zh: Messages = {
message: "本次 Task 的 Prompt",
goal: "目标模式:循环运行直至目标完成;可选 token 预算(如 500k、2m)",
session: "复用既有 Session(完整 id 或唯一片段,如末尾 8 位十六进制)",
- source: "把新建会话标记为 Benchmark 评估创建(`benchmark`);Web App 将其归入「评估任务」子夹",
background: "提交任务后立即退出,打印 session id",
sessionNoOverride: () =>
- "--session 复用既有 Session:不能与 --workspace、--model-id、--provider、--source 同时使用(均沿用该 Session;如需换模型,在 penguin chat --resume 内用 /switch-model,会先压缩上下文)。",
- sourceInvalid: (value) => `无效的 --source 取值 "${value}"。唯一可用取值为 benchmark。`,
+ "--session 复用既有 Session:不能与 --workspace、--model-id、--provider 同时使用(均沿用该 Session;如需换模型,在 penguin chat --resume 内用 /switch-model,会先压缩上下文)。",
+ sourceInvalid: (value) =>
+ `无效的 --source 取值 "${value}"。penguin run 不再接受 --source:它创建的每个会话都是 CLI 会话。`,
+ sourceIgnored: () =>
+ "--source benchmark 已不再需要,已忽略:penguin run 创建的每个会话都是 CLI 会话,列在 Web App 的「后台会话」折叠夹中。",
timeoutWithBackground: () => "--timeout 限定等待,而 --background 不等待:二者去其一。",
},
chat: {
diff --git a/packages/cli/src/server-session.ts b/packages/cli/src/server-session.ts
index 9915a84e..14967c14 100644
--- a/packages/cli/src/server-session.ts
+++ b/packages/cli/src/server-session.ts
@@ -60,8 +60,8 @@ export interface CreateSessionArgs {
modelId?: string;
provider?: string;
approvalMode?: string;
- /** Marks the new Session as created by a Benchmark evaluation (the only origin a client may set). */
- source?: "benchmark";
+ /** `cli` for a Session `penguin run` creates; absent (`penguin chat`) is a person's conversation, `user`. */
+ source?: "cli";
}
/** POST .../sessions with the CLI's client hint. */
diff --git a/packages/cli/test/chat-clear.test.ts b/packages/cli/test/chat-clear.test.ts
index 93ab82ab..8857337e 100644
--- a/packages/cli/test/chat-clear.test.ts
+++ b/packages/cli/test/chat-clear.test.ts
@@ -103,6 +103,15 @@ describe("chat /clear (fresh Session in place, server-backed)", () => {
expect(server.requests.some((r) => r.method === "DELETE")).toBe(false);
});
+ it("creates a person's conversation, for the chat and for /clear: no create request names a source", async () => {
+ await driveChat(["/clear", "/exit"]);
+ const creates = server.requests.filter(
+ (r) => r.method === "POST" && r.path.endsWith("/sessions"),
+ );
+ expect(creates).toHaveLength(2);
+ expect(creates.every((r) => r.body !== undefined && !("source" in r.body))).toBe(true);
+ });
+
it("/clear before any Task prints no resume hint (neither Session has history yet)", async () => {
const out = await driveChat(["/clear", "/exit"]);
expect(server.sessions.size).toBe(2);
diff --git a/packages/cli/test/chat-switch-model.test.ts b/packages/cli/test/chat-switch-model.test.ts
index 93319108..f434a5eb 100644
--- a/packages/cli/test/chat-switch-model.test.ts
+++ b/packages/cli/test/chat-switch-model.test.ts
@@ -114,6 +114,7 @@ function streamedSwitch(status: "completed" | "fatal" | "aborted", errorMessage?
system_prompt: "",
agent_state: "/tmp/agents/default_agent/agent_state",
workspace: session.workspace,
+ source: "user",
}),
]
: []),
diff --git a/packages/cli/test/render.test.ts b/packages/cli/test/render.test.ts
index fa9987bf..a6950658 100644
--- a/packages/cli/test/render.test.ts
+++ b/packages/cli/test/render.test.ts
@@ -417,6 +417,7 @@ describe("StreamRenderer", () => {
system_prompt: "sp",
agent_state: "/a",
workspace: "/w",
+ source: "user",
}),
);
// Two turns: request total 1500, 4000. Per-task token delta = 5500; session cumulative = 12000;
diff --git a/packages/cli/test/server-commands.test.ts b/packages/cli/test/server-commands.test.ts
index 0b7b0ee3..82df4fee 100644
--- a/packages/cli/test/server-commands.test.ts
+++ b/packages/cli/test/server-commands.test.ts
@@ -1,7 +1,8 @@
/**
* Server-backed command wiring, driven through `cli()` in-process against the fake
- * server: run (foreground/background/json, goal exit codes and round lines), ls, input
- * (steer vs task), logs, agent ls/create, project ls, cost, schedule ls.
+ * server: run (foreground/background/json, goal exit codes and round lines, the `cli` source
+ * of every Session it creates and the retired `--source`), ls, input (steer vs task), logs,
+ * agent ls/create, project ls, cost, schedule ls.
*/
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -72,6 +73,25 @@ describe("penguin run", () => {
expect(out()).toContain("hello from the model");
});
+ it("records every Session it creates as a cli Session", async () => {
+ expect(await cli(["run", "-m", "q", "--background"])).toBe(0);
+ const create = server.requests.find((r) => r.method === "POST" && r.path.endsWith("/sessions"));
+ expect(create?.body?.source).toBe("cli");
+ });
+
+ it("accepts the retired --source benchmark as a no-op with a note, and refuses any other value", async () => {
+ expect(await cli(["run", "-m", "q", "--background", "--source", "benchmark"])).toBe(0);
+ expect(stderr.join("")).toContain(t.run.sourceIgnored());
+ const create = server.requests.find((r) => r.method === "POST" && r.path.endsWith("/sessions"));
+ expect(create?.body?.source).toBe("cli");
+
+ stderr.length = 0;
+ expect(await cli(["run", "-m", "q", "--source", "schedule"])).toBe(1);
+ expect(stderr.join("")).toContain("--source");
+ // Refused before anything reached the server: still the one Session from above.
+ expect(server.sessions.size).toBe(1);
+ });
+
it("--background posts and exits with the session id, no stream", async () => {
const code = await cli(["run", "-m", "long job", "--background"]);
expect(code).toBe(0);
@@ -135,16 +155,6 @@ describe("penguin run", () => {
expect(session.patches).toContainEqual({ thinkingLevel: "high" });
expect("thinkingLevel" in (session.tasks[0] as object)).toBe(false);
});
-
- it("--source benchmark creates the Session as an evaluation's Test Session; a plain run creates it with no origin", async () => {
- // How agent-evaluation launches each Test Session, then an ordinary run.
- expect(await cli(["run", "-m", "case 1, run 1", "--source", "benchmark"])).toBe(0);
- expect(await cli(["run", "-m", "an ordinary task"])).toBe(0);
- const creates = server.requests.filter(
- (r) => r.method === "POST" && r.path.endsWith("/sessions"),
- );
- expect(creates.map((r) => r.body?.source)).toEqual(["benchmark", undefined]);
- });
});
describe("penguin ls", () => {
diff --git a/packages/core/src/agent.ts b/packages/core/src/agent.ts
index f25a5c68..71709b9d 100644
--- a/packages/core/src/agent.ts
+++ b/packages/core/src/agent.ts
@@ -83,6 +83,7 @@ import {
compactionEnd,
mcpConnectBegin,
mcpConnectEnd,
+ normalizeSessionSource,
sessionMeta,
toolListReady,
userText,
@@ -92,6 +93,7 @@ import type {
MessageOrigin,
OmniMessage,
SessionMetaPayload,
+ SessionSource,
ToolCallPayload,
} from "./omnimessage/index.js";
import { SUBAGENT_NAME } from "./environment/tools/run-subagent.js";
@@ -248,8 +250,13 @@ export interface CreateSessionOptions {
baseUrl?: string;
/** Internal use: this Session's depth in the subagent spawn chain (0 at the top level), used to cap spawn depth. */
subagentDepth?: number;
- /** Session origin recorded in session_meta (absent = user-created); the subagent spawn site passes "subagent", callers driven by a scheduled task pass "schedule", and the server passes "benchmark" for the Test Sessions of a Benchmark evaluation, which `penguin run --source benchmark` creates. */
- source?: "subagent" | "schedule" | "benchmark";
+ /**
+ * What kind of conversation this is, recorded in session_meta; absent = `user`, a person's.
+ * The subagent spawn site passes `subagent`; a host passes the source its caller stands for
+ * (the server: `schedule` for a scheduled task, `cli` for `penguin run`, `api` for the Agent API,
+ * `company` for company mode's desk and ticket Sessions).
+ */
+ source?: SessionSource;
}
export interface ResumeSessionOptions {
@@ -287,7 +294,7 @@ interface SessionSpec {
*/
thinkingLevel: ThinkingLevelName | null | undefined;
subagentDepth: number;
- source?: "subagent" | "schedule" | "benchmark";
+ source: SessionSource;
}
/**
@@ -624,7 +631,7 @@ export class Agent {
system_prompt: systemPrompt,
agent_state: state.stateDir,
workspace: spec.workspaceDir,
- ...(spec.source !== undefined ? { source: spec.source } : {}),
+ source: spec.source,
};
return {
@@ -732,7 +739,7 @@ export class Agent {
credentialOverride: { apiKey: opts.apiKey, baseUrl: opts.baseUrl },
thinkingLevel: opts.thinkingLevel,
subagentDepth: opts.subagentDepth ?? 0,
- ...(opts.source !== undefined ? { source: opts.source } : {}),
+ source: opts.source ?? "user",
};
// The first context: assembled from the Agent State on disk now (never from this Agent
// object's load-time snapshot — a long-lived Agent, a self-spawned subagent's for
@@ -818,10 +825,10 @@ export class Agent {
// No level at resume: the host re-applies its stored value (Session.thinkingLevel) when it holds one,
// and contexts opened without a pin read the Agent config's chain (the same chain
- // createSession uses). The origin carries over from the original session_meta (a
- // resumed subagent / scheduled / benchmark Session stays marked); the on-disk value
- // is untrusted: only the exact known origins pass, junk written by a third party is
- // dropped rather than cast through.
+ // createSession uses). The source carries over from the original session_meta (a
+ // resumed subagent / scheduled / CLI Session stays what it was); the on-disk value is
+ // untrusted and is narrowed (a Trace from before the source was required reads as
+ // `user`, the retired `benchmark` as `cli`, junk as `user`).
const spec: SessionSpec = {
sessionId,
workspaceDir,
@@ -829,9 +836,7 @@ export class Agent {
credentialOverride: { apiKey: opts.apiKey, baseUrl: opts.baseUrl },
thinkingLevel: undefined,
subagentDepth: 0,
- ...(meta.source === "subagent" || meta.source === "schedule" || meta.source === "benchmark"
- ? { source: meta.source }
- : {}),
+ source: normalizeSessionSource(meta.source),
};
// The context follows the Trace. A context a completed compaction closed is opened here
// for the first time — nothing was produced under any configuration yet — so it is
diff --git a/packages/core/src/omnimessage/index.ts b/packages/core/src/omnimessage/index.ts
index eb8df91b..d4a9188a 100644
--- a/packages/core/src/omnimessage/index.ts
+++ b/packages/core/src/omnimessage/index.ts
@@ -1,6 +1,7 @@
export * from "./types.js";
export * from "./builders.js";
export * from "./aggregate.js";
+export * from "./source.js";
// Special message markers ([user_steering], [use_skills], [handoff_from], …): one module,
// also reachable directly as `@lmliheng/penguin-core/markers`.
export * from "./markers/index.js";
diff --git a/packages/core/src/omnimessage/source.ts b/packages/core/src/omnimessage/source.ts
new file mode 100644
index 00000000..343f6d80
--- /dev/null
+++ b/packages/core/src/omnimessage/source.ts
@@ -0,0 +1,38 @@
+/**
+ * Reading a Session's source (`session_meta.source`) back from a Trace or from a forwarded meta.
+ *
+ * Every meta written since the source became required carries one of the six values. A Trace
+ * kept from before may carry none (it was a person's conversation, or a desk or ticket Session
+ * of company mode) or the retired `benchmark` (a Test Session `penguin run --source benchmark`
+ * started, which `penguin run` now records as `cli`). Old Traces are never rewritten: each
+ * reader narrows what it reads through this one function instead. Seeing the Trace alone, it
+ * reads a missing source as `user`; the server, which also has the Session's index row, reads
+ * one whose row was opened by the organization runtime as `company` instead
+ * (`readRecordedSource` in the server's runtime/session-sources.ts).
+ *
+ * Removal: at the 0.3.0 release preparation the `benchmark` branch goes. The `undefined` branch
+ * goes only together with a one-time rewrite of old heads, or stays for good — the user decides
+ * then: reading never rewrites a head, so every Session created before the source was required
+ * would otherwise become a malformed head, the way one without `provider` is.
+ */
+import type { SessionSource } from "./types.js";
+
+const SESSION_SOURCES: ReadonlySet<unknown> = new Set<SessionSource>([
+ "user",
+ "api",
+ "schedule",
+ "subagent",
+ "cli",
+ "company",
+]);
+
+/** Narrows an untrusted `session_meta.source` to a SessionSource. */
+export function normalizeSessionSource(value: unknown): SessionSource {
+ if (SESSION_SOURCES.has(value)) return value as SessionSource;
+ // compat(0.3.0): a meta written before the source was required has none; it was a person's.
+ if (value === undefined) return "user";
+ // compat(0.3.0): the retired `benchmark` marked Test Sessions `penguin run` started.
+ if (value === "benchmark") return "cli";
+ // Junk a third party wrote is never cast through: it reads as a person's conversation.
+ return "user";
+}
diff --git a/packages/core/src/omnimessage/types.ts b/packages/core/src/omnimessage/types.ts
index 2b6205f4..42fd8d78 100644
--- a/packages/core/src/omnimessage/types.ts
+++ b/packages/core/src/omnimessage/types.ts
@@ -141,10 +141,32 @@ export interface SessionMetaPayload {
agent_state: string;
/** Absolute path to the Workspace. */
workspace: string;
- /** Session origin: spawned by a subagent / triggered by a scheduled task / a Benchmark evaluation's Test Session, created by `penguin run --source benchmark`; absent = user-created. */
- source?: "subagent" | "schedule" | "benchmark";
+ /**
+ * What kind of conversation this is (see {@link SessionSource}), recorded in every context's
+ * meta. A Trace written before the field was required may lack it or carry the retired
+ * `benchmark`; readers narrow what they read through `normalizeSessionSource`.
+ */
+ source: SessionSource;
}
+/**
+ * What kind of conversation a Session is: a person's, or one a program opened for its own
+ * purposes.
+ *
+ * - `user`: a person's conversation, and the default when nothing names a source: the Web App
+ * composer, `penguin chat`, and forks.
+ * - `api`: an external program opened it through the Agent API.
+ * - `schedule`: a scheduled task opened it for one of its runs.
+ * - `subagent`: a `run_subagent` child, whichever Session spawned it (a company Session's too).
+ * - `cli`: `penguin run` created it, the Test Sessions an evaluation launches included.
+ * - `company`: company mode's organization runtime opened it, as an employee's desk or for a
+ * ticket. Only company mode's own views list it.
+ *
+ * Which program created the server's index row is a separate fact (the row's `client`); the two
+ * can differ, as `penguin chat` (a `cli` client writing a `user` Session) shows.
+ */
+export type SessionSource = "user" | "api" | "schedule" | "subagent" | "cli" | "company";
+
// ---------------------------------------------------------------------------
// model_msg — complete messages
// ---------------------------------------------------------------------------
diff --git a/packages/core/test/agent.test.ts b/packages/core/test/agent.test.ts
index 5e3ae2b3..d05ce266 100644
--- a/packages/core/test/agent.test.ts
+++ b/packages/core/test/agent.test.ts
@@ -271,31 +271,6 @@ describe("Agent.createSession model reference ((provider, model_id) pair)", () =
});
});
-describe("Agent.createSession session source (session_meta origin marker)", () => {
- it("records the given source in session_meta; a user-created session carries no source key", async () => {
- const agent = await createAgent();
- const ws = path.join(tmpRoot, "ws-source");
- await fs.mkdir(ws, { recursive: true });
-
- const scheduled = await agent.createSession({ workspaceDir: ws, source: "schedule" });
- try {
- expect((scheduled.metaMessage.payload as { source?: string }).source).toBe("schedule");
- } finally {
- scheduled.dispose();
- }
-
- // Absent = user-created: the key must not appear at all (Trace consumers treat absence as the default).
- const plain = await agent.createSession({ workspaceDir: ws });
- try {
- expect("source" in (plain.metaMessage.payload as unknown as Record<string, unknown>)).toBe(
- false,
- );
- } finally {
- plain.dispose();
- }
- });
-});
-
describe("Agent.createSession thinking level (explicit option wins over the Agent config)", () => {
// A context's level is the LLM object's construction default (the Session's live pin
// overrides it per request); nothing is recorded — the level is a per-request parameter.
diff --git a/packages/core/test/background-execution.test.ts b/packages/core/test/background-execution.test.ts
index ce12f240..f54d3424 100644
--- a/packages/core/test/background-execution.test.ts
+++ b/packages/core/test/background-execution.test.ts
@@ -995,6 +995,7 @@ const META: SessionMetaPayload = {
system_prompt: "sp",
agent_state: "/tmp/state",
workspace: "/tmp/w",
+ source: "user",
};
const IMAGES = { imagesDir: "/tmp/scratchpad/session-bg-1", modelHasVision: true } as const;
diff --git a/packages/core/test/command-policy.test.ts b/packages/core/test/command-policy.test.ts
index 6a9a5a43..9a8c483d 100644
--- a/packages/core/test/command-policy.test.ts
+++ b/packages/core/test/command-policy.test.ts
@@ -402,6 +402,7 @@ describe("Session applies the policy at the approval boundary", () => {
system_prompt: "sp",
agent_state: tmp,
workspace: tmp,
+ source: "user",
});
it("denies a vetoed command under allow-all, and the tool never reaches the Environment", async () => {
diff --git a/packages/core/test/compaction.test.ts b/packages/core/test/compaction.test.ts
index 3f0f1ee3..804d0ffa 100644
--- a/packages/core/test/compaction.test.ts
+++ b/packages/core/test/compaction.test.ts
@@ -140,6 +140,7 @@ const metaMessage = sessionMeta({
system_prompt: "sp",
agent_state: "/tmp/state",
workspace: "/tmp/ws",
+ source: "user",
});
async function collect(gen: AsyncGenerator<OmniMessage>): Promise<OmniMessage[]> {
diff --git a/packages/core/test/engine.test.ts b/packages/core/test/engine.test.ts
index 0522b7da..12772a50 100644
--- a/packages/core/test/engine.test.ts
+++ b/packages/core/test/engine.test.ts
@@ -879,6 +879,7 @@ describe("ContextEngine ReAct loop (mock LLM, approve callback)", () => {
system_prompt: "sys",
agent_state: "/root/p/worker/agent_state",
workspace: "/tmp/w",
+ source: "user",
});
// Custom Environment: on execution, first forwards origin-tagged child session messages
// (child meta / child text / grandchild meta), then yields the complete output (simulates
diff --git a/packages/core/test/helpers/prompt-cache/fixtures.ts b/packages/core/test/helpers/prompt-cache/fixtures.ts
index 176c7f25..807b27a2 100644
--- a/packages/core/test/helpers/prompt-cache/fixtures.ts
+++ b/packages/core/test/helpers/prompt-cache/fixtures.ts
@@ -185,6 +185,7 @@ export const META: SessionMetaPayload = {
system_prompt: SYSTEM_PROMPT,
agent_state: "/tmp/penguin-prompt-cache/state",
workspace: "/tmp/penguin-prompt-cache/workspace",
+ source: "user",
};
export const modelConfig = (over: Partial<GenerativeModelConfig> = {}): GenerativeModelConfig => ({
diff --git a/packages/core/test/hooks.test.ts b/packages/core/test/hooks.test.ts
index 26182433..19c47823 100644
--- a/packages/core/test/hooks.test.ts
+++ b/packages/core/test/hooks.test.ts
@@ -384,6 +384,7 @@ describe("Session user-prompt hook", () => {
system_prompt: "sp",
agent_state: dir,
workspace: dir,
+ source: "user",
};
const scratchpad = path.join(dir, "scratchpad", "session-1");
const session = new Session({
@@ -466,6 +467,7 @@ describe("Session stop hooks", () => {
system_prompt: "sp",
agent_state: dir,
workspace: dir,
+ source: "user",
};
return new Session({
meta,
@@ -691,6 +693,7 @@ describe("Session pre-tool-use hooks", () => {
system_prompt: "sp",
agent_state: dir,
workspace: dir,
+ source: "user",
};
return new Session({
meta,
diff --git a/packages/core/test/input-images.test.ts b/packages/core/test/input-images.test.ts
index d04df3f9..761f978d 100644
--- a/packages/core/test/input-images.test.ts
+++ b/packages/core/test/input-images.test.ts
@@ -198,6 +198,7 @@ describe("Session input-image wiring", () => {
system_prompt: "sp",
agent_state: tmp,
workspace: tmp,
+ source: "user",
});
/** An LLM that steers once from inside its first request, then answers. */
diff --git a/packages/core/test/mcp-tools.test.ts b/packages/core/test/mcp-tools.test.ts
index 33a1e998..351717fc 100644
--- a/packages/core/test/mcp-tools.test.ts
+++ b/packages/core/test/mcp-tools.test.ts
@@ -543,6 +543,7 @@ describe("Session first-run bootstrap events", () => {
system_prompt: "sp",
agent_state: tmp,
workspace: tmp,
+ source: "user",
};
return new Session({
meta,
@@ -665,6 +666,7 @@ describe("Session first-run bootstrap events", () => {
system_prompt: "sp",
agent_state: tmp,
workspace: tmp,
+ source: "user",
},
bootstrap: async ({ emit }) => {
calls += 1;
diff --git a/packages/core/test/model-switch.test.ts b/packages/core/test/model-switch.test.ts
index 8b8ede69..ea203f48 100644
--- a/packages/core/test/model-switch.test.ts
+++ b/packages/core/test/model-switch.test.ts
@@ -130,6 +130,7 @@ const metaFor = (model: ModelRef): SessionMetaPayload => ({
system_prompt: "sp",
agent_state: "/tmp/state",
workspace: "/tmp/ws",
+ source: "user",
});
const SUMMARY_REPLY = "[summary]the distilled summary[/summary]";
diff --git a/packages/core/test/replay.test.ts b/packages/core/test/replay.test.ts
index 5181ce5b..2647eb2a 100644
--- a/packages/core/test/replay.test.ts
+++ b/packages/core/test/replay.test.ts
@@ -54,6 +54,7 @@ function meta(): OmniMessage {
system_prompt: "SP",
agent_state: "/agent/state",
workspace: "/ws",
+ source: "user",
});
}
diff --git a/packages/core/test/resume.test.ts b/packages/core/test/resume.test.ts
index eb93e76c..b53021a0 100644
--- a/packages/core/test/resume.test.ts
+++ b/packages/core/test/resume.test.ts
@@ -80,12 +80,7 @@ async function writeTraceFile(
return file;
}
-function metaFor(
- sessionId: string,
- workspaceDir: string,
- model = MODEL,
- source?: "subagent" | "schedule",
-): OmniMessage {
+function metaFor(sessionId: string, workspaceDir: string, model = MODEL): OmniMessage {
return sessionMeta({
session_id: sessionId,
provider: model.provider,
@@ -94,7 +89,7 @@ function metaFor(
system_prompt: "ORIGINAL SYSTEM PROMPT",
agent_state: "/agent/state",
workspace: workspaceDir,
- ...(source !== undefined ? { source } : {}),
+ source: "user",
});
}
@@ -123,43 +118,6 @@ describe("agent.resumeSession", () => {
expect(texts).toEqual(["hello", "hi there"]);
});
- it("preserves the stored session source across resume (and its absence for user sessions)", async () => {
- const agent = await createAgent({});
- await writeTraceFile(tmpRoot, SID, [
- metaFor(SID, workspace, MODEL, "subagent"),
- userText("child task"),
- requestBegin(),
- assistantText("done"),
- requestEnd("completed"),
- ]);
- const session = await agent.resumeSession({ sessionId: SID });
- // The rebuilt session_meta carries the origin over (a rotated Trace file must re-record it).
- expect((session.metaMessage.payload as { source?: string }).source).toBe("subagent");
- session.dispose();
-
- // A user-created session's meta has no source key, and resume must not invent one.
- const SID2 = "session-2026-07-06-11-00-00-abcdef02";
- await writeTraceFile(tmpRoot, SID2, [metaFor(SID2, workspace), userText("hi")]);
- const plain = await agent.resumeSession({ sessionId: SID2 });
- expect("source" in (plain.metaMessage.payload as unknown as Record<string, unknown>)).toBe(
- false,
- );
- plain.dispose();
-
- // On-disk values are untrusted: a junk source written by a third party is dropped on
- // resume (only the exact known origins pass), not cast through into the rebuilt meta.
- const SID3 = "session-2026-07-06-12-00-00-abcdef03";
- await writeTraceFile(tmpRoot, SID3, [
- metaFor(SID3, workspace, MODEL, "weird-origin" as unknown as "subagent"),
- userText("hi"),
- ]);
- const junk = await agent.resumeSession({ sessionId: SID3 });
- expect("source" in (junk.metaMessage.payload as unknown as Record<string, unknown>)).toBe(
- false,
- );
- junk.dispose();
- });
-
it("keeps abort events in resumed render history", async () => {
const agent = await createAgent({});
await writeTraceFile(tmpRoot, SID, [
diff --git a/packages/core/test/session-source.test.ts b/packages/core/test/session-source.test.ts
new file mode 100644
index 00000000..df32f2fa
--- /dev/null
+++ b/packages/core/test/session-source.test.ts
@@ -0,0 +1,130 @@
+/**
+ * A Session's source (`session_meta.source`): what kind of conversation it is, recorded in
+ * every context's meta and carried across a resume. Old Traces are never rewritten; a resume
+ * reads their head through `normalizeSessionSource`.
+ *
+ * Scenarios:
+ * - Given no source, when a Session is created, its meta records `user`.
+ * - Given a source, when a Session is created, its meta records it unchanged.
+ * - Given a Trace head with a source (a scheduled run's, a company Session's), when the Session
+ * resumes, the meta its next context records carries the same source.
+ * - Given a Trace head written before the source was required (none), the retired
+ * `benchmark`, or junk a third party wrote, when the Session resumes, the source reads as
+ * `user`, `cli` and `user` respectively; the file on disk is left as it was.
+ */
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { createAgent } from "../src/index.js";
+import { sessionMeta, userText } from "../src/omnimessage/index.js";
+import type { OmniMessage, SessionSource } from "../src/omnimessage/index.js";
+import { tracesDir } from "../src/state/paths.js";
+import { stubProviderKeys } from "./provider-keys.js";
+
+let tmpRoot: string;
+let workspace: string;
+let prevHome: string | undefined;
+let restoreKeys: () => void;
+
+beforeEach(async () => {
+ prevHome = process.env.PENGUIN_HOME;
+ tmpRoot = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-source-"));
+ workspace = await fs.mkdtemp(path.join(os.tmpdir(), "penguin-source-ws-"));
+ process.env.PENGUIN_HOME = tmpRoot;
+ restoreKeys = stubProviderKeys();
+});
+
+afterEach(async () => {
+ if (prevHome === undefined) delete process.env.PENGUIN_HOME;
+ else process.env.PENGUIN_HOME = prevHome;
+ restoreKeys();
+ await fs.rm(tmpRoot, { recursive: true, force: true });
+ await fs.rm(workspace, { recursive: true, force: true });
+});
+
+const SID = "session-2026-10-07-10-00-00-5011ce01";
+
+/**
+ * A Trace left behind by an earlier process, whose head carries `source` exactly as given:
+ * a valid value, the retired `benchmark`, junk, or (undefined) no key at all.
+ */
+async function writeTrace(source: unknown): Promise<string> {
+ const dir = path.join(tracesDir(tmpRoot, "default_project", "default_agent"), "2026-10-07");
+ await fs.mkdir(dir, { recursive: true });
+ const meta = {
+ session_id: SID,
+ provider: "anthropic",
+ model_id: "claude-sonnet-4-6",
+ model_context_window: 1000000,
+ system_prompt: "ORIGINAL SYSTEM PROMPT",
+ agent_state: "/agent/state",
+ workspace,
+ ...(source !== undefined ? { source } : {}),
+ };
+ const records: OmniMessage[] = [
+ sessionMeta(meta as Parameters<typeof sessionMeta>[0]),
+ userText("hello"),
+ ];
+ const file = path.join(dir, `${SID}_001.jsonl`);
+ await fs.writeFile(file, records.map((m) => JSON.stringify(m)).join("\n") + "\n", "utf8");
+ return file;
+}
+
+const sourceOf = (session: { metaMessage: OmniMessage }) =>
+ (session.metaMessage.payload as { source?: unknown }).source;
+
+describe("creating a Session", () => {
+ it("records user when no source is given", async () => {
+ const agent = await createAgent();
+ const session = await agent.createSession({ workspaceDir: workspace });
+ try {
+ expect(sourceOf(session)).toBe("user");
+ } finally {
+ session.dispose();
+ }
+ });
+
+ it("records the given source unchanged", async () => {
+ const agent = await createAgent();
+ const session = await agent.createSession({ workspaceDir: workspace, source: "cli" });
+ try {
+ expect(sourceOf(session)).toBe("cli");
+ } finally {
+ session.dispose();
+ }
+ });
+});
+
+describe("resuming a Session", () => {
+ it.each(["schedule", "company"] satisfies SessionSource[])(
+ "carries a recorded %s source into the meta its next context records",
+ async (source) => {
+ await writeTrace(source);
+ const agent = await createAgent();
+ const session = await agent.resumeSession({ sessionId: SID });
+ try {
+ expect(sourceOf(session)).toBe(source);
+ } finally {
+ session.dispose();
+ }
+ },
+ );
+
+ it.each([
+ { head: "no source", value: undefined, reads: "user" },
+ { head: "the retired benchmark", value: "benchmark", reads: "cli" },
+ { head: "junk", value: "weird-origin", reads: "user" },
+ ])("reads a head with $head as $reads, leaving the file as it was", async ({ value, reads }) => {
+ const file = await writeTrace(value);
+ const before = await fs.readFile(file, "utf8");
+ const agent = await createAgent();
+ const session = await agent.resumeSession({ sessionId: SID });
+ try {
+ expect(sourceOf(session)).toBe(reads);
+ expect(await fs.readFile(file, "utf8")).toBe(before);
+ } finally {
+ session.dispose();
+ }
+ });
+});
diff --git a/packages/core/test/session-title.test.ts b/packages/core/test/session-title.test.ts
index fe9724b2..d4fa8d11 100644
--- a/packages/core/test/session-title.test.ts
+++ b/packages/core/test/session-title.test.ts
@@ -55,6 +55,7 @@ const META: SessionMetaPayload = {
system_prompt: "sp",
agent_state: "/tmp/state",
workspace: "/tmp/w",
+ source: "user",
};
/** Image-fold wiring every Session takes; these tests send no images, so it is never exercised. */
diff --git a/packages/core/test/trace.test.ts b/packages/core/test/trace.test.ts
index 5796f485..3f503e8a 100644
--- a/packages/core/test/trace.test.ts
+++ b/packages/core/test/trace.test.ts
@@ -36,6 +36,7 @@ function meta() {
system_prompt: "test system prompt",
agent_state: "/tmp/agent_state",
workspace: "/tmp/workspace",
+ source: "user",
});
}
@@ -96,6 +97,7 @@ describe("Writer", () => {
system_prompt: "child prompt",
agent_state: "/tmp/child_agent/agent_state",
workspace: "/tmp/workspace",
+ source: "user",
});
await writer.writeAll([
meta(),
diff --git a/packages/core/test/user-prompt-hooks.test.ts b/packages/core/test/user-prompt-hooks.test.ts
index 0edcc256..3ca06be7 100644
--- a/packages/core/test/user-prompt-hooks.test.ts
+++ b/packages/core/test/user-prompt-hooks.test.ts
@@ -194,6 +194,7 @@ describe("Session user-prompt hooks", () => {
system_prompt: "sp",
agent_state: dir,
workspace: dir,
+ source: "user",
});
/** A Trace sink that keeps what it is handed, in order. */
diff --git a/packages/docs/content/chat.en.md b/packages/docs/content/chat.en.md
index bb1dff3a..f39abfec 100644
--- a/packages/docs/content/chat.en.md
+++ b/packages/docs/content/chat.en.md
@@ -345,15 +345,18 @@ The right-click menu replaces the browser's own menu only on conversation rows a
| Pin | The conversation is pinned |
| Remote control icon | A messaging connection is enabled for the conversation |
| Alarm clock | A scheduled task bound to the conversation will still fire; see [Scheduled tasks](/schedules) |
+| Plug, calendar, two robots or `>_` prompt | In the **Background** folder: what opened the Session, the Agent API, a scheduled task's run, a parent agent or `penguin run` |
The background-task mark does not depend on the others: an idle conversation whose dev server is still running keeps it, and it disappears as soon as the last task ends, without a refresh.
### Folders
-Below each group's active conversations are its folders: **Subagents**, **Scheduled**, **Evaluations** and **Archived**, each loading its rows only when opened. When grouped by time, one set of folders covers the whole Project, and **Load more chats** fetches older conversations.
+Below each group's active conversations are its two folders, **Background** and **Archived**, each loading its rows only when opened. When grouped by time, one set of folders covers the whole Project, and **Load more chats** fetches older conversations.
-- **Evaluations** holds the Test Sessions an evaluation starts for every case and run, so they do not crowd the tested agent's list. The conversation that **Use** opens in the [Evaluation Center](/evaluation-center) is an ordinary conversation and is not filed there.
-- Opening a subagent, scheduled or evaluation conversation opens its folder.
+- **Background** holds the Sessions a program opened rather than you: those an external program opened through the Agent API, a scheduled task's runs, subagent Sessions, and those `penguin run` created, including the Test Sessions an evaluation starts for every case and run. Each row carries a mark naming its source (API, Scheduled, Subagent or CLI), shown on hover.
+- **Archived** holds every archived conversation, whatever its source.
+- Company mode's desk and ticket Sessions are in none of these, archived or not, in either mode: they are listed only in [company mode](/company-mode)'s own views.
+- Opening a background conversation opens its folder. **Last conversation** and a deleted conversation's successor are only ever your own conversations, never background or company ones.
- A group with nothing but folder rows, such as an agent that has only run evaluations, starts collapsed and sorts after the other groups (pinned groups excepted), with a dimmed header counting the folded rows. Once you open it, it stays open for that Project.
A group's active conversations, and each open folder, show ten conversations at a time. **Show N more chats** reveals ten more; rows already loaded come first, and more are fetched from the server only when they run out. Once more than ten show, **Show less** folds back to the first ten. With more than ten groups, the list shows ten groups per page, with a pager below it.
diff --git a/packages/docs/content/chat.zh.md b/packages/docs/content/chat.zh.md
index 8ca157a8..f704cca0 100644
--- a/packages/docs/content/chat.zh.md
+++ b/packages/docs/content/chat.zh.md
@@ -345,15 +345,18 @@ Task 运行时输入了内容,发送按钮的行为取决于 + 菜单底部的
| 置顶标记 | 对话已置顶 |
| 远程控制图标 | 这段对话已启用消息软件连接 |
| 闹钟 | 绑定到这段对话的定时任务还会触发,见[定时任务](/schedules) |
+| 插头、日历、两个机器人或 `>_` 提示符 | 在**后台会话**折叠夹中,表示是什么打开了这个 Session:Agent API、定时任务的一次运行、父 Agent 或 `penguin run` |
后台任务标记与其他标记互不影响:对话已经空闲、但 dev server 还开着时,标记仍在;最后一个后台任务结束的那一刻标记就会消失,无需刷新。
### 折叠夹
-每个分组的活跃对话下方是它的折叠夹:**子智能体**、**定时任务**、**评估任务**和**已归档**,各自在展开时才加载其中的对话。按时间分组时,整个 Project 共用一组折叠夹,**加载更多会话**用来加载更早的对话。
+每个分组的活跃对话下方是它的两个折叠夹:**后台会话**和**已归档**,各自在展开时才加载其中的对话。按时间分组时,整个 Project 共用一组折叠夹,**加载更多会话**用来加载更早的对话。
-- **评估任务**收纳评估为每道题目、每次运行启动的测试 Session,这样它们就不会挤满被测 Agent 的列表。在[评估中心](/evaluation-center)点击**使用**打开的对话是普通对话,不归入这里。
-- 打开子 Agent、定时任务或评估的对话时,它所在的折叠夹会自动展开。
+- **后台会话**收纳由程序而不是你打开的 Session:外部程序经 Agent API 开出的会话、定时任务的每次运行、子 Agent 会话,以及 `penguin run` 创建的会话,其中包括评估为每道题目、每次运行启动的测试 Session。每一行都带一个标明来源的图标(API、定时任务、子智能体或 CLI),悬停时显示。
+- **已归档**收纳所有已归档的对话,无论来源。
+- 公司模式的工位会话与工单会话不在其中任何一处,归档与否、哪种模式下都一样:它们只列在[公司模式](/company-mode)自己的页面里。
+- 打开后台会话时,它所在的折叠夹会自动展开。**最近一次对话**以及删除当前对话后跳转到的对话,都只会是你自己的对话,不会是后台会话或公司模式的会话。
- 只有折叠夹、没有活跃对话的分组(例如只跑过评估的 Agent)默认折叠,排在其他分组之后(置顶的分组除外),分组标题变浅,并显示折叠的对话数。展开过一次后,在这个 Project 中会一直保持展开。
分组里的活跃对话和每个展开的折叠夹,一次都显示 10 条。**展开其余 N 个对话**每次再显示 10 条:先显示已经加载的,不够时才向服务器取。显示超过 10 条后,**收起**可以折回前 10 条。分组超过 10 个时,列表每页显示 10 个分组,下方有翻页控件。
diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.md
index 6830489f..7f40e833 100644
--- a/packages/docs/content/cli.en.md
+++ b/packages/docs/content/cli.en.md
@@ -52,13 +52,14 @@ penguin run -m <message> [options]
| `--approve <mode>` | Approval mode; see [Approval modes (--approve)](#approval-modes---approve). With `--session`, it PATCHes the Session's sticky mode. | `allow-all` |
| `--thinking <level>` | Pins the Session's thinking level (`low` / `medium` / `high` / `xhigh` / `max`) before the Task. It applies from the Session's next LLM request. | The Session's pinned level, else the agent config |
| `--session <sessionId>` | Reuses an existing Session (full id or unique fragment) instead of creating one. Cannot be combined with `--workspace` or the model pair. | — |
-| `--source <source>` | Marks the new Session as created by a Benchmark evaluation. The only value is `benchmark`, and the Web App files such Sessions under the Evaluations folder of the session list. Cannot be combined with `--session`. | — |
| `--background` | POSTs the Task and exits immediately, printing the session id (`{"sessionId"}` under `--json`). The Task keeps running on the server; follow it with `penguin logs -f`. | — |
| `--timeout <duration>` | Soft-yield wait budget; see [Global conventions](#global-conventions). Cannot be combined with `--background`. | Wait indefinitely |
| `--goal [budget]` | Goal mode: the message is the objective, and the server loops until the goal reaches a terminal state. The optional value is a token budget, such as `500k`. | — |
| `--json` | Prints a final `{sessionId, status, text}` object instead of the rendered stream. `text` joins the main Session's assistant text messages. | — |
| `--server <url>` | Target server; see [Server connection](#server-connection). | — |
+Every Session `run` creates is a CLI Session (`source: "cli"`), which the Web App lists in the **Background** folder of its session list rather than among the agent's conversations. `penguin chat` creates ordinary conversations. The `--source benchmark` that older evaluation skills pass is accepted and ignored, with a note.
+
When `--timeout` expires, `run` prints what has rendered so far and a dim still-running line with the session id, then exits 0 without aborting the Task. Under `--json` it prints `{sessionId, status: "running", text}`. `--timeout 0` returns right after the POST, and under `--json` prints `{sessionId, status: "running"}` with no `text`. For a goal run, the `status` in the final JSON object is the goal outcome.
Ctrl-C at an approval prompt denies that tool call. At any other time it aborts the Task on the server.
diff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.md
index 8da270d8..629f3d5f 100644
--- a/packages/docs/content/cli.zh.md
+++ b/packages/docs/content/cli.zh.md
@@ -52,13 +52,14 @@ penguin run -m <message> [options]
| `--approve <mode>` | 审批模式;见[审批模式(--approve)](#审批模式--approve)。配合 `--session` 时,以 PATCH 请求更新 Session 固定的审批模式。 | `allow-all` |
| `--thinking <level>` | 在 Task 开始前固定 Session 的思考等级(`low` / `medium` / `high` / `xhigh` / `max`)。从 Session 的下一次 LLM 请求起生效。 | Session 已固定的等级,否则用 Agent 配置 |
| `--session <sessionId>` | 复用已有的 Session(完整 id 或唯一片段),而不是新建。不能与 `--workspace` 或模型对同时使用。 | — |
-| `--source <source>` | 把新建的 Session 标记为由 Benchmark 评估创建。取值仅限 `benchmark`,Web App 会把这类 Session 归入会话列表的「评估任务」文件夹。不能与 `--session` 同时使用。 | — |
| `--background` | 以 POST 提交 Task 后立即退出,打印 session id(`--json` 下为 `{"sessionId"}`)。Task 在服务器上继续运行;可用 `penguin logs -f` 跟踪。 | — |
| `--timeout <duration>` | 软让出的等待预算;见[全局约定](#全局约定)。不能与 `--background` 同时使用。 | 无限等待 |
| `--goal [budget]` | 目标模式:消息就是目标,服务器循环执行,直到目标达到终态。可选值是 Token 预算,例如 `500k`。 | — |
| `--json` | 打印最终的 `{sessionId, status, text}` 对象,取代渲染后的流。`text` 拼接主 Session 的 助手文本消息。 | — |
| `--server <url>` | 目标服务器;见[服务器连接](#服务器连接)。 | — |
+`run` 创建的每个 Session 都是 CLI 会话(`source: "cli"`),Web App 把它列在会话列表的**后台会话**折叠夹里,而不是 Agent 的对话之间。`penguin chat` 创建的是普通对话。旧版评估 Skill 传入的 `--source benchmark` 仍被接受,但会被忽略并给出提示。
+
`--timeout` 到时后,`run` 打印目前已渲染的内容和一行暗色的仍在运行提示(附 session id),然后退出 0,不中止 Task。`--json` 下则打印 `{sessionId, status: "running", text}`。`--timeout 0` 在 POST 完成后立即返回,`--json` 下打印 `{sessionId, status: "running"}`,不含 `text`。对目标模式运行,最终 JSON 对象里的 `status` 就是目标结果。
在审批提示处按 Ctrl-C 会拒绝这一次工具调用;其他任何时候按 Ctrl-C 都会在服务器上中止 Task。
diff --git a/packages/docs/content/company-mode.en.md b/packages/docs/content/company-mode.en.md
index 428800b6..b8ebac4e 100644
--- a/packages/docs/content/company-mode.en.md
+++ b/packages/docs/content/company-mode.en.md
@@ -302,7 +302,7 @@ The organization scheduler runs a pass every 30 seconds, and immediately after e
### Session marks
-A desk or ticket session is marked as the organization's on the Session row itself when it is opened. It is therefore listed in company mode and never in development mode's session list, even after the organization's directory is removed by hand or the server switch is turned off, when nothing else could tell whose it was. Organizations that already existed get their Sessions marked on the runtime's next pass over their files.
+A desk or ticket session is a company Session: its Trace records `source: "company"` (see [session_meta](/omni-message#sessionmeta)), and the Session row itself is marked as the organization's when it is opened. It is therefore listed in company mode and never in the session list, in either mode, even after the organization's directory is removed by hand or the server switch is turned off, when nothing else could tell whose it was. Organizations that already existed get their Sessions marked on the runtime's next pass over their files, and their older desk and ticket sessions, whose Traces record no source, read as company Sessions by that mark.
### Skill updates
diff --git a/packages/docs/content/company-mode.zh.md b/packages/docs/content/company-mode.zh.md
index 2bf06f39..b7fcf993 100644
--- a/packages/docs/content/company-mode.zh.md
+++ b/packages/docs/content/company-mode.zh.md
@@ -302,7 +302,7 @@ penguin org finance # spend per employee (cumulati
### 会话标记
-工位会话或工单会话一打开,Session 记录本身就会打上「属于这个组织」的标记。因此它只出现在公司模式里,从不出现在开发模式的会话列表中;即使有人手工删掉了组织目录、服务器开关也已关闭,再没有别的东西能说明它属于谁,也是如此。已经存在的组织,运行时下一轮扫描它的文件时,会给它的会话补上标记。
+工位会话和工单会话是公司模式的会话:其 Trace 记录 `source: "company"`(见 [session_meta](/omni-message#sessionmeta)),一打开,Session 记录本身也会打上「属于这个组织」的标记。因此它只出现在公司模式里,无论哪种模式都不出现在会话列表中;即使有人手工删掉了组织目录、服务器开关也已关闭,再没有别的东西能说明它属于谁,也是如此。已经存在的组织,运行时下一轮扫描它的文件时,会给它的会话补上标记;其中较早的工位会话与工单会话,Trace 没有记录来源,凭这个标记读作公司模式的会话。
### Skill 更新
diff --git a/packages/docs/content/evaluation-center.en.md b/packages/docs/content/evaluation-center.en.md
index 4b12ac34..0c879fe1 100644
--- a/packages/docs/content/evaluation-center.en.md
+++ b/packages/docs/content/evaluation-center.en.md
@@ -142,7 +142,7 @@ An evaluation runs an agent on every case of a Benchmark and adds one labelled s
The dialog has no field for the model or thinking level the tested agent runs on. **Model of the evaluation conversation** only sets the model of the conversation that dispatches and totals the runs.
-The evaluation conversation is an ordinary conversation in the session list. Every Test Session the evaluator starts (`penguin run --source benchmark`) is filed under the **Evaluations** folder. The finished evaluation becomes the newest row of the Benchmark's **Evaluations** table.
+The evaluation conversation is an ordinary conversation of yours. Every Test Session it starts is a CLI Session, filed under the **Background** folder of the session list. The finished evaluation becomes the newest row of the Benchmark's **Evaluations** table.
## Optimize an agent
diff --git a/packages/docs/content/evaluation-center.zh.md b/packages/docs/content/evaluation-center.zh.md
index 3a99aaa5..0f6d6dd5 100644
--- a/packages/docs/content/evaluation-center.zh.md
+++ b/packages/docs/content/evaluation-center.zh.md
@@ -142,7 +142,7 @@ Builder 试测题目和记录基线分时,都用这个新对话的模型来运
对话框里没有设置被测 Agent 所用模型和思考等级的字段。**评估会话使用的模型**只决定派发和汇总评测的那个会话使用什么模型。
-评估会话是会话列表里的普通对话。执行评估的 Agent 启动的每个被测会话(`penguin run --source benchmark`)都归入**评估任务**折叠夹。评估完成后,会成为这个 Benchmark **评估明细**表的最新一行。
+评估会话是你的一段普通对话;它启动的每个被测会话都是 CLI 会话,归入会话列表的**后台会话**折叠夹。评估完成后,会成为这个 Benchmark **评估明细**表的最新一行。
## 优化 Agent
diff --git a/packages/docs/content/omni-message.en.md b/packages/docs/content/omni-message.en.md
index 87489e6a..382e40bb 100644
--- a/packages/docs/content/omni-message.en.md
+++ b/packages/docs/content/omni-message.en.md
@@ -43,12 +43,23 @@ interface SessionMetaPayload {
system_prompt: string; // fully assembled, placeholders substituted
agent_state: string; // absolute path of the Agent State
workspace: string; // absolute path of the Workspace
- source?: "subagent" | "schedule" | "benchmark"; // spawned by a subagent / a scheduled task / a Benchmark run; absent = user-created
+ source: "user" | "api" | "schedule" | "subagent" | "cli" | "company"; // what kind of conversation this is
}
```
The Workspace is fixed for the Session's lifetime. The model and the system prompt are fixed per context: an in-session model switch opens its new context on another model, and this record is the only place that says so.
+`source` says what kind of conversation the Session is, and is fixed for its lifetime too:
+
+- `user`: a person's conversation, the Web App's composer, `penguin chat` and forks included;
+- `api`: one an external program opened through the Agent API;
+- `schedule`: a scheduled task's run;
+- `subagent`: a `run_subagent` child;
+- `cli`: one `penguin run` created;
+- `company`: a desk or ticket Session that [company mode](/company-mode) opened.
+
+A Trace written by an older release may have no `source`, which reads as `user`, or as `company` when the server's index row says company mode opened the Session. It may also carry the retired `benchmark`, which reads as `cli`. The file itself is never rewritten.
+
Every Trace file opens with a `session_meta`. When a compaction opens a new context, the new file's `session_meta` carries the system prompt assembled for that context from the Agent State as it stands at that moment (see [Compaction](/agent-loop#compaction)). On resume, the engine takes the latest file's `session_meta` as the runtime configuration. See [Sessions & Traces](/sessions-and-traces).
The thinking level is not part of the meta. It is a per-request parameter: each request takes the Session's pinned level, which can change mid-context and applies from the next request, or, without a pin, the agent config default read when the context opened. Nothing records the level. A `thinking_level` field found in older Traces is displayed but never read back.
diff --git a/packages/docs/content/omni-message.zh.md b/packages/docs/content/omni-message.zh.md
index 13b8f639..7022b3b5 100644
--- a/packages/docs/content/omni-message.zh.md
+++ b/packages/docs/content/omni-message.zh.md
@@ -43,12 +43,23 @@ interface SessionMetaPayload {
system_prompt: string; // fully assembled, placeholders substituted
agent_state: string; // absolute path of the Agent State
workspace: string; // absolute path of the Workspace
- source?: "subagent" | "schedule" | "benchmark"; // spawned by a subagent / a scheduled task / a Benchmark run; absent = user-created
+ source: "user" | "api" | "schedule" | "subagent" | "cli" | "company"; // what kind of conversation this is
}
```
Workspace 在整个 Session 生命周期内不变,模型与系统提示词则按上下文固定:会话内切换模型时,新上下文开在另一个模型上,所用模型只记在这条记录里。
+`source` 表示这个 Session 是哪一类会话,同样在整个生命周期内不变:
+
+- `user`:人发起的对话,包括 Web App 的输入框、`penguin chat`,以及分叉出的会话;
+- `api`:外部程序经 Agent API 开出的会话;
+- `schedule`:定时任务的一次运行;
+- `subagent`:`run_subagent` 派生的子会话;
+- `cli`:`penguin run` 创建的会话;
+- `company`:[公司模式](/company-mode)开出的工位会话与工单会话。
+
+旧版本写下的 Trace 可能没有 `source`,读作 `user`;若服务器的索引行表明它由公司模式开出,则读作 `company`。也可能是已停用的 `benchmark`,读作 `cli`。文件本身从不改写。
+
每个 Trace 文件都以一条 `session_meta` 开头。压缩开启新上下文时,新文件的 `session_meta` 记录的系统提示词,按当时的 Agent State 为这个上下文重新装配(见[上下文压缩](/agent-loop#上下文压缩))。恢复 Session 时,引擎以最新文件里的 `session_meta` 作为运行时配置,见 [Session 与 Trace](/sessions-and-traces)。
思考等级不在 meta 里,它是逐请求的参数:每次请求取 Session 钉住的等级,这个等级可以在上下文中途更换,从下一次请求起生效;没有钉住时,取上下文开启时读到的 Agent 配置缺省值。思考等级不作任何记录。旧 Trace 里出现的 `thinking_level` 字段只用于展示,不会被读回。
diff --git a/packages/docs/content/self-improvement.en.md b/packages/docs/content/self-improvement.en.md
index aac3e696..4d852728 100644
--- a/packages/docs/content/self-improvement.en.md
+++ b/packages/docs/content/self-improvement.en.md
@@ -21,7 +21,7 @@ No built-in agent is reserved for a role: each role is a Skill, and all four Ski
### How the roles call each other
1. The Builder or the Optimizer dispatches the full Case × runs matrix in parallel through `run_subagent`: one Evaluator per cell, each told to use `agent-evaluation`.
-2. Each Evaluator uses the Penguin CLI to launch the Target Agent once, in a fresh top-level Session and a unique Workspace under the Target Agent's `workspaces/` directory, given by its absolute path. The launch passes `--source benchmark`, so every Test Session lands in the **Evaluations** folder of the Web App's session list instead of among the agent's active conversations. The Evaluator's own Session is an ordinary subagent Session.
+2. Each Evaluator uses the Penguin CLI to launch the Target Agent once, in a fresh top-level Session and a unique Workspace under the Target Agent's `workspaces/` directory, given by its absolute path. Every Session `penguin run` creates is a CLI Session, so every Test Session lands in the **Background** folder of the Web App's session list, marked CLI, instead of among the agent's active conversations. The Evaluator's own Session is an ordinary subagent Session, in the same folder.
3. When the Target Agent finishes, the Evaluator scores the run against the rubric and returns one protocol result: the score, cost, duration and Test Session id. It changes no agent or Benchmark, and never writes `scoreboard.yaml`.
4. The caller checks the complete matrix and writes `scoreboard.yaml`.
diff --git a/packages/docs/content/self-improvement.zh.md b/packages/docs/content/self-improvement.zh.md
index b0546a77..6f2c3b2d 100644
--- a/packages/docs/content/self-improvement.zh.md
+++ b/packages/docs/content/self-improvement.zh.md
@@ -21,7 +21,7 @@ PenguinHarness 的自我进化是一个循环:为 Agent 构建 Benchmark,在
### 角色之间的调用
1. Builder 或 Optimizer 通过 `run_subagent` 并行下发完整的 Case × runs 矩阵:矩阵中的每一格对应一个 Evaluator,并要求它使用 `agent-evaluation`。
-2. 每个 Evaluator 用 Penguin CLI 启动一次 Target Agent:开一个全新的顶层 Session,在 Target Agent 的 `workspaces/` 目录下建一个专属 Workspace,并以绝对路径传入。启动时带上 `--source benchmark`,所以每个被测会话都会归入 Web App 会话列表的**评估任务**折叠夹,不会混进这个 Agent 的活跃对话。Evaluator 自己的 Session 是普通的子 Agent Session。
+2. 每个 Evaluator 用 Penguin CLI 启动一次 Target Agent:开一个全新的顶层 Session,在 Target Agent 的 `workspaces/` 目录下建一个专属 Workspace,并以绝对路径传入。`penguin run` 创建的每个 Session 都是 CLI 会话,所以每个被测会话都会归入 Web App 会话列表的**后台会话**折叠夹并标为 CLI,不会混进这个 Agent 的活跃对话。Evaluator 自己的 Session 是普通的子 Agent Session,同样在这个折叠夹里。
3. Target Agent 运行结束后,Evaluator 按评分细则为这次运行打分,返回一条协议结果:分数、成本、耗时和被测会话 id。Evaluator 不改动任何 Agent 或 Benchmark,也从不写 `scoreboard.yaml`。
4. 调用方核对完整的矩阵后写入 `scoreboard.yaml`。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index 04eeaf9f..e70cfa6e 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -644,13 +644,14 @@ The paths below omit the `/api/projects/:projectId` prefix.
| GET | `/workspace-files/search?workspace=&q=` | Searches that directory by entry name |
| POST | `/workspace-files/reveal?workspace=&path=` | Shows the file in the machine's own file manager |
-- The Session list accepts optional query parameters. `limit` and `offset` page the list (`offset` requires `limit`). `category` (`active`, `subagent`, `schedule`, `benchmark` or `archived`) filters it before paging, and `workspaceGroup` filters it to one Workspace. `counts=1` adds `counts` (totals per category over the whole list, whatever the page), `workspaceCounts` (the same totals per Workspace path) and `workspaceLatest` (each Workspace's newest Session). Without paging parameters, the full list is returned.
+- The Session list accepts optional query parameters. `limit` and `offset` page the list (`offset` requires `limit`). `category` (`active`, `background` or `archived`) filters it before paging, and `workspaceGroup` filters it to one Workspace. `counts=1` adds `counts` (totals per category over the whole list, whatever the page), `workspaceCounts` (the same totals per Workspace path) and `workspaceLatest` (each Workspace's newest Session). Without paging parameters, the full list is returned.
- `order` picks the list's order: `created` (the default) is newest creation first; `activity` is most recent `lastActiveAt` first, equal stamps by `sessionId` descending, both compared by code point rather than by locale. Under `order=activity`, `before=<lastActiveAt>,<sessionId>` with `limit` pages by cursor instead of offset: it returns the rows strictly below that key, typically the last row the client already shows. A Session that becomes active between two pages moves above the cursor, so it is not served again and no other row goes missing. `before` without `order=activity`, together with `offset`, without `limit`, or not a date and a valid id split at the first comma is a 400.
- `excludeOrg=1` leaves an organization's desk, ticket and subagent Sessions out of the page and out of the `counts=1` totals together, which is what development mode's list asks for. Any other value is a 400.
- On creation, `modelId` and `provider` go together: send the complete pair to pick a model, or omit both to use the Project's default model. Sending only one is a 400.
- An explicit `workspace` must be an existing directory; it is never created. When omitted, the Workspace is a temporary one created automatically. The approval mode defaults to `allow-all`.
-- `client` is a provenance hint stored on the row: `"cli"` from the CLI, `"web"` by default. The server itself writes `"org"` on an organization's desk and ticket sessions, and a client cannot send that value. Only `excludeOrg` reads it as a filter, and only to drop those rows.
-- `source` accepts only `"benchmark"`, which the CLI sends for `penguin run --source benchmark`: the Test Sessions a Benchmark evaluation starts. The Web App does not send it. The server sets `subagent` and `schedule` itself.
+- `client` is a provenance hint stored on the row: `"cli"` from the CLI, `"web"` by default. The server itself writes `"org"` on an organization's desk and ticket sessions, and a client cannot send that value. Only `excludeOrg` reads it as a filter, and only to drop those rows. An `"org"` row whose Trace records no `source` (written by an older release, or not run yet) reads as a `company` Session.
+- A Session's `source` says what kind of conversation it is (see [session_meta](/omni-message#sessionmeta)). Its category follows from it: a `company` Session is in no category, archived or not, so a request with `category`, `workspaceGroup` or `counts=1` leaves it out of the page and every total; only the plain list serves it. Otherwise an archived Session is `archived` whatever its source; a `user` Session is `active`, and an `api`, `schedule`, `subagent` or `cli` Session is `background`. A row whose Trace head has not been read yet carries no `source` and counts as `active`.
+- On creation, `source` accepts only `"cli"`, which `penguin run` sends. Every other source is the server's own to write, and omitting it creates a `user` Session. The retired `"benchmark"` is still accepted, as `"cli"`.
- `GET /dirs` starts at the home directory when `path` is omitted; an explicit `path` must be absolute. It answers `{path, parent, entries, platform}`: every entry carries its `kind` (`dir` or `file`) and `mtime`, and on Windows an entry the system hides (the hidden attribute: `AppData`, `NTUSER.DAT`) carries `hidden: true`. A bare drive such as `D:` is taken as its root `D:\`. The home request with `places=1` adds what the picker's sidebar shows: `standardFolders` (Desktop, Documents, Downloads and Pictures as the machine resolves them — Windows known folders, Linux XDG user directories — omitted when they could not be read) and `locations` (Windows drives, macOS volumes, the Linux root and its mounts under `/media`, `/run/media` and `/mnt`, each with its `kind` and, when it has one, its `label`). A directory the server may not read answers `403 dir_permission_denied` rather than an empty list — on macOS that is usually a Files and Folders permission the user has not granted.
- `POST /dirs/access` is the Workspace picker's **Allow access** in the desktop app. macOS asks about Desktop, Documents and Downloads only on behalf of the app it holds responsible for the read, so the desktop shell's main process reads the absolute `path` once, and the answer waits for the user. `granted` says whether the read succeeded (always `true` off macOS, where nothing is read). `packaged` is `false` for a development instance started from a terminal, whose reads macOS charges to that terminal. The route returns `400` `dir_not_absolute` for a path that is not absolute, `503` `shell_unreachable` when the server has no desktop shell to ask, and `504` `timeout` when the shell has not answered within 120 seconds. Only the desktop app's own window may call it; any other session gets `403` `desktop_shell_only`.
- `GET /dir-skills` reads only `<path>/.agents/skills` and `<path>/.claude/skills` of an absolute `path`, and answers `{path, skills}`. A directory without Skills answers with an empty list. See `POST /agents` under [Agents](#agents).
@@ -685,7 +686,7 @@ The paths below omit the `/api/projects/:projectId` prefix.
- `GET /usage/errors` takes `offset`, `limit`, the same `from` / `to` / `fromTs` / `toTs` / `agentId` filter, and an optional `kind` (`unexpected` or `expected`).
- The error table folds the records of one day that share a source, code, kind and message into one row, with its `count`, its latest time `ts` and its first time `firstTs`. `offset`, `limit` and `rows` count those rows; `total` and the dashboard's summary figures count records. `GET /usage` and `GET /usage/errors` take an optional `utcOffsetMinutes`, the reader's offset east of UTC (−840 to 840), which decides the day; without it the day is the server's own.
- `DELETE /usage/errors` takes the same filter as the reads, `from` / `to` / `fromTs` / `toTs` / `agentId`, but no `kind`, because the panel offers no such control. `from` and `to` are both required here (400 otherwise), because an open bound would clear the whole history rather than a filtered part. The clear reaches exactly what the caller's reads reach: an admin's clear also removes the unattributed rows that only an admin's read shows, and a member's clear never does.
-- `GET /agents/:agentId/traces` also accepts `limit` and `offset` for paging, and `category` (which requires `limit`) to list one category of Sessions.
+- `GET /agents/:agentId/traces` also accepts `limit` and `offset` for paging, and `category` (which requires `limit`) to list one category of Sessions. The paged listing leaves out `company` Sessions, which are in no category; the full drill-down without `limit` lists every Trace.
- Any member can download a Trace. Import is owner only, like the Agent State snapshot import, and capped at 14MB. The imported file must be valid Trace JSONL whose first record is a `session_meta` with a filename-safe `session_id`. A session id the agent already has is rejected (409 `trace_session_exists`), so an imported file always becomes index 001 of a new Session, stored in the local date directory of its first record's timestamp.
## Session-Level Endpoints
@@ -1113,7 +1114,7 @@ export type ServerEvent =
| { type: "credentials_updated" }
| { type: "hello" }
| { type: "web_updated"; rev: string }
- | { type: "session_created"; projectId: string; agentId: string; sessionId: string; source?: SessionSource }
+ | { type: "session_created"; projectId: string; agentId: string; sessionId: string; source: SessionSource }
| { type: "schedule_fired"; projectId: string; agentId: string; name: string; sessionId: string }
| { type: "schedule_queued"; projectId: string; agentId: string; name: string; sessionId: string }
| { type: "goal_started"; sessionId: string; objective: string; budget: number }
@@ -1154,7 +1155,7 @@ export type ServerEvent =
- `session_background` fires when a command moves to the background past its yield window or starts with `run_in_background`, when a process exits or is stopped, and when a background subagent starts, settles or is released. It carries `SessionInfo.backgroundTasks` as it now stands (`processes` = background command sessions still running, `subagents` = subagent Sessions moved to the background and mid-round), zeros included, so a list can clear its mark without refetching. The list rows and the single-Session GET omit the field when both counts are zero. Its audience is the same as for `session_state`.
- `credentials_updated` follows `PUT /models` or a completed key-minting flow. Cached runtimes were invalidated, so the client clears any composer state disabled by an auth failure.
- `web_updated` carries the new web revision as `rev` and is sent to every user channel.
-- `session_created` is sent for every creation to the user channels of the Project's owner and members, and for a subagent also on the parent Session's channel. `source` is absent for a user-created Session, as it is on the row. A title set through `PATCH /api/sessions/:id` is announced as `session_title` the same way.
+- `session_created` is sent for every creation to the user channels of the Project's owner and members, and for a subagent also on the parent Session's channel. `source` is what the new Session's `session_meta` records. A title set through `PATCH /api/sessions/:id` is announced as `session_title` the same way.
- `schedule_fired` names in `sessionId` the Session that received the prompt, which in new-Session mode is a new Session. A queued firing is sent once the Session is idle.
- `goal_round` carries `used`, the tokens counted so far.
- The `org_*` events are sent to the user channels of the Project's members. `org_channel` includes the message's mentions, so a client can tell whether it is addressed. These events are best effort; the organization routes carry the durable state.
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index 6a4b42ab..7b37f35f 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -644,13 +644,14 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
| GET | `/workspace-files/search?workspace=&q=` | 按条目名搜索该目录 |
| POST | `/workspace-files/reveal?workspace=&path=` | 在机器自带的文件管理器中显示文件 |
-- Session 列表接受可选查询参数。`limit` 和 `offset` 用于分页(`offset` 必须搭配 `limit`)。`category`(`active`、`subagent`、`schedule`、`benchmark` 或 `archived`)先过滤再分页;`workspaceGroup` 只保留一个 Workspace 的会话。`counts=1` 会在响应里附加 `counts`(整个列表按类别的总数,与取哪一页无关)、`workspaceCounts`(按 Workspace 路径统计的同类总数)和 `workspaceLatest`(每个 Workspace 最新的 Session)。不带分页参数时,返回完整列表。
+- Session 列表接受可选查询参数。`limit` 和 `offset` 用于分页(`offset` 必须搭配 `limit`)。`category`(`active`、`background` 或 `archived`)先过滤再分页;`workspaceGroup` 只保留一个 Workspace 的会话。`counts=1` 会在响应里附加 `counts`(整个列表按类别的总数,与取哪一页无关)、`workspaceCounts`(按 Workspace 路径统计的同类总数)和 `workspaceLatest`(每个 Workspace 最新的 Session)。不带分页参数时,返回完整列表。
- `order` 决定列表顺序:`created`(默认)按创建时间从新到旧;`activity` 按 `lastActiveAt` 从新到旧,时间相同时按 `sessionId` 降序,两者都按码点比较而非按区域设置排序。在 `order=activity` 下,`before=<lastActiveAt>,<sessionId>` 搭配 `limit` 以游标代替 `offset` 分页:只返回严格排在这个键之后的行,通常就是客户端已显示的最后一行。两页之间变为活跃的 Session 会移到游标之前,因此不会被再次返回,也不会让其他行漏掉。`before` 未搭配 `order=activity`、与 `offset` 同时出现、缺少 `limit`,或在第一个逗号处拆开后不是日期加合法 id,均返回 400。
- `excludeOrg=1` 会把组织的工位会话、工单会话和子 Session 一并移出这一页以及 `counts=1` 的总数,这正是开发模式的列表所要的。取其他值返回 400。
- 创建时 `modelId` 和 `provider` 必须成对出现:要指定模型就传完整一对,两个都省略则使用 Project 的默认模型。只传一个返回 400。
- 显式传入的 `workspace` 必须是已存在的目录,永远不会自动创建。省略时自动创建一个临时 Workspace。审批模式默认 `allow-all`。
-- `client` 是记录在数据行上的来源提示:CLI 发起的请求为 `"cli"`,默认 `"web"`。组织的工位会话和工单会话由服务器自己写入 `"org"`,客户端不能发送这个值。只有 `excludeOrg` 会把它当作过滤条件,而且只用来剔除这些行。
-- `source` 只接受 `"benchmark"`,由 CLI 的 `penguin run --source benchmark` 发送,用于 Benchmark 评估启动的被测会话;Web App 不发送它。`subagent` 和 `schedule` 由服务器自己设置。
+- `client` 是记录在数据行上的来源提示:CLI 发起的请求为 `"cli"`,默认 `"web"`。组织的工位会话和工单会话由服务器自己写入 `"org"`,客户端不能发送这个值。只有 `excludeOrg` 会把它当作过滤条件,而且只用来剔除这些行。Trace 未记录 `source` 的 `"org"` 行(旧版本写下的,或尚未运行过的)读作 `company` 会话。
+- Session 的 `source` 表示它是哪一类会话(见 [session_meta](/omni-message#sessionmeta)),类别由它决定:`company` 会话不属于任何类别,归档与否都一样,因此带 `category`、`workspaceGroup` 或 `counts=1` 的请求会把它移出这一页和所有总数,只有不带这些参数的完整列表才返回它。其余的会话,已归档的无论来源都是 `archived`;`user` 会话为 `active`,`api`、`schedule`、`subagent`、`cli` 会话为 `background`。Trace 开头尚未读过的行不带 `source`,按 `active` 计。
+- 创建时 `source` 只接受 `"cli"`,由 `penguin run` 发送;其他来源只由服务器自己写入,省略时创建 `user` 会话。已停用的 `"benchmark"` 仍然接受,按 `"cli"` 处理。
- `GET /dirs` 省略 `path` 时从主目录开始;显式传入的 `path` 必须是绝对路径。响应为 `{path, parent, entries, platform}`:每个条目带 `kind`(`dir` 或 `file`)与 `mtime`;在 Windows 上,系统隐藏的条目(带隐藏属性,如 `AppData`、`NTUSER.DAT`)另带 `hidden: true`,只写盘符如 `D:` 即视为其根目录 `D:\`。请求主目录并带 `places=1` 时,另附选择器左栏所需的两项:`standardFolders`(桌面、文档、下载、图片,按该机器自己的规则取得——Windows 的已知文件夹、Linux 的 XDG 用户目录;读取失败时省略)与 `locations`(Windows 的各盘符、macOS 的各卷、Linux 的根目录及 `/media`、`/run/media`、`/mnt` 下的挂载点,各带 `kind`,有名称时带 `label`)。服务无权读取的目录返回 `403 dir_permission_denied`,不再按空列表返回;在 macOS 上这通常是用户尚未授予的「文件与文件夹」权限。
- `POST /dirs/access` 是桌面端 Workspace 选择器里的**允许访问**。macOS 只替它认定为读取责任方的应用询问桌面、文稿与下载的访问权限,因此由桌面 shell 的主进程把绝对路径 `path` 读一次,响应要等用户作答后才返回。`granted` 表示这次读取是否成功(非 macOS 平台不读取,恒为 `true`)。`packaged` 为 `false` 表示这是从终端启动的开发实例,macOS 把它的读取记在该终端名下。`path` 不是绝对路径时返回 `400` `dir_not_absolute`;服务器没有可询问的桌面 shell 时返回 `503` `shell_unreachable`;shell 在 120 秒内没有应答时返回 `504` `timeout`。只有桌面应用自己的窗口可以调用,其他会话返回 `403` `desktop_shell_only`。
- `GET /dir-skills` 只读取绝对路径下的 `<path>/.agents/skills` 和 `<path>/.claude/skills`,响应为 `{path, skills}`。没有 Skill 的目录返回空列表。参见 [Agent](#agent) 一节中的 `POST /agents`。
@@ -685,7 +686,7 @@ Benchmark 属于 Project,不属于某个 Agent:一个 Benchmark 可以评估
- `GET /usage/errors` 接受 `offset`、`limit`、同样的 `from` / `to` / `fromTs` / `toTs` / `agentId` 过滤条件,以及可选的 `kind`(`unexpected` 或 `expected`)。
- 错误表把同一天里来源、错误码、分类和消息都相同的记录合为一行,带上次数 `count`、最近一次的时间 `ts` 和首次的时间 `firstTs`。`offset`、`limit` 和 `rows` 按行计;`total` 和仪表盘的汇总数字按记录计。`GET /usage` 与 `GET /usage/errors` 都接受可选的 `utcOffsetMinutes`,即读者所在时区相对 UTC 向东的分钟数(−840 到 840),它决定「同一天」按哪一天算;不传时按服务器自己的日期。
- `DELETE /usage/errors` 接受与读取相同的过滤条件(`from` / `to` / `fromTs` / `toTs` / `agentId`),但不接受 `kind`,因为面板上没有这个控件。这里 `from` 和 `to` 都必填(否则返回 400),因为少一个边界,清空的就是整段历史,而不是过滤后的一部分。清空的范围与调用者读取的范围完全一致:管理员清空时,也会删掉只有管理员读取才能看到的未归属行;成员清空时则永远不会。
-- `GET /agents/:agentId/traces` 还接受 `limit` 和 `offset` 分页,以及 `category`(必须搭配 `limit`),用于只列出某一类别的 Session。
+- `GET /agents/:agentId/traces` 还接受 `limit` 和 `offset` 分页,以及 `category`(必须搭配 `limit`),用于只列出某一类别的 Session。分页列表不含不属于任何类别的 `company` 会话;不带 `limit` 的完整目录列出所有 Trace。
- 任何成员都可以下载 Trace。导入只有所有者能做,与 Agent State 快照导入一样,上限 14MB。导入的文件必须是有效的 Trace JSONL,首条记录必须是 `session_meta`,`session_id` 须可安全用作文件名。session id 与 Agent 已有的重复时拒绝导入(409 `trace_session_exists`),所以导入的文件总是成为新 Session 的 index 001,按首条记录的时间戳存入对应的本地日期目录。
## Session 级端点
@@ -1113,7 +1114,7 @@ export type ServerEvent =
| { type: "credentials_updated" }
| { type: "hello" }
| { type: "web_updated"; rev: string }
- | { type: "session_created"; projectId: string; agentId: string; sessionId: string; source?: SessionSource }
+ | { type: "session_created"; projectId: string; agentId: string; sessionId: string; source: SessionSource }
| { type: "schedule_fired"; projectId: string; agentId: string; name: string; sessionId: string }
| { type: "schedule_queued"; projectId: string; agentId: string; name: string; sessionId: string }
| { type: "goal_started"; sessionId: string; objective: string; budget: number }
@@ -1154,7 +1155,7 @@ export type ServerEvent =
- 以下情况会触发 `session_background`:命令超过让出窗口转入后台,或以 `run_in_background` 启动;进程退出或停止;后台子 Agent 开始一轮、结束一轮或释放。事件携带 `SessionInfo.backgroundTasks` 的当前值(`processes` = 仍在运行的后台命令会话数,`subagents` = 已转入后台、正处于一轮中的子 Agent Session 数),归零时同样发送,列表无需重新拉取就能撤下标记。两个计数都为零时,列表行和单个 Session 的 GET 会省略这个字段。受众与 `session_state` 相同。
- `credentials_updated` 在 `PUT /models` 或签发 API key 的流程完成之后发送。缓存的运行时已失效,客户端应清除因认证失败而禁用的输入框状态。
- `web_updated` 以 `rev` 携带新的 web 修订号,发送到每个用户通道。
-- `session_created` 在每次创建时发送到 Project 所有者和成员的用户通道;子 Agent Session 还会同时发送到父 Session 的通道。用户创建的 Session 没有 `source`,与行上一致。通过 `PATCH /api/sessions/:id` 设置的标题以同样方式作为 `session_title` 宣告。
+- `session_created` 在每次创建时发送到 Project 所有者和成员的用户通道;子 Agent Session 还会同时发送到父 Session 的通道。`source` 是新 Session 的 `session_meta` 所记录的来源。通过 `PATCH /api/sessions/:id` 设置的标题以同样方式作为 `session_title` 宣告。
- `schedule_fired` 的 `sessionId` 是接收 Prompt 的 Session,在新建 Session 模式下是一个新 Session。排队的触发会在 Session 空闲后发送。
- `goal_round` 携带 `used`,即目前累计的 Token 数。
- `org_*` 事件发送到 Project 成员的用户通道。`org_channel` 包含消息里的提及信息,客户端可据此判断消息是否指向自己。这些事件是尽力而为的;持久状态以组织路由为准。
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 712c38e7..090151f8 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -16,6 +16,7 @@
import type {
CompactionMode,
OmniMessage,
+ SessionSource,
ToolCallPayload,
} from "@lmliheng/penguin-core/omnimessage";
import type {
@@ -43,8 +44,11 @@ export type ApprovalMode = "allow-all" | "deny-all" | "read-only" | "always-ask"
/** Session run status: idle / Task in progress / compacting. */
export type SessionStatus = "idle" | "running" | "compacting";
-/** Session source marker (default = user-created): triggered by Schedule / registered as a subagent session / a Benchmark evaluation's Test Session, created by `penguin run --source benchmark`. */
-export type SessionSource = "schedule" | "subagent" | "benchmark";
+/**
+ * What kind of conversation a Session is (`user` / `api` / `schedule` / `subagent` / `cli`):
+ * core's type, the one definition, re-exported for the DTOs below.
+ */
+export type { SessionSource };
// ---------------------------------------------------------------------------
// Authentication and users
@@ -1716,7 +1720,16 @@ export interface SessionInfo {
thinkingLevel?: ThinkingLevelName;
/** Short title auto-generated by the model after the first turn; unset until generated (frontend shows "New Chat"). */
title?: string;
- /** Session source (for list badges/folders), derived from core session_meta — the single source of truth (not stored in the DB); unset for user-created sessions. */
+ /**
+ * What kind of conversation this is, read from core session_meta — the single source of
+ * truth (the DB stores no source). A `user` Session is an active row of the sidebar; `api`,
+ * `schedule`, `subagent` and `cli` file the row under its Background folder, marked with its
+ * source; a `company` Session is in no folder of the list at all — company mode's own views
+ * list it. A Trace head that records no source (written before it was required) reads as
+ * `company` for a row the organization runtime opened (`client: "org"`), else as `user`; so
+ * does such a row before its first run. Absent only while any other row is not yet
+ * classified (its Trace head has not been read yet), which renders as `user`.
+ */
source?: SessionSource;
createdAt: string;
/**
@@ -1795,11 +1808,14 @@ export interface SessionBackgroundTasks {
}
/**
- * Session list category, the sidebar's five-way split applied server-side: archived wins
- * regardless of origin (archiving is an explicit user action), then the origin's bucket,
- * and a Session with no (or an unknown) source is `active` — user-created rows.
+ * Session list category, the sidebar's three-way split applied server-side: archived wins
+ * regardless of source (archiving is an explicit user action); otherwise a `user` Session (or
+ * one not yet classified) is `active`, and every other source is `background` — the one
+ * folder that holds what programs opened (API, scheduled, subagent and CLI Sessions). A
+ * `company` Session belongs to none of the three, archived or not: the list leaves it out of
+ * every category and every total.
*/
-export type SessionCategory = "active" | SessionSource | "archived";
+export type SessionCategory = "active" | "background" | "archived";
/** Per-category totals across an Agent's whole Session list (returned when the list is requested with counts). */
export type SessionCategoryCounts = Record<SessionCategory, number>;
@@ -1819,7 +1835,9 @@ export type SessionCategoryCounts = Record<SessionCategory, number>;
* `order=activity`, beside `offset`, without `limit`, or when not a parseable stamp and a
* valid id split at the first comma.
* - `category`, `workspaceGroup`, `excludeOrg=1` filter before paging; `counts=1` adds the
- * whole-list totals below, which no cursor or offset narrows.
+ * whole-list totals below, which no cursor or offset narrows. A request with `category`,
+ * `workspaceGroup` or `counts=1` leaves every `company` Session out of the page and the
+ * totals (it is in no category); one with none of them serves every row.
*/
export interface SessionsResponse {
/**
@@ -1945,14 +1963,12 @@ export interface SessionCreateRequest {
*/
client?: "web" | "cli" | "org";
/**
- * Marks the Session as a Test Session of a Benchmark evaluation: the CLI sends it for
- * `penguin run --source benchmark`, which agent-evaluation uses to launch every Test Session.
- * Only this value is accepted from a client: `subagent` and `schedule` are written by the
- * server itself. The Web App files such Sessions into the Evaluations folder of the session
- * list and never sends the field: the conversation the Evaluation Center's Use dialog opens is
- * an ordinary Session.
+ * The Session's source, when it is not a person's conversation: only `cli` is accepted from
+ * a client (`penguin run` sends it); every other source is the server's own to write, and
+ * absent means `user`. The retired `benchmark` is still accepted, as `cli`, until 0.3.0, for
+ * an older CLI or Web App that still sends it.
*/
- source?: "benchmark";
+ source?: "cli";
}
export interface SessionCreateResponse {
@@ -2984,14 +3000,14 @@ export type ServerEvent =
* A Session now exists. On the user channel for every creation — the CLI, another tab,
* a schedule, an agent spawning a child — so the list learns about rows it did not make;
* and on the parent Session's channel for a subagent, so a tab watching the parent run
- * refreshes in place. `source` is absent for a user-created Session, as it is on the row.
+ * refreshes in place. `source` is what the new Session's meta records.
*/
| {
type: "session_created";
projectId: string;
agentId: string;
sessionId: string;
- source?: SessionSource;
+ source: SessionSource;
}
| ScheduleServerEvent
| GoalServerEvent
diff --git a/packages/server/src/db/repos/trace-index.ts b/packages/server/src/db/repos/trace-index.ts
index d48eac5e..d8072f6e 100644
--- a/packages/server/src/db/repos/trace-index.ts
+++ b/packages/server/src/db/repos/trace-index.ts
@@ -3,8 +3,8 @@
* services/trace-index.ts for the cache rules). Pure row access — reconciliation
* policy (mtime gates, head-reads) lives in the service.
*/
-import type { SessionSource } from "../../api/types.js";
-import { asSessionSource } from "../../runtime/session-sources.js";
+import { normalizeSessionSource } from "@lmliheng/penguin-core";
+import type { RecordedSource } from "../../runtime/session-sources.js";
import { Component, Use } from "@lmliheng/penguin-core/kernel";
import type { Db } from "../../hmr/capabilities.js";
import type { TraceIndexStore } from "../../mechanisms/traces.js";
@@ -24,7 +24,12 @@ export interface TraceSessionRow {
sessionId: string;
projectId: string;
agentId: string;
- source: SessionSource | null;
+ /**
+ * The head's session_meta source, narrowed; `null` when the head records none (written before
+ * the source was required; read it with the row's client, `readRecordedSource`). Meaningful
+ * only once `metaRead`.
+ */
+ source: RecordedSource;
workspace: string;
title: string | null;
provider: string | null;
@@ -45,13 +50,15 @@ function mapFile(r: Record<string, unknown>): TraceFileRow {
}
function mapSession(r: Record<string, unknown>): TraceSessionRow {
- const source = r.source as string | null;
return {
sessionId: r.session_id as string,
projectId: r.project_id as string,
agentId: r.agent_id as string,
- // Narrowed on read as well as write: junk in a hand-edited DB must not leak out as a source.
- source: asSessionSource(source) ?? null,
+ // Narrowed on read as well as write: a row registered before the source was required holds
+ // `benchmark` (read as `cli`) or NULL, which is what a head without a source registers as,
+ // and junk in a hand-edited DB must not leak out as a source. The cache is derived, so old
+ // rows are read, never migrated.
+ source: r.source === null || r.source === undefined ? null : normalizeSessionSource(r.source),
workspace: (r.workspace as string | null) ?? "",
title: (r.title as string | null) ?? null,
provider: (r.provider as string | null) ?? null,
diff --git a/packages/server/src/db/schema.ts b/packages/server/src/db/schema.ts
index b9a0068e..b838b93e 100644
--- a/packages/server/src/db/schema.ts
+++ b/packages/server/src/db/schema.ts
@@ -94,7 +94,7 @@ CREATE TABLE IF NOT EXISTS sessions (
sandbox TEXT, -- the Session's sandbox policy snapshot (JSON SandboxSettings); NULL = legacy row, snapshotted at its next command
last_active_at TEXT, -- last activity this server drove for the session (ISO; stamped once when a run starts and once when it ends, initialized to created_at); monotonic, never moves backwards; NULL only before openDatabase's one-time backfill
created_at TEXT NOT NULL
-); -- the subagent/schedule/benchmark SOURCE is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); "client" is a different, DB-only axis (who created the row)
+); -- the Session's SOURCE (user/api/schedule/subagent/cli/company) is NOT stored: session_meta in the Trace is the single source of truth (see runtime/session-sources.ts); "client" is a different, DB-only axis (who created the row), read for the source only where the Trace records none ('org' → company)
CREATE INDEX IF NOT EXISTS idx_sessions_agent_created ON sessions(project_id, agent_id, created_at DESC);
CREATE TABLE IF NOT EXISTS usage_records (
id INTEGER PRIMARY KEY AUTOINCREMENT,
@@ -202,7 +202,7 @@ CREATE TABLE IF NOT EXISTS trace_sessions ( -- per-session facts read ONCE at
session_id TEXT PRIMARY KEY,
project_id TEXT NOT NULL,
agent_id TEXT NOT NULL,
- source TEXT, -- session_meta origin: 'subagent' | 'schedule' | 'benchmark' | NULL = user-created (or head not yet readable)
+ source TEXT, -- session_meta source as the head carried it: 'user' | 'api' | 'schedule' | 'subagent' | 'cli' | 'company'; NULL = the head records none (written before the source was required: read as 'company' for an 'org' row, else 'user' — readRecordedSource); 'benchmark' from older rows reads as 'cli' (normalizeSessionSource; meaningless while meta_read = 0)
workspace TEXT NOT NULL DEFAULT '',
title TEXT, -- first-prompt fallback title (sessions.title always wins when present)
provider TEXT, -- model reference from session_meta: the model the Session was created on (CLI adoption reads it from here, and the runtime's own answer corrects the row at load; NULL = meta unreadable / legacy without provider)
diff --git a/packages/server/src/http/routes/agent-traces.ts b/packages/server/src/http/routes/agent-traces.ts
index 9da4a318..a7a90038 100644
--- a/packages/server/src/http/routes/agent-traces.ts
+++ b/packages/server/src/http/routes/agent-traces.ts
@@ -8,7 +8,8 @@
* given), stat-ing only the returned page for fresh sizes, and resolves per group a
* display title (sessions DB title, else the registration-time first-prompt
* fallback) plus its sidebar category / Workspace and per-category totals. Every
- * Session is listed whichever client created it.
+ * Session is listed whichever client created it, but a company Session, which no category
+ * holds (company mode's own views list it).
* The listing consults the sessions table read-only (titles, archived, workspace,
* client); discovery itself still comes from the Trace directory tree via the index.
* - GET /api/projects/:p/agents/:a/traces/:sessionId/:index (including /analysis, /download) —
@@ -48,13 +49,7 @@ export interface AgentTracesRouteDeps {
const MAX_TRACE_BYTES = 14 * 1024 * 1024;
/** Accepted `category` query values of the paginated listing (SessionCategory, spelled out for validation — same as the sessions list route). */
-const SESSION_CATEGORIES: readonly SessionCategory[] = [
- "active",
- "subagent",
- "schedule",
- "benchmark",
- "archived",
-];
+const SESSION_CATEGORIES: readonly SessionCategory[] = ["active", "background", "archived"];
export function agentTracesRoutes(deps: AgentTracesRouteDeps): Hono<AppEnv> {
const app = new Hono<AppEnv>();
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index 849ffc4f..fcedf6a5 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -283,13 +283,7 @@ async function sessionCompactionThreshold(
}
/** Accepted `category` query values of the list endpoint (SessionCategory, spelled out for validation). */
-const SESSION_CATEGORIES: readonly SessionCategory[] = [
- "active",
- "subagent",
- "schedule",
- "benchmark",
- "archived",
-];
+const SESSION_CATEGORIES: readonly SessionCategory[] = ["active", "background", "archived"];
/** Accepted `order` query values of the list endpoint (SessionListOrder, spelled out for validation). */
const SESSION_LIST_ORDERS: readonly SessionListOrder[] = ["created", "activity"];
@@ -526,7 +520,8 @@ export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
// Serves every row straight from the DB, whichever client created it (legacy CLI-direct
// Traces were adopted by the boot sweep; see SessionService.listSessions) — unless the
- // caller asks for the user's own rows only (`excludeOrg=1`, development mode's list).
+ // caller asks for the user's own rows only (`excludeOrg=1`, development mode's list) or for
+ // a category, a Workspace group or counts, none of which holds a company Session.
app.get("/", async (c) => {
// Id validity is checked before any path is constructed: guards against agentId path traversal across Projects.
const projectId = requireValidId(c, "projectId");
@@ -602,12 +597,18 @@ export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
}
const approvalMode = optionalEnum(body, "approvalMode", APPROVAL_MODES);
const sandbox = parseSandboxPick(body);
- // Creating-client hint stored on the row ("cli" from the CLI; default "web").
- // Informational provenance only — lists serve every row regardless.
+ // Creating-client hint stored on the row ("cli" from the CLI; default "web"). Provenance:
+ // only "org", which no request may send, is ever read back as a filter.
const client = optionalEnum(body, "client", ["web", "cli"] as const);
- // The only origin a client may set: `subagent` and `schedule` are written by the server
- // itself, so anything but `benchmark` is a 400 rather than a silently ignored field.
- const source = optionalEnum(body, "source", ["benchmark"] as const);
+ // The one source a client may name is `cli` (`penguin run`): every other one is the
+ // server's own to write, and absent means `user`, so anything else is a 400 rather than a
+ // silently ignored field. compat(0.3.0): the retired `benchmark` is accepted as `cli`, for
+ // an older CLI or Web App that still sends it.
+ const source = optionalEnum(
+ { source: body.source === "benchmark" ? "cli" : body.source },
+ "source",
+ ["cli"] as const,
+ );
let workspace = optionalString(body, "workspace", { minLen: 1, label: "workspace" });
if (workspace !== undefined) {
// An explicitly specified Workspace must be an existing directory (never auto-created); reachability is determined by file permissions.
@@ -806,7 +807,8 @@ export function sessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
};
try {
const insertedForkRow = deps.sessionsRepo.insertFork(row.sessionId, forkRow);
- deps.sessionSources.set(fork.sessionId, null);
+ // A fork is a person's conversation, as its Trace head records.
+ deps.sessionSources.set(fork.sessionId, "user");
return c.json(
{
session: await deps.sessionService.toInfo(insertedForkRow, true),
diff --git a/packages/server/src/mechanisms/sessions.ts b/packages/server/src/mechanisms/sessions.ts
index 83e742ea..c4a83008 100644
--- a/packages/server/src/mechanisms/sessions.ts
+++ b/packages/server/src/mechanisms/sessions.ts
@@ -40,6 +40,7 @@ export abstract class SessionIndex {
/** SessionOrigins: the mechanism SessionSources implements. */
@Interface()
export abstract class SessionOrigins {
+ /** `null`: the Session's Trace head records no source (written before it was required). */
abstract set(sessionId: string, source: SessionSource | null): void;
abstract get(sessionId: string): SessionSource | null | undefined;
abstract delete(sessionId: string): void;
diff --git a/packages/server/src/runtime/organization/deps.ts b/packages/server/src/runtime/organization/deps.ts
index 8b1b839b..b8191edc 100644
--- a/packages/server/src/runtime/organization/deps.ts
+++ b/packages/server/src/runtime/organization/deps.ts
@@ -58,6 +58,12 @@ export interface OrgSessionCreator {
* forget it.
*/
client: "org";
+ /**
+ * Always "company": what kind of conversation a desk or ticket session is, recorded in its
+ * session_meta. It keeps the Session out of every category of the session list, so it is
+ * listed only in company mode's own views. Required for the same reason as `client`.
+ */
+ source: "company";
}): Promise<{ sessionId: string; workspace: string }>;
}
diff --git a/packages/server/src/runtime/organization/triggers.ts b/packages/server/src/runtime/organization/triggers.ts
index aceac91c..3f34b574 100644
--- a/packages/server/src/runtime/organization/triggers.ts
+++ b/packages/server/src/runtime/organization/triggers.ts
@@ -5,9 +5,11 @@
* is the single way a desk session comes into being — the hire opens one, the reconcile
* pass provisions the ones that are missing, a trigger falls back on it, and it renews a
* desk when the CEO reassigns a workspace; ticket sessions are opened per start. Both are
- * stamped `client: "org"` at creation — the durable marker development mode's list reads to
- * leave them out of it — and take the organization's approval mode of that moment; a later
- * change of the mode reaches them through `syncApprovalMode` (reconcile.ts).
+ * company Sessions — `source: "company"` in their session_meta, which keeps them out of every
+ * category of the session list — stamped `client: "org"` at creation — the durable marker
+ * development mode's list reads to leave them and what they spawn out of it — and take the
+ * organization's approval mode of that moment; a later change of the mode reaches them
+ * through `syncApprovalMode` (reconcile.ts).
*/
import { buildOrgTriggerMessage, userText } from "@lmliheng/penguin-core";
import type { OrgTriggerOrigin } from "@lmliheng/penguin-core";
@@ -95,6 +97,7 @@ export async function ensureDesk(
...(model !== undefined ? { modelId: model.modelId, provider: model.provider } : {}),
approvalMode: org.config.approvalMode,
client: "org",
+ source: "company",
});
} catch (err) {
return {
@@ -246,6 +249,7 @@ export async function openTicketSession(
...(model !== undefined ? { modelId: model.modelId, provider: model.provider } : {}),
approvalMode: org.config.approvalMode,
client: "org",
+ source: "company",
});
} catch (err) {
return { ok: false, error: err instanceof Error ? err.message : String(err) };
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index 1e3b2a72..b71e40d5 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -43,6 +43,7 @@ import {
isHookInput,
isSessionMeta,
ModelSwitchRefusedError,
+ normalizeSessionSource,
parseUserSteeringText,
tracesDir,
userText,
@@ -84,7 +85,7 @@ import type { PendingApproval } from "./approvals.js";
import type { ChannelHub } from "./channel.js";
import type { ErrorSink } from "./error-recorder.js";
import { LiveTailTracker } from "./live-tail.js";
-import { asSessionSource } from "./session-sources.js";
+import { unrunSource } from "./session-sources.js";
import { StreamErrorWatcher } from "./stream-error-watcher.js";
import type { TitleNotifier } from "./title-generator.js";
import type { UsageContext } from "./usage-recorder.js";
@@ -373,15 +374,17 @@ export function createCoreSessionLoader(
`This Session's Workspace no longer exists: ${row.workspace}, so it cannot continue. Create a new Session.`,
);
}
- const knownSource = sources?.get(row.sessionId);
+ // The source this process recorded at creation, else the one the row stands for: the
+ // organization runtime's are `company` (unrunSource), the list's reading of the same row.
+ const knownSource = sources?.get(row.sessionId) ?? unrunSource(row.client);
try {
return await agent.createSession({
workspaceDir: row.workspace,
modelId: row.modelId,
provider: row.provider,
- // The rebuilt Session re-records a known origin in its fresh session_meta, and
- // starts its first context at the row's pinned level.
- ...(knownSource != null ? { source: knownSource } : {}),
+ // The rebuilt Session records that source in its fresh session_meta (an unknown one
+ // is core's default, `user`), and starts its first context at the row's pinned level.
+ ...(knownSource !== undefined ? { source: knownSource } : {}),
...(row.thinkingLevel ? { thinkingLevel: row.thinkingLevel } : {}),
});
} catch (err) {
@@ -2300,11 +2303,11 @@ export class SessionManager {
const p = msg.payload as SessionMetaPayload;
const agentId = path.basename(path.dirname(p.agent_state));
if (!agentId || agentId === "." || agentId === "..") return null;
- // The forwarded session_meta records the origin at the source (core's spawn site); fall
- // back to inferring "subagent" from the registration path for older metas (narrowed —
- // a junk value also falls back). It goes into the in-process registry only — the index
- // row deliberately stores no source column.
- const source = asSessionSource(p.source) ?? "subagent";
+ // The forwarded session_meta records the source where it is decided (core's spawn site
+ // writes `subagent`); it is narrowed like any meta read back, so the registry holds what
+ // the child's Trace head will answer after a restart. It goes into the in-process registry
+ // only — the index row deliberately stores no source column.
+ const source = normalizeSessionSource(p.source);
this.deps.sources.set(childSid, source);
const root = this.rootSessionOf(entry.sessionId);
this.childRoots.set(childSid, root);
diff --git a/packages/server/src/runtime/session-sources.ts b/packages/server/src/runtime/session-sources.ts
index ca2cc0a7..f6b92ccf 100644
--- a/packages/server/src/runtime/session-sources.ts
+++ b/packages/server/src/runtime/session-sources.ts
@@ -1,39 +1,89 @@
/**
- * In-process registry of Session origins, derived from core `session_meta` — the single
- * source of truth for a Session's origin (the DB stores no `source` column).
+ * In-process registry of Session sources, derived from core `session_meta` — the single
+ * source of truth for what kind of conversation a Session is (the DB stores no `source`
+ * column).
*
* Populated wherever the server actually has the meta in hand: Session creation
* (SessionService reads the just-created core Session's meta), subagent registration
- * (SessionManager reads the forwarded child meta), and Trace adoption / lazy list
- * resolution (SessionService reads the Trace head's session_meta). `null` records a
- * **known** user-created Session (meta seen, no source) so the Trace is not re-read on
- * every list; an absent entry means "unknown" and the list path resolves it from the
- * Trace once per process lifetime.
+ * (SessionManager reads the forwarded child meta), forks (always `user`), and Trace adoption /
+ * lazy list resolution (the trace index's head read). A value read back from a Trace is
+ * narrowed through core's `normalizeSessionSource` (the retired `benchmark` reads as `cli`),
+ * except that a head recording no source is kept as `null`: what it reads as depends on the
+ * Session's index row (`readRecordedSource`), which a head read does not have. An absent entry
+ * means "unknown": the list path resolves it from the Trace once per process lifetime.
*/
-import type { SessionSource } from "../api/types.js";
+import type { SessionCategory, SessionSource } from "../api/types.js";
+import type { SessionRow } from "../db/repos/sessions.js";
import { Component } from "@lmliheng/penguin-core/kernel";
import type { SessionOrigins } from "../mechanisms/sessions.js";
/**
- * Narrows an untrusted value (on-disk Trace JSON / forwarded meta) to a SessionSource:
- * only the exact known origins pass; anything else — including junk written by third
- * parties — is treated as absent rather than cast through.
+ * What a Session's Trace head records as its source: one of the sources, or `null` for a head
+ * written before the source was required, which records none.
*/
-export function asSessionSource(v: unknown): SessionSource | undefined {
- return v === "schedule" || v === "subagent" || v === "benchmark" ? v : undefined;
+export type RecordedSource = SessionSource | null;
+
+/**
+ * A Session's source, from what its Trace head records and the client its index row names.
+ * A recorded source is the answer. A head that records none was written before the source was
+ * required, when company mode's desk and ticket Sessions recorded none either; the organization
+ * runtime stamps those rows `client = "org"`, so such a row reads as `company`, and every other
+ * one as `user`, the reading core's `normalizeSessionSource` gives a missing source.
+ */
+export function readRecordedSource(
+ recorded: RecordedSource,
+ client: SessionRow["client"],
+): SessionSource {
+ if (recorded !== null) return recorded;
+ // compat(0.3.0): a head from before the source was required. It goes with core's missing →
+ // `user` branch (see normalizeSessionSource), and a one-time rewrite of old heads, if that is
+ // what replaces it, writes `company` for these rows.
+ return client === "org" ? "company" : "user";
+}
+
+/**
+ * The source of a Session that has not run yet, read from its index row. Its session_meta is
+ * written by its first run, so once the process that created it is gone nothing on disk names
+ * its source. The organization runtime opens only company Sessions under its `org` client (a
+ * desk opened at a hire can wait days for its first run; the children its Sessions spawn run,
+ * and so record their own source, at once), so such a row is `company`, and the loader rebuilds
+ * it as one. Any other row stays unclassified until its first run records a source.
+ */
+export function unrunSource(client: SessionRow["client"]): SessionSource | undefined {
+ return client === "org" ? "company" : undefined;
+}
+
+/**
+ * The list category of a Session: none for a `company` Session, which only company mode's
+ * own views list (an employee's desk, a ticket's sessions), whether archived or not; otherwise
+ * archived first, then a person's conversation (`user`, or a row not yet classified) is
+ * `active` and every other source — API, scheduled, subagent and CLI Sessions — `background`.
+ * The Web App's sidebar applies the same rule to loaded rows (`sessionCategory`), so server
+ * filtering and client rendering never disagree.
+ */
+export function listCategory(
+ source: SessionSource | undefined,
+ archived: boolean,
+): SessionCategory | null {
+ if (source === "company") return null;
+ if (archived) return "archived";
+ return source === undefined || source === "user" ? "active" : "background";
}
@Component()
export class SessionSources implements SessionOrigins {
- private readonly map = new Map<string, SessionSource | null>();
+ private readonly map = new Map<string, RecordedSource>();
- /** Records a Session's origin as read from session_meta (`null` = meta seen, user-created). */
- set(sessionId: string, source: SessionSource | null): void {
+ /** Records a Session's source as read from session_meta (`null`: a head that records none). */
+ set(sessionId: string, source: RecordedSource): void {
this.map.set(sessionId, source);
}
- /** Known origin, `null` for a known user-created Session, `undefined` when this process has not seen the meta. */
- get(sessionId: string): SessionSource | null | undefined {
+ /**
+ * What the Session's meta records: a source, `null` for a head that records none (read it
+ * through `readRecordedSource`), `undefined` when this process has not seen the meta.
+ */
+ get(sessionId: string): RecordedSource | undefined {
return this.map.get(sessionId);
}
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index 87a4b0ac..6d62dca9 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -14,7 +14,12 @@
* added to session-manager's active table (state idle).
*/
import fs from "node:fs/promises";
-import { agentsDir, createAgent, isSessionMeta } from "@lmliheng/penguin-core";
+import {
+ agentsDir,
+ createAgent,
+ isSessionMeta,
+ normalizeSessionSource,
+} from "@lmliheng/penguin-core";
import type {
AgentAssembly,
ControlEnvContext,
@@ -37,7 +42,7 @@ import { HttpError, isMissingCredential, modelCredentialMissing } from "../http/
import { badRequest } from "../http/validate.js";
import type { SessionRow } from "../db/repos/sessions.js";
import type { SessionManager } from "../runtime/session-manager.js";
-import { asSessionSource } from "../runtime/session-sources.js";
+import { listCategory, readRecordedSource, unrunSource } from "../runtime/session-sources.js";
import { TraceIndexService, traceFilePath } from "./trace-index.js";
import { matchesWorkspaceGroup } from "./workspace-group.js";
import type { TraceIndex, TraceIndexStore } from "../mechanisms/traces.js";
@@ -392,22 +397,23 @@ export class SessionService {
}
/**
- * A Session's origin, with session_meta as the single source of truth: the in-process
- * registry answers first (populated at creation / subagent registration / adoption /
+ * A Session's source, with session_meta as the single source of truth: the in-process
+ * registry answers first (populated at creation / subagent registration / forks / adoption /
* index registration); on a miss (a Session created before this process started) the
* trace index's registration-time facts answer — the reconciler head-read the earliest
- * shard once when the file first appeared, so no file is touched here. A Session with
- * no Trace yet stays unknown and is NOT cached negatively — its meta may appear with
- * the first run.
+ * shard once when the file first appeared, so no file is touched here. A head that records
+ * no source is read with the row's client (readRecordedSource). A Session with no Trace yet
+ * is NOT cached — its meta appears with the first run — and reads as its row says
+ * (unrunSource): the organization runtime's as `company`, any other as unknown.
*/
private async sourceOf(row: SessionRow, hasTrace: boolean): Promise<SessionSource | undefined> {
const known = this.deps.sources.get(row.sessionId);
- if (known !== undefined) return known ?? undefined;
- if (!hasTrace) return undefined;
+ if (known !== undefined) return readRecordedSource(known, row.client);
+ if (!hasTrace) return unrunSource(row.client);
const facts = this.deps.traceStore.getSession(row.sessionId);
if (!facts?.metaRead) return undefined; // Unreadable/unregistered: stay unknown, retry on the next list.
this.deps.sources.set(row.sessionId, facts.source);
- return facts.source ?? undefined;
+ return readRecordedSource(facts.source, row.client);
}
/** Whether this Session already has a Trace record (a Task has been run): answered by the index (reconciled first). */
@@ -416,14 +422,12 @@ export class SessionService {
}
/**
- * The list category of a row: archived wins (an explicit user action), then the
- * origin's bucket, and no/unknown source is `active` — the same precedence the
- * sidebar's partition applies to loaded rows, so server filtering and client
- * rendering can never disagree.
+ * The list category of a row (see listCategory): none for a `company` Session, archived or
+ * not, which the list never serves; otherwise archived wins (an explicit user action), then
+ * its source's.
*/
- private async categoryOf(row: SessionRow, hasTrace: boolean): Promise<SessionCategory> {
- if ((row.archivedAt ?? null) !== null) return "archived";
- return (await this.sourceOf(row, hasTrace)) ?? "active";
+ private async categoryOf(row: SessionRow, hasTrace: boolean): Promise<SessionCategory | null> {
+ return listCategory(await this.sourceOf(row, hasTrace), (row.archivedAt ?? null) !== null);
}
/**
@@ -464,13 +468,22 @@ export class SessionService {
* its siblings were about to read, and their rows move on screen untouched. The two
* filters compose; the returned counts stay whole-Agent either way.
*
+ * A `company` Session — company mode's desk and ticket Sessions, which only company mode's
+ * own views list — belongs to no category (listCategory), archived or not: every classified
+ * form of the list (`category`, `workspaceGroup` or `withCounts`) leaves it out of the page,
+ * the totals, the Workspace breakdown and its stamps alike. The plain form, which classifies
+ * nothing, still serves every row.
+ *
* `excludeOrg` drops the rows an organization owns (its desk and ticket sessions, and the
* sub-sessions they spawned) from the stream BEFORE anything else looks at it — the page,
* `counts`, `workspaceCounts`, `workspaceLatest` and the limit+1 "has more" all describe the
* same own-rows stream. It is what development mode's list asks for: that list draws the
* user's own conversations, and a total or a stamp that still counted a desk or a ticket
- * session would make its Workspace appear as a group the list can never fill. Without the
- * flag every row is served, whichever client created it.
+ * session would make its Workspace appear as a group the list can never fill. The `company`
+ * rule above does not replace it: the sub-sessions are `subagent` Sessions, a person's
+ * conversation attached to a ticket is stamped `org` but stays `user`, and a row the
+ * organization caches name before the reconcile pass stamps it reads as `user`. Without the
+ * flag every row is served, whichever client created it, but for that rule.
*/
async listSessions(
projectId: string,
@@ -544,13 +557,7 @@ export class SessionService {
}
const want = paging ? skip + paging.limit : Infinity;
- const counts: SessionCategoryCounts = {
- active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- };
+ const counts: SessionCategoryCounts = { active: 0, background: 0, archived: 0 };
const workspaceCounts: Record<string, SessionCategoryCounts> = {};
const workspaceLatest: Record<string, string> = {};
const matched: SessionRow[] = [];
@@ -561,15 +568,12 @@ export class SessionService {
if (!servable && !withCounts) continue;
if (!withCounts && matched.length >= want) break;
const cat = await this.categoryOf(row, rowHasTrace(row));
+ // A company Session is in no category: neither served nor counted, nor stamped on its
+ // Workspace, so no total describes a row the list cannot serve.
+ if (cat === null) continue;
counts[cat] += 1;
if (withCounts) {
- const ws = (workspaceCounts[row.workspace] ??= {
- active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
+ const ws = (workspaceCounts[row.workspace] ??= { active: 0, background: 0, archived: 0 });
ws[cat] += 1;
// A path's newest Session by creation, whichever order the walk is in.
const latest = workspaceLatest[row.workspace];
@@ -654,11 +658,11 @@ export class SessionService {
/** Whether the creator is an administrator (may loosen past the settings). Default false. */
isAdmin?: boolean;
/**
- * Session source marker: `schedule` when triggered by a scheduled task, `benchmark` for a
- * Test Session of a Benchmark evaluation, which `penguin run --source benchmark` creates
- * (the only value a client may send); defaults to user-created.
+ * What kind of conversation this is, recorded in the Session's session_meta: `schedule`
+ * from the scheduler, `company` from the organization runtime, `cli` from `penguin run`
+ * (the only source a request may name); absent means `user`, a person's conversation.
*/
- source?: "schedule" | "benchmark";
+ source?: SessionSource;
/**
* Creating-client hint stored on the index row (`POST .../sessions` body `client`):
* "cli" from the CLI, defaulting to "web". "org" is not accepted over HTTP — the
@@ -708,7 +712,7 @@ export class SessionService {
modelId,
provider,
...(args.workspace !== undefined ? { workspaceDir: args.workspace } : {}),
- // The origin is also recorded in core session_meta (Trace), not just the index row.
+ // The source is recorded in core session_meta (Trace); the index row stores none.
...(args.source !== undefined ? { source: args.source } : {}),
});
} catch (err) {
@@ -722,14 +726,14 @@ export class SessionService {
err instanceof Error ? err.message : String(err),
);
}
- // The origin is derived from the just-created core Session's session_meta (the single
+ // The source is read from the just-created core Session's session_meta (the single
// source of truth) rather than echoing args.source back: what the registry serves is
// exactly what the Trace will record.
const metaMsg = session.metaMessage;
- this.deps.sources.set(
- session.sessionId,
- isSessionMeta(metaMsg) ? (asSessionSource(metaMsg.payload.source) ?? null) : null,
+ const source = normalizeSessionSource(
+ isSessionMeta(metaMsg) ? metaMsg.payload.source : undefined,
);
+ this.deps.sources.set(session.sessionId, source);
const createdAt = new Date().toISOString();
const row: SessionRow = {
sessionId: session.sessionId,
@@ -752,13 +756,12 @@ export class SessionService {
this.deps.sessions.insert(row);
this.deps.manager.adopt(row, session);
// After the insert: a reader who reacts by fetching the list must find the row there.
- const source = this.deps.sources.get(session.sessionId);
this.deps.notifyProjectUsers?.(args.projectId, {
type: "session_created",
projectId: args.projectId,
agentId: args.agentId,
sessionId: row.sessionId,
- ...(source ? { source } : {}),
+ source,
});
return this.toInfo(row, false);
}
@@ -860,7 +863,8 @@ export class SessionService {
// (core will give a clear error on resume; the product hasn't launched yet, so
// old data can simply be deleted and recreated).
if (facts.provider === null || facts.modelId === null) return null;
- // Registration already narrowed the origin; record it in the registry (single source of truth).
+ // Registration already narrowed the source (a head without one stays `null`, read with the
+ // row's client); record it in the registry (single source of truth).
this.deps.sources.set(sessionId, facts.source);
const createdAt = sessionIdCreatedAt(sessionId) ?? facts.firstTs ?? new Date().toISOString();
const row: SessionRow = {
diff --git a/packages/server/src/services/trace-index.ts b/packages/server/src/services/trace-index.ts
index fd9d221c..64503391 100644
--- a/packages/server/src/services/trace-index.ts
+++ b/packages/server/src/services/trace-index.ts
@@ -39,13 +39,17 @@
*/
import fs from "node:fs/promises";
import path from "node:path";
-import { agentsDir, isSessionMeta, tracesDir } from "@lmliheng/penguin-core";
+import {
+ agentsDir,
+ isSessionMeta,
+ normalizeSessionSource,
+ tracesDir,
+} from "@lmliheng/penguin-core";
import type { OmniMessage } from "@lmliheng/penguin-core";
import type { TraceFileRow, TraceSessionRow } from "../db/repos/trace-index.js";
import { TraceIndexRepo } from "../db/repos/trace-index.js";
import { cacheable, statMtime } from "../internal/mtime-gate.js";
import { readTraceHead } from "../internal/trace-head.js";
-import { asSessionSource } from "../runtime/session-sources.js";
import { fallbackTitle } from "../runtime/title-generator.js";
import { Component, Use } from "@lmliheng/penguin-core/kernel";
import type { Paths } from "../hmr/capabilities.js";
@@ -99,7 +103,13 @@ function factsFromRecords(
sessionId,
projectId,
agentId,
- source: meta ? (asSessionSource(meta.payload.source) ?? null) : null,
+ // Narrowed (an old head's `benchmark` reads as `cli`), except that a head recording no source
+ // keeps none: what it reads as depends on the Session's index row (readRecordedSource).
+ // Without a meta the value means nothing, and every reader checks metaRead first.
+ source:
+ meta === undefined || meta.payload.source === undefined
+ ? null
+ : normalizeSessionSource(meta.payload.source),
workspace: meta && typeof meta.payload.workspace === "string" ? meta.payload.workspace : "",
title: firstPrompt !== null ? fallbackTitle(firstPrompt) : null,
provider: meta && typeof meta.payload.provider === "string" ? meta.payload.provider : null,
diff --git a/packages/server/src/services/trace-service.ts b/packages/server/src/services/trace-service.ts
index cf4d92f6..65325aca 100644
--- a/packages/server/src/services/trace-service.ts
+++ b/packages/server/src/services/trace-service.ts
@@ -75,6 +75,7 @@ import type {
} from "./message-window.js";
import { buildContextBreakdown, emptyContextBreakdown } from "./context-breakdown.js";
import { sessionIdCreatedAt } from "./session-service.js";
+import { listCategory, readRecordedSource } from "../runtime/session-sources.js";
import { TraceIndexService, traceFilePath } from "./trace-index.js";
import { TraceLineIndex } from "./trace-line-index.js";
import { traceRecordImage, withImagesByReference } from "./trace-images.js";
@@ -809,6 +810,7 @@ export class TraceService implements Traces {
const sourcePrompt = msg.payload.system_prompt;
const sourceVisible = modelVisiblePath(sourceScratchpad);
const forkVisible = modelVisiblePath(forkScratchpad);
+ // A fork is a person's conversation, whatever kind the Session it was cut from was.
const payload = {
...msg.payload,
session_id: newSessionId,
@@ -817,8 +819,8 @@ export class TraceService implements Traces {
.join(newSessionId)
.split(sourceVisible)
.join(forkVisible),
+ source: "user" as const,
};
- delete payload.source;
return { ...msg, payload };
}
const p = msg.payload as { type?: string; role?: string; text?: unknown };
@@ -1637,26 +1639,25 @@ export class TraceService implements Traces {
}
/**
- * Classification (no IO): `archived` comes exactly from the DB row; the origin comes
+ * Classification (no IO): `archived` comes exactly from the DB row; the source comes
* from the shared sources registry, else from the Session's registration-time facts
* (trace_sessions — the reconciler head-read its earliest shard once when the file
- * first appeared, so by listing time every indexed Session is classified exactly).
+ * first appeared, so by listing time every indexed Session is classified exactly), a head
+ * without one read with the row's client. Null for a `company` Session, which is in no
+ * category (listCategory) and so not in this listing.
*/
private classify(
sessionId: string,
row: SessionRow | undefined,
facts: TraceSessionRow | undefined,
- ): TraceSessionFacts {
+ ): TraceSessionFacts | null {
+ // The registry's answer wins — it can be fresher (subagent registration happens at spawn,
+ // before any reconcile); else the stored facts, once their head was read.
const known = this.sources?.get(sessionId);
- // Registry answer (including null = known user-created) wins — it can be fresher
- // (subagent registration happens at spawn, before any reconcile); else the stored facts.
- const source = known !== undefined ? known : (facts?.source ?? undefined);
- const category: SessionCategory =
- (row?.archivedAt ?? null) !== null
- ? "archived"
- : source === "subagent" || source === "schedule" || source === "benchmark"
- ? source
- : "active";
+ const recorded = known !== undefined ? known : facts?.metaRead ? facts.source : undefined;
+ const source = recorded === undefined ? undefined : readRecordedSource(recorded, row?.client);
+ const category = listCategory(source, (row?.archivedAt ?? null) !== null);
+ if (category === null) return null;
return { category, workspace: row?.workspace ?? facts?.workspace ?? "" };
}
@@ -1685,29 +1686,19 @@ export class TraceService implements Traces {
const ids = [...bySession.keys()].sort((a, b) => b.localeCompare(a));
// Classify every group once; the same result drives the category filter, the
// counts AND the returned fields, so a row can never appear in a bucket its own
- // `category` denies. Every Session is listed whichever client created it.
- const counts: SessionCategoryCounts = {
- active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- };
+ // `category` denies. Every Session is listed whichever client created it, but a company
+ // Session, which no category holds.
+ const counts: SessionCategoryCounts = { active: 0, background: 0, archived: 0 };
const workspaceCounts: Record<string, SessionCategoryCounts> = {};
const factsById = new Map<string, TraceSessionFacts>();
const visible: string[] = [];
for (const id of ids) {
const facts = this.classify(id, rows.get(id), factsBySession.get(id));
+ if (facts === null) continue;
factsById.set(id, facts);
visible.push(id);
counts[facts.category] += 1;
- const ws = (workspaceCounts[facts.workspace] ??= {
- active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
+ const ws = (workspaceCounts[facts.workspace] ??= { active: 0, background: 0, archived: 0 });
ws[facts.category] += 1;
}
const filtered =
@@ -1890,7 +1881,7 @@ export class TraceService implements Traces {
if (!sessions) return;
const facts = this.store.getSession(sessionId);
if (!facts?.metaRead || facts.provider === null || facts.modelId === null) return;
- if (facts.source !== null) this.sources?.set(sessionId, facts.source);
+ this.sources?.set(sessionId, facts.source);
const createdAt = sessionIdCreatedAt(sessionId) ?? facts.firstTs ?? new Date().toISOString();
sessions.insertOrIgnore?.({
sessionId,
diff --git a/packages/server/test/agent-trace-detail.test.ts b/packages/server/test/agent-trace-detail.test.ts
index 887a0ebb..29b351b6 100644
--- a/packages/server/test/agent-trace-detail.test.ts
+++ b/packages/server/test/agent-trace-detail.test.ts
@@ -30,6 +30,7 @@ function metaPayload(): SessionMetaPayload {
system_prompt: "",
agent_state: "/tmp/a",
workspace: "/tmp/w",
+ source: "user",
};
}
@@ -117,20 +118,8 @@ describe("agent-trace-detail", () => {
]);
expect(paged.sessions![0]!.category).toBe("active");
expect(paged.sessions![0]!.workspace).toBe("/tmp/w");
- expect(paged.counts).toEqual({
- active: 1,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
- expect(paged.workspaceCounts!["/tmp/w"]).toEqual({
- active: 1,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
+ expect(paged.counts).toEqual({ active: 1, background: 0, archived: 0 });
+ expect(paged.workspaceCounts!["/tmp/w"]).toEqual({ active: 1, background: 0, archived: 0 });
// A sessions-table title (one batched lookup for the page) wins over the fallback.
t.deps.sessionsRepo.insert({
@@ -162,7 +151,7 @@ describe("agent-trace-detail", () => {
// Category filter: pages within one bucket (totalSessions = the bucket's count);
// unknown values and category-without-limit are client errors.
const filtered = (await (
- await owner.get(`${base()}?limit=10&category=subagent`)
+ await owner.get(`${base()}?limit=10&category=background`)
).json()) as AgentTracesResponse;
expect(filtered.sessions).toEqual([]);
expect(filtered.totalSessions).toBe(0);
diff --git a/packages/server/test/context-breakdown.test.ts b/packages/server/test/context-breakdown.test.ts
index c3afeacd..8c9f781f 100644
--- a/packages/server/test/context-breakdown.test.ts
+++ b/packages/server/test/context-breakdown.test.ts
@@ -43,6 +43,7 @@ function metaPayload(systemPrompt: string): SessionMetaPayload {
system_prompt: systemPrompt,
agent_state: `/data/${P}/agents/${A}`,
workspace: "/data/ws",
+ source: "user",
};
}
diff --git a/packages/server/test/errors.test.ts b/packages/server/test/errors.test.ts
index 3945276f..82dd9a43 100644
--- a/packages/server/test/errors.test.ts
+++ b/packages/server/test/errors.test.ts
@@ -477,6 +477,7 @@ describe("stream-error-watcher (LLM / Environment errors)", () => {
system_prompt: "",
agent_state: agentState,
workspace: "/tmp/w",
+ source: "user",
}),
sessionId,
);
diff --git a/packages/server/test/messages-page.test.ts b/packages/server/test/messages-page.test.ts
index 06866dc6..00a436fa 100644
--- a/packages/server/test/messages-page.test.ts
+++ b/packages/server/test/messages-page.test.ts
@@ -70,6 +70,7 @@ function metaPayload(over: Partial<SessionMetaPayload> = {}): SessionMetaPayload
system_prompt: "sp",
agent_state: "/tmp/a",
workspace: "/tmp/w",
+ source: "user",
...over,
};
}
diff --git a/packages/server/test/messages-pending-input.test.ts b/packages/server/test/messages-pending-input.test.ts
index f01ffa3c..ac92172b 100644
--- a/packages/server/test/messages-pending-input.test.ts
+++ b/packages/server/test/messages-pending-input.test.ts
@@ -161,6 +161,7 @@ describe("GET /messages serves the running task's pending inputs", () => {
system_prompt: "test",
agent_state: "/tmp/agent-state",
workspace: "/tmp/w",
+ source: "user",
}),
input,
]);
@@ -200,6 +201,7 @@ describe("GET /messages serves the running task's pending inputs", () => {
system_prompt: "test",
agent_state: "/tmp/agent-state",
workspace: "/tmp/w",
+ source: "user",
}),
...t.deps.manager.pendingInputs(SID),
]);
diff --git a/packages/server/test/organization-runtime.test.ts b/packages/server/test/organization-runtime.test.ts
index 3620a8d4..462c6df9 100644
--- a/packages/server/test/organization-runtime.test.ts
+++ b/packages/server/test/organization-runtime.test.ts
@@ -8,8 +8,9 @@
* paused, held silently when the master switch is off); ticket changes are noticed once;
* channel mentions reach desks and the chain stops at the limit; budgets warn, pause and
* resume (a zero budget being over before anything is spent); a ticket session the runner
- * refuses leaves the ticket as it was; and every pass brings an employee whose company
- * plugins fell behind the library back up to it.
+ * refuses leaves the ticket as it was; every desk and ticket session is opened as a company
+ * Session (`source: "company"`) stamped with the `org` client; and every pass brings an
+ * employee whose company plugins fell behind the library back up to it.
*/
import fs from "node:fs/promises";
import { wire } from "@lmliheng/penguin-core/kernel";
@@ -85,6 +86,7 @@ describe("organization runtime", () => {
modelId?: string;
provider?: string;
client: "org";
+ source: "company";
}>;
let agentsCreated: Array<{ agentId: string; plugins: readonly string[] }>;
let briefs: Map<string, string>;
@@ -188,6 +190,7 @@ describe("organization runtime", () => {
...(args.modelId !== undefined ? { modelId: args.modelId } : {}),
...(args.provider !== undefined ? { provider: args.provider } : {}),
client: args.client,
+ source: args.source,
});
const createdAt = new Date(nowMs).toISOString();
sessions.insert({
@@ -940,10 +943,10 @@ describe("organization runtime", () => {
});
describe("company mode's own sessions", () => {
- it('stamps every desk and ticket session client: "org", and a reconcile pass marks one that is not', async () => {
+ it('opens every desk and ticket session as a company Session stamped client: "org", and a reconcile pass marks one that is not', async () => {
await createOrg();
const ceoDesk = (await service.desk(P, ORG, CEO, {})).sessionId;
- expect(created.at(-1)?.client).toBe("org");
+ expect(created.at(-1)).toMatchObject({ client: "org", source: "company" });
expect(sessions.findById(ceoDesk)?.client).toBe("org");
const t = await service.createTicket(
P,
@@ -958,6 +961,7 @@ describe("organization runtime", () => {
{},
{ userId: "alice" },
);
+ expect(created.at(-1)).toMatchObject({ client: "org", source: "company" });
expect(sessions.findById(work)?.client).toBe("org");
// What an organization that predates the marker looks like: its files still name the
diff --git a/packages/server/test/organizations-routes.test.ts b/packages/server/test/organizations-routes.test.ts
index 18414f6e..4020a5b8 100644
--- a/packages/server/test/organizations-routes.test.ts
+++ b/packages/server/test/organizations-routes.test.ts
@@ -15,19 +15,24 @@
* control environment's API token; a signed-in member's claim is dropped.
* - The sessions route marks a desk whose Session has an enabled messaging binding, read from
* the real bindings table for an organization written straight to disk.
+ * - The sessions route finds an employee's desk and a ticket's session, company Sessions that
+ * the employee's own session list leaves out of every category and total.
*/
import path from "node:path";
import { afterAll, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { sessionMeta, userText } from "@lmliheng/penguin-core";
+import type { SessionSource } from "@lmliheng/penguin-core";
import type {
MeResponse,
OrgSessionsResponse,
ServerSettingsResponse,
SessionResponse,
+ SessionsResponse,
} from "../src/api/types.js";
import { ORG_CONFIG_DEFAULTS } from "../src/organization/files.js";
import { OrgStore } from "../src/organization/store.js";
import type { OrganizationService } from "../src/runtime/organization/service.js";
-import { apiClient, createTestApp, loginAdmin, provisionUser } from "./helpers.js";
+import { apiClient, createTestApp, loginAdmin, provisionUser, writeTraceFile } from "./helpers.js";
import type { TestApp } from "./helpers.js";
type Call = { method: string; args: unknown[] };
@@ -666,4 +671,117 @@ describe("organization sessions route over the real service", () => {
await t.cleanup();
}
});
+
+ it("finds an employee's desk and a ticket's session, which the employee's session list leaves out", async () => {
+ const t = await createTestApp();
+ try {
+ t.deps.serverSettingsRepo.setCompanyMode(true);
+ const u = await provisionUser(t.app, "piper");
+ const api = apiClient(t.app, u.cookie);
+ const projectId = "piper-default_project";
+ const agentId = "acme_ceo";
+ expect((await api.post(`/api/projects/${projectId}/agents`, { agentId })).status).toBe(201);
+ const desk = "session-2026-09-01-09-00-00-0abc0031";
+ const ticketSession = "session-2026-09-02-10-00-00-0abc0032";
+ const own = "session-2026-09-03-11-00-00-0abc0033";
+
+ const store = new OrgStore(t.deps.config.root);
+ const dir = store.dir(projectId, "acme");
+ await store.createLayout(dir);
+ await store.writeConfig(dir, {
+ ...ORG_CONFIG_DEFAULTS,
+ name: "Acme",
+ mission: "Ship the site",
+ timezone: "UTC",
+ createdBy: "piper",
+ });
+ await store.writeChart(dir, {
+ employees: [{ agentId, title: "CEO", reportsTo: null, workspace: "." }],
+ });
+ const workspace = path.join(dir, "workspace");
+ await store.writeDesks(dir, {
+ [agentId]: {
+ sessionId: desk,
+ workspace,
+ openedAt: "2026-09-01T09:00:00.000Z",
+ previous: [],
+ },
+ });
+ await store.writeTicket(dir, "2026-09-02-site", "in_progress", {
+ title: "Launch the site",
+ status: "in_progress",
+ owner: `agent:${agentId}`,
+ notify: [],
+ priority: "P2",
+ sessions: [ticketSession],
+ history: [],
+ goal: "",
+ acceptanceCriteria: "",
+ progress: [],
+ result: "",
+ extra: {},
+ extraSections: [],
+ });
+ // The desk has not run yet (no Trace); the ticket's session ran and recorded `company`;
+ // the person's own conversation recorded `user`.
+ for (const [sessionId, client, source] of [
+ [desk, "org", undefined],
+ [ticketSession, "org", "company"],
+ [own, "web", "user"],
+ ] as const) {
+ const stamp = `${sessionId.slice(8, 18)}T09:00:00.000Z`;
+ t.deps.sessionsRepo.insert({
+ sessionId,
+ projectId,
+ agentId,
+ provider: "custom",
+ modelId: "m-org",
+ workspace,
+ approvalMode: "allow-all",
+ title: null,
+ client,
+ createdAt: stamp,
+ lastActiveAt: stamp,
+ });
+ if (source === undefined) continue;
+ await writeTraceFile(t.root, projectId, agentId, sessionId.slice(8, 18), sessionId, 1, [
+ sessionMeta({
+ session_id: sessionId,
+ model_id: "m-org",
+ provider: "custom",
+ model_context_window: 1000,
+ system_prompt: "",
+ agent_state: "/tmp/a",
+ workspace,
+ source: source satisfies SessionSource,
+ }),
+ userText("work"),
+ ]);
+ }
+
+ const org = (await (
+ await api.get(`/api/projects/${projectId}/organizations/acme/sessions`)
+ ).json()) as OrgSessionsResponse;
+ expect(org.desks.map((d) => d.sessionId)).toEqual([desk]);
+ expect(org.tickets.flatMap((tk) => tk.sessions.map((s) => s.sessionId))).toEqual([
+ ticketSession,
+ ]);
+
+ const list = async (qs: string) =>
+ (await (
+ await api.get(`/api/projects/${projectId}/agents/${agentId}/sessions${qs}`)
+ ).json()) as SessionsResponse;
+ const counted = await list("?category=active&counts=1");
+ expect(counted.sessions.map((s) => s.sessionId)).toEqual([own]);
+ expect(counted.counts).toEqual({ active: 1, background: 0, archived: 0 });
+ expect((await list("?category=background")).sessions).toEqual([]);
+ expect((await list("?category=archived")).sessions).toEqual([]);
+ // Both are company Sessions as the list reads them.
+ const sources = new Map((await list("")).sessions.map((s) => [s.sessionId, s.source]));
+ expect(sources.get(desk)).toBe("company");
+ expect(sources.get(ticketSession)).toBe("company");
+ } finally {
+ await t.cleanup();
+ }
+ });
});
diff --git a/packages/server/test/session-created-events.test.ts b/packages/server/test/session-created-events.test.ts
index 6e7d8639..4b60ae5c 100644
--- a/packages/server/test/session-created-events.test.ts
+++ b/packages/server/test/session-created-events.test.ts
@@ -6,8 +6,8 @@
* `session_state` and `session_title` cannot stand in: both act on a row the list already
* holds. So this event is what makes a Session appear without a reload.
*
- * - A new Session reaches the Project's owner and members with its ids (and no source marker
- * for a user-created one), and nobody else.
+ * - A new Session reaches the Project's owner and members with its ids and its source (`user`
+ * for one a person opens), and nobody else.
* - The event is published after the row is in place, so a reader who reloads on it finds it.
* - A title set by PATCH (the CLI's --title, another tab's rename) is announced to the same
* audience.
@@ -67,7 +67,7 @@ describe("session_created on the user channel", () => {
};
});
- it("reaches the Project's owner and members with the new row's ids, and nobody else", async () => {
+ it("reaches the Project's owner and members with the new row's ids and source, and nobody else", async () => {
const res = (await (
await owner.post(`/api/projects/${projectId}/agents/default_agent/sessions`, {})
).json()) as SessionCreateResponse;
@@ -76,9 +76,14 @@ describe("session_created on the user channel", () => {
for (const who of ["owner", "member"] as const) {
const got = created(boxes[who]);
expect(got, who).toHaveLength(1);
- expect(got[0]).toMatchObject({ projectId, agentId: "default_agent", sessionId });
- // A user-created Session has no source marker, on the row or in the event.
- expect(got[0]).not.toHaveProperty("source");
+ // The event names the Session's source as its meta records it, the same as the row.
+ expect(got[0]).toMatchObject({
+ projectId,
+ agentId: "default_agent",
+ sessionId,
+ source: res.session.source,
+ });
+ expect(res.session.source).toBe("user");
}
expect(created(boxes.stranger)).toHaveLength(0);
});
diff --git a/packages/server/test/session-fork.test.ts b/packages/server/test/session-fork.test.ts
index b17b6d32..24fb406c 100644
--- a/packages/server/test/session-fork.test.ts
+++ b/packages/server/test/session-fork.test.ts
@@ -3,6 +3,8 @@
*
* - A fork copies the history through the selected reply, snapshots the scratchpad, rewrites
* the local attachment markers to its own copy, and outlives the source's deletion.
+ * - A fork is a person's conversation (`user`), whatever kind its source was: a fork of a
+ * `penguin run` (`cli`) Session lists as `user` and its Trace head records `user`.
* - Forks of one source share a persistent number sequence, whatever reply they start from; a
* source with no title forks under a readable numbered fallback.
* - A fork that fails after its row was committed removes the row and the cloned files.
@@ -120,7 +122,7 @@ describe("session fork", () => {
system_prompt: `Session ${SID}; scratchpad ${modelVisiblePath(scratch)}`,
agent_state: path.join(t.root, projectId, "agents", "default_agent", "agent_state"),
workspace,
- source: "schedule",
+ source: "cli",
};
await writeTraceFile(t.root, projectId, "default_agent", "2026-08-14", SID, 1, [
at("2026-08-14T10:00:00.000Z", sessionMeta(meta)),
@@ -176,7 +178,7 @@ describe("session fork", () => {
archived: false,
hasTrace: true,
});
- expect(session.source).toBeUndefined();
+ expect(session.source).toBe("user");
const forked = (await (
await api.get(`/api/sessions/${session.sessionId}/messages`)
@@ -203,6 +205,8 @@ describe("session fork", () => {
expect((forkMeta?.payload as SessionMetaPayload).session_id).toBe(session.sessionId);
expect((forkMeta?.payload as SessionMetaPayload).system_prompt).toContain(session.sessionId);
expect((forkMeta?.payload as SessionMetaPayload).system_prompt).not.toContain(SID);
+ // The head records what the fork is, so a restart reads it the same way.
+ expect((forkMeta?.payload as SessionMetaPayload).source).toBe("user");
const forkScratch = path.join(
scratchpadDir(t.root, projectId, "default_agent"),
@@ -381,6 +385,7 @@ describe("session fork", () => {
system_prompt: `Session ${SID}; scratchpad ${modelVisiblePath(scratch)}`,
agent_state: path.join(t.root, projectId, "agents", "default_agent", "agent_state"),
workspace,
+ source: "user",
};
const compaction = [
at(
@@ -463,6 +468,7 @@ describe("session fork", () => {
system_prompt: `Session ${SID}`,
agent_state: path.join(t.root, projectId, "agents", "default_agent", "agent_state"),
workspace,
+ source: "user",
};
await writeTraceFile(t.root, projectId, "default_agent", "2026-08-15", SID, 2, [
at("2026-08-15T10:00:00.000Z", sessionMeta(meta)),
@@ -544,6 +550,7 @@ describe("session fork", () => {
system_prompt: `Session ${SID}; scratchpad ${modelVisiblePath(scratch)}`,
agent_state: path.join(t.root, projectId, "agents", "default_agent", "agent_state"),
workspace,
+ source: "user",
};
await writeTraceFile(t.root, projectId, "default_agent", "2026-08-14", SID, 2, [
at("2026-08-14T10:01:05.000Z", sessionMeta(metaB)),
diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.ts
index 8d4ea27c..bdc4e142 100644
--- a/packages/server/test/session-index.test.ts
+++ b/packages/server/test/session-index.test.ts
@@ -12,10 +12,9 @@
* - Given a configured model, a created Session gets a temporary Workspace inside its Agent,
* allow-all, a lastActiveAt equal to its creation stored on the row, and shows in the list;
* an explicit Workspace only has to exist.
- * - Given a Session's origin, it is read from session_meta, never the row: a schedule's
- * Session, one only a Trace head knows after a restart, and adopted ones (junk narrowed).
- * - Given many rows, the list pages newest first, filters by sidebar category, by Workspace
- * group and by organization, and its counts stay whole-Agent; junk parameters are 400s.
+ * - Given many rows, the list pages newest first, filters by Workspace group and by
+ * organization, and its counts stay whole-Agent; junk parameters are 400s. (A Session's
+ * source and the category filter built on it: session-source.test.ts.)
* - Given order=activity, the list runs by last activity (equal stamps by id, code points), and
* a client that asks for no order keeps the creation order and its offsets.
* - Given a before cursor, pages cover every row once; a row that runs mid-paging moves above
@@ -181,102 +180,6 @@ describe("session-index", () => {
expect(patched.session.lastActiveAt).toBe(advanced);
});
- it("schedule-created Session: source derives from session_meta (registry), never from the DB row; user sessions carry none", async () => {
- await configureModels();
- // The scheduler goes through SessionService.createSession directly (no HTTP route exposes source).
- const info = await t.deps.sessionService.createSession({
- projectId,
- agentId,
- source: "schedule",
- });
- expect(info.source).toBe("schedule");
- // The index row stores no origin: session_meta is the single source of truth.
- const row = t.deps.sessionsRepo.findById(info.sessionId);
- expect(row && "source" in row).toBe(false);
- expect(t.deps.sessionSources.get(info.sessionId)).toBe("schedule");
-
- // A user-created session (HTTP) has no source, and the list surfaces both accordingly.
- const res = await api.post(base(), {});
- expect(res.status).toBe(201);
- const { session: plain } = (await res.json()) as SessionCreateResponse;
- const list = (await (await api.get(base())).json()) as SessionsResponse;
- expect(list.sessions.find((s) => s.sessionId === info.sessionId)?.source).toBe("schedule");
- expect(list.sessions.find((s) => s.sessionId === plain.sessionId)?.source).toBeUndefined();
- });
-
- it("source survives a restart via the Trace head: an indexed row unknown to this process derives it lazily from session_meta", async () => {
- await configureModels();
- // Simulate a Session created by a previous process: the index row exists, but the
- // in-process registry has never seen it — only its Trace's session_meta knows the origin.
- const sid = "session-2026-07-02-09-00-00-feedc0de";
- t.deps.sessionsRepo.insert({
- sessionId: sid,
- projectId,
- agentId,
- provider: "custom",
- modelId: "m-x",
- workspace: "/tmp/w-restart",
- approvalMode: "allow-all",
- title: null,
- createdAt: "2026-07-02T09:00:00.000Z",
- lastActiveAt: "2026-07-02T09:00:00.000Z",
- });
- const meta: SessionMetaPayload = {
- session_id: sid,
- model_id: "m-x",
- provider: "custom",
- model_context_window: 1000,
- system_prompt: "",
- agent_state: "/tmp/a",
- workspace: "/tmp/w-restart",
- source: "subagent",
- };
- await writeTraceFile(t.root, projectId, agentId, "2026-07-02", sid, 1, [
- sessionMeta(meta),
- userText("child work"),
- ]);
- const list = (await (await api.get(base())).json()) as SessionsResponse;
- expect(list.sessions.find((s) => s.sessionId === sid)?.source).toBe("subagent");
- // The single-session endpoint derives it the same way (and the second read hits the registry).
- const single = (await (await api.get(`/api/sessions/${sid}`)).json()) as SessionResponse;
- expect(single.session.source).toBe("subagent");
- });
-
- it("adoption derives source from the Trace meta, narrowing junk values to user-created", async () => {
- await configureModels();
- // Discovered (no index row) with a valid origin: adoption records it.
- const adopted = "session-2026-07-03-10-00-00-0badf00d";
- const sourced: SessionMetaPayload = {
- session_id: adopted,
- model_id: "m-cli",
- provider: "custom",
- model_context_window: 1000,
- system_prompt: "",
- agent_state: "/tmp/a",
- workspace: "/tmp/w-cli",
- source: "schedule",
- };
- await writeTraceFile(t.root, projectId, agentId, "2026-07-03", adopted, 1, [
- sessionMeta(sourced),
- userText("adopted"),
- ]);
- // Discovered with a junk source (untrusted on-disk data): narrowed to user-created.
- const junk = "session-2026-07-03-11-00-00-0badf00e";
- const junkMeta = {
- ...sourced,
- session_id: junk,
- source: "weird-origin",
- } as unknown as SessionMetaPayload;
- await writeTraceFile(t.root, projectId, agentId, "2026-07-03", junk, 1, [
- sessionMeta(junkMeta),
- userText("junk"),
- ]);
- await t.deps.sessionService.adoptUnmanagedTraceSessions();
- const list = (await (await api.get(base())).json()) as SessionsResponse;
- expect(list.sessions.find((s) => s.sessionId === adopted)?.source).toBe("schedule");
- expect(list.sessions.find((s) => s.sessionId === junk)?.source).toBeUndefined();
- });
-
it("list paging: limit/offset slice the newest-first list; absent params keep the full list; invalid values 400", async () => {
await configureModels();
// Three sessions with distinct createdAt ordering (insert directly for deterministic times).
@@ -314,146 +217,6 @@ describe("session-index", () => {
expect((await api.get(`${base()}?limit=2&offset=-1`)).status).toBe(400);
});
- it("category filter: each sidebar bucket lists only its rows, paging applies within the category, counts return full totals", async () => {
- await configureModels();
- // Two active user Sessions + one archived (HTTP), two schedule-created (service, one
- // then archived — archived must win over the origin), and one subagent Session whose
- // source only exists in its Trace head (cold-registry derivation during the walk).
- const mkUser = async () =>
- ((await (await api.post(base(), {})).json()) as SessionCreateResponse).session.sessionId;
- const activeA = await mkUser();
- const activeB = await mkUser();
- const archivedC = await mkUser();
- expect((await api.patch(`/api/sessions/${archivedC}`, { archived: true })).status).toBe(200);
- const mkSchedule = async () =>
- (
- await t.deps.sessionService.createSession({
- projectId,
- agentId,
- source: "schedule",
- })
- ).sessionId;
- const scheduleD = await mkSchedule();
- const archivedScheduleF = await mkSchedule();
- expect((await api.patch(`/api/sessions/${archivedScheduleF}`, { archived: true })).status).toBe(
- 200,
- );
- const subagentE = "session-2026-07-02-09-30-00-cafe0001";
- t.deps.sessionsRepo.insert({
- sessionId: subagentE,
- projectId,
- agentId,
- provider: "custom",
- modelId: "m-x",
- workspace: "/tmp/w-sub",
- approvalMode: "allow-all",
- title: null,
- createdAt: "2026-07-02T09:30:00.000Z",
- lastActiveAt: "2026-07-02T09:30:00.000Z",
- });
- await writeTraceFile(t.root, projectId, agentId, "2026-07-02", subagentE, 1, [
- sessionMeta({
- session_id: subagentE,
- model_id: "m-x",
- provider: "custom",
- model_context_window: 1000,
- system_prompt: "",
- agent_state: "/tmp/a",
- workspace: "/tmp/w-sub",
- source: "subagent",
- }),
- userText("child work"),
- ]);
-
- const list = async (qs: string) => {
- const res = await api.get(`${base()}${qs}`);
- expect(res.status, qs).toBe(200);
- return (await res.json()) as SessionsResponse;
- };
- const idSet = (body: SessionsResponse) => new Set(body.sessions.map((s) => s.sessionId));
-
- expect(idSet(await list("?category=active"))).toEqual(new Set([activeA, activeB]));
- expect(idSet(await list("?category=schedule"))).toEqual(new Set([scheduleD]));
- expect(idSet(await list("?category=subagent"))).toEqual(new Set([subagentE]));
- expect(idSet(await list("?category=archived"))).toEqual(
- new Set([archivedC, archivedScheduleF]),
- );
-
- // Paging applies within the category: the two archived rows page one at a time.
- const page1 = await list("?category=archived&limit=1&offset=0");
- const page2 = await list("?category=archived&limit=1&offset=1");
- expect(page1.sessions).toHaveLength(1);
- expect(page2.sessions).toHaveLength(1);
- expect(new Set([...idSet(page1), ...idSet(page2)])).toEqual(
- new Set([archivedC, archivedScheduleF]),
- );
- expect((await list("?category=archived&limit=1&offset=2")).sessions).toEqual([]);
-
- // counts=1 returns totals over the whole list, not the returned page — with or without a filter.
- const counted = await list("?category=active&counts=1&limit=1");
- expect(counted.sessions).toHaveLength(1);
- expect(counted.counts).toEqual({
- active: 2,
- subagent: 1,
- schedule: 1,
- benchmark: 0,
- archived: 2,
- });
- const full = await list("?counts=1");
- expect(full.sessions).toHaveLength(6);
- expect(full.counts).toEqual({
- active: 2,
- subagent: 1,
- schedule: 1,
- benchmark: 0,
- archived: 2,
- });
- expect((await list("")).counts).toBeUndefined();
- expect((await list("")).workspaceCounts).toBeUndefined();
- expect((await list("")).workspaceLatest).toBeUndefined();
-
- // The per-Workspace breakdown accompanies the totals and sums back to them: the
- // subagent Session sits alone in its path; every other row lives in its own
- // temporary workspace.
- const byWorkspace = full.workspaceCounts!;
- expect(byWorkspace["/tmp/w-sub"]).toEqual({
- active: 0,
- subagent: 1,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
- const summed = { active: 0, subagent: 0, schedule: 0, benchmark: 0, archived: 0 };
- for (const ws of Object.values(byWorkspace)) {
- for (const key of Object.keys(summed) as (keyof typeof summed)[]) summed[key] += ws[key];
- }
- expect(summed).toEqual(full.counts);
-
- // Junk values are rejected, never silently unfiltered.
- expect((await api.get(`${base()}?category=weird`)).status).toBe(400);
- expect((await api.get(`${base()}?counts=yes`)).status).toBe(400);
- });
-
- it("a Session created with source benchmark lists under the benchmark category", async () => {
- await configureModels();
- const res = await api.post(base(), { source: "benchmark" });
- expect(res.status).toBe(201);
- const { session } = (await res.json()) as SessionCreateResponse;
- // The origin is read back from the just-created core Session's session_meta, so the
- // create response already carries it.
- expect(session.source).toBe("benchmark");
-
- const counted = (await (await api.get(`${base()}?counts=1`)).json()) as SessionsResponse;
- expect(counted.counts?.benchmark).toBe(1);
- const filtered = (await (
- await api.get(`${base()}?category=benchmark`)
- ).json()) as SessionsResponse;
- expect(filtered.sessions.map((s) => s.sessionId)).toEqual([session.sessionId]);
-
- // Only `benchmark` may be set by a client: the server writes the other origins itself.
- expect((await api.post(base(), { source: "schedule" })).status).toBe(400);
- });
-
it("workspaceGroup pages one Workspace group's own stream, temporary workspaces as one group", async () => {
// Rows are inserted straight into the index: the group filter reads the stored path, and
// going through create() would only add realpath validation this has nothing to say about.
@@ -692,20 +455,8 @@ describe("session-index", () => {
});
const counted = await list(`?order=activity&limit=1&before=${below}&counts=1${scope}`);
expect(counted.sessions.map((s) => s.sessionId)).toEqual(["session-act-a4"]);
- expect(counted.counts).toEqual({
- active: 5,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 1,
- });
- expect(counted.workspaceCounts?.[alpha]).toEqual({
- active: 4,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 1,
- });
+ expect(counted.counts).toEqual({ active: 5, background: 0, archived: 1 });
+ expect(counted.workspaceCounts?.[alpha]).toEqual({ active: 4, background: 0, archived: 1 });
// Groups are still placed by their newest CREATION, not by the walk's first row.
expect(counted.workspaceLatest).toEqual({
[alpha]: "2026-07-05T08:00:00.000Z",
@@ -783,6 +534,7 @@ describe("session-index", () => {
system_prompt: "",
agent_state: "/tmp/a",
workspace: "/tmp/cli-workspace",
+ source: "user",
};
await writeTraceFile(t.root, projectId, agentId, "2026-07-01", discovered, 1, [
sessionMeta(meta),
@@ -907,6 +659,7 @@ describe("session-index", () => {
system_prompt: "",
agent_state: "/tmp/a",
workspace: session.workspace,
+ source: "user",
};
const f1 = await writeTraceFile(t.root, projectId, agentId, "2026-07-01", sessionId, 1, [
sessionMeta(meta),
@@ -953,6 +706,7 @@ describe("session-index", () => {
system_prompt: "",
agent_state: "/a",
workspace: "/w",
+ source: "user",
}),
]);
const created = (await (await api.post(base(), {})).json()) as SessionCreateResponse;
@@ -1034,11 +788,14 @@ describe("session-index", () => {
};
const ids = (body: SessionsResponse) => body.sessions.map((s) => s.sessionId);
- // Without the flag the list keeps its whole-stream contract: every row, every total.
+ // Without the flag the plain list serves every row. A counted list already leaves the desk
+ // out — a Session the organization runtime opened is a company Session, in no category —
+ // but not the ticket session the stamp has not reached: that one is the flag's to drop.
+ expect(ids(await list(""))).toEqual([ticket, desk, own]);
const full = await list("?counts=1");
- expect(ids(full)).toEqual([ticket, desk, own]);
- expect(full.counts!.active).toBe(3);
- expect(full.workspaceCounts!["/tmp/w-org"]!.active).toBe(2);
+ expect(ids(full)).toEqual([ticket, own]);
+ expect(full.counts!.active).toBe(2);
+ expect(full.workspaceCounts!["/tmp/w-org"]!.active).toBe(1);
expect(full.workspaceLatest!["/tmp/w-org"]).toBe("2027-01-01T09:30:00.000Z");
// With it, the organization's rows are gone from every part of the answer at once — a
@@ -1144,6 +901,7 @@ describe("session-index", () => {
system_prompt: "",
agent_state: "/tmp/a",
workspace: session.workspace,
+ source: "user",
};
await writeTraceFile(t.root, projectId, agentId, "2026-07-02", session.sessionId, 1, [
sessionMeta(meta),
diff --git a/packages/server/test/session-loader.test.ts b/packages/server/test/session-loader.test.ts
index 5c80ad15..7710c8b4 100644
--- a/packages/server/test/session-loader.test.ts
+++ b/packages/server/test/session-loader.test.ts
@@ -2,7 +2,9 @@
* Integration tests for createCoreSessionLoader (#3/#13): failures recovering a
* historical Session (Workspace deleted / Model removed from config / Trace
* missing session_meta) all collapse into HttpError(409, session_unrecoverable),
- * preserving the original core message instead of bubbling up as a 500.
+ * preserving the original core message instead of bubbling up as a 500. A Session rebuilt
+ * without a Trace records the source this process knows, else the one its row stands for
+ * (`company` on the organization runtime's `org` row), else core's default.
*/
import fs from "node:fs/promises";
import path from "node:path";
@@ -28,6 +30,7 @@ function meta(overrides: Partial<SessionMetaPayload> = {}): SessionMetaPayload {
system_prompt: "sp",
agent_state: "/tmp/a",
workspace: path.join("/tmp", "does-not-exist-xyz"),
+ source: "user",
...overrides,
};
}
@@ -100,7 +103,7 @@ describe("session-loader", () => {
expect((err as HttpError).code).toBe("workspace_missing");
});
- it("self-heal rebuild re-records a registry-known origin in the fresh session_meta; unknown stays absent", async () => {
+ it("self-heal rebuild re-records a registry-known source in the fresh session_meta; an unknown one is company on an org row, user on any other", async () => {
// The anthropic pair constructs without a credential (the same pair session-index
// creates over HTTP); custom/m1 would demand a key at client construction.
await saveProjectConfig(root, PROJECT, {
@@ -127,10 +130,22 @@ describe("session-loader", () => {
(known as unknown as { dispose(): void }).dispose();
// No registry entry (e.g. the process restarted and no Trace was ever written): the
- // rebuilt Session is unsourced — no source key is invented.
+ // rebuilt Session takes core's default, a person's conversation.
const unknown = await createCoreSessionLoader(root, new SessionSources()).load(healRow);
- const unknownMeta = (unknown as unknown as { metaMessage: { payload: object } }).metaMessage;
- expect("source" in unknownMeta.payload).toBe(false);
+ const unknownMeta = (unknown as unknown as { metaMessage: { payload: { source?: string } } })
+ .metaMessage;
+ expect(unknownMeta.payload.source).toBe("user");
(unknown as unknown as { dispose(): void }).dispose();
+
+ // The same on a row the organization runtime opened (a desk waiting for its first run):
+ // the row says what the Session is, a company Session.
+ const desk = await createCoreSessionLoader(root, new SessionSources()).load({
+ ...healRow,
+ client: "org",
+ });
+ const deskMeta = (desk as unknown as { metaMessage: { payload: { source?: string } } })
+ .metaMessage;
+ expect(deskMeta.payload.source).toBe("company");
+ (desk as unknown as { dispose(): void }).dispose();
});
});
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index 8fc8dd9c..d5d1b849 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -518,6 +518,7 @@ describe("session-manager", () => {
system_prompt: "sp",
agent_state: dir,
workspace: dir,
+ source: "user",
},
bootstrap: async () => ({ llm }),
environment,
@@ -975,6 +976,7 @@ describe("session-manager", () => {
system_prompt: "sys",
agent_state: "/root/p1/child_agent/agent_state",
workspace: "/tmp/w-child",
+ source: "subagent",
}),
hop,
);
@@ -1001,9 +1003,8 @@ describe("session-manager", () => {
expect(child?.agentId).toBe("child_agent");
expect(child?.modelId).toBe("m-child");
expect(child?.workspace).toBe("/tmp/w-child");
- // The origin lands in the in-process registry (session_meta is the single source of
- // truth; the row stores no source column) — "subagent" even when the forwarded meta
- // predates the source field (this fake omits it): the registration path is the fallback.
+ // The source lands in the in-process registry (session_meta is the single source of
+ // truth; the row stores no source column).
expect(sources.get("child-1")).toBe("subagent");
expect(child && "source" in child).toBe(false);
// The row itself is inserted with a blank title: the title generator (faked here) is
@@ -1570,6 +1571,7 @@ describe("session-manager", () => {
system_prompt: "sys",
agent_state: "/root/p1/child_agent/agent_state",
workspace: "/tmp/w-child",
+ source: "subagent",
}),
hop,
);
diff --git a/packages/server/test/session-source.test.ts b/packages/server/test/session-source.test.ts
new file mode 100644
index 00000000..64b71ca5
--- /dev/null
+++ b/packages/server/test/session-source.test.ts
@@ -0,0 +1,383 @@
+/**
+ * A Session's source on the server: what kind of conversation each Session is, read from its
+ * session_meta (never the index row), and the sessions list's three categories built on it.
+ *
+ * One app and one Project serve the file; each case works in an Agent of its own, which it
+ * deletes on the way out.
+ *
+ * Scenarios:
+ * - Given Sessions of every source, some archived, the list files `user` rows under `active`,
+ * `api` / `schedule` / `subagent` / `cli` rows under `background`, and an archived row under
+ * `archived` whatever its source — but a `company` row, archived or not, under none of them;
+ * the plain list still serves it.
+ * - Given a category the list no longer has (`subagent`, `schedule`, `benchmark`) or junk,
+ * the list is a 400, never an unfiltered page.
+ * - Given the same rows, `counts=1` returns active / background / archived totals over the
+ * whole list whatever the page, counting no company row; the per-Workspace totals sum back
+ * to them, a Workspace holding only company rows has no totals and no stamp, and a request
+ * without `counts=1` carries none.
+ * - Given more background rows than a page, `category=background` pages by activity cursor,
+ * serving every background row exactly once and no other.
+ * - Given a create request, `source: "cli"` creates a `cli` Session and the retired
+ * `benchmark` is accepted as `cli`; a source the server writes itself is a 400 that creates
+ * nothing.
+ * - Given a Trace head from before the source was required, after a restart (a registry that
+ * has not seen it) one without a source lists as `active` and reads `user`, one with
+ * `benchmark` lists as `background` and reads `cli`; the startup sweep adopts them the same
+ * way.
+ * - Given a Session company mode opened before the source was required (a head without one, the
+ * row's client `org`), it reads as `company` and is in no category; so does an `org` row that
+ * has not run yet.
+ * - Given company mode opening a desk Session (`company`, client `org`), the Session is
+ * `company`, keeps its `org` client and is in no category; a child it spawns is `subagent`,
+ * in Background.
+ * - Given the scheduler opening a Session, it is `schedule`, in Background.
+ * (A fork is `user` whatever it was cut from: session-fork.test.ts.)
+ */
+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it } from "vitest";
+import { assistantText, sessionMeta, userText, withOrigin } from "@lmliheng/penguin-core";
+import type {
+ ProjectCreateResponse,
+ SessionCreateResponse,
+ SessionResponse,
+ SessionsResponse,
+} from "../src/api/types.js";
+import { apiClient, createTestApp, provisionUser, waitFor, writeTraceFile } from "./helpers.js";
+import type { TestApp } from "./helpers.js";
+import { adoptSession, fakeSession } from "./fixtures/session.js";
+
+describe("session source", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ let projectId: string;
+ let agentId: string;
+ let cases = 0;
+ const base = () => `/api/projects/${projectId}/agents/${agentId}/sessions`;
+
+ beforeAll(async () => {
+ t = await createTestApp();
+ const { cookie } = await provisionUser(t.app, "source_owner");
+ api = apiClient(t.app, cookie);
+ const created = (await (
+ await api.post("/api/projects", { projectId: "source_owner-src", name: "Source project" })
+ ).json()) as ProjectCreateResponse;
+ projectId = created.project.projectId;
+ });
+ afterAll(async () => {
+ await t.cleanup();
+ });
+ beforeEach(async () => {
+ agentId = `case_${++cases}`;
+ expect((await api.post(`/api/projects/${projectId}/agents`, { agentId })).status).toBe(201);
+ });
+ afterEach(async () => {
+ await api.delete(`/api/projects/${projectId}/agents/${agentId}`);
+ });
+
+ async function configureModels(): Promise<void> {
+ const res = await api.put(`/api/projects/${projectId}/models`, {
+ defaultModel: { provider: "anthropic", modelId: "claude-sonnet-4-6" },
+ models: [{ provider: "anthropic", modelId: "claude-sonnet-4-6", contextWindow: 128000 }],
+ });
+ expect(res.status).toBe(200);
+ }
+
+ const list = async (qs: string) => {
+ const res = await api.get(`${base()}${qs}`);
+ expect(res.status, qs).toBe(200);
+ return (await res.json()) as SessionsResponse;
+ };
+ const ids = (body: SessionsResponse) => body.sessions.map((s) => s.sessionId);
+ const sourceIn = (body: SessionsResponse, sessionId: string) =>
+ body.sessions.find((s) => s.sessionId === sessionId)?.source;
+
+ /**
+ * A Session created by an earlier process: its index row, and a Trace whose head carries
+ * `source` exactly as given (undefined writes no key). Nothing in this process has seen the
+ * meta, so the list reads it from the head — the path every row takes after a restart.
+ */
+ async function seed(
+ n: number,
+ source: unknown,
+ opts: { workspace?: string; archived?: boolean; indexed?: boolean; client?: "org" } = {},
+ ): Promise<string> {
+ const day = String(n).padStart(2, "0");
+ // Unique per case as well: the in-process source registry outlives a deleted Agent (ids
+ // are never reused in production), so a repeated id would be answered from a stale entry.
+ const minute = String(cases).padStart(2, "0");
+ const sessionId = `session-2026-07-${day}-09-${minute}-00-5eed${minute}${day}`;
+ const stamp = `2026-07-${day}T09:00:00.000Z`;
+ const workspace = opts.workspace ?? `/tmp/ws-source-${day}`;
+ if (opts.indexed !== false) {
+ t.deps.sessionsRepo.insert({
+ sessionId,
+ projectId,
+ agentId,
+ provider: "custom",
+ modelId: "m-x",
+ workspace,
+ approvalMode: "allow-all",
+ title: null,
+ ...(opts.client !== undefined ? { client: opts.client } : {}),
+ createdAt: stamp,
+ lastActiveAt: stamp,
+ });
+ if (opts.archived) t.deps.sessionsRepo.setArchived(sessionId, stamp);
+ }
+ const meta = {
+ session_id: sessionId,
+ model_id: "m-x",
+ provider: "custom",
+ model_context_window: 1000,
+ system_prompt: "",
+ agent_state: "/tmp/a",
+ workspace,
+ ...(source !== undefined ? { source } : {}),
+ };
+ await writeTraceFile(t.root, projectId, agentId, `2026-07-${day}`, sessionId, 1, [
+ sessionMeta(meta as Parameters<typeof sessionMeta>[0]),
+ userText(`work ${n}`),
+ ]);
+ return sessionId;
+ }
+
+ /**
+ * One row of every source, a pre-source `user` row, a retired `benchmark` row, two archived
+ * ones, and three company rows: one sharing a Workspace with background rows, one archived,
+ * one alone in its Workspace.
+ */
+ async function seedEverySource() {
+ return {
+ user: await seed(1, "user"),
+ legacyUser: await seed(2, undefined),
+ api: await seed(3, "api"),
+ schedule: await seed(4, "schedule"),
+ subagent: await seed(5, "subagent", { workspace: "/tmp/ws-source-shared" }),
+ cli: await seed(6, "cli", { workspace: "/tmp/ws-source-shared" }),
+ legacyBenchmark: await seed(7, "benchmark"),
+ archivedUser: await seed(8, "user", { archived: true }),
+ archivedSchedule: await seed(9, "schedule", { archived: true }),
+ company: await seed(10, "company", { workspace: "/tmp/ws-source-shared", client: "org" }),
+ archivedCompany: await seed(11, "company", { archived: true, client: "org" }),
+ companyOnly: await seed(12, "company", { workspace: "/tmp/ws-source-desk", client: "org" }),
+ };
+ }
+
+ it("files user rows under active, other programs' under background, archived rows under archived, and company rows under none", async () => {
+ const rows = await seedEverySource();
+ expect(new Set(ids(await list("?category=active")))).toEqual(
+ new Set([rows.user, rows.legacyUser]),
+ );
+ expect(new Set(ids(await list("?category=background")))).toEqual(
+ new Set([rows.api, rows.schedule, rows.subagent, rows.cli, rows.legacyBenchmark]),
+ );
+ expect(new Set(ids(await list("?category=archived")))).toEqual(
+ new Set([rows.archivedUser, rows.archivedSchedule]),
+ );
+ // Nowhere in the categories, and still a Session: the plain list serves every row.
+ const all = await list("");
+ for (const id of [rows.company, rows.archivedCompany, rows.companyOnly]) {
+ expect(sourceIn(all, id)).toBe("company");
+ }
+ });
+
+ it("refuses a category the list no longer has, or junk, rather than serving an unfiltered page", async () => {
+ await seed(1, "subagent");
+ for (const category of ["subagent", "schedule", "benchmark", "weird"]) {
+ expect((await api.get(`${base()}?category=${category}`)).status, category).toBe(400);
+ }
+ });
+
+ it("counts=1 totals active, background and archived over the whole list, broken down by Workspace, counting no company row", async () => {
+ await seedEverySource();
+ const counted = await list("?category=active&counts=1&limit=1");
+ expect(counted.sessions).toHaveLength(1);
+ expect(counted.counts).toEqual({ active: 2, background: 5, archived: 2 });
+ // The two background rows sharing a Workspace are counted there together, and the company
+ // row beside them is not.
+ expect(counted.workspaceCounts?.["/tmp/ws-source-shared"]).toEqual({
+ active: 0,
+ background: 2,
+ archived: 0,
+ });
+ // A Workspace holding only a company row is no group of the list: no totals, no stamp.
+ expect(counted.workspaceCounts?.["/tmp/ws-source-desk"]).toBeUndefined();
+ expect(counted.workspaceLatest?.["/tmp/ws-source-desk"]).toBeUndefined();
+ const summed = { active: 0, background: 0, archived: 0 };
+ for (const ws of Object.values(counted.workspaceCounts ?? {})) {
+ for (const key of Object.keys(summed) as (keyof typeof summed)[]) summed[key] += ws[key];
+ }
+ expect(summed).toEqual(counted.counts);
+ expect((await list("?category=active")).counts).toBeUndefined();
+ });
+
+ it("pages category=background by activity cursor, serving every background row once and no other", async () => {
+ const background: string[] = [];
+ for (let n = 1; n <= 7; n++) {
+ // Every third row is a person's conversation, interleaved with the background ones.
+ if (n % 3 === 0) await seed(n, "user");
+ else background.push(await seed(n, n % 2 === 0 ? "schedule" : "cli"));
+ }
+ const served: string[] = [];
+ let below: { lastActiveAt: string; sessionId: string } | undefined;
+ for (;;) {
+ const cursor = below
+ ? `&before=${encodeURIComponent(`${below.lastActiveAt},${below.sessionId}`)}`
+ : "";
+ const page = (await list(`?order=activity&category=background&limit=3${cursor}`)).sessions;
+ served.push(...page.slice(0, 2).map((s) => s.sessionId));
+ if (page.length <= 2) break;
+ below = page[1];
+ }
+ // Newest activity first: the seeded stamps rise with n.
+ expect(served).toEqual([...background].reverse());
+ });
+
+ it("creates a cli Session for source cli, and accepts the retired benchmark as cli", async () => {
+ await configureModels();
+ for (const source of ["cli", "benchmark"]) {
+ const res = await api.post(base(), { source });
+ expect(res.status, source).toBe(201);
+ const { session } = (await res.json()) as SessionCreateResponse;
+ expect(session.source, source).toBe("cli");
+ expect(sourceIn(await list("?category=background"), session.sessionId), source).toBe("cli");
+ }
+ });
+
+ it("refuses a source the server writes itself, creating nothing", async () => {
+ await configureModels();
+ for (const source of ["api", "schedule", "subagent", "company", "user"]) {
+ expect((await api.post(base(), { source })).status, source).toBe(400);
+ }
+ expect((await list("")).sessions).toEqual([]);
+ });
+
+ it("reads an old Trace head after a restart: no source lists as active user, benchmark as background cli", async () => {
+ const legacyUser = await seed(1, undefined);
+ const legacyBenchmark = await seed(2, "benchmark");
+ const all = await list("");
+ expect(sourceIn(all, legacyUser)).toBe("user");
+ expect(sourceIn(all, legacyBenchmark)).toBe("cli");
+ expect(ids(await list("?category=active"))).toEqual([legacyUser]);
+ expect(ids(await list("?category=background"))).toEqual([legacyBenchmark]);
+ // The single-session GET reads the same way.
+ const single = (await (
+ await api.get(`/api/sessions/${legacyBenchmark}`)
+ ).json()) as SessionResponse;
+ expect(single.session.source).toBe("cli");
+ });
+
+ it("adopts an unindexed old Trace with the same reading", async () => {
+ const legacyUser = await seed(1, undefined, { indexed: false });
+ const legacyBenchmark = await seed(2, "benchmark", { indexed: false });
+ const junk = await seed(3, "weird-origin", { indexed: false });
+ await t.deps.sessionService.adoptUnmanagedTraceSessions();
+ const all = await list("");
+ expect(sourceIn(all, legacyUser)).toBe("user");
+ expect(sourceIn(all, legacyBenchmark)).toBe("cli");
+ expect(sourceIn(all, junk)).toBe("user");
+ });
+
+ it("reads a Session company mode opened before the source was required as company, in no category", async () => {
+ // Its head records no source; its row carries the organization runtime's `org` stamp.
+ const oldDesk = await seed(1, undefined, { client: "org" });
+ const single = (await (await api.get(`/api/sessions/${oldDesk}`)).json()) as SessionResponse;
+ expect(single.session.source).toBe("company");
+ expect(sourceIn(await list(""), oldDesk)).toBe("company");
+ const counted = await list("?category=active&counts=1");
+ expect(counted.sessions).toEqual([]);
+ expect(counted.counts).toEqual({ active: 0, background: 0, archived: 0 });
+ });
+
+ it("reads an org row that has not run yet as company, in no category", async () => {
+ // A desk opened at a hire and never run, after a restart: no Trace, nothing in the
+ // registry. (Its first run records `company` too: session-loader.test.ts.)
+ const sessionId = `session-2026-07-21-09-${String(cases).padStart(2, "0")}-00-0de5c001`;
+ const stamp = "2026-07-21T09:00:00.000Z";
+ t.deps.sessionsRepo.insert({
+ sessionId,
+ projectId,
+ agentId,
+ provider: "anthropic",
+ modelId: "claude-sonnet-4-6",
+ workspace: t.root,
+ approvalMode: "allow-all",
+ title: null,
+ client: "org",
+ createdAt: stamp,
+ lastActiveAt: stamp,
+ });
+ expect(sourceIn(await list(""), sessionId)).toBe("company");
+ expect((await list("?counts=1")).counts).toEqual({ active: 0, background: 0, archived: 0 });
+ });
+
+ it("opens a company-mode desk Session as company, keeping its org client, in no category", async () => {
+ await configureModels();
+ // The organization runtime's call.
+ const desk = await t.deps.sessionService.createSession({
+ projectId,
+ agentId,
+ client: "org",
+ source: "company",
+ });
+ expect(desk.source).toBe("company");
+ const got = (await (
+ await api.get(`/api/sessions/${desk.sessionId}`)
+ ).json()) as SessionResponse;
+ expect(got.session.source).toBe("company");
+ expect(got.session.client).toBe("org");
+ const counted = await list("?category=active&counts=1");
+ expect(counted.sessions).toEqual([]);
+ expect(counted.counts).toEqual({ active: 0, background: 0, archived: 0 });
+ });
+
+ it("files a child a desk Session spawns under Background as subagent", async () => {
+ const childId = "session-2026-07-20-09-00-00-c41d0001";
+ const deskId = "session-2026-07-20-08-00-00-de5c0001";
+ adoptSession(
+ t.deps,
+ fakeSession(deskId, {
+ async *run() {
+ // Core's spawn site writes the child's meta; it reaches the desk with its origin.
+ yield withOrigin(
+ sessionMeta({
+ session_id: childId,
+ model_id: "m-child",
+ provider: "custom",
+ model_context_window: 1000,
+ system_prompt: "",
+ agent_state: `${t.root}/${projectId}/agents/${agentId}/agent_state`,
+ workspace: "/tmp/ws-desk",
+ source: "subagent",
+ }),
+ childId,
+ );
+ yield withOrigin(assistantText("child done"), childId);
+ yield assistantText("done");
+ },
+ }),
+ { projectId, agentId, client: "org", workspace: "/tmp/ws-desk" },
+ );
+ await t.deps.manager.startTask(deskId, [userText("go")]);
+ await waitFor(() => t.deps.manager.statusOf(deskId) === "idle");
+ const background = await list("?category=background");
+ expect(ids(background)).toEqual([childId]);
+ expect(sourceIn(background, childId)).toBe("subagent");
+ expect(background.sessions[0]!.client).toBe("org");
+ });
+
+ it("opens a scheduled task's Session as schedule, in Background", async () => {
+ await configureModels();
+ // The scheduler's call (new-session mode).
+ const info = await t.deps.sessionService.createSession({
+ projectId,
+ agentId,
+ source: "schedule",
+ });
+ expect(info.source).toBe("schedule");
+ expect(sourceIn(await list("?category=background"), info.sessionId)).toBe("schedule");
+ // Read from session_meta, never from the index row, which stores no source.
+ const row = t.deps.sessionsRepo.findById(info.sessionId);
+ expect(row !== null && "source" in row).toBe(false);
+ });
+});
diff --git a/packages/server/test/session-switch-model.test.ts b/packages/server/test/session-switch-model.test.ts
index 17e3b373..6fa641fb 100644
--- a/packages/server/test/session-switch-model.test.ts
+++ b/packages/server/test/session-switch-model.test.ts
@@ -147,6 +147,7 @@ function switchFake(model: ModelRefDto, behaviour: SwitchBehaviour): SwitchFake
system_prompt: "sp",
agent_state: "/tmp/agents/default_agent/agent_state",
workspace: "/tmp/w",
+ source: "user",
});
}
return status;
diff --git a/packages/server/test/trace-image.test.ts b/packages/server/test/trace-image.test.ts
index 38e755e3..b8e81ace 100644
--- a/packages/server/test/trace-image.test.ts
+++ b/packages/server/test/trace-image.test.ts
@@ -63,6 +63,7 @@ describe("images by reference", () => {
system_prompt: "sp",
agent_state: "/tmp/a",
workspace: "/tmp/w",
+ source: "user",
}),
userText("look at these"), // 1
imageUrlMessage(dataUrl("image/png", PNG)), // 2
diff --git a/packages/server/test/trace-import-export.test.ts b/packages/server/test/trace-import-export.test.ts
index e92f64c7..6f397a7f 100644
--- a/packages/server/test/trace-import-export.test.ts
+++ b/packages/server/test/trace-import-export.test.ts
@@ -30,6 +30,7 @@ function metaPayload(sessionId: string): SessionMetaPayload {
system_prompt: "",
agent_state: "/tmp/a",
workspace: "/tmp/w",
+ source: "user",
};
}
diff --git a/packages/server/test/trace-index.test.ts b/packages/server/test/trace-index.test.ts
index 69a85903..a081aaf3 100644
--- a/packages/server/test/trace-index.test.ts
+++ b/packages/server/test/trace-index.test.ts
@@ -2,12 +2,15 @@
* Trace-file index tests: mtime-gated reconciliation (an unchanged tree costs zero
* directory scans), registration-time classification, gate blind spots recovered by
* the consumers' force-retry, write-time registration (import) and delete coherence.
+ * A cache row registered before the source was required (NULL, or the retired `benchmark`)
+ * reads as a head that records no source (which the session list reads with the row's client)
+ * / as `cli`, without being rewritten.
*/
import fs from "node:fs/promises";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
import { sessionMeta, userText } from "@lmliheng/penguin-core";
-import type { SessionMetaPayload } from "@lmliheng/penguin-core";
+import type { SessionMetaPayload, SessionSource } from "@lmliheng/penguin-core";
import { makeTempRoot, makeTraceHarness, writeTraceFile } from "./helpers.js";
const P = "project-i";
@@ -45,6 +48,7 @@ function meta(sessionId: string, over: Partial<SessionMetaPayload> = {}): Sessio
system_prompt: "sp",
agent_state: "/tmp/a",
workspace: "/ws/one",
+ source: "user",
...over,
};
}
@@ -203,6 +207,28 @@ describe("trace-index", () => {
expect(h.traceIndex.repo.listFilesBySession(P, A, IMP)).toEqual([]);
});
+ it("reads a cache row registered before the source was required: NULL as no recorded source, benchmark as cli", async () => {
+ // The derived cache is never migrated: rows an older release registered keep the string
+ // (or the NULL) their head carried, and are read through the same narrowing. NULL stays
+ // "records none": whether that is a person's conversation or a company Session is the
+ // index row's to say (readRecordedSource).
+ const row = {
+ sessionId: S1,
+ projectId: P,
+ agentId: A,
+ workspace: "/ws/one",
+ title: null,
+ provider: "custom",
+ modelId: "m1",
+ firstTs: null,
+ metaRead: true,
+ };
+ h.traceIndex.repo.upsertSession({ ...row, source: null });
+ expect(h.traceIndex.repo.getSession(S1)?.source).toBeNull();
+ h.traceIndex.repo.upsertSession({ ...row, source: "benchmark" as unknown as SessionSource });
+ expect(h.traceIndex.repo.getSession(S1)?.source).toBe("cli");
+ });
+
it("externally deleted files and date dirs fall out of the index on the next changed-dir pass", async () => {
await writeTraceFile(root, P, A, "2026-07-05", S1, 1, [userText("a")]);
await writeTraceFile(root, P, A, "2026-07-05", S1, 2, [userText("b")]);
diff --git a/packages/server/test/trace-service.test.ts b/packages/server/test/trace-service.test.ts
index e07bf7b3..c29bfd06 100644
--- a/packages/server/test/trace-service.test.ts
+++ b/packages/server/test/trace-service.test.ts
@@ -81,6 +81,7 @@ function metaPayload(over: Partial<SessionMetaPayload> = {}): SessionMetaPayload
system_prompt: "sp",
agent_state: "/tmp/a",
workspace: "/tmp/w",
+ source: "user",
...over,
};
}
@@ -904,7 +905,7 @@ describe("trace-service", () => {
withTitles.close();
});
- it("Agent-level paging: category/workspace come from the DB row (archived wins; a registry-known origin fills its bucket)", async () => {
+ it("Agent-level paging: category/workspace come from the DB row (archived wins; a registry-known source fills its bucket)", async () => {
const s2 = "session-2026-07-06-09-00-00-11112222";
const s3 = "session-2026-07-07-08-00-00-33334444";
await writeTraceFile(root, P, A, "2026-07-05", S, 1, [userText("a")]);
@@ -912,7 +913,7 @@ describe("trace-service", () => {
await writeTraceFile(root, P, A, "2026-07-07", s3, 1, [userText("c")]);
const sources = new SessionSources();
sources.set(s2, "subagent");
- sources.set(s3, null); // meta seen, user-created
+ sources.set(s3, "user"); // meta seen, a person's conversation
const h = makeTraceHarness(root, {
sources,
sessions: {
@@ -927,23 +928,11 @@ describe("trace-service", () => {
const byId = new Map(res.sessions!.map((x) => [x.sessionId, x]));
expect(byId.get(S)!.category).toBe("archived");
expect(byId.get(S)!.workspace).toBe("/ws/one");
- expect(byId.get(s2)!.category).toBe("subagent"); // untracked but registry-known
+ expect(byId.get(s2)!.category).toBe("background"); // untracked but registry-known
expect(byId.get(s3)!.category).toBe("active");
- expect(res.counts).toEqual({ active: 1, subagent: 1, schedule: 0, benchmark: 0, archived: 1 });
- expect(res.workspaceCounts!["/ws/one"]).toEqual({
- active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 1,
- });
- expect(res.workspaceCounts!["/ws/two"]).toEqual({
- active: 1,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
+ expect(res.counts).toEqual({ active: 1, background: 1, archived: 1 });
+ expect(res.workspaceCounts!["/ws/one"]).toEqual({ active: 0, background: 0, archived: 1 });
+ expect(res.workspaceCounts!["/ws/two"]).toEqual({ active: 1, background: 0, archived: 0 });
// The category filter pages within one bucket; totalSessions is the bucket's count.
const active = await h.service.agentTraces(
@@ -954,13 +943,7 @@ describe("trace-service", () => {
);
expect(active.sessions!.map((x) => x.sessionId)).toEqual([s3]);
expect(active.totalSessions).toBe(1);
- expect(active.counts).toEqual({
- active: 1,
- subagent: 1,
- schedule: 0,
- benchmark: 0,
- archived: 1,
- });
+ expect(active.counts).toEqual({ active: 1, background: 1, archived: 1 });
const archived = await h.service.agentTraces(
P,
A,
@@ -981,27 +964,21 @@ describe("trace-service", () => {
]);
const first = await service.agentTraces(P, A, { offset: 0, limit: 10 });
- expect(first.sessions![0]!.category).toBe("subagent");
+ expect(first.sessions![0]!.category).toBe("background");
expect(first.sessions![0]!.workspace).toBe("/ws/child");
- expect(first.counts).toEqual({
- active: 0,
- subagent: 1,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
+ expect(first.counts).toEqual({ active: 0, background: 1, archived: 0 });
// The observation landed in the shared registry (single source of truth) at registration.
expect(harness.sources.get(S)).toBe("subagent");
const reads = harness.traceIndex.counters.headReads;
const second = await service.agentTraces(P, A, { offset: 0, limit: 10 });
- expect(second.sessions![0]!.category).toBe("subagent");
+ expect(second.sessions![0]!.category).toBe("background");
expect(harness.traceIndex.counters.headReads).toBe(reads); // classification never re-reads
});
it("Agent-level paging: every Session is listed whichever client created it (no CLI filter)", async () => {
const cliSid = "session-2026-07-06-09-00-00-11112222"; // untracked, user-created meta (a legacy CLI-direct run)
- const childSid = "session-2026-07-07-08-00-00-33334444"; // untracked but subagent-origin -> its folder
+ const childSid = "session-2026-07-07-08-00-00-33334444"; // untracked but subagent-sourced -> Background
await writeTraceFile(root, P, A, "2026-07-06", cliSid, 1, [
sessionMeta(metaPayload({ session_id: cliSid })),
userText("cli run"),
@@ -1022,13 +999,7 @@ describe("trace-service", () => {
const listed = await h.service.agentTraces(P, A, { offset: 0, limit: 10 });
expect(listed.sessions!.map((x) => x.sessionId)).toEqual([childSid, cliSid, webSid]);
expect(listed.totalSessions).toBe(3);
- expect(listed.counts).toEqual({
- active: 2,
- subagent: 1,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
+ expect(listed.counts).toEqual({ active: 2, background: 1, archived: 0 });
h.close();
});
diff --git a/packages/server/test/trace-subagent-expand.test.ts b/packages/server/test/trace-subagent-expand.test.ts
index b885528f..3cedae8e 100644
--- a/packages/server/test/trace-subagent-expand.test.ts
+++ b/packages/server/test/trace-subagent-expand.test.ts
@@ -41,6 +41,7 @@ function meta(sessionId: string, agentId: string): OmniMessage {
system_prompt: "",
agent_state: `/root/${PROJECT}/${agentId}/agent_state`,
workspace: "/tmp/w",
+ source: "user",
};
return sessionMeta(payload);
}
diff --git a/packages/server/test/usage.test.ts b/packages/server/test/usage.test.ts
index f8c7cf8d..39aabbe5 100644
--- a/packages/server/test/usage.test.ts
+++ b/packages/server/test/usage.test.ts
@@ -71,6 +71,7 @@ function meta(sessionId: string, modelId: string, provider = "custom"): SessionM
system_prompt: "",
agent_state: "/tmp/x",
workspace: "/tmp/w",
+ source: "user",
};
}
diff --git a/packages/ui-gallery/src/app/mock/fixtures.ts b/packages/ui-gallery/src/app/mock/fixtures.ts
index e2501a7a..08cffa61 100644
--- a/packages/ui-gallery/src/app/mock/fixtures.ts
+++ b/packages/ui-gallery/src/app/mock/fixtures.ts
@@ -537,7 +537,8 @@ export function buildFixtures(lang: Lang, now: number): DemoFixtures {
L("评估 CASE-001", "Evaluate CASE-001"),
ago(3),
{
- source: "benchmark",
+ // A Test Session the evaluation launched through `penguin run`.
+ source: "cli",
workspace: `/home/demo/.penguin/data/projects/${IDS.project}/agents/${IDS.agents.docs}/workspaces/case-001`,
},
),
diff --git a/packages/ui-gallery/src/app/mock/routes.ts b/packages/ui-gallery/src/app/mock/routes.ts
index 4d2b6550..5be6669e 100644
--- a/packages/ui-gallery/src/app/mock/routes.ts
+++ b/packages/ui-gallery/src/app/mock/routes.ts
@@ -781,20 +781,26 @@ router
const TEMP_WORKSPACE = /[/\\]workspaces[/\\][^/\\]+$/;
const isTemp = (workspace: string) => workspace === "" || TEMP_WORKSPACE.test(workspace);
-function categoryOf(row: SessionInfo): SessionCategory {
+/**
+ * The server's rule: a company Session is in no category; otherwise archived first, then a
+ * person's conversation is active and every other source background.
+ */
+function categoryOf(row: SessionInfo): SessionCategory | null {
+ if (row.source === "company") return null;
if (row.archived) return "archived";
- return row.source ?? "active";
+ return row.source === undefined || row.source === "user" ? "active" : "background";
}
+/** An organization's desk or ticket Session, by its owner, the durable `org` stamp or its source. */
+const isOrgRow = (row: SessionInfo) =>
+ (row.orgId ?? "") !== "" || row.client === "org" || row.source === "company";
+
function countsOf(rows: readonly SessionInfo[]): SessionCategoryCounts {
- const counts: SessionCategoryCounts = {
- active: 0,
- schedule: 0,
- subagent: 0,
- benchmark: 0,
- archived: 0,
- };
- for (const row of rows) counts[categoryOf(row)] += 1;
+ const counts: SessionCategoryCounts = { active: 0, background: 0, archived: 0 };
+ for (const row of rows) {
+ const category = categoryOf(row);
+ if (category !== null) counts[category] += 1;
+ }
return counts;
}
@@ -814,12 +820,22 @@ function byActivity(
router
.get("/api/projects/:projectId/agents/:agentId/sessions", (ctx): unknown => {
const { store, params, query } = ctx;
+ // `excludeOrg=1` asks for the user's own rows: an organization's Sessions leave the page
+ // and the totals alike. A request for a category, a Workspace group or counts leaves the
+ // company Sessions out too, which no category holds.
+ const ownOnly = query.get("excludeOrg") === "1";
const activity = query.get("order") === "activity";
- const all = store.f.sessions
- .filter((s) => s.agentId === params.agentId)
- .sort(activity ? byActivity : byCreated);
const category = query.get("category") as SessionCategory | null;
const group = query.get("workspaceGroup");
+ const classified = category !== null || group !== null || query.get("counts") === "1";
+ const all = store.f.sessions
+ .filter(
+ (s) =>
+ s.agentId === params.agentId &&
+ !(ownOnly && isOrgRow(s)) &&
+ !(classified && categoryOf(s) === null),
+ )
+ .sort(activity ? byActivity : byCreated);
let rows = category ? all.filter((s) => categoryOf(s) === category) : all;
if (group !== null) {
rows = rows.filter((s) => (group === "temp" ? isTemp(s.workspace) : s.workspace === group));
diff --git a/packages/ui-gallery/src/app/mock/store.ts b/packages/ui-gallery/src/app/mock/store.ts
index 1f2997c7..b1f8ab17 100644
--- a/packages/ui-gallery/src/app/mock/store.ts
+++ b/packages/ui-gallery/src/app/mock/store.ts
@@ -211,6 +211,7 @@ export class DemoStore {
projectId: IDS.project,
agentId,
sessionId: row.sessionId,
+ source: row.source ?? "user",
});
return row;
}
diff --git a/packages/ui-gallery/src/app/mock/transcripts.ts b/packages/ui-gallery/src/app/mock/transcripts.ts
index 0417a3aa..61b3d70e 100644
--- a/packages/ui-gallery/src/app/mock/transcripts.ts
+++ b/packages/ui-gallery/src/app/mock/transcripts.ts
@@ -45,6 +45,7 @@ export const meta = (
system_prompt: "You are Docs Expert. Cite a real file for every claim.",
agent_state: `/home/demo/.penguin/data/projects/${IDS.project}/agents/${IDS.agents.docs}/agent_state`,
workspace,
+ source: "user",
},
});
diff --git a/packages/ui-gallery/test/mock-api.test.ts b/packages/ui-gallery/test/mock-api.test.ts
index 374cbcad..c9513b02 100644
--- a/packages/ui-gallery/test/mock-api.test.ts
+++ b/packages/ui-gallery/test/mock-api.test.ts
@@ -88,9 +88,8 @@ describe("the mocked API", () => {
expect(first.sessions.length).toBe(3);
expect(first.counts?.active).toBeGreaterThan(3);
expect(first.counts?.archived).toBe(1);
- expect(first.counts?.schedule).toBe(1);
- expect(first.counts?.subagent).toBe(1);
- expect(first.counts?.benchmark).toBe(1);
+ // The scheduled, subagent and CLI rows share the Background folder.
+ expect(first.counts?.background).toBe(3);
expect(first.workspaceCounts).toBeDefined();
const rest = await api.listSessions(project, agent, {
offset: 3,
@@ -107,6 +106,18 @@ describe("the mocked API", () => {
category: "archived",
});
expect(archived.sessions.every((s) => s.archived)).toBe(true);
+ // An organization's desk Session reaches neither the user's own page nor its totals. This
+ // demo world seeds no company Session — its org-desk fixture comes from an upstream change
+ // this tree does not carry — so all this checks is that the flag round-trips and that a
+ // counted page and its totals still agree.
+ const notes = await api.listSessions(project, store.f.agents[1]!.agentId, {
+ offset: 0,
+ limit: 10,
+ withCounts: true,
+ excludeOrg: true,
+ });
+ expect(notes.sessions.some((s) => s.client === "org")).toBe(false);
+ expect(notes.counts?.active).toBe(notes.sessions.length);
});
it("pages the list by last activity with a cursor, as the sidebar asks for it", async () => {
diff --git a/packages/ui/src/components/icons/icons.ts b/packages/ui/src/components/icons/icons.ts
index 6d9ab903..72308240 100644
--- a/packages/ui/src/components/icons/icons.ts
+++ b/packages/ui/src/components/icons/icons.ts
@@ -82,6 +82,8 @@ export const ICONS = {
trophy: "M7 4h10v5a5 5 0 0 1-10 0V4zM7 5H4v1a3 3 0 0 0 3 3m10-4h3v1a3 3 0 0 1-3 3M12 14v4m-4 0h8",
/** A `>_` prompt in a window frame. */
terminalWindow: "M3 5h18v14H3zM7 9l3 3-3 3M13 15h4",
+ /** A bare `>_` prompt, without the window frame `terminalWindow` draws round it. */
+ terminalPrompt: "M4 6l4 4-4 4M12 18h8",
/** A tower with wings and windows (lucide building-2). */
building:
"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2M10 6h4M10 10h4M10 14h4M10 18h4",
diff --git a/packages/ui/src/components/shell/session-row/session-row.tsx b/packages/ui/src/components/shell/session-row/session-row.tsx
index 5a182915..86038064 100644
--- a/packages/ui/src/components/shell/session-row/session-row.tsx
+++ b/packages/ui/src/components/shell/session-row/session-row.tsx
@@ -12,10 +12,11 @@
* sidebar's scroller cannot clip them.
*
* Every mark after the title names itself, in a hint and in visually hidden text, which is what
- * lets the standing ones recede to the subtle ink: pinned, relayed to a messaging channel,
- * scheduled to run on its own, and work still running in the background. The live state (a
- * turning hourglass, the compress mark, the unread dot) has one reserved box, kept empty when
- * there is nothing to show, so the title never re-flows as a run starts, finishes and is read.
+ * lets the standing ones recede to the subtle ink: the program that opened it (its source),
+ * pinned, relayed to a messaging channel, scheduled to run on its own, and work still running in
+ * the background. The live state (a turning hourglass, the compress mark, the unread dot) has one
+ * reserved box, kept empty when there is nothing to show, so the title never re-flows as a run
+ * starts, finishes and is read.
*
* The title is the caller's to draw, with the classes the row hands `renderTitle`: the row
* decides the ink and the weight, the caller its own truncation — the app's line reveals a
@@ -157,6 +158,12 @@ export interface SessionRowProps {
archived?: boolean;
/** The conversation's agent, as a small avatar before the title (where its group is not the agent). */
agent?: { id: string; name: string };
+ /**
+ * The program that opened it (an API caller, a scheduled task, a parent agent, a CLI run): the
+ * caller's glyph from the icon registry, named by `sourceLabel`. Drawn only when both are given.
+ */
+ sourceGlyph?: string;
+ sourceLabel?: string;
/** Pinned to the top of its list: the pin mark, named by this. */
pinnedLabel?: string;
/** Relayed to a messaging channel: the paper plane, named by this (the channel's name). */
@@ -206,6 +213,8 @@ export function SessionRow({
active = false,
archived = false,
agent,
+ sourceGlyph,
+ sourceLabel,
pinnedLabel,
relayLabel,
scheduledLabel,
@@ -316,6 +325,9 @@ export function SessionRow({
</span>
)}
{renderTitle(`min-w-0 flex-1 font-sans text-sm ${titleInk}`)}
+ {sourceGlyph !== undefined && sourceLabel !== undefined && (
+ <RowMark glyph={sourceGlyph} label={sourceLabel} />
+ )}
{pinnedLabel !== undefined && <RowMark glyph={ICONS.pin} label={pinnedLabel} />}
{relayLabel !== undefined && <RowMark glyph={ICONS.paperPlane} label={relayLabel} />}
{scheduledLabel !== undefined && (
diff --git a/packages/ui/test/session-row.test.ts b/packages/ui/test/session-row.test.ts
index 584582ed..88bb93a8 100644
--- a/packages/ui/test/session-row.test.ts
+++ b/packages/ui/test/session-row.test.ts
@@ -70,6 +70,8 @@ describe("SessionRow", () => {
it("names every standing mark in words, from the caller's labels", () => {
const html = row({
+ sourceGlyph: ICONS.terminalPrompt,
+ sourceLabel: "CLI",
pinnedLabel: "已置顶",
relayLabel: "飞书远程控制",
scheduledLabel: "定时任务",
@@ -77,6 +79,8 @@ describe("SessionRow", () => {
approvals: { count: 3, label: "3 个待审批" },
agent: { id: "coder", name: "Coder" },
});
+ expect(html).toContain('<span data-tooltip="CLI" class="shrink-0 text-fg-subtle">');
+ expect(html).toContain('<span class="sr-only">CLI</span>');
expect(html).toContain('<span class="sr-only">已置顶</span>');
expect(html).toContain('<span class="sr-only">飞书远程控制</span>');
expect(html).toContain('<span class="sr-only">Coder</span>');
@@ -87,6 +91,12 @@ describe("SessionRow", () => {
);
});
+ it("draws a source mark only when it has both a glyph and its words", () => {
+ // A mark is the subtle-ink span after the title; neither half alone draws one.
+ expect(row({ sourceGlyph: ICONS.plug })).not.toContain('class="shrink-0 text-fg-subtle"');
+ expect(row({ sourceLabel: "API" })).not.toContain("API");
+ });
+
it("draws no background mark and no approval count at zero", () => {
const html = row({
background: { count: 0, label: "0 个后台任务" },
diff --git a/packages/web/e2e/subagent.spec.mjs b/packages/web/e2e/subagent.spec.mjs
index c9a24c79..b98c1f7b 100644
--- a/packages/web/e2e/subagent.spec.mjs
+++ b/packages/web/e2e/subagent.spec.mjs
@@ -240,14 +240,14 @@ test("subagent renders as a chip; the panel shows the call graph and child conve
expect(childMeta, "child trace session_meta").toBeTruthy();
expect(childMeta.payload.source).toBe("subagent");
- // --- Sidebar: the child session (source=subagent) nests inside the collapsed "Subagents"
- // folder (per-origin folders sit parallel to "Archived" within the same temp-workspace
- // group). Reload first so the sidebar list carries the persisted title/source, and the
- // folder is back to its default collapsed state. ---
+ // --- Sidebar: the child session (source=subagent) nests inside the collapsed "Background"
+ // folder (parallel to "Archived" within the same temp-workspace group). Reload first so the
+ // sidebar list carries the persisted title/source, and the folder is back to its default
+ // collapsed state. ---
await page.reload();
const sidebar = page.getByRole("complementary");
- const subagentFolder = sidebar.getByRole("button", { name: "子智能体(1)" });
- await expect(subagentFolder, "collapsed Subagents folder").toBeVisible();
+ const subagentFolder = sidebar.getByRole("button", { name: "后台会话(1)" });
+ await expect(subagentFolder, "collapsed Background folder").toBeVisible();
// Collapsed by default: the child row is not rendered until the folder is expanded.
await expect(sidebar.getByText("Subagent TODO summary")).toHaveCount(0);
await subagentFolder.click();
diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsx
index e2a73457..b61aa318 100644
--- a/packages/web/src/components/layout/app-layout.tsx
+++ b/packages/web/src/components/layout/app-layout.tsx
@@ -115,7 +115,7 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {
/** On some conversation (any non-draft /chat/:id): the "you are here" state of the last-conversation entry. */
const onConversation = activeSessionId !== null && activeSessionId !== DRAFT_SESSION_ID;
- /** Newest loaded conversation across the current Project (active/schedule only — archived and subagent rows are never auto-opened; the flat list is only ordered per Agent). An organization's desk and ticket Sessions are never conversations of this list. */
+ /** Newest loaded conversation across the current Project (the user's own only — archived and background rows are never auto-opened; the flat list is only ordered per Agent). An organization's desk and ticket Sessions are never conversations of this list. */
const lastSession = useMemo(() => latestConversation(withoutOrgSessions(sessions)), [sessions]);
/** Mirrors Sidebar.openSession: the current Agent follows the opened Session's Agent. */
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index a6eb1edc..66a76e01 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -136,6 +136,7 @@ import {
} from "../../lib/session-grouping";
import type { FolderCategory, SessionPartition } from "../../lib/session-grouping";
import { machineForSession } from "../../lib/session-machines";
+import { backgroundSourceMark } from "../../lib/session-source-mark";
import { nameOnMachine } from "../../lib/workspace-machines";
import {
initialNavGroupCollapsed,
@@ -354,9 +355,9 @@ function saveGroupSet(storageKey: string | null, next: ReadonlySet<string>): voi
}
/**
- * Open-state key of a collapsed folder (subagent / scheduled / evaluations / archived) inside
- * a group: each folder has its own state. "\0" never appears in Agent ids or Workspace paths,
- * so the composite never collides across groups or with plain group keys.
+ * Open-state key of a collapsed folder (background / archived) inside a group: each folder has its
+ * own state. "\0" never appears in Agent ids or Workspace paths, so the composite never collides
+ * across groups or with plain group keys.
*/
const folderKey = (groupKey: string, category: FolderCategory) => `${category}\0${groupKey}`;
@@ -374,14 +375,11 @@ const groupShares = (
totals: SessionCategoryCounts | undefined,
rows: readonly SessionInfo[],
): { active: number; folded: number } => {
- const counts: SessionCategoryCounts = {
- active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- };
- for (const s of rows) counts[sessionCategory(s)] += 1;
+ const counts: SessionCategoryCounts = { active: 0, background: 0, archived: 0 };
+ for (const s of rows) {
+ const category = sessionCategory(s);
+ if (category !== null) counts[category] += 1;
+ }
counts.active = Math.max(counts.active, totals?.active ?? 0);
for (const category of FOLDER_CATEGORIES)
counts[category] = Math.max(counts[category], totals?.[category] ?? 0);
@@ -444,8 +442,9 @@ export function Sidebar({
/**
* The rows this list renders: the user's OWN conversations. An organization's desk and
- * ticket Sessions (marked by `orgId`, or by the durable `client === "org"` stamp once the
- * organization is gone) are driven by its scheduler and are reached as themselves in company
+ * ticket Sessions (`company` Sessions, marked by `orgId` too, and by the durable
+ * `client === "org"` stamp that outlives the organization) are driven by its scheduler and
+ * are reached as themselves in company
* mode — a desk from the 工位 group, a ticket session from its ticket. The store's own
* fetches already leave them out, totals and Workspace stamps included (the server's
* `excludeOrg`), so the counts below are the list's exact share; this filter is for a row
@@ -618,7 +617,7 @@ export function Sidebar({
setFolderCaps(new Map());
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [collapseStoreKey, pinStoreKey, folderOnlyStoreKey, currentProjectId]);
- /** Expanded folders (subagent / scheduled / evaluations / archived; collapsed by default), keyed by folderKey — each folder has its own open state. */
+ /** Expanded folders (background / archived; collapsed by default), keyed by folderKey — each folder has its own open state. */
const [openFolders, setOpenFolders] = useState<ReadonlySet<string>>(new Set());
/** "More" rows with a fetch in flight, keyed `${category}\0${groupKey}` — the row disables and reads "loading" so a page that lands entirely in other groups still visibly did something. */
const [pendingLoads, setPendingLoads] = useState<ReadonlySet<string>>(new Set());
@@ -973,9 +972,7 @@ export function Sidebar({
/** A time bucket's rows as a group partition: the buckets carry active conversations only. */
const bucketPartition = (rows: SessionInfo[]): SessionPartition => ({
active: rows,
- subagent: [],
- schedule: [],
- benchmark: [],
+ background: [],
archived: [],
});
@@ -1178,10 +1175,10 @@ export function Sidebar({
}
};
- // The open chat is an automation-created Session: expand exactly its origin's folder in its
- // group, so the active row is never hidden inside a collapsed folder (mirrors the archived
- // expansion on archiving the open chat; archived wins, so an archived Session is left to
- // that folder). Auto-expansion fires ONCE per (grouping mode, active session): the ref guard
+ // The open chat is a background Session (one a program opened): expand the Background folder
+ // in its group, so the active row is never hidden inside a collapsed folder (mirrors the
+ // archived expansion on archiving the open chat; archived wins, so an archived Session is left
+ // to that folder). Auto-expansion fires ONCE per (grouping mode, active session): the ref guard
// keeps list mutations (status ticks, reloads) from re-opening a folder the user explicitly
// collapsed while that chat stays open. `sessions` must remain a dependency — the active
// session may not be in the list yet on first render, and the guard is only set once the
@@ -1192,7 +1189,7 @@ export function Sidebar({
const s = sessions.find((x) => x.sessionId === activeSessionId);
if (!s) return;
const category = sessionCategory(s);
- if (category === "active" || category === "archived") return;
+ if (category === null || category === "active" || category === "archived") return;
const guard = `${groupMode}\0${activeSessionId}`;
if (lastAutoExpandedRef.current === guard) return;
lastAutoExpandedRef.current = guard;
@@ -1344,16 +1341,14 @@ export function Sidebar({
forgetDeletedSessions([target]);
setDeletingSession(null);
// The deleted session was the one open: jump to this Agent's next conversation, otherwise
- // fall back to the chat home page. Auto-opened conversations are never archived (hidden by
- // default — landing there would look like the chat vanished into thin air) and never
- // subagent children (they belong to some other conversation).
+ // fall back to the chat home page. Only a person's conversation is auto-opened — never an
+ // archived one (hidden by default — landing there would look like the chat vanished into
+ // thin air) and never a background one (a program opened it; the user was not in it),
+ // the rule latestConversation follows.
if (activeSessionId === target.sessionId) {
- const rest = (byAgent.get(target.agentId) ?? []).filter((s) => {
- const category = sessionCategory(s);
- return (
- s.sessionId !== target.sessionId && (category === "active" || category === "schedule")
- );
- });
+ const rest = (byAgent.get(target.agentId) ?? []).filter(
+ (s) => s.sessionId !== target.sessionId && sessionCategory(s) === "active",
+ );
navigate(rest[0] ? `/chat/${rest[0].sessionId}` : "/chat");
}
} catch (e) {
@@ -1445,10 +1440,9 @@ export function Sidebar({
const openOne = targets.find((s) => s.sessionId === activeSessionId);
if (openOne !== undefined) {
const deleted = new Set(targets.map((s) => s.sessionId));
- const rest = (byAgent.get(openOne.agentId) ?? []).filter((s) => {
- const category = sessionCategory(s);
- return !deleted.has(s.sessionId) && (category === "active" || category === "schedule");
- });
+ const rest = (byAgent.get(openOne.agentId) ?? []).filter(
+ (s) => !deleted.has(s.sessionId) && sessionCategory(s) === "active",
+ );
navigate(rest[0] ? `/chat/${rest[0].sessionId}` : "/chat");
}
} catch (e) {
@@ -1724,10 +1718,10 @@ export function Sidebar({
background={sessionBackgroundTasks(s)}
scheduled={scheduledSessions.has(s.sessionId)}
pinned={pinnedSessions.has(s.sessionId)}
- // Pinning is an ACTIVE-list priority: folder rows (subagent / scheduled /
- // evaluations / archived) are ordered by last activity inside their folder and
- // never pass through orderSessionRows, so a pin there would write an id, light
- // the glyph, move nothing — and then shift the active list's drag partition.
+ // Pinning is an ACTIVE-list priority: folder rows (background / archived) are
+ // ordered by last activity inside their folder and never pass through
+ // orderSessionRows, so a pin there would write an id, light the glyph, move nothing
+ // — and then shift the active list's drag partition.
canPin={activeList}
// Last ACTIVITY, not creation: the server stamps lastActiveAt when a run
// starts and again when it ends, so a running row shows its run-start time
@@ -1798,14 +1792,13 @@ export function Sidebar({
};
/**
- * Collapsed-by-default lazy folder (subagent / scheduled / evaluations / archived): nothing is
- * fetched until the first expand, and once open the folder reveals and pages
- * independently with its own "More" and "show less" rows. Everything is driven by the
- * group's **own** exact server share (`totals` — the Agent's counts in agent mode, the
- * per-Workspace fold in workspace mode): the folder exists only while its share is
- * non-zero, the label shows that share, and "More" shows only while something of that
- * share is still hidden — an Agent's content in *other* Workspaces can never surface a
- * folder here.
+ * Collapsed-by-default lazy folder (background / archived): nothing is fetched until the
+ * first expand, and once open the folder reveals and pages independently with its own "More"
+ * and "show less" rows. Everything is driven by the group's **own** exact server share
+ * (`totals` — the Agent's counts in agent mode, the per-Workspace fold in workspace mode): the
+ * folder exists only while its share is non-zero, the label shows that share, and "More" shows
+ * only while something of that share is still hidden — an Agent's content in *other*
+ * Workspaces can never surface a folder here.
*
* The folder obeys the same display rule the active list does (revealPlan): one page
* of rows shows at a time and "More" reveals one page more, spending a fetch only when
@@ -1905,10 +1898,10 @@ export function Sidebar({
/**
* Expanded group body shared by both modes: active user rows (display-capped; "More"
- * reveals and loads further **active-only** pages — the folders below never feed it) +
- * the collapsed-by-default subagent / scheduled / evaluations / archived folders, each
- * loading on first expand and paging on its own. `totals` / `agentsFor` carry the group's
- * exact server share and its fetch fan-out set per category.
+ * reveals and loads further **active-only** pages — the folders below never feed it) + the
+ * collapsed-by-default background / archived folders, each loading on first expand and paging
+ * on its own. `totals` / `agentsFor` carry the group's exact server share and its fetch
+ * fan-out set per category.
*/
const renderGroupBody = (
groupKey: string,
@@ -2022,9 +2015,9 @@ export function Sidebar({
/>
)}
- {/* Folders (collapsed by default): subagent first — spawned from the conversations
- at hand — then scheduled background runs, then the Evaluation Center's runs, then
- archived (archived wins over the origin folders). */}
+ {/* Folders (collapsed by default): Background — what programs opened (API,
+ scheduled, subagent and CLI Sessions), each row marked with its source — then
+ Archived (archived wins over the source). */}
{folders}
</>
);
@@ -3295,11 +3288,13 @@ function SidebarSessionRow({
active={active}
archived={s.archived}
{...(agentHint !== undefined ? { agent: { id: s.agentId, name: agentHint } } : {})}
- // Four marks for the row's STANDING arrangements, all in one dim cluster: how the row is
- // filed (pinned — only where pinning reorders anything), where it can be reached from (the
- // messaging relay, named by its channel), whether it runs on its own (a scheduled task still
- // to fire; a paused or ended one draws nothing) and whether it owns work that outlives the
- // turn (background tasks, live via session_background).
+ // The marks for the row's STANDING arrangements, all in one dim cluster: which program
+ // opened it (a Background row's source), how the row is filed (pinned — only where pinning
+ // reorders anything), where it can be reached from (the messaging relay, named by its
+ // channel), whether it runs on its own (a scheduled task still to fire; a paused or ended
+ // one draws nothing) and whether it owns work that outlives the turn (background tasks,
+ // live via session_background).
+ {...(backgroundSourceMark(s) ?? {})}
{...(pinned && canPin ? { pinnedLabel: S.chat.pinnedSession } : {})}
{...(s.messagingChannel !== undefined
? { relayLabel: S.messaging.enabledIndicator[s.messagingChannel] }
diff --git a/packages/web/src/features/benchmark/use-benchmark-modal.tsx b/packages/web/src/features/benchmark/use-benchmark-modal.tsx
index 4ac92de2..9cab154b 100644
--- a/packages/web/src/features/benchmark/use-benchmark-modal.tsx
+++ b/packages/web/src/features/benchmark/use-benchmark-modal.tsx
@@ -18,7 +18,7 @@
* what that agent's baseline recorded, so scores stay comparable. Mounted fresh per Benchmark.
*
* The conversation is an ordinary Session, listed with the agent's own: only the Test Sessions
- * it starts through `penguin run --source benchmark` are filed under the Evaluations folder.
+ * it starts through `penguin run` (CLI Sessions) are filed under the Background folder.
*/
import { useEffect, useState } from "react";
import type {
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 6c082870..88d5eb64 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -888,10 +888,10 @@ export function ChatPage() {
]);
// Auto-select the last conversation when the route doesn't select one: the most recently
- // ACTIVE loaded active/schedule Session, the same rule the collapsed rail's entry follows —
- // archived rows are hidden by choice and subagent Sessions belong to their parent, so
- // neither is auto-opened. If there is none, fall back to draft state (instead of
- // auto-creating one).
+ // ACTIVE loaded conversation of the user's own (`user` source), the same rule the collapsed
+ // rail's entry follows — archived rows are hidden by choice and background Sessions were
+ // opened by a program, so neither is auto-opened. If there is none, fall back to draft state
+ // (instead of auto-creating one).
useEffect(() => {
if (sessionsLoading || draft) return;
if (selected !== null) return;
diff --git a/packages/web/src/features/traces/trace-event-row.tsx b/packages/web/src/features/traces/trace-event-row.tsx
index d3a8e796..d4893bd5 100644
--- a/packages/web/src/features/traces/trace-event-row.tsx
+++ b/packages/web/src/features/traces/trace-event-row.tsx
@@ -209,7 +209,8 @@ const summaryClass =
function SessionMetaBody({ p }: { p: Record<string, unknown> }) {
const rows: Array<[string, string]> = [
["session_id", String(p.session_id ?? "")],
- // Session origin (subagent / schedule); user-created sessions have no source and show the empty dash.
+ // The Session's source as the record carries it; a Trace from before the source was
+ // required has none and shows the empty dash.
["source", String(p.source ?? "")],
["model_id", String(p.model_id ?? "")],
["context_window", String(p.model_context_window ?? "")],
diff --git a/packages/web/src/lib/omni/stream-model.ts b/packages/web/src/lib/omni/stream-model.ts
index 7e1c73d0..e53491f7 100644
--- a/packages/web/src/lib/omni/stream-model.ts
+++ b/packages/web/src/lib/omni/stream-model.ts
@@ -53,6 +53,7 @@
import {
isEventMessage,
isPartialPayload,
+ normalizeSessionSource,
parseBackgroundTaskDoneMessage,
parseUserSteeringText,
} from "@lmliheng/penguin-core/omnimessage";
@@ -65,6 +66,7 @@ import type {
OmniMessage,
PartialModelPayload,
SessionMetaPayload,
+ SessionSource,
StopReason,
TokenUsagePayload,
} from "@lmliheng/penguin-core/omnimessage";
@@ -488,8 +490,8 @@ export interface NestedSessionMeta {
agentId: string | null;
provider: string;
modelId: string;
- /** Session origin as recorded by core (subagent / schedule / benchmark); absent = user-created. */
- source?: "subagent" | "schedule" | "benchmark";
+ /** What kind of conversation the child is, as its meta records it (narrowed: an old Trace's missing source reads as `user`, `benchmark` as `cli`). */
+ source: SessionSource;
}
export interface StreamModel {
@@ -803,13 +805,13 @@ export function pushMessage(
}
if (msg.type === "session_meta" && model.nested) {
const p = msg.payload as SessionMetaPayload;
- const meta: NestedSessionMeta = {
+ model.meta = {
agentId: agentIdFromStatePath(p.agent_state),
provider: p.provider,
modelId: p.model_id,
+ // Replayed from the child's own Trace, which may predate the required source.
+ source: normalizeSessionSource(p.source),
};
- if (p.source !== undefined) meta.source = p.source;
- model.meta = meta;
}
}
diff --git a/packages/web/src/lib/session-grouping.ts b/packages/web/src/lib/session-grouping.ts
index 4f8567ce..7ef67d71 100644
--- a/packages/web/src/lib/session-grouping.ts
+++ b/packages/web/src/lib/session-grouping.ts
@@ -301,18 +301,19 @@ export function splitPage<T>(fetched: T[], pageSize: number): { items: T[]; hasM
}
/**
- * The sidebar category a Session renders under — the same precedence the server's
- * `category` list filter applies, so filtered fetching and client rendering can never
- * disagree: archived wins regardless of `source` (archiving is an explicit user action,
- * so the Archived folder must show everything the user put there); otherwise a Session
- * goes to its origin's bucket, and no (or an unrecognized future) source falls through
- * to the active user rows (visible) rather than vanishing into the wrong folder.
- */
-export function sessionCategory(s: SessionInfo): SessionCategory {
+ * The sidebar category a Session renders under — the same rule the server's `category`
+ * list filter applies, so filtered fetching and client rendering can never disagree. A
+ * company Session (company mode's desk and ticket Sessions) is in none, archived or not: only
+ * company mode's own views list it. Otherwise archived wins regardless of `source` (archiving
+ * is an explicit user action, so the Archived folder must show everything the user put there);
+ * then a person's conversation (`user`, or a row the server has not classified yet) is active,
+ * and every other source — API, scheduled, subagent and CLI Sessions — goes to the Background
+ * folder.
+ */
+export function sessionCategory(s: SessionInfo): SessionCategory | null {
+ if (s.source === "company") return null;
if (s.archived) return "archived";
- return s.source === "subagent" || s.source === "schedule" || s.source === "benchmark"
- ? s.source
- : "active";
+ return s.source === undefined || s.source === "user" ? "active" : "background";
}
/**
@@ -327,34 +328,34 @@ export function matchesSessionQuery(s: SessionInfo, query: string): boolean {
}
/** The collapsed-folder categories of a group, in render order (below the active user rows). */
-export const FOLDER_CATEGORIES = ["subagent", "schedule", "benchmark", "archived"] as const;
+export const FOLDER_CATEGORIES = ["background", "archived"] as const;
export type FolderCategory = (typeof FOLDER_CATEGORIES)[number];
/**
- * Five-way split of one sidebar group's Sessions by sessionCategory (rendered top to
+ * Three-way split of one sidebar group's Sessions by sessionCategory (rendered top to
* bottom in this order): active user rows in the group body, then the collapsed
- * Subagents / Scheduled / Evaluations / Archived folders.
+ * Background and Archived folders.
*/
export type SessionPartition = Record<SessionCategory, SessionInfo[]>;
-/** Partitions a group's Sessions for rendering. Input order is preserved within each part. */
+/**
+ * Partitions a group's Sessions for rendering. Input order is preserved within each part; a
+ * company Session, in no category, is in no part.
+ */
export function partitionSessions(sessions: SessionInfo[]): SessionPartition {
- const parts: SessionPartition = {
- active: [],
- subagent: [],
- schedule: [],
- benchmark: [],
- archived: [],
- };
- for (const s of sessions) parts[sessionCategory(s)].push(s);
+ const parts: SessionPartition = { active: [], background: [], archived: [] };
+ for (const s of sessions) {
+ const category = sessionCategory(s);
+ if (category !== null) parts[category].push(s);
+ }
return parts;
}
/**
- * A group's FOLDED share: the conversations its collapsed folders hold (Subagents /
- * Scheduled / Evaluations / Archived), summed from one set of category counts. Missing
- * keys count as zero rather than poisoning the sum with NaN — the guard
- * aggregateWorkspaceCounts applies to the same numbers.
+ * A group's FOLDED share: the conversations its collapsed folders hold (Background /
+ * Archived), summed from one set of category counts. Missing keys count as zero rather than
+ * poisoning the sum with NaN — the guard aggregateWorkspaceCounts applies to the same
+ * numbers.
*/
export function foldedShare(counts: SessionCategoryCounts): number {
let total = 0;
@@ -404,8 +405,8 @@ export function aggregateWorkspaceCounts(
let group = out.get(key);
if (!group) {
group = {
- totals: { active: 0, subagent: 0, schedule: 0, benchmark: 0, archived: 0 },
- agents: { active: [], subagent: [], schedule: [], benchmark: [], archived: [] },
+ totals: { active: 0, background: 0, archived: 0 },
+ agents: { active: [], background: [], archived: [] },
};
out.set(key, group);
}
@@ -425,20 +426,17 @@ export function aggregateWorkspaceCounts(
/**
* The Session the UI opens as "the last conversation" (the chat home's auto-select and
* the collapsed rail's entry): the loaded row the user was last IN — not the one created
- * last, which on a revisited conversation is a different row. Archived rows are hidden by
- * choice, a subagent Session is a child of some other conversation, and a benchmark Session is
- * an evaluator's Test Session rather than a conversation of the user's (the evaluate / optimize
- * conversation they just sent is already the one on screen), so none of the three is ever
- * auto-opened; schedule-created runs are the user's conversations and qualify. Newest by
- * lastActiveAt (stamped from `Date#toISOString`, so uniform ISO-8601 UTC like createdAt and
- * comparable as a string), ties broken by sessionId — the list's ordering convention. Input
- * order doesn't matter.
+ * last, which on a revisited conversation is a different row. Only a person's conversation
+ * (an active row) qualifies: archived rows are hidden by choice, and neither a background
+ * Session — one an API caller, a scheduled task, a parent agent or `penguin run` opened — nor a
+ * company Session is a conversation of this list the user was in. Newest by lastActiveAt (stamped from `Date#toISOString`, so
+ * uniform ISO-8601 UTC like createdAt and comparable as a string), ties broken by sessionId —
+ * the list's ordering convention. Input order doesn't matter.
*/
export function latestConversation(sessions: readonly SessionInfo[]): SessionInfo | null {
let best: SessionInfo | null = null;
for (const s of sessions) {
- const category = sessionCategory(s);
- if (category !== "active" && category !== "schedule") continue;
+ if (sessionCategory(s) !== "active") continue;
if (
!best ||
s.lastActiveAt > best.lastActiveAt ||
@@ -604,10 +602,10 @@ const MONTH_MS = 30 * DAY_MS;
export const timeGroupKey = (bucket: TimeBucket): string => `\0time-${bucket}`;
/**
- * Group key the folders (Subagents / Scheduled / Evaluations / Archived) hang off in time
- * mode. They are NOT bucketed: their rows load only when a folder is first expanded, so an
- * unloaded Session's bucket is unknown and no bucket could honestly advertise a share of
- * them. One shared, Project-wide set below the buckets is what the sidebar renders instead.
+ * Group key the folders (Background / Archived) hang off in time mode. They are NOT bucketed:
+ * their rows load only when a folder is first expanded, so an unloaded Session's bucket is
+ * unknown and no bucket could honestly advertise a share of them. One shared, Project-wide set
+ * below the buckets is what the sidebar renders instead.
*/
export const TIME_FOLDERS_GROUP_KEY = "\0time-folders";
@@ -661,13 +659,7 @@ export function groupSessionsByTime<T extends ActivityKey>(
export function totalCategoryCounts(
byAgent: ReadonlyMap<string, SessionCategoryCounts>,
): SessionCategoryCounts {
- const totals: SessionCategoryCounts = {
- active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- };
+ const totals: SessionCategoryCounts = { active: 0, background: 0, archived: 0 };
for (const counts of byAgent.values()) {
for (const category of ALL_CATEGORIES) {
const n = counts[category];
@@ -697,17 +689,19 @@ export function pinnedFirst<T>(
}
/**
- * The two marks a Session an organization owns can carry — a desk session of one of its
+ * The marks a Session an organization owns can carry — a desk session of one of its
* employees, or a session contributing to one of its tickets. `client` is stamped on the row
- * when the organization runtime creates the Session and never changes; `orgId` is resolved per
- * read from the organization's own caches. Both are optional on the wire, and a row is an
- * organization's when either says so.
+ * when the organization runtime creates the Session and never changes, and a Session it opened
+ * is a `company` Session; `orgId` is resolved per read from the organization's own caches. All
+ * are optional on the wire, and a row is an organization's when any says so.
*/
export interface OrgSessionMarks {
/** The owning organization, resolved per read; absent once the organization is deleted. */
orgId?: string;
/** The client that created the Session; "org" is the organization runtime's own stamp. */
client?: string;
+ /** What kind of conversation it is; "company" for a desk or ticket Session. */
+ source?: string;
}
/**
@@ -716,7 +710,11 @@ export interface OrgSessionMarks {
* longer hold the Session, and the row would otherwise reappear somewhere it never belonged.
*/
export function isOrgSession(row: OrgSessionMarks): boolean {
- return (row.orgId !== undefined && row.orgId !== "") || row.client === "org";
+ return (
+ (row.orgId !== undefined && row.orgId !== "") ||
+ row.client === "org" ||
+ row.source === "company"
+ );
}
/**
diff --git a/packages/web/src/lib/session-source-mark.ts b/packages/web/src/lib/session-source-mark.ts
new file mode 100644
index 00000000..ca13fce9
--- /dev/null
+++ b/packages/web/src/lib/session-source-mark.ts
@@ -0,0 +1,40 @@
+/**
+ * The source mark a row of the sidebar's Background folder carries: which program opened the
+ * Session (the Agent API, a scheduled task, a parent agent or `penguin run`), as a registry
+ * glyph and the tooltip that names it.
+ *
+ * A scheduled task's run takes the calendar, not the alarm clock: the alarm is the separate mark
+ * of a scheduled task still to fire into a conversation (the row's `scheduledLabel`), and one
+ * row must never show two alarms that mean different things.
+ */
+import type { SessionInfo, SessionSource } from "@lmliheng/penguin-server/api";
+import { ICONS } from "@lmliheng/penguin-ui";
+import { sessionCategory } from "./session-grouping";
+import { S } from "./strings";
+
+/** The sources the Background folder holds: a person's and a company Session are never in it. */
+type BackgroundSource = Exclude<SessionSource, "user" | "company">;
+
+const SOURCE_GLYPHS: Record<BackgroundSource, string> = {
+ api: ICONS.plug,
+ schedule: ICONS.calendar,
+ subagent: ICONS.robotPair,
+ cli: ICONS.terminalPrompt,
+};
+
+/** A row's source mark, as `SessionRow` takes it. */
+export interface SourceMark {
+ sourceGlyph: string;
+ sourceLabel: string;
+}
+
+/** The mark of a row in the Background folder; null for any other row. */
+export function backgroundSourceMark(s: SessionInfo): SourceMark | null {
+ const source = s.source;
+ if (sessionCategory(s) !== "background" || !isBackgroundSource(source)) return null;
+ return { sourceGlyph: SOURCE_GLYPHS[source], sourceLabel: S.chat.sessionSource[source] };
+}
+
+function isBackgroundSource(source: SessionSource | undefined): source is BackgroundSource {
+ return source !== undefined && source !== "user" && source !== "company";
+}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index eff3427a..db51ed82 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -3368,11 +3368,15 @@ export const en: Strings = {
loadMoreSessions: "Load more chats",
/** Collapsed sidebar folders inside a group (lazy-loaded); the count is the group's exact server share. */
folderGroups: {
- subagent: (n: number) => `Subagents (${n})`,
- schedule: (n: number) => `Scheduled (${n})`,
- benchmark: (n: number) => `Evaluations (${n})`,
+ background: (n: number) => `Background (${n})`,
archived: (n: number) => `Archived (${n})`,
},
+ sessionSource: {
+ api: "API",
+ schedule: "Scheduled",
+ subagent: "Subagent",
+ cli: "CLI",
+ },
/** Tooltip of a folder-only group's header (nothing active of its own): what its folders hold, plus the Workspace path where the header has one. */
folderOnlyGroup: (n: number, path?: string) =>
`Folded tasks only: ${n} conversation${n === 1 ? "" : "s"}${path ? ` (${path})` : ""}`,
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 313982a1..dbab4a19 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -3412,11 +3412,16 @@ export const zh = {
loadMoreSessions: "加载更多会话",
/** Collapsed sidebar folders inside a group (lazy-loaded); the count is the group's exact server share. */
folderGroups: {
- subagent: (n: number) => `子智能体(${n})`,
- schedule: (n: number) => `定时任务(${n})`,
- benchmark: (n: number) => `评估任务(${n})`,
+ background: (n: number) => `后台会话(${n})`,
archived: (n: number) => `已归档(${n})`,
},
+ /** A Background row's source mark: the program that opened the Session, as its tooltip and hidden text. */
+ sessionSource: {
+ api: "API",
+ schedule: "定时任务",
+ subagent: "子智能体",
+ cli: "CLI",
+ },
/**
* Tooltip of a folder-only group's header — a group with no active conversation of its
* own, only rows inside its folders (it renders collapsed and sorts last). `n` is what
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index eaf1fa3a..05b19d03 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -4,8 +4,9 @@
* the chat page shares this same data for status sync / title events / self-healing reload.
*
* **Paged per (Agent, category)**: the default load fetches only the **active** category
- * (user-created, non-archived) plus per-category totals — archived / subagent / schedule /
- * benchmark Sessions are not loaded until their collapsed folder is opened. Each pair fetches
+ * (a person's conversations, non-archived) plus per-category totals — background (API,
+ * scheduled, subagent and CLI) and archived Sessions are not loaded until their collapsed
+ * folder is opened. Each pair fetches
* SIDEBAR_PAGE_SIZE sessions per page (requesting one extra to detect "has more" — see
* splitPage); `loadMoreFor` fetches a pair's first page when unloaded and the next page
* otherwise, so every category's paging is independent of the others. A reload resets each
@@ -22,8 +23,9 @@
* sidebar cuts at it), so a later page can only ever add rows below the ones on screen.
*
* **Own rows only**: every fetch asks the server for the user's own conversations
- * (`excludeOrg`), so an organization's desk, ticket and sub-sessions are in neither the rows
- * nor the totals the sidebar builds its groups from. One can still enter through `add()` (the
+ * (`excludeOrg`), and no category holds a company Session anyway, so an organization's desk,
+ * ticket and sub-sessions are in neither the rows nor the totals the sidebar builds its groups
+ * from. One can still enter through `add()` (the
* chat page's deep-link self-heal): the sidebar drops it at render (withoutOrgSessions), the
* totals are left alone for it, and a reload carries it over. Live statuses are remembered for
* EVERY `session_state` the user channel reports (`liveStatuses`), row or no row — company
@@ -466,12 +468,12 @@ export function createSessionsStore() {
/**
* Keeps an Agent's category totals — overall and per Workspace — in step with a local
* list mutation of `session` (no-op while its counts are unknown). An organization's row
- * never moves them: the server's totals are the user's own rows only (`excludeOrg`), so
- * such a row — held for the page that deep-linked it — was never counted and must not be
- * counted out.
+ * never moves them: the server's totals are the user's own rows only (`excludeOrg`), and a
+ * company Session is in no category, so such a row — held for the page that deep-linked
+ * it — was never counted and must not be counted out.
*/
- const adjustCount = (session: SessionInfo, category: SessionCategory, delta: number) => {
- if (isOrgSession(session)) return;
+ const adjustCount = (session: SessionInfo, category: SessionCategory | null, delta: number) => {
+ if (category === null || isOrgSession(session)) return;
const { agentId, workspace } = session;
const counts = get().countsByAgent;
const cur = counts.get(agentId);
@@ -486,13 +488,7 @@ export function createSessionsStore() {
// Keyed by GROUP, as the fetch stores them: the badge belongs to the directory on
// the machine this Session is on, not to every machine holding that path string.
const key = workspaceGroupKey(workspace, machineForSession(session.sessionId));
- const ws = wsCur[key] ?? {
- active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- };
+ const ws = wsCur[key] ?? { active: 0, background: 0, archived: 0 };
const next = new Map(workspaceCounts);
next.set(agentId, {
...wsCur,
@@ -517,6 +513,7 @@ export function createSessionsStore() {
const category = sessionCategory(session);
if (
!existed &&
+ category !== null &&
get().pageState.get(pageKey(session.agentId, category, "", source))?.hasMore === false
) {
adjustCount(session, category, 1);
diff --git a/packages/web/test/draft-cache.test.ts b/packages/web/test/draft-cache.test.ts
index 8da2d438..305aedf3 100644
--- a/packages/web/test/draft-cache.test.ts
+++ b/packages/web/test/draft-cache.test.ts
@@ -6,7 +6,8 @@
* draft, wrongly typed, unknown or half fields are dropped and the rest kept (the permission
* picks, the paired model references, the AI-prefill mark only as true, the approval mode's
* four values, the skills list); a legacy string model id is always dropped, and so is the
- * evaluation mark an earlier release saved with an Evaluation Center draft.
+ * evaluation mark (`source: "benchmark"`) an earlier release saved with an Evaluation Center
+ * draft, so the conversation such a draft creates is an ordinary one.
* - Saved drafts read back equal; Project and Session drafts, and two users' drafts of the
* same Project, never read or overwrite each other (#68); a cleared draft reads as empty.
* - Dropping the model pin keeps everything else; dropping the `[default_chat]`-seeded
diff --git a/packages/web/test/group-order.test.ts b/packages/web/test/group-order.test.ts
index 6c54a8ac..1a02b905 100644
--- a/packages/web/test/group-order.test.ts
+++ b/packages/web/test/group-order.test.ts
@@ -374,12 +374,12 @@ describe("folder-only groups sort last (demote)", () => {
});
it("is folder-only when the active share is zero and something is folded away", () => {
- // One Workspace of an evaluation: a single Test Session, inside the Evaluations folder.
- const evaluation = { active: 0, subagent: 0, schedule: 0, benchmark: 1, archived: 0 };
+ // One Workspace of an evaluation: a single Test Session, inside the Background folder.
+ const evaluation = { active: 0, background: 1, archived: 0 };
expect(foldedShare(evaluation)).toBe(1);
expect(isFolderOnly(0, foldedShare(evaluation))).toBe(true);
// Every folded category counts; the active one never does.
- const mixed = { active: 7, subagent: 2, schedule: 1, benchmark: 3, archived: 4 };
+ const mixed = { active: 7, background: 6, archived: 4 };
expect(foldedShare(mixed)).toBe(10);
// A registered but still unused Workspace has nothing folded away to fold up …
expect(isFolderOnly(0, 0)).toBe(false);
diff --git a/packages/web/test/new-chat.test.ts b/packages/web/test/new-chat.test.ts
index a2dd6d98..8311e1d2 100644
--- a/packages/web/test/new-chat.test.ts
+++ b/packages/web/test/new-chat.test.ts
@@ -5,8 +5,8 @@
* - The new chat starts on the Project's default Agent while it names a listed Agent, else
* default_agent wherever it sits, else the first Agent, else none.
* - Preparing the draft parks typed text with its selections, then leaves only the model
- * carry-over and staged skills in the active slot: a text-less draft's other selections
- * are released, a slot holding nothing it keeps is emptied, and an empty slot is left alone.
+ * carry-over and staged skills in the active slot: a text-less draft's other selections are
+ * released, a slot holding nothing it keeps is emptied, and an empty slot is left alone.
*/
import { describe, expect, it } from "vitest";
import type { AgentSummary } from "@lmliheng/penguin-server/api";
diff --git a/packages/web/test/pinned-sessions.test.ts b/packages/web/test/pinned-sessions.test.ts
index ad50c844..b94719ac 100644
--- a/packages/web/test/pinned-sessions.test.ts
+++ b/packages/web/test/pinned-sessions.test.ts
@@ -143,7 +143,7 @@ describe("pinned ordering composes with the group lists", () => {
expect(active.map((s) => s.sessionId)).toEqual(["s3", "s1", "s2"]);
// Folder rows keep chronological order and membership regardless of pins …
expect(parts.archived.map((s) => s.sessionId)).toEqual(["s4"]);
- expect(parts.subagent.map((s) => s.sessionId)).toEqual(["s5"]);
+ expect(parts.background.map((s) => s.sessionId)).toEqual(["s5"]);
// … and a stored id of a Session deleted elsewhere never surfaces a row.
expect(active.some((s) => s.sessionId === "deleted-elsewhere")).toBe(false);
});
diff --git a/packages/web/test/session-grouping.test.ts b/packages/web/test/session-grouping.test.ts
index 56f95fbc..6d90b500 100644
--- a/packages/web/test/session-grouping.test.ts
+++ b/packages/web/test/session-grouping.test.ts
@@ -10,11 +10,12 @@
* - Grouping by Workspace merges Agents on one path (newest Session first, newest group first),
* folds every temporary Workspace into one trailing group per machine, keeps one path on two
* machines apart, and keeps archived rows in their group.
- * - A Session's folder is decided by archived first, then its source; partitioning keeps the
- * order inside each folder, and the Test Sessions an evaluation starts get a folder of their
- * own while the evaluation conversation stays an active row.
- * - The auto-opened "last conversation" is the most recently active user or scheduled row
- * (ties by id), never an archived, subagent or benchmark one.
+ * - A Session's folder is decided by archived first, then its source: a person's conversation
+ * (`user`, or not yet classified) is active, every other source goes to Background;
+ * partitioning keeps the order inside each folder. A company Session, archived or not, is in
+ * no category and no part.
+ * - The auto-opened "last conversation" is the most recently active person's conversation
+ * (ties by id), never an archived, a background (scheduled ones included) or a company one.
* - A page fetched with one extra row reports whether the server has more, never showing it.
* - Server counts sum per Workspace across Agents (recording which Agents hold each folder) and
* stay apart per machine; the newest stamp per group survives aggregation.
@@ -37,7 +38,11 @@
* least a page more, or the rest.
*/
import { describe, expect, it } from "vitest";
-import type { SessionCategoryCounts, SessionInfo } from "@lmliheng/penguin-server/api";
+import type {
+ SessionCategoryCounts,
+ SessionInfo,
+ SessionSource,
+} from "@lmliheng/penguin-server/api";
import type { ActivityKey, StreamPosition } from "../src/lib/session-grouping";
import {
SIDEBAR_PAGE_SIZE,
@@ -78,7 +83,7 @@ function session(
sessionId?: string;
agentId?: string;
archived?: boolean;
- source?: "schedule" | "subagent" | "benchmark";
+ source?: SessionSource;
lastActiveAt?: string;
} = {},
): SessionInfo {
@@ -265,79 +270,90 @@ describe("groupSessionsByWorkspace", () => {
});
describe("sessionCategory (the bucket a Session renders under = the server's list filter)", () => {
- it("archived wins over source; a source names its bucket; no source is active", () => {
- const at = "2026-07-01T10:00:00.000Z";
+ const at = "2026-07-01T10:00:00.000Z";
+
+ it.each(["api", "schedule", "subagent", "cli"] as const)(
+ "files a %s Session under Background",
+ (source) => {
+ expect(sessionCategory(session("/srv/a", at, { source }))).toBe("background");
+ },
+ );
+
+ it("files a person's conversation, and a row not yet classified, as active", () => {
+ expect(sessionCategory(session("/srv/a", at, { source: "user" }))).toBe("active");
expect(sessionCategory(session("/srv/a", at))).toBe("active");
- expect(sessionCategory(session("/srv/a", at, { source: "subagent" }))).toBe("subagent");
- expect(sessionCategory(session("/srv/a", at, { source: "schedule" }))).toBe("schedule");
+ });
+
+ it("files an archived Session as archived, whatever its source", () => {
expect(sessionCategory(session("/srv/a", at, { archived: true }))).toBe("archived");
- expect(sessionCategory(session("/srv/a", at, { source: "subagent", archived: true }))).toBe(
+ expect(sessionCategory(session("/srv/a", at, { source: "cli", archived: true }))).toBe(
"archived",
);
});
-});
-describe("partitionSessions (per-group user / subagent / scheduled / evaluations / archived split)", () => {
- it("splits user rows and one bucket per origin, preserving order within each part", () => {
- const user1 = session("/srv/alpha", "2026-07-06T10:00:00.000Z");
- const sched1 = session("/srv/alpha", "2026-07-05T10:00:00.000Z", { source: "schedule" });
- const sub1 = session("/srv/alpha", "2026-07-04T10:00:00.000Z", { source: "subagent" });
- const user2 = session("/srv/alpha", "2026-07-03T10:00:00.000Z");
- const sub2 = session("/srv/alpha", "2026-07-02T10:00:00.000Z", { source: "subagent" });
- const gone = session("/srv/alpha", "2026-07-01T10:00:00.000Z", { archived: true });
- const parts = partitionSessions([user1, sched1, sub1, user2, sub2, gone]);
- expect(parts.active.map((s) => s.sessionId)).toEqual([user1.sessionId, user2.sessionId]);
- expect(parts.subagent.map((s) => s.sessionId)).toEqual([sub1.sessionId, sub2.sessionId]);
- expect(parts.schedule.map((s) => s.sessionId)).toEqual([sched1.sessionId]);
- expect(parts.archived.map((s) => s.sessionId)).toEqual([gone.sessionId]);
+ it("files a company Session under no category, archived or not", () => {
+ expect(sessionCategory(session("/srv/a", at, { source: "company" }))).toBeNull();
+ expect(
+ sessionCategory(session("/srv/a", at, { source: "company", archived: true })),
+ ).toBeNull();
});
+});
- it("archived wins over source: an archived automation-created session goes to the Archived folder only", () => {
- const sub = session("/srv/alpha", "2026-07-01T10:00:00.000Z", {
- source: "subagent",
+describe("partitionSessions (per-group active / Background / Archived split)", () => {
+ it("splits active rows from the Background and Archived folders, preserving order within each part, and puts company rows in none", () => {
+ const user1 = session("/srv/alpha", "2026-07-06T10:00:00.000Z", { source: "user" });
+ const sched = session("/srv/alpha", "2026-07-05T10:00:00.000Z", { source: "schedule" });
+ const sub = session("/srv/alpha", "2026-07-04T10:00:00.000Z", { source: "subagent" });
+ const user2 = session("/srv/alpha", "2026-07-03T10:00:00.000Z");
+ const cli = session("/srv/alpha", "2026-07-02T10:00:00.000Z", { source: "cli" });
+ const gone = session("/srv/alpha", "2026-07-01T10:00:00.000Z", {
+ source: "api",
archived: true,
});
- const sched = session("/srv/alpha", "2026-07-02T10:00:00.000Z", {
- source: "schedule",
+ // Company mode's desk, live and archived: in no part at all.
+ const desk = session("/srv/alpha", "2026-07-05T12:00:00.000Z", { source: "company" });
+ const oldDesk = session("/srv/alpha", "2026-06-30T10:00:00.000Z", {
+ source: "company",
archived: true,
});
- const parts = partitionSessions([sub, sched]);
- expect(parts.subagent).toEqual([]);
- expect(parts.schedule).toEqual([]);
- expect(parts.archived.map((s) => s.sessionId)).toEqual([sub.sessionId, sched.sessionId]);
- expect(parts.active).toEqual([]);
- });
-
- it("empty input yields five empty parts", () => {
- expect(partitionSessions([])).toEqual({
- active: [],
- subagent: [],
- schedule: [],
- benchmark: [],
- archived: [],
- });
+ const parts = partitionSessions([user1, desk, sched, sub, user2, cli, gone, oldDesk]);
+ expect(parts.active.map((s) => s.sessionId)).toEqual([user1.sessionId, user2.sessionId]);
+ expect(parts.background.map((s) => s.sessionId)).toEqual([
+ sched.sessionId,
+ sub.sessionId,
+ cli.sessionId,
+ ]);
+ expect(parts.archived.map((s) => s.sessionId)).toEqual([gone.sessionId]);
+ expect(Object.values(parts).flat()).toHaveLength(6);
});
});
describe("latestConversation (the auto-opened 'last conversation')", () => {
- it("picks the most recently active active/schedule row regardless of input order; archived and subagent rows never win", () => {
+ it("picks the most recently active person's conversation regardless of input order; archived and background rows never win", () => {
// Created first but returned to since: this is the conversation the user was last in,
// and the one created last is not.
const revisited = session("/srv/a", "2026-07-01T10:00:00.000Z", {
lastActiveAt: "2026-07-06T10:00:00.000Z",
});
- const newerUntouched = session("/srv/a", "2026-07-03T10:00:00.000Z");
- // Active more recently than every conversation, but never auto-opened:
+ const newerUntouched = session("/srv/a", "2026-07-03T10:00:00.000Z", { source: "user" });
+ // Active more recently than every conversation, but never auto-opened — a scheduled run
+ // included: a program opened it, and the user was not in it.
const subAfter = session("/srv/a", "2026-07-08T10:00:00.000Z", { source: "subagent" });
+ const schedAfter = session("/srv/a", "2026-07-07T10:00:00.000Z", { source: "schedule" });
const goneAfter = session("/srv/a", "2026-07-09T10:00:00.000Z", { archived: true });
- expect(latestConversation([subAfter, newerUntouched, goneAfter, revisited])).toBe(revisited);
+ expect(latestConversation([subAfter, schedAfter, newerUntouched, goneAfter, revisited])).toBe(
+ revisited,
+ );
+ });
- // A schedule-created run is the user's conversation: the most recently active one qualifies.
- const schedAfter = session("/srv/a", "2026-07-05T10:00:00.000Z", {
- lastActiveAt: "2026-07-07T10:00:00.000Z",
- source: "schedule",
+ it("never picks a company Session, however recently its desk ran", () => {
+ const mine = session("/srv/a", "2026-07-01T10:00:00.000Z");
+ const desk = session("/srv/a", "2026-07-02T10:00:00.000Z", {
+ source: "company",
+ lastActiveAt: "2026-07-10T10:00:00.000Z",
});
- expect(latestConversation([revisited, schedAfter, subAfter])).toBe(schedAfter);
+ expect(latestConversation([desk, mine])).toBe(mine);
+ expect(latestConversation([desk])).toBeNull();
});
it("ties on lastActiveAt break by sessionId, and no qualifying row yields null", () => {
@@ -347,21 +363,7 @@ describe("latestConversation (the auto-opened 'last conversation')", () => {
expect(latestConversation([a, b])).toBe(b);
expect(latestConversation([b, a])).toBe(b);
expect(latestConversation([])).toBeNull();
- expect(latestConversation([session("/srv/a", at, { source: "subagent" })])).toBeNull();
- });
-});
-
-describe("benchmark Sessions (the Test Sessions an evaluation starts)", () => {
- it("files a Test Session into the Evaluations folder and never auto-opens it, while the evaluation conversation stays an active row", () => {
- // The conversation the Evaluation Center's Use dialog opened carries no source; the Test
- // Session it launched for a Case × Run (`penguin run --source benchmark`) ran after it.
- const evaluation = session("/srv/a", "2026-07-02T10:00:00.000Z");
- const run = session("/srv/a", "2026-07-08T10:00:00.000Z", { source: "benchmark" });
- const parts = partitionSessions([run, evaluation]);
- expect(parts.benchmark.map((s) => s.sessionId)).toEqual([run.sessionId]);
- expect(parts.active.map((s) => s.sessionId)).toEqual([evaluation.sessionId]);
- // The conversation the user was last in is the evaluation they sent, not a run it launched.
- expect(latestConversation([run, evaluation])).toBe(evaluation);
+ expect(latestConversation([session("/srv/a", at, { source: "cli" })])).toBeNull();
});
});
@@ -379,39 +381,27 @@ describe("splitPage (limit+1 fetch trick)", () => {
});
describe("aggregateWorkspaceCounts (per-group exact server share)", () => {
- const zero = { active: 0, subagent: 0, schedule: 0, benchmark: 0, archived: 0 };
+ const zero = { active: 0, background: 0, archived: 0 };
it("sums each Workspace path across Agents and records which Agents hold each category", () => {
const byAgent = new Map<string, Record<string, SessionCategoryCounts>>([
[
"agent_a",
{
- "/srv/alpha": { ...zero, active: 2, subagent: 1 },
+ "/srv/alpha": { ...zero, active: 2 },
"/srv/beta": { ...zero, archived: 3 },
},
],
- ["agent_b", { "/srv/alpha": { ...zero, active: 1, schedule: 2 } }],
+ ["agent_b", { "/srv/alpha": { ...zero, active: 1, background: 2 } }],
]);
const groups = aggregateWorkspaceCounts(byAgent);
expect(groups.get("/srv/alpha")).toEqual({
- totals: { active: 3, subagent: 1, schedule: 2, benchmark: 0, archived: 0 },
- agents: {
- active: ["agent_a", "agent_b"],
- subagent: ["agent_a"],
- schedule: ["agent_b"],
- benchmark: [],
- archived: [],
- },
+ totals: { active: 3, background: 2, archived: 0 },
+ agents: { active: ["agent_a", "agent_b"], background: ["agent_b"], archived: [] },
});
expect(groups.get("/srv/beta")).toEqual({
totals: { ...zero, archived: 3 },
- agents: {
- active: [],
- subagent: [],
- schedule: [],
- benchmark: [],
- archived: ["agent_a"],
- },
+ agents: { active: [], background: [], archived: ["agent_a"] },
});
// A group only in another Workspace never appears — its content can't surface elsewhere.
expect(groups.has("/srv/gamma")).toBe(false);
@@ -431,13 +421,7 @@ describe("aggregateWorkspaceCounts (per-group exact server share)", () => {
expect(groups.size).toBe(1);
expect(groups.get(TEMP_WORKSPACE_GROUP_KEY)).toEqual({
totals: { ...zero, active: 3, archived: 1 },
- agents: {
- active: ["agent_a"],
- subagent: [],
- schedule: [],
- benchmark: [],
- archived: ["agent_a"],
- },
+ agents: { active: ["agent_a"], background: [], archived: ["agent_a"] },
});
});
@@ -608,9 +592,7 @@ describe("groupSessionsByTime", () => {
describe("totalCategoryCounts", () => {
const counts = (over: Partial<SessionCategoryCounts>): SessionCategoryCounts => ({
active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
+ background: 0,
archived: 0,
...over,
});
@@ -620,20 +602,14 @@ describe("totalCategoryCounts", () => {
totalCategoryCounts(
new Map([
["a", counts({ active: 3, archived: 2 })],
- ["b", counts({ active: 4, subagent: 1 })],
+ ["b", counts({ active: 4, background: 1 })],
]),
),
- ).toEqual({ active: 7, subagent: 1, schedule: 0, benchmark: 0, archived: 2 });
+ ).toEqual({ active: 7, background: 1, archived: 2 });
});
it("reports zeros for an empty map rather than leaving fields undefined", () => {
- expect(totalCategoryCounts(new Map())).toEqual({
- active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
+ expect(totalCategoryCounts(new Map())).toEqual({ active: 0, background: 0, archived: 0 });
});
});
@@ -666,10 +642,10 @@ describe("aggregateWorkspaceLatest (per-group newest-Session stamp)", () => {
});
describe("completeWorkspaceGroups (every counted Workspace is a group, placed by recency)", () => {
- const zero = { active: 0, subagent: 0, schedule: 0, benchmark: 0, archived: 0 };
+ const zero = { active: 0, background: 0, archived: 0 };
const counted = (totals: Partial<SessionCategoryCounts>) => ({
totals: { ...zero, ...totals },
- agents: { active: [], subagent: [], schedule: [], benchmark: [], archived: [] },
+ agents: { active: [], background: [], archived: [] },
});
it("reads a machine-qualified count key as that machine's directory, not as a path", () => {
diff --git a/packages/web/test/session-source-mark.test.ts b/packages/web/test/session-source-mark.test.ts
new file mode 100644
index 00000000..8c7eee14
--- /dev/null
+++ b/packages/web/test/session-source-mark.test.ts
@@ -0,0 +1,76 @@
+/**
+ * The source mark a row of the sidebar's Background folder carries (lib/session-source-mark.ts).
+ *
+ * - Given a Background row (an API, scheduled, subagent or CLI Session), it carries one mark
+ * with a tooltip, and no two sources share a drawing or a name.
+ * - Given a person's conversation (`user`, or a row not yet classified), a company Session or
+ * an archived row of any source, it carries no source mark.
+ * - Given a scheduled task's Session, its mark is not the alarm clock: that mark belongs to a
+ * task still to fire into a conversation, and one row must not show two alarms.
+ * - In English, no mark falls back to a Chinese name.
+ */
+import { afterEach, describe, expect, it } from "vitest";
+import type { SessionInfo, SessionSource } from "@lmliheng/penguin-server/api";
+import { ICONS } from "@lmliheng/penguin-ui";
+import { backgroundSourceMark } from "../src/lib/session-source-mark";
+import { setActiveStrings, zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+afterEach(() => setActiveStrings(zh));
+
+function session(over: { source?: SessionSource; archived?: boolean } = {}): SessionInfo {
+ return {
+ sessionId: "session-1",
+ projectId: "proj",
+ agentId: "default_agent",
+ provider: "custom",
+ modelId: "m1",
+ workspace: "/srv/a",
+ approvalMode: "allow-all",
+ sandbox: { mode: "danger-full-access", network: "open" },
+ createdAt: "2026-10-07T10:00:00.000Z",
+ lastActiveAt: "2026-10-07T10:00:00.000Z",
+ status: "idle",
+ pendingApprovalCount: 0,
+ pendingFollowUpCount: 0,
+ hasTrace: true,
+ archived: over.archived ?? false,
+ ...(over.source !== undefined ? { source: over.source } : {}),
+ };
+}
+
+const BACKGROUND = ["api", "schedule", "subagent", "cli"] as const;
+
+describe("backgroundSourceMark", () => {
+ it("marks every Background row, each source with a drawing and a name of its own", () => {
+ const marks = BACKGROUND.map((source) => backgroundSourceMark(session({ source })));
+ for (const mark of marks) {
+ expect(mark?.sourceGlyph).toBeTruthy();
+ expect(mark?.sourceLabel).toBeTruthy();
+ }
+ expect(new Set(marks.map((m) => m?.sourceGlyph)).size).toBe(BACKGROUND.length);
+ expect(new Set(marks.map((m) => m?.sourceLabel)).size).toBe(BACKGROUND.length);
+ });
+
+ it("leaves a person's conversation, a company Session and every archived row unmarked", () => {
+ expect(backgroundSourceMark(session({ source: "user" }))).toBeNull();
+ expect(backgroundSourceMark(session())).toBeNull();
+ expect(backgroundSourceMark(session({ source: "company" }))).toBeNull();
+ for (const source of BACKGROUND) {
+ expect(backgroundSourceMark(session({ source, archived: true }))).toBeNull();
+ }
+ });
+
+ it("never draws a scheduled task's Session with the alarm clock a task still to fire uses", () => {
+ expect(backgroundSourceMark(session({ source: "schedule" }))?.sourceGlyph).not.toBe(
+ ICONS.alarmClock,
+ );
+ });
+
+ it("names every source in English without falling back to Chinese", () => {
+ setActiveStrings(en);
+ for (const source of BACKGROUND) {
+ expect(backgroundSourceMark(session({ source }))?.sourceLabel).not.toMatch(/\p{Script=Han}/u);
+ }
+ });
+});
diff --git a/packages/web/test/sessions-store.test.ts b/packages/web/test/sessions-store.test.ts
index e822be46..da6fcc12 100644
--- a/packages/web/test/sessions-store.test.ts
+++ b/packages/web/test/sessions-store.test.ts
@@ -141,13 +141,7 @@ const serverRecent = (
? -1
: 0;
-const zeroCounts = (): SessionCategoryCounts => ({
- active: 0,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
-});
+const zeroCounts = (): SessionCategoryCounts => ({ active: 0, background: 0, archived: 0 });
/** One page of an Agent's rows as the list route answers it: order, cursor, filters, counts. */
function servedPage(rows: readonly SessionInfo[], query: URLSearchParams): Response {
@@ -174,8 +168,10 @@ function servedPage(rows: readonly SessionInfo[], query: URLSearchParams): Respo
const counts = zeroCounts();
const workspaceCounts: Record<string, SessionCategoryCounts> = {};
for (const s of rows) {
- counts[sessionCategory(s)] += 1;
- (workspaceCounts[s.workspace] ??= zeroCounts())[sessionCategory(s)] += 1;
+ const category = sessionCategory(s);
+ if (category === null) continue;
+ counts[category] += 1;
+ (workspaceCounts[s.workspace] ??= zeroCounts())[category] += 1;
}
Object.assign(body, { counts, workspaceCounts });
}
@@ -215,7 +211,7 @@ function session(sessionId: string, over: Partial<SessionInfo> = {}): SessionInf
const row = (sessionId: string, createdAt: string, agentId = "a1") =>
session(sessionId, { agentId, createdAt, lastActiveAt: createdAt });
-const COUNTS = { active: 1, subagent: 1, schedule: 0, benchmark: 0, archived: 0 };
+const COUNTS = { active: 1, background: 1, archived: 0 };
const page = (
sessions: SessionInfo[],
@@ -224,7 +220,7 @@ const page = (
): SessionsResponse =>
({
sessions,
- counts: { active, subagent: 0, schedule: 0, benchmark: 0, archived: 0 },
+ counts: { active, background: 0, archived: 0 },
...(workspaceCounts === undefined ? {} : { workspaceCounts }),
}) as SessionsResponse;
@@ -415,9 +411,9 @@ describe("the list fetches the user's own rows only", () => {
const store = boot();
await store.getState().reload();
fetch.requests.length = 0;
- await store.getState().loadMoreFor(["a1"], "subagent");
+ await store.getState().loadMoreFor(["a1"], "background");
expect(fetch.requests).toHaveLength(1);
- expect(fetch.requests[0]!.query.get("category")).toBe("subagent");
+ expect(fetch.requests[0]!.query.get("category")).toBe("background");
expect(fetch.requests[0]!.query.get("excludeOrg")).toBe("1");
});
});
diff --git a/packages/web/test/stream-controller.test.ts b/packages/web/test/stream-controller.test.ts
index 70653e2e..fe758cbc 100644
--- a/packages/web/test/stream-controller.test.ts
+++ b/packages/web/test/stream-controller.test.ts
@@ -711,6 +711,7 @@ describe("windowed history: tail-first load + scroll-up backfill", () => {
system_prompt: "",
agent_state: "/tmp/a",
workspace: "/tmp/w",
+ source: "user",
});
const A = { provider: "anthropic", modelId: "a-1" };
const B = { provider: "openai", modelId: "b-2" };
diff --git a/packages/web/test/stream-model.test.ts b/packages/web/test/stream-model.test.ts
index 51098191..a5a84fa7 100644
--- a/packages/web/test/stream-model.test.ts
+++ b/packages/web/test/stream-model.test.ts
@@ -135,6 +135,7 @@ function meta(sessionId: string): OmniMessage<SessionMetaPayload> {
system_prompt: "",
agent_state: "/a",
workspace: "/w",
+ source: "user",
});
}
diff --git a/plugins/agent-tuning/plugin.json b/plugins/agent-tuning/plugin.json
index 6bbaed76..9f3cc9be 100644
--- a/plugins/agent-tuning/plugin.json
+++ b/plugins/agent-tuning/plugin.json
@@ -3,6 +3,6 @@
"description_zh": "闭环的 Agent 调优:依据需求初始化 Agent、设计并校准能力 Benchmark、隔离执行与评分、再根据测得结果改进 Agent。",
"short_description": "Initialize, benchmark, evaluate and improve agents.",
"short_description_zh": "初始化、评测、评分与改进 Agent。",
- "version": "2026.10.07.1",
+ "version": "2026.10.10.1",
"category": "ai-app-development"
}
diff --git a/plugins/agent-tuning/skills/agent-evaluation/SKILL.md b/plugins/agent-tuning/skills/agent-evaluation/SKILL.md
index 5c03af99..f421e02f 100644
--- a/plugins/agent-tuning/skills/agent-evaluation/SKILL.md
+++ b/plugins/agent-tuning/skills/agent-evaluation/SKILL.md
@@ -70,10 +70,10 @@ penguin run \
--message "Read README.md in the current Workspace and complete the task exactly as specified there." \
--provider "<provider>" --model-id "<model_id>" --project-id "$PROJECT_ID" \
--agent-id "<test_agent_id>" --workspace "<absolute_unique_workspace_path>" \
- --approve allow-all --source benchmark
+ --approve allow-all
```
-`--source benchmark` files the Test Session under the Evaluations folder of the Web App's session list rather than the Test Agent's active conversations; never omit it.
+Every Session `penguin run` creates is a CLI Session, so the Test Session lands in the Background folder of the Web App's session list, marked CLI, rather than among the Test Agent's active conversations.
Use the exact requested Agent, Project, absolute Workspace path, and model pair. Never omit either model flag and never fall back to a Project default. If a launch fails, retry only when unchanged Workspace and Trace evidence proves that the Test Agent did not start. Every retry must follow a new diagnosis and apply a specific correction; never repeat an unchanged launch. Do not impose a numeric retry limit while distinct safe repairs remain. Return `evaluation_failed` when no new repair remains, external configuration is required, or it is unclear whether the Test Agent started.