A local-first multi-agent app development platform, built on PenguinHarness
feat(server): in company mode an employee's model is its desk session's (#915)
Yaowei Zheng1304fb5d0ced
diff --git a/changelog/unreleased/2026-09-30-desk-model-follows-session.md b/changelog/unreleased/2026-09-30-desk-model-follows-session.mdnew file mode 100644index 00000000..c1268ca3--- /dev/null+++ b/changelog/unreleased/2026-09-30-desk-model-follows-session.md@@ -0,0 +1,21 @@+# Company mode: an employee's model is its desk session's++- **Date:** 2026-09-30+- **Type:** feature+- **Scope:** `server`, `docs`+- **PR:** [#915](https://github.com/Prism-Shadow/penguin-harness/pull/915)++[中文版](2026-09-30-desk-model-follows-session.zh.md)++An employee's model was read from its chart entry, while its desk session could be moved to another model in place (the in-session switch of [#748](https://github.com/Prism-Shadow/penguin-harness/pull/748)): the chart kept the old model, and the employee's ticket sessions and its next desk still opened on it. The employee's model is now the model its current desk session runs on.++## Server++- Switching the model inside an employee's current desk session — the toolbar's model picker, `/switch-model`, or the API — is the employee's switch: when it completes, the server writes the new model to the employee's entry in `org_chart.yaml`, so a desk renewed later opens on it. A switch made in a ticket session, or in a desk that has already been replaced, changes that session only.+- Ticket sessions open on the model the employee's current desk session runs on at that moment. The chart's `model` (then the organization's, then the Project default) is used only for an employee that has no desk.+- The chart's `model` is what a desk is opened on, at hire or on renewal. Writing it alone (`penguin org employee set --model-id … --provider …`) leaves the open desk and its ticket sessions where they are.+- The session manager tells subscribers when a Session's model moves (`onModelChanged`), after the row carries the new model.++## Docs++- `company-mode` ("Desk sessions") and `cli` (`employee set`), in both languages.diff --git a/changelog/unreleased/2026-09-30-desk-model-follows-session.zh.md b/changelog/unreleased/2026-09-30-desk-model-follows-session.zh.mdnew file mode 100644index 00000000..a798fa66--- /dev/null+++ b/changelog/unreleased/2026-09-30-desk-model-follows-session.zh.md@@ -0,0 +1,21 @@+# 公司模式:员工的 Model 以工位会话为准++- **Date:** 2026-09-30+- **Type:** feature+- **Scope:** `server`, `docs`+- **PR:** [#915](https://github.com/Prism-Shadow/penguin-harness/pull/915)++[English](2026-09-30-desk-model-follows-session.md)++员工的 Model 原先读自员工条目,而工位会话可以在会话内切换到另一个 Model([#748](https://github.com/Prism-Shadow/penguin-harness/pull/748) 的会话内切换):员工条目仍是旧 Model,该员工的工单会话和下一个工位也还开在旧 Model 上。现在,员工的 Model 就是它当前工位会话所用的 Model。++## Server++- 在员工当前的工位会话里切换 Model——工具条的模型选择器、`/switch-model` 或 API——即员工换 Model:切换完成时,服务端把新 Model 写入 `org_chart.yaml` 里该员工的条目,之后换工位也开在它上面。在工单会话里、或在已被替换的旧工位里切换,只影响那个会话。+- 工单会话开在员工当前工位会话此刻所用的 Model 上。只有员工还没有工位时,才取员工条目的 `model`(其次是组织的,再次是 Project 默认 Model)。+- 员工条目的 `model` 决定的是工位开在哪个 Model 上,即招募时和换工位时。只改它(`penguin org employee set --model-id … --provider …`)不会改动已经开着的工位和它的工单会话。+- Session 的 Model 变动时,会话管理器会通知订阅者(`onModelChanged`),此时 Session 行已是新 Model。++## Docs++- `company-mode`(「工位会话」)与 `cli`(`employee set`),中英文同步。diff --git a/packages/docs/content/cli.en.md b/packages/docs/content/cli.en.mdindex 4b8d6978..2ac5c5b9 100644--- a/packages/docs/content/cli.en.md+++ b/packages/docs/content/cli.en.md@@ -386,7 +386,7 @@ A desk or ticket session also creates its directory when it opens. `--budget` is### employee set-`employee set` changes only the fields you give. `--workspace` works as it does for `hire` but has no default: the partition changes only when you pass the flag. `--budget` is the monthly budget in USD for the employee plus everyone below it. The model pair is both-or-neither, as everywhere.+`employee set` changes only the fields you give. `--workspace` works as it does for `hire` but has no default: the partition changes only when you pass the flag. `--budget` is the monthly budget in USD for the employee plus everyone below it. The model pair is both-or-neither, as everywhere; it names the model the employee's next desk opens on and leaves the open desk as it is (see [Desk sessions](/company-mode#desk-sessions)).### calendardiff --git a/packages/docs/content/cli.zh.md b/packages/docs/content/cli.zh.mdindex 16cfede1..291848b7 100644--- a/packages/docs/content/cli.zh.md+++ b/packages/docs/content/cli.zh.md@@ -386,7 +386,7 @@ penguin org finance [--period <YYYY-MM>] [--json]### employee set-`employee set` 只修改你给出的字段。`--workspace` 的用法与 `hire` 相同,但没有默认值:只有传了这个选项才改变分区。`--budget` 是月度预算,单位为美元,覆盖这名员工以及下面的所有人。模型对要么都给,要么都不给,与其他地方一致。+`employee set` 只修改你给出的字段。`--workspace` 的用法与 `hire` 相同,但没有默认值:只有传了这个选项才改变分区。`--budget` 是月度预算,单位为美元,覆盖这名员工以及下面的所有人。模型对要么都给,要么都不给,与其他地方一致;它指定的是员工下一个工位开在哪个模型上,不改动已经开着的工位(见[工位会话](/company-mode#工位会话))。### calendardiff --git a/packages/docs/content/company-mode.en.md b/packages/docs/content/company-mode.en.mdindex 32e474eb..428800b6 100644--- a/packages/docs/content/company-mode.en.md+++ b/packages/docs/content/company-mode.en.md@@ -86,6 +86,13 @@ The handbook, the employee briefs (`AGENTS.md`), the CEO's initialization run anEach employee gets one standing desk session the moment it is hired. Calendar events, channel mentions and people all arrive there. A desk schedules work and opens ticket sessions rather than doing the work itself. The server opens a desk for any employee that has none: one added to `org_chart.yaml` by hand, or one whose Session was deleted.+**An employee's model is the model its desk session runs on.** The `model` of its entry in `org_chart.yaml` only says which model a desk is opened on, at hire or when the desk is renewed. There are two ways to change it:++- Switch the model inside the desk conversation, with the model picker in the composer's toolbar or `/switch-model` in `penguin chat` (see [Switch the model](/chat#switch-the-model)). The desk keeps its conversation, the server writes the new model to the chart entry, and a desk renewed later opens on it.+- Use `/model` in the desk conversation. It writes the chart entry first and then opens a new desk on that model.++Ticket sessions open on the model the employee's desk runs on at that moment. Editing the chart entry alone (`penguin org employee set --model-id <id> --provider <p>`) leaves the open desk and its ticket sessions where they are; it takes effect when the desk is renewed.+### TicketsA ticket file has YAML frontmatter (`title`, `status`, `owner`, `parent`, `notify`, `priority`, `due`, `blocked`, `blocked_by`, `sessions`, `history`), followed by four sections: `## Goal`, `## Acceptance criteria`, `## Progress` and `## Result`. The column directory the file is in is its status. The slug in the file name is lowercase English words joined by hyphens.diff --git a/packages/docs/content/company-mode.zh.md b/packages/docs/content/company-mode.zh.mdindex 759df220..2bf06f39 100644--- a/packages/docs/content/company-mode.zh.md+++ b/packages/docs/content/company-mode.zh.md@@ -86,6 +86,13 @@ id 使用小写 snake_case,长 2 到 64 个字符,以字母开头。按惯员工一受雇就有一个常设的工位会话。日程项、频道里的提及和真人的消息都送到这里。工位负责调度,开工单会话去干活,自己不动手。服务端会为没有工位的员工补开一个,比如手工写进 `org_chart.yaml` 的员工,或者工位会话已删除的员工。+**员工的模型就是它的工位会话所用的模型。** `org_chart.yaml` 里员工条目的 `model` 只决定工位开在哪个模型上,也就是受雇时和换工位时。换模型有两种方式:++- 在工位对话里切换模型:用输入框工具栏的模型选择器,或 `penguin chat` 里的 `/switch-model`(见[切换模型](/chat#切换模型))。工位保留原来的对话,服务端把新模型写回员工条目,之后换工位也开在它上面。+- 在工位对话里用 `/model`。它先写员工条目,再在这个模型上开一个新工位。++工单会话开在员工工位此刻所用的模型上。只改员工条目(`penguin org employee set --model-id <id> --provider <p>`)不会改动已经开着的工位和它的工单会话,要到换工位时才生效。+### 工单工单文件先是 YAML frontmatter(`title`、`status`、`owner`、`parent`、`notify`、`priority`、`due`、`blocked`、`blocked_by`、`sessions`、`history`),后面是四节:`## Goal`、`## Acceptance criteria`、`## Progress` 和 `## Result`。文件所在的列目录就是它的状态。文件名里的 slug 是用连字符连接的小写英文单词。diff --git a/packages/server/src/runtime/organization/deps.ts b/packages/server/src/runtime/organization/deps.tsindex a0e0b10b..8d90c2de 100644--- a/packages/server/src/runtime/organization/deps.ts+++ b/packages/server/src/runtime/organization/deps.ts@@ -36,6 +36,10 @@ export interface OrgTaskRunner {*/export interface OrgRunsShape extends OrgTaskRunner {invalidateAgentRuntimes(projectId: string, agentId: string): void;+ /** Subscribes to a Session's model moving (an in-session switch); returns the unsubscribe. */+ onModelChanged(+ listener: (sessionId: string, model: { provider: string; modelId: string }) => void,+ ): () => void;}/** Session creation (desk and ticket sessions are ordinary sessions of the employee's Agent). */diff --git a/packages/server/src/runtime/organization/service.ts b/packages/server/src/runtime/organization/service.tsindex 83897bbe..23498b82 100644--- a/packages/server/src/runtime/organization/service.ts+++ b/packages/server/src/runtime/organization/service.ts@@ -967,6 +967,36 @@ export class OrganizationService {return item;}+ /**+ * A Session's model moved (an in-session switch). When that Session is an employee's+ * CURRENT desk the switch is the employee's: its chart entry takes the desk's model, so a+ * desk renewed later opens on it (ticket Sessions read the desk itself, see+ * `openTicketSession`). Any other Session — a ticket Session, a desk already replaced, one+ * no organization owns — leaves the chart alone.+ */+ async deskModelChanged(+ sessionId: string,+ model: { provider: string; modelId: string },+ ): Promise<void> {+ const owner = this.deps.cache.ownerOfSession(sessionId);+ if (owner === null || owner.kind !== "desk") return;+ const { projectId, orgId, agentId } = owner;+ await this.scheduler.withLock(projectId, orgId, async () => {+ const org = await loadOrg(this.deps, projectId, orgId);+ // An organization that needs repair is repaired by editing its files, not from here.+ if (org === null || org.invalid !== undefined) return;+ if (org.desks[agentId]?.sessionId !== sessionId) return;+ const employee = org.byId.get(agentId);+ if (!employee) return;+ if (employee.model?.provider === model.provider && employee.model.modelId === model.modelId)+ return;+ await this.writeChart(+ org,+ org.chart.employees.map((e) => (e.agentId === agentId ? { ...e, model } : e)),+ );+ });+ }+/** Removes the employee from the tree (subordinates move up to its manager); the Agent and its sessions stay. */async leave(projectId: string, orgId: string, agentId: string): Promise<void> {await this.scheduler.withLock(projectId, orgId, async () => {@@ -2798,7 +2828,20 @@ export class OrganizationModule {};const orgScheduler = new OrganizationScheduler(deps);this.orgScheduler = orgScheduler;- this.orgService = new OrganizationService(deps, orgScheduler);+ const service = new OrganizationService(deps, orgScheduler);+ this.orgService = service;+ // An employee's model is its desk Session's: a switch made on a desk reaches the chart.+ const unsubscribe = runner.onModelChanged((sessionId, model) => {+ service.deskModelChanged(sessionId, model).catch((err: unknown) =>+ deps.errors.record({+ source: "organization",+ err,+ code: "org_desk_model_sync_failed",+ ctx: { sessionId },+ }),+ );+ });+ effect(() => unsubscribe());// Only active while this App is; the successor's start() reconciles from the files.effect(() => orgScheduler.stop());}diff --git a/packages/server/src/runtime/organization/triggers.ts b/packages/server/src/runtime/organization/triggers.tsindex 79cfb0b9..14a71696 100644--- a/packages/server/src/runtime/organization/triggers.ts+++ b/packages/server/src/runtime/organization/triggers.ts@@ -66,6 +66,8 @@ export async function ensureDesk(error: `workspace directory does not exist for ${agentId}: ${employee.workspace}`,};}+ // What a desk is opened on. The chart follows an in-session switch made on the desk (see+ // OrganizationService.deskModelChanged), so a renewal keeps the employee's model.const model = employee.model ?? org.config.model;const existing = org.desks[agentId];if (@@ -119,6 +121,21 @@ export async function ensureDesk(};}+/**+ * The model an employee's current desk Session runs on, or undefined when it has no desk (or+ * the desk's Session is gone). The chart's `model` is what a desk is OPENED on; from then on+ * the desk Session is where the employee's model is read.+ */+export function deskModel(+ deps: OrgDeps,+ org: LoadedOrg,+ agentId: string,+): { provider: string; modelId: string } | undefined {+ const desk = org.desks[agentId];+ const row = desk ? deps.sessions.findById(desk.sessionId) : null;+ return row ? { provider: row.provider, modelId: row.modelId } : undefined;+}+/** Projects the ledger into `org_sessions` (current desks and their history). */export function syncDeskCache(deps: OrgDeps, org: LoadedOrg): void {const rows: Array<{ sessionId: string; agentId: string; current: boolean }> = [];@@ -215,7 +232,10 @@ export async function openTicketSession(if (workspace === null) {return { ok: false, error: `workspace directory does not exist: ${spec}` };}- const model = employee.model ?? org.config.model;+ // An employee's model is its desk Session's: a ticket Session opens on the model the+ // current desk runs on now — an in-session switch there moved it — and on the chart's only+ // for an employee that has no desk.+ const model = deskModel(deps, org, agentId) ?? employee.model ?? org.config.model;let created: { sessionId: string; workspace: string };try {created = await deps.sessionCreator.createSession({diff --git a/packages/server/src/runtime/session-manager.ts b/packages/server/src/runtime/session-manager.tsindex e7f58a01..6133209d 100644--- a/packages/server/src/runtime/session-manager.ts+++ b/packages/server/src/runtime/session-manager.ts@@ -1448,13 +1448,27 @@ export class SessionManager {});}+ /** Who is told when a Session's model moves (see `onModelChanged`). */+ private readonly modelListeners = new Set<(sessionId: string, model: ModelRefDto) => void>();++ /**+ * Subscribes to a Session's model moving: an in-session switch completing, or a row brought+ * back in step with its Trace when the Session loads. The listener runs once the entry and+ * the row carry the new pair. Returns the unsubscribe. Company mode listens: an employee's+ * model is its desk Session's.+ */+ onModelChanged(listener: (sessionId: string, model: ModelRefDto) => void): () => void {+ this.modelListeners.add(listener);+ return () => void this.modelListeners.delete(listener);+ }+/*** Moves the entry — and the row it caches into — to the model the runtime reports itself on,* when that differs: the pair the next drive attributes usage to, and the one* `GET /sessions/:id` describes. A runtime that reports none (test fakes) leaves the entry* alone. The row write is guarded like the other bookkeeping writes (see `touchRow`): a* switch must not be stranded mid-drive by a closed DB handle, and the entry is right either- * way.+ * way. The same holds for whoever listens: a listener that throws is recorded, not rethrown.*/private syncEntryModel(entry: RuntimeEntry): void {const model = runtimeModelOf(entry.session);@@ -1462,6 +1476,7 @@ export class SessionManager {if (entry.provider === model.provider && entry.modelId === model.modelId) return;entry.provider = model.provider;entry.modelId = model.modelId;+ const ctx = { projectId: entry.projectId, agentId: entry.agentId, sessionId: entry.sessionId };try {this.deps.sessions.updateModel(entry.sessionId, model.provider, model.modelId);} catch (err) {@@ -1471,10 +1486,22 @@ export class SessionManager {this.deps.errors?.record({source: "session",err,- ctx: { projectId: entry.projectId, agentId: entry.agentId, sessionId: entry.sessionId },+ ctx,code: "session_model_update_failed",});}+ for (const listener of this.modelListeners) {+ try {+ listener(entry.sessionId, model);+ } catch (err) {+ this.deps.errors?.record({+ source: "session",+ err,+ ctx,+ code: "session_model_listener_failed",+ });+ }+ }}/** Submit an approval decision; returns false if the pending approval doesn't exist (already decided/unknown). */@@ -2474,6 +2501,7 @@ export abstract class Sessions extends Interface<| "startGoal"| "startCompact"| "startSwitch"+ | "onModelChanged"| "decideApproval"| "steer"| "recallSteering"diff --git a/packages/server/test/organization-runtime.test.ts b/packages/server/test/organization-runtime.test.tsindex e37d118f..4b9afb10 100644--- a/packages/server/test/organization-runtime.test.ts+++ b/packages/server/test/organization-runtime.test.ts@@ -440,7 +440,7 @@ describe("organization runtime", () => {).rejects.toMatchObject({ status: 400 });});- it("hires without a model by default: the entry carries none and the hire's sessions open without a model pair, so the Project default is resolved as each session opens", async () => {+ it("hires without a model by default: the entry carries none and the desk opens without a model pair, so the Project default is resolved as the desk opens — and the ticket sessions follow the desk", async () => {await createOrg();await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });const entry = (await service.chart(P, ORG)).employees.find((e) => e.agentId === HR);@@ -453,7 +453,8 @@ describe("organization runtime", () => {expect(desk.agentId).toBe(HR);expect(desk).not.toHaveProperty("modelId");expect(desk).not.toHaveProperty("provider");- // A ticket session of that employee opens the same way — the default is read per session.+ // A ticket session of that employee opens on the model its desk runs on — the pair the+ // desk resolved when it opened — rather than on a default read a second time.const t = await service.createTicket(P,ORG,@@ -461,9 +462,7 @@ describe("organization runtime", () => {{ userId: "alice" },);await service.startTicket(P, ORG, t.ticketId, {}, { userId: "alice" });- const work = created.at(-1)!;- expect(work.agentId).toBe(HR);- expect(work).not.toHaveProperty("modelId");+ expect(created.at(-1)).toMatchObject({ agentId: HR, provider: "custom", modelId: "m-bench" });// A model the board asked for by name still travels with the hire.await service.hire(P, ORG, {newAgent: { agentId: `${ORG}_dev` },@@ -478,6 +477,95 @@ describe("organization runtime", () => {});});+ describe("an employee's model is its desk session's", () => {+ const NEXT = { provider: "custom", modelId: "m-next" };+ const entryOf = async (agentId: string) =>+ (await service.chart(P, ORG)).employees.find((e) => e.agentId === agentId)!;+ const ticketFor = async (agentId: string): Promise<string> =>+ (+ await service.createTicket(+ P,+ ORG,+ { title: "Staff the company", owner: `agent:${agentId}` },+ { userId: "alice" },+ )+ ).ticketId;+ /** The desk Session switches models in place: the session runtime moves the row, then tells the organization. */+ const switchDesk = async (sessionId: string): Promise<void> => {+ sessions.updateModel(sessionId, NEXT.provider, NEXT.modelId);+ await service.deskModelChanged(sessionId, NEXT);+ };++ beforeEach(async () => {+ await saveProjectConfig(root, P, {+ default_model: { provider: "custom", model_id: "m-bench" },+ models: [+ { provider: "custom", model_id: "m-bench" },+ { provider: "custom", model_id: "m-next" },+ ],+ });+ await createOrg();+ await service.hire(P, ORG, { newAgent: { agentId: HR }, title: "HR", reportsTo: CEO });+ });++ it("a switch on the desk is the employee's: the chart entry takes the model, the next ticket session opens on it, and so does a renewed desk", async () => {+ const desk = (await service.desk(P, ORG, HR, {})).sessionId;+ expect(await entryOf(HR)).not.toHaveProperty("model");++ await switchDesk(desk);++ expect((await entryOf(HR)).model).toEqual(NEXT);+ // Nobody else's entry moved.+ expect(await entryOf(CEO)).not.toHaveProperty("model");+ await service.startTicket(P, ORG, await ticketFor(HR), {}, { userId: "alice" });+ expect(created.at(-1)).toMatchObject({ agentId: HR, ...NEXT });+ const renewed = (await service.desk(P, ORG, HR, { renew: true })).sessionId;+ expect(renewed).not.toBe(desk);+ expect(created.at(-1)).toMatchObject({ agentId: HR, ...NEXT });+ expect(sessions.findById(renewed)?.modelId).toBe(NEXT.modelId);+ });++ it("a ticket session follows the desk, not the chart: a model written to the chart alone waits for the next desk", async () => {+ await service.patchEmployee(P, ORG, HR, { model: NEXT });+ // The desk that is open keeps the model it runs on, and so do its ticket sessions.+ await service.startTicket(P, ORG, await ticketFor(HR), {}, { userId: "alice" });+ expect(created.at(-1)).toMatchObject({ agentId: HR, provider: "custom", modelId: "m-bench" });+ // The next desk opens on the chart's model, and the ticket sessions follow it there.+ await service.desk(P, ORG, HR, { renew: true });+ expect(created.at(-1)).toMatchObject({ agentId: HR, ...NEXT });+ await service.startTicket(P, ORG, await ticketFor(HR), {}, { userId: "alice" });+ expect(created.at(-1)).toMatchObject({ agentId: HR, ...NEXT });+ });++ it("only the current desk speaks for the employee: a replaced desk, a ticket session or a session of no organization leaves the chart alone", async () => {+ const replaced = (await service.desk(P, ORG, HR, {})).sessionId;+ await service.desk(P, ORG, HR, { renew: true });+ const work = (await service.startTicket(P, ORG, await ticketFor(HR), {}, { userId: "alice" }))+ .sessionId;+ const chartFile = path.join(orgDir(), "org_chart.yaml");+ const before = await fs.readFile(chartFile, "utf8");++ await switchDesk(replaced);+ await switchDesk(work);+ await service.deskModelChanged("session-2026-09-01-00-00-00-ffffffff", NEXT);++ expect(await fs.readFile(chartFile, "utf8")).toBe(before);+ expect(await entryOf(HR)).not.toHaveProperty("model");+ });++ it("a switch back to the model the chart already names writes nothing", async () => {+ const desk = (await service.desk(P, ORG, HR, {})).sessionId;+ await switchDesk(desk);+ const chartFile = path.join(orgDir(), "org_chart.yaml");+ const stamp = (await fs.stat(chartFile)).mtimeMs;+ await new Promise((resolve) => setTimeout(resolve, 20));++ await service.deskModelChanged(desk, NEXT);++ expect((await fs.stat(chartFile)).mtimeMs).toBe(stamp);+ });+ });+it("refuses a taken organization id and cleans up when the CEO cannot be created", async () => {await createOrg();await expect(createOrg()).rejects.toMatchObject({ status: 409, code: "org_exists" });diff --git a/packages/server/test/session-switch-model.test.ts b/packages/server/test/session-switch-model.test.tsindex ebee97cc..3777379e 100644--- a/packages/server/test/session-switch-model.test.ts+++ b/packages/server/test/session-switch-model.test.ts@@ -12,6 +12,8 @@* and usage is attributed to the model that served each request — the switch's own compaction* request to the previous model, the next Task to the new one.*/+import fs from "node:fs";+import path from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";import {abortEvent,@@ -34,6 +36,8 @@ import type {TaskCreateResponse,} from "../src/api/types.js";import type { SessionRow } from "../src/db/repos/sessions.js";+import { ORG_CONFIG_DEFAULTS } from "../src/organization/files.js";+import { OrgStore } from "../src/organization/store.js";import type { RuntimeSession } from "../src/runtime/session-manager.js";import { compactionThresholdFor } from "../src/services/context-breakdown.js";import { apiClient, createTestApp, provisionUser, waitFor } from "./helpers.js";@@ -581,4 +585,95 @@ describe("POST /switch-model", () => {expect(feed.events).toEqual([]);expect(usageModels()).toEqual([]);});++ it("tells its listeners when a Session's model moves — once per switch that completes, the row already on it — and a listener that throws stops nothing", async () => {+ adopt(switchFake(A, { kind: "stream", status: "completed" }));+ const heard: Array<{ sessionId: string; model: ModelRefDto; row: ModelRefDto }> = [];+ t.deps.manager.onModelChanged(() => {+ throw new Error("a listener of another module broke");+ });+ const off = t.deps.manager.onModelChanged((sessionId, model) => {+ const r = row();+ heard.push({ sessionId, model, row: { provider: r.provider, modelId: r.modelId } });+ });++ expect((await api.post(url, B)).status).toBe(202);+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");+ expect(heard).toEqual([{ sessionId: SID, model: B, row: B }]);+ expect(row()).toMatchObject(B);+ expect(t.deps.errorsRepo.recent(PROJECT).map((r) => r.code)).toEqual([+ "session_model_listener_failed",+ ]);++ // Unsubscribed: the next switch is not heard.+ off();+ expect((await api.post(url, A)).status).toBe(202);+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");+ expect(row()).toMatchObject(A);+ expect(heard).toHaveLength(1);+ });++ it("a switch completed inside the request is heard too", async () => {+ const heard: ModelRefDto[] = [];+ t.deps.manager.onModelChanged((_sessionId, model) => void heard.push(model));+ adopt(switchFake(A, { kind: "inline" }));+ expect((await api.post(url, B)).status).toBe(200);+ expect(heard).toEqual([B]);+ });++ it("company mode: a switch on an employee's current desk reaches its chart entry — through the app's own wiring, not a call made for it", async () => {+ // The organization as its files describe it: a CEO and one report, whose desk is this Session.+ const store = new OrgStore(t.deps.config.root);+ const dir = store.dir(PROJECT, "acme");+ await store.createLayout(dir);+ await store.writeConfig(dir, {+ ...ORG_CONFIG_DEFAULTS,+ name: "Acme",+ mission: "Ship the site",+ timezone: "UTC",+ createdBy: "switcher",+ });+ await store.writeChart(dir, {+ employees: [+ { agentId: "acme_ceo", title: "CEO", reportsTo: null, workspace: "." },+ { agentId: "default_agent", title: "Developer", reportsTo: "acme_ceo", workspace: "." },+ ],+ });+ await store.writeDesks(dir, {+ default_agent: {+ sessionId: SID,+ workspace: path.join(dir, "workspace"),+ openedAt: "2026-09-16T10:00:00.000Z",+ previous: [],+ },+ });+ t.deps.orgCacheRepo.syncDeskSessions(PROJECT, "acme", [+ { sessionId: SID, agentId: "default_agent", current: true },+ ]);+ const chartFile = path.join(dir, "org_chart.yaml");+ expect(fs.readFileSync(chartFile, "utf8")).not.toContain(B.modelId);+ adopt(switchFake(A, { kind: "stream", status: "completed" }));++ expect((await api.post(url, B)).status).toBe(202);+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");+ // The chart write is the organization's own step, behind the switch.+ await waitFor(() => fs.readFileSync(chartFile, "utf8").includes(B.modelId));++ const employees = new Map(+ (await t.deps.orgService.chart(PROJECT, "acme")).employees.map((e) => [e.agentId, e]),+ );+ expect(employees.get("default_agent")!.model).toEqual(B);+ expect(employees.get("acme_ceo")).not.toHaveProperty("model");+ expect(t.deps.errorsRepo.recent(PROJECT).map((r) => r.code)).toEqual([]);+ });++ it("a failed switch tells nobody", async () => {+ const heard: ModelRefDto[] = [];+ t.deps.manager.onModelChanged((_sessionId, model) => void heard.push(model));+ adopt(switchFake(A, { kind: "stream", status: "fatal" }));+ expect((await api.post(url, B)).status).toBe(202);+ await waitFor(() => t.deps.manager.statusOf(SID) === "idle");+ expect(row()).toMatchObject(A);+ expect(heard).toEqual([]);+ });});