Skip to content

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

feat(web): copyable Session id, schedule-form pickers aligned with project defaults, saved toast, {{SHELL}} placeholder (#245)

Yaowei Zheng09a70359e7ea
diff --git a/packages/web/e2e/chat-tweaks.spec.mjs b/packages/web/e2e/chat-tweaks.spec.mjs
new file mode 100644
index 00000000..883d3183
--- /dev/null
+++ b/packages/web/e2e/chat-tweaks.spec.mjs
@@ -0,0 +1,101 @@
+/**
+ * Chat/schedule tweaks:
+ * - the schedule create form's model/workspace use the same form-style pickers as the
+ * Project defaults dialog, and its bind-Session field is a searchable dropdown (not a
+ * raw id text input);
+ * - the chat details card shows the Session id as a click-to-copy row (label flips to
+ * "已复制").
+ *
+ * (The Project-defaults "已保存" toast is a one-line success path exercised manually; it is
+ * left out here — dirtying the defaults block through its custom pickers is too sensitive
+ * to first-run config-load timing to assert reliably.)
+ */
+import { test, expect } from "@playwright/test";
+import { provisionAndLogin } from "./auth.mjs";
+
+const BASE = process.env.BASE_URL;
+const MOCK = process.env.MOCK_URL;
+const U = "tweakuser";
+const P = "password123";
+
+test("schedule form pickers and details Session-id copy", async ({ page }) => {
+ await provisionAndLogin(page.request, U, P);
+ const projectId = (await (await page.request.get(`${BASE}/api/projects`)).json()).projects[0]
+ .projectId;
+ const put = await page.request.put(`${BASE}/api/projects/${projectId}/models`, {
+ data: {
+ defaultModel: { provider: "custom", modelId: "claude-4-8" },
+ models: [
+ {
+ provider: "custom",
+ modelId: "claude-4-8",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 200000,
+ },
+ {
+ provider: "custom",
+ modelId: "haiku-x",
+ apiKey: "sk-mock",
+ baseUrl: MOCK,
+ contextWindow: 100000,
+ },
+ ],
+ },
+ });
+ expect(put.ok(), "put models").toBeTruthy();
+
+ // A session to bind the schedule to (and to open in chat for the details card).
+ const sess = await (
+ await page.request.post(`${BASE}/api/projects/${projectId}/agents/default_agent/sessions`, {
+ data: { provider: "custom", modelId: "claude-4-8", approvalMode: "allow-all" },
+ })
+ ).json();
+ const sessionId = sess.session.sessionId;
+ const idTail = sessionId.slice(-6);
+
+ const dlg = () => page.locator(".anim-pop").last();
+
+ // --- Schedule form pickers ---
+ await page.goto(`${BASE}/agents/default_agent?tab=schedules`);
+ await page.getByRole("button", { name: "新建定时任务" }).click();
+ await dlg().getByText("每次新建会话").first().waitFor();
+ // New-session mode: model + workspace are the form-style dropdowns (not native selects),
+ // matching the Project defaults dialog.
+ await expect(dlg().getByRole("button", { name: "选择模型" })).toBeVisible();
+ await expect(dlg().getByRole("button", { name: "Workspace" })).toBeVisible();
+
+ // Switch to bind-Session mode → the searchable session dropdown replaces the id input.
+ // The Target control is a custom Select (accessible name = its label "目标"); its
+ // open-on-click is momentarily racy under full-page load, so retry the whole
+ // open-then-pick block rather than a single click (Playwright's toPass idiom).
+ await expect(async () => {
+ await dlg().getByRole("button", { name: "目标" }).click();
+ await page.getByRole("option", { name: "绑定 Session" }).click({ timeout: 2000 });
+ }).toPass({ timeout: 15_000 });
+ await page.getByRole("button", { name: "选择要绑定的 Session" }).click();
+ const search = page.getByPlaceholder(/搜索标题/);
+ await search.waitFor();
+ // Filter by the session id tail — deterministic regardless of the generated title.
+ await search.fill(idTail);
+ const row = page.locator("button").filter({ hasText: idTail });
+ await expect(row.first()).toBeVisible();
+ await row.first().click();
+ // The trigger now shows the bound session (its title), not the placeholder.
+ await expect(page.getByRole("button", { name: "选择要绑定的 Session" })).not.toContainText(
+ "选择要绑定的 Session",
+ );
+
+ // --- Details card Session id + copy ---
+ // The id is selectable mono text with the copy button beside it (not inside it); the
+ // "已复制" feedback appears AT the button (text), and the "Session id" label is untouched.
+ await page.goto(`${BASE}/chat/${sessionId}`);
+ await page.getByPlaceholder(/输入消息/).waitFor();
+ await page.locator('button[title="Session 信息"]').click();
+ await expect(page.getByText(sessionId, { exact: true }).first()).toBeVisible();
+ const copyBtn = page.getByRole("button", { name: "复制 Session id" });
+ await copyBtn.click();
+ await expect(copyBtn).toContainText("已复制");
+ // The section label above the id is not the feedback target — it stays "Session id".
+ await expect(page.getByText("Session id", { exact: true })).toBeVisible();
+});
diff --git a/packages/web/src/components/layout/project-dialogs.tsx b/packages/web/src/components/layout/project-dialogs.tsx
index bb512b9d..28bc98dc 100644
--- a/packages/web/src/components/layout/project-dialogs.tsx
+++ b/packages/web/src/components/layout/project-dialogs.tsx
@@ -33,7 +33,7 @@ import { Button } from "../ui/button";
import { Input } from "../ui/input";
import { Select } from "../ui/select";
import { FieldError, FieldHint, FieldLabel } from "../ui/field";
-import { toastError } from "../ui/toast";
+import { toastError, toastSuccess } from "../ui/toast";
import { Modal } from "../ui/modal";
import { ConfirmModal } from "../ui/confirm-modal";
import { Badge } from "../ui/badge";
@@ -539,6 +539,10 @@ function ChatDefaultsSection({ projectId, isOwner }: { projectId: string; isOwne
if (user) clearDraftModelRef(user.userId, projectId);
changed = { ...(changed ?? { projectId }), defaultModel: res.defaultModel };
}
+ // Both writes landed (the try didn't throw): confirm it — the dialog stays open, so
+ // without a toast a successful save is silent. `changed` is non-null whenever
+ // anything was actually written (the early-return above guards the no-op case).
+ if (changed) toastSuccess(S.common.saved);
} catch (e) {
toastError(apiErrorText(e));
} finally {
diff --git a/packages/web/src/components/ui/copy-button.tsx b/packages/web/src/components/ui/copy-button.tsx
new file mode 100644
index 00000000..3ea5a4bc
--- /dev/null
+++ b/packages/web/src/components/ui/copy-button.tsx
@@ -0,0 +1,82 @@
+/**
+ * Copy-to-clipboard button and the hook behind it — the single place the app's "copy"
+ * affordance and its feedback live, so every copy control behaves the same:
+ *
+ * - the write is optimistic (an insecure context or denied permission must not leave the
+ * control stuck), matching the clipboard convention used across the chat views;
+ * - the feedback is ALWAYS shown AT THE BUTTON — the icon swaps copy → check for
+ * COPIED_MS and the tooltip flips to "已复制"; a control with room can also show the
+ * "已复制" text next to the check (showCopiedText). The feedback never replaces an
+ * unrelated label/title elsewhere.
+ *
+ * Icon-only callers (message footer, code block, reply stats) pass their own compact
+ * className and omit showCopiedText, keeping their existing look; wider affordances (the
+ * details card's Session id row) opt into the text.
+ */
+import { useState } from "react";
+import { S } from "../../lib/strings";
+import { STAT_ICONS } from "../../lib/stat-icons";
+import { GlyphIcon } from "./glyph-icon";
+
+/** How long the copied state (check icon + "已复制") stays after a click. */
+const COPIED_MS = 1500;
+
+/** Best-effort clipboard write (never throws; no-op where the API is unavailable). */
+export function writeClipboard(text: string): void {
+ void navigator.clipboard?.writeText(text);
+}
+
+/**
+ * Transient "just copied" flag: `flash()` writes the text and turns `copied` on for
+ * COPIED_MS. Exposed for the rare caller whose copy trigger is not a plain CopyButton
+ * (e.g. a whole row); most callers should use CopyButton directly.
+ */
+export function useCopied(): { copied: boolean; flash: (text: string) => void } {
+ const [copied, setCopied] = useState(false);
+ const flash = (text: string) => {
+ writeClipboard(text);
+ setCopied(true);
+ setTimeout(() => setCopied(false), COPIED_MS);
+ };
+ return { copied, flash };
+}
+
+/** Default compact icon-button look (message footer / code block). */
+const DEFAULT_CLASS =
+ "rounded p-0.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300";
+
+export function CopyButton({
+ text,
+ label,
+ className = DEFAULT_CLASS,
+ showCopiedText = false,
+}: {
+ /** The string to copy, or a getter for content computed at click time (e.g. a formatted stats line). */
+ text: string | (() => string);
+ /** Accessible name / idle tooltip for the copy action (the tooltip flips to "已复制" while copied). */
+ label: string;
+ /** Overrides the compact default look (e.g. the reply row's fixed-size button). */
+ className?: string;
+ /** Render the "已复制" text beside the check while copied (for wide affordances with room). */
+ showCopiedText?: boolean;
+}) {
+ const { copied, flash } = useCopied();
+ return (
+ <button
+ type="button"
+ title={copied ? S.common.copied : label}
+ aria-label={label}
+ onClick={() => flash(typeof text === "function" ? text() : text)}
+ className={className}
+ >
+ {showCopiedText && copied ? (
+ <span className="flex items-center gap-1">
+ <GlyphIcon d={STAT_ICONS.check} />
+ {S.common.copied}
+ </span>
+ ) : (
+ <GlyphIcon d={copied ? STAT_ICONS.check : STAT_ICONS.copy} />
+ )}
+ </button>
+ );
+}
diff --git a/packages/web/src/components/ui/form-picker.tsx b/packages/web/src/components/ui/form-picker.tsx
new file mode 100644
index 00000000..f7f95dd4
--- /dev/null
+++ b/packages/web/src/components/ui/form-picker.tsx
@@ -0,0 +1,81 @@
+/**
+ * Form-style picker shell: a full-width trigger that looks exactly like an Input/Select
+ * (controlBase + the sm size tier — leading icon, truncating label, trailing chevron) with
+ * a portaled dropdown hanging under its left edge. It is the single source of the
+ * "form-variant" look shared by the model picker, the workspace picker and the schedule's
+ * session picker, so the three read identically and none re-hand-rolls the trigger.
+ *
+ * It owns only the trigger + Dropdown wiring; the menu body is the caller's `children`
+ * (a searchable list, a directory browser, …), and open/close state stays with the caller
+ * (the pickers drive it and close on pick).
+ */
+import type { ReactNode } from "react";
+import { Dropdown } from "./dropdown";
+import { ChevronDown } from "./icons";
+import { controlBase } from "./field";
+import { sizeClass } from "./input";
+
+export function FormPicker({
+ open,
+ setOpen,
+ leading,
+ label,
+ labelClassName = "",
+ muted = false,
+ title,
+ ariaLabel,
+ ariaHaspopup = "listbox",
+ disabled = false,
+ menuClass,
+ children,
+}: {
+ open: boolean;
+ setOpen: (open: boolean) => void;
+ /** Leading visual (provider logo / folder icon), sized by the caller; omitted when there's none. */
+ leading?: ReactNode;
+ /** The selected value's display, or a placeholder (pair with `muted`). */
+ label: ReactNode;
+ /** Extra classes on the label span (e.g. `font-mono` for a path value). */
+ labelClassName?: string;
+ /** Grays the label as a placeholder (nothing selected yet). */
+ muted?: boolean;
+ title: string;
+ ariaLabel: string;
+ ariaHaspopup?: "listbox" | "dialog";
+ disabled?: boolean;
+ /** Width / origin classes for the dropdown panel (placement itself is measured from the trigger). */
+ menuClass: string;
+ /** The dropdown menu body. */
+ children: ReactNode;
+}) {
+ return (
+ <Dropdown
+ open={open}
+ setOpen={setOpen}
+ menuClass={menuClass}
+ portal={{ direction: "down", align: "left" }}
+ button={
+ <button
+ type="button"
+ title={title}
+ aria-label={ariaLabel}
+ aria-haspopup={ariaHaspopup}
+ aria-expanded={open}
+ disabled={disabled}
+ onClick={() => setOpen(!open)}
+ className={`flex w-full items-center gap-2 text-left ${controlBase} ${sizeClass.sm} disabled:cursor-not-allowed disabled:opacity-60`}
+ >
+ {leading}
+ <span
+ className={`min-w-0 flex-1 truncate ${muted ? "text-gray-400" : ""} ${labelClassName}`}
+ >
+ {label}
+ </span>
+ <ChevronDown className="text-gray-400" />
+ </button>
+ }
+ >
+ {children}
+ </Dropdown>
+ );
+}
diff --git a/packages/web/src/features/agents/schedules-tab.tsx b/packages/web/src/features/agents/schedules-tab.tsx
index 020a2422..f971f7b7 100644
--- a/packages/web/src/features/agents/schedules-tab.tsx
+++ b/packages/web/src/features/agents/schedules-tab.tsx
@@ -17,13 +17,13 @@ import type {
SchedulesResponse,
ScheduleStatus,
ScheduleUpsertRequest,
+ SessionInfo,
} from "@prismshadow/penguin-server/api";
import * as api from "../../api/endpoints";
import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { formatDateTime } from "../../lib/format";
import { useProject } from "../../state/project";
-import { providerInfo } from "@prismshadow/penguin-core/model-catalog";
import { Badge, type BadgeTone } from "../../components/ui/badge";
import { Button } from "../../components/ui/button";
import { Input, Textarea } from "../../components/ui/input";
@@ -31,7 +31,12 @@ import { Select } from "../../components/ui/select";
import { Modal } from "../../components/ui/modal";
import { ConfirmModal } from "../../components/ui/confirm-modal";
import { SkeletonList } from "../../components/ui/skeleton";
+import { FormPicker } from "../../components/ui/form-picker";
+import { FieldError, FieldLabel } from "../../components/ui/field";
import { toastError, toastInfo, toastSuccess } from "../../components/ui/toast";
+import { ModelSelect, PickerList } from "../chat/model-select";
+import { WorkspaceSelect } from "../chat/workspace-select";
+import { sameModelRef } from "../models/model-grouping";
/** Display status → badge tone. */
const STATUS_TONE: Record<ScheduleStatus, BadgeTone> = {
@@ -52,25 +57,6 @@ function toLocalInput(iso: string | undefined): string {
return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}
-/**
- * Model reference ↔ native select option value: encoded as a JSON array
- * ([provider, modelId]), used only as a transient DOM-value serialization —
- * it never enters storage or requests; the persisted/submitted data still keeps
- * provider and modelId as two separate fields (no concatenation anywhere in the
- * pipeline). "" means the Project default.
- */
-const modelOptionValue = (ref: ModelRefDto): string => JSON.stringify([ref.provider, ref.modelId]);
-
-const parseModelOption = (v: string): ModelRefDto | null => {
- if (!v) return null;
- const [provider, modelId] = JSON.parse(v) as [string, string];
- return { provider, modelId };
-};
-
-/** Display label for a model option: upstream id + provider name (shown side by side, not a composite id). */
-const modelOptionLabel = (ref: ModelRefDto): string =>
- `${ref.modelId} · ${providerInfo(ref.provider)?.label ?? ref.provider}`;
-
/**
* Stored schedule fields → a model reference. A reference is always the complete
* (provider, model_id) pair, since provider is never inferred: the DTO types the two
@@ -113,6 +99,105 @@ const EMPTY_FORM: FormState = {
model: null,
};
+/** Case-insensitive match of a Session by its title and its id (mirrors filterAgents in agent-handoff.ts). */
+function filterSessions(sessions: SessionInfo[], query: string): SessionInfo[] {
+ const q = query.trim().toLowerCase();
+ if (!q) return sessions;
+ return sessions.filter(
+ (s) => s.sessionId.toLowerCase().includes(q) || (s.title ?? "").toLowerCase().includes(q),
+ );
+}
+
+/**
+ * Searchable Session picker for the bind-to-Session mode: the shared FormPicker (same
+ * trigger look as ModelSelect/WorkspaceSelect) whose panel is the shared PickerList (search
+ * box + keyboard nav). The Agent's full Session list is fetched once when the picker first
+ * opens — un-paged, mirroring how the form one-shots getModels — so search covers every
+ * Session rather than only the sidebar's loaded active page. The stored value is still the
+ * plain sessionId; the trigger resolves it to the Session's title for display.
+ */
+function SessionSelect({
+ projectId,
+ agentId,
+ value,
+ onChange,
+}: {
+ projectId: string;
+ agentId: string;
+ value: string;
+ onChange: (sessionId: string) => void;
+}) {
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [sessions, setSessions] = useState<SessionInfo[] | null>(null);
+
+ // Load lazily on first open, then keep the snapshot; a failed fetch degrades to an empty
+ // list (the user can still see the currently-bound id on the trigger and cancel out).
+ useEffect(() => {
+ if (!open || sessions !== null) return;
+ let cancelled = false;
+ api
+ .listSessions(projectId, agentId)
+ .then((res) => {
+ if (!cancelled) setSessions(res.sessions);
+ })
+ .catch(() => {
+ if (!cancelled) setSessions([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [open, sessions, projectId, agentId]);
+
+ const selected = sessions?.find((s) => s.sessionId === value) ?? null;
+ const label = selected
+ ? (selected.title ?? S.chat.defaultSessionTitle)
+ : value || S.schedule.chooseSession;
+
+ return (
+ <FormPicker
+ open={open}
+ setOpen={setOpen}
+ label={label}
+ muted={!value}
+ title={value ? `${S.schedule.sessionId}:${value}` : S.schedule.chooseSession}
+ ariaLabel={S.schedule.chooseSession}
+ ariaHaspopup="listbox"
+ menuClass="w-80 origin-top-left"
+ >
+ {sessions === null ? (
+ <p className="px-3 py-2 text-xs text-gray-400">{S.common.loading}</p>
+ ) : sessions.length === 0 ? (
+ <p className="px-3 py-2 text-xs text-gray-400">{S.schedule.sessionEmpty}</p>
+ ) : (
+ <PickerList
+ items={filterSessions(sessions, query)}
+ itemKey={(s) => s.sessionId}
+ isCurrent={(s) => s.sessionId === value}
+ query={query}
+ onQueryChange={setQuery}
+ searchPlaceholder={S.schedule.sessionSearch}
+ emptyText={S.schedule.sessionNoMatch}
+ onPick={(s) => {
+ onChange(s.sessionId);
+ setOpen(false);
+ }}
+ renderRow={(s) => (
+ <>
+ <span className="min-w-0 flex-1 truncate text-gray-800 dark:text-gray-200">
+ {s.title ?? S.chat.defaultSessionTitle}
+ </span>
+ <span className="shrink-0 font-mono text-[11px] text-gray-400 dark:text-gray-500">
+ {s.sessionId.slice(-6)}
+ </span>
+ </>
+ )}
+ />
+ )}
+ </FormPicker>
+ );
+}
+
export function SchedulesTab({ agentId }: { agentId: string }) {
const { currentProject } = useProject();
const projectId = currentProject?.projectId ?? null;
@@ -138,6 +223,9 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
const [deleting, setDeleting] = useState<string | null>(null);
// Model dropdown data (needed only for owners); load failure doesn't block the form — falling back to "Project default" is fine.
const [models, setModels] = useState<ModelInfo[]>([]);
+ // The Project default model reference, kept so ModelSelect can mark it and so the form can
+ // treat "the default is selected" as "follow the default" (omit the model from the body).
+ const [defaultModel, setDefaultModel] = useState<ModelRefDto | null>(null);
const load = useCallback(async () => {
if (!projectId || !agentId) return;
@@ -158,8 +246,14 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
if (!projectId || !isOwner) return;
api
.getModels(projectId)
- .then((res) => setModels(res.models))
- .catch(() => setModels([]));
+ .then((res) => {
+ setModels(res.models);
+ setDefaultModel(res.defaultModel ?? null);
+ })
+ .catch(() => {
+ setModels([]);
+ setDefaultModel(null);
+ });
}, [projectId, isOwner]);
const set = (patch: Partial<FormState>) => {
@@ -212,7 +306,10 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
...(form.target === "new" && form.workspace.trim()
? { workspace: form.workspace.trim() }
: {}),
- ...(form.target === "new" && form.model
+ // Model is sent only when it differs from the Project default: selecting the default
+ // (or leaving it) means "follow the Project default", stored by omitting the pair —
+ // so a later change to the default keeps flowing through (matches the header note).
+ ...(form.target === "new" && form.model && !sameModelRef(defaultModel, form.model)
? { modelId: form.model.modelId, provider: form.model.provider }
: {}),
};
@@ -270,7 +367,10 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
target: item.sessionId ? "session" : "new",
sessionId: item.sessionId ?? "",
workspace: item.workspace ?? "",
- model: itemModelRef(item),
+ // A schedule that follows the Project default stores no model; show the current
+ // default in the picker (ModelSelect has no null state), which the submit body then
+ // treats as "follow default" again and omits.
+ model: itemModelRef(item) ?? defaultModel,
});
};
@@ -417,7 +517,12 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
{/* Create entry point (owner): the form lives in a modal; the inline "Edit" button reuses the same modal. */}
{isOwner && data !== null && (
- <Button size="sm" variant="primary" disabled={busy} onClick={() => openForm(EMPTY_FORM)}>
+ <Button
+ size="sm"
+ variant="primary"
+ disabled={busy}
+ onClick={() => openForm({ ...EMPTY_FORM, model: defaultModel })}
+ >
{S.schedule.addTitle}
</Button>
)}
@@ -490,54 +595,50 @@ export function SchedulesTab({ agentId }: { agentId: string }) {
<option value="session">{S.schedule.targetSession}</option>
</Select>
{form.target === "session" ? (
- <Input
- size="sm"
- label={S.schedule.sessionId}
- required
- error={fieldErrors.sessionId}
- value={form.sessionId}
- onChange={(e) => set({ sessionId: e.target.value })}
- className="font-mono"
- autoComplete="off"
- />
+ // Searchable Session picker (dropdown), replacing the raw id text input: the
+ // schedule binds to an existing conversation, and typing its id by hand was
+ // both error-prone and unsearchable.
+ <div>
+ <FieldLabel required>{S.schedule.sessionId}</FieldLabel>
+ {projectId && (
+ <SessionSelect
+ projectId={projectId}
+ agentId={agentId}
+ value={form.sessionId}
+ onChange={(sessionId) => set({ sessionId })}
+ />
+ )}
+ {fieldErrors.sessionId && <FieldError>{fieldErrors.sessionId}</FieldError>}
+ </div>
) : (
+ // New-Session mode: Model and Workspace use the same form-variant pickers as
+ // the Project default-settings dialog (ModelSelect / WorkspaceSelect), so the
+ // two surfaces read identically.
<>
- <Select
- size="sm"
- label={S.schedule.model}
- value={form.model ? modelOptionValue(form.model) : ""}
- onChange={(e) => set({ model: parseModelOption(e.target.value) })}
- >
- <option value="">{S.schedule.modelDefault}</option>
- {/* When the prefilled pair is no longer in the model config (the entry was
- renamed or deleted), add an extra option so it isn't displayed as
- "Project default". */}
- {form.model &&
- !models.some(
- (m) =>
- m.modelId === form.model!.modelId && m.provider === form.model!.provider,
- ) && (
- <option value={modelOptionValue(form.model)}>
- {modelOptionLabel(form.model)}
- </option>
- )}
- {models.map((m) => (
- <option
- key={`${m.provider}:${m.modelId}`}
- value={modelOptionValue({ provider: m.provider, modelId: m.modelId })}
- >
- {modelOptionLabel({ provider: m.provider, modelId: m.modelId })}
- </option>
- ))}
- </Select>
- <Input
- size="sm"
- label={S.schedule.workspace}
- value={form.workspace}
- onChange={(e) => set({ workspace: e.target.value })}
- className="font-mono"
- autoComplete="off"
- />
+ <div>
+ <FieldLabel>{S.schedule.model}</FieldLabel>
+ {models.length > 0 ? (
+ <ModelSelect
+ models={models}
+ value={form.model}
+ {...(defaultModel ? { defaultModel } : {})}
+ onChange={(ref) => set({ model: ref })}
+ disabled={busy}
+ variant="form"
+ />
+ ) : (
+ <p className="text-xs text-gray-400">{S.schedule.modelDefault}</p>
+ )}
+ </div>
+ <div>
+ <FieldLabel>{S.schedule.workspace}</FieldLabel>
+ <WorkspaceSelect
+ projectId={projectId ?? ""}
+ workspace={form.workspace}
+ onChange={(workspace) => set({ workspace })}
+ variant="form"
+ />
+ </div>
</>
)}
</div>
diff --git a/packages/web/src/features/chat/chat-page.tsx b/packages/web/src/features/chat/chat-page.tsx
index 0b8efe74..e9d3d703 100644
--- a/packages/web/src/features/chat/chat-page.tsx
+++ b/packages/web/src/features/chat/chat-page.tsx
@@ -52,6 +52,7 @@ import { Button } from "../../components/ui/button";
import { Skeleton } from "../../components/ui/skeleton";
import { Truncated } from "../../components/ui/truncated";
import { Dropdown } from "../../components/ui/dropdown";
+import { CopyButton } from "../../components/ui/copy-button";
import { EmptyState } from "../../components/ui/empty-state";
import { toastError } from "../../components/ui/toast";
import { MessageStream } from "./message-stream";
@@ -134,6 +135,30 @@ function StatChip({ icon, value, label }: { icon: string; value: ReactNode; labe
);
}
+/**
+ * Session id row in the details card: the id is selectable mono text (styled like the other
+ * sections' values) with the shared CopyButton beside it. The copy feedback shows the check
+ * + "已复制" text at the button (showCopiedText) — the "Session id" label above never changes.
+ */
+function SessionIdRow({ sessionId }: { sessionId: string }) {
+ return (
+ <div>
+ <p className="text-xs font-medium text-gray-500 dark:text-gray-400">
+ {S.chat.sessionIdLabel}
+ </p>
+ <div className="flex items-start gap-1.5">
+ <span className="min-w-0 flex-1 break-all font-mono text-xs leading-5">{sessionId}</span>
+ <CopyButton
+ text={sessionId}
+ label={S.chat.copySessionId}
+ showCopiedText
+ className="flex shrink-0 items-center gap-1 rounded p-0.5 text-xs text-gray-400 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 dark:text-gray-500 dark:hover:bg-gray-800 dark:hover:text-gray-300"
+ />
+ </div>
+ </div>
+ );
+}
+
/**
* Elapsed value for the header statistics: while a Task runs it ticks once per second over the
* live cumulative (settled cross-Task total + the running Task's wall clock so far, see
@@ -1406,6 +1431,7 @@ export function ChatPage() {
</span>
</p>
</div>
+ <SessionIdRow sessionId={selected.sessionId} />
<div>
<p className="text-xs font-medium text-gray-500 dark:text-gray-400">
{S.chat.workspace}
diff --git a/packages/web/src/features/chat/code-block.tsx b/packages/web/src/features/chat/code-block.tsx
index a138b049..d5043fa1 100644
--- a/packages/web/src/features/chat/code-block.tsx
+++ b/packages/web/src/features/chat/code-block.tsx
@@ -13,31 +13,7 @@
*/
import { useEffect, useState } from "react";
import { S } from "../../lib/strings";
-import { STAT_ICONS } from "../../lib/stat-icons";
-import { GlyphIcon } from "../../components/ui/glyph-icon";
-
-const COPIED_MS = 1500;
-
-/** Copy button in the header bar (same visual style as MessageMeta's copy button; always visible — the header bar has no hover-gated container). */
-function CopyCodeButton({ code }: { code: string }) {
- const [copied, setCopied] = useState(false);
- const copy = () => {
- void navigator.clipboard.writeText(code);
- setCopied(true);
- setTimeout(() => setCopied(false), COPIED_MS);
- };
- return (
- <button
- type="button"
- title={copied ? S.common.copied : S.chat.copyCode}
- aria-label={S.chat.copyCode}
- onClick={copy}
- className="rounded p-0.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300"
- >
- <GlyphIcon d={copied ? STAT_ICONS.check : STAT_ICONS.copy} />
- </button>
- );
-}
+import { CopyButton } from "../../components/ui/copy-button";
export function CodeBlock({
language,
@@ -81,7 +57,8 @@ export function CodeBlock({
<span className="font-mono text-xs lowercase text-gray-500 dark:text-gray-400">
{language || "text"}
</span>
- <CopyCodeButton code={code} />
+ {/* Always visible — the header bar has no hover-gated container. */}
+ <CopyButton text={code} label={S.chat.copyCode} />
</div>
<div className="overflow-x-auto bg-white text-[13px] leading-relaxed dark:bg-gray-950">
{html ? (
diff --git a/packages/web/src/features/chat/message-item.tsx b/packages/web/src/features/chat/message-item.tsx
index 209db820..74f1927a 100644
--- a/packages/web/src/features/chat/message-item.tsx
+++ b/packages/web/src/features/chat/message-item.tsx
@@ -13,6 +13,7 @@ import { splitAttachments } from "../../lib/attachments";
import type { ChatItem, ReconnectItem } from "../../lib/omni/stream-model";
import { Md } from "./md";
import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { CopyButton } from "../../components/ui/copy-button";
import { ZoomableImage } from "../../components/ui/image-zoom";
import { MessageFilesCard } from "./message-files-card";
import { ThinkingBlock } from "./thinking-block";
@@ -34,9 +35,6 @@ import { parseSkillsMessage } from "./skill-use";
import { TaskStatsLine } from "./task-stats-line";
import type { StreamRenderContext } from "./message-stream";
-/** Duration the "Copied" tooltip stays visible (milliseconds). */
-const COPIED_MS = 1200;
-
/** User glyph (24×24 line path) for the mid-run steering chip. */
const USER_STEERING_ICON =
"M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2M16 7a4 4 0 1 1-8 0 4 4 0 0 1 8 0";
@@ -64,13 +62,6 @@ function MessageMeta({
align?: "left" | "right";
}) {
const { locale } = useLocale();
- const [copied, setCopied] = useState(false);
- const copy = () => {
- if (text === undefined) return;
- void navigator.clipboard.writeText(text);
- setCopied(true);
- setTimeout(() => setCopied(false), COPIED_MS);
- };
return (
<div
className={`flex h-5 items-center gap-2 transition-opacity duration-150 group-hover:opacity-100 focus-within:opacity-100 sm:opacity-0 ${
@@ -80,17 +71,8 @@ function MessageMeta({
{atMs !== undefined && (
<span className="text-[11px] text-gray-400">{formatMessageTime(atMs, locale)}</span>
)}
- {text !== undefined && (
- <button
- type="button"
- title={copied ? S.common.copied : S.chat.copyMessage}
- aria-label={S.chat.copyMessage}
- onClick={copy}
- className="rounded p-0.5 text-gray-400 transition-colors hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300"
- >
- <GlyphIcon d={copied ? STAT_ICONS.check : STAT_ICONS.copy} />
- </button>
- )}
+ {/* No copy button for image-only messages: copying an image message has no clear meaning. */}
+ {text !== undefined && <CopyButton text={text} label={S.chat.copyMessage} />}
</div>
);
}
diff --git a/packages/web/src/features/chat/model-select.tsx b/packages/web/src/features/chat/model-select.tsx
index 1f86d2c7..94a2e120 100644
--- a/packages/web/src/features/chat/model-select.tsx
+++ b/packages/web/src/features/chat/model-select.tsx
@@ -15,10 +15,9 @@ import type { ModelInfo, ModelRefDto } from "@prismshadow/penguin-server/api";
import { S } from "../../lib/strings";
import { Badge } from "../../components/ui/badge";
import { Dropdown } from "../../components/ui/dropdown";
-import { controlBase } from "../../components/ui/field";
+import { FormPicker } from "../../components/ui/form-picker";
import { GlyphIcon } from "../../components/ui/glyph-icon";
-import { ChevronDown } from "../../components/ui/icons";
-import { noAutofill, sizeClass } from "../../components/ui/input";
+import { noAutofill } from "../../components/ui/input";
import { ProviderLogo } from "../../components/ui/provider-logo";
import {
hasConfiguredKey,
@@ -258,9 +257,8 @@ export function ModelMenuList({
* Two trigger variants, one menu:
* - "pill" (default): the composer's compact toolbar button — collapses to the logo alone
* under the card's own `@container` query, menu right-aligned;
- * - "form": a full-width trigger styled like the dialog's Input/Select (controlBase + the
- * sm size tier), label always visible (a container-less host's `@md:` variant would never
- * match), menu left-aligned under the control.
+ * - "form": the shared FormPicker (full-width Input/Select-styled trigger, menu left-aligned
+ * under the control), used by every dialog host.
*/
export function ModelSelect({
models,
@@ -289,74 +287,75 @@ export function ModelSelect({
className="h-4 w-4 shrink-0"
/>
);
+ const menu = (
+ <ModelMenuList
+ models={models}
+ value={value}
+ {...(defaultModel !== undefined ? { defaultModel } : {})}
+ onPick={(m) => {
+ onChange({ provider: m.provider, modelId: m.modelId });
+ setOpen(false);
+ }}
+ />
+ );
+ // Form: the shared full-width trigger (same look as Input/Select), used by every dialog picker.
+ if (variant === "form") {
+ return (
+ <FormPicker
+ open={open}
+ setOpen={setOpen}
+ leading={logo}
+ label={label}
+ title={`${S.chat.chooseModel}:${label}`}
+ ariaLabel={S.chat.chooseModel}
+ ariaHaspopup="listbox"
+ disabled={disabled || models.length === 0}
+ menuClass="w-max min-w-56 origin-top-left"
+ >
+ {menu}
+ </FormPicker>
+ );
+ }
+ // Pill: the composer's compact toolbar button — the panel's right edge docks to it; portal
+ // placement then clamps both edges inside the viewport.
return (
<Dropdown
open={open}
setOpen={setOpen}
- // Pill: the panel's right edge docks to the button; portal placement then clamps both
- // edges inside the viewport, so a w-max panel can no longer run off-screen on phones
- // (it used to need a hand-tuned width clamp reserving the anchor offset). Form: the
- // panel hangs under the full-width control's left edge, like the dialog's Select.
- menuClass={`w-max min-w-56 ${variant === "form" ? "origin-top-left" : "origin-top-right"}`}
- portal={{ direction: "down", align: variant === "form" ? "left" : "right" }}
+ menuClass="w-max min-w-56 origin-top-right"
+ portal={{ direction: "down", align: "right" }}
button={
- variant === "form" ? (
- // Dialog form control: full width, same border/height/typography as Input/Select (sm tier).
- <button
- type="button"
- title={`${S.chat.chooseModel}:${label}`}
- aria-label={S.chat.chooseModel}
- aria-haspopup="listbox"
- aria-expanded={open}
- disabled={disabled || models.length === 0}
- onClick={() => setOpen(!open)}
- className={`flex w-full items-center gap-2 text-left ${controlBase} ${sizeClass.sm} disabled:cursor-not-allowed disabled:opacity-60`}
+ <button
+ type="button"
+ title={`${S.chat.chooseModel}:${label}`}
+ aria-label={S.chat.chooseModel}
+ disabled={disabled || models.length === 0}
+ onClick={() => setOpen(!open)}
+ className="flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
+ >
+ {logo}
+ {/* When the card is narrower than @md, only the provider logo remains (title shows the full name). */}
+ <span className="hidden min-w-0 truncate @md:block">{label}</span>
+ <svg
+ width="10"
+ height="10"
+ viewBox="0 0 12 12"
+ fill="none"
+ stroke="currentColor"
+ className="shrink-0"
+ aria-hidden
>
- {logo}
- <span className="min-w-0 flex-1 truncate">{label}</span>
- <ChevronDown className="text-gray-400" />
- </button>
- ) : (
- <button
- type="button"
- title={`${S.chat.chooseModel}:${label}`}
- aria-label={S.chat.chooseModel}
- disabled={disabled || models.length === 0}
- onClick={() => setOpen(!open)}
- className="flex h-8 max-w-44 shrink-0 items-center gap-1.5 rounded-md px-2 text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 hover:text-gray-800 disabled:cursor-not-allowed disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800 dark:hover:text-gray-200"
- >
- {logo}
- {/* When the card is narrower than @md, only the provider logo remains (title shows the full name). */}
- <span className="hidden min-w-0 truncate @md:block">{label}</span>
- <svg
- width="10"
- height="10"
- viewBox="0 0 12 12"
- fill="none"
- stroke="currentColor"
- className="shrink-0"
- aria-hidden
- >
- <path
- d="M3 4.5l3 3 3-3"
- strokeWidth="1.5"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
- </button>
- )
+ <path
+ d="M3 4.5l3 3 3-3"
+ strokeWidth="1.5"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ </button>
}
>
- <ModelMenuList
- models={models}
- value={value}
- {...(defaultModel !== undefined ? { defaultModel } : {})}
- onPick={(m) => {
- onChange({ provider: m.provider, modelId: m.modelId });
- setOpen(false);
- }}
- />
+ {menu}
</Dropdown>
);
}
diff --git a/packages/web/src/features/chat/task-stats-line.tsx b/packages/web/src/features/chat/task-stats-line.tsx
index 39b2e835..767b9da0 100644
--- a/packages/web/src/features/chat/task-stats-line.tsx
+++ b/packages/web/src/features/chat/task-stats-line.tsx
@@ -24,7 +24,6 @@
* footer**: it provides the reply timestamp and copy button at the end, so the assistant message
* itself doesn't render a separate one (otherwise two copy buttons would pop up in the same spot).
*/
-import { useState } from "react";
import { formatTaskStats } from "../../lib/omni/task-stats";
import type { TaskStats } from "../../lib/omni/task-stats";
import {
@@ -37,6 +36,7 @@ import {
import { STAT_ICONS } from "../../lib/stat-icons";
import { S } from "../../lib/strings";
import { GlyphIcon } from "../../components/ui/glyph-icon";
+import { CopyButton } from "../../components/ui/copy-button";
import { useTheme } from "../../state/theme";
import { useLocale } from "../../state/locale";
@@ -89,7 +89,6 @@ export function TaskStatsLine({
/** Timestamp of this turn's AI reply (this line is that reply's footer). */
atMs?: number;
}) {
- const [copied, setCopied] = useState(false);
const { currency } = useTheme();
const { locale } = useLocale();
@@ -97,23 +96,19 @@ export function TaskStatsLine({
const b = stats?.tokensByBucket;
const input = b ? b.cacheRead + b.cacheWrite : 0;
- const copy = () => {
- const text =
- assistantText?.trim() || stats === null
- ? (assistantText ?? "")
- : formatTaskStats(stats, {
- stats: S.chat.statsLabel,
- input: S.chat.statInput,
- cached: S.chat.statCached,
- output: S.chat.statOutput,
- parenOpen: S.chat.statParenOpen,
- parenClose: S.chat.statParenClose,
- });
- void navigator.clipboard?.writeText(text).then(() => {
- setCopied(true);
- setTimeout(() => setCopied(false), 1500);
- });
- };
+ // Computed at click time (CopyButton takes a getter): the reply text, or the formatted
+ // stats line when there's no reply body.
+ const copyText = () =>
+ assistantText?.trim() || stats === null
+ ? (assistantText ?? "")
+ : formatTaskStats(stats, {
+ stats: S.chat.statsLabel,
+ input: S.chat.statInput,
+ cached: S.chat.statCached,
+ output: S.chat.statOutput,
+ parenOpen: S.chat.statParenOpen,
+ parenClose: S.chat.statParenClose,
+ });
// ≥sm: invisible but **space-reserved** by default (sm:opacity-0, not hidden) — the user
// footer's hover-reveal convention; because the space is always reserved, appearing never
@@ -170,15 +165,12 @@ export function TaskStatsLine({
</>
)}
</span>
- <button
- type="button"
- title={copied ? S.common.copied : S.chat.copyReply}
- aria-label={S.chat.copyReply}
- onClick={copy}
+ {/* Pinned at the row's end, outside the scrollable stats span. */}
+ <CopyButton
+ text={copyText}
+ label={S.chat.copyReply}
className="flex h-5 w-5 shrink-0 items-center justify-center rounded transition-colors duration-150 hover:bg-gray-100 hover:text-gray-600 dark:hover:bg-gray-800 dark:hover:text-gray-300"
- >
- <GlyphIcon d={copied ? STAT_ICONS.check : STAT_ICONS.copy} />
- </button>
+ />
</div>
);
}
diff --git a/packages/web/src/features/chat/workspace-select.tsx b/packages/web/src/features/chat/workspace-select.tsx
index 18bbbb06..7b800fc4 100644
--- a/packages/web/src/features/chat/workspace-select.tsx
+++ b/packages/web/src/features/chat/workspace-select.tsx
@@ -4,10 +4,9 @@
* Two trigger variants, one menu:
* - "pill" (default): the draft page's pill trigger with viewport-docked in-flow menu —
* moved verbatim, unchanged markup/classes/behavior;
- * - "form": a full-width trigger styled like the dialog's Input/Select (controlBase +
- * the sm size tier), with the SAME menu portaled to body — a dialog's overflow-y-auto
- * content area would clip an in-flow panel, and the portal tier (z-[60]) clears the
- * Modal overlay.
+ * - "form": the shared FormPicker (full-width Input/Select-styled trigger, portaled menu) —
+ * a dialog's overflow-y-auto content area would clip an in-flow panel, and the portal
+ * tier (z-[60]) clears the Modal overlay.
*/
import { useCallback, useEffect, useRef, useState } from "react";
import type { MouseEvent as ReactMouseEvent } from "react";
@@ -17,9 +16,8 @@ import { S } from "../../lib/strings";
import { apiErrorText } from "../../lib/api-error";
import { Chevron } from "../../components/ui/chevron";
import { Dropdown } from "../../components/ui/dropdown";
-import { controlBase } from "../../components/ui/field";
-import { ChevronDown } from "../../components/ui/icons";
-import { noAutofill, sizeClass } from "../../components/ui/input";
+import { FormPicker } from "../../components/ui/form-picker";
+import { noAutofill } from "../../components/ui/input";
import { toastError } from "../../components/ui/toast";
/** Shared style for pill trigger buttons (ChatGPT project button style: small rounded pill + icon + short name + collapse arrow). */
@@ -109,11 +107,25 @@ export function WorkspaceSelect({
[projectId],
);
+ // Only loads on first expand: an already-filled absolute path is used as the starting point, otherwise the server falls back to the home directory.
+ const loadOnFirstOpen = (next: boolean) => {
+ if (next && !browsedRef.current) {
+ browsedRef.current = true;
+ const ws = workspace.trim();
+ loadDir(ws.startsWith("/") ? ws : "");
+ }
+ };
+
+ /** Form-variant open handler (FormPicker owns the trigger): portaled, so no dock measurement — just open + lazy load. */
+ const setFormOpen = (next: boolean) => {
+ setOpen(next);
+ loadOnFirstOpen(next);
+ };
+
+ /** Pill-variant trigger: measures viewport room to dock the in-flow panel left/right before opening. */
const toggle = (e: ReactMouseEvent<HTMLButtonElement>) => {
const next = !open;
- // The dock measurement steers the in-flow (pill) panel only; the form variant portals,
- // and Dropdown's own viewport clamping takes over.
- if (next && variant === "pill") {
+ if (next) {
const r = e.currentTarget.getBoundingClientRect();
const rem = parseFloat(getComputedStyle(document.documentElement).fontSize);
const margin = 12; // breathing room against the viewport edge
@@ -128,12 +140,7 @@ export function WorkspaceSelect({
else setMenuDock({ right: false, maxWidth: roomRight });
}
setOpen(next);
- // Only loads on first expand: an already-filled absolute path is used as the starting point, otherwise the server falls back to the home directory.
- if (next && !browsedRef.current) {
- browsedRef.current = true;
- const ws = workspace.trim();
- loadDir(ws.startsWith("/") ? ws : "");
- }
+ loadOnFirstOpen(next);
};
/**
@@ -180,171 +187,171 @@ export function WorkspaceSelect({
/>
</svg>
);
- return (
- <Dropdown
- open={open}
- setOpen={setOpen}
- {...(variant === "form"
- ? // Portaled menu (size classes only; placement is measured from the trigger).
- { menuClass: "w-80", portal: { direction: "down" as const, align: "left" as const } }
- : {
- menuClass: `top-full mt-1 w-80 max-w-[calc(100vw-2rem)] ${
- menuDock.right ? "right-0 origin-top-right" : "left-0 origin-top-left"
- }`,
- ...(menuDock.maxWidth !== undefined
- ? { menuStyle: { maxWidth: menuDock.maxWidth } }
- : {}),
- })}
- button={
- variant === "form" ? (
- // Dialog form control: full width, same border/height/typography as Input/Select (sm tier).
- <button
- type="button"
- title={trimmed ? `${S.chat.workspace}:${trimmed}` : S.chat.workspaceHint}
- aria-label={S.chat.workspace}
- aria-haspopup="dialog"
- aria-expanded={open}
- onClick={toggle}
- className={`flex w-full items-center gap-2 text-left ${controlBase} ${sizeClass.sm}`}
- >
- {folderIcon("")}
- <span className={`min-w-0 flex-1 truncate ${trimmed ? "font-mono" : ""}`}>{label}</span>
- <ChevronDown className="text-gray-400" />
- </button>
- ) : (
- <button
- type="button"
- title={trimmed ? `${S.chat.workspace}:${trimmed}` : S.chat.workspaceHint}
+ const menu = (
+ <div className="space-y-1.5 px-2.5 pb-2.5 pt-2">
+ <div className="rounded-md border border-gray-200 dark:border-gray-800">
+ {/* Current path (editable: Enter/blur commits, Escape discards) + "Use this directory" (closes the menu once selected) */}
+ <div className="flex items-center gap-1.5 border-b border-gray-100 px-1.5 py-1 dark:border-gray-800">
+ <input
+ value={pathDraft}
+ placeholder="…"
aria-label={S.chat.workspace}
- onClick={toggle}
- className={pillClass}
- >
- {folderIcon("ml-0.5")}
- <span className={`min-w-0 truncate ${trimmed ? "font-mono" : ""}`}>{label}</span>
- <Chevron open={open} size={12} className="shrink-0 text-gray-400" />
- </button>
- )
- }
- >
- <div className="space-y-1.5 px-2.5 pb-2.5 pt-2">
- <div className="rounded-md border border-gray-200 dark:border-gray-800">
- {/* Current path (editable: Enter/blur commits, Escape discards) + "Use this directory" (closes the menu once selected) */}
- <div className="flex items-center gap-1.5 border-b border-gray-100 px-1.5 py-1 dark:border-gray-800">
- <input
- value={pathDraft}
- placeholder="…"
- aria-label={S.chat.workspace}
- {...noAutofill}
- onChange={(e) => setPathDraft(e.target.value)}
- onBlur={commitPathEdit}
- onKeyDown={(e) => {
- if (e.key === "Enter" && !e.nativeEvent.isComposing) {
- e.preventDefault();
- commitPathEdit();
- } else if (e.key === "Escape") {
- // Discard the edit: only reverts the draft; Escape bubbles up to Dropdown, which closes the menu.
- setPathDraft(dir?.path ?? "");
- }
- }}
- className="min-w-0 flex-1 rounded border border-transparent bg-transparent px-1 py-0.5 font-mono text-xs text-gray-600 focus:border-gray-300 focus:outline-none dark:text-gray-300 dark:focus:border-gray-600"
- />
- <button
- type="button"
- disabled={!dir}
- onClick={() => {
- if (!dir) return;
- onChange(dir.path);
- setOpen(false);
- }}
- className="shrink-0 rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
- >
- {S.chat.workspaceUseThis}
- </button>
- </div>
- {/* Directory list (excludes hidden directories) */}
- <ul className="max-h-40 overflow-y-auto py-1">
- {/* Rows are disabled while a load is in flight: they still show the PREVIOUS
- directory until the response lands, so clicks during the window would resend
- stale targets (N clicks on "parent" all resending the same dir.parent). */}
- {parentPath !== null && (
- <li>
- <button
- type="button"
- disabled={loading}
- onClick={() => loadDir(parentPath)}
- className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left font-mono text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800"
- >
- ↰ {S.chat.workspaceUp}
- </button>
- </li>
- )}
- {entries.map((entry) => (
- <li key={entry.path}>
- <button
- type="button"
- disabled={loading}
- onClick={() => loadDir(entry.path)}
- className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left font-mono text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-300 dark:hover:bg-gray-800"
- >
- <svg
- width="13"
- height="13"
- viewBox="0 0 24 24"
- fill="none"
- stroke="currentColor"
- className="shrink-0 text-gray-400"
- aria-hidden
- >
- <path
- d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"
- strokeWidth="1.6"
- strokeLinejoin="round"
- />
- </svg>
- <span className="min-w-0 flex-1 truncate">{entry.name}</span>
- </button>
- </li>
- ))}
- {dir && entries.length === 0 && (
- <li className="px-2.5 py-1.5 text-xs text-gray-400">{S.chat.workspaceNoSubdirs}</li>
- )}
- {loading && <li className="px-2.5 py-1.5 text-xs text-gray-400">{S.common.loading}</li>}
- {/* Load failure (e.g. the cached starting directory was deleted): provide "retry" to fall back to the home directory, avoiding getting stuck in an error state. */}
- {error && (
- <li className="flex items-center justify-between gap-2 px-2.5 py-1.5 text-xs text-red-500">
- <span className="min-w-0 flex-1 truncate" title={error}>
- {error}
- </span>
- <button
- type="button"
- disabled={loading}
- onClick={() => loadDir("")}
- className="shrink-0 rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
- >
- {S.common.retry}
- </button>
- </li>
- )}
- </ul>
- </div>
- {/* When a directory has been specified, offer a one-click way back to a temporary workspace */}
- {trimmed && (
+ {...noAutofill}
+ onChange={(e) => setPathDraft(e.target.value)}
+ onBlur={commitPathEdit}
+ onKeyDown={(e) => {
+ if (e.key === "Enter" && !e.nativeEvent.isComposing) {
+ e.preventDefault();
+ commitPathEdit();
+ } else if (e.key === "Escape") {
+ // Discard the edit: only reverts the draft; Escape bubbles up to Dropdown, which closes the menu.
+ setPathDraft(dir?.path ?? "");
+ }
+ }}
+ className="min-w-0 flex-1 rounded border border-transparent bg-transparent px-1 py-0.5 font-mono text-xs text-gray-600 focus:border-gray-300 focus:outline-none dark:text-gray-300 dark:focus:border-gray-600"
+ />
<button
type="button"
+ disabled={!dir}
onClick={() => {
- onChange("");
+ if (!dir) return;
+ onChange(dir.path);
setOpen(false);
}}
- className="text-xs text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"
+ className="shrink-0 rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
>
- {S.chat.workspaceClear}
+ {S.chat.workspaceUseThis}
</button>
- )}
- {/* Hint text (bottom of the menu) */}
- <p className="px-0.5 text-xs leading-5 text-gray-400 dark:text-gray-500">
- {S.chat.workspaceHint}
- </p>
+ </div>
+ {/* Directory list (excludes hidden directories) */}
+ <ul className="max-h-40 overflow-y-auto py-1">
+ {/* Rows are disabled while a load is in flight: they still show the PREVIOUS
+ directory until the response lands, so clicks during the window would resend
+ stale targets (N clicks on "parent" all resending the same dir.parent). */}
+ {parentPath !== null && (
+ <li>
+ <button
+ type="button"
+ disabled={loading}
+ onClick={() => loadDir(parentPath)}
+ className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left font-mono text-xs text-gray-500 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-400 dark:hover:bg-gray-800"
+ >
+ ↰ {S.chat.workspaceUp}
+ </button>
+ </li>
+ )}
+ {entries.map((entry) => (
+ <li key={entry.path}>
+ <button
+ type="button"
+ disabled={loading}
+ onClick={() => loadDir(entry.path)}
+ className="flex w-full items-center gap-2 px-2.5 py-1.5 text-left font-mono text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:text-gray-300 dark:hover:bg-gray-800"
+ >
+ <svg
+ width="13"
+ height="13"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ className="shrink-0 text-gray-400"
+ aria-hidden
+ >
+ <path
+ d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V7z"
+ strokeWidth="1.6"
+ strokeLinejoin="round"
+ />
+ </svg>
+ <span className="min-w-0 flex-1 truncate">{entry.name}</span>
+ </button>
+ </li>
+ ))}
+ {dir && entries.length === 0 && (
+ <li className="px-2.5 py-1.5 text-xs text-gray-400">{S.chat.workspaceNoSubdirs}</li>
+ )}
+ {loading && <li className="px-2.5 py-1.5 text-xs text-gray-400">{S.common.loading}</li>}
+ {/* Load failure (e.g. the cached starting directory was deleted): provide "retry" to fall back to the home directory, avoiding getting stuck in an error state. */}
+ {error && (
+ <li className="flex items-center justify-between gap-2 px-2.5 py-1.5 text-xs text-red-500">
+ <span className="min-w-0 flex-1 truncate" title={error}>
+ {error}
+ </span>
+ <button
+ type="button"
+ disabled={loading}
+ onClick={() => loadDir("")}
+ className="shrink-0 rounded border border-gray-300 px-1.5 py-0.5 text-xs text-gray-700 transition-colors duration-150 hover:bg-gray-100 disabled:opacity-50 dark:border-gray-700 dark:text-gray-300 dark:hover:bg-gray-800"
+ >
+ {S.common.retry}
+ </button>
+ </li>
+ )}
+ </ul>
</div>
+ {/* When a directory has been specified, offer a one-click way back to a temporary workspace */}
+ {trimmed && (
+ <button
+ type="button"
+ onClick={() => {
+ onChange("");
+ setOpen(false);
+ }}
+ className="text-xs text-gray-500 underline decoration-gray-300 underline-offset-2 transition-colors duration-150 hover:text-gray-800 dark:text-gray-400 dark:hover:text-gray-200"
+ >
+ {S.chat.workspaceClear}
+ </button>
+ )}
+ {/* Hint text (bottom of the menu) */}
+ <p className="px-0.5 text-xs leading-5 text-gray-400 dark:text-gray-500">
+ {S.chat.workspaceHint}
+ </p>
+ </div>
+ );
+
+ // Form: the shared full-width trigger (its label goes mono once a real path is set).
+ if (variant === "form") {
+ return (
+ <FormPicker
+ open={open}
+ setOpen={setFormOpen}
+ leading={folderIcon("")}
+ label={label}
+ {...(trimmed ? { labelClassName: "font-mono" } : {})}
+ title={trimmed ? `${S.chat.workspace}:${trimmed}` : S.chat.workspaceHint}
+ ariaLabel={S.chat.workspace}
+ ariaHaspopup="dialog"
+ menuClass="w-80"
+ >
+ {menu}
+ </FormPicker>
+ );
+ }
+
+ // Pill: the composer's compact toolbar trigger, with the in-flow panel docked left/right by `toggle`'s measurement.
+ return (
+ <Dropdown
+ open={open}
+ setOpen={setOpen}
+ menuClass={`top-full mt-1 w-80 max-w-[calc(100vw-2rem)] ${
+ menuDock.right ? "right-0 origin-top-right" : "left-0 origin-top-left"
+ }`}
+ {...(menuDock.maxWidth !== undefined ? { menuStyle: { maxWidth: menuDock.maxWidth } } : {})}
+ button={
+ <button
+ type="button"
+ title={trimmed ? `${S.chat.workspace}:${trimmed}` : S.chat.workspaceHint}
+ aria-label={S.chat.workspace}
+ onClick={toggle}
+ className={pillClass}
+ >
+ {folderIcon("ml-0.5")}
+ <span className={`min-w-0 truncate ${trimmed ? "font-mono" : ""}`}>{label}</span>
+ <Chevron open={open} size={12} className="shrink-0 text-gray-400" />
+ </button>
+ }
+ >
+ {menu}
</Dropdown>
);
}
diff --git a/packages/web/src/lib/strings-en.ts b/packages/web/src/lib/strings-en.ts
index e0f6b4cf..1c988c1d 100644
--- a/packages/web/src/lib/strings-en.ts
+++ b/packages/web/src/lib/strings-en.ts
@@ -257,6 +257,7 @@ export const en: Strings = {
["{{SKILL_METADATA}}", "Injects the installed skills' metadata lines (empty when none)"],
["{{PLATFORM}}", "Runtime platform"],
["{{OS_VERSION}}", "Operating system version"],
+ ["{{SHELL}}", "Shell used to run commands"],
["{{DATE}}", "Current date"],
[
"{{PROJECT_DIR}}",
@@ -525,7 +526,12 @@ export const en: Strings = {
target: "Target",
targetNew: "New session each time",
targetSession: "Bound Session",
- sessionId: "Session id",
+ sessionId: "Session",
+ /** Bind-Session picker (searchable dropdown): trigger placeholder, search box, and empty states. */
+ chooseSession: "Choose a Session to bind",
+ sessionSearch: "Search title or Session id…",
+ sessionNoMatch: "No matching Session",
+ sessionEmpty: "This agent has no Sessions yet",
workspace: "Workspace (optional; a temporary workspace is created when empty)",
model: "Model",
modelDefault: "Project default",
@@ -869,6 +875,9 @@ Scenarios:
"This model cannot view images directly: on send, images are saved to the session scratchpad and passed as file paths (viewed via describe_image)",
infoPanel: "Session info",
sessionStats: "Stats",
+ /** Info-dropdown Session id row: the id itself is a click-to-copy button. */
+ sessionIdLabel: "Session id",
+ copySessionId: "Copy Session id",
/** Info-dropdown trace row: labels the Session's trace file path (clicking deep-links to the Trace page). */
traceFile: "Trace file",
/** Info-dropdown list of background processes the conversation started, and its per-row actions. */
diff --git a/packages/web/src/lib/strings.ts b/packages/web/src/lib/strings.ts
index 68f91337..ba13c4d8 100644
--- a/packages/web/src/lib/strings.ts
+++ b/packages/web/src/lib/strings.ts
@@ -248,6 +248,7 @@ export const zh = {
["{{SKILL_METADATA}}", "注入已安装 Skill 的元数据行(无 Skill 时为空)"],
["{{PLATFORM}}", "运行平台"],
["{{OS_VERSION}}", "操作系统版本"],
+ ["{{SHELL}}", "命令执行使用的 Shell"],
["{{DATE}}", "当前日期"],
[
"{{PROJECT_DIR}}",
@@ -507,7 +508,12 @@ export const zh = {
target: "目标",
targetNew: "每次新建会话",
targetSession: "绑定 Session",
- sessionId: "Session id",
+ sessionId: "Session",
+ /** Bind-Session picker (searchable dropdown): trigger placeholder, search box, and empty states. */
+ chooseSession: "选择要绑定的 Session",
+ sessionSearch: "搜索标题或 Session id…",
+ sessionNoMatch: "无匹配的 Session",
+ sessionEmpty: "该 Agent 暂无 Session",
workspace: "Workspace(可选,留空自动创建临时工作区)",
model: "Model",
modelDefault: "Project 默认",
@@ -847,6 +853,9 @@ Benchmark:
"当前模型不支持直接查看图片:发送时图片将保存到会话临时目录,以文件路径转交(模型经 describe_image 查看)",
infoPanel: "Session 信息",
sessionStats: "统计",
+ /** Info-dropdown Session id row: the id itself is a click-to-copy button. */
+ sessionIdLabel: "Session id",
+ copySessionId: "复制 Session id",
/** Info-dropdown trace row: labels the Session's trace file path (clicking deep-links to the Trace page). */
traceFile: "轨迹文件",
/** Info-dropdown list of background processes the conversation started, and its per-row actions. */
diff --git a/packages/web/test/placeholders-parity.test.ts b/packages/web/test/placeholders-parity.test.ts
new file mode 100644
index 00000000..e2bdcbf5
--- /dev/null
+++ b/packages/web/test/placeholders-parity.test.ts
@@ -0,0 +1,45 @@
+/**
+ * The Agent Prompt tab's "available placeholders" list must stay in lockstep with the
+ * default system prompt it mirrors — same tokens, same order (the dictionary carries that
+ * invariant as a comment). This drift went unnoticed once ({{SHELL}} was added to the
+ * prompt but not the list), so pin it: derive the tokens from core's real default prompt
+ * and compare to both dictionaries.
+ */
+import { describe, expect, it } from "vitest";
+import { defaultSystemConfig } from "@prismshadow/penguin-core";
+import { zh } from "../src/lib/strings";
+import { en } from "../src/lib/strings-en";
+
+const dictionaries = { zh, en };
+
+/** Tokens `{{FOO}}` in first-appearance order, de-duplicated (a token may recur in the prompt body). */
+function promptTokensInOrder(prompt: string): string[] {
+ const seen = new Set<string>();
+ const out: string[] = [];
+ for (const m of prompt.matchAll(/\{\{[A-Z_]+\}\}/g)) {
+ if (!seen.has(m[0])) {
+ seen.add(m[0]);
+ out.push(m[0]);
+ }
+ }
+ return out;
+}
+
+describe("agent placeholder list ⇔ default system prompt", () => {
+ const promptTokens = promptTokensInOrder(defaultSystemConfig().system_prompt);
+
+ it("the prompt actually uses placeholders (guards against a broken extraction)", () => {
+ expect(promptTokens.length).toBeGreaterThan(0);
+ expect(promptTokens).toContain("{{SHELL}}");
+ });
+
+ for (const [locale, dict] of Object.entries(dictionaries)) {
+ it(`${locale} lists every prompt placeholder once, in prompt order`, () => {
+ const listed = dict.agent.placeholders.map(([token]) => token);
+ // No duplicate rows (a copy-paste slip would show the same token twice).
+ expect(new Set(listed).size).toBe(listed.length);
+ // Same set and same order as the prompt.
+ expect(listed).toEqual(promptTokens);
+ });
+ }
+});