A local-first multi-agent app development platform, built on PenguinHarness
feat(web): ticket cards open on click and move by dragging; opened ticket sessions stay in a Temporary sidebar group (#752)
Yaowei Zhengb40a8ace6d34
diff --git a/changelog/unreleased/2026-09-16-company-tickets-click.md b/changelog/unreleased/2026-09-16-company-tickets-click.mdnew file mode 100644index 00000000..503e3909--- /dev/null+++ b/changelog/unreleased/2026-09-16-company-tickets-click.md@@ -0,0 +1,58 @@+# A ticket card opens with a click and moves with a drag, and a ticket session opens++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#752](https://github.com/Prism-Shadow/penguin-harness/pull/752)++[中文版](2026-09-16-company-tickets-click.zh.md)++Company mode's ticket board and ticket dialog changed how they are clicked. A whole ticket card+became the target that opens the ticket, and dragging it moved it between columns, after a long+press on a touch screen. Inside the dialog the parent, the child tickets and the ticket sessions+opened from their titles instead of corner buttons. Clicking a ticket session had landed back on+the board with the dialog closed; it opened the conversation, and the company sidebar listed it in+a new Temporary group.++## Board++- A click, Enter or Space anywhere on a card opened the ticket dialog; the title button inside+ the card went away. The card was the one declared exception to the company pages' rule against+ whole-area click targets.+- A mouse or pen press that moved more than 6 px lifted the card at once, with no hold: the card+ followed the pointer as a ghost and asked to move when released over another column, through the+ same confirmation as before. A press released before moving that far was a click, and a drag did+ not also open the ticket.+- On a touch screen a card lifted only after being held still for 350 ms, and a finger that moved+ before then scrolled the page.+- Holding a lifted card near an edge of the board or the page scrolled it. Escape put a lifted card+ back.+- HTML5 drag-and-drop was replaced by pointer events, so a card could be dragged with a mouse, a+ pen or a finger. The dialog's move control stayed as the way to move a ticket without dragging.++## Ticket dialog++- The parent ticket, each child ticket and each ticket session opened by clicking its title, which+ underlines on hover and names its destination in its tooltip. The jump buttons beside them were+ removed.+- A session the ticket still named but whose record was gone, for example after its Agent was+ deleted, showed as plain text instead of a link.++## Ticket sessions++- Opening a ticket session from the dialog on the board used to return to the board: the dialog+ closed before the router committed the new location, and the board, still mounted, removed+ `?ticket=` from its query against its own location, replacing the conversation's history entry.+ The board stopped writing its query once the browser has left it.+- The opened session went to the top of a collapsible **Temporary** group in the company sidebar,+ below **Desks** and shown only while it listed something. Each row had the employee's avatar, the+ session title, its run mark and a ✕; the collapsed rail showed the entries' avatars after the+ desk avatars.+- An entry stayed until its ✕ removed it, or until **Close all** in the group's header emptied the+ group in one click, with no confirmation; both took entries off the list and left the sessions+ themselves alone. Going elsewhere or reloading the page kept an entry, and a ✕ pressed on the+ session on screen removed only the row. Opening a listed session again moved it to the top.+- The list was kept in the browser's localStorage, per user, Project and organization, with no+ cap. A desk session opened from a ticket was not listed; its desk row already named it.+- The company mode guide described the board's click and drag, the dialog's titles and the+ Temporary group, in both languages.diff --git a/changelog/unreleased/2026-09-16-company-tickets-click.zh.md b/changelog/unreleased/2026-09-16-company-tickets-click.zh.mdnew file mode 100644index 00000000..15f3865c--- /dev/null+++ b/changelog/unreleased/2026-09-16-company-tickets-click.zh.md@@ -0,0 +1,31 @@+# 工单卡片点击打开、拖动移动,工单会话可以打开了++- **Date:** 2026-09-16+- **Type:** feature+- **Scope:** `web`, `docs`+- **PR:** [#752](https://github.com/Prism-Shadow/penguin-harness/pull/752)++[English](2026-09-16-company-tickets-click.md)++公司模式的工单看板与工单窗口改了点击方式。整张工单卡片成为打开工单的点击目标,拖动卡片即在列之间移动(触屏上先长按)。工单窗口里的父工单、子工单与工单会话改为点标题打开,不再用角上的跳转按钮。点击工单会话原本会落回看板、窗口关闭;现在会打开该会话,并列入公司侧栏新增的「临时」分组。++## 看板++- 在卡片任意位置点击、按 Enter 或空格,都会打开工单窗口;卡片里的标题按钮随之移除。卡片是公司页面「不设整块点击区域」规则下唯一声明的例外。+- 鼠标或触控笔按下后移动超过 6 px,卡片即刻浮起、无需按住:以残影跟随指针,在另一列上松开时走与之前相同的确认弹窗。未移动到这个距离就松开算作点击;拖动过的卡片松开后不会再打开工单。+- 触屏上要按住卡片 350 ms 不动它才浮起,在此之前手指划动滚动的是页面。+- 把浮起的卡片停在看板或页面边缘会自动滚动;Esc 放回卡片。+- HTML5 拖放换成了指针事件,鼠标、触控笔与手指都能拖动卡片。工单窗口里的移动控件保留,作为不拖拽也能移动工单的途径。++## 工单窗口++- 父工单、每张子工单与每个工单会话都点标题打开:标题悬停时加下划线,提示里写明去向。旁边的跳转按钮已移除。+- 工单仍记着、但会话记录已不存在的会话(例如其 Agent 已被删除)显示为纯文本,不再是链接。++## 工单会话++- 在看板上从工单窗口打开工单会话,原本会回到看板:窗口在路由提交新位置之前就已关闭,仍挂载着的看板按自己的旧位置删掉查询里的 `?ticket=`,把会话的历史记录项替换掉了。现在浏览器一旦离开看板,看板就不再改写自己的查询。+- 打开的会话排到公司侧栏「临时」分组的最上面。该分组可折叠,位于「工位」下方,有条目时才出现;每行显示员工头像、会话标题、运行标记与 ✕,折叠侧栏在各工位的头像之后显示这些条目的头像。+- 条目一直保留,直到点 ✕ 移除,或点分组标题上的「全部关闭」一次清空、无需确认;两者都只把条目移出列表,会话本身不受影响。去往别处或刷新页面都不会让条目消失,在正查看的会话上点 ✕ 也只移除这一行。再次打开已列出的会话会把它移到最上面。+- 列表按用户、Project 与组织保存在浏览器的 localStorage 中,不设上限。从工单打开的若是工位会话,不列入「临时」,仍由它自己的工位行标示。+- 公司模式指南中英两版都补上了看板的点击与拖动、工单窗口的标题点击,以及「临时」分组。diff --git a/packages/docs/content/company-mode.en.md b/packages/docs/content/company-mode.en.mdindex 484177ec..32e474eb 100644--- a/packages/docs/content/company-mode.en.md+++ b/packages/docs/content/company-mode.en.md@@ -266,6 +266,7 @@ In company mode, the sidebar lists the organization's pages: **Overview**, **Org- **Overview** is where an organization opens. It shows the mission folded to one line, this period's spend against the CEO's budget, and a KPI strip, followed by three full-width sections: the **Inbox** (all-hands messages that mention you or `@all`, every blocked ticket whoever it waits on, and the tickets closed this period), today's calendar, and the budget alerts. No card is a link; each has one corner button that names the page it summarizes.- **Org Chart** shows the reporting tree. Each employee's menu offers **Hire a subordinate**, **Set budget**, **Change reporting line**, **New desk session** and **Leave the organization**.+- **Tickets** is the board. Clicking a card opens its ticket in place, and dragging the card to another column moves the ticket; on a touch screen, hold the card until it lifts before dragging it, since a finger that moves straight away scrolls the page. The move control inside the ticket moves it without dragging. Inside a ticket, the parent, a child ticket and a ticket session each open by clicking their title. A ticket session opens as its full conversation and goes to the top of the sidebar's **Temporary** group, below **Desks**. It stays listed, in this browser, until you remove it with its ✕ or empty the whole group with **Close all** in its header; going elsewhere or reloading the page keeps it. Both only take entries off the list: the sessions themselves are kept. Ticket sessions are never listed in the sidebar otherwise.- **Handbook** shows the knowledge base as an explorer tree beside the rendered document. At every level, folders come before documents; folders stay collapsed until opened, and the arrow keys move through the tree.- **Finance** shows the period in three rows: the KPI panel beside the daily trend, then the spend tree and the ticket table side by side, then the period's warnings and pauses.- **Calendar** and **Tickets** each show a single create button while they are empty, under a hint you can dismiss for good.diff --git a/packages/docs/content/company-mode.zh.md b/packages/docs/content/company-mode.zh.mdindex 983e5356..759df220 100644--- a/packages/docs/content/company-mode.zh.md+++ b/packages/docs/content/company-mode.zh.md@@ -266,6 +266,7 @@ penguin org finance # spend per employee (cumulati- **概览**是打开组织时的落脚页。它显示折成一行的使命、本周期支出与 CEO 预算的对照、一条 KPI 带,下面是三段通栏:**收件箱**(全员频道里提及你或 `@all` 的消息,不论在等谁的全部阻塞工单,以及本周期关闭的工单)、今日日程和预算告警。卡片本身都不是链接,每张卡片角上各有一个按钮,写明它汇总的是哪个页面。- **组织图**展示汇报树。每名员工的菜单里有**招募下属**、**设预算**、**调整汇报线**、**换工位**和**离任**。+- **工单**就是看板。点卡片即在原地打开工单,把卡片拖到另一列即移动工单;触屏上要先按住卡片直到它浮起再拖,手指直接划动滚动的是页面。工单里的移动控件不用拖拽也能移动它。工单里的父工单、子工单与工单会话都点标题打开。工单会话以完整的会话页打开,并排到侧栏「工位」下方「临时」分组的最上面。它会一直列在那里(保存在当前浏览器中),直到你点它的 ✕,或点分组标题上的「全部关闭」清空整个分组;去往别处或刷新页面都不会让它消失。两者都只把条目移出列表,会话本身仍在。除此之外,侧栏从不列出工单会话。- **手册**以资源管理器式的树展示知识库,旁边是渲染好的文档。每一层都是文件夹排在文档前面;文件夹默认收起,可以用方向键在树中移动。- **财务**把本周期分成三行:KPI 面板与逐日趋势并排,然后是支出树与工单表左右并排,最后是本周期的告警与暂停。- **日历**和**工单**在空的时候只留一个新建按钮,按钮上方的提示可以永久关掉。diff --git a/packages/web/e2e/company.spec.mjs b/packages/web/e2e/company.spec.mjsindex 994f7a96..5c68628d 100644--- a/packages/web/e2e/company.spec.mjs+++ b/packages/web/e2e/company.spec.mjs@@ -2,8 +2,11 @@* Company mode, end to end through the browser with the mock LLM: switch modes, create the* marketplace organization from the switcher, land on the CEO's desk conversation (its* initialization run is answered by the mock), find the CEO on the org chart and a ticket on- * the board, open a desk from the sidebar's 工位 group and another from the org chart, then- * work in the channels — post in the all-hands channel and see the mention reach the CEO's+ * the board, open a desk from the sidebar's 工位 group and another from the org chart, work the+ * board — a click on a card opens its ticket, a mouse drag onto another column moves it, and a+ * ticket session opened from the dialog stays on screen and joins the sidebar's 临时 group,+ * which survives a reload and empties only through its ✕ and its 全部关闭 — then work in the+ * channels — post in the all-hands channel and see the mention reach the CEO's* desk as an `[org_trigger]` work run, create a channel, invite the CEO into it, and post a* mention there — and finally check that development mode lists none of the organization's* own sessions. The desk row's run mark is checked on both sides of the initialization run:@@ -45,7 +48,7 @@ async function enableCompanyMode() {test("company mode: create the organization, meet the CEO, see the board and the chat work", async ({page,}) => {- test.setTimeout(120_000);+ test.setTimeout(180_000);await enableCompanyMode();await provisionAndLogin(page.request, U, P);const project = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0];@@ -178,6 +181,92 @@ test("company mode: create the organization, meet the CEO, see the board and theawait page.goto(`/org/${projectId}/${ORG}/tickets`);await expect(page.getByText("Build the marketplace site").first()).toBeVisible();+ // A click anywhere on a card opens its ticket in place.+ const board = `/org/${projectId}/${ORG}/tickets`;+ const card = (title) => page.locator("[data-ticket-column] button", { hasText: title }).first();+ await card("Build the marketplace site").click();+ const siteDialog = page.getByRole("dialog", { name: "Build the marketplace site" });+ await expect(siteDialog).toBeVisible();+ await page.keyboard.press("Escape");+ await expect(siteDialog).toHaveCount(0);++ // A mouse drag onto another column lifts the card as soon as it moves and asks to move the+ // ticket there; confirming moves it.+ const from = await card("Build the marketplace site").boundingBox();+ const to = await page.locator('[data-ticket-column="in_progress"]').boundingBox();+ await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2);+ await page.mouse.down();+ // Near the column's top rather than its middle: a tall column can end below the viewport.+ await page.mouse.move(to.x + to.width / 2, to.y + Math.min(60, to.height / 2), { steps: 12 });+ await page.mouse.up();+ const moveConfirm = page.getByRole("dialog", { name: "移动工单" });+ await expect(+ moveConfirm.getByText("将「Build the marketplace site」移到「进行中」?"),+ ).toBeVisible();+ await moveConfirm.getByRole("button", { name: "确认", exact: true }).click();+ await expect(+ page.locator('[data-ticket-column="in_progress"]').getByText("Build the marketplace site"),+ ).toBeVisible();++ // A ticket session opened from the dialog lands on its conversation and STAYS there: the+ // board, still mounted while the router commits the new location, must not write its+ // `?ticket=` query back over the conversation's history entry.+ const startSession = async (ticketId) => {+ const res = await page.request.post(api(`/organizations/${ORG}/tickets/${ticketId}/start`), {+ data: { message: "Pick this up." },+ });+ expect(res.ok(), "start ticket session").toBeTruthy();+ return (await res.json()).sessionId;+ };+ const openFromTicket = async (title, sessionId) => {+ await page.goto(board);+ await card(title).click();+ const dialog = page.getByRole("dialog", { name: title });+ await dialog.getByRole("button", { name: /^关联工单会话/ }).click();+ await dialog.locator('button[title="打开会话"]').first().click();+ await expect(page).toHaveURL(new RegExp(`/chat/${sessionId}$`));+ await expect(page.getByPlaceholder(/输入消息/)).toBeVisible();+ expect(new URL(page.url()).pathname).toBe(`/chat/${sessionId}`);+ };+ const siteSession = await startSession(ticket.ticketId);+ await openFromTicket("Build the marketplace site", siteSession);++ // It joins the 临时 group below 工位, marked as the session on screen, and a reload keeps it.+ const tempHeader = (n) => sidebar.getByRole("button", { name: `临时(${n})` });+ const anyTempHeader = sidebar.getByRole("button", { name: /^临时(/ });+ const removeRow = sidebar.getByRole("button", { name: "从「临时」中移除" });+ await expect(tempHeader(1)).toBeVisible();+ const desksTop = (await sidebar.getByRole("button", { name: /^工位(/ }).boundingBox()).y;+ expect((await tempHeader(1).boundingBox()).y).toBeGreaterThan(desksTop);+ await expect(sidebar.locator('li button[aria-current="true"]')).toHaveCount(1);+ await page.reload();+ await expect(tempHeader(1)).toBeVisible();+ await expect(page).toHaveURL(new RegExp(`/chat/${siteSession}$`));++ // A second one goes on top. Its ✕ removes only its row, even while it is on screen: the+ // page stays on the conversation and the other entry stays listed.+ const launch = await page.request.post(api(`/organizations/${ORG}/tickets`), {+ data: { title: "Write the launch post", goal: "Announce the site.", owner: `agent:${ORG}_ceo` },+ });+ expect(launch.ok(), "create second ticket").toBeTruthy();+ const launchSession = await startSession((await launch.json()).ticketId);+ await openFromTicket("Write the launch post", launchSession);+ await expect(tempHeader(2)).toBeVisible();+ await removeRow.first().click();+ await expect(tempHeader(1)).toBeVisible();+ await expect(sidebar.locator('li button[aria-current="true"]')).toHaveCount(0);+ await expect(page).toHaveURL(new RegExp(`/chat/${launchSession}$`));++ // 全部关闭 empties the group in one click, with no confirmation, and it stays empty.+ await openFromTicket("Write the launch post", launchSession);+ await expect(tempHeader(2)).toBeVisible();+ await sidebar.getByRole("button", { name: "全部关闭", exact: true }).click();+ await expect(anyTempHeader).toHaveCount(0);+ await expect(page).toHaveURL(new RegExp(`/chat/${launchSession}$`));+ await page.reload();+ await expect(sidebar.getByRole("button", { name: /^工位(/ })).toBeVisible();+ await expect(anyTempHeader).toHaveCount(0);+// An organization opens on its overview; its channels are the sidebar's own list, where// development mode lists conversations, with the all-hands channel pinned at its top.await page.goto(`/org/${projectId}/${ORG}`);@@ -239,7 +328,7 @@ test("company mode: create the organization, meet the CEO, see the board and theexpect(siteDay.messages.some((m) => m.text.includes("站点频道成立"))).toBe(true);expect(siteDay.messages.some((m) => m.mentions.includes(`agent:${ORG}_ceo`))).toBe(true);- // The overview reflects it all: one employee, one proposed ticket, the mission on screen.+ // The overview shows the organization, its mission on screen.await page.goto(`/org/${projectId}/${ORG}/overview`);await expect(page.getByText("Plugin Marketplace").first()).toBeVisible();@@ -259,5 +348,6 @@ test("company mode: create the organization, meet the CEO, see the board and theawait expect(sidebar.getByRole("button", { name: /^组织(/ })).toHaveCount(0);const overview = await (await page.request.get(api(`/organizations/${ORG}`))).json();expect(overview.board.proposed).toBe(1);- expect(overview.openTickets).toBe(1);+ expect(overview.board.in_progress).toBe(1);+ expect(overview.openTickets).toBe(2);});diff --git a/packages/web/src/components/layout/app-layout.tsx b/packages/web/src/components/layout/app-layout.tsxindex d228489a..1804a2a9 100644--- a/packages/web/src/components/layout/app-layout.tsx+++ b/packages/web/src/components/layout/app-layout.tsx@@ -25,7 +25,7 @@ import { COMPANY_MODE_ICON, CloseIcon, NAV_ICONS } from "../ui/icons";import { useCompany } from "../../state/company";import { COMPANY_NAV_ICONS } from "../../features/company/company-nav-icons";import { ChannelRailRows } from "../../features/company/channel-sidebar";-import { DeskRailRows } from "../../features/company/org-session-groups";+import { DeskRailRows, TempSessionRailRows } from "../../features/company/org-session-groups";import {COMPANY_NAV_KEYS,isOrgRoute,@@ -293,16 +293,17 @@ function CollapsedRail({ onExpand }: { onExpand: () => void }) {</Tooltip>);})}- {/* The organization's channels and then its desks, under the pages the way they sit- under the nav in the pinned sidebar. A hairline says where each run ends; a channel- row carries its own unread count and a desk its running dot, since a rail with no- labels must still say how much is waiting. */}+ {/* The organization's channels, its desks and then its Temporary entries, under the+ pages the way they sit under the nav in the pinned sidebar. A hairline says where each+ run ends; a channel row carries its own unread count and a desk or an entry its+ running dot, since a rail with no labels must still say how much is waiting. */}{inCompany && navOrg !== null && (<><span aria-hidden className="my-0.5 h-px w-5 shrink-0 bg-gray-200 dark:bg-gray-800" /><ChannelRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} /><span aria-hidden className="my-0.5 h-px w-5 shrink-0 bg-gray-200 dark:bg-gray-800" /><DeskRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} />+ <TempSessionRailRows projectId={navOrg.projectId} orgId={navOrg.orgId} /></>)}</nav>diff --git a/packages/web/src/components/ui/group-list.tsx b/packages/web/src/components/ui/group-list.tsxindex a247760b..8df82387 100644--- a/packages/web/src/components/ui/group-list.tsx+++ b/packages/web/src/components/ui/group-list.tsx@@ -225,6 +225,7 @@ export function FolderSection({label,open,onToggle,+ action,more = false,moreLabel,pending = false,@@ -236,6 +237,11 @@ export function FolderSection({label: string;open: boolean;onToggle: () => void;+ /**+ * A flat action at the right end of the folder's row, outside its toggle, so a click on it+ * never folds the folder (the company sidebar's Temporary "Close all").+ */+ action?: ReactNode;/** Show the folder's own "More" row (its share isn't fully loaded and somewhere is left to fetch from). */more?: boolean;/**@@ -252,12 +258,26 @@ export function FolderSection({onLess?: () => void;children?: ReactNode;}) {+ const toggle = (+ <button+ type="button"+ onClick={onToggle}+ className={action === undefined ? FOLDER_ROW_CLASS : `${FOLDER_ROW_CLASS} min-w-0 flex-1`}+ >+ <Chevron open={open} size={12} />+ {label}+ </button>+ );return (<div className="mt-1">- <button type="button" onClick={onToggle} className={FOLDER_ROW_CLASS}>- <Chevron open={open} size={12} />- {label}- </button>+ {action === undefined ? (+ toggle+ ) : (+ <div className="flex items-center gap-1">+ {toggle}+ {action}+ </div>+ )}{open && children}{open && more && (<MoreRowdiff --git a/packages/web/src/features/company/org-session-groups.tsx b/packages/web/src/features/company/org-session-groups.tsxindex 914f0034..5e2bb7eb 100644--- a/packages/web/src/features/company/org-session-groups.tsx+++ b/packages/web/src/features/company/org-session-groups.tsx@@ -1,13 +1,17 @@/**- * The 工位 group under the company sidebar's channel list, and the collapsed rail's twin.+ * The Desks and Temporary groups under the company sidebar's channel list, and the collapsed+ * rail's twins.*- * One row per employee, in chart order, expanded by default: the organization's people are- * its primary objects, and a desk is where a person is talked to. Every employee has a desk+ * Desks: one row per employee, in chart order, expanded by default: the organization's people+ * are its primary objects, and a desk is where a person is talked to. Every employee has a desk* session from the moment it is hired, so a row normally carries one; a row whose id these* caches have not learned yet still stands there and opens the desk on click, exactly as the- * org chart's card does. Ticket sessions have no group of their own — a session exists- * because a ticket started it, and it is read from that ticket's drawer, where the work it- * belongs to is on screen beside it.+ * org chart's card does.+ *+ * Temporary: ticket sessions have no group of their own. Each exists because a ticket started+ * it, and it is opened from that ticket's dialog. The ones opened from there are listed below the+ * desks, newest first, until the reader removes one with its ✕ or all of them with the header's+ * "Close all"; the group shows only while it lists something (temp-session.ts).** A row that names a desk session carries the development list's row menu (right-click, and* the hover ellipsis), pared down to the two actions an organization leaves to the reader:@@ -30,6 +34,7 @@ import { S } from "../../lib/strings";import { apiErrorText } from "../../lib/api-error";import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";import { toneDot, toneInk } from "../../lib/tone";+import { useAuth } from "../../state/auth";import { useCompany } from "../../state/company";import { useProject } from "../../state/project";import { useLiveSessionStatuses } from "../../state/sessions";@@ -39,7 +44,7 @@ import { useRowContextMenu } from "../../components/ui/context-menu";import { writeClipboard } from "../../components/ui/copy-button";import { Dropdown } from "../../components/ui/dropdown";import { FolderSection, Icon } from "../../components/ui/group-list";-import { MESSAGING_RELAY_ICON } from "../../components/ui/icons";+import { CloseIcon, MESSAGING_RELAY_ICON } from "../../components/ui/icons";import { SessionActivityIcon } from "../../components/ui/session-activity-icon";import {DESK_ROW_ACTIONS,@@ -52,8 +57,15 @@ import { toastError, toastSuccess } from "../../components/ui/toast";import { Truncated } from "../../components/ui/truncated";import { MessagingBindingModal } from "../messaging/messaging-binding-modal";import { orgKey } from "./company-nav";-import { deskRows, orgRowActivity } from "./org-sessions";+import { deskRows, orgRowActivity, ticketSessionTitles } from "./org-sessions";import type { OrgDeskRow } from "./org-sessions";+import {+ dismissAllTempSessions,+ dismissTempSession,+ tempSessionRows,+ useTempSessions,+} from "./temp-session";+import type { TempSessionRow } from "./temp-session";/*** The row's surface — the hover and active fill — on the wrapper rather than on the button,@@ -80,7 +92,8 @@ const DESK_ROW_STATE: SessionRowState = { archived: false, pinned: false };/*** Opening a desk: the store's row when one exists, and otherwise the desk endpoint, which* creates it — the same call the org chart's card makes, so the two entry points cannot- * disagree about what "open the desk" means.+ * disagree about what "open the desk" means. `openSession` is how a Temporary row opens its+ * session.*/function useOpenDesk(projectId: string, orgId: string, onNavigate?: () => void) {const navigate = useNavigate();@@ -114,7 +127,7 @@ function useOpenDesk(projectId: string, orgId: string, onNavigate?: () => void)setOpening(null);}};- return { openDesk, opening };+ return { openDesk, openSession, opening };}/**@@ -255,6 +268,135 @@ function DeskRow({);}+/** A Temporary row with what it draws besides its entry. */+interface TempRowView extends TempSessionRow {+ /** The employee's name, for the avatar and the tooltip. */+ name: string;+ activity: ReturnType<typeof orgRowActivity>;+}++/**+ * This organization's Temporary rows for the signed-in user, with what each draws: the title the+ * organization gives the session (the ticket's listing at open time until the route names it),+ * the employee's name, and the live run state. A desk session is left to its desk row.+ */+function useTempRows(+ projectId: string,+ orgId: string,+ desks: readonly OrgDeskRow[],+ activeSessionId: string | null,+): TempRowView[] {+ const company = useCompany();+ const { user } = useAuth();+ const live = useLiveSessionStatuses();+ const list = useTempSessions(user?.userId ?? null, projectId, orgId);+ const titles = ticketSessionTitles(company.orgSessions.get(orgKey(projectId, orgId)));+ return tempSessionRows(+ list,+ desks.map((d) => d.sessionId),+ activeSessionId,+ ).map((row) => {+ const named = titles.get(row.sessionId);+ const title = named ?? (row.title !== "" ? row.title : S.company.sessionList.untitledSession);+ const name =+ company.orgChart?.employees.find((e) => e.agentId === row.agentId)?.name ?? row.agentId;+ const status = live.get(row.sessionId);+ return { ...row, title, name, activity: status === undefined ? null : orgRowActivity(status) };+ });+}++/**+ * One Temporary row: the employee's avatar, the session's title and its run mark, then a ✕ that+ * removes the row and nothing else. The page stays where it is, even on this session.+ */+function TempRow({+ row,+ onOpen,+ onDismiss,+}: {+ row: TempRowView;+ onOpen: () => void;+ onDismiss: () => void;+}) {+ const label =+ row.activity === "running" ? `${row.title} · ${S.company.sessionList.running}` : row.title;+ const remove = S.company.sessionList.closeTemporary;+ return (+ <li>+ <div className={rowSurface(row.active)}>+ <button+ type="button"+ aria-current={row.active ? "true" : undefined}+ title={`${row.name} · ${row.title}`}+ aria-label={label}+ onClick={onOpen}+ className={rowButton(row.active)}+ >+ <AgentAvatar+ id={row.agentId}+ name={row.name}+ size={ICON_SIZE.rowLead}+ className="shrink-0 rounded"+ />+ <Truncated text={row.title} className="min-w-0 flex-1" />+ {row.activity !== null && <SessionActivityIcon activity={row.activity} />}+ </button>+ {/* The same trailing slot a desk row keeps for its menu, so the run marks line up+ across the two groups. */}+ <button+ type="button"+ title={remove}+ aria-label={remove}+ onClick={onDismiss}+ className="flex h-6 w-6 shrink-0 items-center justify-center rounded text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"+ >+ <CloseIcon />+ </button>+ </div>+ </li>+ );+}++/**+ * The collapsed rail's Temporary entries, after the desks and a hairline: avatars with their+ * running dots, drawn the way the desks are.+ */+export function TempSessionRailRows({ projectId, orgId }: { projectId: string; orgId: string }) {+ const company = useCompany();+ const live = useLiveSessionStatuses();+ const desks = deskRows(company.orgChart, company.orgSessions.get(orgKey(projectId, orgId)), live);+ const rows = useTempRows(projectId, orgId, desks, null);+ const { openSession } = useOpenDesk(projectId, orgId);+ if (rows.length === 0) return null;+ return (+ <>+ <span aria-hidden className="my-0.5 h-px w-5 shrink-0 bg-gray-200 dark:bg-gray-800" />+ {rows.map((row) => {+ const entry = S.company.sessionList.temporaryEntry(row.title);+ const name = row.activity !== null ? `${entry} · ${S.company.sessionList.running}` : entry;+ return (+ <button+ key={row.sessionId}+ type="button"+ title={name}+ aria-label={name}+ onClick={() => openSession(row.sessionId, row.agentId)}+ className="relative flex h-8 w-8 items-center justify-center rounded-md transition-colors duration-150 hover:bg-gray-200/70 dark:hover:bg-gray-800"+ >+ <AgentAvatar id={row.agentId} name={row.name} size={18} className="rounded" />+ {row.activity !== null && (+ <span+ aria-hidden+ className={`absolute -right-0.5 -top-0.5 h-1.5 w-1.5 rounded-full ${toneDot.busy}`}+ />+ )}+ </button>+ );+ })}+ </>+ );+}+export function OrgSessionGroups({projectId,orgId,@@ -268,13 +410,16 @@ export function OrgSessionGroups({onNavigate?: () => void;}) {const company = useCompany();+ const { user } = useAuth();const [desksOpen, setDesksOpen] = useState(true);+ const [tempOpen, setTempOpen] = useState(true);/** 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 orgSessions = company.orgSessions.get(orgKey(projectId, orgId));const desks = deskRows(company.orgChart, orgSessions, live);- const { openDesk, opening } = useOpenDesk(projectId, orgId, onNavigate);+ const { openDesk, openSession, opening } = useOpenDesk(projectId, orgId, onNavigate);+ const tempRows = useTempRows(projectId, orgId, desks, activeSessionId);// Nothing has been read for this organization yet: a skeleton, not an "empty" claim.const chartFailed = company.orgChart === null && company.orgChartError !== null;const loading = company.orgChart === null && orgSessions === undefined && !chartFailed;@@ -314,6 +459,37 @@ export function OrgSessionGroups({</ul>)}</FolderSection>+ {tempRows.length > 0 && (+ <FolderSection+ label={S.company.sessionList.temporary(tempRows.length)}+ open={tempOpen}+ onToggle={() => setTempOpen((v) => !v)}+ // One click, no confirmation: nothing is lost, each session stays one click away in+ // its ticket. Nothing navigates, even when the session on screen was listed.+ action={+ <button+ type="button"+ onClick={() => dismissAllTempSessions(user?.userId ?? null, projectId, orgId)}+ className="shrink-0 rounded px-1.5 py-1 text-[11px] font-medium text-gray-400 transition-colors duration-150 hover:text-gray-700 dark:text-gray-500 dark:hover:text-gray-200"+ >+ {S.company.sessionList.closeAllTemporary}+ </button>+ }+ >+ <ul className="space-y-0.5">+ {tempRows.map((row) => (+ <TempRow+ key={row.sessionId}+ row={row}+ onOpen={() => openSession(row.sessionId, row.agentId)}+ onDismiss={() =>+ dismissTempSession(user?.userId ?? null, projectId, orgId, row.sessionId)+ }+ />+ ))}+ </ul>+ </FolderSection>+ )}{/* Messaging binding dialog (the row menu's "Messaging binding…"): the row's indicatorfollows the dialog's own enable/disable outcome, written into the company store'scopy of the sessions route. */}diff --git a/packages/web/src/features/company/org-sessions.ts b/packages/web/src/features/company/org-sessions.tsindex 2044f7a9..2135572a 100644--- a/packages/web/src/features/company/org-sessions.ts+++ b/packages/web/src/features/company/org-sessions.ts@@ -119,6 +119,24 @@ export function withDeskMessagingChannel(return { ...sessions, desks };}+/**+ * The title the organization gives each of its ticket sessions, by Session id — what the+ * sidebar's Temporary group draws. The organization's own sessions route is the source because+ * the development list excludes organization rows and cannot be asked (see the session list's+ * `excludeOrg`); a session the route does not name keeps the title its ticket listed it under.+ */+export function ticketSessionTitles(+ sessions: OrgSessionsResponse | undefined,+): ReadonlyMap<string, string> {+ const out = new Map<string, string>();+ for (const ticket of sessions?.tickets ?? []) {+ for (const s of ticket.sessions) {+ if (s.title !== undefined && s.title !== "") out.set(s.sessionId, s.title);+ }+ }+ return out;+}+/*** 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 deskdiff --git a/packages/web/src/features/company/shared.tsx b/packages/web/src/features/company/shared.tsxindex ca36968d..e8341e4e 100644--- a/packages/web/src/features/company/shared.tsx+++ b/packages/web/src/features/company/shared.tsx@@ -78,8 +78,8 @@ export function JumpButton({* A title that opens what it names: the click target of a card or a row that has one. The* title is the one part of a surface that already says where a click would land, so it is the* link — a real button, focusable and underlined on hover — while the rest of the surface stays- * inert (or, on the ticket board, stays the drag handle). Where a row has no natural title,- * JumpButton is the way out instead.+ * inert. Where a row has no natural title, JumpButton is the way out instead. (The ticket+ * board's card is the one surface that is a button whole: see tickets-page.tsx.)** The visible text is the accessible name; `title` carries the destination as the tooltip, so* the name is still the thing the reader sees.diff --git a/packages/web/src/features/company/temp-session.ts b/packages/web/src/features/company/temp-session.tsnew file mode 100644index 00000000..62a18518--- /dev/null+++ b/packages/web/src/features/company/temp-session.ts@@ -0,0 +1,268 @@+/**+ * The company sidebar's Temporary group: the ticket sessions the reader opened from a ticket.+ *+ * Ticket sessions are never listed wholesale. There are many of them, and each belongs to the+ * ticket that started it. But a conversation opened from a ticket needs a place in the sidebar+ * that names it and leads back to it later. So opening one from a ticket's dialog adds it to+ * this list, and the sidebar draws the list as a collapsible group below the Desks group:+ *+ * - Opening a session puts it at the top, or moves it there if it is already listed.+ * - An entry stays until the reader removes it: its own ✕, or the group's "Close all". Nothing+ * else does — going elsewhere keeps it, a reload keeps it, and the list has no cap.+ * - A desk session is never listed: its desk row already names it.+ *+ * The list is kept in localStorage, one key per user, Project and organization: two people on+ * one browser keep separate lists, and one organization's sessions never show in another's+ * sidebar. Nothing here follows the location; where the reader is only decides which row is+ * marked as the one on screen.+ *+ * The list logic is pure, and the store takes its storage as an argument (vitest runs in Node,+ * with no localStorage). A read that fails lists nothing, and a write that fails keeps the list+ * in memory for this tab.+ */+import { useSyncExternalStore } from "react";++/** One ticket session in the Temporary group. */+export interface TempSessionEntry {+ sessionId: string;+ /** The employee the session runs as: the row's avatar. */+ agentId: string;+ /** The title the ticket listed it under, until the session list has its own. */+ title: string;+}++/** A row the group draws: an entry, marked when it is the session on screen. */+export interface TempSessionRow extends TempSessionEntry {+ active: boolean;+}++/** The route a Session opens at. */+export function chatPath(sessionId: string): string {+ return `/chat/${sessionId}`;+}++const KEY_PREFIX = "penguin.orgTempSessions.";++/** The list's storage key: one per user, Project and organization. A signed-out browser gets its own bucket. */+export function tempSessionsKey(userId: string | null, projectId: string, orgId: string): string {+ return `${KEY_PREFIX}${userId ?? ""}.${projectId}.${orgId}`;+}++function isDesk(sessionId: string, deskSessionIds: Iterable<string | null>): boolean {+ for (const id of deskSessionIds) if (id === sessionId) return true;+ return false;+}++const EMPTY: readonly TempSessionEntry[] = [];++/**+ * The list after opening `entry`: at the top and listed once. A desk session leaves the list as+ * it was, the same array.+ */+export function withOpened(+ list: readonly TempSessionEntry[],+ entry: TempSessionEntry,+ deskSessionIds: Iterable<string | null> = [],+): readonly TempSessionEntry[] {+ if (isDesk(entry.sessionId, deskSessionIds)) return list;+ return [entry, ...list.filter((e) => e.sessionId !== entry.sessionId)];+}++/** The list after removing one session. A session it does not hold leaves it as it was, the same array. */+export function withDismissed(+ list: readonly TempSessionEntry[],+ sessionId: string,+): readonly TempSessionEntry[] {+ if (!list.some((e) => e.sessionId === sessionId)) return list;+ return list.filter((e) => e.sessionId !== sessionId);+}++/**+ * The rows the group draws, wherever the reader is: every entry except a desk session, which+ * has its desk row. The session on screen is marked; being somewhere else only moves the mark.+ */+export function tempSessionRows(+ list: readonly TempSessionEntry[],+ deskSessionIds: Iterable<string | null>,+ activeSessionId: string | null,+): TempSessionRow[] {+ const desks = new Set(deskSessionIds);+ return list+ .filter((e) => !desks.has(e.sessionId))+ .map((e) => ({ ...e, active: e.sessionId === activeSessionId }));+}++/**+ * A stored list. Only this module's store writes the key, always a whole list, so what is there+ * is read as written; a value that is not JSON lists nothing (the localStorage convention of+ * page-hints.ts).+ */+export function parseTempSessions(raw: string | null): TempSessionEntry[] {+ if (raw === null || raw === "") return [];+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch {+ return [];+ }+ return Array.isArray(parsed) ? (parsed as TempSessionEntry[]) : [];+}++// ---------------------------------------------------------------------------+// The store+// ---------------------------------------------------------------------------++/** The subset of localStorage the store uses; tests pass an in-memory one. */+export interface TempSessionStorage {+ getItem(key: string): string | null;+ setItem(key: string, value: string): void;+ removeItem(key: string): void;+}++export interface TempSessionStore {+ /** One list, newest first. The same array until it changes, as useSyncExternalStore needs. */+ list(key: string): readonly TempSessionEntry[];+ open(key: string, entry: TempSessionEntry, deskSessionIds?: Iterable<string | null>): void;+ dismiss(key: string, sessionId: string): void;+ /** Removes every entry of one list at once. */+ dismissAll(key: string): void;+ /** Drops the copy held for `key` (for every key when null), so the next read goes back to storage. */+ reread(key: string | null): void;+ subscribe(listener: () => void): () => void;+}++/**+ * A store over `storage`, resolved on each access so a storage that throws (blocked site data)+ * is caught where it is used. Each list is read from storage once and then held in memory.+ */+export function createTempSessionStore(+ storage: () => TempSessionStorage | null | undefined,+): TempSessionStore {+ const lists = new Map<string, readonly TempSessionEntry[]>();+ const listeners = new Set<() => void>();+ const notify = (): void => {+ for (const listener of listeners) listener();+ };++ const list = (key: string): readonly TempSessionEntry[] => {+ const held = lists.get(key);+ if (held !== undefined) return held;+ let read: readonly TempSessionEntry[] = EMPTY;+ try {+ const parsed = parseTempSessions(storage()?.getItem(key) ?? null);+ if (parsed.length > 0) read = parsed;+ } catch {+ // Unreadable storage: nothing is listed.+ }+ lists.set(key, read);+ return read;+ };++ const write = (key: string, next: readonly TempSessionEntry[]): void => {+ lists.set(key, next);+ try {+ const target = storage();+ if (next.length === 0) target?.removeItem(key);+ else target?.setItem(key, JSON.stringify(next));+ } catch {+ // Quota or blocked storage: the list lasts as long as this tab.+ }+ notify();+ };++ return {+ list,+ open(key, entry, deskSessionIds = []) {+ const current = list(key);+ const next = withOpened(current, entry, deskSessionIds);+ if (next !== current) write(key, next);+ },+ dismiss(key, sessionId) {+ const current = list(key);+ const next = withDismissed(current, sessionId);+ if (next !== current) write(key, next);+ },+ dismissAll(key) {+ if (list(key).length > 0) write(key, EMPTY);+ },+ reread(key) {+ if (key === null) lists.clear();+ else if (!lists.delete(key)) return;+ notify();+ },+ subscribe(listener) {+ listeners.add(listener);+ return () => {+ listeners.delete(listener);+ };+ },+ };+}++/** The app's store, over this browser's localStorage. */+const store = createTempSessionStore(() => globalThis.localStorage);++let watchingOtherTabs = false;++/**+ * Another tab's write replaces the copy held here. Without this, a tab still holding an entry+ * that another tab removed would write it back the next time it opened or removed one.+ */+function watchOtherTabs(): void {+ if (watchingOtherTabs || typeof window === "undefined") return;+ watchingOtherTabs = true;+ window.addEventListener("storage", (event) => {+ if (event.key === null) store.reread(null);+ else if (event.key.startsWith(KEY_PREFIX)) store.reread(event.key);+ });+}++function subscribe(listener: () => void): () => void {+ watchOtherTabs();+ return store.subscribe(listener);+}++/** One organization's Temporary list for this user, newest first. */+export function useTempSessions(+ userId: string | null,+ projectId: string,+ orgId: string,+): readonly TempSessionEntry[] {+ const key = tempSessionsKey(userId, projectId, orgId);+ const read = (): readonly TempSessionEntry[] => store.list(key);+ return useSyncExternalStore(subscribe, read, read);+}++/** Adds a ticket session to the list, or moves it to the top; a desk session is left out. The caller navigates to it. */+export function openTempSession(+ userId: string | null,+ projectId: string,+ orgId: string,+ entry: TempSessionEntry,+ deskSessionIds: Iterable<string | null>,+): void {+ store.open(tempSessionsKey(userId, projectId, orgId), entry, deskSessionIds);+}++/** Removes one entry. Nothing navigates: the page stays where it is, even on that session. */+export function dismissTempSession(+ userId: string | null,+ projectId: string,+ orgId: string,+ sessionId: string,+): void {+ store.dismiss(tempSessionsKey(userId, projectId, orgId), sessionId);+}++/**+ * The group's "Close all": every entry of this organization's list at once, with no+ * confirmation — the sessions themselves are untouched, and each is still one click away in+ * its ticket. Nothing navigates.+ */+export function dismissAllTempSessions(+ userId: string | null,+ projectId: string,+ orgId: string,+): void {+ store.dismissAll(tempSessionsKey(userId, projectId, orgId));+}diff --git a/packages/web/src/features/company/ticket-dialog.tsx b/packages/web/src/features/company/ticket-dialog.tsxindex 883e470a..02c7b996 100644--- a/packages/web/src/features/company/ticket-dialog.tsx+++ b/packages/web/src/features/company/ticket-dialog.tsx@@ -16,9 +16,12 @@* its own save / cancel; the footer holds the block / unblock and move actions. Saves confirm* first, like every organization write.*- * Nothing here is a whole-row link: a child, a session and the parent are opened by their own- * small corner button, so a click always says where it lands. Only a session leaves the page —- * a conversation has no in-place form — and a parent or a child swaps the dialog's own ticket.+ * The parent, a child and a ticket session are each opened by clicking their title — a text+ * button that underlines on hover and names its destination in its tooltip — while the rest of+ * their row stays inert, so the controls and marks beside a title are never a click target.+ * A parent or a child swaps the dialog's own ticket. Only a session leaves the page, since a+ * conversation has no in-place form: it opens as the full conversation page and joins the+ * company sidebar's Temporary group (temp-session.ts).* A session's live status is not drawn: a ticket reports its own work, not what a session is* doing this second.*/@@ -41,6 +44,7 @@ import { ICON_GAP, ICON_SIZE } from "../../lib/icon-scale";import { toneInk, toneStrip } from "../../lib/tone";import { useAuth } from "../../state/auth";import { useCompany } from "../../state/company";+import { useProject } from "../../state/project";import { useTheme } from "../../state/theme";import { Button } from "../../components/ui/button";import { Chevron } from "../../components/ui/chevron";@@ -58,10 +62,10 @@ import { Md } from "../chat/md";import { OrgSection } from "./org-layout";import {BlockedBadge,- JumpButton,PrincipalChip,PriorityBadge,TicketStatusBadge,+ TitleButton,principalLabel,} from "./shared";import { agentPrincipal, splitPrincipalList } from "./principals";@@ -75,6 +79,9 @@ import {} from "./ticket-board";import { ticketHistoryRows, ticketSummaryCounts } from "./ticket-history";import { dayKey } from "./calendar-geom";+import { orgKey } from "./company-nav";+import { deskRows } from "./org-sessions";+import { chatPath, openTempSession } from "./temp-session";const PRIORITIES: readonly OrgTicketPriority[] = ["P0", "P1", "P2"];@@ -137,6 +144,7 @@ function TicketDialog({}) {const navigate = useNavigate();const company = useCompany();+ const { setCurrentAgentId } = useProject();const { currency } = useTheme();const { user } = useAuth();const me = user?.userId ?? null;@@ -382,11 +390,25 @@ function TicketDialog({);/**- * One field of the summary grid. Every row is exactly one line tall, so labels and values- * line up down the column: anything taller than the line — the parent's jump button is the- * only such thing — pulls its own box back in with a negative margin rather than growing- * the row and pushing its label off the others' baseline.+ * Opens a ticket session: the one way out of the dialog. The session goes to the top of the+ * company sidebar's Temporary group (a desk session keeps its desk row instead) and the+ * conversation opens as its full page. The current Agent follows it, as a desk row's does.*/+ const openSession = (session: { sessionId: string; agentId: string; title?: string }) => {+ const desks = deskRows(company.orgChart, company.orgSessions.get(orgKey(projectId, orgId)));+ openTempSession(+ me,+ projectId,+ orgId,+ { sessionId: session.sessionId, agentId: session.agentId, title: session.title ?? "" },+ desks.map((d) => d.sessionId),+ );+ if (session.agentId !== "") setCurrentAgentId(session.agentId);+ onClose();+ navigate(chatPath(session.sessionId));+ };++ /** One field of the summary grid: every row is one line tall, so labels and values line up down the column. */const row = (label: string, value: ReactNode) => (<><dt className="whitespace-nowrap text-gray-500 dark:text-gray-400">{label}</dt>@@ -582,16 +604,13 @@ function TicketDialog({{row(S.company.tickets.parent,detail.parent !== undefined ? (- <>- <span className="min-w-0 truncate" title={detail.parent}>- {titles.get(detail.parent) ?? detail.parent}- </span>- <JumpButton- label={S.company.tickets.openTicket}- className="-my-1"- onClick={() => onOpenTicket(detail.parent!)}- />- </>+ <TitleButton+ title={`${S.company.tickets.openTicket} · ${detail.parent}`}+ className="truncate"+ onClick={() => onOpenTicket(detail.parent!)}+ >+ {titles.get(detail.parent) ?? detail.parent}+ </TitleButton>) : (<span className="text-gray-400 dark:text-gray-500">{S.company.tickets.noParent}@@ -698,7 +717,7 @@ function TicketDialog({{textSection("result", detail.result, S.company.tickets.noResult)}</OrgSection>- {/* The child tickets, folded: a plain list, each row opened by its own button. */}+ {/* The child tickets, folded: a plain list, each opened by clicking its title. */}<Foldtitle={S.company.tickets.children}summary={@@ -715,8 +734,14 @@ function TicketDialog({<ul className="space-y-0.5">{children.map((c) => (<li key={c.ticketId} className="flex items-center gap-2 px-2 py-1.5 text-sm">- <span className="min-w-0 flex-1 truncate" title={c.ticketId}>- {c.title}+ <span className="flex min-w-0 flex-1">+ <TitleButton+ title={`${S.company.tickets.openTicket} · ${c.ticketId}`}+ className="truncate"+ onClick={() => onOpenTicket(c.ticketId)}+ >+ {c.title}+ </TitleButton></span>{"status" in c && <TicketStatusBadge status={c.status} />}{"owner" in c && (@@ -732,19 +757,15 @@ function TicketDialog({{formatMoney(c.cost, currency)}</span>)}- <JumpButton- label={S.company.tickets.openTicket}- onClick={() => onOpenTicket(c.ticketId)}- /></li>))}</ul>)}</Fold>- {/* The sessions this ticket was worked in, folded. They are opened from here and- nowhere else: starting one and attaching one belong to the owner's desk and to- the CLI, not to a reader of the board. */}+ {/* The sessions this ticket was worked in, folded, each opened by clicking its+ title. They are opened from here and nowhere else: starting one and attaching+ one belong to the owner's desk and to the CLI, not to a reader of the board. */}<Foldtitle={S.company.tickets.sessions}summary={@@ -760,23 +781,33 @@ function TicketDialog({{detail.sessionItems.map((s) => (<li key={s.sessionId} className="flex items-center gap-2 px-2 py-1.5 text-sm"><PrincipalChip principal={agentPrincipal(s.agentId)} names={names} />- <span className="min-w-0 flex-1 truncate text-gray-600 dark:text-gray-300">- {s.title ?? s.sessionId}+ <span className="flex min-w-0 flex-1">+ {s.agentId === "" ? (+ // The ticket still names a session whose row is gone (its Agent+ // was deleted, say): the server answers it with no Agent, and+ // there is nothing to open, so it is plain text and never+ // becomes a Temporary entry.+ <span+ className="truncate text-gray-400 dark:text-gray-500"+ title={s.sessionId}+ >+ {s.title ?? s.sessionId}+ </span>+ ) : (+ <TitleButton+ title={S.company.tickets.openSession}+ className="truncate text-gray-600 hover:text-gray-900 dark:text-gray-300 dark:hover:text-gray-100"+ onClick={() => openSession(s)}+ >+ {s.title ?? s.sessionId}+ </TitleButton>+ )}</span>{s.lastActiveAt !== undefined && (<span className="shrink-0 font-mono text-[11px] tabular-nums text-gray-400 dark:text-gray-500">{formatDateTime(s.lastActiveAt)}</span>)}- {/* The one way out of the dialog: a conversation has no in-place form,- so opening a session closes this and lands on it. */}- <JumpButton- label={S.company.tickets.openSession}- onClick={() => {- onClose();- navigate(`/chat/${s.sessionId}`);- }}- /></li>))}</ul>@@ -981,8 +1012,8 @@ function TicketDialog({}/**- * The confirmation every move goes through, wherever the move was asked for — the board's- * drag-and-drop and the dialog's footer — so a card dropped in a column and a ticket moved+ * The confirmation every move goes through, wherever the move was asked for — a card dragged+ * on the board and the dialog's footer — so a card dropped in a column and a ticket moved* from its detail ask the same question. Moving into rejected also asks for the one-line* reason that is recorded under the ticket's result; the box empties whenever a new move is* proposed, so yesterday's wording cannot ride along.diff --git a/packages/web/src/features/company/ticket-drag.ts b/packages/web/src/features/company/ticket-drag.tsnew file mode 100644index 00000000..8dc161e7--- /dev/null+++ b/packages/web/src/features/company/ticket-drag.ts@@ -0,0 +1,294 @@+/**+ * The ticket board's card gesture, bound to the DOM: the press machine of ticket-press.ts fed+ * from pointer events, the lifted card's ghost following the pointer, the column under it, the+ * board and the page scrolling while the ghost is held near their edges, and the one thing a+ * touch screen needs on top — once a card has lifted, the finger's movement drags it instead of+ * scrolling the page.+ *+ * A card is a plain `<button>`: a click (a press the machine lets through, Enter, Space, or a+ * screen reader's activation) opens the ticket. Only the press is tracked here; its moves and its+ * release are read off `window` for the length of the press, so the pointer is followed wherever+ * it goes without capturing it. Columns are found by `data-ticket-column` under the pointer.+ */+import { useCallback, useEffect, useMemo, useRef, useState } from "react";+import type {+ MouseEvent as ReactMouseEvent,+ PointerEvent as ReactPointerEvent,+ RefObject,+} from "react";+import type { OrgTicketItem, OrgTicketStatus } from "@prismshadow/penguin-server/api";+import { canMove, isTicketStatus } from "./ticket-board";+import { createTicketPress, edgeScrollStep } from "./ticket-press";++/** The attribute a column's drop zone carries, holding its status. */+export const TICKET_COLUMN_ATTR = "data-ticket-column";++/** The card being lifted: what the ghost draws and where it is held from. */+export interface LiftedCard {+ ticket: OrgTicketItem;+ /** The card's width, so the ghost is the card's shape. */+ width: number;+ /** Where inside the card the pointer holds it. */+ offsetX: number;+ offsetY: number;+}++/** The column whose drop zone is under a viewport point, if any. */+function columnAt(x: number, y: number): OrgTicketStatus | null {+ const el = document.elementFromPoint(x, y);+ const zone = el?.closest<HTMLElement>(`[${TICKET_COLUMN_ATTR}]`);+ const status = zone?.getAttribute(TICKET_COLUMN_ATTR) ?? null;+ return isTicketStatus(status) ? status : null;+}++/** The nearest ancestor that scrolls vertically: the page column the board sits in. */+function verticalScroller(from: HTMLElement | null): HTMLElement | null {+ for (let el = from?.parentElement ?? null; el !== null; el = el.parentElement) {+ const overflow = getComputedStyle(el).overflowY;+ if ((overflow === "auto" || overflow === "scroll") && el.scrollHeight > el.clientHeight) {+ return el;+ }+ }+ return null;+}++export function useTicketBoardDrag({+ onOpen,+ onDrop,+}: {+ onOpen: (ticket: OrgTicketItem) => void;+ /** A lifted card was released over another column. */+ onDrop: (ticket: OrgTicketItem, to: OrgTicketStatus) => void;+}): {+ /** The board's horizontal scroller: the touch listener and the edge scroll hang off it. */+ boardRef: RefObject<HTMLDivElement | null>;+ /** The ghost element: its position is written straight to the DOM as the pointer moves. */+ ghostRef: RefObject<HTMLDivElement | null>;+ lifted: LiftedCard | null;+ /** The ghost's position as of this render, for its `style`. */+ ghostTransform: () => string;+ dropOver: OrgTicketStatus | null;+ cardProps: (ticket: OrgTicketItem) => {+ onPointerDown: (e: ReactPointerEvent<HTMLElement>) => void;+ onClick: (e: ReactMouseEvent<HTMLElement>) => void;+ onContextMenu: (e: ReactMouseEvent<HTMLElement>) => void;+ };+} {+ const [lifted, setLifted] = useState<LiftedCard | null>(null);+ const [dropOver, setDropOver] = useState<OrgTicketStatus | null>(null);+ const boardRef = useRef<HTMLDivElement | null>(null);+ const ghostRef = useRef<HTMLDivElement | null>(null);+ const callbacks = useRef({ onOpen, onDrop });+ callbacks.current = { onOpen, onDrop };+ /** The pressed card and the live pointer: read by the machine's handlers and the scroll loop. */+ const pressed = useRef<{+ ticket: OrgTicketItem;+ el: HTMLElement;+ x: number;+ y: number;+ offsetX: number;+ offsetY: number;+ } | null>(null);+ const frame = useRef<number | null>(null);+ const detach = useRef<(() => void) | null>(null);++ const ghostTransform = useCallback(() => {+ const p = pressed.current;+ return p === null ? "none" : `translate(${p.x - p.offsetX}px, ${p.y - p.offsetY}px)`;+ }, []);++ /** Re-reads the column under the pointer; only a column the card may move to lights up. */+ const track = useCallback(() => {+ const p = pressed.current;+ if (p === null) return;+ const over = columnAt(p.x, p.y);+ setDropOver(over !== null && canMove(p.ticket.status, over) ? over : null);+ }, []);++ const stopScrolling = useCallback(() => {+ if (frame.current !== null) cancelAnimationFrame(frame.current);+ frame.current = null;+ }, []);++ /** The press is over: the ghost goes, the columns go dark, the edge scroll stops. */+ const finish = useCallback(() => {+ stopScrolling();+ pressed.current = null;+ setLifted(null);+ setDropOver(null);+ }, [stopScrolling]);++ const press = useMemo(+ () =>+ createTicketPress({+ lift: () => {+ const p = pressed.current;+ if (p === null) return;+ const rect = p.el.getBoundingClientRect();+ p.offsetX = p.x - rect.left;+ p.offsetY = p.y - rect.top;+ setLifted({+ ticket: p.ticket,+ width: rect.width,+ offsetX: p.offsetX,+ offsetY: p.offsetY,+ });+ track();+ // Held near an edge of the board or of the page, the view scrolls toward the column+ // the card is being carried to — one step a frame, for as long as it is held there.+ const board = boardRef.current;+ const page = verticalScroller(board);+ const step = () => {+ const q = pressed.current;+ if (q === null) return;+ let moved = false;+ if (board !== null) {+ const r = board.getBoundingClientRect();+ const dx = edgeScrollStep(q.x, r.left, r.right);+ if (dx !== 0) {+ const before = board.scrollLeft;+ board.scrollLeft += dx;+ moved ||= board.scrollLeft !== before;+ }+ }+ if (page !== null) {+ const r = page.getBoundingClientRect();+ const dy = edgeScrollStep(q.y, r.top, r.bottom);+ if (dy !== 0) {+ const before = page.scrollTop;+ page.scrollTop += dy;+ moved ||= page.scrollTop !== before;+ }+ }+ if (moved) track();+ frame.current = requestAnimationFrame(step);+ };+ frame.current = requestAnimationFrame(step);+ },+ drag: (at) => {+ const p = pressed.current;+ if (p === null) return;+ p.x = at.x;+ p.y = at.y;+ if (ghostRef.current !== null) ghostRef.current.style.transform = ghostTransform();+ track();+ },+ drop: (at) => {+ const p = pressed.current;+ const to = columnAt(at.x, at.y);+ finish();+ if (p !== null && to !== null && canMove(p.ticket.status, to)) {+ callbacks.current.onDrop(p.ticket, to);+ }+ },+ cancel: () => finish(),+ }),+ [track, ghostTransform, finish],+ );++ // A lifted card owns the touch that carries it: its moves drag the card rather than scroll the+ // page. The listener is registered for the board's lifetime, not per press, because a browser+ // decides whether a touch may be held back from scrolling when the touch starts — a listener+ // added once the card has lifted would be too late to stop anything.+ useEffect(() => {+ const board = boardRef.current;+ if (board === null) return;+ const hold = (e: TouchEvent) => {+ if (press.phase() === "lifted" && e.cancelable) e.preventDefault();+ };+ board.addEventListener("touchmove", hold, { passive: false });+ return () => board.removeEventListener("touchmove", hold);+ }, [press]);++ useEffect(+ () => () => {+ detach.current?.();+ press.dispose();+ stopScrolling();+ },+ [press, stopScrolling],+ );++ const cardProps = (ticket: OrgTicketItem) => ({+ onPointerDown: (e: ReactPointerEvent<HTMLElement>) => {+ if (!e.isPrimary || e.button !== 0) return;+ detach.current?.();+ pressed.current = {+ ticket,+ el: e.currentTarget,+ x: e.clientX,+ y: e.clientY,+ offsetX: 0,+ offsetY: 0,+ };+ press.down({+ pointerId: e.pointerId,+ x: e.clientX,+ y: e.clientY,+ button: e.button,+ isPrimary: e.isPrimary,+ pointerType: e.pointerType,+ });+ const pointerId = e.pointerId;+ /** Once the machine is idle again the press is over: nothing is held and nothing listens. */+ const settle = () => {+ if (press.phase() !== "idle") return;+ pressed.current = null;+ detach.current?.();+ };+ const onMove = (ev: PointerEvent) => {+ if (ev.pointerId !== pointerId) return;+ press.move({ pointerId: ev.pointerId, x: ev.clientX, y: ev.clientY });+ };+ const onUp = (ev: PointerEvent) => {+ press.up({ pointerId: ev.pointerId, x: ev.clientX, y: ev.clientY });+ settle();+ };+ const onCancel = (ev: PointerEvent) => {+ if (ev.pointerId !== pointerId) return;+ press.cancel();+ settle();+ };+ const onKey = (ev: KeyboardEvent) => {+ // Escape puts a lifted card back and goes no further (it would close a dialog). A card+ // not yet lifted has nothing to put back, so its press carries on.+ if (ev.key !== "Escape" || press.phase() !== "lifted") return;+ ev.preventDefault();+ ev.stopPropagation();+ press.cancel();+ settle();+ };+ const onBlur = () => {+ press.cancel();+ settle();+ };+ window.addEventListener("pointermove", onMove);+ window.addEventListener("pointerup", onUp);+ window.addEventListener("pointercancel", onCancel);+ window.addEventListener("keydown", onKey, true);+ window.addEventListener("blur", onBlur);+ detach.current = () => {+ window.removeEventListener("pointermove", onMove);+ window.removeEventListener("pointerup", onUp);+ window.removeEventListener("pointercancel", onCancel);+ window.removeEventListener("keydown", onKey, true);+ window.removeEventListener("blur", onBlur);+ detach.current = null;+ };+ },+ onClick: (e: ReactMouseEvent<HTMLElement>) => {+ // The click a drag produces is not an open.+ if (press.consumeClick()) {+ e.preventDefault();+ return;+ }+ callbacks.current.onOpen(ticket);+ },+ // A pressed card must not raise the platform's long-press menu under the finger.+ onContextMenu: (e: ReactMouseEvent<HTMLElement>) => {+ if (press.phase() !== "idle") e.preventDefault();+ },+ });++ return { boardRef, ghostRef, lifted, ghostTransform, dropOver, cardProps };+}diff --git a/packages/web/src/features/company/ticket-press.ts b/packages/web/src/features/company/ticket-press.tsnew file mode 100644index 00000000..9a3b6bfd--- /dev/null+++ b/packages/web/src/features/company/ticket-press.ts@@ -0,0 +1,226 @@+/**+ * The ticket card's press gesture (pure, unit tested): a click opens the ticket, and dragging the+ * card lifts it so it can be dropped on another column.+ *+ * One machine per board, since a board only ever has one card under a finger or the mouse:+ *+ * - `idle` → a primary press starts `pressing`.+ * - `pressing` → released without moving past the slop: a click, and the click event that follows+ * is let through, so the card opens. A mouse or a pen that moves past the slop lifts the card+ * there and then. A touch lifts it only by holding still for the long press: on a phone the+ * board is mostly cards, so a finger moving on one has to scroll the page, and a touch that moves+ * past the slop first gives the press up and leaves the browser's scroll (or tap) alone.+ * - `lifted` → the card follows the pointer, and releasing it drops it where the pointer is.+ * - A cancel (the browser took the gesture over, the pointer was lost, Escape) ends any phase; a+ * lifted card is put back.+ *+ * Only a gesture that lifted the card swallows the click the browser sends after it: a mouse+ * released over the card it pressed still fires one, and so does a touch released between the+ * hold completing and the platform's own long-press threshold. The guard is short-lived and a new+ * press resets it, so a click that does not belong to a drag — Enter, Space, a screen reader's+ * activation — is never eaten by a stale one.+ *+ * The touch-scroll half of the contract lives in the DOM binding: while a card is only being+ * pressed nothing here stops the page, so a finger that moves scrolls it and the browser's+ * `pointercancel` ends the press.+ */++/** How long a touch has to hold a card still before it lifts; a mouse or a pen never waits. */+export const LONG_PRESS_MS = 350;++/**+ * How far (px, either axis) a pressed pointer may move and still be a click. Past it a mouse or a+ * pen starts dragging the card, and a touch gives up its hold.+ */+export const PRESS_SLOP_PX = 6;++/** How long after a drag ends the click it produces is still swallowed. */+export const CLICK_GUARD_MS = 600;++export type PressPhase = "idle" | "pressing" | "lifted";++export interface PressPoint {+ pointerId: number;+ x: number;+ y: number;+}++export interface PressStart extends PressPoint {+ /** `MouseEvent.button`: only the main button (0) presses a card. */+ button: number;+ isPrimary: boolean;+ /** `PointerEvent.pointerType`: `"touch"` lifts the card on a long press, any other on movement. */+ pointerType: string;+}++export interface PressHandlers {+ /** The card lifts, held from the point it was pressed. */+ lift: (at: { x: number; y: number }) => void;+ /** A lifted card follows the pointer. */+ drag: (at: { x: number; y: number }) => void;+ /** A lifted card was released here. */+ drop: (at: { x: number; y: number }) => void;+ /** A lifted card was cancelled rather than released: it goes back where it was. */+ cancel: () => void;+}++/** The timer seam: the browser's in the app, fake timers in the tests. */+export interface PressTimers {+ set: (fn: () => void, ms: number) => unknown;+ clear: (handle: unknown) => void;+}++const defaultTimers: PressTimers = {+ set: (fn, ms) => setTimeout(fn, ms),+ clear: (handle) => clearTimeout(handle as ReturnType<typeof setTimeout>),+};++export interface TicketPress {+ phase: () => PressPhase;+ down: (e: PressStart) => void;+ move: (e: PressPoint) => void;+ up: (e: PressPoint) => void;+ /** The gesture is over without a release: pointercancel, a lost pointer, Escape. */+ cancel: () => void;+ /** Whether the click now arriving belongs to a drag (and so is swallowed). */+ consumeClick: () => boolean;+ dispose: () => void;+}++export function createTicketPress(+ handlers: PressHandlers,+ options: { holdMs?: number; slopPx?: number; timers?: PressTimers } = {},+): TicketPress {+ const holdMs = options.holdMs ?? LONG_PRESS_MS;+ const slopPx = options.slopPx ?? PRESS_SLOP_PX;+ const timers = options.timers ?? defaultTimers;+ let phase: PressPhase = "idle";+ let pointerId = -1;+ let origin = { x: 0, y: 0 };+ /** The press is a touch: it lifts on the hold, and moving past the slop gives it up. */+ let touch = false;+ let holdTimer: unknown = null;+ let guard = false;+ let guardTimer: unknown = null;++ const clearHold = () => {+ if (holdTimer !== null) timers.clear(holdTimer);+ holdTimer = null;+ };+ const clearGuard = () => {+ if (guardTimer !== null) timers.clear(guardTimer);+ guardTimer = null;+ guard = false;+ };+ /** A drag ended: swallow the click it is about to produce. */+ const armGuard = () => {+ clearGuard();+ guard = true;+ guardTimer = timers.set(() => {+ guard = false;+ guardTimer = null;+ }, CLICK_GUARD_MS);+ };+ const end = () => {+ clearHold();+ phase = "idle";+ pointerId = -1;+ };+ const liftCard = () => {+ phase = "lifted";+ handlers.lift(origin);+ };++ return {+ phase: () => phase,++ down: (e) => {+ if (!e.isPrimary || e.button !== 0) return;+ // A lifted card whose release was lost goes back before the next press takes over.+ if (phase === "lifted") handlers.cancel();+ end();+ clearGuard();+ phase = "pressing";+ pointerId = e.pointerId;+ origin = { x: e.x, y: e.y };+ touch = e.pointerType === "touch";+ if (touch) {+ holdTimer = timers.set(() => {+ holdTimer = null;+ if (phase === "pressing") liftCard();+ }, holdMs);+ }+ },++ move: (e) => {+ if (phase === "idle" || e.pointerId !== pointerId) return;+ if (phase === "lifted") {+ handlers.drag({ x: e.x, y: e.y });+ return;+ }+ if (Math.abs(e.x - origin.x) <= slopPx && Math.abs(e.y - origin.y) <= slopPx) return;+ // Past the slop before lifting: a touch is scrolling the page, anything else is dragging.+ if (touch) {+ end();+ return;+ }+ liftCard();+ handlers.drag({ x: e.x, y: e.y });+ },++ up: (e) => {+ if (phase === "idle" || e.pointerId !== pointerId) return;+ const was = phase;+ end();+ // Released before it lifted, the press is a click: the click that follows opens the card.+ if (was !== "lifted") return;+ handlers.drop({ x: e.x, y: e.y });+ armGuard();+ },++ cancel: () => {+ if (phase === "idle") return;+ const was = phase;+ end();+ if (was !== "lifted") return;+ handlers.cancel();+ armGuard();+ },++ consumeClick: () => {+ const swallow = guard;+ clearGuard();+ return swallow;+ },++ dispose: () => {+ end();+ clearGuard();+ },+ };+}++/**+ * How far to scroll a container this frame while a lifted card is held near one of its edges:+ * nothing outside the band, then faster the deeper into it — negative toward the start edge,+ * positive toward the end. `pos`, `start` and `end` are one axis of the pointer and of the+ * container's visible box.+ */+export function edgeScrollStep(+ pos: number,+ start: number,+ end: number,+ band = 48,+ maxStep = 16,+): number {+ if (end - start <= band * 2) return 0;+ if (pos < start + band) {+ const depth = Math.min(1, (start + band - pos) / band);+ return -Math.ceil(depth * maxStep);+ }+ if (pos > end - band) {+ const depth = Math.min(1, (pos - (end - band)) / band);+ return Math.ceil(depth * maxStep);+ }+ return 0;+}diff --git a/packages/web/src/features/company/tickets-page.tsx b/packages/web/src/features/company/tickets-page.tsxindex a04dbe41..babe96d0 100644--- a/packages/web/src/features/company/tickets-page.tsx+++ b/packages/web/src/features/company/tickets-page.tsx@@ -2,13 +2,17 @@* The ticket board: five columns in lifecycle order (shaping in ticket-board.ts), each with* its colour bar and count, a card per ticket — title, priority, due date (danger once* passed), the blocked badge, a muted line naming its parent, and its owner — a search box- * and a blocked-only switch, drag-and-drop between columns that confirms the move (a move- * into rejected asks for a one-line reason) before posting it, the create form, and the- * tickets and files the server could not accept.- * The whole card is the drag handle, and its title is the one click target: the title is a- * text button that opens the detail dialog (the shell's one host renders it, so the board- * stays where it is), the rest of the card is inert, and a drag never fires a click — so- * dragging anywhere (the title included) moves the ticket while clicking the title opens it.+ * and a blocked-only switch, moving a card between columns by dragging it, which+ * confirms the move (a move into rejected asks for a one-line reason) before posting it, the+ * create form, and the tickets and files the server could not accept.+ * The whole card is one button — the board's one exception to the company pages' rule against+ * whole-area click targets, and it holds no control of its own. A click anywhere on it (Enter+ * and Space too) opens the detail dialog in place (the shell's one host renders it, so the+ * board stays where it is). Dragging it moves it: a mouse or pen press that travels a few pixels+ * lifts the card, which follows the pointer and, released over another column, asks to move+ * there. A finger has to hold the card still for a moment before it lifts, so a finger that moves+ * scrolls the page as usual (ticket-press.ts, ticket-drag.ts). The dialog's move control is the+ * way to move a ticket without dragging.* The priority rides on the title's line, one size under it. What a card deliberately does* not carry is the session count, the cost and any live session status — those are the* dialog's, and a ticket is not the place to watch a session run.@@ -22,8 +26,8 @@* shell state, not a route.*/import { useCallback, useEffect, useRef, useState } from "react";-import type { DragEvent as ReactDragEvent } from "react";-import { useSearchParams } from "react-router";+import { createPortal } from "react-dom";+import { useLocation, useSearchParams } from "react-router";import type {OrgChartResponse,OrgTicketItem,@@ -75,9 +79,8 @@ import { MoveTicketConfirm } from "./ticket-dialog";import { dismissHint, hintKey, isHintDismissed } from "./page-hints";import { agentPrincipal, splitPrincipalList } from "./principals";import { dayKey } from "./calendar-geom";+import { TICKET_COLUMN_ATTR, useTicketBoardDrag } from "./ticket-drag";-/** Private drag payload type of a card move (never text/plain: a mis-aimed drop must not paste into a text field). */-const TICKET_DRAG_MIME = "application/x-penguin-ticket-id";const PRIORITIES: readonly OrgTicketPriority[] = ["P0", "P1", "P2"];/** Clock face (lucide): the due-date mark on a card. */@@ -104,14 +107,13 @@ export function TicketsPage() {const company = useCompany();const { user } = useAuth();const [params, setParams] = useSearchParams();+ const location = useLocation();useDocumentTitle(org ? `${org.name} · ${S.nav.org.tickets}` : S.nav.org.tickets);const [board, setBoard] = useState<OrgTicketsResponse | null>(null);const [chart, setChart] = useState<OrgChartResponse | null>(null);const [error, setError] = useState<string | null>(null);const [blockedOnly, setBlockedOnly] = useState(params.get("blocked") === "1");const [query, setQuery] = useState("");- const [drag, setDrag] = useState<{ ticketId: string; from: OrgTicketStatus } | null>(null);- const [dropOver, setDropOver] = useState<OrgTicketStatus | null>(null);const [move, setMove] = useState<{ ticket: OrgTicketItem; to: OrgTicketStatus } | null>(null);const [createOpen, setCreateOpen] = useState(false);const [busy, setBusy] = useState(false);@@ -159,6 +161,11 @@ export function TicketsPage() {setParams(next, { replace: true });};const openTicket = (ticketId: string) => company.openTicket(projectId, orgId, ticketId);+ const drag = useTicketBoardDrag({+ onOpen: (ticket) => openTicket(ticket.ticketId),+ onDrop: (ticket, to) => setMove({ ticket, to }),+ });+ const { lifted, dropOver } = drag;// `?ticket=` and the open dialog, kept in step in both directions: the query opens the// dialog on arrival (a deep link, a reload), and the dialog writes itself back into the@@ -173,7 +180,14 @@ export function TicketsPage() {: null;const syncedTicket = useRef<string | null>(null);const { openTicket: openTicketInShell } = company;+ const routedPath = location.pathname;useEffect(() => {+ // The browser has already left this page: a click that closes the dialog and navigates+ // (opening a ticket session) is rendered first with the dialog closed and this page still+ // mounted, since the router commits its new location in a transition. Writing the query now+ // would resolve against this page's stale location and replace the new history entry with+ // the board — the navigation would silently land back here.+ if (window.location.pathname !== routedPath) return;if (urlTicket !== syncedTicket.current) {syncedTicket.current = urlTicket;if (urlTicket !== null) {@@ -192,7 +206,7 @@ export function TicketsPage() {},{ replace: true },);- }, [urlTicket, dialogTicket, projectId, orgId, openTicketInShell, setParams]);+ }, [urlTicket, dialogTicket, projectId, orgId, openTicketInShell, setParams, routedPath]);const confirmMove = async (reason: string) => {if (move === null) return;@@ -214,65 +228,15 @@ export function TicketsPage() {}};- const columnDrop = (status: OrgTicketStatus) => ({- onDragOver: (e: ReactDragEvent) => {- if (- drag === null ||- !e.dataTransfer.types.includes(TICKET_DRAG_MIME) ||- !canMove(drag.from, status)- )- return;- e.preventDefault();- e.dataTransfer.dropEffect = "move";- if (dropOver !== status) setDropOver(status);- },- onDragLeave: (e: ReactDragEvent) => {- const to = e.relatedTarget;- if (to instanceof Node && e.currentTarget.contains(to)) return;- setDropOver((prev) => (prev === status ? null : prev));- },- onDrop: (e: ReactDragEvent) => {- if (drag === null || !canMove(drag.from, status) || board === null) return;- e.preventDefault();- const ticket = allTickets(board).find((t) => t.ticketId === drag.ticketId);- setDrag(null);- setDropOver(null);- if (ticket === undefined) return;- setMove({ ticket, to: status });- },- });-- /** A card: the title with its priority first (the title is the button that opens it), then what decides its urgency, then where it hangs and who holds it. */- const card = (t: OrgTicketItem) => {+ /** A card's face: the title with its priority first, then what decides its urgency, then where it hangs and who holds it. */+ const cardBody = (t: OrgTicketItem) => {const overdue = isOverdue(t.due, todayKey) && t.status !== "done" && t.status !== "rejected";return (- <div- key={t.ticketId}- draggable- onDragStart={(e) => {- e.dataTransfer.setData(TICKET_DRAG_MIME, t.ticketId);- e.dataTransfer.effectAllowed = "move";- setDrag({ ticketId: t.ticketId, from: t.status });- }}- onDragEnd={() => {- setDrag(null);- setDropOver(null);- }}- title={`${t.title} · ${t.ticketId} · ${S.company.tickets.dragHint}`}- className={`block w-full cursor-grab rounded-md border bg-white p-2.5 text-left text-xs transition-colors duration-150 hover:border-gray-300 dark:bg-gray-900 dark:hover:border-gray-600 ${- t.invalid !== undefined- ? "border-red-300 dark:border-red-800"- : "border-gray-200 dark:border-gray-800"- } ${drag?.ticketId === t.ticketId ? "opacity-50" : ""}`}- >- <div className="flex items-start gap-1.5">- <TitleButton- title={S.company.tickets.openTicket}- className="line-clamp-2 flex-1 text-[13px] font-medium leading-snug text-gray-900 dark:text-gray-100"- onClick={() => openTicket(t.ticketId)}- >+ <>+ <span className="flex items-start gap-1.5">+ <span className="line-clamp-2 min-w-0 flex-1 text-[13px] font-medium leading-snug text-gray-900 dark:text-gray-100">{t.title}- </TitleButton>+ </span>{/* The priority reads with the title and shares its line, a size under it; the linebelow carries what is time-bound — the due date and the blocked mark. */}<span className="mt-px shrink-0">@@ -284,11 +248,11 @@ export function TicketsPage() {<span className="sr-only">{S.company.tickets.invalid}</span></span>)}- </div>+ </span>{/* The time-bound line, drawn only when there is something on it: the priority hasmoved up to the title and an empty row would leave a gap under it. */}{(t.due !== undefined || isBlocked(t)) && (- <div className="mt-2 flex flex-wrap items-center gap-1.5 text-[11px] text-gray-500 dark:text-gray-400">+ <span className="mt-2 flex flex-wrap items-center gap-1.5 text-[11px] text-gray-500 dark:text-gray-400">{t.due !== undefined && (<spanclassName={`inline-flex items-center gap-1 font-mono tabular-nums ${overdue ? toneInk.danger : ""}`}@@ -307,28 +271,56 @@ export function TicketsPage() {/></span>)}- </div>+ </span>)}{t.parent !== undefined && (- <p- className="mt-2 truncate text-[11px] text-gray-400 dark:text-gray-500"+ <span+ className="mt-2 block truncate text-[11px] text-gray-400 dark:text-gray-500"title={t.parent}>{S.company.tickets.parentLine(titles.get(t.parent) ?? t.parent)}- </p>+ </span>)}- <div className="mt-2 flex items-center gap-2 text-[11px] text-gray-500 dark:text-gray-400">+ <span className="mt-2 flex items-center gap-2 text-[11px] text-gray-500 dark:text-gray-400"><spanclassName="flex min-w-0 text-gray-700 dark:text-gray-200"title={`${S.company.tickets.owner} ${principalLabel(t.owner, names)}`}><PrincipalChip principal={t.owner} names={names} size={ICON_SIZE.rowLead} /></span>- </div>- </div>+ </span>+ </>);};+ /** The card's frame: a hairline box, danger-edged when the server flagged the ticket. */+ const cardFrame = (t: OrgTicketItem) =>+ `block w-full rounded-md border bg-white p-2.5 text-left text-xs dark:bg-gray-900 ${+ t.invalid !== undefined+ ? "border-red-300 dark:border-red-800"+ : "border-gray-200 dark:border-gray-800"+ }`;++ /**+ * A card: one button over the whole face. Unselectable and without the platform's long-press+ * callout, so dragging it never selects its words and holding it on a touch screen never raises+ * a menu; dimmed in place while its ghost is being carried.+ */+ const card = (t: OrgTicketItem) => (+ <button+ key={t.ticketId}+ type="button"+ data-ticket-card={t.ticketId}+ title={`${t.title} · ${t.ticketId} · ${S.company.tickets.dragHint}`}+ {...drag.cardProps(t)}+ className={`${cardFrame(t)} cursor-pointer select-none transition-[border-color,opacity] duration-150 [-webkit-touch-callout:none] hover:border-gray-300 dark:hover:border-gray-600 ${+ lifted?.ticket.ticketId === t.ticketId ? "opacity-40" : ""+ }`}+ >+ {cardBody(t)}+ </button>+ );+const columns = board === null ? null : boardColumns(board, { blockedOnly, query, names });const narrowed = blockedOnly || query.trim() !== "";const invalids = board === null ? [] : invalidTickets(board);@@ -401,7 +393,7 @@ export function TicketsPage() {</div>)}- <div className="overflow-x-auto pb-2">+ <div ref={drag.boardRef} className="overflow-x-auto pb-2"><div className="grid min-w-[50rem] grid-cols-5 gap-3">{columns === null? TICKET_COLUMNS.map((status) => <ColumnSkeleton key={status} status={status} />)@@ -410,7 +402,7 @@ export function TicketsPage() {key={col.status}role="group"aria-label={`${S.company.tickets.columns[col.status] ?? col.status} · ${col.tickets.length}`}- {...columnDrop(col.status)}+ {...{ [TICKET_COLUMN_ATTR]: col.status }}className={`${columnClass} ${dropOver === col.status? "border-[var(--accent-bg)] ring-1 ring-[var(--accent-bg)]"@@ -438,7 +430,7 @@ export function TicketsPage() {: "border-gray-300 text-gray-400 dark:border-gray-700 dark:text-gray-500"}`}>- {drag !== null && canMove(drag.from, col.status)+ {lifted !== null && canMove(lifted.ticket.status, col.status)? S.company.tickets.dropHere: narrowed? S.company.tickets.searchNoMatch@@ -493,6 +485,26 @@ export function TicketsPage() {</div>)}+ {/* The lifted card's ghost: the card's own face at its own width, following the+ pointer above everything else and never under it — the column hit test reads through+ it. The pointer's moves write its position straight to the element. */}+ {lifted !== null &&+ createPortal(+ <div+ ref={drag.ghostRef}+ aria-hidden+ style={{ width: lifted.width, transform: drag.ghostTransform() }}+ className="pointer-events-none fixed left-0 top-0 z-[60]"+ >+ <div+ className={`${cardFrame(lifted.ticket)} rotate-1 shadow-lg ring-1 ring-[var(--accent-bg)]`}+ >+ {cardBody(lifted.ticket)}+ </div>+ </div>,+ document.body,+ )}+{/* Move confirmation: the target column, and a reason when the target is rejected —the same dialog the detail's own move goes through. */}<MoveTicketConfirmdiff --git a/packages/web/src/lib/install-scope.ts b/packages/web/src/lib/install-scope.tsindex 02ec12d8..2fa6656d 100644--- a/packages/web/src/lib/install-scope.ts+++ b/packages/web/src/lib/install-scope.ts@@ -325,6 +325,12 @@ export const KEY_RULES: readonly KeyRule[] = [scope: "install",why: "A dismissed empty-page note, keyed by user, Project and organization id of this root.",},+ {+ kind: "family",+ key: "penguin.orgTempSessions.",+ scope: "install",+ why: "The company sidebar's Temporary group of ticket sessions, keyed by user, Project and organization id and naming Sessions and Agents of this root.",+ },{kind: "family",key: "penguin.lastAgentId.",diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.tsindex 5328079e..2fa17564 100644--- a/packages/web/src/lib/strings-en.ts+++ b/packages/web/src/lib/strings-en.ts@@ -3999,6 +3999,10 @@ Scenarios:noEmployees: "This organization has no employees yet",untitledSession: "Untitled session",loadFailed: "The employee list could not be loaded",+ temporary: (n: number): string => `Temporary (${n})`,+ temporaryEntry: (title: string): string => `Temporary · ${title}`,+ closeTemporary: "Remove from Temporary",+ closeAllTemporary: "Close all",},overview: {title: "Overview",@@ -4258,7 +4262,7 @@ Scenarios:},tickets: {title: "Tickets",- info: "Five columns are a ticket's life: proposed → in progress → review → done / rejected. Drag a card to move it between columns, click a card's title to open its detail in place; a blocked ticket stays in its column with a badge. A ticket is the organization's unit of work: use New ticket, top right, to create one and name an owner, and the owner's desk session starts a ticket session for it.",+ info: "Five columns are a ticket's life: proposed → in progress → review → done / rejected. Click a card to open its detail in place, and drag it to another column to move it (on a touch screen, press and hold the card first); a blocked ticket stays in its column with a badge. A ticket is the organization's unit of work: use New ticket, top right, to create one and name an owner, and the owner's desk session starts a ticket session for it.",columns: {proposed: "Proposed",in_progress: "In progress",diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.tsindex c7fcbfb9..c1ba8a7b 100644--- a/packages/web/src/lib/strings.ts+++ b/packages/web/src/lib/strings.ts@@ -4024,6 +4024,13 @@ Benchmark:noEmployees: "这个组织还没有员工",untitledSession: "未命名会话",loadFailed: "员工列表加载失败",+ /** The group below the desks listing the ticket sessions opened from a ticket, each kept until removed. */+ temporary: (n: number): string => `临时(${n})`,+ /** A Temporary entry's name on the collapsed rail, where no group header says where it belongs. */+ temporaryEntry: (title: string): string => `临时 · ${title}`,+ closeTemporary: "从「临时」中移除",+ /** The Temporary group header's action: removes every entry at once; the sessions themselves are kept. */+ closeAllTemporary: "全部关闭",},overview: {title: "概览",@@ -4255,7 +4262,7 @@ Benchmark:},tickets: {title: "工单",- info: "五列看板即工单的生命周期:提议 → 进行中 → 审核中 → 已完成 / 已拒绝。拖拽卡片移列,点卡片标题在原地弹出详情窗口;被阻塞的工单留在原列并带角标。工单是组织的工作单位:点右上角「新建工单」建一张并指定负责人,它的工位会话会为这张工单发起工单会话。",+ info: "五列看板即工单的生命周期:提议 → 进行中 → 审核中 → 已完成 / 已拒绝。点卡片在原地弹出详情窗口,把卡片拖到另一列即可移列(触屏上先长按卡片再拖);被阻塞的工单留在原列并带角标。工单是组织的工作单位:点右上角「新建工单」建一张并指定负责人,它的工位会话会为这张工单发起工单会话。",columns: {proposed: "提议",in_progress: "进行中",diff --git a/packages/web/test/company-click-targets.test.ts b/packages/web/test/company-click-targets.test.tsindex 098cf2fe..1f351791 100644--- a/packages/web/test/company-click-targets.test.ts+++ b/packages/web/test/company-click-targets.test.ts@@ -3,8 +3,10 @@** A card, a row, a heading or a panel is never itself the link — but a row's or a card's *title** is: the title renders as a text button that opens what it names, and the surface around it- * stays inert (on the ticket board it stays the drag handle). A row with no title of its own- * carries a small named icon button instead. What the rule rules out is the silently clickable+ * stays inert. A row with no title of its own carries a small named icon button instead. The one+ * deliberate exception is the ticket board's card, which is a `<button>` over its whole face: a+ * click anywhere opens the ticket and a drag moves it, and it holds no control of its own+ * that the whole-card target could swallow. What the rule rules out is the silently clickable* surface, which swallows the controls living inside it and leaves a reader guessing what a* click will do. It came out of the company pages, where a whole card, a whole row and a bare* heading had each grown a click of its own.@@ -19,7 +21,8 @@* A `<button>` around a title is a control host and passes, which is the point — the check is* about where the handler sits, not about whether a surface navigates at all. Out of its reach,* and still on the rule: a `<button>` that wraps a whole row (nothing in the syntax says how much- * of the row it covers), and a click handler passed down as a prop. Those are on the reviewer.+ * of the row it covers — the ticket card is the declared one), and a click handler passed down as+ * a prop. Those are on the reviewer.*/import { describe, expect, it } from "vitest";import { readFileSync } from "node:fs";@@ -42,6 +45,7 @@ const MODULES = ["features/company/handbook-page.tsx","features/company/org-chart-page.tsx","features/company/org-layout.tsx",+ "features/company/org-session-groups.tsx","features/company/overview-page.tsx","features/company/shared.tsx","features/company/ticket-dialog.tsx",diff --git a/packages/web/test/install-scope.test.ts b/packages/web/test/install-scope.test.tsindex 048f6940..0edef0fa 100644--- a/packages/web/test/install-scope.test.ts+++ b/packages/web/test/install-scope.test.ts@@ -66,6 +66,8 @@ function populated(): ReturnType<typeof memStorage> {"penguin.modelsGroupOrder.default_project": '["anthropic"]',"penguin.dock.layout": '{"scopes":{"session-1":{}},"bottomRatio":0.4}',"penguin.terminal.page.id": "term-1",+ "penguin.orgTempSessions.admin.default_project.acme":+ '[{"sessionId":"session-2","agentId":"acme_dev","title":"Build the site"}]',"penguin.theme": "dark","penguin.fontScale": "lg",diff --git a/packages/web/test/org-sessions.test.ts b/packages/web/test/org-sessions.test.tsindex de75e057..76c9205f 100644--- a/packages/web/test/org-sessions.test.ts+++ b/packages/web/test/org-sessions.test.ts@@ -3,7 +3,8 @@* 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+ * the titles the route gives the ticket sessions the Temporary group lists, 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 —* 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@@ -19,6 +20,7 @@ import {deskRows,liveEmployeeStates,orgRowActivity,+ ticketSessionTitles,withDeskMessagingChannel,} from "../src/features/company/org-sessions";import { isOrgSession, withoutOrgSessions } from "../src/lib/session-grouping";@@ -202,6 +204,21 @@ describe("the desk row's messaging mark", () => {});});+describe("ticketSessionTitles", () => {+ it("names the ticket sessions the route gave a title, across every ticket", () => {+ const titles = ticketSessionTitles(sessions);+ expect(titles.get("s-t2")).toBe("Write docs");+ expect(titles.get("s-t3")).toBe("Build the site");+ // Untitled yet, and a desk: neither is named, so the Temporary row keeps its own title.+ expect(titles.has("s-t1")).toBe(false);+ expect(titles.has("s-ceo")).toBe(false);+ });++ it("names nothing while the route has not been read", () => {+ expect(ticketSessionTitles(undefined).size).toBe(0);+ });+});+describe("orgRowActivity", () => {it("draws the live states and nothing when settled", () => {expect(orgRowActivity("running")).toBe("running");diff --git a/packages/web/test/temp-session.test.ts b/packages/web/test/temp-session.test.tsnew file mode 100644index 00000000..e821c8e7--- /dev/null+++ b/packages/web/test/temp-session.test.ts@@ -0,0 +1,251 @@+/**+ * temp-session.ts unit tests: the company sidebar's Temporary group of ticket sessions. Opening+ * a session adds it at the top or moves it there; ✕ removes one entry and "Close all" every+ * entry, and nothing else removes any: going elsewhere only moves the on-screen mark, a reload+ * reads the list back from storage, and the list has no cap. It never holds a desk session, and+ * is kept per user, Project and organization.+ */+import { describe, expect, it } from "vitest";+import {+ chatPath,+ createTempSessionStore,+ parseTempSessions,+ tempSessionRows,+ tempSessionsKey,+ withDismissed,+ withOpened,+} from "../src/features/company/temp-session";+import type { TempSessionEntry, TempSessionStorage } from "../src/features/company/temp-session";++/** In-memory storage (vitest runs in a Node environment, no localStorage). */+function memStorage(): TempSessionStorage & { map: Map<string, string> } {+ const map = new Map<string, string>();+ return {+ map,+ getItem: (k) => map.get(k) ?? null,+ setItem: (k, v) => void map.set(k, v),+ removeItem: (k) => void map.delete(k),+ };+}++function entry(n: number | string, over: Partial<TempSessionEntry> = {}): TempSessionEntry {+ return { sessionId: `sess_${n}`, agentId: "acme_dev", title: `Ticket session ${n}`, ...over };+}++const ids = (list: readonly { sessionId: string }[]): string[] => list.map((e) => e.sessionId);++const KEY = tempSessionsKey("admin", "proj", "acme");++describe("temporary session list", () => {+ it("opens a conversation at its own route", () => {+ expect(chatPath("sess_a")).toBe("/chat/sess_a");+ });++ it("adds an opened session at the top", () => {+ const one = withOpened([], entry("a"));+ expect(one).toEqual([entry("a")]);+ expect(ids(withOpened(one, entry("b")))).toEqual(["sess_b", "sess_a"]);+ });++ it("moves a session opened again to the top, listed once and with the title it was opened under", () => {+ const list = [entry("c"), entry("b"), entry("a")];+ const next = withOpened(list, entry("a", { title: "Renamed" }));+ expect(ids(next)).toEqual(["sess_a", "sess_c", "sess_b"]);+ expect(next[0]!.title).toBe("Renamed");+ });++ it("removes a dismissed session and keeps the rest in order", () => {+ const list = [entry("c"), entry("b"), entry("a")];+ expect(ids(withDismissed(list, "sess_b"))).toEqual(["sess_c", "sess_a"]);+ // A session the list does not hold changes nothing, down to the array itself.+ expect(withDismissed(list, "sess_gone")).toBe(list);+ });++ it("has no cap: opening more sessions never drops an older one", () => {+ let list: readonly TempSessionEntry[] = [];+ for (let n = 1; n <= 50; n += 1) list = withOpened(list, entry(n));+ expect(list).toHaveLength(50);+ expect(list[0]!.sessionId).toBe("sess_50");+ expect(list[49]!.sessionId).toBe("sess_1");+ });++ it("never lists a desk session, which has its desk row", () => {+ const list = [entry("a")];+ expect(withOpened(list, entry("desk"), ["sess_desk", null])).toBe(list);+ // One recorded before its desk was known is still not drawn.+ const rows = tempSessionRows([entry("desk"), entry("a")], [null, "sess_desk"], null);+ expect(ids(rows)).toEqual(["sess_a"]);+ });++ it("keeps every entry wherever the reader goes; only the on-screen mark moves", () => {+ const list = [entry("b"), entry("a")];+ const onA = tempSessionRows(list, [], "sess_a");+ expect(onA.map((r) => [r.sessionId, r.active])).toEqual([+ ["sess_b", false],+ ["sess_a", true],+ ]);+ // Another conversation, a desk, or a page with no conversation at all.+ for (const elsewhere of ["sess_other", "sess_desk", null]) {+ const rows = tempSessionRows(list, ["sess_desk"], elsewhere);+ expect(ids(rows)).toEqual(["sess_b", "sess_a"]);+ expect(rows.every((r) => !r.active)).toBe(true);+ }+ });++ it("removes only the row when the session on screen is dismissed", () => {+ const list = withDismissed([entry("b"), entry("a")], "sess_a");+ expect(tempSessionRows(list, [], "sess_a")).toEqual([{ ...entry("b"), active: false }]);+ });+});++describe("stored temporary session list", () => {+ it("reads nothing from a missing, malformed or non-list value", () => {+ expect(parseTempSessions(null)).toEqual([]);+ expect(parseTempSessions("")).toEqual([]);+ expect(parseTempSessions("{not json")).toEqual([]);+ expect(parseTempSessions('{"sessionId":"sess_a"}')).toEqual([]);+ });+});++describe("temporary session store", () => {+ it("survives a reload: a new store over the same storage reads the list back", () => {+ const storage = memStorage();+ const before = createTempSessionStore(() => storage);+ before.open(KEY, entry("a"));+ before.open(KEY, entry("b"));+ before.open(KEY, entry("c"));+ before.dismiss(KEY, "sess_b");++ const after = createTempSessionStore(() => storage);+ expect(after.list(KEY)).toEqual([entry("c"), entry("a")]);+ });++ it("removes the stored key once the last entry is dismissed", () => {+ const storage = memStorage();+ const store = createTempSessionStore(() => storage);+ store.open(KEY, entry("a"));+ expect(storage.map.has(KEY)).toBe(true);+ store.dismiss(KEY, "sess_a");+ expect(storage.map.has(KEY)).toBe(false);+ expect(createTempSessionStore(() => storage).list(KEY)).toEqual([]);+ });++ it("closes every entry at once with Close all, and says so once", () => {+ const storage = memStorage();+ const store = createTempSessionStore(() => storage);+ const other = tempSessionsKey("admin", "proj", "globex");+ store.open(KEY, entry("a"));+ store.open(KEY, entry("b"));+ store.open(other, entry("c"));+ let notified = 0;+ store.subscribe(() => {+ notified += 1;+ });++ store.dismissAll(KEY);+ expect(store.list(KEY)).toEqual([]);+ expect(notified).toBe(1);+ expect(storage.map.has(KEY)).toBe(false);+ // Another organization's list is its own.+ expect(store.list(other)).toEqual([entry("c")]);+ // And the next page load agrees.+ expect(createTempSessionStore(() => storage).list(KEY)).toEqual([]);++ // Nothing left to close: nobody is told.+ store.dismissAll(KEY);+ expect(notified).toBe(1);+ });++ it("keeps one list per user, Project and organization", () => {+ const keys = [+ tempSessionsKey("admin", "proj", "acme"),+ tempSessionsKey("admin", "proj", "globex"),+ tempSessionsKey("admin", "other_proj", "acme"),+ tempSessionsKey("dana", "proj", "acme"),+ tempSessionsKey(null, "proj", "acme"),+ ];+ expect(new Set(keys).size).toBe(keys.length);+ for (const key of keys) expect(key.startsWith("penguin.orgTempSessions.")).toBe(true);++ const storage = memStorage();+ const store = createTempSessionStore(() => storage);+ store.open(keys[0]!, entry("a"));+ store.open(keys[1]!, entry("b"));+ expect(store.list(keys[0]!)).toEqual([entry("a")]);+ expect(store.list(keys[1]!)).toEqual([entry("b")]);+ for (const key of keys.slice(2)) expect(store.list(key)).toEqual([]);+ // And the same after a reload.+ const reloaded = createTempSessionStore(() => storage);+ expect(reloaded.list(keys[0]!)).toEqual([entry("a")]);+ expect(reloaded.list(keys[3]!)).toEqual([]);+ });++ it("leaves a desk session out of the stored list", () => {+ const storage = memStorage();+ const store = createTempSessionStore(() => storage);+ store.open(KEY, entry("a"));+ store.open(KEY, entry("desk"), ["sess_desk"]);+ expect(store.list(KEY)).toEqual([entry("a")]);+ });++ it("tells subscribers about a change and nothing else, and hands out the same array until one", () => {+ const storage = memStorage();+ const store = createTempSessionStore(() => storage);+ let notified = 0;+ const unsubscribe = store.subscribe(() => {+ notified += 1;+ });+ const empty = store.list(KEY);+ expect(store.list(KEY)).toBe(empty);++ store.open(KEY, entry("a"));+ expect(notified).toBe(1);+ const one = store.list(KEY);+ expect(one).not.toBe(empty);+ expect(store.list(KEY)).toBe(one);++ store.open(KEY, entry("desk"), ["sess_desk"]);+ store.dismiss(KEY, "sess_gone");+ expect(notified).toBe(1);+ expect(store.list(KEY)).toBe(one);++ store.dismiss(KEY, "sess_a");+ expect(notified).toBe(2);+ unsubscribe();+ store.open(KEY, entry("b"));+ expect(notified).toBe(2);+ });++ it("rereads a list another tab changed, so an entry removed there is not written back", () => {+ const storage = memStorage();+ const here = createTempSessionStore(() => storage);+ const there = createTempSessionStore(() => storage);+ here.open(KEY, entry("a"));+ expect(there.list(KEY)).toEqual([entry("a")]);++ here.dismiss(KEY, "sess_a");+ let notified = 0;+ there.subscribe(() => {+ notified += 1;+ });+ there.reread(KEY);+ expect(notified).toBe(1);+ expect(there.list(KEY)).toEqual([]);+ there.open(KEY, entry("b"));+ expect(createTempSessionStore(() => storage).list(KEY)).toEqual([entry("b")]);++ // A key this store never read has nothing to drop, so nobody is told.+ const before = notified;+ there.reread(tempSessionsKey("admin", "proj", "globex"));+ expect(notified).toBe(before);+ });++ it("lists nothing from a storage that throws, and keeps what is opened for this tab", () => {+ const blocked = createTempSessionStore(() => {+ throw new Error("site data is blocked");+ });+ expect(blocked.list(KEY)).toEqual([]);+ blocked.open(KEY, entry("a"));+ expect(blocked.list(KEY)).toEqual([entry("a")]);+ });+});diff --git a/packages/web/test/ticket-press.test.ts b/packages/web/test/ticket-press.test.tsnew file mode 100644index 00000000..bf01950d--- /dev/null+++ b/packages/web/test/ticket-press.test.ts@@ -0,0 +1,236 @@+/**+ * ticket-press.ts unit tests: a press released inside the slop is a click and lets its click+ * through; a mouse or pen press that moves past the slop lifts the card at once, with no timer; a+ * touch lifts it only after the long press and gives the press up when it moves first; a release+ * drops a lifted card and swallows the click that follows, for a short window only; a cancel+ * (Escape) puts a lifted card back; only the main button of the primary pointer presses. Plus the+ * edge-scroll step a lifted card drives. Timings run on fake timers.+ */+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import {+ CLICK_GUARD_MS,+ LONG_PRESS_MS,+ PRESS_SLOP_PX,+ createTicketPress,+ edgeScrollStep,+} from "../src/features/company/ticket-press";+import type { PressStart } from "../src/features/company/ticket-press";++function setup(pointerType = "mouse") {+ const calls: string[] = [];+ const press = createTicketPress({+ lift: (at) => calls.push(`lift ${at.x},${at.y}`),+ drag: (at) => calls.push(`drag ${at.x},${at.y}`),+ drop: (at) => calls.push(`drop ${at.x},${at.y}`),+ cancel: () => calls.push("cancel"),+ });+ const down = (x = 10, y = 10, over: Partial<PressStart> = {}) =>+ press.down({ pointerId: 1, button: 0, isPrimary: true, pointerType, x, y, ...over });+ const move = (x: number, y: number, pointerId = 1) => press.move({ pointerId, x, y });+ const up = (x: number, y: number, pointerId = 1) => press.up({ pointerId, x, y });+ return { press, calls, down, move, up };+}++beforeEach(() => {+ vi.useFakeTimers();+});+afterEach(() => {+ vi.useRealTimers();+});++describe("ticket card press: mouse and pen", () => {+ it.each(["mouse", "pen"])(+ "%s: a press released inside the slop is a click, and its click opens the card",+ (pointerType) => {+ const { press, calls, down, move, up } = setup(pointerType);+ down(10, 10);+ move(10 + PRESS_SLOP_PX, 10 - PRESS_SLOP_PX);+ up(10 + PRESS_SLOP_PX, 10 - PRESS_SLOP_PX);+ expect(calls).toEqual([]);+ expect(press.phase()).toBe("idle");+ expect(press.consumeClick()).toBe(false);+ },+ );++ it.each(["mouse", "pen"])(+ "%s: moving past the slop lifts the card at once, with no timer, and it follows to the drop",+ (pointerType) => {+ const { press, calls, down, move, up } = setup(pointerType);+ down(10, 20);+ expect(vi.getTimerCount()).toBe(0);+ move(10 + PRESS_SLOP_PX + 1, 20);+ expect(press.phase()).toBe("lifted");+ expect(calls).toEqual(["lift 10,20", `drag ${10 + PRESS_SLOP_PX + 1},20`]);+ move(200, 40);+ up(210, 44);+ expect(calls.slice(2)).toEqual(["drag 200,40", "drop 210,44"]);+ expect(press.phase()).toBe("idle");+ },+ );++ it("swallows the click a drag produces, once, even when released where it started", () => {+ const { press, calls, down, move, up } = setup();+ down(10, 10);+ move(40, 10);+ move(10, 10);+ up(10, 10);+ expect(calls).toEqual(["lift 10,10", "drag 40,10", "drag 10,10", "drop 10,10"]);+ expect(press.consumeClick()).toBe(true);+ expect(press.consumeClick()).toBe(false);+ });++ it("puts a dragged card back on Escape: no drop, and its click is swallowed", () => {+ const { press, calls, down, move, up } = setup();+ down();+ move(80, 10);+ press.cancel();+ expect(press.phase()).toBe("idle");+ move(120, 10);+ up(120, 10);+ expect(calls).toEqual(["lift 10,10", "drag 80,10", "cancel"]);+ expect(press.consumeClick()).toBe(true);+ });++ it("ends a press cancelled before it moved without lifting or swallowing anything", () => {+ const { press, calls, down, move, up } = setup();+ down();+ press.cancel();+ move(100, 10);+ up(100, 10);+ expect(calls).toEqual([]);+ expect(press.phase()).toBe("idle");+ expect(press.consumeClick()).toBe(false);+ });+});++describe("ticket card press: touch", () => {+ it("opens on a tap: released before the hold completes, nothing lifts", () => {+ const { press, calls, down, up } = setup("touch");+ down();+ vi.advanceTimersByTime(LONG_PRESS_MS - 1);+ up(10, 10);+ vi.advanceTimersByTime(LONG_PRESS_MS);+ expect(calls).toEqual([]);+ expect(press.phase()).toBe("idle");+ expect(press.consumeClick()).toBe(false);+ });++ it("lifts only after the hold, through a wobble inside the slop, then drags and drops", () => {+ const { press, calls, down, move, up } = setup("touch");+ down(10, 20);+ move(10 + PRESS_SLOP_PX, 20 - PRESS_SLOP_PX);+ vi.advanceTimersByTime(LONG_PRESS_MS - 1);+ expect(calls).toEqual([]);+ expect(press.phase()).toBe("pressing");+ vi.advanceTimersByTime(1);+ expect(press.phase()).toBe("lifted");+ move(200, 40);+ up(210, 44);+ expect(calls).toEqual(["lift 10,20", "drag 200,40", "drop 210,44"]);+ expect(press.consumeClick()).toBe(true);+ });++ it("swallows the click of a hold released in place", () => {+ const { press, calls, down, up } = setup("touch");+ down(50, 50);+ vi.advanceTimersByTime(LONG_PRESS_MS);+ up(50, 50);+ expect(calls).toEqual(["lift 50,50", "drop 50,50"]);+ expect(press.consumeClick()).toBe(true);+ });++ it("gives the press up when the finger moves past the slop first: it scrolls, nothing lifts", () => {+ const { press, calls, down, move, up } = setup("touch");+ down(10, 10);+ vi.advanceTimersByTime(100);+ move(10, 10 + PRESS_SLOP_PX + 1);+ expect(press.phase()).toBe("idle");+ vi.advanceTimersByTime(LONG_PRESS_MS);+ move(10, 200);+ up(10, 200);+ expect(calls).toEqual([]);+ expect(press.consumeClick()).toBe(false);+ });++ it("ends a press the browser took over for a scroll: the hold never completes", () => {+ const { press, calls, down } = setup("touch");+ down();+ vi.advanceTimersByTime(100);+ press.cancel();+ vi.advanceTimersByTime(LONG_PRESS_MS);+ expect(calls).toEqual([]);+ expect(press.phase()).toBe("idle");+ expect(press.consumeClick()).toBe(false);+ });+});++describe("ticket card press: any pointer", () => {+ it("ignores a secondary button, a non-primary pointer and another pointer's events", () => {+ const { press, calls, down, move, up } = setup();+ down(10, 10, { button: 2 });+ down(10, 10, { isPrimary: false });+ expect(press.phase()).toBe("idle");+ down(10, 10);+ move(400, 400, 2);+ up(400, 400, 2);+ expect(press.phase()).toBe("pressing");+ expect(calls).toEqual([]);+ move(400, 400);+ expect(calls).toEqual(["lift 10,10", "drag 400,400"]);+ });++ it("puts back a lifted card whose release was lost when the next press starts", () => {+ const { press, calls, down, move } = setup();+ down();+ move(100, 10);+ down(50, 50);+ expect(calls).toEqual(["lift 10,10", "drag 100,10", "cancel"]);+ expect(press.phase()).toBe("pressing");+ });++ it("forgets the click guard after its window, and on the next press", () => {+ const { press, down, move, up } = setup();+ down();+ move(100, 10);+ up(100, 10);+ vi.advanceTimersByTime(CLICK_GUARD_MS);+ // A screen reader's activation long after the drag still opens the card.+ expect(press.consumeClick()).toBe(false);++ down();+ move(100, 10);+ up(100, 10);+ down();+ up(10, 10);+ expect(press.consumeClick()).toBe(false);+ });++ it("stops everything on dispose", () => {+ const { press, calls, down } = setup("touch");+ down();+ press.dispose();+ vi.advanceTimersByTime(LONG_PRESS_MS);+ expect(calls).toEqual([]);+ expect(press.phase()).toBe("idle");+ expect(vi.getTimerCount()).toBe(0);+ });+});++describe("edge scroll step", () => {+ it("scrolls toward the edge the pointer is held near, faster the deeper it goes", () => {+ expect(edgeScrollStep(500, 0, 1000)).toBe(0);+ expect(edgeScrollStep(40, 0, 1000)).toBeLessThan(0);+ expect(edgeScrollStep(0, 0, 1000)).toBeLessThan(edgeScrollStep(40, 0, 1000));+ expect(edgeScrollStep(960, 0, 1000)).toBeGreaterThan(0);+ expect(edgeScrollStep(1000, 0, 1000)).toBeGreaterThan(edgeScrollStep(960, 0, 1000));+ });++ it("caps the step once the pointer leaves the container", () => {+ expect(edgeScrollStep(-500, 0, 1000)).toBe(edgeScrollStep(0, 0, 1000));+ expect(edgeScrollStep(5000, 0, 1000)).toBe(edgeScrollStep(1000, 0, 1000));+ });++ it("does not scroll a container too small to have a middle", () => {+ expect(edgeScrollStep(10, 0, 90)).toBe(0);+ });+});