Skip to content

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

fix(server,web): company-mode sessions stay out of the development list (#751)

Yaowei Zheng8278fff0490e
diff --git a/changelog/unreleased/2026-09-16-org-sessions-out-of-the-development-list.md b/changelog/unreleased/2026-09-16-org-sessions-out-of-the-development-list.md
new file mode 100644
index 00000000..a3bfc8a6
--- /dev/null
+++ b/changelog/unreleased/2026-09-16-org-sessions-out-of-the-development-list.md
@@ -0,0 +1,44 @@
+# Company mode's Sessions stay out of the development list
+
+- **Date:** 2026-09-16
+- **Type:** fix
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#751](https://github.com/Prism-Shadow/penguin-harness/pull/751)
+
+[中文版](2026-09-16-org-sessions-out-of-the-development-list.zh.md)
+
+While an organization was working, its Sessions could surface in development mode's Session
+list. Once an employee held more Sessions than the list loads per page, the server's totals
+still counted the desk and ticket sessions the list had not loaded, so the list drew their
+Workspace as a group — placed at the top by the Session that had just opened — with a reveal
+row that revealed nothing; and a sub-session an employee spawned carried no organization mark
+at all, so it listed under the Subagents folder like any other conversation. The list now asks
+the server for the user's own rows only, and a sub-session inherits its parent's stamp.
+
+## Details
+
+- `GET /api/projects/:projectId/agents/:agentId/sessions` accepts `excludeOrg=1`: the rows an
+ organization owns — its desk and ticket sessions and the sub-sessions they spawned, by the
+ durable `client: "org"` stamp or by the organization caches — leave the page, the `counts=1`
+ totals, the per-Workspace breakdown and the Workspace stamps together, and paging walks the
+ filtered stream. Without the flag the route keeps serving every row, whichever client
+ created it. The Server API reference documents the flag in both languages.
+- A sub-session registered under a Session stamped `client: "org"` is inserted with the same
+ stamp; one registered under any other Session keeps the blank marker it always had.
+- The Web App's session list store passes `excludeOrg` on every fetch and no longer corrects
+ the server's totals on its side; a row that still enters through the chat page's deep-link
+ self-heal is dropped at render, leaves the totals alone and is kept across list reloads, so
+ the desk or ticket session open in the chat page keeps its approval-mode, thinking-level,
+ title and status updates.
+- The store remembers every run status the user channel reports (`session_state`), whether or
+ not a loaded page holds the row, and company mode's desk rows, org chart and overview read
+ those — so a desk past the first page of an employee's stream shows its run ending too. A
+ `resync_required` clears them, and company mode re-reads its sessions route, organization
+ list and open chart, so a desk whose run ended among the lost events does not stay running.
+- `GET /api/projects/:projectId/organizations/:orgId/sessions` marks a desk whose Session has
+ an enabled messaging binding with `messagingChannel`, read as the Session's own row reads it.
+ The company sidebar's desk rows draw their messaging mark from it — every bound desk, where
+ the mark used to come from whichever desks the development list happened to hold — and a
+ bind or unbind from a desk's row menu updates the row at once.
+- Both marks go through one channel check covering Feishu, Telegram, QQ and WeChat, keyed by
+ `MessagingChannel`, so a channel left out of it fails typecheck.
diff --git a/changelog/unreleased/2026-09-16-org-sessions-out-of-the-development-list.zh.md b/changelog/unreleased/2026-09-16-org-sessions-out-of-the-development-list.zh.md
new file mode 100644
index 00000000..f7cf6b71
--- /dev/null
+++ b/changelog/unreleased/2026-09-16-org-sessions-out-of-the-development-list.zh.md
@@ -0,0 +1,36 @@
+# 公司模式的会话不再进入开发模式的会话列表
+
+- **Date:** 2026-09-16
+- **Type:** fix
+- **Scope:** `server`, `web`, `docs`
+- **PR:** [#751](https://github.com/Prism-Shadow/penguin-harness/pull/751)
+
+[English](2026-09-16-org-sessions-out-of-the-development-list.md)
+
+组织运转期间,它的会话可能冒进开发模式的会话列表。一个员工的会话数一旦超过列表每页加载的数量,
+服务端的统计仍把尚未加载的工位会话与工单会话计在内,列表便把它们的 Workspace 画成一个分组——由
+刚打开的那个会话把它顶到最上面——附带一行什么都展开不出来的「展开其余」;员工派生出的子会话则完全
+不带组织标记,像普通对话一样列在「子智能体」文件夹下。现在列表只向服务端请求用户自己的行,子会话
+也继承其父会话的标记。
+
+## 细节
+
+- `GET /api/projects/:projectId/agents/:agentId/sessions` 接受 `excludeOrg=1`:组织拥有的行——
+ 工位会话、工单会话及其派生的子会话,依据持久的 `client: "org"` 标记或组织缓存判定——同时从分页、
+ `counts=1` 的统计、按 Workspace 的分项与 Workspace 时间戳中剔除,分页沿过滤后的流推进。不带该
+ 参数时路由照旧列出所有行,无论由哪个客户端创建。服务端 API 参考的中英两份文档都记录了该参数。
+- 在标记为 `client: "org"` 的会话下注册的子会话,插入时带上同一标记;在其他会话下注册的子会话保持
+ 原有的空标记。
+- Web App 的会话列表 store 每次请求都带上 `excludeOrg`,不再在客户端修正服务端统计;仍经聊天页深链
+ 自愈进入的行在渲染时被丢弃、不改动统计,并在列表重新加载后保留,于是聊天页打开的工位或工单会话仍能
+ 收到审批模式、思考级别、标题与状态的更新。
+- store 记住用户频道报告的每一次运行状态(`session_state`),不论已加载的分页是否持有该行;公司模式的
+ 工位行、组织架构图与总览读取的正是这份记录——于是一个排在员工会话流第一页之外的工位,也能看到运行结束。
+ 收到 `resync_required` 时这份记录被清空,公司模式重新读取组织的会话接口、组织列表与当前打开的组织
+ 架构,运行结束的事件即便在丢失之列,工位也不会一直显示运行中。
+- `GET /api/projects/:projectId/organizations/:orgId/sessions` 为启用了消息渠道绑定的工位会话带上
+ `messagingChannel`,与该 Session 自身列表行的读法一致。公司模式侧栏的工位行据此绘制消息渠道标记——
+ 覆盖每个已绑定的工位,而此前标记只来自开发模式列表恰好持有的那些工位——在工位行菜单里绑定或解绑后,
+ 该行标记随即更新。
+- 两处标记共用同一个渠道判定,覆盖飞书、Telegram、QQ 与微信,并以 `MessagingChannel` 为键,
+ 漏掉任何一个渠道都无法通过类型检查。
diff --git a/packages/docs/content/server-api.en.md b/packages/docs/content/server-api.en.md
index ca4b8bf8..a0be606a 100644
--- a/packages/docs/content/server-api.en.md
+++ b/packages/docs/content/server-api.en.md
@@ -313,7 +313,7 @@ All paths below are under `/api/projects/:projectId/organizations`. Every route
| GET / POST | /:orgId/channels/:channelId/messages | A day's messages (`?date=yyyy-mm-dd`, default today in the organization's timezone) with the caller's unread and mention counts / send `{text, refs?}`; mentions are resolved from the text and must all be members. A `system` line also carries `notice` — a `kind` (`employee_joined`, `employee_left`, `channel_created`, `channel_archived`, `channel_unarchived`, `channel_joined`, `channel_invited`, `channel_left`, `channel_removed`, `budget_warned`, `budget_paused`, and the legacy `ticket_blocked`, `ticket_done`, `ticket_rejected` — nothing writes those three any more, they are kept so lines already on disk still render) and string `params` — beside its English `text`, so a client renders the sentence in the reader's language; lines written before the field have none |
| POST | /:orgId/channels/:channelId/read | `{upTo}` — the caller's read cursor in this channel |
| GET | /:orgId/finance | Spend per employee (own and cumulative along the reporting line), per ticket (rolled up along `Parent`), daily trend, alerts; `?period=yyyy-mm` |
-| GET | /:orgId/sessions | The organization's desk sessions and ticket sessions grouped by ticket |
+| GET | /:orgId/sessions | The organization's desk sessions and ticket sessions grouped by ticket; a desk whose Session has an enabled messaging binding carries its `messagingChannel`, as the Session's own row does |
Channel errors: `channel_not_found` (404 — also for an id no channel could carry), `channel_exists` (409), `channel_archived` (409 — an archived channel takes no writes until it is unarchived), `not_a_member` (403 — reading, posting or inviting without membership, and any people-only action attempted by an employee), `all_hands_immutable` (400 — archiving `default_channel` or editing its membership), `mention_not_member` (400 — the message names principals the channel does not hold; nothing is written), `invalid_principal` (400).
@@ -325,7 +325,7 @@ A desk session is driven by three things only: a calendar event, a channel `@`-m
| Method | Path | Description |
| --- | --- | --- |
-| GET | /agents/:agentId/sessions | List Sessions (including run state); every row is listed whichever client created it |
+| GET | /agents/:agentId/sessions | List Sessions (including run state); every row is listed whichever client created it, unless `excludeOrg=1` asks for the user's own rows only — an organization's desk, ticket and sub-sessions then leave the page and the `counts=1` totals together (what development mode's list requests) |
| POST | /agents/:agentId/sessions | Create a Session: `{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201. `client` is the creating-client hint stored on the row (`"cli"` from the CLI; default `"web"`) — informational provenance, never a list filter; `source` accepts only `"benchmark"` (a Benchmark evaluation or optimization), since `subagent` and `schedule` are set by the server itself `org` is the value the server itself writes for an organization's desk and ticket sessions (company mode); a client cannot pass it. |
| GET | /dirs?path= | Server-side directory browser (backs the Workspace picker) |
diff --git a/packages/docs/content/server-api.zh.md b/packages/docs/content/server-api.zh.md
index f46e195d..34154e3b 100644
--- a/packages/docs/content/server-api.zh.md
+++ b/packages/docs/content/server-api.zh.md
@@ -313,7 +313,7 @@ Benchmark 挂在 Project 上而非某个 Agent 上:一个 Benchmark 评测过
| GET / POST | /:orgId/channels/:channelId/messages | 某一天的消息(`?date=yyyy-mm-dd`,缺省为组织时区的今天)及调用方的未读与 @ 计数 / 发送 `{text, refs?}`;@ 从正文解析,且必须都是频道成员。`system` 消息在英文 `text` 之外还带 `notice`——一个 `kind`(`employee_joined`、`employee_left`、`channel_created`、`channel_archived`、`channel_unarchived`、`channel_joined`、`channel_invited`、`channel_left`、`channel_removed`、`budget_warned`、`budget_paused`,以及遗留的 `ticket_blocked`、`ticket_done`、`ticket_rejected`——这三种已不再写入,保留只是为了让磁盘上已有的行仍能渲染)与一组字符串 `params`——客户端据此按读者的语言渲染该句;该字段出现之前写下的消息没有它 |
| POST | /:orgId/channels/:channelId/read | `{upTo}`——调用方在该频道的已读游标 |
| GET | /:orgId/finance | 按员工(本人与沿汇报线累计)、按工单(沿 `Parent` 上卷)的支出、逐日趋势与告警;`?period=yyyy-mm` |
-| GET | /:orgId/sessions | 组织的工位会话与按工单分组的工单会话 |
+| GET | /:orgId/sessions | 组织的工位会话与按工单分组的工单会话;工位会话启用了消息渠道绑定时带 `messagingChannel`,与该 Session 自身的列表行一致 |
频道相关错误:`channel_not_found`(404,频道 id 不合法时同样如此)、`channel_exists`(409)、`channel_archived`(409,归档频道在取消归档前不接受写入)、`not_a_member`(403,无成员身份的读取、发言与邀请,以及员工尝试仅限人的操作)、`all_hands_immutable`(400,归档 `default_channel` 或编辑其成员)、`mention_not_member`(400,消息提及了不在该频道的对象,整条不写入)、`invalid_principal`(400)。
@@ -325,7 +325,7 @@ Benchmark 挂在 Project 上而非某个 Agent 上:一个 Benchmark 评测过
| 方法 | 路径 | 说明 |
| --- | --- | --- |
-| GET | /agents/:agentId/sessions | Session 列表(含运行状态);无论由哪个客户端创建,所有行都会列出 |
+| GET | /agents/:agentId/sessions | Session 列表(含运行状态);无论由哪个客户端创建,所有行都会列出;带 `excludeOrg=1` 时只列用户自己的行——组织的工位会话、工单会话及其派生的子会话同时从分页与 `counts=1` 的统计中剔除(开发模式的会话列表即以此请求) |
| POST | /agents/:agentId/sessions | 创建 Session:`{modelId?, provider?, workspace?, approvalMode?, client?, source?}` → 201。`client` 是存入索引行的创建客户端标记(CLI 传 `"cli"`,缺省 `"web"`)——仅作来源信息,绝不参与列表过滤;`source` 只接受 `"benchmark"`(Benchmark 评估或优化创建),`subagent` 与 `schedule` 由服务端自己写入 `org` 是服务端为组织的工位与工单会话(公司模式)自行写入的值,客户端不能传。 |
| GET | /dirs?path= | 服务器端目录浏览(Workspace 选择器数据源) |
diff --git a/packages/server/src/api/types.ts b/packages/server/src/api/types.ts
index 685e0793..5626347d 100644
--- a/packages/server/src/api/types.ts
+++ b/packages/server/src/api/types.ts
@@ -1411,16 +1411,17 @@ export interface SessionInfo {
/**
* Company mode: the organization that owns this Session — a desk session of one of its
* employees, or a session contributing to one of its tickets — read from the organization
- * caches. Absent for every ordinary Session. Development mode's list and its time buckets
- * hide every row that carries it (only while company mode is available to that user: it is
- * stamped either way, and company mode is what lists these Sessions instead), and the
- * company sidebar's 工位 / 工单会话 groups are where they are listed.
+ * caches. Absent for every ordinary Session. Development mode's list asks the server to
+ * leave every such row out (`excludeOrg=1` on the list route — page and totals alike) and
+ * still drops one that reaches it by another door; the company sidebar's 工位 group and the
+ * tickets are where these Sessions are reached instead.
*/
orgId?: string;
/**
* Which client opened the Session, as stored on the index row: "cli" from the CLI (a
* Session adopted from a legacy CLI-direct Trace included), "org" from the organization
- * runtime (a desk or a ticket session), "web" otherwise. Absent only on a row that
+ * runtime (a desk or a ticket session, and every sub-session one of those spawns), "web"
+ * otherwise. Absent only on a row that
* predates the column, which reads as "web". Unlike {@link SessionInfo.orgId} — projected
* from the organization caches, so it disappears with the organization and is not read
* while company mode is off — this is a durable stamp on the row: development mode's list
@@ -1458,6 +1459,13 @@ export type SessionCategory = "active" | SessionSource | "archived";
export type SessionCategoryCounts = Record<SessionCategory, number>;
export interface SessionsResponse {
+ /**
+ * The page. With `excludeOrg=1` on the request, the rows an organization owns — its desk
+ * and ticket sessions and the sub-sessions they spawned — are left out of it and of every
+ * total below, so a caller drawing the user's own conversations is never handed a total
+ * for rows it will not be handed. Without the flag every row is served, whichever client
+ * created it.
+ */
sessions: SessionInfo[];
/** Present when the request asked for counts (`counts=1`): totals per category over the full list, not just the returned page. */
counts?: SessionCategoryCounts;
@@ -1525,7 +1533,8 @@ export interface SessionCreateRequest {
* not the organization still exists); defaults to "web". A REQUEST may send only "web" or
* "cli": the runtime writes "org" by calling the service directly, so no caller can claim
* an organization's provenance for its own Session. Lists serve every row regardless of
- * client; only development mode's session list filters on it.
+ * client unless asked for the user's own rows only (`excludeOrg=1`), which is what
+ * development mode's session list asks for.
*/
client?: "web" | "cli" | "org";
/**
@@ -4403,6 +4412,12 @@ export interface OrgDeskItem {
status: SessionStatus;
workspace: string;
lastActiveAt?: string;
+ /**
+ * Present when the desk session has an ENABLED messaging binding: its channel, read as
+ * `SessionInfo.messagingChannel` is (the company sidebar's desk row draws the same mark as a
+ * development row, and the development list never holds a desk).
+ */
+ messagingChannel?: MessagingChannel;
}
export interface OrgSessionsResponse {
diff --git a/packages/server/src/db/repos/sessions.ts b/packages/server/src/db/repos/sessions.ts
index bfc7577f..fe01803f 100644
--- a/packages/server/src/db/repos/sessions.ts
+++ b/packages/server/src/db/repos/sessions.ts
@@ -31,11 +31,12 @@ export interface SessionRow {
/**
* Creating client: "web" (created via the Web App), "cli" (created through the API by
* the CLI, or adopted from a Trace a legacy CLI-direct run left behind), "org" (opened by
- * the organization runtime — a desk or a ticket session); NULL = legacy row from before
- * the column existed, treated as web. Free text in SQLite, so a new value needs no
- * migration. Provenance that outlives its organization: development mode's list is the
- * one reader that filters on it, and it hides "org" rows whether or not the organization
- * still exists. The schedule/subagent SOURCE is deliberately NOT a row field — core
+ * the organization runtime — a desk or a ticket session — or spawned as a sub-session of
+ * one, which inherits the stamp at registration); NULL = legacy row from before the column
+ * existed, treated as web. Free text in SQLite, so a new value needs no migration.
+ * Provenance that outlives its organization: development mode's list is the one reader
+ * that filters on it (through the list's `excludeOrg`), and it hides "org" rows whether or
+ * not the organization still exists. The schedule/subagent SOURCE is deliberately NOT a row field — core
* session_meta in the Trace stays the single source of truth for it
* (runtime/session-sources.ts); `client` is a separate, DB-only axis that meta never
* records.
diff --git a/packages/server/src/http/routes/messaging.ts b/packages/server/src/http/routes/messaging.ts
index b4dd0658..083cb87b 100644
--- a/packages/server/src/http/routes/messaging.ts
+++ b/packages/server/src/http/routes/messaging.ts
@@ -93,6 +93,7 @@ import {
} from "./messaging-channels.js";
import type { MessagingChannelSpec } from "./messaging-channels.js";
import type { MessagingChannel } from "../../runtime/messaging/connector.js";
+import { isMessagingChannel } from "../../runtime/messaging/enabled-channel.js";
import type { WeChatScanService } from "../../runtime/messaging/wechat-scan.js";
import type { MessagingBridge } from "../../runtime/messaging/bridge.js";
import type { QQScanService } from "../../runtime/messaging/qq-scan.js";
@@ -160,8 +161,8 @@ function wechatFieldsOf(row: MessagingBindingRow): { botId: string; botToken: st
* message, the enable gate's credential check — is written once.
*
* A `Record` keyed by the discriminant rather than an array: every lookup here starts from a
- * channel already in hand, and a stored row's channel is untrusted text, so `?? null` on a
- * miss is the shape both callers want.
+ * channel already in hand, and a stored row's channel is untrusted text, so null for an id
+ * `isMessagingChannel` does not know (specOf) is the shape both callers want.
*/
const CHANNEL_SPECS: Readonly<Record<MessagingChannel, MessagingChannelSpec>> = {
feishu: {
@@ -230,7 +231,7 @@ const CHANNEL_SPECS: Readonly<Record<MessagingChannel, MessagingChannelSpec>> =
/** The spec for a stored row's channel, or null on an unknown discriminator (skipped defensively, like the bridge does). */
function specOf(channel: string): MessagingChannelSpec | null {
- return CHANNEL_SPECS[channel as MessagingChannel] ?? null;
+ return isMessagingChannel(channel) ? CHANNEL_SPECS[channel] : null;
}
/** Whatever channel the row is: its masked view, or null on an unknown discriminator. */
diff --git a/packages/server/src/http/routes/sessions.ts b/packages/server/src/http/routes/sessions.ts
index ef2f1dad..4cc79450 100644
--- a/packages/server/src/http/routes/sessions.ts
+++ b/packages/server/src/http/routes/sessions.ts
@@ -477,7 +477,8 @@ export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
const app = new 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).
+ // 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).
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");
@@ -502,12 +503,19 @@ export function agentSessionsRoutes(deps: SessionsRouteDeps): Hono<AppEnv> {
}
const rawCounts = c.req.query("counts");
if (rawCounts !== undefined && rawCounts !== "1") throw badRequest("counts only accepts 1.");
+ // Optional own-rows filter: leaves an organization's desk, ticket and sub-sessions out of
+ // the page AND the totals (a total the page can never fill is a group the sidebar draws).
+ const rawExcludeOrg = c.req.query("excludeOrg");
+ if (rawExcludeOrg !== undefined && rawExcludeOrg !== "1") {
+ throw badRequest("excludeOrg only accepts 1.");
+ }
const { sessions, counts, workspaceCounts, workspaceLatest } =
await deps.sessionService.listSessions(projectId, agentId, {
...(paging ? { paging } : {}),
...(rawCategory !== undefined ? { category: rawCategory as SessionCategory } : {}),
...(rawWorkspaceGroup !== undefined ? { workspaceGroup: rawWorkspaceGroup } : {}),
...(rawCounts !== undefined ? { withCounts: true } : {}),
+ ...(rawExcludeOrg !== undefined ? { excludeOrg: true } : {}),
});
return c.json({
sessions,
diff --git a/packages/server/src/runtime/messaging/connector.ts b/packages/server/src/runtime/messaging/connector.ts
index 2eb4cd67..33aaade0 100644
--- a/packages/server/src/runtime/messaging/connector.ts
+++ b/packages/server/src/runtime/messaging/connector.ts
@@ -11,9 +11,14 @@
* every connector method validates its own shape and throws a readable error on a
* malformed one — the bridge treats that like any other channel failure.
*/
+import type { MessagingChannel } from "../../api/types.js";
-/** Known messaging channels (the DB stores the discriminator as text; unknown values are skipped defensively). */
-export type MessagingChannel = "feishu" | "telegram" | "qq" | "wechat";
+/**
+ * Known messaging channels, declared once with the wire types. The DB stores the discriminator
+ * as text; `isMessagingChannel` (enabled-channel.ts) narrows a stored one, and an unknown value
+ * is skipped defensively.
+ */
+export type { MessagingChannel };
/** One inbound image's bytes, once fetched, with the MIME type the bridge needs for its data URL. */
export interface MessagingInboundImageData {
diff --git a/packages/server/src/runtime/messaging/enabled-channel.ts b/packages/server/src/runtime/messaging/enabled-channel.ts
new file mode 100644
index 00000000..6548b65f
--- /dev/null
+++ b/packages/server/src/runtime/messaging/enabled-channel.ts
@@ -0,0 +1,33 @@
+/**
+ * The channel a Session's ENABLED messaging binding connects, or null when none is enabled —
+ * the one reading behind every row mark that says "this Session relays to a bot": the
+ * development list's `SessionInfo.messagingChannel` and the company sidebar's
+ * `OrgDeskItem.messagingChannel`. A saved-but-disabled config marks nothing, and neither does
+ * a stored channel id that is not a `MessagingChannel`.
+ */
+import type { MessagingChannel } from "../../api/types.js";
+import type { MessagingBindings } from "../../mechanisms/messaging.js";
+
+/**
+ * Every channel id, keyed so that a `MessagingChannel` added without an entry here fails
+ * typecheck instead of silently losing its row mark.
+ */
+const MESSAGING_CHANNEL_IDS = {
+ feishu: true,
+ telegram: true,
+ qq: true,
+ wechat: true,
+} as const satisfies Record<MessagingChannel, true>;
+
+/** Whether a stored channel discriminator — untrusted text in the DB — names a known channel. */
+export function isMessagingChannel(channel: string): channel is MessagingChannel {
+ return Object.hasOwn(MESSAGING_CHANNEL_IDS, channel);
+}
+
+export function enabledMessagingChannel(
+ bindings: Pick<MessagingBindings, "findEnabled">,
+ sessionId: string,
+): MessagingChannel | null {
+ const enabled = bindings.findEnabled(sessionId);
+ return enabled !== null && isMessagingChannel(enabled.channel) ? enabled.channel : null;
+}
diff --git a/packages/server/src/runtime/organization/deps.ts b/packages/server/src/runtime/organization/deps.ts
index 7ca52b23..a0e0b10b 100644
--- a/packages/server/src/runtime/organization/deps.ts
+++ b/packages/server/src/runtime/organization/deps.ts
@@ -6,7 +6,12 @@
*/
import type { OmniMessage } from "@prismshadow/penguin-core";
import { Interface } from "@prismshadow/penguin-core/kernel";
-import type { ApprovalMode, ServerEvent, SessionStatus } from "../../api/types.js";
+import type {
+ ApprovalMode,
+ MessagingChannel,
+ ServerEvent,
+ SessionStatus,
+} from "../../api/types.js";
import type { OrgCache } from "../../mechanisms/organization.js";
import type { Members, ProjectConfigStore, Projects } from "../../mechanisms/projects.js";
import type { SessionIndex } from "../../mechanisms/sessions.js";
@@ -139,6 +144,12 @@ export interface OrgDeps {
*/
completeOnce?: (projectId: string, prompt: string) => Promise<UtilityCompletion>;
usage: OrgUsageGateway;
+ /**
+ * The channel of a Session's ENABLED messaging binding, or null when none is enabled — the
+ * same reading behind `SessionInfo.messagingChannel`, so the company sidebar's desk row can
+ * carry the development row's mark without the development list holding the desk.
+ */
+ messagingChannel: (sessionId: string) => MessagingChannel | null;
errors: ErrorSink;
/** Company-mode notifications go to the Project's owner and members (app.ts binds the user channels). */
notifyProject: (projectId: string, event: ServerEvent) => void;
diff --git a/packages/server/src/runtime/organization/service.ts b/packages/server/src/runtime/organization/service.ts
index c721a403..3ff8e89c 100644
--- a/packages/server/src/runtime/organization/service.ts
+++ b/packages/server/src/runtime/organization/service.ts
@@ -64,6 +64,7 @@ import type {
ProjectConfigStore,
Projects,
} from "../../mechanisms/projects.js";
+import type { MessagingBindings } from "../../mechanisms/messaging.js";
import type { SessionIndex } from "../../mechanisms/sessions.js";
import type { Settings } from "../../mechanisms/settings.js";
import type { Errors, UsageQueries } from "../../mechanisms/observability.js";
@@ -111,6 +112,7 @@ import {
sanitizeSuggestedId,
} from "../../organization/semantic-id.js";
import { SEMANTIC_ID_PATTERN } from "../../services/ids.js";
+import { enabledMessagingChannel } from "../messaging/enabled-channel.js";
import { latestSlotAt, nextSlotAfter, slotInWindow } from "../schedule-file.js";
import type { ScheduleDefinition } from "../schedule-file.js";
import { budgetLine, budgetRatio, computeSpend, pausedEmployees } from "./budget.js";
@@ -2458,6 +2460,7 @@ export class OrganizationService {
const desk = org.desks[e.agentId];
if (!desk) continue;
const row = this.deps.sessions.findById(desk.sessionId);
+ const messagingChannel = this.deps.messagingChannel(desk.sessionId);
desks.push({
agentId: e.agentId,
name: (await this.deps.agents.exists(projectId, e.agentId))
@@ -2468,6 +2471,7 @@ export class OrganizationService {
status: this.deps.runner.statusOf(desk.sessionId),
workspace: desk.workspace,
...(row?.lastActiveAt ? { lastActiveAt: row.lastActiveAt } : {}),
+ ...(messagingChannel !== null ? { messagingChannel } : {}),
});
}
const ticketGroups: OrgSessionsResponse["tickets"] = [];
@@ -2775,6 +2779,7 @@ export class OrganizationModule {
@Use() private readonly usage!: UsageQueries;
@Use() private readonly errors!: Errors;
@Use() private readonly settings!: Settings;
+ @Use() private readonly messagingRepo!: MessagingBindings;
@Provide() orgService!: OrgService;
@Provide() orgScheduler!: OrgScheduler;
setup({ effect }: ClassCtx) {
@@ -2816,6 +2821,7 @@ export class OrganizationModule {
projectConfig,
completeOnce: (projectId, prompt) => projectConfig.completeOnce(projectId, prompt),
usage: this.usage,
+ messagingChannel: (sessionId) => enabledMessagingChannel(this.messagingRepo, sessionId),
errors: this.errors,
notifyProject: (projectId, event) => {
const ownerUserId = this.projects.findById(projectId)?.ownerUserId;
diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.ts
index e3fbdf8f..4d041b60 100644
--- a/packages/server/src/runtime/session-manager.ts
+++ b/packages/server/src/runtime/session-manager.ts
@@ -96,6 +96,7 @@ import type { TraceIndex, TraceIndexStore } from "../mechanisms/traces.js";
import type { Settings } from "../mechanisms/settings.js";
import type { MessagingBindings } from "../mechanisms/messaging.js";
import type { OrgCache } from "../mechanisms/organization.js";
+import { enabledMessagingChannel } from "./messaging/enabled-channel.js";
/**
* 409 for when there's nothing to compact: give the specific reason rather than a
@@ -2045,6 +2046,13 @@ export class SessionManager {
const source = asSessionSource(p.source) ?? "subagent";
this.deps.sources.set(childSid, source);
const createdAt = this.now().toISOString();
+ // A sub-session of an organization's Session is company mode's own as much as the desk
+ // or ticket session that spawned it: it inherits the durable "org" stamp, which is the
+ // only mark it can carry — the organization caches name desks and ticket sessions, never
+ // what those spawn — and the one development mode's list leaves out. Every other parent
+ // leaves the marker blank (read as web): the child was spawned by this server's run, not
+ // opened through the CLI, whatever opened its parent.
+ const parentClient = this.deps.sessions.findById(entry.sessionId)?.client;
this.deps.sessions.insertOrIgnore({
sessionId: childSid,
projectId: entry.projectId,
@@ -2056,7 +2064,8 @@ export class SessionManager {
// inserted with defaults (matches the convention for Sessions discovered by the CLI).
approvalMode: "allow-all",
title: null,
- // Spawned by this server's run (client NULL = web); its Trace exists by construction.
+ ...(parentClient === "org" ? { client: "org" as const } : {}),
+ // Its Trace exists by construction.
hasTrace: true,
// A subagent's own runs are driven through the PARENT entry's drive, so nothing ever
// stamps this row: it stays at its registration time (see SessionRow.lastActiveAt).
@@ -2397,19 +2406,7 @@ export class SessionsModule {
traceStore: this.traceStore,
proxyEnv: env.proxyEnv,
controlEnv: env.controlEnv,
- // List rows carry the ENABLED channel's indicator (saved-but-dark configs stay off
- // the row); a point query per row keeps the repo out of the service. An unknown
- // stored channel reads as none (same defensive skip as the bridge and the routes).
- messagingChannel: (sessionId) => {
- const enabled = this.messagingRepo.findEnabled(sessionId);
- return enabled !== null &&
- (enabled.channel === "feishu" ||
- enabled.channel === "telegram" ||
- enabled.channel === "qq" ||
- enabled.channel === "wechat")
- ? enabled.channel
- : null;
- },
+ messagingChannel: (sessionId) => enabledMessagingChannel(this.messagingRepo, sessionId),
// Company mode: which organization owns a Session, so development mode's list can hide
// organization sessions and the company sidebar can group its own. The caches are a
// projection of the organization's files, rebuilt every reconcile pass, so a row that
diff --git a/packages/server/src/services/session-service.ts b/packages/server/src/services/session-service.ts
index b827f906..7508e028 100644
--- a/packages/server/src/services/session-service.ts
+++ b/packages/server/src/services/session-service.ts
@@ -211,6 +211,14 @@ export class SessionService {
* sharing one per-Agent cursor — without it, one group's "load more" consumes the page
* 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.
+ *
+ * `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.
*/
async listSessions(
projectId: string,
@@ -220,6 +228,7 @@ export class SessionService {
category?: SessionCategory;
workspaceGroup?: string;
withCounts?: boolean;
+ excludeOrg?: boolean;
} = {},
): Promise<{
sessions: SessionInfo[];
@@ -227,7 +236,7 @@ export class SessionService {
workspaceCounts?: Record<string, SessionCategoryCounts>;
workspaceLatest?: Record<string, string>;
}> {
- const { paging, category, workspaceGroup, withCounts } = opts;
+ const { paging, category, workspaceGroup, withCounts, excludeOrg } = opts;
const rows = new Map(
this.deps.sessions.listByAgent(projectId, agentId).map((r) => [r.sessionId, r]),
);
@@ -235,6 +244,12 @@ export class SessionService {
// below: the company caches are small, and a lookup per row would put a statement
// behind every entry of a long sidebar list.
const orgIds = this.deps.orgIdsOfProject?.(projectId) ?? EMPTY_ORG_IDS;
+ if (excludeOrg) {
+ // The durable `client` stamp answers first: it survives the organization and is
+ // inherited by sub-sessions, which no cache names. The caches catch a row the
+ // reconcile pass has not stamped yet.
+ for (const [id, row] of rows) if (row.client === "org" || orgIds.has(id)) rows.delete(id);
+ }
let traces: ReadonlySet<string> | undefined;
if ([...rows.values()].some((r) => this.deps.sources.get(r.sessionId) === undefined)) {
diff --git a/packages/server/test/messaging-telegram.test.ts b/packages/server/test/messaging-telegram.test.ts
index 2dd47c82..62a3d045 100644
--- a/packages/server/test/messaging-telegram.test.ts
+++ b/packages/server/test/messaging-telegram.test.ts
@@ -1910,15 +1910,6 @@ describe("telegram binding routes and connector loop", () => {
await settle(40);
expect(runs).toHaveLength(1);
});
-
- it("the session list marks a telegram-ENABLED row with messagingChannel telegram", async () => {
- await bindEnabled(SID);
- const res = await api.get(`/api/projects/${projectId}/agents/default_agent/sessions`);
- const body = (await res.json()) as {
- sessions: Array<{ sessionId: string; messagingChannel?: string }>;
- };
- expect(body.sessions.find((s) => s.sessionId === SID)?.messagingChannel).toBe("telegram");
- });
});
// ---------------------------------------------------------------------------
diff --git a/packages/server/test/messaging-wechat.test.ts b/packages/server/test/messaging-wechat.test.ts
index fad750ca..cf27b04a 100644
--- a/packages/server/test/messaging-wechat.test.ts
+++ b/packages/server/test/messaging-wechat.test.ts
@@ -481,15 +481,6 @@ describe("wechat binding routes and the long poll", () => {
expect(body.bindings.map((b) => b.binding.channel).sort()).toEqual(["telegram", "wechat"]);
});
- it("the session list marks a wechat-ENABLED row with messagingChannel wechat", async () => {
- await bindEnabled(SID);
- const res = await api.get(`/api/projects/${PROJECT}/agents/default_agent/sessions`);
- const body = (await res.json()) as {
- sessions: Array<{ sessionId: string; messagingChannel?: string }>;
- };
- expect(body.sessions.find((s) => s.sessionId === SID)?.messagingChannel).toBe("wechat");
- });
-
// —— The long poll ————————————————————————————————————————————————————————
it("reports the connection ready before any poll has answered", async () => {
diff --git a/packages/server/test/messaging.test.ts b/packages/server/test/messaging.test.ts
index f774c3ba..4a2da478 100644
--- a/packages/server/test/messaging.test.ts
+++ b/packages/server/test/messaging.test.ts
@@ -2234,23 +2234,6 @@ describe("messaging binding routes and bridge", () => {
expect(fake.connections[1]!.closed).toBe(true);
});
- it("the session list marks rows with the ENABLED channel only", async () => {
- // Saved but disabled: no indicator — the row marks live connections, not stored configs.
- await api.put(BASE(SID), PUT_BODY);
- const saved = await api.get(`/api/projects/${projectId}/agents/default_agent/sessions`);
- const savedBody = (await saved.json()) as {
- sessions: Array<{ sessionId: string; messagingChannel?: string }>;
- };
- expect("messagingChannel" in savedBody.sessions.find((s) => s.sessionId === SID)!).toBe(false);
-
- await api.post(`${BASE(SID)}/state`, { enabled: true });
- const res = await api.get(`/api/projects/${projectId}/agents/default_agent/sessions`);
- const body = (await res.json()) as {
- sessions: Array<{ sessionId: string; messagingChannel?: string }>;
- };
- expect(body.sessions.find((s) => s.sessionId === SID)?.messagingChannel).toBe("feishu");
- });
-
it("start() connects only enabled bindings and reconciles away rows whose Session is gone", async () => {
t.deps.messagingRepo.upsert({
sessionId: SID,
@@ -3470,6 +3453,52 @@ describe("messaging binding routes and bridge", () => {
const settle = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
+/**
+ * The session list's messaging mark, every channel in one table: a row carries the channel of
+ * its ENABLED binding, and a saved-but-disabled config marks nothing. The mark reads the stored
+ * binding alone (enabledMessagingChannel), so each case writes the binding straight into the
+ * repo and no connector ever connects.
+ */
+describe("the session list's messaging mark", () => {
+ let t: TestApp;
+ let api: ReturnType<typeof apiClient>;
+ const projectId = "birder-default_project";
+
+ beforeEach(async () => {
+ t = await createTestApp();
+ api = apiClient(t.app, (await provisionUser(t.app, "birder")).cookie);
+ t.deps.sessionsRepo.insert(sessionRowOf(SID, projectId));
+ });
+ afterEach(async () => {
+ await t.cleanup();
+ });
+
+ /** The Session's row as the development list serves it. */
+ const listedRow = async () => {
+ const res = await api.get(`/api/projects/${projectId}/agents/default_agent/sessions`);
+ const body = (await res.json()) as {
+ sessions: Array<{ sessionId: string; messagingChannel?: string }>;
+ };
+ return body.sessions.find((s) => s.sessionId === SID);
+ };
+
+ it.each(["feishu", "telegram", "qq", "wechat"] as const)(
+ "marks a %s row once its binding is enabled, and not while it is only saved",
+ async (channel) => {
+ t.deps.messagingRepo.upsert({
+ sessionId: SID,
+ channel,
+ accountId: `${channel}-bot`,
+ config: {},
+ });
+ expect(await listedRow()).not.toHaveProperty("messagingChannel");
+
+ t.deps.messagingRepo.setEnabled(SID, channel, true);
+ expect((await listedRow())?.messagingChannel).toBe(channel);
+ },
+ );
+});
+
/**
* The failure #484 named and left open: an inbound message arrives, `startTask` throws, the
* bridge swallows it into an error record and the chat hears nothing at all. It is one of the
diff --git a/packages/server/test/org-harness.ts b/packages/server/test/org-harness.ts
index 7aa38cf3..f3fdde0c 100644
--- a/packages/server/test/org-harness.ts
+++ b/packages/server/test/org-harness.ts
@@ -209,6 +209,7 @@ export async function makeOrgHarness(opts: {
}),
dailyCostForSessions: async () => [],
},
+ messagingChannel: () => null,
errors: { record: (e) => void errors.push(e) },
notifyProject: (_p, event) => void events.push(event),
companyModeEnabled: () => flags.companyMode,
diff --git a/packages/server/test/organization-runtime.test.ts b/packages/server/test/organization-runtime.test.ts
index fcbcc0e0..b55c2ea9 100644
--- a/packages/server/test/organization-runtime.test.ts
+++ b/packages/server/test/organization-runtime.test.ts
@@ -235,6 +235,7 @@ describe("organization runtime", () => {
}),
dailyCostForSessions: async () => [],
},
+ messagingChannel: () => null,
errors: { record: (e) => void errors.push(e) },
notifyProject: (_p, event) => void events.push(event),
companyModeEnabled: () => companyMode,
diff --git a/packages/server/test/organizations-routes.test.ts b/packages/server/test/organizations-routes.test.ts
index 19e8d6a3..618a778a 100644
--- a/packages/server/test/organizations-routes.test.ts
+++ b/packages/server/test/organizations-routes.test.ts
@@ -6,10 +6,21 @@
* calling session and employee ride write bodies as `sessionId` / `agentId` (a read's query
* string), but only from the control environment's API token — a signed-in member's claim is
* dropped. The service itself is a recording fake here — its semantics have their
- * own suites — so no Agent is created and no session runs.
+ * own suites — so no Agent is created and no session runs. The one exception is the sessions
+ * route's desk mark, which is wiring rather than semantics: an organization written straight to
+ * disk is served by the real service, and a desk's enabled messaging binding has to reach its
+ * row from the real bindings table.
*/
+import path from "node:path";
import { afterEach, beforeEach, describe, expect, it } from "vitest";
-import type { MeResponse, ServerSettingsResponse } from "../src/api/types.js";
+import type {
+ MeResponse,
+ OrgSessionsResponse,
+ ServerSettingsResponse,
+ SessionResponse,
+} 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 type { TestApp } from "./helpers.js";
@@ -587,3 +598,93 @@ describe("organization routes", () => {
]);
});
});
+
+describe("organization sessions route over the real service", () => {
+ it("marks a desk whose Session has an enabled messaging binding, as the Session's own row is marked", async () => {
+ const t = await createTestApp();
+ try {
+ t.deps.serverSettingsRepo.setCompanyMode(true);
+ const u = await provisionUser(t.app, "olivia");
+ const api = apiClient(t.app, u.cookie);
+ const projectId = "olivia-default_project";
+ const ceoDesk = "session-2026-09-01-09-00-00-0abc0021";
+ const devDesk = "session-2026-09-01-09-05-00-0abc0022";
+
+ // The organization as its files describe it: a CEO and one report, each with a desk.
+ 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: "olivia",
+ });
+ await store.writeChart(dir, {
+ employees: [
+ { agentId: "acme_ceo", title: "CEO", reportsTo: null, workspace: "." },
+ { agentId: "acme_dev", title: "Developer", reportsTo: "acme_ceo", workspace: "." },
+ ],
+ });
+ const openedAt = "2026-09-01T09:00:00.000Z";
+ const workspace = path.join(dir, "workspace");
+ await store.writeDesks(dir, {
+ acme_ceo: { sessionId: ceoDesk, workspace, openedAt, previous: [] },
+ acme_dev: { sessionId: devDesk, workspace, openedAt, previous: [] },
+ });
+ for (const [sessionId, agentId] of [
+ [ceoDesk, "acme_ceo"],
+ [devDesk, "acme_dev"],
+ ] as const) {
+ t.deps.sessionsRepo.insert({
+ sessionId,
+ projectId,
+ agentId,
+ provider: "custom",
+ modelId: "m-org",
+ workspace,
+ approvalMode: "allow-all",
+ title: null,
+ client: "org",
+ createdAt: openedAt,
+ lastActiveAt: openedAt,
+ });
+ }
+ const desks = async () => {
+ const res = await api.get(`/api/projects/${projectId}/organizations/acme/sessions`);
+ expect(res.status).toBe(200);
+ return new Map(
+ ((await res.json()) as OrgSessionsResponse).desks.map((d) => [d.agentId, d]),
+ );
+ };
+
+ // A saved config is not a binding until it is enabled: no mark yet.
+ t.deps.messagingRepo.upsert({
+ sessionId: ceoDesk,
+ channel: "telegram",
+ accountId: "12345",
+ config: { botToken: "12345:secret" },
+ });
+ expect((await desks()).get("acme_ceo")).not.toHaveProperty("messagingChannel");
+
+ t.deps.messagingRepo.setEnabled(ceoDesk, "telegram", true);
+ const bound = await desks();
+ expect(bound.get("acme_ceo")).toMatchObject({
+ sessionId: ceoDesk,
+ messagingChannel: "telegram",
+ });
+ expect(bound.get("acme_dev")).toMatchObject({ sessionId: devDesk });
+ expect(bound.get("acme_dev")).not.toHaveProperty("messagingChannel");
+ // One reading behind both marks: the Session's own row says the same.
+ const own = (await (await api.get(`/api/sessions/${ceoDesk}`)).json()) as SessionResponse;
+ expect(own.session.messagingChannel).toBe("telegram");
+
+ // Unbinding takes the mark away with it.
+ t.deps.messagingRepo.setEnabled(ceoDesk, "telegram", false);
+ expect((await desks()).get("acme_ceo")).not.toHaveProperty("messagingChannel");
+ } finally {
+ await t.cleanup();
+ }
+ });
+});
diff --git a/packages/server/test/session-index.test.ts b/packages/server/test/session-index.test.ts
index 394de94b..c0025b9c 100644
--- a/packages/server/test/session-index.test.ts
+++ b/packages/server/test/session-index.test.ts
@@ -797,6 +797,70 @@ describe("session-index", () => {
}
});
+ it("excludeOrg=1 serves the user's own rows only: an organization's Sessions leave the page, the totals, the Workspace breakdown and its stamps together", async () => {
+ await configureModels();
+ const own = ((await (await api.post(base(), {})).json()) as SessionCreateResponse).session
+ .sessionId;
+ // A desk session, stamped at creation — and newer than every own row, so it would head
+ // the unfiltered stream. A ticket session the organization caches name but the reconcile
+ // pass has not stamped yet: the same predicate must catch it through `orgId`.
+ const desk = "session-2027-01-01-09-00-00-0abc0011";
+ const ticket = "session-2027-01-01-09-30-00-0abc0012";
+ for (const [sessionId, createdAt, client] of [
+ [desk, "2027-01-01T09:00:00.000Z", "org"],
+ [ticket, "2027-01-01T09:30:00.000Z", undefined],
+ ] as const) {
+ t.deps.sessionsRepo.insert({
+ sessionId,
+ projectId,
+ agentId: "default_agent",
+ provider: "custom",
+ modelId: "m-org",
+ workspace: "/tmp/w-org",
+ approvalMode: "allow-all",
+ title: null,
+ ...(client !== undefined ? { client } : {}),
+ createdAt,
+ lastActiveAt: createdAt,
+ });
+ }
+ t.deps.orgCacheRepo.addTicketSession(
+ projectId,
+ "acme",
+ "2026-09-02-site",
+ ticket,
+ "default_agent",
+ );
+ 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);
+
+ // Without the flag the list keeps its whole-stream contract: every row, every total.
+ 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(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
+ // total or a stamp that still counted them would conjure their Workspace as a group.
+ const mine = await list("?counts=1&excludeOrg=1");
+ expect(ids(mine)).toEqual([own]);
+ expect(mine.counts!.active).toBe(1);
+ expect(mine.workspaceCounts!["/tmp/w-org"]).toBeUndefined();
+ expect(mine.workspaceLatest!["/tmp/w-org"]).toBeUndefined();
+ // Paging and the category filter walk the filtered stream: the first own row is the
+ // first row, not the third.
+ expect(ids(await list("?excludeOrg=1&limit=1&offset=0"))).toEqual([own]);
+ expect(ids(await list("?excludeOrg=1&category=active&limit=1&offset=0"))).toEqual([own]);
+ expect(ids(await list("?excludeOrg=1&limit=1&offset=1"))).toEqual([]);
+
+ expect((await api.get(`${base()}?excludeOrg=yes`)).status).toBe(400);
+ });
+
it("PATCH approval mode persists and reads back", async () => {
await configureModels();
const { session } = (await (await api.post(base(), {})).json()) as SessionCreateResponse;
diff --git a/packages/server/test/session-manager.test.ts b/packages/server/test/session-manager.test.ts
index f5a39e41..13dc5da0 100644
--- a/packages/server/test/session-manager.test.ts
+++ b/packages/server/test/session-manager.test.ts
@@ -875,6 +875,50 @@ describe("session-manager", () => {
);
});
+ it("a sub-session registered under an organization's Session inherits its org stamp; one under an ordinary Session stays unmarked", async () => {
+ // A desk session: the organization runtime stamped it at creation.
+ sessions.insert({ ...ROW, sessionId: "session-org", client: "org" });
+ const spawning = (sessionId: string, childId: string): RuntimeSession => ({
+ sessionId,
+ toolPermission: () => "rw",
+ generateTitle: async () => ({ title: null, usage: null }),
+ compactability: () => "ok" as const,
+ steer: () => false,
+ skipReconnectWait: () => false,
+ async *run() {
+ yield withOrigin(
+ sessionMeta({
+ session_id: childId,
+ model_id: "m-child",
+ provider: "custom",
+ model_context_window: 1000,
+ system_prompt: "sys",
+ agent_state: "/root/p1/child_agent/agent_state",
+ workspace: "/tmp/w-child",
+ source: "subagent",
+ }),
+ childId,
+ );
+ yield withOrigin(assistantText("child done"), childId);
+ yield assistantText("done");
+ },
+ async *compact() {},
+ });
+ const manager = makeManager({
+ load: async (row) =>
+ spawning(row.sessionId, row.sessionId === "session-org" ? "child-org" : "child-plain"),
+ });
+ await manager.startTask("session-org", [userText("go")]);
+ await waitFor(() => manager.statusOf("session-org") === "idle");
+ await manager.startTask("session-1", [userText("go")]);
+ await waitFor(() => manager.statusOf("session-1") === "idle");
+ // The child is company mode's own as much as the desk that spawned it: development
+ // mode's list reads the stamp, and no organization cache ever names a sub-session.
+ expect(sessions.findById("child-org")?.client).toBe("org");
+ // An ordinary Session's child keeps the registration path's blank marker (read as web).
+ expect(sessions.findById("child-plain")?.client).toBeNull();
+ });
+
it("sub-session (origin) registration: session_meta persists; the title is generated from the spawning prompt", async () => {
const fake: RuntimeSession = {
sessionId: "session-1",
diff --git a/packages/web/src/api/endpoints.ts b/packages/web/src/api/endpoints.ts
index 56696e28..1990e734 100644
--- a/packages/web/src/api/endpoints.ts
+++ b/packages/web/src/api/endpoints.ts
@@ -597,13 +597,16 @@ export const listSessions = (
/** One Workspace group's rows only: its path, or the merged temporary group's sentinel (session-grouping.ts). */
workspaceGroup?: string;
withCounts?: boolean;
+ /** The user's own rows only: an organization's desk, ticket and sub-sessions leave the page and the totals together (the development list's contract). */
+ excludeOrg?: boolean;
},
) => {
const qs = opts
? `?limit=${opts.limit}&offset=${opts.offset}` +
(opts.category ? `&category=${opts.category}` : "") +
(opts.workspaceGroup ? `&workspaceGroup=${encodeURIComponent(opts.workspaceGroup)}` : "") +
- (opts.withCounts ? "&counts=1" : "")
+ (opts.withCounts ? "&counts=1" : "") +
+ (opts.excludeOrg ? "&excludeOrg=1" : "")
: "";
return apiFetch<SessionsResponse>(
`/api/projects/${encodeURIComponent(projectId)}/agents/${encodeURIComponent(agentId)}/sessions${qs}`,
diff --git a/packages/web/src/components/layout/sidebar.tsx b/packages/web/src/components/layout/sidebar.tsx
index bdaccc60..a2f37f60 100644
--- a/packages/web/src/components/layout/sidebar.tsx
+++ b/packages/web/src/components/layout/sidebar.tsx
@@ -27,8 +27,9 @@
* six pages in the nav group, and the channel list where the conversation list is, followed
* by the organization's own 工位 group — one row per employee
* (features/company/channel-sidebar.tsx, features/company/org-session-groups.tsx). The
- * development list is the user's OWN conversations only: an organization's desk and ticket
- * Sessions are filtered out of every group, bucket and folder here.
+ * development list is the user's OWN conversations only: an organization's desk, ticket and
+ * sub-sessions are left out of its fetches and totals by the server, and out of every group,
+ * bucket and folder here should one still arrive.
* Desktop keeps it pinned as the left column; mobile puts the whole thing in a drawer.
* New chats always enter draft state (/chat/new; a group header's "+" names its group's Agent or
* Workspace in route state): Model / Workspace / approval mode are all chosen on the draft input
@@ -61,7 +62,6 @@ import {
aggregateWorkspaceCounts,
aggregateWorkspaceLatest,
clampGroupPage,
- countsWithoutOrgSessions,
completeWorkspaceGroups,
foldedShare,
groupPageCount,
@@ -74,7 +74,6 @@ import {
partitionSessions,
revealPlan,
sessionCategory,
- splitDevelopmentList,
totalCategoryCounts,
withoutOrgSessions,
workspaceGroupKey,
@@ -397,8 +396,8 @@ export function Sidebar({
const {
sessions: allSessions,
byAgent: allByAgent,
- countsByAgent: serverCountsByAgent,
- workspaceCountsByAgent: serverWorkspaceCounts,
+ countsByAgent,
+ workspaceCountsByAgent,
workspaceLatestByAgent,
isLoadedFor,
hasMoreFor,
@@ -425,27 +424,21 @@ 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
- * mode — a desk from the 工位 group, a ticket session from its ticket — so they are
- * filtered out here — once, at the source, or a
- * dropped row would still conjure the Workspace group, Agent group or time bucket it belongs
- * to. They are filtered whatever the company-mode switches say (see withoutOrgSessions):
- * this list is the user's conversations, and a switch about the shell does not turn a
- * scheduler's Session into one.
+ * 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
+ * that entered by another door (the chat page's deep-link self-heal), applied once, at the
+ * source, or the dropped row would still conjure the Workspace group, Agent group or time
+ * bucket it belongs to. It applies whatever the company-mode switches say (see
+ * withoutOrgSessions): this list is the user's conversations, and a switch about the shell
+ * does not turn a scheduler's Session into one.
*/
- const devList = useMemo(() => splitDevelopmentList(allSessions), [allSessions]);
- const sessions = devList.own;
+ const sessions = useMemo(() => withoutOrgSessions(allSessions), [allSessions]);
const byAgent = useMemo(() => {
const map = new Map<string, SessionInfo[]>();
for (const [agentId, rows] of allByAgent) map.set(agentId, withoutOrgSessions(rows));
return map;
}, [allByAgent]);
- // …and the server totals those rows are counted in, corrected the same way, so a group
- // header never promises rows this list will not draw.
- const { byAgent: countsByAgent, byWorkspace: workspaceCountsByAgent } = useMemo(
- () =>
- countsWithoutOrgSessions(serverCountsByAgent, serverWorkspaceCounts, devList.organization),
- [serverCountsByAgent, serverWorkspaceCounts, devList],
- );
const currentProjectId = currentProject?.projectId ?? null;
/** This Project's read markers; re-renders the rows whenever one is stamped. */
diff --git a/packages/web/src/features/company/org-session-groups.tsx b/packages/web/src/features/company/org-session-groups.tsx
index f231b77f..914f0034 100644
--- a/packages/web/src/features/company/org-session-groups.tsx
+++ b/packages/web/src/features/company/org-session-groups.tsx
@@ -14,7 +14,8 @@
* copy the Session id, and bind the desk to a messaging bot. A desk's title and its lifecycle are
* the organization's — the employee names it, hiring and firing open and close it — so
* rename, archive, delete and pin are not offered here. The binding's own indicator is read
- * from the session list store: the organization's sessions route does not carry it.
+ * from the organization's sessions route, which marks a desk the way the Session's own row is
+ * marked; the session list store never holds a desk, so it cannot say.
*
* The group reads the company store's caches (the organization's chart and its sessions
* route), so opening it costs no request; the session the shell is on is marked in place. The
@@ -22,9 +23,8 @@
* caches are only re-read on an organization event, and a run ending publishes none
* (org-sessions.ts).
*/
-import { useMemo, useState } from "react";
+import { useState } from "react";
import { useNavigate } from "react-router";
-import type { MessagingChannel } from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
@@ -32,7 +32,7 @@ import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";
import { toneDot, toneInk } from "../../lib/tone";
import { useCompany } from "../../state/company";
import { useProject } from "../../state/project";
-import { useLiveSessionStatuses, useSessions } from "../../state/sessions";
+import { useLiveSessionStatuses } from "../../state/sessions";
import { AgentAvatar } from "../../components/ui/agent-avatar";
import { Button } from "../../components/ui/button";
import { useRowContextMenu } from "../../components/ui/context-menu";
@@ -126,7 +126,6 @@ function DeskRow({
row,
active,
opening,
- messagingChannel,
onOpen,
onMessaging,
}: {
@@ -134,13 +133,13 @@ function DeskRow({
active: boolean;
/** This row's desk is being created right now (the click that creates it is in flight). */
opening: boolean;
- /** The enabled messaging binding of this desk's Session, from the session list store. */
- messagingChannel: MessagingChannel | undefined;
onOpen: () => void;
onMessaging: (sessionId: string) => void;
}) {
const ctx = useRowContextMenu();
const sessionId = row.sessionId;
+ /** The enabled messaging binding of this desk's Session, as the organization's sessions route marks it. */
+ const messagingChannel = row.messagingChannel;
const activity = orgRowActivity(row.status);
const deskName = S.company.sessionList.deskOf(row.name);
const label =
@@ -273,16 +272,6 @@ export function OrgSessionGroups({
/** The desk whose messaging binding is open in the dialog; null when none is. */
const [messagingSessionId, setMessagingSessionId] = useState<string | null>(null);
const live = useLiveSessionStatuses();
- const { sessions, replace } = useSessions();
- // Which desks relay to a bot. The organization's sessions route has no such field, so the
- // session list store is the only source — a desk it has not loaded simply shows no mark.
- const messaging = useMemo(() => {
- const map = new Map<string, MessagingChannel>();
- for (const s of sessions) {
- if (s.messagingChannel !== undefined) map.set(s.sessionId, s.messagingChannel);
- }
- return map;
- }, [sessions]);
const orgSessions = company.orgSessions.get(orgKey(projectId, orgId));
const desks = deskRows(company.orgChart, orgSessions, live);
const { openDesk, opening } = useOpenDesk(projectId, orgId, onNavigate);
@@ -318,7 +307,6 @@ export function OrgSessionGroups({
row={d}
active={d.sessionId !== null && d.sessionId === activeSessionId}
opening={opening === d.agentId}
- messagingChannel={d.sessionId === null ? undefined : messaging.get(d.sessionId)}
onOpen={() => void openDesk(d.agentId, d.sessionId)}
onMessaging={setMessagingSessionId}
/>
@@ -327,7 +315,8 @@ export function OrgSessionGroups({
)}
</FolderSection>
{/* Messaging binding dialog (the row menu's "Messaging binding…"): the row's indicator
- follows the dialog's own save/unbind outcome through the session list store. */}
+ follows the dialog's own enable/disable outcome, written into the company store's
+ copy of the sessions route. */}
{messagingSessionId !== null && (
<MessagingBindingModal
sessionId={messagingSessionId}
@@ -338,14 +327,7 @@ export function OrgSessionGroups({
// not happen — but when it does, the cache is what is stale: re-read it, and the
// editor's own toast has already said why the dialog closed.
onLoadFailed={() => void company.reloadOrgSessions()}
- onChanged={(sessionId, channel) => {
- const current = sessions.find((x) => x.sessionId === sessionId);
- if (!current) return;
- const updated = { ...current };
- if (channel !== null) updated.messagingChannel = channel;
- else delete updated.messagingChannel;
- replace(updated);
- }}
+ onChanged={company.setDeskMessagingChannel}
/>
)}
</div>
diff --git a/packages/web/src/features/company/org-sessions.ts b/packages/web/src/features/company/org-sessions.ts
index 7307e509..2044f7a9 100644
--- a/packages/web/src/features/company/org-sessions.ts
+++ b/packages/web/src/features/company/org-sessions.ts
@@ -1,9 +1,9 @@
/**
* The company sidebar's 工位 group, as pure shaping (unit tested) over the organization's
- * chart, its sessions route and the session list's live statuses: one row per EMPLOYEE, in
- * chart order, whether or not these caches already name its desk session. The roster is the
- * chart's (the sessions route only knows employees whose desk is in the ledger); the state is
- * the live one where the session list holds the row.
+ * chart, its sessions route and the live statuses the user channel has reported: one row per
+ * EMPLOYEE, in chart order, whether or not these caches already name its desk session. The
+ * roster is the chart's (the sessions route only knows employees whose desk is in the ledger);
+ * the state is the live one wherever an event has named the desk session.
*
* The employees' own states (the chart's dots, the overview's counts) are corrected the same
* way by `liveEmployeeStates` at the bottom of this file, which reads the sessions attached to
@@ -14,11 +14,12 @@
* them only move on an organization event: the sessions route is re-read when a run is
* dispatched (`org_run`) or a ticket moves, and the chart when a summary does — and a run
* ENDING publishes none of those. A desk would sit on 「运行中」 until some unrelated event
- * happened to arrive. The session list's own statuses come from the user event channel, which
- * reports every flip of every Session, so they are the state that is actually current; the
- * snapshots stand in for the rows that list has not loaded.
+ * happened to arrive. The live statuses are every `session_state` the user event channel has
+ * reported, and that channel reports every flip of every Session, so they are the state that
+ * is actually current; the snapshots stand in for a Session no event has named.
*/
import type {
+ MessagingChannel,
OrgChartResponse,
OrgEmployeeState,
OrgSessionsResponse,
@@ -27,9 +28,10 @@ import type {
import type { SessionActivity } from "../../lib/session-activity";
/**
- * Live run statuses by Session id — the session list store's view of them (state/sessions.tsx),
- * which the user event channel keeps in step. A Session the list has not loaded is simply
- * absent, and the caller falls back to the snapshot it does have.
+ * Live run statuses by Session id — every `session_state` the user event channel has reported,
+ * as the session list store remembers them (state/sessions.tsx, useLiveSessionStatuses). A
+ * Session no event has named is simply absent, and the caller falls back to the snapshot it
+ * does have.
*/
export type LiveSessionStatuses = ReadonlyMap<string, SessionStatus>;
@@ -46,6 +48,11 @@ export interface OrgDeskRow {
jobTitle: string;
sessionId: string | null;
status: SessionStatus;
+ /**
+ * The channel of the desk's enabled messaging binding, from the sessions route's own row;
+ * absent when it has none, or while that route has not listed the desk.
+ */
+ messagingChannel?: MessagingChannel;
}
/**
@@ -56,6 +63,9 @@ export interface OrgDeskRow {
* chart yet (the first read of an organization) the sessions route stands in: it walks the
* same chart server-side, so the order holds and only employees without a desk are missing
* until the chart lands.
+ *
+ * The messaging mark is the sessions route's alone: the chart carries no binding, and the
+ * development list — where a Session's mark used to be read — never holds a desk.
*/
export function deskRows(
chart: OrgChartResponse | null,
@@ -70,6 +80,7 @@ export function deskRows(
jobTitle: "",
sessionId: d.sessionId,
status: live?.get(d.sessionId) ?? d.status,
+ ...(d.messagingChannel !== undefined ? { messagingChannel: d.messagingChannel } : {}),
}));
}
return chart.employees.map((e) => {
@@ -82,10 +93,32 @@ export function deskRows(
jobTitle: e.title,
sessionId,
status: liveStatus ?? desk?.status ?? (e.state === "running" ? "running" : "idle"),
+ ...(desk?.messagingChannel !== undefined ? { messagingChannel: desk.messagingChannel } : {}),
};
});
}
+/**
+ * The sessions route's answer with one desk's messaging mark set to `channel` (null clears
+ * it) — what binding or unbinding a desk from its row menu writes into the loaded copy, so the
+ * row follows at once instead of at the next organization event. The same object when no desk
+ * names `sessionId` or the mark already says so, so a store holding it spends no render.
+ */
+export function withDeskMessagingChannel(
+ sessions: OrgSessionsResponse,
+ sessionId: string,
+ channel: MessagingChannel | null,
+): OrgSessionsResponse {
+ const at = sessions.desks.findIndex((d) => d.sessionId === sessionId);
+ if (at === -1 || (sessions.desks[at]!.messagingChannel ?? null) === channel) return sessions;
+ const desk = { ...sessions.desks[at]! };
+ if (channel === null) delete desk.messagingChannel;
+ else desk.messagingChannel = channel;
+ const desks = sessions.desks.slice();
+ desks[at] = desk;
+ return { ...sessions, desks };
+}
+
/**
* The glyph a desk row draws: the same live states the ordinary session list shows (an
* hourglass while running, the squeeze while compacting), and nothing when settled — a desk
@@ -102,9 +135,9 @@ export function orgRowActivity(status: SessionStatus): SessionActivity {
* any of them is running or compacting, idle once all of them have settled, and — when nothing
* is known about any of them — the state the chart itself reported.
*
- * Each Session is judged by the live status where the list holds it and by the organization's
- * own snapshot otherwise, which is exactly how the desk and ticket rows draw their marks, so
- * the chart and the sidebar can never say different things about the same run.
+ * Each Session is judged by its live status where an event has named it and by the
+ * organization's own snapshot otherwise, which is exactly how the desk and ticket rows draw
+ * their marks, so the chart and the sidebar can never say different things about the same run.
*
* `paused` is not a run state — the budget stopped the employee, and no Session can say
* otherwise — so it is returned untouched.
diff --git a/packages/web/src/lib/session-grouping.ts b/packages/web/src/lib/session-grouping.ts
index a357f3d9..da6465f2 100644
--- a/packages/web/src/lib/session-grouping.ts
+++ b/packages/web/src/lib/session-grouping.ts
@@ -593,82 +593,19 @@ export function isOrgSession(row: OrgSessionMarks): boolean {
}
/**
- * The development list's own rows, and the ones an organization owns.
+ * The rows the development list shows: the user's own conversations, ALWAYS. An
+ * organization's Sessions are driven by its scheduler rather than by the user, which is a
+ * fact about the Session and not about the shell around it — so neither company mode being
+ * switched off (the admin's master switch or the user's own) nor the organization being
+ * deleted turns one back into a conversation of this list. They are reached as themselves in
+ * company mode — a desk from the 工位 group, a ticket session from the ticket that started it
+ * — and stay reachable by their own url and through the Trace page regardless.
*
- * Development mode lists only the first half, and it does so ALWAYS. An organization's
- * Sessions are driven by its scheduler rather than by the user, which is a fact about the
- * Session and not about the shell around it — so neither company mode being switched off (the
- * admin's master switch or the user's own) nor the organization being deleted turns one back
- * into a conversation of this list. They are reached as themselves in company mode — a desk
- * from the 工位 group, a ticket session from the ticket that started it — and stay reachable
- * by their own url and through the Trace page regardless.
- *
- * The second half is not waste: the server's totals count those rows, so the group headers
- * and the "show the rest" arithmetic have to subtract them (countsWithoutOrgSessions).
- */
-export function splitDevelopmentList<T extends { sessionId: string } & OrgSessionMarks>(
- rows: readonly T[],
-): { own: T[]; organization: T[] } {
- const own: T[] = [];
- const organization: T[] = [];
- for (const s of rows) (isOrgSession(s) ? organization : own).push(s);
- return { own, organization };
-}
-
-/** Just the rows the development list shows — splitDevelopmentList's first half. */
-export function withoutOrgSessions<T extends { sessionId: string } & OrgSessionMarks>(
- rows: readonly T[],
-): T[] {
- return splitDevelopmentList(rows).own;
-}
-
-/** A per-category counter set, copied so the correction below never writes into the store's. */
-function copyCounts(counts: SessionCategoryCounts): SessionCategoryCounts {
- return { ...counts };
-}
-
-/**
- * The server's per-category totals with the organization rows the list does not show taken
- * back out — the per-Agent totals and their per-Workspace breakdown together, in one pass, so
- * the two can never disagree about the same group.
- *
- * The server counts every Session of an Agent, an organization's desks and ticket sessions
- * included, while the development list draws the user's own. A group header promising five
- * where three rows follow is the visible half of that gap; a "show the rest" row that reveals
- * nothing is the other. Only rows already LOADED can be subtracted, so a group whose
- * organization rows sit past the fetched pages still counts a little high — the direction
- * this number has always erred in, and it settles as those pages arrive.
- *
- * The fetch logic reads the store's raw counts, not these: what is worth fetching does not
- * change because a row will not be drawn.
+ * The list's own fetches already leave these rows out, totals included (the server's
+ * `excludeOrg`); this is the guard for a row that enters by another door — the chat page's
+ * deep-link self-heal — and, applied at the source, it keeps such a row from conjuring the
+ * Workspace group, Agent group or time bucket it would belong to.
*/
-export function countsWithoutOrgSessions(
- byAgent: ReadonlyMap<string, SessionCategoryCounts>,
- byWorkspace: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>,
- organizationRows: readonly SessionInfo[],
-): {
- byAgent: ReadonlyMap<string, SessionCategoryCounts>;
- byWorkspace: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>;
-} {
- if (organizationRows.length === 0) return { byAgent, byWorkspace };
- const agents = new Map([...byAgent].map(([id, counts]) => [id, copyCounts(counts)]));
- const workspaces = new Map(
- [...byWorkspace].map(
- ([id, perWorkspace]) =>
- [
- id,
- Object.fromEntries(
- Object.entries(perWorkspace).map(([path, counts]) => [path, copyCounts(counts)]),
- ),
- ] as const,
- ),
- );
- for (const row of organizationRows) {
- const category = sessionCategory(row);
- const counts = agents.get(row.agentId);
- if (counts) counts[category] = Math.max(counts[category] - 1, 0);
- const perWorkspace = workspaces.get(row.agentId)?.[row.workspace];
- if (perWorkspace) perWorkspace[category] = Math.max(perWorkspace[category] - 1, 0);
- }
- return { byAgent: agents, byWorkspace: workspaces };
+export function withoutOrgSessions<T extends OrgSessionMarks>(rows: readonly T[]): T[] {
+ return rows.filter((s) => !isOrgSession(s));
}
diff --git a/packages/web/src/state/company.tsx b/packages/web/src/state/company.tsx
index c698480f..7ebf7bd6 100644
--- a/packages/web/src/state/company.tsx
+++ b/packages/web/src/state/company.tsx
@@ -40,6 +40,7 @@ import { createContext, useContext, useEffect, useMemo, useRef, useState } from
import type { ReactNode } from "react";
import type {
CompanyServerEvent,
+ MessagingChannel,
OrgChannelItem,
OrgChartResponse,
OrgSessionsResponse,
@@ -56,6 +57,7 @@ import { markBetaNoticeShown, shouldShowBetaNotice } from "../features/company/b
import { channelBadgeCounts } from "../features/company/channel-list";
import { orgKey, parseOrgKey } from "../features/company/company-nav";
import type { WorkMode } from "../features/company/company-nav";
+import { withDeskMessagingChannel } from "../features/company/org-sessions";
import {
clearLastOrgKey,
initialLastOrgKey,
@@ -95,6 +97,25 @@ export function subscribeCompanyEvents(listener: CompanyEventListener): () => vo
};
}
+/**
+ * The user channel reconnected past its replay buffer (`resync_required`): any number of the
+ * events above were lost, and so were the `session_state` flips company surfaces take run state
+ * from — the session list store forgets those on the same event, and the company store re-reads
+ * the snapshots they would otherwise have corrected (`resync`).
+ */
+const resyncListeners = new Set<() => void>();
+
+export function publishCompanyResync(): void {
+ for (const listener of resyncListeners) listener();
+}
+
+export function subscribeCompanyResync(listener: () => void): () => void {
+ resyncListeners.add(listener);
+ return () => {
+ resyncListeners.delete(listener);
+ };
+}
+
/** Subscribes a component to company events for its mounted lifetime; the latest handler is always the one called. */
export function useCompanyEvents(handler: CompanyEventListener): void {
const ref = useRef(handler);
@@ -111,12 +132,12 @@ export interface TicketDialogTarget {
/** Version counters, one per event family: a page refetches when the one it depends on moves. */
export interface CompanyVersions {
- /** The organization list (an org's summary counts changed: a budget pause, a run). */
+ /** The organization list (an org's summary counts changed: a budget pause, a run, a resync). */
orgs: number;
/** A new message landed in one of the organization's channels. */
messages: number;
tickets: number;
- /** A desk or ticket Session was opened by the scheduler. */
+ /** A desk or ticket Session was opened by the scheduler, or a resync may have lost that news. */
runs: number;
budget: number;
}
@@ -181,12 +202,15 @@ interface CompanyStoreState {
reloadOrganizations: (projectIds: readonly string[]) => Promise<void>;
forgetMissingOrganizations: () => void;
reloadOrgSessions: (projectId: string) => Promise<void>;
+ /** A desk was bound to a messaging bot here (or unbound: null): its row's mark follows without a re-read. */
+ setDeskMessagingChannel: (sessionId: string, channel: MessagingChannel | null) => void;
reloadOrgChart: (projectId: string, orgId: string) => Promise<void>;
openTicket: (projectId: string, orgId: string, ticketId: string) => void;
closeTicket: () => void;
backTicket: () => void;
ticketsChanged: () => void;
applyCompanyEvent: (ev: CompanyServerEvent, userId: string | null) => void;
+ resync: () => void;
}
/** The two badge numbers of a channel listing (channel-list.ts), in the shape the store stores them. */
@@ -393,6 +417,19 @@ export function createCompanyStore() {
set({ orgSessions: next });
},
+ setDeskMessagingChannel: (sessionId, channel) => {
+ // A Session id is unique across organizations, so every entry is asked and at most one
+ // changes; nothing is set when none does.
+ let changed = false;
+ const next = new Map<string, OrgSessionsResponse>();
+ for (const [key, sessions] of get().orgSessions) {
+ const patched = withDeskMessagingChannel(sessions, sessionId, channel);
+ if (patched !== sessions) changed = true;
+ next.set(key, patched);
+ }
+ if (changed) set({ orgSessions: next });
+ },
+
/**
* Re-reads the open organization's chart (the 工位 group's roster). A response for an
* organization the shell has since left is dropped, and a failure leaves whatever the
@@ -498,6 +535,16 @@ export function createCompanyStore() {
}
set({ versions });
},
+
+ /**
+ * Events were lost (see publishCompanyResync): re-read the snapshots that carry run state
+ * through the versions that already drive them — `runs` the sessions route, `orgs` the
+ * organization list and the open chart — so the surfaces stand on current state again.
+ */
+ resync: () => {
+ const versions = get().versions;
+ set({ versions: { ...versions, runs: versions.runs + 1, orgs: versions.orgs + 1 } });
+ },
}));
}
@@ -532,6 +579,8 @@ interface CompanyContextValue {
markChannelRead: (channelId: string) => void;
/** Desk and ticket Sessions of every organization of the current Project, keyed by org key. */
orgSessions: ReadonlyMap<string, OrgSessionsResponse>;
+ /** Writes a desk's messaging binding change into `orgSessions` (null = unbound), so its row's mark follows at once. */
+ setDeskMessagingChannel: (sessionId: string, channel: MessagingChannel | null) => void;
/** The open organization's employees, in chart order; null until the first read. */
orgChart: OrgChartResponse | null;
orgChartError: string | null;
@@ -664,6 +713,7 @@ export function CompanyProvider({ children }: { children: ReactNode }) {
() => subscribeCompanyEvents((ev) => store.getState().applyCompanyEvent(ev, userId)),
[store, userId],
);
+ useEffect(() => subscribeCompanyResync(() => store.getState().resync()), [store]);
const value = useMemo<CompanyContextValue>(() => {
const available = serverEnabled && state.personalEnabled;
@@ -699,6 +749,7 @@ export function CompanyProvider({ children }: { children: ReactNode }) {
},
markChannelRead: state.markChannelRead,
orgSessions: state.orgSessions,
+ setDeskMessagingChannel: state.setDeskMessagingChannel,
orgChart: state.orgChart,
orgChartError: state.orgChartError,
reloadOrgChart: () => {
diff --git a/packages/web/src/state/sessions.tsx b/packages/web/src/state/sessions.tsx
index fcd16b43..59909554 100644
--- a/packages/web/src/state/sessions.tsx
+++ b/packages/web/src/state/sessions.tsx
@@ -13,6 +13,15 @@
* back to its first page (an open folder must not blank on an event-triggered refresh)
* and leaves unopened folders unloaded.
*
+ * **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
+ * 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
+ * mode's surfaces read them for the Sessions this list deliberately does not fetch
+ * (useLiveSessionStatuses).
+ *
* **Sessions are not auto-created here**: a new conversation starts as a draft (chat page `/chat/new`),
* and the Session is only actually created when the first message is sent — after landing, the user
* may still switch models or configure an API key first, so persisting the Session early would both
@@ -37,10 +46,11 @@ import { useStore } from "zustand/react";
import { createStore } from "zustand/vanilla";
import * as api from "../api/endpoints";
import { openUserEvents } from "../api/sse";
-import { isCompanyEvent, publishCompanyEvent } from "./company";
+import { isCompanyEvent, publishCompanyEvent, publishCompanyResync } from "./company";
import {
FOLDER_CATEGORIES,
SIDEBAR_PAGE_SIZE,
+ isOrgSession,
sessionCategory,
splitPage,
workspaceGroupKey,
@@ -60,6 +70,8 @@ interface SessionsContextValue {
workspaceCountsByAgent: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>;
/** agentId → each Workspace path's newest Session `createdAt` from the last list fetch: what places a workspace-mode group before any of its rows are loaded. */
workspaceLatestByAgent: ReadonlyMap<string, Readonly<Record<string, string>>>;
+ /** Every run status the user channel has reported this page's lifetime, by Session id — loaded row or not (see useLiveSessionStatuses). */
+ liveStatuses: ReadonlyMap<string, SessionStatus>;
/**
* Whether a pair's first page has been fetched (false = the folder shows nothing because
* nothing was asked for yet). `workspaceGroup` asks about ONE group's own stream, which
@@ -177,6 +189,16 @@ interface SessionsStoreState {
countsByAgent: ReadonlyMap<string, SessionCategoryCounts>;
workspaceCountsByAgent: ReadonlyMap<string, Readonly<Record<string, SessionCategoryCounts>>>;
workspaceLatestByAgent: ReadonlyMap<string, Readonly<Record<string, string>>>;
+ /**
+ * Run status by Session id as the user channel last reported it, for every `session_state`
+ * received — the rows this store holds AND the ones it never fetches (an organization's
+ * desks and ticket sessions, another category's unopened folder). The user channel is the
+ * only source that reports a run ENDING, so company mode's surfaces read this for the
+ * Sessions the development list deliberately leaves out. Not reset on a Project switch:
+ * ids are globally unique and a status is a fact about the Session, not about the list.
+ * Cleared on `resync_required`, which says flips were lost (see applyUserEvent).
+ */
+ liveStatuses: ReadonlyMap<string, SessionStatus>;
loading: boolean;
reload: () => Promise<void>;
@@ -206,6 +228,28 @@ interface SessionsStoreState {
*/
const DELETED_IDS_MAX = 500;
+/**
+ * Cap on remembered live statuses, for the same reason as DELETED_IDS_MAX: a very long-lived
+ * tab must not grow the map without bound. Evicts oldest-first; a Session that flips again is
+ * re-inserted at the end, so what falls off is what has been quiet longest — and a dropped
+ * entry only costs company mode a fallback to its own snapshot for that Session.
+ */
+const LIVE_STATUS_MAX = 1000;
+
+/** `live` with `sessionId` at `status` — the same map when nothing changed, so no render is spent on a repeat. */
+function rememberStatus(
+ live: ReadonlyMap<string, SessionStatus>,
+ sessionId: string,
+ status: SessionStatus,
+): ReadonlyMap<string, SessionStatus> {
+ if (live.get(sessionId) === status) return live;
+ const next = new Map(live);
+ next.delete(sessionId);
+ next.set(sessionId, status);
+ while (next.size > LIVE_STATUS_MAX) next.delete(next.keys().next().value!);
+ return next;
+}
+
/**
* Builds one Provider's store. Exported as a test seam: vitest runs this package in Node with
* no DOM, so the list's own behaviour is exercised against the store directly rather than
@@ -217,8 +261,15 @@ export function createSessionsStore() {
let gen = 0;
return createStore<SessionsStoreState>((set, get) => {
- /** 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). */
+ /**
+ * 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.
+ */
const adjustCount = (session: SessionInfo, category: SessionCategory, delta: number) => {
+ if (isOrgSession(session)) return;
const { agentId, workspace } = session;
const counts = get().countsByAgent;
const cur = counts.get(agentId);
@@ -256,6 +307,7 @@ export function createSessionsStore() {
countsByAgent: new Map(),
workspaceCountsByAgent: new Map(),
workspaceLatestByAgent: new Map(),
+ liveStatuses: new Map(),
loading: true,
reload: async () => {
@@ -290,6 +342,7 @@ export function createSessionsStore() {
offset: 0,
limit: SIDEBAR_PAGE_SIZE + 1,
category,
+ excludeOrg: true,
...(scope === "" ? {} : { workspaceGroup: scope }),
...(category === "active" && scope === "" ? { withCounts: true } : {}),
});
@@ -337,8 +390,12 @@ export function createSessionsStore() {
}
}
}
+ // No fetch returns an organization row (`excludeOrg`), so one held here entered
+ // through add() for the page showing it (an open desk or ticket session) and no
+ // reload can bring it back: carry it over, or that page's writes stop reaching it.
+ const held = get().sessions.filter((s) => isOrgSession(s) && !seen.has(s.sessionId));
set({
- sessions: nextSessions,
+ sessions: [...nextSessions, ...held],
pageState: nextPageState,
countsByAgent: nextCounts,
workspaceCountsByAgent: nextWorkspaceCounts,
@@ -408,6 +465,7 @@ export function createSessionsStore() {
offset,
limit: SIDEBAR_PAGE_SIZE + 1,
category,
+ excludeOrg: true,
...(scope === "" ? {} : { workspaceGroup: scope }),
})
).sessions;
@@ -519,11 +577,20 @@ export function createSessionsStore() {
* Session, it does not describe one, and a row invented from a status and a timestamp
* would have no title, Agent or Workspace to render. That same drop is what filters
* another Project's Sessions — this store only ever holds the current Project's rows.
+ * The STATUS is remembered either way (`liveStatuses`): the user channel is the one
+ * source that reports a run ending, and company mode reads it for the Sessions this
+ * list never fetches.
*/
setStatus: (sessionId, status, row) => {
+ const remembered = rememberStatus(get().liveStatuses, sessionId, status);
+ // The remembered half of the write, empty when this status was already on record.
+ const patch = remembered === get().liveStatuses ? {} : { liveStatuses: remembered };
const prev = get().sessions;
const target = prev.find((s) => s.sessionId === sessionId);
- if (!target) return;
+ if (!target) {
+ if ("liveStatuses" in patch) set(patch);
+ return;
+ }
const lastActiveAt = row?.lastActiveAt ?? target.lastActiveAt;
const live = status === "running" || status === "compacting";
const hasTrace = target.hasTrace || row?.hasTrace === true || live;
@@ -532,9 +599,11 @@ export function createSessionsStore() {
target.lastActiveAt === lastActiveAt &&
target.hasTrace === hasTrace
) {
+ if ("liveStatuses" in patch) set(patch);
return;
}
set({
+ ...patch,
sessions: prev.map((s) =>
s.sessionId === sessionId ? { ...s, status, lastActiveAt, hasTrace } : s,
),
@@ -645,9 +714,13 @@ export function applyUserEvent(
}
// The reconnect landed outside the channel's replay buffer, so an unknown number of the flips
// above were lost — away long enough and a row sits on an hourglass that will never stop.
- // Refetch once, on the event that says so, rather than polling for it.
+ // Refetch once, on the event that says so, rather than polling for it. The remembered
+ // statuses go too: no fetch here refreshes them, and a stale entry beats every fresh snapshot
+ // company mode reads, so those surfaces re-read their snapshots and fall back to them.
if (ev.type === "resync_required") {
+ store.setState({ liveStatuses: new Map() });
void store.getState().reload();
+ publishCompanyResync();
return;
}
// Company-mode notifications fan out to the company store and any mounted organization page
@@ -695,6 +768,7 @@ export function SessionsProvider({ children }: { children: ReactNode }) {
// deletedSessionIds is deliberately NOT reset: session ids are globally unique and never
// reused, so a Session deleted before a Project switch is still deleted after it — and
// re-arming its lookup would just re-create the 404 this set exists to prevent.
+ // liveStatuses stays for the same reason: a status is a fact about the Session.
store.setState({
projectId,
agentIds: agentIdsKey === "" ? [] : agentIdsKey.split(","),
@@ -782,6 +856,7 @@ export function SessionsProvider({ children }: { children: ReactNode }) {
countsByAgent: state.countsByAgent,
workspaceCountsByAgent: state.workspaceCountsByAgent,
workspaceLatestByAgent: state.workspaceLatestByAgent,
+ liveStatuses: state.liveStatuses,
isLoadedFor,
hasMoreFor,
loading: state.loading,
@@ -806,15 +881,37 @@ export function useSessions(): SessionsContextValue {
}
/**
- * Every loaded Session's run status by id — the user event channel's view of it, which is the
- * only one that reports a run ENDING. Surfaces built on a server-side snapshot (company mode's
- * desk and ticket rows, the org chart's state dots, the overview's employee counts) read this
- * first and keep their snapshot for the rows this list has not loaded: their snapshots are
- * re-read on organization events, and no event announces that a run finished.
+ * Run status by Session id as this page knows it: every status the user channel has reported
+ * (`live`, loaded row or not), with a loaded row's own status winning — a row is written by
+ * the same events AND by every list fetch, so it is never older than the remembered entry,
+ * while an id the list does not hold has only the remembered one. An organization row held for
+ * the page showing it is the exception: no list fetch refreshes it, so it speaks for nothing
+ * and its Session has the remembered entry alone (which a resync clears). Pure, so the merge
+ * the hook below publishes is testable without a React tree.
+ */
+export function liveSessionStatuses(
+ sessions: readonly SessionInfo[],
+ live: ReadonlyMap<string, SessionStatus>,
+): ReadonlyMap<string, SessionStatus> {
+ const out = new Map(live);
+ for (const s of sessions) if (!isOrgSession(s)) out.set(s.sessionId, s.status);
+ return out;
+}
+
+/**
+ * Run status by Session id — the user event channel's view of it, which is the only one that
+ * reports a run ENDING. Surfaces built on a server-side snapshot (company mode's desk and
+ * ticket rows, the org chart's state dots, the overview's employee counts) read this first and
+ * keep their snapshot for a Session no event has named yet: their snapshots are re-read on
+ * organization events and on a resync, and no event announces that a run finished. The
+ * development list never fetches an organization's Sessions, so for them this is the
+ * remembered `session_state` alone — which reaches every one of them, not only the first page
+ * of an employee's stream.
*
- * Memoized on the rows, so a consumer re-shapes only when a status (or the list) actually moves.
+ * Memoized on the rows and the remembered statuses, so a consumer re-shapes only when one
+ * actually moves.
*/
export function useLiveSessionStatuses(): ReadonlyMap<string, SessionStatus> {
- const { sessions } = useSessions();
- return useMemo(() => new Map(sessions.map((s) => [s.sessionId, s.status])), [sessions]);
+ const { sessions, liveStatuses } = useSessions();
+ return useMemo(() => liveSessionStatuses(sessions, liveStatuses), [sessions, liveStatuses]);
}
diff --git a/packages/web/test/company-store.test.ts b/packages/web/test/company-store.test.ts
index eb1ee0d0..42cb0c36 100644
--- a/packages/web/test/company-store.test.ts
+++ b/packages/web/test/company-store.test.ts
@@ -4,18 +4,25 @@
* version bump each family causes, and what a local read mark clears), the open ticket every
* company surface shares (the back stack a parent or a child pushes, and what closes it), what
* it forgets when the organization list comes back without the organization it is aimed at,
- * and the
+ * a desk's messaging mark written into the loaded sessions route by a bind or an unbind, and the
* user-channel forwarding in state/sessions.tsx's applyUserEvent — a company event reaches
- * every subscriber, and a work run refreshes the session list of the Project it belongs to.
+ * every subscriber, a work run refreshes the session list of the Project it belongs to, and a
+ * resync re-reads the company snapshots.
*/
import { describe, expect, it, vi } from "vitest";
import type {
CompanyServerEvent,
OrgChannelItem,
OrgChannelMessage,
+ OrgSessionsResponse,
OrganizationSummary,
} from "@prismshadow/penguin-server/api";
-import { createCompanyStore, isCompanyEvent, subscribeCompanyEvents } from "../src/state/company";
+import {
+ createCompanyStore,
+ isCompanyEvent,
+ subscribeCompanyEvents,
+ subscribeCompanyResync,
+} from "../src/state/company";
import { applyUserEvent, createSessionsStore } from "../src/state/sessions";
const message = (over: Partial<OrgChannelMessage> = {}): OrgChannelMessage => ({
@@ -280,6 +287,43 @@ describe("forgetting an organization the list no longer holds", () => {
});
});
+describe("a desk's messaging binding changed here", () => {
+ const desks = (agentId: string, sessionId: string): OrgSessionsResponse => ({
+ desks: [{ agentId, name: agentId, sessionId, status: "idle", workspace: "/w" }],
+ tickets: [],
+ });
+
+ it("marks the desk in whichever organization holds it, and clears the mark on unbind", () => {
+ const store = createCompanyStore();
+ const other = desks("beta_ceo", "s-beta");
+ store.setState({
+ orgSessions: new Map([
+ ["p1/acme", desks("acme_ceo", "s-acme")],
+ ["p1/beta", other],
+ ]),
+ });
+ store.getState().setDeskMessagingChannel("s-acme", "telegram");
+ expect(store.getState().orgSessions.get("p1/acme")?.desks[0]?.messagingChannel).toBe(
+ "telegram",
+ );
+ // The organization that does not hold the desk keeps its very answer.
+ expect(store.getState().orgSessions.get("p1/beta")).toBe(other);
+
+ store.getState().setDeskMessagingChannel("s-acme", null);
+ expect(store.getState().orgSessions.get("p1/acme")?.desks[0]).not.toHaveProperty(
+ "messagingChannel",
+ );
+ });
+
+ it("sets nothing when no loaded desk is that Session", () => {
+ const store = createCompanyStore();
+ store.setState({ orgSessions: new Map([["p1/acme", desks("acme_ceo", "s-acme")]]) });
+ const before = store.getState().orgSessions;
+ store.getState().setDeskMessagingChannel("s-elsewhere", "qq");
+ expect(store.getState().orgSessions).toBe(before);
+ });
+});
+
describe("the ticket dialog the whole shell shares", () => {
const open = (store: ReturnType<typeof createCompanyStore>) => store.getState().ticketDialog;
@@ -375,4 +419,24 @@ describe("applyUserEvent forwarding", () => {
stop();
}
});
+
+ it("a resync has the company store re-read the snapshots its surfaces now fall back to", () => {
+ const sessions = createSessionsStore();
+ sessions.setState({ projectId: "p1", reload: vi.fn(() => Promise.resolve()) });
+ const company = createCompanyStore();
+ const stop = subscribeCompanyResync(() => company.getState().resync());
+ try {
+ applyUserEvent(sessions, { type: "resync_required" }, () => undefined);
+ // `runs` re-reads the sessions route; `orgs` the organization list and the open chart.
+ expect(company.getState().versions).toEqual({
+ orgs: 1,
+ messages: 0,
+ tickets: 0,
+ runs: 1,
+ budget: 0,
+ });
+ } finally {
+ stop();
+ }
+ });
});
diff --git a/packages/web/test/org-sessions.test.ts b/packages/web/test/org-sessions.test.ts
index 7ca55558..de75e057 100644
--- a/packages/web/test/org-sessions.test.ts
+++ b/packages/web/test/org-sessions.test.ts
@@ -2,26 +2,26 @@
* The company sidebar's 工位 group (features/company/org-sessions.ts) and the development
* list's organization filter (session-grouping): a desk row per employee in chart order
* whether or not a desk exists, the session list's live status winning over both snapshots,
+ * the messaging mark read from the sessions route and patched by a bind or an unbind,
* the glyph a row draws, an employee's own state read from every Session the organization
* attributes to it — its ticket sessions included, though no list shows them as a group —
- * the split of a loaded list into the user's own rows and the organizations', and the totals
- * corrected by what that split hid.
+ * and the render-time guard that keeps an organization's row out of the development list when
+ * one still reaches it (the server leaves them out of the list's own fetches; see
+ * sessions-own-rows.test.ts).
*/
import { describe, expect, it } from "vitest";
import type {
OrgChartResponse,
OrgSessionsResponse,
- SessionCategoryCounts,
- SessionInfo,
SessionStatus,
} from "@prismshadow/penguin-server/api";
-import { deskRows, liveEmployeeStates, orgRowActivity } from "../src/features/company/org-sessions";
import {
- countsWithoutOrgSessions,
- isOrgSession,
- splitDevelopmentList,
- withoutOrgSessions,
-} from "../src/lib/session-grouping";
+ deskRows,
+ liveEmployeeStates,
+ orgRowActivity,
+ withDeskMessagingChannel,
+} from "../src/features/company/org-sessions";
+import { isOrgSession, withoutOrgSessions } from "../src/lib/session-grouping";
const liveStatuses = (entries: Record<string, SessionStatus>): ReadonlyMap<string, SessionStatus> =>
new Map(Object.entries(entries));
@@ -155,6 +155,53 @@ describe("deskRows", () => {
});
});
+describe("the desk row's messaging mark", () => {
+ const bound: OrgSessionsResponse = {
+ ...sessions,
+ desks: sessions.desks.map((d) =>
+ d.agentId === "ceo" ? { ...d, messagingChannel: "telegram" as const } : d,
+ ),
+ };
+
+ // The development list never holds a desk, so the sessions route is the only place the
+ // binding is read from — with or without a chart.
+ it("carries the sessions route's channel onto the desk it names, and nothing onto the rest", () => {
+ const rows = deskRows(chart, bound);
+ expect(rows[0]).toMatchObject({ agentId: "ceo", messagingChannel: "telegram" });
+ expect(rows[1]).not.toHaveProperty("messagingChannel");
+ expect(rows[2]).not.toHaveProperty("messagingChannel");
+ expect(deskRows(null, bound).find((d) => d.agentId === "ceo")).toMatchObject({
+ messagingChannel: "telegram",
+ });
+ // A desk only the chart names yet has no sessions-route row to be marked by.
+ expect(deskRows(chart, { desks: [], tickets: [] })[0]).not.toHaveProperty("messagingChannel");
+ });
+
+ it("follows a bind, a switch of channel and an unbind written into the loaded answer", () => {
+ const pm = (r: OrgSessionsResponse) => r.desks.find((d) => d.sessionId === "s-pm");
+ const onPm = withDeskMessagingChannel(bound, "s-pm", "feishu");
+ expect(pm(onPm)?.messagingChannel).toBe("feishu");
+ expect(deskRows(chart, onPm)[1]).toMatchObject({ agentId: "pm", messagingChannel: "feishu" });
+ // The input is left as it was: the store's previous copy is never written into.
+ expect(pm(bound)).not.toHaveProperty("messagingChannel");
+
+ expect(pm(withDeskMessagingChannel(onPm, "s-pm", "qq"))?.messagingChannel).toBe("qq");
+ const off = withDeskMessagingChannel(onPm, "s-pm", null);
+ expect(pm(off)).not.toHaveProperty("messagingChannel");
+ expect(deskRows(chart, off)[1]).not.toHaveProperty("messagingChannel");
+ // The other desk and the tickets ride through untouched.
+ expect(off.desks.find((d) => d.agentId === "ceo")?.messagingChannel).toBe("telegram");
+ expect(off.tickets).toBe(bound.tickets);
+ });
+
+ it("hands back the same answer when no desk is that Session or the mark already says so", () => {
+ // A ticket session is not a desk: the sidebar draws no mark for it.
+ expect(withDeskMessagingChannel(bound, "s-t1", "telegram")).toBe(bound);
+ expect(withDeskMessagingChannel(bound, "s-ceo", "telegram")).toBe(bound);
+ expect(withDeskMessagingChannel(bound, "s-pm", null)).toBe(bound);
+ });
+});
+
describe("orgRowActivity", () => {
it("draws the live states and nothing when settled", () => {
expect(orgRowActivity("running")).toBe("running");
@@ -232,7 +279,7 @@ describe("isOrgSession", () => {
});
});
-describe("splitDevelopmentList", () => {
+describe("withoutOrgSessions", () => {
const rows = [
{ sessionId: "a" },
{ sessionId: "s-ceo", orgId: "acme" },
@@ -242,15 +289,11 @@ describe("splitDevelopmentList", () => {
{ sessionId: "s-orphan", client: "org" },
];
- it("moves the organizations' rows into their own list, keeping order on both sides", () => {
- expect(splitDevelopmentList(rows)).toEqual({
- own: [{ sessionId: "a" }, { sessionId: "b", client: "web" }],
- organization: [
- { sessionId: "s-ceo", orgId: "acme" },
- { sessionId: "s-t1", orgId: "acme" },
- { sessionId: "s-orphan", client: "org" },
- ],
- });
+ it("keeps the user's own rows in order and drops the organizations' by either mark", () => {
+ expect(withoutOrgSessions(rows)).toEqual([
+ { sessionId: "a" },
+ { sessionId: "b", client: "web" },
+ ]);
});
it("treats an empty orgId as no organization", () => {
@@ -261,84 +304,8 @@ describe("splitDevelopmentList", () => {
});
it("hides the organizations' rows whatever the company-mode switches say", () => {
- // There is no switch to pass any more: this list is the user's own conversations, and a
- // Session the scheduler drives is not one whether or not company mode is on screen.
+ // There is no switch to pass: this list is the user's own conversations, and a Session
+ // the scheduler drives is not one whether or not company mode is on screen.
expect(withoutOrgSessions(rows).map((s) => s.sessionId)).toEqual(["a", "b"]);
});
});
-
-describe("countsWithoutOrgSessions", () => {
- const row = (over: Partial<SessionInfo>): SessionInfo =>
- ({
- sessionId: "s",
- projectId: "p",
- agentId: "ceo",
- provider: "custom",
- modelId: "m",
- workspace: "/org",
- approvalMode: "allow-all",
- createdAt: "2026-09-02T00:00:00Z",
- lastActiveAt: "2026-09-02T00:00:00Z",
- status: "idle",
- pendingApprovalCount: 0,
- pendingFollowUpCount: 0,
- hasTrace: true,
- archived: false,
- ...over,
- }) as SessionInfo;
- const counts = new Map<string, SessionCategoryCounts>([
- ["ceo", { active: 3, subagent: 0, schedule: 0, benchmark: 0, archived: 1 }],
- ["other", { active: 2, subagent: 0, schedule: 0, benchmark: 0, archived: 0 }],
- ]);
- const workspaceCounts = new Map<string, Readonly<Record<string, SessionCategoryCounts>>>([
- ["ceo", { "/org": { active: 3, subagent: 0, schedule: 0, benchmark: 0, archived: 1 } }],
- ["other", { "/w": { active: 2, subagent: 0, schedule: 0, benchmark: 0, archived: 0 } }],
- ]);
-
- it("subtracts each hidden row from its Agent's totals and from its Workspace's share", () => {
- const out = countsWithoutOrgSessions(counts, workspaceCounts, [
- row({ sessionId: "s-desk", orgId: "acme" }),
- row({ sessionId: "s-old", orgId: "acme", archived: true }),
- ]);
- expect(out.byAgent.get("ceo")).toEqual({
- active: 2,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
- expect(out.byWorkspace.get("ceo")?.["/org"]).toEqual({
- active: 2,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
- // Another Agent's totals are untouched, and the store's own maps are never written into.
- expect(out.byAgent.get("other")).toEqual({
- active: 2,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 0,
- });
- expect(counts.get("ceo")).toEqual({
- active: 3,
- subagent: 0,
- schedule: 0,
- benchmark: 0,
- archived: 1,
- });
- });
-
- it("gives the maps straight back when nothing is hidden, and never counts below zero", () => {
- expect(countsWithoutOrgSessions(counts, workspaceCounts, []).byAgent).toBe(counts);
- const out = countsWithoutOrgSessions(counts, workspaceCounts, [
- row({ agentId: "other", workspace: "/w", orgId: "acme" }),
- row({ agentId: "other", workspace: "/w", orgId: "acme" }),
- row({ agentId: "other", workspace: "/w", orgId: "acme" }),
- ]);
- expect(out.byAgent.get("other")?.active).toBe(0);
- expect(out.byWorkspace.get("other")?.["/w"]?.active).toBe(0);
- });
-});
diff --git a/packages/web/test/sessions-own-rows.test.ts b/packages/web/test/sessions-own-rows.test.ts
new file mode 100644
index 00000000..408473c0
--- /dev/null
+++ b/packages/web/test/sessions-own-rows.test.ts
@@ -0,0 +1,184 @@
+/**
+ * The development list holds the user's own conversations, end to end (state/sessions.tsx).
+ *
+ * An organization's desk and ticket Sessions (and the sub-sessions they spawn) must never
+ * reach development mode's list — not as rows, and not as the totals and Workspace stamps
+ * the sidebar builds groups from. The store therefore asks the server for its own rows only
+ * on every fetch, keeps the server's totals as they are when an organization row still
+ * enters by another door (a deep link's self-heal) and carries that row across reloads, and
+ * remembers every live status the user channel reports whether or not a loaded page holds the
+ * row — which is what company mode's surfaces read, now that the rows themselves are no longer
+ * fetched here — until a resync says flips were lost.
+ *
+ * The store is exercised directly (node, no DOM); the API module is mocked at the seam.
+ */
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { ServerEvent, SessionInfo, SessionsResponse } from "@prismshadow/penguin-server/api";
+
+vi.mock("../src/api/endpoints", () => ({ listSessions: vi.fn() }));
+
+import * as api from "../src/api/endpoints";
+import { applyUserEvent, createSessionsStore, liveSessionStatuses } from "../src/state/sessions";
+
+const listSessions = vi.mocked(api.listSessions);
+
+const NO_ROWS: SessionsResponse = { sessions: [] };
+const COUNTS = { active: 1, subagent: 1, schedule: 0, benchmark: 0, archived: 0 };
+
+function session(sessionId: string, over: Partial<SessionInfo> = {}): SessionInfo {
+ return {
+ sessionId,
+ projectId: "proj",
+ agentId: "default_agent",
+ provider: "anthropic",
+ modelId: "claude-sonnet-4",
+ workspace: "/w",
+ approvalMode: "allow-all",
+ createdAt: "2026-09-16T09:00:00.000Z",
+ lastActiveAt: "2026-09-16T09:00:00.000Z",
+ status: "idle",
+ pendingApprovalCount: 0,
+ pendingFollowUpCount: 0,
+ hasTrace: true,
+ archived: false,
+ ...over,
+ };
+}
+
+const stateEvent = (sessionId: string, state: "running" | "idle"): ServerEvent => ({
+ type: "session_state",
+ sessionId,
+ state,
+ lastActiveAt: "2026-09-16T09:05:00.000Z",
+ hasTrace: true,
+});
+
+beforeEach(() => {
+ listSessions.mockReset();
+});
+
+describe("the list fetches the user's own rows only", () => {
+ it("reload() asks the server to leave the organizations' rows out of the page and the totals", async () => {
+ listSessions.mockResolvedValue({ ...NO_ROWS, counts: COUNTS });
+ const store = createSessionsStore();
+ store.setState({ projectId: "proj", agentIds: ["default_agent", "acme_dev"] });
+ await store.getState().reload();
+ expect(listSessions).toHaveBeenCalledTimes(2);
+ for (const call of listSessions.mock.calls) {
+ expect(call[0]).toBe("proj");
+ expect(call[2]).toMatchObject({ category: "active", withCounts: true, excludeOrg: true });
+ }
+ });
+
+ it("loadMoreFor() pages a folder down the same own-rows stream", async () => {
+ listSessions.mockResolvedValue({ ...NO_ROWS, counts: COUNTS });
+ const store = createSessionsStore();
+ store.setState({ projectId: "proj", agentIds: ["default_agent"] });
+ await store.getState().reload();
+ listSessions.mockClear();
+ listSessions.mockResolvedValue(NO_ROWS);
+ await store.getState().loadMoreFor(["default_agent"], "subagent");
+ expect(listSessions).toHaveBeenCalledTimes(1);
+ expect(listSessions.mock.calls[0]![2]).toMatchObject({
+ category: "subagent",
+ excludeOrg: true,
+ });
+ });
+});
+
+describe("an organization row that enters by another door", () => {
+ /** A store whose one loaded pair is complete, so an added own row would count. */
+ async function loadedStore() {
+ listSessions.mockResolvedValue({
+ sessions: [session("own")],
+ counts: COUNTS,
+ workspaceCounts: { "/w": COUNTS },
+ workspaceLatest: { "/w": "2026-09-16T09:00:00.000Z" },
+ });
+ const store = createSessionsStore();
+ store.setState({ projectId: "proj", agentIds: ["default_agent"] });
+ await store.getState().reload();
+ return store;
+ }
+
+ it("is held for the page that asked for it but never moves the server's own-only totals", async () => {
+ const store = await loadedStore();
+ const desk = session("s-desk", { client: "org", orgId: "acme" });
+ store.getState().add(desk);
+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["s-desk", "own"]);
+ expect(store.getState().countsByAgent.get("default_agent")?.active).toBe(1);
+ expect(store.getState().workspaceCountsByAgent.get("default_agent")?.["/w"]?.active).toBe(1);
+ store.getState().remove("s-desk");
+ expect(store.getState().countsByAgent.get("default_agent")?.active).toBe(1);
+ });
+
+ it("an own row added under the same conditions still counts (the rule is about organization rows)", async () => {
+ const store = await loadedStore();
+ store.getState().add(session("own-2"));
+ expect(store.getState().countsByAgent.get("default_agent")?.active).toBe(2);
+ });
+
+ it("survives a reload, which can never fetch it back for the page showing it", async () => {
+ const store = await loadedStore();
+ store.getState().add(session("s-desk", { client: "org", orgId: "acme" }));
+ await store.getState().reload();
+ expect(store.getState().sessions.map((s) => s.sessionId)).toEqual(["own", "s-desk"]);
+ expect(store.getState().countsByAgent.get("default_agent")?.active).toBe(1);
+ });
+});
+
+describe("live statuses outlive the rows", () => {
+ it("remembers a session_state for a Session no loaded page holds, without inventing a row", () => {
+ const store = createSessionsStore();
+ store.setState({ projectId: "proj", agentIds: ["default_agent"], sessions: [session("own")] });
+ applyUserEvent(store, stateEvent("s-desk", "running"), () => undefined);
+ const state = store.getState();
+ expect(state.sessions.map((s) => s.sessionId)).toEqual(["own"]);
+ expect(liveSessionStatuses(state.sessions, state.liveStatuses).get("s-desk")).toBe("running");
+ // The run ending is the fact no other channel reports: it must be kept, not dropped as
+ // "nothing to draw".
+ applyUserEvent(store, stateEvent("s-desk", "idle"), () => undefined);
+ const after = store.getState();
+ expect(liveSessionStatuses(after.sessions, after.liveStatuses).get("s-desk")).toBe("idle");
+ });
+
+ it("a loaded row's own status wins over an older remembered one", () => {
+ const store = createSessionsStore();
+ store.setState({ projectId: "proj", agentIds: ["default_agent"], sessions: [] });
+ applyUserEvent(store, stateEvent("own", "running"), () => undefined);
+ // A list fetch that landed after the event carries the row as it stands now.
+ store.setState({ sessions: [session("own", { status: "idle" })] });
+ const state = store.getState();
+ expect(liveSessionStatuses(state.sessions, state.liveStatuses).get("own")).toBe("idle");
+ });
+
+ it("a resync forgets them: the flip that ended a run may be among the ones it lost", () => {
+ const store = createSessionsStore();
+ store.setState({
+ projectId: "proj",
+ agentIds: ["default_agent"],
+ reload: vi.fn(() => Promise.resolve()),
+ });
+ applyUserEvent(store, stateEvent("s-desk", "running"), () => undefined);
+ applyUserEvent(store, { type: "resync_required" }, () => undefined);
+ const state = store.getState();
+ expect(state.liveStatuses.has("s-desk")).toBe(false);
+ expect(liveSessionStatuses(state.sessions, state.liveStatuses).has("s-desk")).toBe(false);
+ });
+
+ it("an organization row held for its page does not stand in for them", () => {
+ const store = createSessionsStore();
+ store.setState({
+ projectId: "proj",
+ agentIds: ["default_agent"],
+ reload: vi.fn(() => Promise.resolve()),
+ });
+ // The desk the chat page opened while it ran: no list fetch ever refreshes this row, so
+ // after a resync its status is as stale as the forgotten entry.
+ store.getState().add(session("s-desk", { client: "org", orgId: "acme", status: "running" }));
+ applyUserEvent(store, { type: "resync_required" }, () => undefined);
+ const state = store.getState();
+ expect(state.sessions.map((s) => s.sessionId)).toEqual(["s-desk"]);
+ expect(liveSessionStatuses(state.sessions, state.liveStatuses).has("s-desk")).toBe(false);
+ });
+});