feat: session-first workspace activity and installable daemon

Workspaces page:
- list the newest sessions across workspaces in the activity column; the
  daemon exposes GET /api/v1/sessions/recent as a disk projection and the
  browser enriches live rows from the per-workspace session relay
- put recent activity first below 1100px and fix the mobile page-header
  flex-basis gap

Smoke:
- pin PI2_HOST=127.0.0.1 in both smoke scripts and make the startup-line
  assertion follow the configured host; the daemon default stays 0.0.0.0

Install:
- standalone binary build/install scripts, packaging templates, CI/release
  hooks, CLI-first install docs and the supporting config/doctor changes
This commit is contained in:
yuez committed 2026-10-28 10:53:48 +08:00
1 parent fc51c3be37
commit d2e20d428a
50 files changed
+5104 -188

No files matched your search

+1 -1
View File
@@ -5,7 +5,7 @@
"type": "module",
"description": "pi2 web console — React port of the pi2 web UI prototype",
"engines": {
"node": ">=22"
"node": ">=20"
},
"scripts": {
"dev": "vite",
+50 -42
View File
@@ -5,14 +5,11 @@ import { Icon } from "@/components/icons";
import { RelativeTime } from "@/components/shared/relative-time";
import { Empty } from "@/components/ui/empty";
import { StatusDot } from "@/components/ui/status-dot";
import { plural } from "@/lib/i18n";
import { sessionDot, sessionStatusKey } from "@/features/chat/session-state";
import { sessionTitle } from "@/features/chat/session-title";
import type { WorkspaceInfo } from "@/lib/protocol";
import { workspaceName, workspaceSessionCount } from "./commands";
import { instanceState } from "./workspace-card";
/** The design lists the newest 5 entries. */
export const ACTIVITY_LIMIT = 5;
import { useRecentSessions, type RecentSessionRow } from "./recent-sessions";
export interface ActivityColumnProps {
workspaces: readonly WorkspaceInfo[];
@@ -20,53 +17,32 @@ export interface ActivityColumnProps {
/**
* "Recent activity" column (pi2-web-ui-design v0.1.1 §5.1): the newest
* `ACTIVITY_LIMIT` entries by `lastActiveAt`, dot + name + meta + relative
* time, each row linking into the chat UI.
* `RECENT_SESSION_LIMIT` sessions across every visible workspace, dot + title +
* owning-workspace + relative time, each row linking into the chat UI.
*
* The prototype derives it from `MOCK.sessions`; the daemon exposes no
* cross-workspace session feed (only `/workspaces/<id>/sessions`), so the rows
* are workspace-level and the meta slot carries the session count instead of
* the owning workspace name.
* Two read-only sources feed it (`features/workspaces/recent-sessions.ts`): the
* daemon's disk feed (survives restarts, never spawns an instance) and the
* per-workspace session list for live instances (adds names and live status).
*/
export function ActivityColumn({ workspaces }: ActivityColumnProps) {
const { t } = useTranslation();
const recent = [...workspaces]
.filter((workspace) => typeof workspace.lastActiveAt === "number" && Number.isFinite(workspace.lastActiveAt))
.sort((a, b) => (b.lastActiveAt ?? 0) - (a.lastActiveAt ?? 0))
.slice(0, ACTIVITY_LIMIT);
const sessions = useRecentSessions(workspaces, workspaces.length > 0);
const phrases = {
unnamed: t("chat.sessionUnnamed"),
subagentUnnamed: t("chat.subagentUnnamed"),
};
return (
<aside className="ws-activity" aria-label={t("workspaces.activity")} data-testid="workspaces-activity">
<div className="ws-activity__head">
<span className="section-label ws-activity__label">{t("workspaces.activity")}</span>
{recent.length > 0 ? <span className="ws-activity__count tabular">{recent.length}</span> : null}
{sessions.length > 0 ? <span className="ws-activity__count tabular">{sessions.length}</span> : null}
</div>
{recent.length > 0 ? (
{sessions.length > 0 ? (
<div className="ws-activity__list">
{recent.map((workspace) => {
const state = instanceState(workspace);
return (
<Link
key={workspace.workspaceId}
to="/chat"
search={{ workspace: workspace.workspaceId }}
className="ws-activity__row"
data-workspace-id={workspace.workspaceId}
data-testid="workspace-activity-row"
>
<StatusDot status={state.status} title={t(state.labelKey)} />
<span className="ws-activity__main">
<span className="ws-activity__name">
{workspaceName(workspace, t("workspaces.unnamed"))}
</span>
<span className="ws-activity__ws">
{plural("workspaces.sessionCount", workspaceSessionCount(workspace))}
</span>
</span>
<RelativeTime ts={workspace.lastActiveAt} className="ws-activity__rel" />
</Link>
);
})}
{sessions.map((session) => (
<ActivityRow key={session.sessionId} session={session} phrases={phrases} />
))}
</div>
) : (
<Empty icon={<Icon name="clock" size={22} />} title={t("workspaces.activityEmpty")} />
@@ -74,3 +50,35 @@ export function ActivityColumn({ workspaces }: ActivityColumnProps) {
</aside>
);
}
type Phrases = { unnamed: string; subagentUnnamed: string };
function ActivityRow({ session, phrases }: { session: RecentSessionRow; phrases: Phrases }) {
const { t } = useTranslation();
// A disk-only row has no live state; the session title contract then falls
// back to `(unnamed)` (never an id), and the dot is the hollow "exited".
const title = session.state
? sessionTitle(session.state, phrases)
: { text: phrases.unnamed, provisional: true, spinner: false };
const dot = session.state ? sessionDot(session.state) : { status: "exited" as const };
const label = session.state ? t(`state.${sessionStatusKey(session.state)}`) : t("state.exited");
return (
<Link
to="/chat/$sessionId"
params={{ sessionId: session.sessionId }}
search={{ workspace: session.workspaceId }}
className="ws-activity__row"
data-session-id={session.sessionId}
data-workspace-id={session.workspaceId}
data-testid="workspace-activity-row"
>
<StatusDot status={dot.status} blink={dot.blink} title={label} />
<span className="ws-activity__main">
<span className="ws-activity__name">{title.text}</span>
<span className="ws-activity__ws">{session.workspaceName}</span>
</span>
<RelativeTime ts={session.ts || null} className="ws-activity__rel" />
</Link>
);
}
@@ -0,0 +1,160 @@
import { useQuery } from "@tanstack/react-query";
import { useMemo } from "react";
import { apiRequest } from "@/lib/api";
import type { RecentSessionInfo, SessionState, WorkspaceInfo } from "@/lib/protocol";
import { normalizeSessionSummary } from "@/features/chat/session-state";
import { useWorkspaceSessionsQueries } from "@/features/status/queries";
/** The design lists the newest five sessions across every workspace. */
export const ACTIVITY_LIMIT = 5;
/** Enough headroom for the client-side merge with live session rows. */
const FEED_LIMIT = 20;
export interface RecentSessionRow {
sessionId: string;
workspaceId: string;
workspaceName: string;
/** Recency: live `lastActiveAt`/`createdAt`, else the file's mtime/start. */
ts: number;
/** Full state when a live instance answered for the workspace; null for disk-only rows. */
state: SessionState | null;
}
function rec(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined;
}
function str(value: unknown): string | undefined {
return typeof value === "string" && value !== "" ? value : undefined;
}
function num(value: unknown): number | undefined {
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
}
/**
* `GET /api/v1/sessions/recent` → `{sessions: RecentSessionInfo[]}`.
* Tolerates a bare array and drops malformed rows instead of failing the column.
*/
export function normalizeRecentSessions(payload: unknown): RecentSessionInfo[] {
const record = rec(payload);
const list = Array.isArray(payload) ? payload : Array.isArray(record?.sessions) ? record.sessions : [];
const rows: RecentSessionInfo[] = [];
for (const entry of list) {
const row = rec(entry);
const sessionId = str(row?.sessionId);
const workspaceId = str(row?.workspaceId);
if (!row || !sessionId || !workspaceId) continue;
rows.push({
sessionId,
workspaceId,
workspaceName: str(row.workspaceName) ?? workspaceId,
cwd: str(row.cwd) ?? "",
sessionFile: str(row.sessionFile) ?? "",
timestamp: num(row.timestamp) ?? 0,
modified: num(row.modified) ?? 0,
});
}
return rows;
}
/**
* Merge the daemon's disk feed with session states from live instances.
*
* Disk rows are the base (they exist after a daemon restart, before any
* workspace is spawned). A live row with the same id replaces the metadata:
* it carries the authoritative name/first message/status. Sub-sessions are
* dropped — the design's activity column is a list of workspace roots.
*/
export function mergeRecentSessions(
disk: readonly RecentSessionInfo[],
live: readonly SessionState[],
workspaces: readonly WorkspaceInfo[],
limit = ACTIVITY_LIMIT,
): RecentSessionRow[] {
const allowed = new Set(workspaces.map((workspace) => workspace.workspaceId));
const nameById = new Map(workspaces.map((workspace) => [workspace.workspaceId, workspace.name]));
const byId = new Map<string, { disk?: RecentSessionInfo; live?: SessionState }>();
for (const row of disk) {
if (!allowed.has(row.workspaceId)) continue;
byId.set(row.sessionId, { disk: row });
}
for (const state of live) {
if (!state.sessionId || !allowed.has(state.workspaceId)) continue;
const entry = byId.get(state.sessionId) ?? {};
entry.live = state;
byId.set(state.sessionId, entry);
}
const rows: RecentSessionRow[] = [];
for (const [sessionId, entry] of byId) {
if (entry.live?.parentId) continue;
const workspaceId = entry.live?.workspaceId ?? entry.disk?.workspaceId ?? "";
const ts = Math.max(
entry.live?.lastActiveAt ?? 0,
entry.live?.createdAt ?? 0,
entry.disk?.modified ?? 0,
entry.disk?.timestamp ?? 0,
);
rows.push({
sessionId,
workspaceId,
workspaceName: nameById.get(workspaceId) ?? entry.disk?.workspaceName ?? "",
ts,
state: entry.live ?? null,
});
}
rows.sort((a, b) => b.ts - a.ts || a.sessionId.localeCompare(b.sessionId));
return rows.slice(0, limit);
}
/**
* Recent activity for the workspaces page.
*
* Two sources, both read-only:
* - the daemon's disk feed (no instance spawn, survives a restart), and
* - `/workspaces/:id/sessions` for workspaces with a live instance, which adds
* names/first messages/status without spawning anything (the status page
* uses the same query keys).
*/
export function useRecentSessions(workspaces: readonly WorkspaceInfo[], enabled = true): RecentSessionRow[] {
const liveIds = useMemo(
() => workspaces.filter((workspace) => workspace.instance != null).map((workspace) => workspace.workspaceId),
[workspaces],
);
const feed = useQuery({
queryKey: ["recent-sessions"],
queryFn: async ({ signal }) =>
normalizeRecentSessions(
await apiRequest<unknown>(`/api/v1/sessions/recent?limit=${FEED_LIMIT}`, { signal }),
),
enabled,
staleTime: 10_000,
refetchInterval: 15_000,
retry: false,
});
const sessionQueries = useWorkspaceSessionsQueries(liveIds, enabled);
// `useWorkspaceSessionsQueries` returns the daemon's list rows as-is (the
// status page only reads `tasks`); the activity column needs the reducer's
// defaults for flags/attention, so normalize before rendering a dot.
const live = useMemo(
() =>
sessionQueries.flatMap((query, index) => {
const workspaceId = liveIds[index] ?? "";
return (Array.isArray(query.data) ? query.data : []).map((row) =>
normalizeSessionSummary(row, workspaceId),
);
}),
[sessionQueries, liveIds],
);
return useMemo(
() => mergeRecentSessions(feed.data ?? [], live, workspaces),
[feed.data, live, workspaces],
);
}
+3
View File
@@ -708,6 +708,9 @@ html[data-pi-blink-slow="dim"] .dot--blink-slow { opacity: .35; }
.page-head--lg .page-head__sub { margin-top: 2px; }
@media (max-width: 599px) {
.page-head { align-items: center; }
/* Column direction turns `flex-basis: 14rem` into a 224px-tall header block,
which reads as a blank band under the title. Fall back to content height. */
.page-head__text { flex: 0 1 auto; }
.page-head__actions { margin-left: 0; }
}
+3 -3
View File
@@ -78,10 +78,10 @@
.ws-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.ws-activity { position: sticky; top: calc(var(--topbar-h) + var(--space-4)); }
}
/* <1100:单列,活动列排到网格下方 */
/* <1100:单列,最近活动放在最上面(手机端先看最近会话) */
@media (max-width: 1099px) {
.ws-main { order: 1; }
.ws-activity { order: 2; }
.ws-main { order: 2; }
.ws-activity { order: 1; }
}
/* ---------- workspace card(整卡 = 一个链接,无行级 primary 按钮) ---------- */
+97 -9
View File
@@ -34,10 +34,32 @@ function routes() {
return [
{ path: "/workspaces", component: WorkspacesPage },
{ path: "/chat", component: () => <div>Chat destination</div> },
{ path: "/chat/$sessionId", component: () => <div>Chat session destination</div> },
{ path: "/status", component: () => <div>Status destination</div> },
];
}
/** The activity column's disk feed; most tests only need it to resolve empty. */
function recentRoute(rows: unknown[] = []) {
return { path: "/api/v1/sessions/recent", handler: () => ({ body: { sessions: rows } }) };
}
/** One workspace's `/sessions` relay (only called for live instances). */
function sessionsRoute(workspaceId: string, rows: unknown[] = []) {
return { path: `/api/v1/workspaces/${workspaceId}/sessions`, handler: () => ({ body: { sessions: rows } }) };
}
function diskSession(overrides: Record<string, unknown> & { sessionId: string; workspaceId: string }) {
return {
workspaceName: overrides.workspaceId,
cwd: `/work/${overrides.workspaceId}`,
sessionFile: `/sessions/${overrides.workspaceId}/${overrides.sessionId}.jsonl`,
timestamp: 1_000,
modified: 1_000,
...overrides,
};
}
/** Card names are also repeated in the activity column, so wait on the cards. */
async function waitForCards(count: number) {
await waitFor(() => expect(screen.getAllByTestId("workspace-row")).toHaveLength(count));
@@ -61,6 +83,7 @@ describe("WorkspacesPage", () => {
mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
recentRoute(),
]);
const { container } = await renderPage(routes(), "/workspaces", { paired: true });
@@ -108,6 +131,8 @@ describe("WorkspacesPage", () => {
],
}),
},
recentRoute(),
sessionsRoute("ws-a"),
]);
const { container } = await renderPage(routes(), "/workspaces", { paired: true });
@@ -145,6 +170,7 @@ describe("WorkspacesPage", () => {
],
}),
},
recentRoute(),
]);
const { container } = await renderPage(routes(), "/workspaces", { paired: true });
@@ -164,30 +190,91 @@ describe("WorkspacesPage", () => {
expect(container.querySelector(".ws-context")).toBeNull();
});
it("lists the newest workspaces in a recent-activity column", async () => {
const items = [1, 2, 3, 4, 5, 6].map((n) =>
workspace({ workspaceId: `ws-${n}`, cwd: `/work/${n}`, name: `Project ${n}`, lastActiveAt: n * 1_000 }),
);
it("lists the newest sessions across workspaces in a recent-activity column", async () => {
const items = [
workspace({ workspaceId: "ws-a", cwd: "/work/a", name: "Alpha", lastActiveAt: 1_000 }),
workspace({ workspaceId: "ws-b", cwd: "/work/b", name: "Bravo", lastActiveAt: 2_000 }),
];
const rows = [
diskSession({ sessionId: "s-6", workspaceId: "ws-b", workspaceName: "Bravo", modified: 6_000 }),
diskSession({ sessionId: "s-1", workspaceId: "ws-a", workspaceName: "Alpha", modified: 1_000 }),
diskSession({ sessionId: "s-4", workspaceId: "ws-a", workspaceName: "Alpha", modified: 4_000 }),
diskSession({ sessionId: "s-2", workspaceId: "ws-b", workspaceName: "Bravo", modified: 2_000 }),
diskSession({ sessionId: "s-5", workspaceId: "ws-a", workspaceName: "Alpha", modified: 5_000 }),
diskSession({ sessionId: "s-3", workspaceId: "ws-a", workspaceName: "Alpha", modified: 3_000 }),
];
mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
recentRoute(rows),
]);
await renderPage(routes(), "/workspaces", { paired: true });
await waitForCards(6);
await waitForCards(2);
const activity = screen.getByTestId("workspaces-activity");
expect(activity.tagName).toBe("ASIDE");
const rows = within(activity).getAllByTestId("workspace-activity-row");
// Newest first, capped at 5 (v0.1.1 §5.1).
expect(rows.map((row) => row.getAttribute("data-workspace-id"))).toEqual(["ws-6", "ws-5", "ws-4", "ws-3", "ws-2"]);
expect(rows[0]).toHaveAttribute("href", "/chat?workspace=ws-6");
const links = await within(activity).findAllByTestId("workspace-activity-row");
// Newest session first, capped at 5 (v0.1.1 §5.1), regardless of the
// workspace order in the grid.
expect(links.map((row) => row.getAttribute("data-session-id"))).toEqual(["s-6", "s-5", "s-4", "s-3", "s-2"]);
expect(links[0]).toHaveAttribute("href", "/chat/s-6?workspace=ws-b");
expect(links[0]).toHaveTextContent("Bravo");
// Head carries the section label + the entry count (a11y name is the i18n label).
expect(activity).toHaveAttribute("aria-label");
expect(activity.querySelector(".ws-activity__count")).toHaveTextContent("5");
});
it("enriches a recent-activity row with the live session's title and status", async () => {
const items = [
workspace({
workspaceId: "ws-a",
cwd: "/work/a",
name: "Alpha",
sessionCount: 1,
liveCount: 1,
lastActiveAt: 5_000,
instance: {
workspaceId: "ws-a",
instanceId: "inst-a",
status: "ready",
nvimPid: 42,
pluginVersion: "0.1.1",
hasUI: true,
attachedClients: 1,
listenAddr: "127.0.0.1:7777",
startedAt: 1_000,
},
}),
];
const liveRow = {
sessionId: "s-live",
workspaceId: "ws-a",
name: "Refactor the console",
status: "busy",
flags: { attention: false, done: false, error: false },
lastActiveAt: 9_000,
};
mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
recentRoute([diskSession({ sessionId: "s-live", workspaceId: "ws-a", modified: 4_000 })]),
sessionsRoute("ws-a", [liveRow]),
]);
await renderPage(routes(), "/workspaces", { paired: true });
await waitForCards(1);
const activity = screen.getByTestId("workspaces-activity");
expect(await within(activity).findByText("Refactor the console")).toBeInTheDocument();
const [row] = within(activity).getAllByTestId("workspace-activity-row");
expect(row).toHaveAttribute("data-session-id", "s-live");
expect(row).toHaveAttribute("href", "/chat/s-live?workspace=ws-a");
expect(row?.querySelector(".ws-activity__ws")).toHaveTextContent("Alpha");
expect(row?.querySelector(".dot")).toHaveClass("dot--busy");
});
it("opens the new-workspace dialog from the empty state", async () => {
const fetchMock = mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
@@ -259,6 +346,7 @@ describe("WorkspacesPage", () => {
const fetchMock = mockApi([
{ path: "/api/v1/info", handler: () => ({ body: infoBody }) },
{ path: "/api/v1/workspaces", handler: () => ({ body: items }) },
recentRoute(),
{
method: "POST",
path: "/api/v1/cmd",