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

+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 按钮) ---------- */