feat: add project-aware agent workspace
Generic Container CI/CD / test-build-publish (push) Successful in 2m9s
Frontend CI/CD / build-test-publish-and-deploy (push) Successful in 2m39s

This commit is contained in:
2026-10-22 18:52:18 +08:00
parent c6a0e74e72
commit 2d8506fea0
191 changed files with 12373 additions and 3556 deletions
+2 -2
View File
@@ -95,7 +95,7 @@ test("preserves compact typography in header and agent controls", async ({ page
await expect(approvalControl).toHaveCSS("font-size", "12px");
await expect(approvalControl).toHaveCSS("line-height", "16px");
await expect(suggestion).toHaveCSS("font-size", "12px");
await expect(suggestion).toHaveCSS("font-weight", "600");
await expect(suggestion).toHaveCSS("font-weight", "400");
});
test("lets interactive utilities override surface materials", async ({ page }) => {
@@ -138,7 +138,7 @@ test("keeps menu origin and the solid Main Frame styling through Tailwind v4", a
};
});
expect(navigationMaterial.backdropFilter).toBe("none");
expect(navigationMaterial.backgroundColor).toBe(await readThemeColor(navigation, "--agent-dock-surface"));
expect(navigationMaterial.backgroundColor).toBe(await readThemeColor(navigation, "--surface-navigation"));
await expect(page.locator("#main-workspace")).toHaveAttribute("data-layout-mode", "default");
await expect(page.getByRole("toolbar", { name: "工作区窗口任务栏" })).toHaveCount(0);
});
+2 -2
View File
@@ -1,12 +1,12 @@
import { MapToaster } from "@/features/map/core";
import { MapWorkbenchPage } from "@/features/workbench";
import { ProjectWorkbench } from "@/features/workbench";
import type { Authentication } from "@/shared/auth/keycloak-auth";
import { AppProviders } from "./providers";
export function App({ authentication }: { authentication: Authentication }) {
return (
<AppProviders>
<MapWorkbenchPage
<ProjectWorkbench
user={authentication.user ?? undefined}
onLogout={authentication.logout}
getAccessToken={authentication.getAccessToken}
+12 -21
View File
@@ -1,26 +1,17 @@
import { Droplets, RefreshCw } from "lucide-react";
import { Button } from "@/shared/ui/button";
import { Droplet } from "lucide-react";
import { StartupScreen } from "@/shared/ui/startup-screen";
export function AuthStartupScreen({ error }: { error?: boolean }) {
return (
<main className="grid min-h-[100dvh] place-items-center bg-slate-100 px-5 text-slate-900">
<section className="surface-reading w-full max-w-md p-6 text-center shadow-xl shadow-slate-900/5">
<span className="mx-auto grid h-11 w-11 place-items-center rounded-xl bg-blue-600 text-white">
<Droplets size={22} aria-hidden="true" />
</span>
<h1 className="mt-4 text-lg font-semibold">
{error ? "统一身份认证连接失败" : "正在连接统一身份认证"}
</h1>
<p className="mt-2 text-sm leading-6 text-slate-500">
{error ? "请检查网络或 Keycloak 配置后重试。" : "正在检查登录状态,请稍候。"}
</p>
{error ? (
<Button className="mt-5" onClick={() => window.location.reload()}>
<RefreshCw size={15} aria-hidden="true" />
重新连接
</Button>
) : null}
</section>
</main>
<StartupScreen
brand={{ name: "TJWater", description: "智慧水务平台", icon: <Droplet strokeWidth={1.5} /> }}
title={error ? "统一身份认证连接失败" : "正在连接统一身份认证"}
description={error ? "连接恢复后,可以重新尝试登录。" : "正在确认登录状态,完成后自动继续。"}
progressLabel="身份认证进度"
steps={[{ id: "identity", label: "检查登录状态", detail: "连接认证服务,确认登录状态", state: "loading" }]}
error={error ? "暂时无法连接登录服务,请检查网络连接后重试。" : null}
retryLabel="重新连接"
onRetry={() => window.location.reload()}
/>
);
}
@@ -1,6 +1,7 @@
import { StreamingTokenResponse } from "../components/streaming-token-response";
import { AnswerUiView, type AnswerUiMapTarget } from "./answer-ui-view";
import type { AnswerUiPart } from "./contract";
import type { AnswerUiSelection } from "./answer-ui-interaction-context";
export function AnswerPartsView({
parts,
@@ -9,7 +10,8 @@ export function AnswerPartsView({
streaming,
streamDone,
onLocate,
onSubmit
onSubmit,
onAsk
}: {
parts: AnswerUiPart[];
messageId: string;
@@ -18,6 +20,7 @@ export function AnswerPartsView({
streamDone: boolean;
onLocate?: (target: AnswerUiMapTarget) => Promise<unknown> | void;
onSubmit?: (text: string) => Promise<void> | void;
onAsk?: (selection: AnswerUiSelection) => void;
}) {
return (
<div className="space-y-4">
@@ -29,6 +32,7 @@ export function AnswerPartsView({
disabled={disabled}
onLocate={onLocate}
onSubmit={onSubmit}
onAsk={onAsk}
/>
) : (
<StreamingTokenResponse
@@ -0,0 +1,16 @@
import { createContext } from "react";
export type AnswerUiSelection = { title: string; text: string };
export type AnswerUiMapTarget = {
layer: "junctions" | "pipes" | "valves" | "pumps" | "tanks" | "reservoirs" | "scada";
feature_ids: string[];
};
export type AnswerUiInteractions = {
disabled: boolean;
onLocate?: (target: AnswerUiMapTarget) => Promise<unknown> | void;
onSubmit?: (text: string) => Promise<void> | void;
onAsk?: (selection: AnswerUiSelection) => Promise<void> | void;
evidenceFilter?: string;
submitMode?: "send" | "draft";
};
export const AnswerInteractionContext = createContext<AnswerUiInteractions>({ disabled: true });
@@ -0,0 +1,24 @@
import { AnswerInteractionContext, type AnswerUiSelection } from "./answer-ui-interaction-context";
import { useContext, useState } from "react";
import { MessageSquarePlus } from "lucide-react";
import { Button } from "@/shared/ui/button";
export function AskAboutContent({ title, text, compact = false }: AnswerUiSelection & { compact?: boolean }) {
const { onAsk, disabled } = useContext(AnswerInteractionContext);
const [running, setRunning] = useState(false);
const [error, setError] = useState<string | null>(null);
if (!onAsk) return null;
return <div className={compact ? "answer-ui-metric-ask" : undefined}><Button type="button"
size={compact ? "icon-sm" : "sm"} variant="ghost"
className={compact ? "text-muted-foreground" : "h-9 gap-1.5 text-xs text-muted-foreground"}
aria-label={compact ? `针对${title}提问` : undefined}
title={compact ? `针对${title}提问` : undefined}
disabled={disabled || running} onClick={async () => {
setRunning(true); setError(null);
try { await onAsk({ title, text }); }
catch (error) { setError(error instanceof Error ? error.message : "引用暂未带入对话,请重试。"); }
finally { setRunning(false); }
}}>
<MessageSquarePlus size={14} aria-hidden />{compact ? null : "针对这部分提问"}
</Button>{error ? <p role="status" className="text-xs text-destructive">{error}</p> : null}</div>;
}
@@ -1,7 +1,9 @@
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import userEvent from "@testing-library/user-event";
import { AnswerUiView } from "./answer-ui-view";
import { parseAnswerUiBlock } from "./contract";
vi.mock("echarts-for-react", () => ({ default: () => <div aria-label="测试图形" /> }));
function block(type: string, props: Record<string, unknown>) {
const parsed = parseAnswerUiBlock({
@@ -14,7 +16,19 @@ function block(type: string, props: Record<string, unknown>) {
return parsed;
}
describe("local interactive answer renderer", () => {
it("renders through json-render and lets readers inspect exact chart data", () => {
it("offers a named metric quote action and retains the exact value, unit and source", async () => {
const user = userEvent.setup();
const ask = vi.fn();
render(<AnswerUiView block={block("Metric", {
label: "当前压力", value: "0.3000", unit: "MPa", source: "已加载记录",
})} onAsk={ask} />);
await user.click(screen.getByRole("button", { name: "针对当前压力提问" }));
expect(ask).toHaveBeenCalledWith({
title: "当前压力", text: "当前压力:0.3000MPa\n来源:已加载记录\n引用内容块:test",
});
});
it("renders through json-render and lets readers inspect exact chart data with keyboard tabs", async () => {
const user = userEvent.setup();
render(
<AnswerUiView
block={block("Chart", {
@@ -26,10 +40,14 @@ describe("local interactive answer renderer", () => {
})}
/>
);
fireEvent.click(screen.getByRole("button", { name: /^数据$/ }));
await user.click(screen.getByRole("tab", { name: /^数据$/ }));
expect(screen.getByRole("table")).toHaveTextContent("0.3");
expect(screen.getByRole("table")).toHaveTextContent("09:00");
expect(screen.getByRole("button", { name: /^数据$/ })).toHaveAttribute("aria-pressed", "true");
expect(screen.getByRole("tab", { name: /^数据$/ })).toHaveAttribute("aria-selected", "true");
await user.keyboard("{ArrowLeft}");
expect(screen.getByRole("tab", { name: /^柱状$/ })).toHaveFocus();
expect(screen.getByRole("tab", { name: /^柱状$/ })).toHaveAttribute("aria-selected", "true");
expect(screen.queryByRole("table")).not.toBeInTheDocument();
});
it("runs map location only after a user click and reports missing IDs", async () => {
const locate = vi
@@ -54,6 +72,35 @@ describe("local interactive answer renderer", () => {
feature_ids: ["DEMO-P001", "DEMO-P002"]
});
});
it("filters and sorts loaded rows, then quotes the selected original values without sending", async () => {
const user = userEvent.setup();
const ask = vi.fn();
const submit = vi.fn();
render(<AnswerUiView block={block("Table", {
title: "监测记录", columns: ["监测点", "压力"],
rows: [["南站", "0.32"], ["北站", "0.21"], ["南站二号", "0.26"]]
})} onAsk={ask} onSubmit={submit} />);
await user.type(screen.getByRole("textbox", { name: "搜索监测记录" }), "南站");
expect(screen.getByText("2 / 3 行")).toBeInTheDocument();
await user.click(screen.getByRole("button", { name: "按压力排序" }));
const rows = screen.getAllByRole("row");
expect(rows[1]).toHaveTextContent("南站二号");
await user.click(screen.getByRole("checkbox", { name: "选择第 3 行" }));
await user.click(screen.getByRole("button", { name: "针对这部分提问" }));
expect(ask).toHaveBeenCalledWith({ title: "监测记录", text: expect.stringContaining("监测点:南站二号;压力:0.26") });
expect(submit).not.toHaveBeenCalled();
});
it("keeps form values after a failed submission", async () => {
const user = userEvent.setup();
render(<AnswerUiView block={block("FollowUpForm", {
title: "现场事实", description: "用户填写",
fields: [{ name: "detail", label: "记录", kind: "text", required: true }]
})} onSubmit={async () => { throw new Error("暂未发送"); }} />);
await user.type(screen.getByLabelText("记录(必填)"), "北站现场记录");
await user.click(screen.getByRole("button", { name: "发送补充资料" }));
expect(await screen.findByRole("status")).toHaveTextContent("暂未发送");
expect(screen.getByLabelText("记录(必填)")).toHaveValue("北站现场记录");
});
it("starts blank, requires input and sends one user message without claiming evidence is saved", async () => {
let complete!: () => void;
const submit = vi.fn(
+171 -179
View File
@@ -1,26 +1,32 @@
import { AskAboutContent } from "./answer-ui-interactions";
import { JSONUIProvider, Renderer, defineRegistry } from "@json-render/react";
import { createContext, useContext, useId, useState } from "react";
import { useContext, useId, useState } from "react";
import {
ArrowUpRight,
ChevronDown,
ClipboardList,
Database,
FileCheck2,
FlaskConical,
Lightbulb,
MapPin,
MessageSquare
} from "lucide-react";
import { Button } from "@/shared/ui/button";
import { Disclosure } from "@/shared/ui/disclosure";
import { Badge } from "@/shared/ui/badge";
import { Card, CardContent } from "@/shared/ui/card";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/shared/ui/collapsible";
import { DateTimeField } from "@/shared/ui/date-time-field";
import { Input } from "@/shared/ui/input";
import { Textarea } from "@/shared/ui/textarea";
import { cn } from "@/shared/ui/cn";
import { AgentChartView } from "../components/agent-ui-envelope-renderer";
import { InteractiveChart } from "./interactive-chart";
import { InteractiveDataTable } from "./interactive-data-table";
import { AnswerInteractionContext as InteractionContext, type AnswerUiInteractions, type AnswerUiMapTarget } from "./answer-ui-interaction-context";
export type { AnswerUiMapTarget, AnswerUiSelection } from "./answer-ui-interaction-context";
import { answerUiCatalog } from "./catalog";
import type { AnswerUiBlock } from "./contract";
export type AnswerUiMapTarget = {
layer: "junctions" | "pipes" | "valves" | "pumps" | "tanks" | "reservoirs" | "scada";
feature_ids: string[];
};
type Interactions = {
disabled: boolean;
onLocate?: (target: AnswerUiMapTarget) => Promise<unknown> | void;
onSubmit?: (text: string) => Promise<void> | void;
};
const InteractionContext = createContext<Interactions>({ disabled: true });
const { registry } = defineRegistry(answerUiCatalog, {
actions: {},
components: {
@@ -37,9 +43,12 @@ const { registry } = defineRegistry(answerUiCatalog, {
),
Section: ({ props, children }) => (
<section className="answer-ui-section">
<h3 className="text-sm font-semibold text-[var(--ink)]">{props.title}</h3>
<h3 className="flex items-center gap-2 text-sm font-semibold text-foreground">
<ClipboardList size={15} aria-hidden="true" />
{props.title}
</h3>
{props.description ? (
<p className="mt-1 text-xs leading-5 text-[var(--ink-muted)]">{props.description}</p>
<p className="mt-1 text-xs leading-5 text-muted-foreground">{props.description}</p>
) : null}
<div className="mt-3 space-y-3">{children}</div>
</section>
@@ -59,43 +68,27 @@ const { registry } = defineRegistry(answerUiCatalog, {
</p>
),
Metric: ({ props }) => (
<div className="min-w-0 py-2">
<p className="text-xs text-[var(--ink-muted)]">{props.label}</p>
<p className="mt-1 break-words text-xl font-semibold tabular-nums text-[var(--ink)]">
{props.value}
{props.unit ? <span className="ml-1 text-xs font-normal">{props.unit}</span> : null}
</p>
{props.source ? (
<p className="mt-1 text-xs leading-5 text-[var(--ink-muted)]">来源:{props.source}</p>
) : null}
</div>
<Card className="answer-ui-metric">
<CardContent className="answer-ui-metric-content p-3">
<p className="answer-ui-metric-label text-xs leading-5 text-muted-foreground">{props.label}</p>
<p className="answer-ui-metric-value break-words text-2xl font-semibold tabular-nums text-foreground">
{props.value}
{props.unit ? (
<span className="ml-1.5 text-xs font-normal text-muted-foreground">{props.unit}</span>
) : null}
</p>
{props.source ? (
<p className="answer-ui-metric-source text-[11px] leading-5 text-muted-foreground">来源:{props.source}</p>
) : null}
<AskAboutContent compact title={props.label} text={`${props.label}:${props.value}${props.unit ?? ""}${props.source ? `\n来源:${props.source}` : ""}`} />
</CardContent>
</Card>
),
Table: ({ props }) => (
<DataTable title={props.title} columns={props.columns} rows={props.rows} />
),
Chart: ({ props }) => <AnswerChart {...props} />,
Evidence: ({ props }) => (
<Disclosure label={props.title} className="answer-ui-evidence">
<div className="space-y-2 py-2 text-xs leading-5">
<p className="text-[var(--ink-muted)]">
{
(
{
observed: "查询记录",
human_input: "用户提供",
inference: "分析推断",
demo: "演练数据"
} as const
)[props.kind]
}{" "}
· {props.source}
</p>
<p className="whitespace-pre-wrap">{props.summary}</p>
{props.observed_at ? <p>记录时间:{props.observed_at}</p> : null}
{props.evidence_id ? <p>资料编号:{props.evidence_id}</p> : null}
</div>
</Disclosure>
<InteractiveDataTable key={JSON.stringify([props.columns, props.rows])} title={props.title} columns={props.columns} rows={props.rows} />
),
Chart: ({ props }) => <InteractiveChart key={JSON.stringify(props)} {...props} />,
Evidence: ({ props }) => <EvidenceCard {...props} />,
MapLocation: ({ props }) => <LocateButton {...props} />,
FollowUpForm: ({ props }) => <FollowUpForm {...props} />
}
@@ -105,11 +98,21 @@ export function AnswerUiView({
block,
disabled = false,
onLocate,
onSubmit
}: { block: AnswerUiBlock } & Partial<Interactions>) {
onSubmit,
onAsk,
submitMode = "send"
}: { block: AnswerUiBlock } & Partial<AnswerUiInteractions>) {
const [filter, setFilter] = useState("all");
const kinds = [...new Set(Object.values(block.spec.elements).filter((node) => node.type === "Evidence").map((node) => String(node.props.kind)))];
return (
<InteractionContext.Provider value={{ disabled, onLocate, onSubmit }}>
<InteractionContext.Provider value={{ disabled, onLocate, onSubmit, submitMode, evidenceFilter: filter,
onAsk: onAsk ? (selection) => onAsk({ ...selection, text: `${selection.text}\n引用内容块:${block.block_id}` }) : undefined }}>
<div className="answer-ui-root" data-answer-ui={block.block_id}>
{kinds.length > 1 ? <div className="mb-3 flex flex-wrap gap-1.5" aria-label="筛选证据类别">
{["all", ...kinds].map((kind) => <Button key={kind} variant="outline" size="sm" className="h-8 text-xs" aria-pressed={filter === kind} onClick={() => setFilter(kind)}>
{kind === "all" ? "全部依据" : evidenceKinds[kind as keyof typeof evidenceKinds].label}
</Button>)}
</div> : null}
<JSONUIProvider registry={registry}>
<Renderer spec={block.spec} registry={registry} />
</JSONUIProvider>
@@ -118,97 +121,74 @@ export function AnswerUiView({
);
}
function DataTable({
title,
columns,
rows
}: {
title: string;
columns: string[];
rows: string[][];
}) {
return (
<div className="min-w-0">
<div
role="region"
aria-label={title}
tabIndex={0}
className="overflow-x-auto rounded-lg border border-[var(--surface-divider)]"
>
<table className="w-full border-collapse text-left text-xs">
<caption className="px-3 py-2 text-left font-medium text-[var(--ink)]">{title}</caption>
<thead className="bg-[var(--surface-subtle)]">
<tr>
{columns.map((column, index) => (
<th key={index} className="whitespace-nowrap px-3 py-2 font-medium">
{column}
</th>
))}
</tr>
</thead>
<tbody>
{rows.map((row, index) => (
<tr key={index} className="border-t border-[var(--surface-divider)]">
{row.map((cell, cellIndex) => (
<td key={cellIndex} className="min-w-24 px-3 py-2 align-top">
{cell}
</td>
))}
</tr>
))}
</tbody>
</table>
</div>
</div>
);
}
type ChartProps = {
title: string;
chart_type: "line" | "bar";
x_data: string[];
series: Array<{ name: string; data: number[] }>;
source: string;
const evidenceKinds = {
observed: { label: "查询记录", icon: Database },
human_input: { label: "用户提供", icon: MessageSquare },
inference: { label: "分析推断", icon: Lightbulb },
demo: { label: "演练数据", icon: FlaskConical }
};
function AnswerChart(props: ChartProps) {
const [mode, setMode] = useState<"line" | "bar" | "table">(props.chart_type);
function EvidenceCard(props: {
title: string;
summary: string;
source: string;
kind: keyof typeof evidenceKinds;
observed_at: string | null;
evidence_id: string | null;
}) {
const [open, setOpen] = useState(false);
const meta = evidenceKinds[props.kind];
const Icon = meta.icon;
const { evidenceFilter } = useContext(InteractionContext);
if (evidenceFilter && evidenceFilter !== "all" && evidenceFilter !== props.kind) return null;
return (
<div className="min-w-0">
<div role="group" aria-label={`${props.title}显示方式`} className="mb-2 flex flex-wrap gap-1">
{(
[
["line", "折线"],
["bar", "柱状"],
["table", "数据"]
] as const
).map(([value, label]) => (
<Button
key={value}
size="sm"
variant="ghost"
aria-pressed={mode === value}
onClick={() => setMode(value)}
>
{label}
</Button>
))}
</div>
{mode === "table" ? (
<DataTable
title={props.title}
columns={["时间或类别", ...props.series.map((series) => series.name)]}
rows={props.x_data.map((label, index) => [
label,
...props.series.map((series) => String(series.data[index]))
])}
/>
) : (
<AgentChartView chart={{ ...props, chart_type: mode }} />
)}
<p className="mt-2 whitespace-pre-wrap text-xs leading-5 text-[var(--ink-muted)]">
来源:{props.source}
</p>
</div>
<Collapsible open={open} onOpenChange={setOpen} className="answer-ui-evidence">
<CollapsibleTrigger asChild>
<Button
variant="ghost"
type="button"
className="h-auto min-h-12 w-full justify-start gap-2.5 whitespace-normal rounded-xl px-3 py-3 text-left shadow-none"
>
<span className="answer-ui-evidence-icon">
<Icon size={16} aria-hidden="true" />
</span>
<span className="min-w-0 flex-1">
<span className="block text-xs font-medium">{props.title}</span>
<span className="mt-0.5 block break-words text-[11px] font-normal text-muted-foreground">
{props.source}
</span>
</span>
<Badge variant="outline" className="shrink-0 px-1.5 text-[10px] font-normal">
{meta.label}
</Badge>
<ChevronDown
size={14}
className={cn("shrink-0", open && "rotate-180")}
aria-hidden="true"
/>
</Button>
</CollapsibleTrigger>
<CollapsibleContent className="px-3 pb-3 text-xs leading-6">
<p className="whitespace-pre-wrap border-t border-border pt-3">{props.summary}</p>
{props.observed_at || props.evidence_id ? (
<dl className="mt-3 grid gap-1 text-[11px] text-muted-foreground">
{props.observed_at ? (
<div>
<dt className="inline">记录时间:</dt>
<dd className="inline tabular-nums">{props.observed_at}</dd>
</div>
) : null}
{props.evidence_id ? (
<div>
<dt className="inline">资料编号:</dt>
<dd className="inline break-all font-mono">{props.evidence_id}</dd>
</div>
) : null}
</dl>
) : null}
<AskAboutContent title={props.title} text={`${props.summary}\n来源:${props.source}\n类别:${meta.label}${props.evidence_id ? `\n资料编号:${props.evidence_id}` : ""}${props.observed_at ? `\n记录时间:${props.observed_at}` : ""}`} />
</CollapsibleContent>
</Collapsible>
);
}
@@ -221,37 +201,43 @@ function LocateButton({
const [running, setRunning] = useState(false);
const [feedback, setFeedback] = useState<string | null>(null);
return (
<div>
<Button
size="sm"
variant="outline"
disabled={disabled || running || !onLocate}
onClick={async () => {
setRunning(true);
setFeedback(null);
try {
const result = await onLocate?.(target);
const output = result as { located_ids?: string[]; missing_ids?: string[] } | undefined;
setFeedback(
output?.missing_ids?.length
? `已定位 ${output.located_ids?.length ?? 0} 个,另有 ${output.missing_ids.length} 个未找到`
: "已定位到地图"
);
} catch (error) {
setFeedback(error instanceof Error ? error.message : "地图定位失败");
} finally {
setRunning(false);
}
}}
>
{running ? "正在定位…" : label}
</Button>
<p className="mt-1 text-xs leading-5 text-[var(--ink-muted)]">依据:{source}</p>
{feedback ? (
<p role="status" className="mt-1 text-xs leading-5">
{feedback}
</p>
) : null}
<div className="answer-ui-location">
<MapPin size={17} className="mt-1 shrink-0 text-muted-foreground" aria-hidden="true" />
<div className="min-w-0 flex-1">
<Button
size="sm"
variant="outline"
disabled={disabled || running || !onLocate}
onClick={async () => {
setRunning(true);
setFeedback(null);
try {
const result = await onLocate?.(target);
if (result === false) throw new Error("关联要素暂不可定位,请检查地图提示。");
const output = result as
{ located_ids?: string[]; missing_ids?: string[] } | undefined;
setFeedback(
output?.missing_ids?.length
? `已定位 ${output.located_ids?.length ?? 0} 个,另有 ${output.missing_ids.length} 个未找到`
: "已定位到地图"
);
} catch (error) {
setFeedback(error instanceof Error ? error.message : "地图定位失败");
} finally {
setRunning(false);
}
}}
>
{running ? "正在定位…" : label}
<ArrowUpRight size={14} aria-hidden="true" />
</Button>
<p className="mt-1 text-xs leading-5 text-[var(--ink-muted)]">依据:{source}</p>
{feedback ? (
<p role="status" className="mt-1 text-xs leading-5">
{feedback}
</p>
) : null}
</div>
</div>
);
}
@@ -271,7 +257,7 @@ function FollowUpForm({
description: string;
fields: FormField[];
}) {
const { disabled, onSubmit } = useContext(InteractionContext);
const { disabled, onSubmit, submitMode } = useContext(InteractionContext);
const prefix = useId();
const [values, setValues] = useState<Record<string, string>>({});
const [submitting, setSubmitting] = useState(false);
@@ -307,7 +293,7 @@ function FollowUpForm({
await onSubmit(
`我补充以下资料,请按用户提供的信息处理,说明保存或调查的实际结果:\n${entries.join("\n")}`
);
setFeedback("资料已发送,请查看 Agent 回复。");
setFeedback(submitMode === "draft" ? "资料已带入对话,请确认后发送。" : "资料已发送,请查看 Agent 回复。");
} catch (error) {
setFeedback(error instanceof Error ? error.message : "资料发送失败,请重试。");
} finally {
@@ -315,9 +301,14 @@ function FollowUpForm({
}
}}
>
<div>
<h4 className="text-sm font-semibold">{title}</h4>
<p className="mt-1 text-xs leading-5 text-[var(--ink-muted)]">{description}</p>
<div className="flex items-start gap-2.5">
<span className="answer-ui-evidence-icon">
<FileCheck2 size={16} aria-hidden="true" />
</span>
<div className="min-w-0">
<h4 className="text-sm font-semibold">{title}</h4>
<p className="mt-1 text-xs leading-5 text-[var(--ink-muted)]">{description}</p>
</div>
</div>
{fields.map((field) =>
field.kind === "datetime" ? (
@@ -347,6 +338,7 @@ function FollowUpForm({
/>
) : (
<Input
className="h-10"
id={`${prefix}-${field.name}`}
type="number"
value={values[field.name] ?? ""}
@@ -367,7 +359,7 @@ function FollowUpForm({
variant="outline"
disabled={disabled || submitting || !onSubmit}
>
{submitting ? "正在发送…" : "发送补充资料"}
{submitting ? submitMode === "draft" ? "正在处理…" : "正在发送…" : submitMode === "draft" ? "带入对话" : "发送补充资料"}
</Button>
{feedback ? (
<p role="status" className="text-xs leading-5">
+13
View File
@@ -16,6 +16,19 @@ const payloadSchema = z
})
.strict();
// Stored reports remain readable if one presentation component is no longer supported.
export const storedAnswerUiBlockSchema = z.object({
version: z.string(),
block_id: key,
fallback_text: z.string().min(1).max(4000),
spec: z.unknown()
});
export const reportUiBlocksSchema = z.array(z.object({
block: storedAnswerUiBlockSchema,
evidence_refs: z.array(z.string().min(1).max(128)).min(1).max(100)
}).strict()).max(8);
export type StoredReportUiBlock = z.infer<typeof reportUiBlocksSchema>[number];
export type AnswerUiBlock = {
version: typeof ANSWER_UI_VERSION;
block_id: string;
@@ -0,0 +1,126 @@
import { useState } from "react";
import ReactECharts from "echarts-for-react";
import { BarChart3, ChevronDown, Database, SlidersHorizontal, Table2, TrendingUp } from "lucide-react";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/shared/ui/card";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/shared/ui/tabs";
import { Button } from "@/shared/ui/button";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/ui/select";
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/shared/ui/collapsible";
import { InteractiveDataTable } from "./interactive-data-table";
import { AskAboutContent } from "./answer-ui-interactions";
export type AnswerChartProps = {
title: string;
chart_type: "line" | "bar";
x_data: string[];
series: Array<{ name: string; data: number[] }>;
source: string;
};
const colors = ["#2563eb", "#059669", "#d97706", "#7c3aed", "#0891b2", "#e11d48", "#475569", "#a16207"];
function PointSelect({ label, value, labels, onChange }: {
label: string; value: number; labels: string[]; onChange: (value: number) => void;
}) {
return <Select value={String(value)} onValueChange={(next) => onChange(Number(next))}>
<SelectTrigger aria-label={label} className="h-9 min-w-0 flex-1 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>{labels.map((text, index) => <SelectItem key={index} value={String(index)}>{text}</SelectItem>)}</SelectContent>
</Select>;
}
export function InteractiveChart(props: AnswerChartProps) {
const [view, setView] = useState<string>(props.chart_type);
const [hidden, setHidden] = useState<number[]>([]);
const [range, setRange] = useState<[number, number]>([0, props.x_data.length - 1]);
const [point, setPoint] = useState(0);
const visible = props.series.filter((_, index) => !hidden.includes(index));
const labels = props.x_data.slice(range[0], range[1] + 1);
const pointIndex = Math.min(range[1], Math.max(range[0], point));
const fullRange = range[0] === 0 && range[1] === props.x_data.length - 1;
const option = (type: "line" | "bar") => ({
animation: false,
color: colors.filter((_, index) => !hidden.includes(index)),
aria: { enabled: true },
tooltip: { trigger: "axis", renderMode: "richText" },
grid: { top: 16, right: 12, bottom: 38, left: 12, containLabel: true },
xAxis: { type: "category", data: labels, axisLabel: { fontSize: 11, color: "#64748b", hideOverlap: true } },
yAxis: { type: "value", axisLabel: { fontSize: 11, color: "#64748b" }, splitLine: { lineStyle: { color: "#e2e8f0" } } },
series: visible.map((series) => ({ name: series.name, type, data: series.data.slice(range[0], range[1] + 1),
showSymbol: true, symbolSize: 7, emphasis: { focus: "series" } }))
});
return <Card className="answer-ui-chart overflow-hidden">
<CardHeader className="space-y-1 px-3.5 pb-3 pt-3.5">
<CardTitle className="flex items-center gap-2 text-xs leading-5 tracking-normal"><TrendingUp size={15} />{props.title}</CardTitle>
<CardDescription className="text-[11px]">{labels.length} / {props.x_data.length} 个数据点 · {visible.length} 组序列</CardDescription>
</CardHeader>
<CardContent className="space-y-3 px-3.5 pb-3.5 pt-0">
<Tabs value={view} onValueChange={setView}>
<TabsList aria-label={`${props.title}显示方式`} className="mb-3 grid w-full grid-cols-3">
<TabsTrigger value="line"><TrendingUp size={13} />折线</TabsTrigger>
<TabsTrigger value="bar"><BarChart3 size={13} />柱状</TabsTrigger>
<TabsTrigger value="table"><Table2 size={13} />数据</TabsTrigger>
</TabsList>
<div className="answer-ui-chart-series mb-2 flex flex-wrap gap-2" aria-label="显示的数据序列">
{props.series.map((series, index) => <Button key={index} size="sm" variant="outline"
className="h-8 gap-1.5 text-[11px]" aria-pressed={!hidden.includes(index)}
disabled={visible.length === 1 && !hidden.includes(index)}
onClick={() => setHidden((current) => current.includes(index) ? current.filter((item) => item !== index) : [...current, index])}>
<span className="size-2 rounded-full" style={{ background: hidden.includes(index) ? "#cbd5e1" : colors[index] }} />{series.name}
</Button>)}
</div>
<Collapsible className="mb-2">
<div className="flex flex-wrap items-center justify-between gap-x-2 gap-y-1">
<CollapsibleTrigger asChild>
<Button type="button" variant="ghost" size="sm" aria-label="筛选数据范围"
className="group h-8 gap-1.5 px-1.5 font-normal text-muted-foreground">
<SlidersHorizontal size={13} aria-hidden />数据范围
<ChevronDown size={13} aria-hidden className="group-data-[state=open]:rotate-180" />
</Button>
</CollapsibleTrigger>
<span className="text-[11px] text-muted-foreground">
{fullRange ? "全部数据" : `${props.x_data[range[0]]} 至 ${props.x_data[range[1]]}`}
</span>
</div>
<CollapsibleContent className="space-y-2 rounded-lg border bg-muted/30 p-2.5">
<div className="flex items-center gap-2">
<PointSelect label="区间起点" value={range[0]} labels={props.x_data}
onChange={(start) => setRange([start, Math.max(start, range[1])])} />
<span className="text-xs text-muted-foreground">至</span>
<PointSelect label="区间终点" value={range[1]} labels={props.x_data}
onChange={(end) => setRange([Math.min(range[0], end), end])} />
</div>
<Button type="button" variant="ghost" size="sm" disabled={fullRange}
onClick={() => setRange([0, props.x_data.length - 1])}>重置范围</Button>
</CollapsibleContent>
</Collapsible>
{(["line", "bar"] as const).map((type) => <TabsContent key={type} value={type}>
<div role="img" aria-label={props.title}>
<ReactECharts option={option(type)} opts={{ renderer: "svg" }} notMerge style={{ height: 220 }}
onEvents={{ click: (event: { componentType?: string; dataIndex?: number }) => {
if (event.componentType === "series" && typeof event.dataIndex === "number")
setPoint(range[0] + event.dataIndex);
} }} />
</div>
</TabsContent>)}
<TabsContent value="table" forceMount style={view === "table" ? undefined : { display: "none" }}>
<InteractiveDataTable key={JSON.stringify([hidden, range])} title={props.title} columns={["时间或类别", ...visible.map((series) => series.name)]}
rows={labels.map((label, index) => [label, ...visible.map((series) => String(series.data[range[0] + index]))])}
source={props.source} />
</TabsContent>
</Tabs>
<div className="rounded-lg bg-muted/40 p-2.5">
<div className="flex items-center gap-2"><span className="text-xs text-muted-foreground">查看数据点</span>
<PointSelect label="选择数据点" value={pointIndex - range[0]} labels={labels} onChange={(index) => setPoint(range[0] + index)} />
</div>
<dl className="my-2 space-y-1.5 text-xs">
{visible.map((series, index) => <div key={index} className="flex items-baseline justify-between gap-3">
<dt className="min-w-0 text-muted-foreground">{series.name}</dt>
<dd className="shrink-0 font-medium tabular-nums">{series.data[pointIndex]}</dd>
</div>)}
</dl>
<AskAboutContent title={`${props.title} · ${props.x_data[pointIndex]}`}
text={`${props.x_data[pointIndex]}\n${visible.map((series) => `${series.name}:${series.data[pointIndex]}`).join("\n")}\n来源:${props.source}`} />
</div>
<p className="flex items-start gap-1.5 border-t pt-2.5 text-[11px] leading-5 text-muted-foreground">
<Database size={12} className="mt-1 shrink-0" /><span>来源:{props.source}。区间操作仅查看已加载数据。</span>
</p>
</CardContent>
</Card>;
}
@@ -0,0 +1,70 @@
import { useMemo, useState } from "react";
import { ArrowDown, ArrowUp, ArrowUpDown } from "lucide-react";
import { Input } from "@/shared/ui/input";
import { Button } from "@/shared/ui/button";
import { Checkbox } from "@/shared/ui/checkbox";
import { cn } from "@/shared/ui/cn";
import { Table, TableBody, TableCaption, TableCell, TableHead, TableHeader, TableRow } from "@/shared/ui/table";
import { AskAboutContent } from "./answer-ui-interactions";
export function InteractiveDataTable({ title, columns, rows, source }: {
title: string; columns: string[]; rows: string[][]; source?: string;
}) {
const [query, setQuery] = useState("");
const [sort, setSort] = useState<{ column: number; descending: boolean } | null>(null);
const [selection, setSelection] = useState<number[]>([]);
const filtered = useMemo(() => {
const items = rows.map((cells, id) => ({ cells, id }))
.filter(({ cells }) => cells.join(" ").toLocaleLowerCase().includes(query.trim().toLocaleLowerCase()));
if (sort) items.sort((a, b) => {
const aValue = a.cells[sort.column], bValue = b.cells[sort.column];
const compared = /^[-+]?\d+(\.\d+)?%?$/.test(aValue) && /^[-+]?\d+(\.\d+)?%?$/.test(bValue)
? Number.parseFloat(aValue) - Number.parseFloat(bValue)
: aValue.localeCompare(bValue, "zh-CN", { numeric: true });
return sort.descending ? -compared : compared;
});
return items;
}, [rows, sort, query]);
const selected = filtered.filter(({ id }) => selection.includes(id));
const quote = selected.map(({ cells }) => cells.map((cell, index) => `${columns[index]}:${cell}`).join(";")).join("\n");
return <div className="min-w-0 space-y-2" data-interactive-table>
<div className="flex flex-wrap items-center gap-2">
<Input aria-label={`搜索${title}`} placeholder="搜索当前数据" value={query} className="h-9 min-w-0 flex-1 text-xs"
onChange={(event) => { setQuery(event.currentTarget.value); setSelection([]); }} />
<span className="text-[11px] tabular-nums text-muted-foreground">{filtered.length} / {rows.length} 行</span>
</div>
<div role="region" aria-label={title} tabIndex={0}
className="answer-ui-table overflow-x-auto rounded-lg border border-border focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring">
<Table>
<TableCaption className="caption-top font-medium">{title}</TableCaption>
<TableHeader className="bg-muted/50"><TableRow>
<TableHead scope="col" className="w-10"><span className="sr-only">选择行</span></TableHead>
{columns.map((column, index) => <TableHead key={index} scope="col" className="whitespace-nowrap"
aria-sort={sort?.column === index ? sort.descending ? "descending" : "ascending" : "none"}>
<Button size="sm" variant="ghost" className="h-9 gap-1 px-1 text-xs" aria-label={`按${column}排序`}
onClick={() => setSort((current) => current?.column === index
? current.descending ? null : { column: index, descending: true }
: { column: index, descending: false })}>
{column}{sort?.column === index ? sort.descending ? <ArrowDown size={12} /> : <ArrowUp size={12} /> : <ArrowUpDown size={12} />}
</Button>
</TableHead>)}
</TableRow></TableHeader>
<TableBody>
{filtered.map(({ cells, id }) => <TableRow key={id} data-state={selection.includes(id) ? "selected" : undefined}>
<TableCell className="w-10"><Checkbox aria-label={`选择第 ${id + 1} 行`} checked={selection.includes(id)}
onChange={(event) => setSelection((current) => event.target.checked ? [...current, id] : current.filter((value) => value !== id))} /></TableCell>
{cells.map((cell, index) => <TableCell key={index}
className={cn("min-w-24", /^[-+]?\d+(\.\d+)?%?$/.test(cell) && "text-right tabular-nums")}>{cell}</TableCell>)}
</TableRow>)}
{!filtered.length ? <TableRow><TableCell colSpan={columns.length + 1} className="py-6 text-center text-xs text-muted-foreground">
{rows.length ? "当前筛选没有匹配的数据。" : "没有已加载的数据。"}
</TableCell></TableRow> : null}
</TableBody>
</Table>
</div>
{selected.length ? <div className="flex flex-wrap items-center justify-between gap-1">
<span className="text-xs text-muted-foreground">已选 {selected.length} 行</span>
<AskAboutContent title={title} text={`${quote}${source ? `\n来源:${source}` : ""}`} />
</div> : <p className="text-[11px] text-muted-foreground">筛选与排序仅作用于已加载数据;勾选行可继续提问。</p>}
</div>;
}
@@ -0,0 +1,34 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { createAgentApiClient } from "./client";
afterEach(() => { vi.restoreAllMocks(); vi.unstubAllGlobals(); });
describe("authenticated session exports", () => {
it("fetches only Agent session files with identity and project headers", async () => {
const fetchMock = vi.fn(async () => new Response("ZIP", { headers: { "Content-Type": "application/zip" } }));
vi.stubGlobal("fetch", fetchMock);
vi.stubGlobal("URL", class extends URL {
static createObjectURL = vi.fn(() => "blob:fixture");
static revokeObjectURL = vi.fn();
});
const click = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
const client = createAgentApiClient("https://agent.test", { getAccessToken: async () => "FIXTURE", getProjectId: async () => "project-a" });
const path = "/api/v1/session/session-a/files/mcp-11111111-1111-1111-1111-111111111111.zip";
await client.downloadFile(path);
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
expect(url).toBe(`https://agent.test${path}`);
expect(new Headers(init.headers).get("Authorization")).toBe("Bearer FIXTURE");
expect(new Headers(init.headers).get("X-Project-Id")).toBe("project-a");
expect(init.redirect).toBe("error");
expect(click).toHaveBeenCalledOnce();
});
it("rejects arbitrary URLs and paths before requesting any credential", async () => {
const getAccessToken = vi.fn();
const client = createAgentApiClient("https://agent.test", { getAccessToken });
for (const path of ["https://foreign.test/file.zip", "/api/v1/admin/files/a.zip", "/api/v1/session/s/files/secret.env", "/api/v1/session/s/files/../owner.json"]) {
await expect(client.downloadFile(path)).rejects.toThrow("无效");
}
expect(getAccessToken).not.toHaveBeenCalled();
});
});
+34 -3
View File
@@ -2,16 +2,45 @@ import { afterEach, describe, expect, it, vi } from "vitest";
import { createAgentApiClient } from "./client";
describe("Agent prompt suggestions", () => {
it("uses owned topic endpoints and retains full-text hits from another topic", async () => {
const topic = { id: "topic-a", name: "城南压力问题", createdAt: "2026-10-22T01:00:00Z", updatedAt: "2026-10-22T01:00:00Z" };
const fetchMock = vi.fn()
.mockResolvedValueOnce(Response.json({ topics: [topic] }))
.mockResolvedValueOnce(Response.json({ sessions: [{ id: "session-b", title: "另一段对话", topic_id: "topic-b", topic_name: "检修事件", search_snippet: "正文中的南桥阀门", purpose: "task_collaboration" }], has_more: false }))
.mockResolvedValueOnce(Response.json({ session_id: "session-b", topic_id: "topic-a" }))
.mockResolvedValueOnce(new Response(null, { status: 204 }));
vi.stubGlobal("fetch", fetchMock);
const client = createAgentApiClient("http://agent.local", { getAccessToken: async () => "token", getProjectId: async () => "project-a" });
expect(await client.listTopics()).toEqual([topic]);
const result = await client.listSessionPage({ q: "南桥阀门", includeCollaboration: true });
expect(result.sessions[0]).toMatchObject({ title: "另一段对话", topicId: "topic-b", topicName: "检修事件", searchSnippet: "正文中的南桥阀门", purpose: "task_collaboration" });
const query = new URL(String(fetchMock.mock.calls[1]?.[0])).searchParams;
expect(query.get("q")).toBe("南桥阀门");
expect(query.has("topic_id")).toBe(false);
expect(query.get("include_collaboration")).toBe("true");
await client.moveSessionToTopic("session-b", "topic-a");
expect(JSON.parse(String(fetchMock.mock.calls[2]?.[1]?.body))).toEqual({ topic_id: "topic-a" });
await client.deleteTopic("topic-a");
expect(String(fetchMock.mock.calls[3]?.[0])).toContain("/topics/topic-a");
for (const [, init] of fetchMock.mock.calls) {
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer token");
expect(new Headers(init?.headers).get("X-Project-Id")).toBe("project-a");
}
});
it("submits and edits pending input through the scoped Responses and session endpoints", async () => {
const input = { id: `msg_${"1".repeat(32)}`, text: "补充压力测点", delivery: "steer", status: "pending" };
const fetchMock = vi.fn().mockResolvedValueOnce(Response.json(input)).mockResolvedValueOnce(Response.json({ items: [input] }))
.mockResolvedValueOnce(Response.json({ ...input, delivery: "queue" }));
.mockResolvedValueOnce(Response.json({ ...input, delivery: "queue" }))
.mockResolvedValueOnce(Response.json({ ...input, status: "cancelled" }));
vi.stubGlobal("fetch", fetchMock);
const client = createAgentApiClient("http://agent.local", { getAccessToken: async () => "token", getProjectId: async () => "project" });
await expect(client.submitResponseInput("session-1", input.text, "steer", input.id)).resolves.toEqual(input);
expect(JSON.parse(String(fetchMock.mock.calls[0]?.[1]?.body))).toEqual({ input: input.text, conversation: "session-1", stream: false, tjwater: { delivery: "steer", input_id: input.id } });
await expect(client.listResponseInputs("session-1")).resolves.toEqual([input]);
await expect(client.updateResponseInput("session-1", input.id, "queue")).resolves.toEqual({ ...input, delivery: "queue" });
await expect(client.cancelResponseInput("session-1", input.id)).resolves.toEqual({ ...input, status: "cancelled" });
expect(fetchMock.mock.calls[3]?.[1]?.method).toBe("DELETE");
expect(String(fetchMock.mock.calls[0]?.[0])).toBe("http://agent.local/api/v1/responses");
expect(String(fetchMock.mock.calls[2]?.[0])).toContain(`/api/v1/session/session-1/inputs/${input.id}`);
for (const [, request] of fetchMock.mock.calls) {
@@ -83,7 +112,8 @@ describe("Agent API client sessions", () => {
runStatus: "running",
purpose: "ordinary_chat",
taskId: undefined,
trigger: undefined
trigger: undefined,
topicId: null, topicName: undefined, searchSnippet: undefined
},
{
id: "old",
@@ -96,7 +126,8 @@ describe("Agent API client sessions", () => {
runStatus: undefined,
purpose: "ordinary_chat",
taskId: undefined,
trigger: undefined
trigger: undefined,
topicId: null, topicName: undefined, searchSnippet: undefined
}
]);
});
+85 -8
View File
@@ -39,12 +39,15 @@ export type AgentModelsResponse = {
};
export type AgentInputDelivery = "steer" | "queue";
export type AgentResponseInput = { id: string; text: string; delivery: AgentInputDelivery; status: "pending" | "delivered" };
export type AgentResponseInput = { id: string; text: string; delivery: AgentInputDelivery; status: "pending" | "delivered" | "cancelled" };
export type AgentTopic = { id: string; name: string; createdAt: string; updatedAt: string };
export type AgentChatSession = {
id?: string;
session_id: string;
title?: string;
topic_id?: string | null;
status?: string;
run_status?: AgentRunStatus;
is_streaming?: boolean;
@@ -64,12 +67,16 @@ export type AgentChatSessionSummary = {
trigger?: { subjectId: string; workflow: "water_quality_complaint"; occurredAt: string };
id: string;
title: string;
topicId?: string | null;
topicName?: string;
searchSnippet?: string;
createdAt: number;
updatedAt: number;
status?: string;
parentSessionId?: string;
isStreaming?: boolean;
runStatus?: AgentRunStatus;
needsInput?: boolean;
purpose: AgentSessionPurpose;
taskId?: string;
};
@@ -89,10 +96,15 @@ export type AgentPromptSuggestion = {
activityId: string | null;
};
export type AgentMessagePagination = { hasMore: boolean; beforeCursor: string | null };
export type AgentSessionPage = { sessions: AgentChatSessionSummary[]; hasMore: boolean; nextCursor: string | null };
export type AgentHistoryMessagePage = { messages: unknown[]; messagePage: AgentMessagePagination };
export type AgentLoadedChatSession = AgentChatSessionSummary & {
sessionId: string;
isTitleManuallyEdited: boolean;
messages: unknown[];
messagePage?: AgentMessagePagination;
};
export type AgentSessionStreamDataEventType =
@@ -124,6 +136,7 @@ export type AgentSessionStreamEvent =
| {
type: "state";
executionPlans?: unknown[];
messagePage?: AgentMessagePagination;
sessionId: string;
messages: unknown[];
isStreaming: boolean;
@@ -136,20 +149,30 @@ export type AgentSessionStreamEvent =
};
export type AgentApiClient = {
downloadFile: (path: string) => Promise<void>;
submitResponseInput: (sessionId: string, text: string, delivery: AgentInputDelivery, id: string) => Promise<AgentResponseInput>;
listResponseInputs: (sessionId: string) => Promise<AgentResponseInput[]>;
updateResponseInput: (sessionId: string, id: string, delivery: AgentInputDelivery) => Promise<AgentResponseInput>;
cancelResponseInput: (sessionId: string, id: string) => Promise<AgentResponseInput>;
listAgentMessages: (sessionId: string, options?: { cursor?: string; signal?: AbortSignal }) => Promise<AgentMessagePage>;
streamAgentMessages: (sessionId: string, options: { signal?: AbortSignal; onMessage: () => void }) => Promise<void>;
generatePromptSuggestions: (activities: AgentRecentActivity[], model: string, signal?: AbortSignal) => Promise<AgentPromptSuggestion[]>;
createSession: (options?: { triggerContext?: AgentEventTriggerContext }) => Promise<AgentChatSession>;
createSession: (options?: { triggerContext?: AgentEventTriggerContext; topicId?: string }) => Promise<AgentChatSession>;
listSessions: (options?: { purpose?: AgentSessionPurpose; taskId?: string }) => Promise<AgentChatSessionSummary[]>;
listSessionPage: (options?: { q?: string; cursor?: string; limit?: number; purpose?: AgentSessionPurpose; topicId?: string; includeCollaboration?: boolean; signal?: AbortSignal }) => Promise<AgentSessionPage>;
listTopics: () => Promise<AgentTopic[]>;
createTopic: (name: string) => Promise<AgentTopic>;
renameTopic: (id: string, name: string) => Promise<AgentTopic>;
deleteTopic: (id: string) => Promise<void>;
moveSessionToTopic: (sessionId: string, topicId: string | null) => Promise<void>;
loadOlderMessages: (sessionId: string, before: string, signal?: AbortSignal) => Promise<AgentHistoryMessagePage>;
createTaskCollaborationSession: (taskId: string) => Promise<AgentChatSession>;
loadSession: (sessionId: string) => Promise<AgentLoadedChatSession | null>;
loadSession: (sessionId: string, options?: { messageLimit?: number; signal?: AbortSignal }) => Promise<AgentLoadedChatSession | null>;
streamSession: (
sessionId: string,
options: {
signal?: AbortSignal;
messageLimit?: number;
onEvent: (event: AgentSessionStreamEvent) => void;
}
) => Promise<void>;
@@ -218,6 +241,19 @@ export function createAgentApiClient(
};
return {
async downloadFile(path) {
const match = /^\/api\/v1(\/session\/[^/?#]+\/files\/mcp-[a-f0-9-]{36}\.(?:zip|xlsx))$/.exec(path);
if (!match) throw new Error("无效的会话文件地址");
const response = await request(match[1], { redirect: "error" });
if (!response.ok) throw new Error("文件不可用或当前账号无权下载");
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = path.split("/").at(-1) ?? "export.zip";
anchor.click();
setTimeout(() => URL.revokeObjectURL(url), 1000);
},
async submitResponseInput(sessionId, text, delivery, id) {
return requestJson<AgentResponseInput>("/responses", {
method: "POST", headers: { "Content-Type": "application/json" },
@@ -233,6 +269,11 @@ export function createAgentApiClient(
method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ delivery })
});
},
async cancelResponseInput(sessionId, id) {
return requestJson<AgentResponseInput>(`/session/${encodeURIComponent(sessionId)}/inputs/${encodeURIComponent(id)}`, {
method: "DELETE"
});
},
async generatePromptSuggestions(activities, model, signal) {
const result = await requestJson<unknown>("/suggestions", {
method: "POST",
@@ -260,7 +301,7 @@ export function createAgentApiClient(
return requestJson<AgentChatSession>("/session", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ trigger_context: options?.triggerContext })
body: JSON.stringify({ trigger_context: options?.triggerContext, topic_id: options?.topicId })
});
},
@@ -274,6 +315,31 @@ export function createAgentApiClient(
return (payload.sessions ?? []).map(toSessionSummary).filter(isPresent).sort(compareSessionSummaries);
},
async listSessionPage(options) {
const params = new URLSearchParams({ purpose: options?.purpose ?? "ordinary_chat", limit: String(options?.limit ?? 30) });
if (options?.q) params.set("q", options.q);
if (options?.topicId) params.set("topic_id", options.topicId);
if (options?.includeCollaboration) params.set("include_collaboration", "true");
if (options?.cursor) params.set("cursor", options.cursor);
const payload = await requestJson<{ sessions?: unknown[]; has_more?: boolean; next_cursor?: string | null }>(
`/sessions?${params}`, { signal: options?.signal });
return { sessions: (payload.sessions ?? []).map(toSessionSummary).filter(isPresent),
hasMore: payload.has_more === true, nextCursor: typeof payload.next_cursor === "string" ? payload.next_cursor : null };
},
async listTopics() { return (await requestJson<{ topics: AgentTopic[] }>("/topics")).topics; },
async createTopic(name) { return requestJson<AgentTopic>("/topics", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) }); },
async renameTopic(id, name) { return requestJson<AgentTopic>(`/topics/${encodeURIComponent(id)}`, { method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ name }) }); },
async deleteTopic(id) { await requestJson(`/topics/${encodeURIComponent(id)}`, { method: "DELETE" }); },
async moveSessionToTopic(sessionId, topicId) { await requestJson(`/session/${encodeURIComponent(sessionId)}/topic`, {
method: "PATCH", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ topic_id: topicId }),
}); },
async loadOlderMessages(sessionId, before, signal) {
const query = new URLSearchParams({ limit: "40", before });
const payload = await requestJson<{ messages?: unknown[]; message_page?: unknown }>(
`/session/${encodeURIComponent(sessionId)}/messages?${query}`, { signal });
return { messages: payload.messages ?? [], messagePage: readMessagePagination(payload.message_page) ?? { hasMore: false, beforeCursor: null } };
},
async createTaskCollaborationSession(taskId) {
return requestJson<AgentChatSession>(
`/task/${encodeURIComponent(taskId)}/collaboration/session`,
@@ -293,8 +359,9 @@ export function createAgentApiClient(
});
},
async loadSession(sessionId) {
const response = await request(`/session/${encodeURIComponent(sessionId)}`);
async loadSession(sessionId, options) {
const query = options?.messageLimit ? `?message_limit=${options.messageLimit}` : "";
const response = await request(`/session/${encodeURIComponent(sessionId)}${query}`, { signal: options?.signal });
const text = await response.text();
const data = text ? JSON.parse(text) : null;
@@ -310,7 +377,7 @@ export function createAgentApiClient(
async streamSession(sessionId, options) {
const response = await request(
`/session/${encodeURIComponent(sessionId)}/stream`,
`/session/${encodeURIComponent(sessionId)}/stream${options.messageLimit ? `?message_limit=${options.messageLimit}` : ""}`,
{ signal: options.signal }
);
@@ -564,6 +631,9 @@ function toSessionSummary(value: unknown): AgentChatSessionSummary | null {
return {
id,
title: normalizeTitle(value.title),
topicId: typeof value.topic_id === "string" ? value.topic_id : null,
topicName: typeof value.topic_name === "string" ? value.topic_name : undefined,
searchSnippet: typeof value.search_snippet === "string" ? value.search_snippet : undefined,
createdAt: toMillis(value.created_at),
updatedAt: toMillis(value.updated_at),
status: typeof value.status === "string" ? value.status : undefined,
@@ -591,7 +661,8 @@ function toLoadedSession(value: unknown): AgentLoadedChatSession {
sessionId: typeof value.session_id === "string" ? value.session_id : summary.id,
isTitleManuallyEdited:
typeof value.is_title_manually_edited === "boolean" ? value.is_title_manually_edited : false,
messages: Array.isArray(value.messages) ? value.messages : []
messages: Array.isArray(value.messages) ? value.messages : [],
messagePage: readMessagePagination(value.message_page)
};
}
@@ -657,6 +728,7 @@ function emitSessionSseEvent(
onEvent({
type: "state",
executionPlans: Array.isArray(data.execution_plans) ? data.execution_plans : undefined,
messagePage: readMessagePagination(data.message_page),
sessionId,
messages: Array.isArray(data.messages) ? data.messages : [],
isStreaming: data.is_streaming === true,
@@ -717,3 +789,8 @@ function compareSessionSummaries(left: AgentChatSessionSummary, right: AgentChat
return right.id.localeCompare(left.id);
}
function readMessagePagination(value: unknown): AgentMessagePagination | undefined {
if (!isRecord(value)) return undefined;
return { hasMore: value.has_more === true, beforeCursor: typeof value.before_cursor === "string" ? value.before_cursor : null };
}
@@ -32,7 +32,7 @@ describe("Responses transport", () => {
const messages = [{ id: "old", role: "assistant", parts: [{ type: "text", text: "旧回答" }] }, { id: "new", role: "user", parts: [{ type: "text", text: "继续核查" }] }] as UIMessage[];
expect(createResponseRequest(messages, { conversation: "owned", approvalMode: "always" })).toEqual({
input: [{ role: "user", content: [{ type: "input_text", text: "继续核查" }] }], stream: true, conversation: "owned",
tjwater: { approval_mode: "always", capabilities: [] },
tjwater: { client_message_id: "new", approval_mode: "always", capabilities: [] },
});
});
it("decodes split UTF-8 and CRLF while retaining approval events", async () => {
@@ -4,7 +4,7 @@ const record = (value: unknown): value is Record<string, unknown> => typeof valu
export function createResponseRequest(messages: UIMessage[], options: {
conversation?: string; model?: string; approvalMode?: string; capabilities?: string[];
triggerContext?: unknown; taskContext?: unknown;
triggerContext?: unknown; taskContext?: unknown; topicId?: string;
}) {
const latest = [...messages].reverse().find((message) => message.role === "user");
const text = latest?.parts.filter((part) => part.type === "text").map((part) => part.text).join("\n").trim();
@@ -13,7 +13,7 @@ export function createResponseRequest(messages: UIMessage[], options: {
input: [{ role: "user", content: [{ type: "input_text", text }] }], stream: true,
...(options.model ? { model: options.model } : {}),
...(options.conversation ? { conversation: options.conversation } : {}),
tjwater: { approval_mode: options.approvalMode ?? "request", capabilities: options.capabilities ?? [],
tjwater: { ...(options.topicId ? { topic_id: options.topicId } : {}), ...(latest?.id ? { client_message_id: latest.id } : {}), approval_mode: options.approvalMode ?? "request", capabilities: options.capabilities ?? [],
...(options.triggerContext ? { trigger_context: options.triggerContext } : {}),
...(options.taskContext ? { task_context: options.taskContext } : {}),
},
@@ -44,6 +44,9 @@ export function responsesToUiStream(stream: ReadableStream<Uint8Array>): Readabl
if (value.type === "response.created") {
if (responseId || !record(value.response) || typeof value.response.id !== "string") throw new Error("Responses 创建事件不正确");
responseId = value.response.id;
if (record(value.response.conversation) && typeof value.response.conversation.id === "string") {
controller.enqueue({ type: "data-session_created", data: { session_id: value.response.conversation.id }, transient: true });
}
return;
}
if (!responseId) throw new Error("Responses 流缺少创建事件");
@@ -0,0 +1,73 @@
import { useState } from "react";
import { Check, Copy, LoaderCircle } from "lucide-react";
import { Badge } from "@/shared/ui/badge";
import { MessageAction, MessageActions } from "@/shared/ai-elements/message";
import type { AnswerUiPart } from "../answer-ui/contract";
export function AgentChatMessageHeader({
running,
interactive
}: {
running: boolean;
interactive: boolean;
}) {
if (!running && !interactive) return null;
return (
<div className="agent-chat-message-header">
{running ? (
<span
role="status"
className="ml-auto inline-flex items-center gap-1.5 text-[11px] text-muted-foreground"
>
<LoaderCircle size={12} className="motion-safe:animate-spin" aria-hidden="true" />
正在回复
</span>
) : interactive ? (
<Badge
variant="secondary"
className="ml-auto border-0 px-2 py-0.5 text-[10px] font-medium shadow-none"
>
交互回答
</Badge>
) : null}
</div>
);
}
export function AgentChatMessageActions({ parts }: { parts: AnswerUiPart[] }) {
const [copied, setCopied] = useState(false);
const [error, setError] = useState(false);
const text = parts
.map((part) => (part.type === "text" ? part.text : part.block.fallback_text))
.join("\n\n");
if (!text.trim()) return null;
return (
<MessageActions className="agent-chat-message-actions">
<MessageAction
tooltip={copied ? "回复已复制" : "复制回复"}
label={copied ? "回复已复制" : "复制回复"}
size="sm"
className="h-10 gap-1.5 px-2 text-[11px] font-normal shadow-none"
aria-label={copied ? "回复已复制" : "复制回复"}
onClick={async () => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
setError(false);
} catch {
setCopied(false);
setError(true);
}
}}
>
{copied ? <Check size={13} aria-hidden="true" /> : <Copy size={13} aria-hidden="true" />}
{copied ? "已复制" : "复制回复"}
</MessageAction>
<span role="status" className="text-[11px] text-muted-foreground">
{error ? "复制失败,请选择文字复制" : copied ? "已复制回复文字与交互内容摘要" : ""}
</span>
</MessageActions>
);
}
@@ -1,7 +1,8 @@
import { ChevronRight } from "lucide-react";
import { motion, useReducedMotion } from "motion/react";
import type { PersonaState } from "@/shared/ai-elements/persona";
import { cn } from "@/shared/ui/cn";
import { Button } from "@/shared/ui/button";
import { AgentPersona } from "./agent-persona";
import { agentLayoutTransition } from "./agent-motion";
type AgentCollapsedRailProps = {
personaState?: PersonaState;
@@ -15,26 +16,27 @@ export function AgentCollapsedRail({
onExpand
}: AgentCollapsedRailProps) {
const expandLabel = `展开 Agent 助手面板,当前状态:${statusLabel}`;
const prefersReducedMotion = useReducedMotion();
return (
<aside
<motion.aside
aria-label="Agent 折叠栏"
className={cn(
"agent-rail-enter acrylic-control pointer-events-auto w-[72px] rounded-2xl border p-1.5"
)}
initial={prefersReducedMotion ? false : { opacity: 0, x: -5, scale: 0.94 }}
animate={{ opacity: 1, x: 0, scale: 1 }}
transition={prefersReducedMotion ? { duration: 0 } : agentLayoutTransition}
style={{ transformOrigin: "left top" }}
className="agent-collapsed-rail pointer-events-auto size-[var(--workbench-agent-rail-width,64px)] rounded-full"
>
<button
<Button
variant="ghost"
type="button"
aria-label={expandLabel}
title={expandLabel}
onClick={onExpand}
className="agent-rail-item group relative flex h-14 w-full items-center justify-center rounded-xl border border-transparent bg-transparent hover:bg-[var(--action-selection-soft)]"
className="flex h-full w-full items-center justify-center rounded-full border-0 bg-transparent p-0"
>
<AgentPersona className="h-11 w-11" state={personaState} />
<span className="agent-panel-primary-icon absolute bottom-0.5 right-0.5 grid h-5 w-5 place-items-center rounded-md border-0! shadow-xs transition-transform group-hover:translate-x-0.5">
<ChevronRight size={13} strokeWidth={2.5} aria-hidden="true" />
</span>
</button>
</aside>
<AgentPersona className="h-full w-full" state={personaState} />
</Button>
</motion.aside>
);
}
File diff suppressed because it is too large Load Diff
@@ -1,333 +1,196 @@
import { Check, Loader2, Pencil, RefreshCw, Trash2, X } from "lucide-react";
import { AnimatePresence, motion } from "motion/react";
import { useState } from "react";
import { Check, ChevronDown, FolderInput, MoreHorizontal, Pencil, RefreshCw, Search, Trash2, X } from "lucide-react";
import { useEffect, useRef, useState, type CSSProperties, type RefObject } from "react";
import { Button } from "@/shared/ui/button";
import { Input } from "@/shared/ui/input";
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "@/shared/ui/dialog";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuTrigger } from "@/shared/ui/dropdown-menu";
import { Separator } from "@/shared/ui/separator";
import { cn } from "@/shared/ui/cn";
import { StatusBadge, StatusDot } from "@/shared/ui/status";
import type { AgentChatSessionSummary } from "../api/client";
import {
agentLayoutTransition,
agentPanelItemVariants,
agentPanelListVariants
} from "./agent-motion";
import { StatusBadge } from "@/shared/ui/status";
import type { AgentChatSessionSummary, AgentTopic } from "../api/client";
type AgentHistoryPanelProps = {
type Props = {
open: boolean;
onOpenChange: (open: boolean) => void;
triggerRef: RefObject<HTMLButtonElement | null>;
scopeLabel: string;
activeSessionId?: string | null;
loading: boolean;
loadingSessionId: string | null;
sessions: AgentChatSessionSummary[];
topics?: AgentTopic[];
topicId?: string;
onTopicChange?: (id: string | undefined) => void;
onMoveSessionToTopic?: (sessionId: string, topicId: string | null) => Promise<void>;
query?: string;
onQueryChange?: (value: string) => void;
hasMore?: boolean;
loadingMore?: boolean;
error?: string;
pendingUpdate?: boolean;
onLoadMore?: () => Promise<unknown> | void;
onRefresh?: () => Promise<void> | void;
onSelectSession: (sessionId: string) => void;
onRenameSession?: (sessionId: string, title: string) => Promise<void> | void;
onDeleteSession?: (sessionId: string) => Promise<void> | void;
};
export function AgentHistoryPanel({
activeSessionId,
loading,
loadingSessionId,
sessions,
onRefresh,
onSelectSession,
onRenameSession,
onDeleteSession
}: AgentHistoryPanelProps) {
const [editingSessionId, setEditingSessionId] = useState<string | null>(null);
const [draftTitle, setDraftTitle] = useState("");
const [savingSessionId, setSavingSessionId] = useState<string | null>(null);
const [deletingSessionId, setDeletingSessionId] = useState<string | null>(null);
const [confirmingDeleteSessionId, setConfirmingDeleteSessionId] = useState<string | null>(null);
const beginRename = (session: AgentChatSessionSummary) => {
setEditingSessionId(session.id);
setDraftTitle(session.title);
export function AgentHistoryPanel({ open, onOpenChange, triggerRef, scopeLabel, activeSessionId, loading, loadingSessionId,
sessions, query = "", onQueryChange, hasMore, loadingMore, error, pendingUpdate, onLoadMore, onRefresh,
topics = [], topicId, onTopicChange, onMoveSessionToTopic, onSelectSession, onRenameSession, onDeleteSession }: Props) {
const [search, setSearch] = useState(query);
const [movingId, setMovingId] = useState<string | null>(null);
const [editingId, setEditingId] = useState<string | null>(null);
const [deletingId, setDeletingId] = useState<string | null>(null);
const [title, setTitle] = useState("");
const [busy, setBusy] = useState<string | null>(null);
const [actionError, setActionError] = useState<string | null>(null);
const searchRef = useRef<HTMLInputElement>(null);
const [viewport, setViewport] = useState<{ height: number; top: number } | null>(null);
useEffect(() => {
if (!open) return;
const visual = window.visualViewport;
const update = () => {
const next = { height: visual?.height ?? window.innerHeight, top: visual?.offsetTop ?? 0 };
setViewport((current) => current?.height === next.height && current.top === next.top ? current : next);
};
update();
visual?.addEventListener("resize", update);
visual?.addEventListener("scroll", update);
window.addEventListener("resize", update);
return () => {
visual?.removeEventListener("resize", update);
visual?.removeEventListener("scroll", update);
window.removeEventListener("resize", update);
};
}, [open]);
useEffect(() => {
if (!open || search === query) return;
const timer = setTimeout(() => onQueryChange?.(search.trim()), 250);
return () => clearTimeout(timer);
}, [onQueryChange, open, query, search]);
const perform = async (id: string, action: () => Promise<void> | void) => {
setBusy(id); setActionError(null);
try { await action(); setEditingId(null); setDeletingId(null); }
catch (reason) { setActionError(reason instanceof Error ? reason.message : "操作失败,请重试"); }
finally { setBusy(null); }
};
const cancelRename = () => {
setEditingSessionId(null);
setDraftTitle("");
};
const saveRename = (session: AgentChatSessionSummary) => {
const normalizedTitle = draftTitle.trim();
if (!normalizedTitle || normalizedTitle === session.title) {
cancelRename();
return;
}
setSavingSessionId(session.id);
void Promise.resolve(onRenameSession?.(session.id, normalizedTitle))
.then(cancelRename)
.finally(() => setSavingSessionId(null));
};
const confirmDelete = (sessionId: string) => {
setDeletingSessionId(sessionId);
void Promise.resolve(onDeleteSession?.(sessionId))
.then(() => setConfirmingDeleteSessionId(null))
.finally(() => setDeletingSessionId(null));
};
return (
<div className="px-3 pb-3">
<div className="agent-panel-control rounded-2xl p-2.5 shadow-xs">
<div className="mb-2 flex items-center justify-between gap-2">
<div className="min-w-0">
<p className="text-sm font-semibold text-slate-950">历史记录</p>
<p className="mt-0.5 text-xs text-[var(--ink-muted)]">
{sessions.length ? `${sessions.length} 个会话` : "暂无历史会话"}
</p>
let previousGroup = "";
return <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent showCloseButton={false} data-agent-theme="chat"
overlayClassName="agent-history-overlay motion-reduce:animate-none"
className="agent-history-dialog flex flex-col gap-0 overflow-hidden bg-card p-0 text-foreground motion-reduce:animate-none"
style={viewport ? { "--history-viewport-height": `${viewport.height}px`, "--history-viewport-top": `${viewport.top}px` } as CSSProperties : undefined}
onOpenAutoFocus={(event) => { event.preventDefault(); searchRef.current?.focus(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); triggerRef.current?.focus(); }}>
<div data-agent-history-header className="shrink-0 space-y-4 p-4 sm:p-6 sm:pb-4">
<div className="flex items-start justify-between gap-4">
<DialogHeader className="min-w-0 text-left">
<DialogTitle>历史对话</DialogTitle>
<DialogDescription className="break-words">{scopeLabel}</DialogDescription>
</DialogHeader>
<div className="flex shrink-0 items-center gap-2">
<Button variant="ghost" size="icon-sm" aria-label="刷新 Agent 历史记录" loading={loadingMore}
onClick={() => void perform("refresh", () => onRefresh?.())}><RefreshCw aria-hidden="true" /></Button>
<Button variant="ghost" size="icon-sm" aria-label="关闭历史对话" onClick={() => onOpenChange(false)}><X aria-hidden="true" /></Button>
</div>
<Button
type="button"
aria-label="刷新 Agent 历史记录"
title="刷新 Agent 历史记录"
size="icon"
variant="ghost"
disabled={loading && sessions.length === 0}
loading={loading && sessions.length > 0}
loadingLabel="正在刷新 Agent 历史记录"
onClick={() => void Promise.resolve(onRefresh?.())}
>
<RefreshCw size={15} aria-hidden="true" />
</Button>
</div>
<motion.div
className="max-h-56 space-y-1 overflow-y-auto pr-1"
variants={agentPanelListVariants}
animate="animate"
>
<AnimatePresence initial={false} mode="popLayout">
{loading && sessions.length === 0 ? (
<motion.div
key="history-loading"
className="agent-history-state flex items-center gap-2 rounded-xl px-3 py-3 text-xs font-semibold text-[var(--ink-muted)]"
initial="initial"
animate="animate"
exit="exit"
variants={agentPanelItemVariants}
>
<Loader2 size={14} className="animate-spin" aria-hidden="true" />
正在加载
</motion.div>
) : sessions.length > 0 ? (
sessions.map((session) => {
const active = session.id === activeSessionId;
const itemLoading = loadingSessionId === session.id;
const editing = editingSessionId === session.id;
const saving = savingSessionId === session.id;
const deleting = deletingSessionId === session.id;
const confirmingDelete = confirmingDeleteSessionId === session.id;
return (
<motion.div
key={session.id}
layout
className={cn(
"agent-history-item grid w-full grid-cols-[1fr_auto] gap-2 rounded-xl px-3 py-2 text-left transition-colors",
active && !editing
? "agent-history-item-active border border-[var(--surface-border)]"
: "border border-transparent"
)}
initial="initial"
animate="animate"
exit="exit"
variants={agentPanelItemVariants}
transition={agentLayoutTransition}
>
<AnimatePresence initial={false} mode="popLayout">
{confirmingDelete ? (
<motion.div
key="confirm-delete"
className="min-w-0"
initial="initial"
animate="animate"
exit="exit"
variants={agentPanelItemVariants}
>
<span
className="status-tone-danger block truncate text-xs font-semibold text-[var(--status-foreground)]"
title={session.title}
>
删除“{session.title}”?
</span>
<span className="mt-0.5 block truncate text-xs text-[var(--ink-muted)]">
删除后无法从历史记录中恢复
</span>
</motion.div>
) : editing ? (
<motion.form
key="rename"
className="min-w-0"
initial="initial"
animate="animate"
exit="exit"
variants={agentPanelItemVariants}
onSubmit={(event) => {
event.preventDefault();
saveRename(session);
}}
>
<Input
autoFocus
className="agent-history-rename-input h-8 rounded-lg bg-[var(--surface-reading)] text-xs"
value={draftTitle}
disabled={saving}
onChange={(event) => setDraftTitle(event.currentTarget.value)}
onKeyDown={(event) => {
if (event.key === "Escape") {
cancelRename();
}
}}
/>
</motion.form>
) : (
<motion.button
key="session-summary"
type="button"
className="agent-history-session-trigger min-w-0 text-left"
disabled={itemLoading || deleting}
initial="initial"
animate="animate"
exit="exit"
variants={agentPanelItemVariants}
onClick={() => onSelectSession(session.id)}
>
<span
className="block truncate text-xs font-semibold text-slate-900"
title={session.title}
>
{session.title}
</span>
<span className="mt-0.5 block truncate text-xs text-[var(--ink-muted)]">
{formatSessionUpdatedAt(session.updatedAt)}
</span>
</motion.button>
)}
</AnimatePresence>
<span className="flex items-center gap-2">
{session.runStatus === "running" || session.isStreaming ? (
<StatusDot tone="info" activity="live" />
) : null}
{itemLoading || saving || deleting ? (
<Loader2
size={13}
className="animate-spin text-[var(--action-blue-hover)]"
aria-hidden="true"
/>
) : null}
{active && !editing && !confirmingDelete ? (
<StatusBadge tone="info">当前</StatusBadge>
) : null}
{confirmingDelete ? (
<>
<Button
type="button"
variant="destructive"
size="sm"
loading={deleting}
loadingLabel="正在删除对话"
onClick={() => confirmDelete(session.id)}
>
确认
</Button>
<Button
type="button"
aria-label="取消删除"
title="取消删除"
size="icon-sm"
variant="ghost"
disabled={deleting}
onClick={() => setConfirmingDeleteSessionId(null)}
>
<X size={14} aria-hidden="true" />
</Button>
</>
) : editing ? (
<>
<Button
type="button"
aria-label="保存对话主题"
title="保存对话主题"
size="icon-sm"
loading={saving}
loadingLabel="正在保存对话主题"
onClick={() => saveRename(session)}
>
<Check size={14} aria-hidden="true" />
</Button>
<Button
type="button"
aria-label="取消重命名"
title="取消重命名"
size="icon-sm"
variant="ghost"
disabled={saving}
onClick={cancelRename}
>
<X size={14} aria-hidden="true" />
</Button>
</>
) : (
<>
<Button
type="button"
aria-label="重命名对话"
title="重命名对话"
size="icon-sm"
variant="ghost"
disabled={itemLoading || deleting || !onRenameSession}
onClick={() => beginRename(session)}
>
<Pencil size={14} aria-hidden="true" />
</Button>
<Button
type="button"
aria-label="删除对话"
title="删除对话"
size="icon-sm"
variant="ghost"
className="text-[var(--ink-muted)] hover:bg-red-50 hover:text-red-600"
disabled={itemLoading || deleting || !onDeleteSession}
onClick={() => {
cancelRename();
setConfirmingDeleteSessionId(session.id);
}}
>
<Trash2 size={14} aria-hidden="true" />
</Button>
</>
)}
</span>
</motion.div>
);
})
) : (
<motion.div
key="history-empty"
className="agent-history-state rounded-xl px-3 py-3 text-xs text-[var(--ink-muted)]"
initial="initial"
animate="animate"
exit="exit"
variants={agentPanelItemVariants}
>
暂无历史记录
</motion.div>
)}
</AnimatePresence>
</motion.div>
<div className="relative">
<Search aria-hidden="true" className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-muted-foreground" />
<Input ref={searchRef} type="search" maxLength={200} aria-label="搜索标题和对话内容" placeholder="搜索标题或对话内容"
value={search} onChange={(event) => setSearch(event.target.value)} className="pl-9" />
</div>
{onTopicChange || pendingUpdate ? <div className="flex flex-wrap items-center justify-between gap-2">
{onTopicChange ? <DropdownMenu><DropdownMenuTrigger asChild><Button variant="outline" size="sm" aria-label="筛选历史主题" className="max-w-full">
<FolderInput aria-hidden="true" /><span className="truncate">{topicId === "unclassified" ? "未分类" : topics.find((topic) => topic.id === topicId)?.name ?? "全部主题"}</span><ChevronDown aria-hidden="true" />
</Button></DropdownMenuTrigger><DropdownMenuContent data-agent-theme="chat" align="start" className="z-[112] max-h-64 overflow-y-auto">
<DropdownMenuRadioGroup value={topicId ?? "all"} onValueChange={(id) => onTopicChange(id === "all" ? undefined : id)}>
<DropdownMenuRadioItem value="all">全部主题</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="unclassified">未分类</DropdownMenuRadioItem>
{topics.map((topic) => <DropdownMenuRadioItem key={topic.id} value={topic.id}>{topic.name}</DropdownMenuRadioItem>)}
</DropdownMenuRadioGroup>
</DropdownMenuContent></DropdownMenu> : null}
{pendingUpdate ? <Button variant="link" className="text-xs" onClick={() => void perform("refresh", () => onRefresh?.())}>
历史记录有更新,点击刷新
</Button> : null}
</div> : null}
{error || actionError ? <p role="alert" className="text-sm text-destructive">{actionError ?? error}</p> : null}
</div>
</div>
);
<Separator />
<div role="region" aria-label="Agent 历史记录" aria-busy={loading || undefined}
className="agent-history-list min-h-0 flex-1 overflow-y-auto overscroll-contain px-2 pb-4 sm:px-4">
{loading && !sessions.length ? <p role="status" className="px-3 py-8 text-center text-sm text-muted-foreground">正在加载历史对话…</p>
: !sessions.length ? <p className="px-3 py-8 text-center text-sm text-muted-foreground">{error ? "历史记录暂不可用,请刷新重试" : query ? "没有找到匹配的会话" : "暂无历史记录"}</p> : null}
{sessions.map((session) => {
const group = historyGroup(session.updatedAt);
const showGroup = group !== previousGroup;
previousGroup = group;
const active = session.id === activeSessionId;
const editing = session.id === editingId;
const deleting = session.id === deletingId;
const itemBusy = busy === session.id || loadingSessionId === session.id;
return <div key={session.id}>
{showGroup ? <h3 className="px-3 pb-2 pt-4 text-xs font-medium text-muted-foreground">{group}</h3> : null}
<div className={cn("agent-history-item flex items-center gap-3 rounded-md p-3", active ? "agent-history-item-active bg-accent" : "hover:bg-accent/50")}>
{editing ? <form className="flex min-w-0 flex-1 flex-wrap items-center gap-2" onSubmit={(event) => {
event.preventDefault(); if (title.trim()) void perform(session.id, () => onRenameSession?.(session.id, title.trim()));
}} onKeyDown={(event) => { if (event.key === "Escape") { event.preventDefault(); event.stopPropagation(); setEditingId(null); } }}>
<Input autoFocus aria-label="会话标题" value={title} disabled={itemBusy} onChange={(event) => setTitle(event.target.value)} className="min-w-0 flex-1" />
<Button type="submit" size="icon" aria-label="保存对话标题" loading={itemBusy} disabled={!title.trim()}><Check aria-hidden="true" /></Button>
<Button type="button" size="icon" variant="ghost" aria-label="取消重命名" onClick={() => setEditingId(null)}><X aria-hidden="true" /></Button>
</form> : movingId === session.id ? <div className="min-w-0 flex-1 space-y-2">
<p className="text-xs font-medium text-muted-foreground">移入主题</p>
<div className="flex max-h-48 flex-col gap-1 overflow-y-auto">
{[{ id: "", name: "未分类" }, ...topics].map((topic) => <Button key={topic.id} variant="ghost" disabled={Boolean(busy)} className="h-auto min-h-9 justify-start whitespace-normal break-words text-left" onClick={() => void perform(session.id, async () => {
await onMoveSessionToTopic?.(session.id, topic.id || null); setMovingId(null);
})}>{topic.name}</Button>)}
</div><Button size="sm" variant="ghost" onClick={() => setMovingId(null)}>取消移动</Button>
</div> : deleting ? <div className="flex min-w-0 flex-1 flex-wrap items-center justify-between gap-2">
<div className="min-w-0 flex-1"><p className="break-words text-sm">删除“{session.title}”?</p><p className="mt-1 text-xs text-muted-foreground">删除后无法从历史记录中恢复</p></div>
<Button variant="destructive" loading={itemBusy} onClick={() => void perform(session.id, () => onDeleteSession?.(session.id))}>确认</Button>
<Button variant="ghost" size="icon" aria-label="取消删除" onClick={() => setDeletingId(null)}><X aria-hidden="true" /></Button>
</div> : <>
<button type="button" className="agent-history-session-trigger min-w-0 flex-1 rounded-sm text-left outline-hidden focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2"
aria-current={active ? "true" : undefined}
disabled={itemBusy || Boolean(loadingSessionId)} onClick={() => onSelectSession(session.id)}>
<span className="line-clamp-2 break-words text-sm font-medium leading-6 text-foreground" title={session.title}>{session.title}</span>
<span className="mt-1 block truncate text-xs text-muted-foreground">{topics.find((topic) => topic.id === session.topicId)?.name ?? session.topicName ?? "未分类"}</span>
{session.searchSnippet ? <span className="mt-1 line-clamp-2 break-words text-xs leading-5 text-muted-foreground">{session.searchSnippet}</span> : null}
<span className="mt-1 block text-xs tabular-nums text-muted-foreground">{formatUpdatedAt(session.updatedAt)}{itemBusy ? " · 正在打开" : ""}</span>
</button>
<span className="flex shrink-0 flex-col items-end gap-1">
{session.purpose === "task_collaboration" ? <StatusBadge tone="neutral">任务协作</StatusBadge> : null}
{active ? <StatusBadge tone="info">当前</StatusBadge> : null}
{session.needsInput ? <StatusBadge tone="warning">需要确认</StatusBadge> : null}
{session.isStreaming || session.runStatus === "running" ? <StatusBadge tone="info">处理中</StatusBadge> : null}
{session.runStatus === "error" ? <StatusBadge tone="danger">处理失败</StatusBadge> : null}
</span>
<DropdownMenu><DropdownMenuTrigger asChild><Button size="icon" variant="ghost" disabled={Boolean(loadingSessionId)} aria-label={`会话操作:${session.title}`}><MoreHorizontal aria-hidden="true" /></Button></DropdownMenuTrigger>
<DropdownMenuContent data-agent-theme="chat" align="end" className="z-[112]">
<DropdownMenuItem disabled={!onRenameSession} onSelect={() => { setEditingId(session.id); setDeletingId(null); setTitle(session.title); }}><Pencil aria-hidden="true" />重命名对话</DropdownMenuItem>
<DropdownMenuItem disabled={!onMoveSessionToTopic} onSelect={() => { setMovingId(session.id); setEditingId(null); setDeletingId(null); }}><FolderInput aria-hidden="true" />移入主题</DropdownMenuItem>
<DropdownMenuItem disabled={!onDeleteSession} onSelect={() => { setDeletingId(session.id); setEditingId(null); }}><Trash2 aria-hidden="true" />删除对话</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</>}
</div>
</div>;
})}
{hasMore ? <div className="px-3 pt-4"><Button className="w-full" variant="outline" loading={loadingMore} onClick={() => void onLoadMore?.()}>加载更多</Button></div> : null}
</div>
</DialogContent>
</Dialog>;
}
function formatSessionUpdatedAt(value: number) {
return new Intl.DateTimeFormat("zh-CN", {
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit"
}).format(value);
function historyGroup(value: number) {
const now = new Date();
const day = new Date(now.getFullYear(), now.getMonth(), now.getDate()).getTime();
const date = new Date(value);
const start = new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime();
const yesterday = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 1).getTime();
const week = new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7).getTime();
return start >= day ? "今天" : start === yesterday ? "昨天" : start >= week ? "近 7 天" : "更早";
}
function formatUpdatedAt(value: number) {
return new Intl.DateTimeFormat("zh-CN", { year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit" }).format(value);
}
@@ -27,8 +27,10 @@ export function AgentMessageInbox({ messages, loading, error, hasMore, loadingMo
<span>{messageStatusLabels[message.status]}</span>
</div>
<p className="whitespace-pre-wrap break-words text-sm leading-6 text-[var(--ink)]">{message.text}</p>
<p className="break-all text-[var(--ink-muted)]">task_id: <span className="select-text font-mono">{message.task_id}</span></p>
<p className="break-all text-[var(--ink-muted)]">run_id: <span className="select-text font-mono">{message.run_id}</span></p>
<details className="text-[var(--ink-muted)]"><summary className="cursor-pointer">消息详情</summary>
<p className="break-all">任务编号:<span className="select-text font-mono">{message.task_id}</span></p>
<p className="break-all">运行编号:<span className="select-text font-mono">{message.run_id}</span></p>
</details>
{message.failure_detail ? <p className="break-words text-[var(--status-danger-foreground)]">{message.failure_detail}</p> : null}
</article>)}
{hasMore ? <Button variant="ghost" size="sm" disabled={loadingMore} onClick={() => void onLoadMore?.().catch(() => undefined)}>{loadingMore ? "正在加载…" : "加载更多消息"}</Button> : null}
@@ -0,0 +1,128 @@
import { useEffect, useRef, useState } from "react";
import { LoaderCircle, MoreHorizontal, Pencil, X } from "lucide-react";
import { Button } from "@/shared/ui/button";
import { cn } from "@/shared/ui/cn";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuLabel,
DropdownMenuRadioGroup,
DropdownMenuRadioItem,
DropdownMenuSeparator,
DropdownMenuTrigger
} from "@/shared/ui/dropdown-menu";
import type { AgentInputDelivery, AgentResponseInput } from "../api/client";
import type { AgentCommandPanelPresentation } from "./agent-command-panel";
type AgentPendingInputsProps = {
presentation: AgentCommandPanelPresentation;
inputs: AgentResponseInput[];
onDeliveryChange?: (id: string, delivery: AgentInputDelivery) => Promise<void> | void;
onEdit?: (id: string) => Promise<void> | void;
onCancel?: (id: string) => Promise<void> | void;
};
const menuItemClassName = "min-h-10 rounded-lg border border-transparent px-2.5 py-2 text-xs focus:border-[var(--action-border-hover)] focus:bg-[var(--action-selection-soft-hover)] data-[highlighted]:border-[var(--action-border-hover)] data-[highlighted]:bg-[var(--action-selection-soft-hover)]";
export function AgentPendingInputs({ presentation, inputs, onDeliveryChange, onEdit, onCancel }: AgentPendingInputsProps) {
const [busyId, setBusyId] = useState<string | null>(null);
const listRef = useRef<HTMLUListElement | null>(null);
const latestId = inputs.at(-1)?.id;
useEffect(() => {
const list = listRef.current;
if (list) list.scrollTop = list.scrollHeight;
}, [latestId]);
const performAction = (id: string, action: () => Promise<void> | void) => {
setBusyId(id);
void Promise.resolve().then(action).catch(() => {}).finally(() => setBusyId(null));
};
if (!inputs.length) return null;
return (
<section aria-label="待处理消息队列" className="order-first w-full min-w-0 border-b border-[var(--surface-divider)] bg-[var(--surface-reading)]">
<p className="px-3 pt-2 text-[11px] leading-5 text-muted-foreground" aria-live="polite">
等待处理 <span className="ml-1 tabular-nums">{inputs.length}</span>
</p>
<ul ref={listRef} aria-label="待处理消息" className="max-h-[min(12rem,28dvh)] divide-y divide-[var(--surface-divider)] overflow-y-auto overscroll-contain px-2 pb-1">
{inputs.map((input) => (
<li key={input.id} aria-busy={busyId === input.id} className="flex min-w-0 items-start gap-1 py-1">
<PendingInputText text={input.text} />
<span className="shrink-0 py-2 text-[11px] leading-6 text-muted-foreground" title={input.delivery === "queue" ? "当前任务结束后处理" : "在下一步补充当前任务"}>
{input.delivery === "queue" ? "排队" : "引导"}
</span>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button type="button" variant="ghost" size="icon" aria-label={`消息操作:${input.text}`}
disabled={Boolean(busyId)} className="agent-panel-icon-button size-10 shrink-0 active:scale-95 motion-reduce:transform-none">
{busyId === input.id
? <LoaderCircle size={16} className="motion-safe:animate-spin" aria-hidden />
: <MoreHorizontal size={16} aria-hidden />}
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent data-agent-presentation={presentation} side="top" align="end" sideOffset={6} collisionPadding={12}
className="agent-panel-overlay w-48 rounded-xl p-1.5">
<DropdownMenuItem disabled={!onEdit} className={menuItemClassName}
onSelect={() => performAction(input.id, () => onEdit?.(input.id))}>
<Pencil size={14} aria-hidden />编辑消息
</DropdownMenuItem>
<DropdownMenuSeparator />
<DropdownMenuLabel className="px-2 py-1 text-[11px] font-normal text-muted-foreground">处理方式</DropdownMenuLabel>
<DropdownMenuRadioGroup aria-label="消息处理方式" value={input.delivery} onValueChange={(delivery) => {
if (onDeliveryChange && (delivery === "steer" || delivery === "queue")) {
void Promise.resolve().then(() => onDeliveryChange(input.id, delivery)).catch(() => {});
}
}}>
<DropdownMenuRadioItem value="steer" disabled={!onDeliveryChange} className={`${menuItemClassName} pl-8`}>引导当前任务</DropdownMenuRadioItem>
<DropdownMenuRadioItem value="queue" disabled={!onDeliveryChange} className={`${menuItemClassName} pl-8`}>排队处理</DropdownMenuRadioItem>
</DropdownMenuRadioGroup>
<DropdownMenuSeparator />
<DropdownMenuItem disabled={!onCancel} className={menuItemClassName}
onSelect={() => performAction(input.id, () => onCancel?.(input.id))}>
<X size={14} aria-hidden />关闭排队
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</li>
))}
</ul>
</section>
);
}
function PendingInputText({ text }: { text: string }) {
const [expanded, setExpanded] = useState(false);
const [overflows, setOverflows] = useState(false);
const textRef = useRef<HTMLParagraphElement | null>(null);
useEffect(() => {
const node = textRef.current;
if (!node) return;
const measure = () => {
setOverflows(node.scrollHeight > Number.parseFloat(getComputedStyle(node).lineHeight) * 2 + 1);
};
const observer = new ResizeObserver(measure);
observer.observe(node);
measure();
return () => observer.disconnect();
}, [text]);
useEffect(() => {
if (expanded) textRef.current?.parentElement?.scrollIntoView({ block: "nearest" });
}, [expanded]);
return (
<div className="min-w-0 flex-1 px-1 py-2">
<p ref={textRef} className={cn("text-sm leading-6 text-foreground [overflow-wrap:anywhere]", expanded ? "whitespace-pre-wrap" : "whitespace-normal line-clamp-2")}>
{text}
</p>
{overflows ? <button type="button" aria-expanded={expanded} onClick={() => setExpanded((current) => !current)}
className="relative mt-1 rounded-sm text-[11px] leading-5 text-muted-foreground underline underline-offset-4 after:absolute after:-inset-y-2.5 after:inset-x-0 hover:text-foreground focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-ring active:opacity-70">
{expanded ? "收起全文" : "展开全文"}
</button> : null}
</div>
);
}
+80 -29
View File
@@ -1,18 +1,37 @@
import { Bot } from "lucide-react";
import { lazy, Suspense, useCallback, useEffect, useRef, useState } from "react";
import type { PersonaState } from "@/shared/ai-elements/persona";
import asset from "@/shared/ai-elements/persona-resource-manifest.json";
import { cn } from "@/shared/ui/cn";
const LazyPersona = lazy(async () => {
const module = await import("@/shared/ai-elements/persona");
return { default: module.Persona };
});
const Persona = lazy(() =>
import("@/shared/ai-elements/persona").then((module) => ({ default: module.Persona }))
);
const stillSources = {
idle: "/agent/obsidian-water-idle.png",
asleep: "/agent/obsidian-water-offline.png"
};
type AgentPersonaProps = {
className?: string;
state?: PersonaState;
};
function usePrefersReducedMotion() {
const [reducedMotion, setReducedMotion] = useState(
() => window.matchMedia("(prefers-reduced-motion: reduce)").matches
);
useEffect(() => {
const query = window.matchMedia("(prefers-reduced-motion: reduce)");
const update = () => setReducedMotion(query.matches);
update();
query.addEventListener("change", update);
return () => query.removeEventListener("change", update);
}, []);
return reducedMotion;
}
function useElementVisibility() {
const containerRef = useRef<HTMLSpanElement>(null);
const [visible, setVisible] = useState(false);
@@ -20,60 +39,92 @@ function useElementVisibility() {
useEffect(() => {
const container = containerRef.current;
if (!container) return;
let intersectsViewport = false;
const updateVisibility = () => {
const updateVisibility = () =>
setVisible(intersectsViewport && document.visibilityState === "visible");
};
const observer = new IntersectionObserver(([entry]) => {
intersectsViewport = Boolean(entry?.isIntersecting);
updateVisibility();
});
observer.observe(container);
document.addEventListener("visibilitychange", updateVisibility);
return () => {
observer.disconnect();
document.removeEventListener("visibilitychange", updateVisibility);
};
}, []);
return { containerRef, visible };
}
function PersonaFallback() {
function PersonaStill({ state }: { state: PersonaState }) {
const source = stillSources[state === "asleep" ? "asleep" : "idle"];
return <img className="agent-orb-still" src={`${source}?v=${asset.sha256}`} alt="" draggable={false} />;
}
function LivePersona({ state }: { state: PersonaState }) {
const [loaded, setLoaded] = useState(false);
const [ready, setReady] = useState(false);
const [failed, setFailed] = useState(false);
const onLoad = useCallback(() => setLoaded(true), []);
const onLoadError = useCallback(() => setFailed(true), []);
useEffect(() => {
if (!loaded) return;
// Keep the matching still visible while Rive completes its entrance animation.
const timer = window.setTimeout(() => setReady(true), 600);
return () => window.clearTimeout(timer);
}, [loaded]);
return (
<span className="grid h-full w-full place-items-center rounded-full border border-[var(--surface-border)]/70 bg-[var(--surface-control)] text-[var(--ink-muted)]">
<Bot className="h-2/5 w-2/5" aria-hidden="true" />
<span className="agent-orb-live" data-ready={ready && !failed} data-failed={failed}>
<PersonaStill state={state} />
{!failed ? (
<Suspense fallback={null}>
<Persona
className="agent-orb-canvas"
state={state}
onLoad={onLoad}
onLoadError={onLoadError}
/>
</Suspense>
) : null}
</span>
);
}
export function AgentPersona({ className, state = "idle" }: AgentPersonaProps) {
const { containerRef, visible } = useElementVisibility();
const [failed, setFailed] = useState(false);
const handleLoadError = useCallback(() => setFailed(true), []);
const reducedMotion = usePrefersReducedMotion();
const [hovered, setHovered] = useState(false);
const live = visible && !reducedMotion;
const shouldRenderAnimation = !failed && visible;
useEffect(() => {
if (!live) setHovered(false);
}, [live]);
return (
<span
ref={containerRef}
aria-label="Agent 状态"
className={cn("relative block shrink-0", className)}
className={cn("relative block h-16 w-16 shrink-0", className)}
>
{shouldRenderAnimation ? (
<Suspense fallback={<PersonaFallback />}>
<LazyPersona
className="h-full w-full scale-110"
onLoadError={handleLoadError}
state={state}
/>
</Suspense>
) : (
<PersonaFallback />
)}
<span
className="agent-orb"
data-agent-orb={state}
data-animated={live}
data-hovered={hovered && live}
aria-hidden="true"
onPointerEnter={(event) => {
if (event.isPrimary && event.pointerType !== "touch") setHovered(true);
}}
onPointerLeave={() => setHovered(false)}
onPointerCancel={() => setHovered(false)}
>
<span className="agent-orb-response">
{live ? <LivePersona state={state} /> : <PersonaStill state={state} />}
<span className="agent-orb-contrast" />
</span>
</span>
</span>
);
}
@@ -0,0 +1,55 @@
import { ChevronsUpDown, Folder, FolderPlus, Settings2 } from "lucide-react";
import { useRef, useState } from "react";
import type { AgentTopic } from "../api/client";
import { Button } from "@/shared/ui/button";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuTrigger } from "@/shared/ui/dropdown-menu";
import { AgentTopicDialog } from "./agent-topic-dialog";
export type AgentTopicControlsProps = {
topics: AgentTopic[];
topicId?: string | null;
loading?: boolean;
error?: string;
onOpen: () => Promise<unknown>;
onSelect: (id: string | null) => void;
onCreate: (name: string) => Promise<unknown>;
onRename: (id: string, name: string) => Promise<unknown>;
onDelete: (id: string) => Promise<unknown>;
};
export function AgentTopicControls({ topics, topicId, loading, error, onOpen, onSelect, onCreate, onRename, onDelete }: AgentTopicControlsProps) {
const triggerRef = useRef<HTMLButtonElement>(null);
const [open, setOpen] = useState(false);
const [mode, setMode] = useState<"create" | "manage">("create");
const [dialogKey, setDialogKey] = useState(0);
const current = topics.find((topic) => topic.id === topicId);
const begin = (next: "create" | "manage") => {
setMode(next);
setDialogKey((key) => key + 1);
setOpen(true);
};
return <>
<DropdownMenu onOpenChange={(next) => { if (next) void onOpen().catch(() => {}); }}>
<DropdownMenuTrigger asChild><Button ref={triggerRef} variant="outline" size="sm" aria-label="选择主题" aria-description={current?.name ?? "未分类"} title={`主题:${current?.name ?? "未分类"}`} className="min-w-0 max-w-full justify-start gap-1.5 px-1.5 text-xs font-medium text-foreground">
<Folder aria-hidden="true" className="text-muted-foreground" /><span className="truncate">{current?.name ?? "未分类"}</span><ChevronsUpDown aria-hidden="true" className="ml-auto text-muted-foreground" />
</Button></DropdownMenuTrigger>
<DropdownMenuContent data-agent-theme="chat" align="start" side="bottom" className="w-[var(--radix-dropdown-menu-trigger-width)] min-w-56 max-w-[min(20rem,calc(100vw-1rem))]">
<DropdownMenuLabel className="text-xs font-normal text-muted-foreground">切换主题</DropdownMenuLabel>
<DropdownMenuRadioGroup value={current?.id ?? "unclassified"} onValueChange={(id) => onSelect(id === "unclassified" ? null : id)} className="max-h-[min(45dvh,15rem)] overflow-y-auto">
<DropdownMenuRadioItem value="unclassified">未分类</DropdownMenuRadioItem>
{topics.map((topic) => <DropdownMenuRadioItem key={topic.id} value={topic.id}>
<span className="min-w-0 line-clamp-2 break-words" title={topic.name}>{topic.name}</span>
</DropdownMenuRadioItem>)}
</DropdownMenuRadioGroup>
{loading ? <p role="status" className="px-2 py-2 text-xs text-muted-foreground">正在加载主题…</p> : null}
{error ? <p role="alert" className="px-2 py-2 text-xs text-destructive">{error}</p> : null}
<DropdownMenuSeparator className="bg-border/50" />
<DropdownMenuItem onSelect={() => begin("create")}><FolderPlus size={15} />新建主题</DropdownMenuItem>
<DropdownMenuItem onSelect={() => begin("manage")}><Settings2 size={15} />管理主题</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<AgentTopicDialog key={dialogKey} open={open} initialMode={mode} onOpenChange={setOpen} triggerRef={triggerRef}
topics={topics} onCreate={onCreate} onRename={onRename} onDelete={onDelete} />
</>;
}
@@ -0,0 +1,108 @@
import { Folder, FolderPlus, Pencil, Trash2, X } from "lucide-react";
import { useId, useRef, useState, type RefObject } from "react";
import { Button } from "@/shared/ui/button";
import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle } from "@/shared/ui/dialog";
import { Input } from "@/shared/ui/input";
import type { AgentTopic } from "../api/client";
type TopicView = { kind: "list" | "create" } | { kind: "rename" | "delete"; topic: AgentTopic };
type Props = {
open: boolean;
initialMode: "create" | "manage";
onOpenChange: (open: boolean) => void;
triggerRef: RefObject<HTMLButtonElement | null>;
topics: AgentTopic[];
onCreate: (name: string) => Promise<unknown>;
onRename: (id: string, name: string) => Promise<unknown>;
onDelete: (id: string) => Promise<unknown>;
};
export function AgentTopicDialog({ open, initialMode, onOpenChange, triggerRef, topics, onCreate, onRename, onDelete }: Props) {
const [view, setView] = useState<TopicView>({ kind: initialMode === "create" ? "create" : "list" });
const [name, setName] = useState("");
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string>();
const fieldId = useId();
const inputRef = useRef<HTMLInputElement>(null);
const newTopicRef = useRef<HTMLButtonElement>(null);
const isForm = view.kind === "create" || view.kind === "rename";
const title = view.kind === "create" ? "新建主题" : view.kind === "rename" ? "重命名主题" : view.kind === "delete" ? "删除主题" : "管理主题";
const description = view.kind === "create" ? "将相关事件、问题和对话整理到同一主题。"
: view.kind === "rename" ? "修改名称不会影响主题中的现有会话。"
: view.kind === "delete" ? "仅删除分类,其中的会话会保留在未分类中。"
: `当前项目共有 ${topics.length} 个主题,用于整理相关事件与问题。`;
const changeView = (next: TopicView) => {
setError(undefined);
setName(next.kind === "rename" ? next.topic.name : "");
setView(next);
};
const perform = async (action: () => Promise<unknown>, done: () => void) => {
setBusy(true);
setError(undefined);
try { await action(); done(); }
catch (reason) { setError(reason instanceof Error ? reason.message : "主题操作失败,请重试"); }
finally { setBusy(false); }
};
const cancel = () => initialMode === "create" ? onOpenChange(false) : changeView({ kind: "list" });
const footerClass = "gap-2 px-6 pb-6 sm:gap-0";
return <Dialog open={open} onOpenChange={(next) => { if (!busy) onOpenChange(next); }}>
<DialogContent data-agent-theme="chat" overlayClassName="agent-history-overlay" showCloseButton={false}
className="agent-topic-dialog z-[111] flex max-h-[min(80dvh,40rem)] w-[calc(100vw-2rem)] max-w-md flex-col gap-0 overflow-hidden bg-card p-0"
onOpenAutoFocus={(event) => { event.preventDefault(); (inputRef.current ?? newTopicRef.current)?.focus(); }}
onCloseAutoFocus={(event) => { event.preventDefault(); triggerRef.current?.focus(); }}>
<DialogHeader className="p-6 pb-4 pr-14 text-left">
<DialogTitle>{title}</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
<Button variant="ghost" size="icon-sm" className="absolute right-4 top-4" aria-label="关闭主题窗口" disabled={busy} onClick={() => onOpenChange(false)}>
<X aria-hidden="true" />
</Button>
{isForm ? <form className="flex min-h-0 flex-col" onSubmit={(event) => {
event.preventDefault();
if (!name.trim() || busy) return;
void perform(() => view.kind === "rename" ? onRename(view.topic.id, name.trim()) : onCreate(name.trim()),
() => view.kind === "create" ? onOpenChange(false) : changeView({ kind: "list" }));
}}>
<div className="min-h-0 space-y-2 overflow-y-auto px-6 pb-6">
<label htmlFor={fieldId} className="text-sm font-medium">主题名称</label>
<Input ref={inputRef} id={fieldId} autoFocus maxLength={80} value={name} disabled={busy}
aria-describedby={`${fieldId}-hint`} onChange={(event) => setName(event.target.value)} placeholder="例如:城南压力异常排查" />
<p id={`${fieldId}-hint`} className="text-xs text-muted-foreground">名称最多 80 个字符。</p>
{error ? <p role="alert" className="text-sm text-destructive">{error}</p> : null}
</div>
<DialogFooter className={footerClass}>
<Button type="button" variant="outline" disabled={busy} onClick={cancel}>取消</Button>
<Button type="submit" loading={busy} disabled={!name.trim()}>{view.kind === "rename" ? "保存主题" : "创建主题"}</Button>
</DialogFooter>
</form> : view.kind === "delete" ? <>
<div className="min-h-0 space-y-3 overflow-y-auto px-6 pb-6">
<p className="break-words text-sm">确认删除“{view.topic.name}”?</p>
{error ? <p role="alert" className="text-sm text-destructive">{error}</p> : null}
</div>
<DialogFooter className={footerClass}>
<Button type="button" autoFocus variant="outline" disabled={busy} onClick={() => changeView({ kind: "list" })}>取消</Button>
<Button variant="destructive" loading={busy} onClick={() => void perform(() => onDelete(view.topic.id), () => changeView({ kind: "list" }))}>确认删除主题</Button>
</DialogFooter>
</> : <>
<div role="list" aria-label="主题列表" className="min-h-0 overflow-y-auto px-6 pb-4">
{topics.length === 0 ? <p className="py-6 text-center text-sm text-muted-foreground">还没有主题,可以新建一个来整理对话。</p> : topics.map((topic) => (
<div role="listitem" key={topic.id} className="flex items-center gap-3 border-b border-border/40 py-3 last:border-0">
<Folder aria-hidden="true" className="size-4 shrink-0 text-muted-foreground" />
<span className="min-w-0 flex-1 break-words text-sm font-medium">{topic.name}</span>
<div className="flex shrink-0 items-center gap-2">
<Button variant="ghost" size="icon-sm" aria-label={`重命名主题:${topic.name}`} onClick={() => changeView({ kind: "rename", topic })}><Pencil aria-hidden="true" /></Button>
<Button variant="ghost" size="icon-sm" aria-label={`删除主题:${topic.name}`} onClick={() => changeView({ kind: "delete", topic })}><Trash2 aria-hidden="true" /></Button>
</div>
</div>
))}
</div>
<DialogFooter className={footerClass}>
<Button ref={newTopicRef} autoFocus variant="outline" onClick={() => changeView({ kind: "create" })}><FolderPlus aria-hidden="true" />新建主题</Button>
<Button onClick={() => onOpenChange(false)}>完成</Button>
</DialogFooter>
</>}
</DialogContent>
</Dialog>;
}
@@ -71,11 +71,11 @@ function AgentUiResultCard({ result }: { result: AgentUiResult }) {
);
}
export function AgentChartView({ chart }: { chart: NonNullable<ReturnType<typeof parseFrontendChart>> }) {
return <SafeChartEnvelope envelope={{ kind: "chart", schemaVersion: "agent-ui@1", grammar: "echarts-safe-subset", surface: "side_panel", spec: { title: chart.title, chart_type: chart.chart_type }, data: { x_data: chart.x_data, series: chart.series } }} />;
export function AgentChartView({ chart, embedded = false }: { chart: NonNullable<ReturnType<typeof parseFrontendChart>>; embedded?: boolean }) {
return <SafeChartEnvelope embedded={embedded} envelope={{ kind: "chart", schemaVersion: "agent-ui@1", grammar: "echarts-safe-subset", surface: "side_panel", spec: { title: chart.title, chart_type: chart.chart_type }, data: { x_data: chart.x_data, series: chart.series } }} />;
}
function SafeChartEnvelope({ envelope }: { envelope: Extract<UIEnvelope, { kind: "chart" }> }) {
function SafeChartEnvelope({ envelope, embedded = false }: { envelope: Extract<UIEnvelope, { kind: "chart" }>; embedded?: boolean }) {
const spec = parseChartSpec(envelope.spec);
const data = normalizeSafeChartData(envelope.data, 100);
@@ -84,9 +84,9 @@ function SafeChartEnvelope({ envelope }: { envelope: Extract<UIEnvelope, { kind:
}
return (
<div className="agent-panel-nested rounded-xl p-3">
<div className={embedded ? "min-w-0" : "agent-panel-nested rounded-xl p-3"}>
<div className="mb-3 flex items-start justify-between gap-3">
<div className="min-w-0">
{!embedded ? <div className="min-w-0">
<p className="truncate text-sm font-semibold text-slate-950" title={spec.title}>
{spec.title ?? "Agent 图表"}
</p>
@@ -94,7 +94,7 @@ function SafeChartEnvelope({ envelope }: { envelope: Extract<UIEnvelope, { kind:
{spec.chartType === "bar" ? "柱状图" : "折线图"}
{spec.yAxisName ? ` · ${spec.yAxisName}` : ""}
</p>
</div>
</div> : null}
<div className="flex shrink-0 flex-wrap justify-end gap-1.5">
{data.series.slice(0, 3).map((series, index) => (
<span key={series.name} className="flex items-center gap-1 text-xs text-slate-600">
@@ -0,0 +1,20 @@
import { createElement, type ComponentType, type ReactNode } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { expect, it } from "vitest";
import { artifactLinkComponents, artifactLinksPlugin } from "./artifact-markdown";
it("keeps external link safety and rejects forged custom export links", () => {
const Renderer = artifactLinkComponents["agent-export-link"] as ComponentType<{ href: string; children: ReactNode }>;
const path = "/api/v1/session/s/files/mcp-11111111-1111-1111-1111-111111111111.zip";
const render = (href: string) => renderToStaticMarkup(createElement(Renderer, { href, children: "下载" }));
expect(render(path)).toContain(`<a href="${path}"`);
for (const href of ["https://foreign.test/x", "javascript:alert(1)", "/api/v1/admin/secrets"]) {
expect(render(href)).toBe("<span>下载</span>");
}
const root = { type: "root", children: [
{ type: "element", tagName: "a", properties: { href: path } },
{ type: "element", tagName: "a", properties: { href: "https://example.com" } },
] };
artifactLinksPlugin()(root);
expect(root.children.map((child) => child.tagName)).toEqual(["agent-export-link", "a"]);
});
@@ -0,0 +1,32 @@
import type { Components } from "streamdown";
import type { ReactNode } from "react";
type MarkdownNode = {
type: string;
tagName?: string;
properties?: Record<string, unknown>;
children?: MarkdownNode[];
};
const artifactPath = /^\/api\/v1\/session\/[^/?#]+\/files\/mcp-[a-f0-9-]{36}\.(?:zip|xlsx)$/;
// Only verified-format first-party download paths use the authenticated click
// handler. All other anchors retain Streamdown's built-in link safety dialog.
export function artifactLinksPlugin() {
return (tree: MarkdownNode) => {
const visit = (node: MarkdownNode) => {
if (node.tagName === "a" && typeof node.properties?.href === "string" && artifactPath.test(node.properties.href)) {
node.tagName = "agent-export-link";
}
node.children?.forEach(visit);
};
visit(tree);
};
}
export const artifactLinkComponents: Components = {
"agent-export-link": ({ href, children }) => {
if (typeof href !== "string" || !artifactPath.test(href)) return <span>{children as ReactNode}</span>;
return <a href={href} className="wrap-anywhere font-medium text-primary underline">{children as ReactNode}</a>;
}
};
@@ -1,5 +1,9 @@
import { cn } from "@/shared/ui/cn";
import { MessageResponse } from "@/shared/ai-elements/message";
import { defaultRehypePlugins } from "streamdown";
import { artifactLinkComponents, artifactLinksPlugin } from "./artifact-markdown";
const responseRehypePlugins = [...Object.values(defaultRehypePlugins), artifactLinksPlugin];
type StreamingTokenResponseProps = {
content: string;
@@ -27,6 +31,8 @@ export function StreamingTokenResponse({
isAnimating={isAnimating}
mode="streaming"
parseIncompleteMarkdown={true}
rehypePlugins={responseRehypePlugins}
components={artifactLinkComponents}
>
{content}
</MessageResponse>
+8 -3
View File
@@ -7,7 +7,6 @@ export { AgentChartView } from "./components/agent-ui-envelope-renderer";
export { countPendingAgentInputs, hasPendingAgentInput } from "./message-state";
export type {
AgentCommandPanelPresentation,
AgentConversationProjectOption,
AgentWorkspaceContextItem
} from "./components/agent-command-panel";
export { AgentPersona } from "./components/agent-persona";
@@ -20,6 +19,7 @@ export type {
AgentInputDelivery,
AgentResponseInput,
AgentChatSessionSummary,
AgentTopic,
AgentSessionPurpose,
AgentEventTriggerContext,
AgentLoadedChatSession,
@@ -94,8 +94,13 @@ export type { SafeChartData, SafeChartSeries, SafeChartSpec } from "./chart-data
export { parseFrontendChart } from "./frontend-action/chart";
export { parseAnswerUiBlock } from "./answer-ui/contract";
export type { AnswerUiBlock, AnswerUiPart } from "./answer-ui/contract";
export type { AnswerUiMapTarget } from "./answer-ui/answer-ui-view";
export { ResponsesChatTransport, createResponseRequest } from "./api/responses-transport";
export { AnswerUiView } from "./answer-ui/answer-ui-view";
export { parseAnswerUiBlock, reportUiBlocksSchema } from "./answer-ui/contract";
export type { AnswerUiBlock, AnswerUiPart, StoredReportUiBlock } from "./answer-ui/contract";
export type { AnswerUiSelection } from "./answer-ui/answer-ui-interaction-context";
export type { AgentSessionPage, AgentHistoryMessagePage, AgentMessagePagination } from "./api/client";
export type { AgentRunStatus } from "./api/client";
@@ -1,5 +1,6 @@
import { getWorkbenchAccessToken } from "./request-context";
import { z } from "zod";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "./request-context";
import { env } from "@/shared/config/env";
import type { WaterNetworkSourceId } from "../map/sources";
import {
@@ -48,13 +49,13 @@ export async function fetchElementGisProperties(
elementType: WaterNetworkSourceId,
elementId: string,
projectId: string | null,
getAccessToken?: AccessTokenProvider,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal
): Promise<GisAttributeGroup[]> {
const ownedProject = projectId
? null
: await findOwnedWorkbenchProject(getAccessToken, signal);
const accessToken = ownedProject?.accessToken ?? await getAccessToken?.();
const accessToken = ownedProject?.accessToken ?? await getWorkbenchAccessToken(getAccessToken);
const resolvedProjectId = projectId ?? ownedProject?.project.project_id;
if (!resolvedProjectId) throw new Error("未找到 GIS 台账所属项目");
const path = [
@@ -82,13 +83,13 @@ export async function fetchSourceGisFeatureProperties(
layerKey: string,
sourceFid: number,
projectId: string | null,
getAccessToken?: AccessTokenProvider,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal
): Promise<GisAttributeGroup[]> {
const ownedProject = projectId
? null
: await findOwnedWorkbenchProject(getAccessToken, signal);
const accessToken = ownedProject?.accessToken ?? await getAccessToken?.();
const accessToken = ownedProject?.accessToken ?? await getWorkbenchAccessToken(getAccessToken);
const resolvedProjectId = projectId ?? ownedProject?.project.project_id;
if (!resolvedProjectId) throw new Error("未找到 GIS 台账所属项目");
const path = [
@@ -74,3 +74,12 @@ describe("investigation report read contract", () => {
expect(() => investigationReportSchema.parse({ ...result, ...changes })).toThrow();
});
});
it("retains fallback text from a future component while reading the fixed report facts", () => {
const value = investigationReportSchema.parse({ ...base, ui_blocks: [{ evidence_refs: ["query-1"], block: {
version: "answer-ui@future", block_id: "future", fallback_text: "旧版客户端仍可阅读。", spec: { future: true },
} }] });
expect(value.current_conclusion).toBe(base.current_conclusion);
expect(value.ui_blocks?.[0].block.fallback_text).toBe("旧版客户端仍可阅读。");
expect(investigationReportSchema.parse(base).ui_blocks).toBeUndefined();
});
@@ -1,11 +1,13 @@
import { z } from "zod";
import type { AgentTaskDiscussionContext } from "@/features/agent";
import type { AgentTaskDiscussionContext, AnswerUiSelection } from "@/features/agent";
import { reportUiBlocksSchema } from "@/features/agent";
export type InvestigationDiscussion = {
prompt?: string;
context?: AgentTaskDiscussionContext;
// Display metadata from the selected report, never the task's current round.
reportGeneration?: number | null;
reference?: AnswerUiSelection;
};
const text = z.string().trim().min(1);
@@ -74,7 +76,8 @@ export const investigationReportSchema = z
outcome: z.enum(["concluded", "insufficient_data"]).nullish(),
stop_reason: text.nullish(),
data_gaps: z.array(dataGapSchema).nullish(),
diagram: investigationDiagramSchema.nullish()
diagram: investigationDiagramSchema.nullish(),
ui_blocks: reportUiBlocksSchema.optional()
})
.strict()
.superRefine((report, ctx) => {
@@ -1,7 +1,7 @@
import { z } from "zod";
import { investigationReportSchema, investigationDiagramSchema } from "./investigation-report";
import { investigationPresentationCursorSchema } from "./investigation-presentation";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "./request-context";
import { env } from "@/shared/config/env";
import { createWorkbenchHeaders, findOwnedWorkbenchProject, getServerError } from "./project-client";
@@ -316,6 +316,39 @@ const taskDataSnapshotSchema = z.object({
"run_burst_location",
"analyze_valve_isolation",
"run_leakage_identification",
"get_mutation_status",
"query_nearby_elements",
"list_regions",
"get_region",
"get_region_nodes",
"get_node_connections",
"query_network_extent",
"list_major_nodes",
"get_model_configuration",
"list_model_configurations",
"search_project_places",
"reverse_geocode",
"get_project_info",
"export_project_model",
"get_sensor_placement_candidate",
"export_sensor_placement",
"list_task_schedules",
"get_task_run_history",
"calculate_demand_allocation",
"run_burst_simulation",
"edit_model_element",
"edit_model_configuration",
"clean_scada_readings",
"write_scada_readings",
"delete_scada_readings",
"save_simulation_scenario",
"create_sensor_placement",
"update_sensor_placement",
"create_operational_task",
"create_task_schedule",
"update_task_schedule",
"retry_operational_task",
"cancel_task_run",
]),
source_ref: z.string().min(1),
queried_at: workbenchDateTimeSchema,
@@ -366,7 +399,7 @@ export type CreateOperationalTaskInput = {
const SERVER_API_BASE_URL = env.TJWATER_SERVER_API_BASE_URL.replace(/\/$/, "");
async function operationalTaskRequest(path: string, getAccessToken?: AccessTokenProvider, init?: RequestInit) {
async function operationalTaskRequest(path: string, getAccessToken?: WorkbenchAccess, init?: RequestInit) {
const { project, accessToken } = await findOwnedWorkbenchProject(getAccessToken, init?.signal ?? undefined);
const headers = new Headers(createWorkbenchHeaders(accessToken, project.project_id));
if (init?.body) headers.set("Content-Type", "application/json");
@@ -376,7 +409,7 @@ async function operationalTaskRequest(path: string, getAccessToken?: AccessToken
return payload;
}
export async function fetchOperationalTask(taskId: string, getAccessToken?: AccessTokenProvider, signal?: AbortSignal) {
export async function fetchOperationalTask(taskId: string, getAccessToken?: WorkbenchAccess, signal?: AbortSignal) {
return operationalTaskSchema.parse(await operationalTaskRequest(
`/operational-tasks/${encodeURIComponent(taskId)}`,
getAccessToken,
@@ -384,19 +417,19 @@ export async function fetchOperationalTask(taskId: string, getAccessToken?: Acce
));
}
export async function fetchOperationalTaskReports(taskId: string, offset: number, getAccessToken?: AccessTokenProvider) {
export async function fetchOperationalTaskReports(taskId: string, offset: number, getAccessToken?: WorkbenchAccess) {
return reportPageSchema.parse(await operationalTaskRequest(
`/operational-tasks/${encodeURIComponent(taskId)}/reports?limit=20&offset=${offset}`, getAccessToken,
));
}
export async function fetchOperationalTaskPresentationCursor(taskId: string, getAccessToken?: AccessTokenProvider, signal?: AbortSignal) {
export async function fetchOperationalTaskPresentationCursor(taskId: string, getAccessToken?: WorkbenchAccess, signal?: AbortSignal) {
return investigationPresentationCursorSchema.parse(await operationalTaskRequest(
`/operational-tasks/${encodeURIComponent(taskId)}/presentation-cursor`, getAccessToken, { signal }
));
}
export async function createOperationalTask(input: CreateOperationalTaskInput, getAccessToken?: AccessTokenProvider) {
export async function createOperationalTask(input: CreateOperationalTaskInput, getAccessToken?: WorkbenchAccess) {
return operationalTaskSchema.parse(await operationalTaskRequest(
"/operational-tasks",
getAccessToken,
@@ -409,7 +442,7 @@ export async function decideOperationalTaskAction(taskId: string, actionId: stri
expected_version: number;
decision: OperationalTaskDecision;
comment?: string;
}, getAccessToken?: AccessTokenProvider) {
}, getAccessToken?: WorkbenchAccess) {
return actionSchema.parse(await operationalTaskRequest(
`/operational-tasks/${encodeURIComponent(taskId)}/actions/${encodeURIComponent(actionId)}/decision`,
getAccessToken,
@@ -420,7 +453,7 @@ export async function decideOperationalTaskAction(taskId: string, actionId: stri
export async function executeOperationalTaskAction(taskId: string, actionId: string, input: {
request_id: string;
expected_version: number;
}, getAccessToken?: AccessTokenProvider) {
}, getAccessToken?: WorkbenchAccess) {
return actionSchema.parse(await operationalTaskRequest(
`/operational-tasks/${encodeURIComponent(taskId)}/actions/${encodeURIComponent(actionId)}/execute`,
getAccessToken,
@@ -430,7 +463,7 @@ export async function executeOperationalTaskAction(taskId: string, actionId: str
export async function updateOperationalWorkOrderDraft(taskId: string, actionId: string, input: {
request_id: string; expected_version: number; payload: Record<string, unknown>;
}, getAccessToken?: AccessTokenProvider) {
}, getAccessToken?: WorkbenchAccess) {
return actionSchema.parse(await operationalTaskRequest(
`/operational-tasks/${encodeURIComponent(taskId)}/actions/${encodeURIComponent(actionId)}/draft`,
getAccessToken, { method: "PATCH", body: JSON.stringify(input) }
@@ -439,7 +472,7 @@ export async function updateOperationalWorkOrderDraft(taskId: string, actionId:
export async function confirmOperationalWorkOrderDispatch(taskId: string, actionId: string, input: {
request_id: string; expected_version: number;
}, getAccessToken?: AccessTokenProvider) {
}, getAccessToken?: WorkbenchAccess) {
return actionSchema.parse(await operationalTaskRequest(
`/operational-tasks/${encodeURIComponent(taskId)}/actions/${encodeURIComponent(actionId)}/confirm-dispatch`,
getAccessToken, { method: "POST", body: JSON.stringify(input) }
@@ -449,14 +482,14 @@ export async function confirmOperationalWorkOrderDispatch(taskId: string, action
export async function decideOperationalTaskAccess(taskId: string, accessRequestId: string, input: {
request_id: string; expected_version: number; decision: "approved" | "rejected";
approved_scopes: string[]; comment?: string;
}, getAccessToken?: AccessTokenProvider) {
}, getAccessToken?: WorkbenchAccess) {
return accessRequestSchema.parse(await operationalTaskRequest(
`/operational-tasks/${encodeURIComponent(taskId)}/access-requests/${encodeURIComponent(accessRequestId)}/decision`,
getAccessToken, { method: "POST", body: JSON.stringify(input) }
));
}
export async function fetchOperationalTaskNotifications(getAccessToken?: AccessTokenProvider, signal?: AbortSignal) {
export async function fetchOperationalTaskNotifications(getAccessToken?: WorkbenchAccess, signal?: AbortSignal) {
return notificationPageSchema.parse(await operationalTaskRequest(
"/operational-task-notifications?unread_only=false&limit=100&offset=0",
getAccessToken,
@@ -464,7 +497,7 @@ export async function fetchOperationalTaskNotifications(getAccessToken?: AccessT
)).items;
}
export async function acknowledgeOperationalTaskNotification(notificationId: string, version: number, requestId: string, getAccessToken?: AccessTokenProvider) {
export async function acknowledgeOperationalTaskNotification(notificationId: string, version: number, requestId: string, getAccessToken?: WorkbenchAccess) {
return notificationSchema.parse(await operationalTaskRequest(
`/operational-task-notifications/${encodeURIComponent(notificationId)}/acknowledge`,
getAccessToken,
@@ -472,7 +505,7 @@ export async function acknowledgeOperationalTaskNotification(notificationId: str
));
}
export async function fetchOperationalTaskSchedules(getAccessToken?: AccessTokenProvider, signal?: AbortSignal) {
export async function fetchOperationalTaskSchedules(getAccessToken?: WorkbenchAccess, signal?: AbortSignal) {
return schedulePageSchema.parse(await operationalTaskRequest(
"/operational-tasks/schedules",
getAccessToken,
@@ -488,7 +521,7 @@ export async function createOperationalTaskSchedule(input: {
interval_seconds: number;
next_run_at: string;
priority: "normal" | "urgent";
}, getAccessToken?: AccessTokenProvider) {
}, getAccessToken?: WorkbenchAccess) {
return scheduleSchema.parse(await operationalTaskRequest(
"/operational-tasks/schedules",
getAccessToken,
@@ -499,7 +532,7 @@ export async function createOperationalTaskSchedule(input: {
export async function reconcileOperationalTaskAction(taskId: string, actionId: string, input: {
request_id: string;
expected_version: number;
}, getAccessToken?: AccessTokenProvider) {
}, getAccessToken?: WorkbenchAccess) {
return actionSchema.parse(await operationalTaskRequest(
`/operational-tasks/${encodeURIComponent(taskId)}/actions/${encodeURIComponent(actionId)}/reconcile`,
getAccessToken,
@@ -507,7 +540,7 @@ export async function reconcileOperationalTaskAction(taskId: string, actionId: s
));
}
export async function fetchOperationalTaskEvidenceSnapshot(taskId: string, evidenceId: string, getAccessToken?: AccessTokenProvider) {
export async function fetchOperationalTaskEvidenceSnapshot(taskId: string, evidenceId: string, getAccessToken?: WorkbenchAccess) {
return taskDataSnapshotSchema.parse(await operationalTaskRequest(
`/operational-tasks/${encodeURIComponent(taskId)}/evidence/${encodeURIComponent(evidenceId)}/snapshot`,
getAccessToken
@@ -1,11 +1,11 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { searchPlaces } from "./place-search-client";
import { reverseGeocodePoint, searchPlaces } from "./place-search-client";
const item = { id: "place-1", name: "南桥路", address: "奉贤区南桥路", longitude: 121.441891, latitude: 31.220188, category: "道路名", district: "奉贤区" };
const results = { items: [item], total: 1, truncated: false, region: "奉贤区" };
afterEach(() => vi.restoreAllMocks());
describe("Fengxian place search client", () => {
describe("project place search client", () => {
it("uses the new endpoint with trimmed keywords, identity and project headers", async () => {
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json(results));
expect(await searchPlaces(" 南桥路 ", "project-1", async () => "read-token", undefined)).toEqual(results);
@@ -22,7 +22,7 @@ describe("Fengxian place search client", () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({ ...results, items: [], total: 0 }));
expect((await searchPlaces("未知位置", "project-1")).items).toEqual([]);
});
it("accepts at most ten Fengxian candidates", async () => {
it("accepts at most ten candidates", async () => {
const capped = { ...results, items: Array.from({ length: 10 }, (_, index) => ({ ...item, id: `place-${index}` })), total: 10, truncated: true };
vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json(capped));
expect(await searchPlaces("南桥路", "project-1")).toEqual(capped);
@@ -39,7 +39,21 @@ describe("Fengxian place search client", () => {
{ status: "0", location: { lon: "121", lat: "31" } }
])("rejects malformed, mismatched or legacy responses: %j", async (payload) => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json(payload));
await expect(searchPlaces("南桥路", "project-1")).rejects.toThrow("未获得有效的地名搜索结果");
await expect(searchPlaces("南桥路", "project-1", undefined, undefined, { enabled: true, provider: "tianditu", admin_code: "310120", region: "奉贤区" })).rejects.toThrow("未获得有效的地名搜索结果");
});
it("accepts candidates in different districts within a configured city", async () => {
const cityResults = { ...results, region: "上海市", items: [item, { ...item, id: "place-2", district: "青浦区" }], total: 2 };
vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json(cityResults));
expect(await searchPlaces("路", "project-1", undefined, undefined, {
enabled: true, provider: "tianditu", admin_code: "310000", region: "上海市"
})).toEqual(cityResults);
});
it("accepts a configured project outside Fengxian", async () => {
const value = { ...results, region: "凤阳县", items: [{ ...item, name: "府城镇", district: "凤阳县" }] };
vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json(value));
expect(await searchPlaces("府城镇", "fengyang", undefined, undefined, {
enabled: true, provider: "tianditu", admin_code: "341126", region: "凤阳县"
})).toEqual(value);
});
it("does not fetch blank keywords", async () => {
const fetchMock = vi.spyOn(globalThis, "fetch");
@@ -59,3 +73,29 @@ describe("Fengxian place search client", () => {
expect(fetchMock).not.toHaveBeenCalled();
});
});
describe("reverse geocoding point client", () => {
it("sends coordinates with project and authentication headers", async () => {
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json(item));
expect(await reverseGeocodePoint(item.longitude, item.latitude, "project-1", async () => "token")).toEqual(item);
const [url, init] = fetchMock.mock.calls[0];
expect(url).toContain("/api/v1/reverse-geocoding-requests");
expect(JSON.parse(init?.body as string)).toEqual({ longitude: item.longitude, latitude: item.latitude });
expect(new Headers(init?.headers).get("X-Project-Id")).toBe("project-1");
expect(new Headers(init?.headers).get("Authorization")).toBe("Bearer token");
});
it.each([[181, 31], [121, 91], [NaN, 31], [121, Infinity]])("rejects invalid input %s, %s", async (longitude, latitude) => {
const fetchMock = vi.spyOn(globalThis, "fetch");
await expect(reverseGeocodePoint(longitude, latitude, "project-1")).rejects.toThrow("坐标无效");
expect(fetchMock).not.toHaveBeenCalled();
});
it("rejects a result that changes the clicked point", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({ ...item, longitude: item.longitude + 0.01 }));
await expect(reverseGeocodePoint(item.longitude, item.latitude, "project-1")).rejects.toThrow("未获得有效");
});
it("preserves an out of project scope message", async () => {
vi.spyOn(globalThis, "fetch").mockResolvedValue(Response.json({ detail: "取点位置不在当前项目的地名搜索范围内(凤阳县)" }, { status: 422 }));
await expect(reverseGeocodePoint(117, 32, "project-1")).rejects.toThrow("凤阳县");
});
});
@@ -1,7 +1,8 @@
import { getWorkbenchAccessToken } from "./request-context";
import { z } from "zod";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "./request-context";
import { env } from "@/shared/config/env";
import { createWorkbenchHeaders, findOwnedWorkbenchProject, getServerError } from "./project-client";
import { createWorkbenchHeaders, findOwnedWorkbenchProject, getServerError, type PlaceSearchConfiguration } from "./project-client";
export const MAX_PLACE_SEARCH_RESULTS = 10;
@@ -9,11 +10,11 @@ const placeSchema = z.object({
id: z.string().min(1), name: z.string().trim().min(1), address: z.string(),
longitude: z.number().finite().min(-180).max(180),
latitude: z.number().finite().min(-90).max(90),
category: z.string().nullable(), district: z.literal("奉贤区")
category: z.string().nullable(), district: z.string().trim().min(1)
});
const resultsSchema = z.object({
items: z.array(placeSchema).max(MAX_PLACE_SEARCH_RESULTS), total: z.number().int().min(0).max(MAX_PLACE_SEARCH_RESULTS),
truncated: z.boolean().default(false), region: z.literal("奉贤区")
truncated: z.boolean().default(false), region: z.string().trim().min(1)
});
export type PlaceSearchItem = z.infer<typeof placeSchema>;
export type PlaceSearchResults = z.infer<typeof resultsSchema>;
@@ -21,33 +22,70 @@ export type PlaceSearchResults = z.infer<typeof resultsSchema>;
export async function searchPlaces(
keyword: string,
projectId: string | null,
getAccessToken?: AccessTokenProvider,
signal?: AbortSignal
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal,
configuration?: PlaceSearchConfiguration | null
): Promise<PlaceSearchResults> {
const query = keyword.trim();
if (!query) throw new Error("请输入需要搜索的地址或地名");
if (query.length > 120) throw new Error("查询关键字不能超过120个字符");
const requestSignal = signal
? AbortSignal.any([signal, AbortSignal.timeout(20_000)])
: AbortSignal.timeout(20_000);
const ownedProject = projectId ? null : await findOwnedWorkbenchProject(getAccessToken, requestSignal);
const accessToken = ownedProject?.accessToken ?? await getAccessToken?.();
requestSignal.throwIfAborted();
const resolvedProjectId = projectId ?? ownedProject?.project.project_id;
if (!resolvedProjectId) throw new Error("未找到地名搜索所属项目");
const response = await fetch(`${env.TJWATER_SERVER_API_BASE_URL.replace(/\/$/, "")}/api/v1/place-search-requests`, {
method: "POST",
headers: createWorkbenchHeaders(accessToken, resolvedProjectId, true),
body: JSON.stringify({ keyword: query }),
signal: requestSignal
});
const payload: unknown = await response.json().catch(() => null);
if (!response.ok) throw new Error(getServerError(payload, response.status, "地名搜索"));
const payload = await requestPlaceData("place-search-requests", { keyword: query }, projectId, getAccessToken, signal);
const parsed = resultsSchema.safeParse(payload);
if (!parsed.success
|| new Set(parsed.data.items.map((item) => item.id)).size !== parsed.data.items.length
|| parsed.data.total !== parsed.data.items.length) {
|| parsed.data.total !== parsed.data.items.length
|| (configuration && (parsed.data.region !== configuration.region
|| (!configuration.admin_code.endsWith("00") && parsed.data.items.some((item) => item.district !== configuration.region))))) {
throw new Error("未获得有效的地名搜索结果,请稍后重试");
}
return parsed.data;
}
export async function reverseGeocodePoint(
longitude: number,
latitude: number,
projectId: string | null,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal,
configuration?: PlaceSearchConfiguration | null
): Promise<PlaceSearchItem> {
const coordinates = z.object({
longitude: z.number().finite().min(-180).max(180),
latitude: z.number().finite().min(-90).max(90)
}).safeParse({ longitude, latitude });
if (!coordinates.success) throw new Error("地图取点坐标无效");
const payload = await requestPlaceData("reverse-geocoding-requests", coordinates.data, projectId, getAccessToken, signal);
const parsed = placeSchema.safeParse(payload);
if (!parsed.success || parsed.data.longitude !== longitude || parsed.data.latitude !== latitude
|| (configuration && !configuration.admin_code.endsWith("00") && parsed.data.district !== configuration.region)) {
throw new Error("未获得有效的地图取点结果,请重新取点");
}
return parsed.data;
}
async function requestPlaceData(
path: string,
body: Record<string, string | number>,
projectId: string | null,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal
): Promise<unknown> {
const requestSignal = signal
? AbortSignal.any([signal, AbortSignal.timeout(20_000)])
: AbortSignal.timeout(20_000);
const ownedProject = projectId ? null : await findOwnedWorkbenchProject(getAccessToken, requestSignal);
const accessToken = ownedProject?.accessToken ?? await getWorkbenchAccessToken(getAccessToken);
requestSignal.throwIfAborted();
const resolvedProjectId = projectId ?? ownedProject?.project.project_id;
if (!resolvedProjectId) throw new Error("未找到地名搜索所属项目");
const response = await fetch(`${env.TJWATER_SERVER_API_BASE_URL.replace(/\/$/, "")}/api/v1/${path}`, {
method: "POST",
headers: createWorkbenchHeaders(accessToken, resolvedProjectId, true),
body: JSON.stringify(body),
signal: requestSignal
});
const payload: unknown = await response.json().catch(() => null);
if (!response.ok) throw new Error(getServerError(payload, response.status, "地名搜索"));
return payload;
}
@@ -1,11 +1,57 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import {
fetchWorkbenchProjectPresentation,
parsePlaceSearchConfiguration,
fetchWorkbenchProjects,
clearWorkbenchProjectCache,
findOwnedWorkbenchProject,
parseProjectMapExtent
} from "./project-client";
describe("workbench project client", () => {
it("caches complete authorized lists across repeated openings and refreshes explicitly or after expiry", async () => {
const clock = vi.spyOn(Date, "now").mockReturnValue(100);
const fetch = vi.fn(async () => Response.json({ items: [{ project_id: "supply", gs_workspace: "tjwater_next", status: "active" }], total: 1, limit: 1000, offset: 0 }));
vi.stubGlobal("fetch", fetch);
const provider = async () => "owner-token";
await Promise.all([fetchWorkbenchProjects(provider), fetchWorkbenchProjects(provider)]);
for (let i = 0; i < 10; i++) await fetchWorkbenchProjects(provider);
expect(fetch).toHaveBeenCalledTimes(1);
await fetchWorkbenchProjects(provider, undefined, true);
expect(fetch).toHaveBeenCalledTimes(2);
clock.mockReturnValue(300_101);
await fetchWorkbenchProjects(provider);
expect(fetch).toHaveBeenCalledTimes(3);
clearWorkbenchProjectCache(provider);
await fetchWorkbenchProjects(provider);
expect(fetch).toHaveBeenCalledTimes(4);
});
it("uses the explicitly selected project for each request without rediscovering the demo project", async () => {
const fetchMock = vi.fn();
vi.stubGlobal("fetch", fetchMock);
const getAccessToken = vi.fn(async () => "token");
const project = { project_id: "fengyang", gs_workspace: "fengyang_v2", status: "active" };
const scoped = await findOwnedWorkbenchProject({ project, getAccessToken });
const other = await findOwnedWorkbenchProject({ project: { ...project, project_id: "demo" }, getAccessToken });
expect(scoped).toEqual({ project, accessToken: "token" });
expect(other.project.project_id).toBe("demo");
expect(fetchMock).not.toHaveBeenCalled();
});
it("loads all authorized project pages and excludes inactive projects", async () => {
const fetchMock = vi.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({ items: [
{ project_id: "old", gs_workspace: "old", status: "inactive" },
{ project_id: "demo", gs_workspace: "tjwater_next", status: "active" }
], total: 3, limit: 1000, offset: 0 })))
.mockResolvedValueOnce(new Response(JSON.stringify({ items: [
{ project_id: "fengyang", gs_workspace: "fengyang_v2", status: "active" }
], total: 3, limit: 1000, offset: 2 })));
vi.stubGlobal("fetch", fetchMock);
expect((await fetchWorkbenchProjects()).map((project) => project.project_id)).toEqual(["demo", "fengyang"]);
expect(String(fetchMock.mock.calls[1][0])).toContain("offset=2");
});
afterEach(() => {
vi.unstubAllGlobals();
vi.restoreAllMocks();
@@ -158,3 +204,16 @@ describe("workbench project client", () => {
});
});
});
describe("project place search configuration", () => {
it("reads configured regions and preserves unrelated map configuration", () => {
const config = { enabled: true, provider: "tianditu", admin_code: "341126", region: "凤阳县" };
expect(parsePlaceSearchConfiguration({ legend: "existing", place_search: config })).toEqual(config);
});
it.each([undefined, {}, { place_search: null }, { place_search: { enabled: false } },
{ place_search: { enabled: true, provider: "tianditu", admin_code: "invalid", region: "凤阳县" } }
])("disables absent or invalid configuration: %j", (config) => {
expect(parsePlaceSearchConfiguration(config)).toBeNull();
});
});
+66 -4
View File
@@ -1,8 +1,10 @@
import { ResourceCache } from "@/shared/cache/resource-cache";
import { z } from "zod";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import { env } from "@/shared/config/env";
import type { NetworkViewParams } from "../map/camera";
import { GEOSERVER_WORKSPACE } from "../map/geoserver-config";
import { getWorkbenchAccessToken, getWorkbenchProject, type WorkbenchAccess } from "./request-context";
const projectSchema = z.object({
project_id: z.string().min(1),
@@ -22,12 +24,27 @@ const projectPageSchema = z.object({
export type WorkbenchProject = z.infer<typeof projectSchema>;
const placeSearchConfigurationSchema = z.object({
enabled: z.boolean(),
provider: z.literal("tianditu"),
admin_code: z.string().regex(/^(?:156)?[0-9]{6}$/),
region: z.string().trim().min(1)
});
export type PlaceSearchConfiguration = z.infer<typeof placeSearchConfigurationSchema>;
export function parsePlaceSearchConfiguration(mapConfig: unknown): PlaceSearchConfiguration | null {
if (!mapConfig || typeof mapConfig !== "object" || !("place_search" in mapConfig)) return null;
const parsed = placeSearchConfigurationSchema.safeParse(mapConfig.place_search);
return parsed.success && parsed.data.enabled ? parsed.data : null;
}
const projectMetadataSchema = z.object({
project_id: z.string().min(1),
name: z.string().trim().min(1),
code: z.string().trim().min(1),
gs_workspace: z.string().trim().min(1),
map_extent: z.unknown().nullable().optional(),
map_config: z.unknown().optional(),
status: z.string(),
project_role: z.string().trim().min(1)
});
@@ -64,13 +81,14 @@ export type WorkbenchProjectPresentation = {
systemRole: string | null;
isSystemAdmin: boolean;
networkView: NetworkViewParams | null;
placeSearch: PlaceSearchConfiguration | null;
metadataAvailable: boolean;
accessContextAvailable: boolean;
};
const SERVER_API_BASE_URL = env.TJWATER_SERVER_API_BASE_URL.replace(/\/$/, "");
const PROJECT_CACHE_TTL_MS = 5 * 60_000;
const projectContextPromises = new WeakMap<AccessTokenProvider, {
const projectContextPromises = new WeakMap<WorkbenchAccess, {
promise: Promise<WorkbenchProject>;
expiresAt: number;
}>();
@@ -86,11 +104,13 @@ function awaitProject(promise: Promise<WorkbenchProject>, signal?: AbortSignal)
}
export async function findOwnedWorkbenchProject(
getAccessToken?: AccessTokenProvider,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal
): Promise<{ project: WorkbenchProject; accessToken: string | null | undefined }> {
const accessToken = await getAccessToken?.();
const accessToken = await getWorkbenchAccessToken(getAccessToken);
signal?.throwIfAborted();
const scopedProject = getWorkbenchProject(getAccessToken);
if (scopedProject) return { project: scopedProject, accessToken };
const existing = getAccessToken
? projectContextPromises.get(getAccessToken)
: undefined;
@@ -123,7 +143,7 @@ export async function findOwnedWorkbenchProject(
}
export async function fetchWorkbenchProjectPresentation(
getAccessToken?: AccessTokenProvider,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal
): Promise<WorkbenchProjectPresentation> {
const { project, accessToken } = await findOwnedWorkbenchProject(getAccessToken, signal);
@@ -147,11 +167,53 @@ export async function fetchWorkbenchProjectPresentation(
systemRole: accessContext?.system_role ?? null,
isSystemAdmin: accessContext?.is_system_admin ?? false,
networkView: parseProjectMapExtent(metadata?.map_extent),
placeSearch: parsePlaceSearchConfiguration(metadata?.map_config),
metadataAvailable: metadata !== null,
accessContextAvailable: accessContext !== null
};
}
const projectListCaches = new WeakMap<AccessTokenProvider, ResourceCache>();
export function clearWorkbenchProjectCache(provider?: AccessTokenProvider) {
if (provider) { projectListCaches.delete(provider); projectContextPromises.delete(provider); }
}
export async function fetchWorkbenchProjects(getAccessToken?: AccessTokenProvider, signal?: AbortSignal, force = false) {
if (!getAccessToken) return loadWorkbenchProjects(getAccessToken, signal);
let cache = projectListCaches.get(getAccessToken);
if (!cache) { cache = new ResourceCache(); projectListCaches.set(getAccessToken, cache); }
const pending = cache.load("projects", () => loadWorkbenchProjects(getAccessToken, AbortSignal.timeout(15_000)),
PROJECT_CACHE_TTL_MS, { force });
if (!signal) return pending;
signal.throwIfAborted();
return new Promise<WorkbenchProject[]>((resolve, reject) => {
const abort = () => reject(signal.reason ?? new DOMException("Aborted", "AbortError"));
signal.addEventListener("abort", abort, { once: true });
pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
});
}
async function loadWorkbenchProjects(getAccessToken?: AccessTokenProvider, signal?: AbortSignal) {
const token = await getAccessToken?.();
signal?.throwIfAborted();
const projects: WorkbenchProject[] = [];
let offset = 0;
while (true) {
const response = await fetch(`${SERVER_API_BASE_URL}/api/v1/projects?limit=1000&offset=${offset}`, {
headers: createWorkbenchHeaders(token), signal
});
const payload: unknown = await response.json().catch(() => null);
if (!response.ok) throw new Error(getServerError(payload, response.status, "项目查询"));
const page = projectPageSchema.parse(payload);
projects.push(...page.items.filter((project) => project.status === "active"));
offset += page.items.length;
if (offset >= page.total) break;
if (!page.items.length) throw new Error("项目列表分页未返回后续数据");
}
return projects;
}
export function parseProjectMapExtent(value: unknown): NetworkViewParams | null {
let bbox: z.infer<typeof bboxSchema> | null = null;
if (value && typeof value === "object" && "bbox" in value) {
@@ -1,5 +1,5 @@
import { z } from "zod";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "./request-context";
import { env } from "@/shared/config/env";
import type { PipeFlowCalculation } from "../map/flow-overlay";
import { createWorkbenchHeaders, findOwnedWorkbenchProject, getServerError } from "./project-client";
@@ -20,7 +20,7 @@ export type RealtimePipeFlowSnapshot = {
};
export async function fetchRealtimePipeFlows(
getAccessToken?: AccessTokenProvider,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal,
now = new Date()
): Promise<RealtimePipeFlowSnapshot> {
@@ -0,0 +1,23 @@
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchProject, WorkbenchProjectPresentation } from "./project-client";
export type WorkbenchRequestContext = {
project: WorkbenchProject;
getAccessToken?: AccessTokenProvider;
presentation?: WorkbenchProjectPresentation;
};
// Unscoped callers are retained for isolated tools and existing integrations.
export type WorkbenchAccess = WorkbenchRequestContext | AccessTokenProvider;
export function getWorkbenchTokenProvider(access?: WorkbenchAccess): AccessTokenProvider | undefined {
return typeof access === "function" ? access : access?.getAccessToken;
}
export function getWorkbenchAccessToken(access?: WorkbenchAccess) {
return getWorkbenchTokenProvider(access)?.();
}
export function getWorkbenchProject(access?: WorkbenchAccess) {
return typeof access === "object" ? access.project : undefined;
}
@@ -1,5 +1,5 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { fetchScadaDeviceCollection, fetchScadaSnapshot } from "./scada-client";
import { fetchScadaDeviceCollection, fetchScadaSnapshot, ScadaSystemClient } from "./scada-client";
const device = {
device_id: "SCADA-1",
@@ -119,4 +119,47 @@ describe("SCADA API client", () => {
await expect(fetchScadaDeviceCollection()).rejects.toThrow("未找到GeoServer工作空间");
expect(fetchMock).toHaveBeenCalledOnce();
});
it("reads the bounded latest-value projection and reuses the resolved project", async () => {
const latestPayload = {
items: [{
device_id: "SCADA-1",
device_type: "pressure",
measurement_unit: "MPa",
transmission_mode: "realtime",
transmission_frequency: "15min",
observed_at: "2026-10-22T01:02:00Z",
monitored_value: 0.31,
cleaned_value: 0.3
}],
total: 1,
limit: 500,
offset: 0,
observed_count: 1,
latest_observed_at: "2026-10-22T01:02:00Z"
};
const fetchMock = vi
.fn()
.mockResolvedValueOnce(new Response(JSON.stringify({
items: [{ project_id: "project-1", gs_workspace: "tjwater_next", status: "active" }],
total: 1,
limit: 1000,
offset: 0
}), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify(latestPayload), { status: 200 }))
.mockResolvedValueOnce(new Response(JSON.stringify(latestPayload), { status: 200 }));
vi.stubGlobal("fetch", fetchMock);
const getAccessToken = vi.fn().mockResolvedValue("access-token");
const client = new ScadaSystemClient(getAccessToken);
await expect(client.getLatestReadings()).resolves.toEqual(latestPayload);
await expect(client.getLatestReadings()).resolves.toEqual(latestPayload);
expect(fetchMock).toHaveBeenCalledTimes(3);
expect(String(fetchMock.mock.calls[1]?.[0])).toContain(
"/api/v1/timeseries/scada-readings/latest?limit=500&offset=0"
);
expect(new Headers(fetchMock.mock.calls[1]?.[1]?.headers).get("X-Project-Id")).toBe("project-1");
expect(getAccessToken).toHaveBeenCalledTimes(3);
});
});
+59 -3
View File
@@ -1,5 +1,5 @@
import type { Feature, FeatureCollection, Point } from "geojson";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import { getWorkbenchAccessToken, type WorkbenchAccess } from "./request-context";
import { env } from "@/shared/config/env";
import { z } from "zod";
import { createWorkbenchHeaders, findOwnedWorkbenchProject, getServerError } from "./project-client";
@@ -36,7 +36,29 @@ const scadaReadingSchema = z.object({
const scadaReadingsSchema = z.array(scadaReadingSchema);
const latestScadaReadingSchema = z.object({
device_id: z.string().trim().min(1),
device_type: z.string().trim().min(1),
measurement_unit: z.string(),
transmission_mode: z.string(),
transmission_frequency: z.string(),
observed_at: z.string().datetime({ offset: true }).nullable(),
monitored_value: z.number().finite().nullable(),
cleaned_value: z.number().finite().nullable()
});
const latestScadaReadingsSchema = z.object({
items: z.array(latestScadaReadingSchema),
total: z.number().int().nonnegative(),
limit: z.number().int().min(1).max(500),
offset: z.number().int().nonnegative(),
observed_count: z.number().int().nonnegative(),
latest_observed_at: z.string().datetime({ offset: true }).nullable()
});
export type ScadaDevice = z.infer<typeof scadaDeviceSchema>;
export type LatestScadaReading = z.infer<typeof latestScadaReadingSchema>;
export type LatestScadaReadings = z.infer<typeof latestScadaReadingsSchema>;
export type ScadaSnapshot = {
collection: FeatureCollection<Point, ScadaDevice>;
@@ -49,15 +71,49 @@ const SERVER_API_BASE_URL = env.TJWATER_SERVER_API_BASE_URL.replace(/\/$/, "");
const SCADA_LOOKBACK_MS = 15 * 60 * 1000;
const SCADA_READING_BATCH_SIZE = 100;
export class ScadaSystemClient {
private projectIdPromise: Promise<string> | null = null;
constructor(private readonly getAccessToken?: WorkbenchAccess) {}
async getLatestReadings(signal?: AbortSignal): Promise<LatestScadaReadings> {
const [projectId, accessToken] = await Promise.all([
this.resolveProjectId(),
getWorkbenchAccessToken(this.getAccessToken)
]);
return latestScadaReadingsSchema.parse(
await requestJson(
"/api/v1/timeseries/scada-readings/latest?limit=500&offset=0",
accessToken,
projectId,
signal
)
);
}
private resolveProjectId() {
// Project identity is stable for this panel instance. Do not bind the shared
// promise to an individual refresh signal because React StrictMode cancels
// and immediately restarts effects during development.
this.projectIdPromise ??= findOwnedWorkbenchProject(this.getAccessToken)
.then(({ project }) => project.project_id)
.catch((error) => {
this.projectIdPromise = null;
throw error;
});
return this.projectIdPromise;
}
}
export async function fetchScadaDeviceCollection(
getAccessToken?: AccessTokenProvider,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal
): Promise<FeatureCollection<Point, ScadaDevice>> {
return (await fetchScadaSnapshot(getAccessToken, signal)).collection;
}
export async function fetchScadaSnapshot(
getAccessToken?: AccessTokenProvider,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal,
now = new Date()
): Promise<ScadaSnapshot> {
@@ -1,5 +1,5 @@
import { z } from "zod";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "./request-context";
import { env } from "@/shared/config/env";
import { createWorkbenchHeaders, findOwnedWorkbenchProject, getServerError } from "./project-client";
@@ -47,7 +47,7 @@ export async function fetchWorkbenchAnalysisHistory(
options: {
limit?: number;
offset?: number;
getAccessToken?: AccessTokenProvider;
getAccessToken?: WorkbenchAccess;
signal?: AbortSignal;
} = {}
): Promise<WorkbenchAnalysisHistoryPage> {
@@ -1,6 +1,6 @@
import { z } from "zod";
import type { FeatureCollection, Geometry, Position } from "geojson";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "./request-context";
import { env } from "@/shared/config/env";
import { formatDateTime } from "@/shared/utils/date-time";
import type {
@@ -254,7 +254,7 @@ export function parseWorkbenchRuntimeSnapshot(payload: unknown): WorkbenchRuntim
export async function fetchWorkbenchAnalysisRun(
runId: string,
getAccessToken?: AccessTokenProvider,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal
): Promise<WorkbenchAnalysisProjection> {
const normalizedRunId = runId.trim();
@@ -1,5 +1,5 @@
import { z } from "zod";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "./request-context";
import { env } from "@/shared/config/env";
import {
parseOperationalTaskNotification,
@@ -60,7 +60,7 @@ export type WorkbenchSyncSnapshot = {
};
export async function fetchWorkbenchSyncSnapshot(
getAccessToken?: AccessTokenProvider,
getAccessToken?: WorkbenchAccess,
signal?: AbortSignal
): Promise<WorkbenchSyncSnapshot> {
const { project, accessToken } = await findOwnedWorkbenchProject(getAccessToken, signal);
@@ -82,7 +82,7 @@ export async function fetchWorkbenchSyncSnapshot(
export async function consumeWorkbenchEvents(input: {
after: number;
getAccessToken?: AccessTokenProvider;
getAccessToken?: WorkbenchAccess;
onEvents: (events: WorkbenchEvent[]) => void;
onOpen?: () => void;
onReset: () => Promise<void>;
@@ -1,6 +1,6 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { Archive, BarChart3, ChevronRight, LoaderCircle, RefreshCw } from "lucide-react";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "../api/request-context";
import { Button } from "@/shared/ui/button";
import { Disclosure } from "@/shared/ui/disclosure";
import { StatusBadge, type StatusTone } from "@/shared/ui/status";
@@ -22,7 +22,7 @@ export function AnalysisHistorySection({
getAccessToken,
onOpenArtifact
}: {
getAccessToken?: AccessTokenProvider;
getAccessToken?: WorkbenchAccess;
onOpenArtifact: (artifact: AnalysisArtifact) => void;
}) {
const [items, setItems] = useState<WorkbenchAnalysisHistoryItem[]>([]);
@@ -1,5 +1,5 @@
import { BarChart3, X } from "lucide-react";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "../api/request-context";
import { Button } from "@/shared/ui/button";
import type { AnalysisArtifact } from "../workspace/workspace-model";
import { AnalysisHistorySection } from "./analysis-history-section";
@@ -12,7 +12,7 @@ export function AnalysisResultsPanel({
}: {
open: boolean;
onClose: () => void;
getAccessToken?: AccessTokenProvider;
getAccessToken?: WorkbenchAccess;
onOpenArtifact: (artifact: AnalysisArtifact) => void;
}) {
if (!open) return null;
@@ -1,7 +1,7 @@
import { Check, Copy, Database, X } from "lucide-react";
import type { ComponentType } from "react";
import { useEffect, useRef, useState } from "react";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "../api/request-context";
import {
MAP_FOCUS_SURFACE_CLASS_NAME,
MAP_MAJOR_PANEL_RADIUS_CLASS_NAME,
@@ -36,7 +36,7 @@ import { FeaturePropertyList } from "./feature-property-list";
type FeaturePopoverProps = {
feature: DetailFeature | null;
projectId: string | null;
getAccessToken?: AccessTokenProvider;
getAccessToken?: WorkbenchAccess;
onClose: () => void;
};
@@ -1,4 +1,4 @@
import { ChevronDown, LocateFixed, MapPin, Search, Trash2 } from "lucide-react";
import { ChevronDown, Crosshair, LocateFixed, MapPin, Search, Trash2 } from "lucide-react";
import { useId, useLayoutEffect, useRef } from "react";
import { Button } from "@/shared/ui/button";
import { Input } from "@/shared/ui/input";
@@ -31,8 +31,9 @@ export function GeocodingPanel({ geocoding }: { geocoding: WorkbenchGeocoding })
const candidateListRef = useRef<HTMLUListElement | null>(null);
const changeSelectionRef = useRef<HTMLButtonElement | null>(null);
const { address, result, results, pending, error, enabled } = geocoding;
const mapResult = geocoding.origin === "map";
const selectionCollapsed = Boolean(result && !geocoding.choosing);
const hideSelectionHint = Boolean(results?.items.length && enabled && !error);
const hideSelectionHint = Boolean(results?.items.length && enabled && !error && !geocoding.picking);
useLayoutEffect(() => {
if (selectionCollapsed || !result) return;
const list = candidateListRef.current;
@@ -42,12 +43,13 @@ export function GeocodingPanel({ geocoding }: { geocoding: WorkbenchGeocoding })
const row = selected.getBoundingClientRect();
list.scrollTop += row.top - viewport.top - (list.clientHeight - row.height) / 2;
}, [selectionCollapsed, result, results]);
const status = error
?? (pending ? "正在搜索地名…"
const status = !geocoding.configured ? "当前项目暂未配置地名搜索" : error
?? (pending ? (mapResult ? "正在查询取点位置…" : "正在搜索地名…")
: !enabled ? "等待地图加载后即可定位"
: geocoding.picking ? "点击地图查询地名,按 Esc 结束取点"
: result ? "已在地图标出所选位置"
: results ? results.items.length ? "选择一个候选位置进行定位" : "奉贤区内未找到匹配位置,请细化关键字"
: "搜索奉贤区内地址或地名,支持回车查询");
: results ? results.items.length ? "选择一个候选位置进行定位" : `${geocoding.region}内未找到匹配位置,请细化关键字`
: `搜索${geocoding.region}内地址或地名,支持回车查询`);
return (
<div className="flex min-h-0 flex-1 flex-col gap-3">
@@ -79,12 +81,17 @@ export function GeocodingPanel({ geocoding }: { geocoding: WorkbenchGeocoding })
aria-label="搜索地名"
className="shrink-0 gap-1.5 px-3 text-xs"
disabled={!enabled || !address.trim()}
loading={pending}
loading={pending && !mapResult}
loadingLabel="正在搜索地名"
>
<Search aria-hidden="true" />查询
</Button>
</div>
<Button type="button" variant="secondary" className="w-full text-xs"
aria-label="从地图取点查找地名" aria-pressed={geocoding.picking} disabled={!enabled}
onClick={geocoding.togglePicking}>
<Crosshair aria-hidden="true" />{geocoding.picking ? "结束取点" : "地图取点"}
</Button>
<div
id={statusId}
role={error ? "alert" : "status"}
@@ -97,9 +104,9 @@ export function GeocodingPanel({ geocoding }: { geocoding: WorkbenchGeocoding })
</form>
{results && results.items.length > 0 ? (
<section aria-label="搜索结果" className="flex min-h-0 flex-1 flex-col gap-2 border-t border-[var(--surface-divider)] pt-3">
<div className="flex h-10 shrink-0 items-center justify-between gap-2 px-1 text-[11px] text-[var(--ink-muted)]">
<span className="text-xs font-semibold">{selectionCollapsed ? "已选位置" : "选择位置"}</span>
{selectionCollapsed ? (
<div className={cn("flex shrink-0 items-center justify-between gap-2 px-1 text-[11px] text-[var(--ink-muted)]", mapResult ? "h-6" : "h-10")}>
<span className="text-xs font-semibold">{selectionCollapsed ? mapResult ? "取点结果" : "已选位置" : "选择位置"}</span>
{selectionCollapsed && !mapResult ? (
<Button ref={changeSelectionRef} type="button" variant="secondary" className="gap-1.5 px-3 text-xs" aria-expanded={false}
onClick={(event) => {
geocoding.changeSelection();
@@ -111,7 +118,7 @@ export function GeocodingPanel({ geocoding }: { geocoding: WorkbenchGeocoding })
}}>
更换位置<ChevronDown aria-hidden="true" />
</Button>
) : <span className="tabular-nums">{results.truncated ? `前 ${results.total} 个结果` : `共 ${results.total} 个结果`}</span>}
) : mapResult ? <span>地图位置</span> : <span className="tabular-nums">{results.truncated ? `前 ${results.total} 个结果` : `共 ${results.total} 个结果`}</span>}
</div>
{!selectionCollapsed ? <ul ref={candidateListRef} aria-busy={pending} className={cn(RESULT_VIEWPORT_CLASS_NAME, "bg-transparent", pending && "opacity-60")}>
{results.items.map((item, index) => (
@@ -132,8 +139,8 @@ export function GeocodingPanel({ geocoding }: { geocoding: WorkbenchGeocoding })
{result && selectionCollapsed ? (
<section aria-label="定位结果" className={cn(RESULT_VIEWPORT_CLASS_NAME, "flex flex-col gap-2 overflow-hidden")}>
<div className="min-h-0 flex-1 overflow-y-auto overscroll-contain [scrollbar-width:thin]">
<div className="space-y-3">
<div className="flex min-h-16 items-center gap-3 border-b border-[var(--surface-divider)] px-1 py-3 text-xs">
<div className={mapResult ? "space-y-2" : "space-y-3"}>
<div className={cn("flex items-center gap-3 border-b border-[var(--surface-divider)] px-1 text-xs", mapResult ? "min-h-12 py-1" : "min-h-16 py-3")}>
<PlaceSummary item={result} annotation={result.category ?? result.district} />
</div>
<dl aria-label="经纬度坐标" className="space-y-1 px-1">
@@ -55,7 +55,7 @@ export function InvestigationDiagramView({
renderDetails: (node: InvestigationDiagram["node_refs"][number]) => ReactNode;
onAsk?: (node: InvestigationDiagram["node_refs"][number]) => void;
running?: boolean;
onLocate?: (targets: InvestigationMapTarget[]) => void;
onLocate?: (targets: InvestigationMapTarget[]) => Promise<unknown> | void;
}) {
const [selectedNodeId, setSelectedNodeId] = useState<string | null>(null);
const pointerStart = useRef<{ nodeId: string; x: number; y: number } | null>(null);
@@ -9,7 +9,7 @@ import { cn } from "@/shared/ui/cn";
/** Report-specific progressive disclosure. The source stays mounted while reading. */
export function InvestigationExpandCard({
title, label = title, preview, children, wide = false, onOpen, contentRef,
triggerLabel = `展开${title}`, className, revision, disabled = false, reuseContent = false
triggerLabel = `展开${title}`, className, revision, disabled = false, reuseContent = false, headingAccessory
}: {
title: string;
label?: string;
@@ -25,6 +25,7 @@ export function InvestigationExpandCard({
disabled?: boolean;
/** Move one live content host between slots, preserving expensive renderers. */
reuseContent?: boolean;
headingAccessory?: ReactNode;
}) {
const id = useId();
const triggerRef = useRef<HTMLButtonElement>(null);
@@ -77,7 +78,10 @@ export function InvestigationExpandCard({
style={{ borderRadius: 12 }}
>
<div className="investigation-card-heading">
<h3 className="text-sm font-semibold text-[var(--ink)]">{title}</h3>
<div className="flex min-w-0 flex-wrap items-center gap-2">
<h3 className="text-sm font-semibold text-[var(--ink)]">{title}</h3>
{headingAccessory}
</div>
<Dialog.Trigger asChild>
<Button ref={triggerRef} variant="ghost" size="icon-sm" aria-label={triggerLabel} disabled={disabled}
title={triggerLabel} onClick={(event) => setKeyboard(event.detail === 0)}>
@@ -0,0 +1,62 @@
import { fireEvent, render, screen } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { InvestigationReportBlocks } from "./investigation-report-blocks";
import type { OperationalTask, OperationalTaskReport } from "../api/operational-task-client";
const now = "2026-10-20T08:00:00Z";
const task: Pick<OperationalTask, "evidence"> = { evidence: [{
evidence_id: "saved-evidence", kind: "synthetic", summary: "保存的演练压力,不代表现场事实。",
source_label: "保存的监测来源", observed_at: now, recorded_at: now, recorded_by: "agent", source_ref: null, has_snapshot: false,
}] };
const snapshot: OperationalTaskReport = {
revision: 3, execution_generation: 2, source_session_id: "session", published_at: now, published_by: "agent",
report: { title: "演练调查报告", current_conclusion: "待核验", conclusion_boundary: "演练数据",
evidence_refs: ["saved-evidence"], recommendations: [], pending_items: [], ui_blocks: [{
evidence_refs: ["saved-evidence"], block: { version: "answer-ui@1", block_id: "analysis", fallback_text: "分析待核验。",
spec: { root: "evidence", elements: { evidence: { type: "Evidence", children: [], props: {
title: "监测依据", summary: "模型填写的错误摘要", source: "模型填写的错误来源", kind: "observed",
observed_at: null, evidence_id: "saved-evidence",
} } } },
},
}] },
};
describe("formal report interactive content", () => {
it("uses saved evidence facts and quotes the selected report version without dispatching work", () => {
const onContinue = vi.fn();
render(<InvestigationReportBlocks task={task} snapshot={snapshot} onContinue={onContinue} />);
fireEvent.click(screen.getByRole("button", { name: /监测依据/ }));
expect(screen.getByText("保存的演练压力,不代表现场事实。")).toBeVisible();
expect(screen.queryByText(/模型填写/)).not.toBeInTheDocument();
fireEvent.click(screen.getByRole("button", { name: "针对这部分提问" }));
expect(onContinue).toHaveBeenCalledWith(expect.objectContaining({
context: { report_revision: 3 }, reportGeneration: 2,
reference: { title: "演练调查报告 · 报告第 3 版 · 监测依据",
text: expect.stringContaining("保存的监测来源\n类别:演练数据") },
}));
expect(onContinue.mock.calls[0][0].reference.text).toContain("报告第 3 版 · 第 2 轮");
expect(onContinue.mock.calls[0][0].reference.text).toContain("引用依据:保存的监测来源(saved-evidence)");
});
it("keeps unsupported content readable through its fallback and renders no executable nodes", () => {
const next = structuredClone(snapshot);
next.report.ui_blocks![0].block.version = "answer-ui@future";
next.report.ui_blocks![0].block.spec = { type: "iframe", src: "https://example.invalid" };
const { container } = render(<InvestigationReportBlocks task={task} snapshot={next} onContinue={vi.fn()} />);
expect(screen.getByText("分析待核验。")).toBeVisible();
expect(container.querySelector("iframe")).toBeNull();
});
it("turns report form input into a versioned conversation draft", async () => {
const next = structuredClone(snapshot);
next.report.ui_blocks![0].block.spec = { root: "form", elements: { form: {
type: "FollowUpForm", children: [], props: { title: "补充资料", description: "填写核验位置",
fields: [{ name: "site", label: "位置", kind: "text", required: true }] },
} } };
const onContinue = vi.fn();
render(<InvestigationReportBlocks task={task} snapshot={next} onContinue={onContinue} />);
fireEvent.change(screen.getByLabelText("位置(必填)"), { target: { value: "演练位置" } });
fireEvent.click(screen.getByRole("button", { name: "带入对话" }));
expect(await screen.findByText("资料已带入对话,请确认后发送。")).toBeVisible();
expect(onContinue.mock.calls[0][0].reference.text).toContain("位置:演练位置");
expect(onContinue.mock.calls[0][0].context).toEqual({ report_revision: 3 });
});
});
@@ -0,0 +1,63 @@
import { AnswerUiView, parseAnswerUiBlock, type AnswerUiBlock, type AnswerUiSelection } from "@/features/agent";
import type { OperationalTask, OperationalTaskReport } from "../api/operational-task-client";
import type { InvestigationDiscussion, InvestigationMapTarget } from "../api/investigation-report";
export function InvestigationReportBlocks({ task, snapshot, onContinue, onLocate }: {
task: Pick<OperationalTask, "evidence">;
snapshot: OperationalTaskReport;
onContinue: (discussion?: InvestigationDiscussion) => Promise<boolean | void> | boolean | void;
onLocate?: (targets: InvestigationMapTarget[]) => Promise<unknown> | void;
}) {
const blocks = snapshot.report.ui_blocks ?? [];
if (!blocks.length) return null;
const ask = async (selection: AnswerUiSelection) => {
const result = await onContinue({
reference: {
title: `${snapshot.report.title} · 报告第 ${snapshot.revision} 版 · ${selection.title}`,
text: `${selection.text}\n报告第 ${snapshot.revision} 版${snapshot.execution_generation ? ` · 第 ${snapshot.execution_generation} 轮` : ""}`
},
context: { report_revision: snapshot.revision },
reportGeneration: snapshot.execution_generation
});
if (result === false) throw new Error("引用暂未带入对话,请重试。");
};
return <section className="investigation-report-section space-y-4" aria-label="交互分析">
<div>
<h3 className="text-sm font-semibold">数据与分析</h3>
<p className="mt-1 text-xs text-muted-foreground">探索报告中的数据,选择内容后可引用到对话。</p>
</div>
{blocks.map((item) => {
const parsed = parseAnswerUiBlock(item.block);
const evidence = task.evidence.filter((entry) => item.evidence_refs.includes(entry.evidence_id));
const quote = (selection: AnswerUiSelection) => ask({
...selection,
text: `${selection.text}\n引用依据:${item.evidence_refs.map((id) => {
const record = evidence.find((entry) => entry.evidence_id === id);
return record ? `${record.source_label}(${id})` : `${id}(记录当前不可用)`;
}).join("、")}`
});
// Evidence facts are supplied by the saved task record, not generated presentation props.
const block: AnswerUiBlock | null = parsed ? { ...parsed, spec: {
...parsed.spec,
elements: Object.fromEntries(Object.entries(parsed.spec.elements).map(([id, node]) => {
if (node.type !== "Evidence") return [id, node];
const record = evidence.find((entry) => entry.evidence_id === node.props.evidence_id);
return [id, record ? { ...node, props: {
...node.props, summary: record.summary, source: record.source_label,
observed_at: record.observed_at,
kind: record.kind === "synthetic" ? "demo" : record.kind === "human_input" ? "human_input" : "observed"
} } : { type: "Text", children: [], props: { text: "这条引用证据当前不可用。", tone: "warning" } }];
}))
} } : null;
return <div key={`${snapshot.revision}:${item.block.block_id}`} className="space-y-2">
{block ? <AnswerUiView block={block} onAsk={quote} submitMode="draft"
onSubmit={(text) => quote({ title: "补充资料", text })}
onLocate={onLocate ? (target) => onLocate(target.feature_ids.map((id) => ({ source_id: target.layer, feature_id: id }))) : undefined} />
: <p className="whitespace-pre-wrap rounded-lg border p-3 text-sm leading-6">{item.block.fallback_text}</p>}
<p className="text-[11px] leading-5 text-muted-foreground">
引用依据:{evidence.map((entry) => entry.source_label).join("、") || "关联记录当前不可用"}
</p>
</div>;
})}
</section>;
}
@@ -0,0 +1,96 @@
import { useEffect, useRef, useState, type RefObject } from "react";
import { Button } from "@/shared/ui/button";
import { useReadingWorkspace } from "@/shared/ui/reading-workspace-context";
const labels = {
任务报告: "结论",
交互分析: "分析",
当前调查进展: "调查进展",
当前需处理: "待办",
处置进展: "处置",
数据缺口: "缺口",
调查脉络: "脉络",
主要依据: "依据",
任务时间线: "时间线",
报告版本: "版本",
};
export type InvestigationReportSection = keyof typeof labels;
export function InvestigationReportNavigation({ reportRef, sections }: {
reportRef: RefObject<HTMLElement | null>;
sections: InvestigationReportSection[];
}) {
const navigation = useRef<HTMLElement>(null);
const lastJump = useRef<{ section: string; scrollTop: number } | null>(null);
const reading = useReadingWorkspace();
const [current, setCurrent] = useState<string>("任务报告");
const sectionKey = sections.join("|");
useEffect(() => {
const report = reportRef.current;
const nav = navigation.current;
const scroll = report?.closest<HTMLElement>("[data-reading-scroll]");
if (!report || !nav || !scroll) return;
const targets = sectionKey.split("|").flatMap((label) => {
const element = report.querySelector<HTMLElement>(`section[aria-label="${label}"]`);
return element ? [{ label, element }] : [];
});
let frame = 0;
const update = () => {
// Near the document end an anchor cannot always reach the top. Keep the
// chosen chapter current until the reader actually moves away from it.
if (lastJump.current && Math.abs(lastJump.current.scrollTop - scroll.scrollTop) < 1
&& targets.some(({ label }) => label === lastJump.current?.section)) {
setCurrent(lastJump.current.section);
return;
}
lastJump.current = null;
const edge = scroll.getBoundingClientRect().top + nav.offsetHeight + 20;
const active = [...targets].reverse().find(({ element }) => element.getBoundingClientRect().top <= edge);
setCurrent(active?.label ?? targets[0]?.label ?? "");
};
const schedule = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(update);
};
scroll.addEventListener("scroll", schedule, { passive: true });
const observer = new ResizeObserver(schedule);
observer.observe(report);
observer.observe(scroll);
schedule();
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
scroll.removeEventListener("scroll", schedule);
};
}, [reportRef, sectionKey, reading?.active, reading?.view]);
// Keep the active chapter reachable when the navigation overflows on a phone.
useEffect(() => {
const nav = navigation.current;
const button = nav?.querySelector<HTMLElement>('[aria-current="location"]');
if (!nav || !button) return;
const bounds = nav.getBoundingClientRect();
const target = button.getBoundingClientRect();
if (target.left < bounds.left) nav.scrollLeft -= bounds.left - target.left + 4;
else if (target.right > bounds.right) nav.scrollLeft += target.right - bounds.right + 4;
}, [current]);
return <nav ref={navigation} className="investigation-report-navigation" aria-label="报告章节">
{sections.map((section) => <Button key={section} type="button" variant="ghost" size="sm"
aria-current={current === section ? "location" : undefined}
className="shrink-0 font-normal"
onClick={() => {
const target = reportRef.current?.querySelector<HTMLElement>(`section[aria-label="${section}"]`);
if (!target) return;
target.tabIndex = -1;
target.focus({ preventScroll: true });
target.scrollIntoView({ block: "start", behavior: "instant" });
const scroll = target.closest<HTMLElement>("[data-reading-scroll]");
if (scroll) lastJump.current = { section, scrollTop: scroll.scrollTop };
setCurrent(section);
}}>
{labels[section]}
</Button>)}
</nav>;
}
@@ -21,17 +21,20 @@ import {
import { InvestigationDiagramView } from "./investigation-diagram-view";
import { InvestigationExpandCard } from "./investigation-expand-card";
import { useReportUpdateMotion } from "../hooks/use-report-update-motion";
import { ExpandableReading } from "@/shared/ui/reading-workspace";
import { InvestigationReportBlocks } from "./investigation-report-blocks";
import { InvestigationReportNavigation, type InvestigationReportSection } from "./investigation-report-navigation";
type ReportSelection = { snapshot: OperationalTaskReport; diagram: InvestigationDiagram | null };
type Props = {
task: OperationalTask;
onContinue: (discussion?: InvestigationDiscussion) => void;
onContinue: (discussion?: InvestigationDiscussion) => Promise<boolean | void> | boolean | void;
renderAction: (action: OperationalTaskAction) => ReactNode;
renderEvidence: (evidence: OperationalTaskEvidence) => ReactNode;
onLoadReports?: (offset: number) => Promise<OperationalTaskReportPage>;
onReportViewed?: (generation: number, revision: number) => void;
focusActionId?: string | null;
onLocate?: (targets: InvestigationMapTarget[]) => void;
onLocate?: (targets: InvestigationMapTarget[]) => Promise<unknown> | void;
};
const roundLabel = (snapshot: OperationalTaskReport) =>
@@ -167,6 +170,17 @@ export function InvestigationTaskReport({
const timeline = investigationTimeline(task, snapshot);
const reportRef = useReportUpdateMotion(task.task_id,
`${snapshot?.execution_generation}:${snapshot?.revision}:${progress?.run_id}:${progress?.revision}`, live);
const sections: InvestigationReportSection[] = [
"任务报告",
...(report?.ui_blocks?.length ? ["交互分析" as const] : []),
...(live ? ["当前调查进展" as const] : []),
...(pendingActions.length ? ["当前需处理" as const] : []),
...(completedActions.length ? ["处置进展" as const] : []),
...(report?.data_gaps?.length ? ["数据缺口" as const] : []),
...(diagram ? ["调查脉络" as const] : []),
"主要依据", "任务时间线",
...(onLoadReports ? ["报告版本" as const] : []),
];
useEffect(() => {
if (snapshot?.execution_generation == null || !onReportViewed) return;
@@ -209,6 +223,8 @@ export function InvestigationTaskReport({
};
return (
<ExpandableReading title={snapshot?.report.title ?? task.title}
summary={<p>{snapshot?.report.current_conclusion ?? task.summary}</p>}>
<article ref={reportRef} aria-label="调查任务报告" className="investigation-report surface-reading">
<header className="investigation-report-header">
<div className="min-w-0">
@@ -244,6 +260,8 @@ export function InvestigationTaskReport({
</Button>
</header>
<InvestigationReportNavigation reportRef={reportRef} sections={sections} />
{latestAvailable ? (
<div className="investigation-report-update" role="status">
<span>正在阅读历史报告{olderRevision ? ",已有新报告" : ""}</span>
@@ -254,9 +272,8 @@ export function InvestigationTaskReport({
) : null}
<InvestigationExpandCard title="当前结果" label="任务报告" disabled={!report}
revision={`${snapshot?.execution_generation}:${snapshot?.revision}`} preview={<>
<div className="flex flex-wrap items-center justify-between gap-2">
{report ? (
revision={`${snapshot?.execution_generation}:${snapshot?.revision}`}
headingAccessory={report ? (
<StatusBadge tone={insufficient ? "warning" : "neutral"}>
{insufficient
? "证据不足"
@@ -265,9 +282,10 @@ export function InvestigationTaskReport({
: "结果未记录"}
</StatusBadge>
) : null}
</div>
preview={<>
{report && snapshot ? (
<>
{previousRound || olderRevision || insufficient || report.stage !== "final" || report.outcome !== "concluded" ? (
<p className="mt-3 text-sm font-semibold leading-6 text-[var(--ink)]">
{previousRound
? task.status === "queued" || task.status === "running"
@@ -283,11 +301,10 @@ export function InvestigationTaskReport({
: "无法形成结论 · 正在结束本轮"
: report.stage === "interim"
? "阶段性判断"
: report.outcome === "concluded"
? "调查结论"
: "历史报告内容"}
: "历史报告内容"}
</p>
<p className="investigation-conclusion-preview mt-1 text-sm leading-6 text-[var(--ink)]">{formatInvestigationText(report.current_conclusion)}</p>
) : null}
<p className="investigation-conclusion-preview mt-2 text-sm leading-6 text-[var(--ink)]">{formatInvestigationText(report.current_conclusion)}</p>
<p className="mt-2 text-xs leading-5 text-[var(--ink-muted)]">
结论边界:{formatInvestigationText(report.conclusion_boundary)}
</p>
@@ -318,6 +335,8 @@ export function InvestigationTaskReport({
</> : <p className="text-sm text-[var(--ink-muted)]">尚未发布本轮调查报告。</p>}
</InvestigationExpandCard>
{snapshot ? <InvestigationReportBlocks task={task} snapshot={snapshot} onContinue={onContinue} onLocate={onLocate} /> : null}
{live ? <section aria-label="当前调查进展" className="investigation-report-section">
<h3 className="text-sm font-semibold text-[var(--ink)]">当前调查进展</h3>
<p className="mt-2 whitespace-pre-wrap break-words text-sm leading-6 text-[var(--ink)]">{formatInvestigationText(progress?.progress.summary ?? "尚未发布本轮调查进展。")}</p>
@@ -622,6 +641,7 @@ export function InvestigationTaskReport({
任务更新于 {dateLabel(task.updated_at)}
</p>
</article>
</ExpandableReading>
);
}
@@ -21,6 +21,7 @@ type MobileWorkbenchSheetProps = {
onClose: () => void;
children: ReactNode;
className?: string;
suspended?: boolean;
};
const SNAP_ORDER: MobileWorkbenchSheetSnap[] = ["half", "full"];
@@ -31,7 +32,8 @@ export function MobileWorkbenchSheet({
onSnapChange,
onClose,
children,
className
className,
suspended = false
}: MobileWorkbenchSheetProps) {
const pointerStartRef = useRef<{ y: number; height: number } | null>(null);
const draggedRef = useRef(false);
@@ -52,6 +54,7 @@ export function MobileWorkbenchSheet({
}, []);
useEffect(() => {
if (suspended) return;
const handleEscape = (event: globalThis.KeyboardEvent) => {
if (event.key === "Escape" && !event.defaultPrevented) {
onClose();
@@ -60,7 +63,7 @@ export function MobileWorkbenchSheet({
window.addEventListener("keydown", handleEscape);
return () => window.removeEventListener("keydown", handleEscape);
}, [onClose]);
}, [onClose, suspended]);
function handlePointerDown(event: PointerEvent<HTMLButtonElement>) {
pointerStartRef.current = {
@@ -0,0 +1,29 @@
import { Droplet } from "lucide-react";
import { StartupScreen } from "@/shared/ui/startup-screen";
export type ProjectStartupState = { phase: "projects" } | { phase: "context"; projectName: string };
export function ProjectStartupScreen({ state, error, onRetry }: {
state: ProjectStartupState;
error: string | null;
onRetry: () => void;
}) {
const readingProjects = state.phase === "projects";
return (
<StartupScreen
brand={{ name: "TJWater", description: "智慧水务平台", icon: <Droplet strokeWidth={1.5} /> }}
title={error ? "暂时无法进入工作台" : readingProjects ? "正在加载授权项目" : "正在准备项目环境"}
description={error ? "请查看原因后重试。" : "正在准备你的项目工作台,完成后自动进入。"}
progressLabel="项目加载进度"
steps={[
{ id: "projects", label: "读取授权项目", state: readingProjects ? "loading" : "complete",
detail: readingProjects ? "获取当前账号可访问的项目列表" : "已获取可访问的项目" },
{ id: "context", label: "准备项目环境", state: readingProjects ? "waiting" : "loading",
detail: state.phase === "context" ? `${state.projectName}\n正在读取项目配置与访问权限` : "等待项目列表返回" }
]}
error={error}
onRetry={onRetry}
/>
);
}
@@ -0,0 +1,100 @@
import { useId, useRef, useState } from "react";
import * as DialogPrimitive from "@radix-ui/react-dialog";
import { motion, useIsPresent, useReducedMotion } from "motion/react";
import { Droplet, RefreshCw, X } from "lucide-react";
import { Button } from "@/shared/ui/button";
import { Dialog, DialogDescription, DialogPortal, DialogTitle } from "@/shared/ui/dialog";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/shared/ui/select";
import type { WorkbenchProjectSelection } from "./workbench-top-bar-menus";
const roleLabels: Record<string, string> = { member: "项目成员", admin: "项目管理员", viewer: "只读成员", owner: "项目负责人" };
export function ProjectSwitchDialog({ selection, keyboardOpened, onClose, onRestoreFocus }: {
selection: WorkbenchProjectSelection;
keyboardOpened: boolean;
onClose: () => void;
onRestoreFocus: () => void;
}) {
const [projectId, setProjectId] = useState(selection.selectedProjectId);
const [attemptedProjectId, setAttemptedProjectId] = useState<string | null>(null);
const [keyboard, setKeyboard] = useState(keyboardOpened);
const present = useIsPresent();
const reducedMotion = useReducedMotion();
const labelId = useId();
const projectTriggerRef = useRef<HTMLButtonElement>(null);
const pending = selection.pendingProjectId !== null;
const current = selection.projects.find((project) => project.project_id === selection.selectedProjectId);
const selected = selection.projects.find((project) => project.project_id === projectId);
const error = attemptedProjectId === projectId || attemptedProjectId === null ? selection.error : null;
const transition = { duration: reducedMotion || keyboard ? 0 : 0.18, ease: [0.22, 1, 0.36, 1] as const };
return (
<Dialog open={present} onOpenChange={(open) => { if (!open && !pending) onClose(); }}>
<DialogPortal forceMount>
<DialogPrimitive.Overlay forceMount asChild>
<motion.div className="fixed inset-0 z-[100] bg-slate-950/10 backdrop-blur-[3px]"
initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} transition={transition} />
</DialogPrimitive.Overlay>
<DialogPrimitive.Content forceMount asChild
onOpenAutoFocus={(event) => { event.preventDefault(); projectTriggerRef.current?.focus({ preventScroll: true }); }}
onEscapeKeyDown={() => setKeyboard(true)}
onCloseAutoFocus={(event) => { event.preventDefault(); onRestoreFocus(); }}>
<motion.section
className="acrylic-panel acrylic-panel-white fixed left-1/2 top-1/2 z-[101] max-h-[calc(100dvh-2rem)] w-[calc(100%-2rem)] max-w-[420px] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-2xl border border-[var(--surface-border)] p-6 text-slate-900 shadow-[var(--shadow-panel)] outline-0 sm:p-7"
initial={reducedMotion || keyboard ? false : { opacity: 0, y: 8 }}
animate={{ opacity: 1, y: 0 }} exit={{ opacity: 0, y: reducedMotion || keyboard ? 0 : 4 }} transition={transition}
onKeyDownCapture={() => setKeyboard(true)} onPointerDownCapture={() => setKeyboard(false)}>
{selection.onRefresh ? <Button className="absolute right-14 top-3" variant="ghost" size="icon-sm"
aria-label="刷新授权项目" loading={selection.refreshing} onClick={selection.onRefresh}><RefreshCw size={16} /></Button> : null}
<Button className="absolute right-3 top-3" variant="ghost" size="icon-sm" aria-label="关闭项目切换" disabled={pending} onClick={onClose}>
<X size={18} aria-hidden="true" />
</Button>
<header>
<div className="flex items-center gap-2 pr-7 text-xs font-medium text-slate-500">
<Droplet className="h-5 w-5 shrink-0 fill-[var(--action-blue)] text-[var(--action-blue)]" strokeWidth={1.5} aria-hidden="true" />
<span><span className="font-semibold text-slate-700">TJWater</span><span className="mx-2 text-slate-300" aria-hidden="true">/</span>智慧水务平台</span>
</div>
<DialogTitle className="mt-6 text-[22px] font-semibold leading-8 tracking-normal">切换项目</DialogTitle>
<DialogDescription className="mt-1.5 break-words text-xs leading-5 text-slate-500">当前项目:{current?.name ?? current?.code ?? "当前项目"}</DialogDescription>
</header>
<form className="mt-6" onSubmit={(event) => {
event.preventDefault();
if (pending || projectId === selection.selectedProjectId) return;
setAttemptedProjectId(projectId);
selection.onSelectProject(projectId);
}}>
<div>
<label id={labelId} className="mb-2 block text-xs font-medium leading-4 text-slate-600">项目环境</label>
<Select value={projectId} disabled={pending} onValueChange={(value) => { setProjectId(value); setAttemptedProjectId(null); }}>
<SelectTrigger ref={projectTriggerRef} aria-labelledby={labelId} aria-describedby={error ? `${labelId}-error` : undefined} aria-invalid={!!error}
className="h-auto min-h-20 gap-3 whitespace-normal rounded-xl border-[var(--surface-divider)] bg-[var(--surface-reading)] px-4 py-3.5 text-left shadow-none transition-colors hover:bg-[var(--surface-control)] data-[state=open]:border-[var(--action-blue)] motion-reduce:transition-none [&>span]:line-clamp-none [&>svg]:shrink-0">
<SelectValue>
<span className="block min-w-0 space-y-1.5">
<span className="block break-words text-base font-medium leading-6">{selected?.name ?? selected?.code ?? "请选择项目"}</span>
<span className="flex flex-wrap items-center gap-x-3 gap-y-1 text-xs leading-5 text-slate-500">
<span className="inline-flex items-center gap-1.5"><span className="h-1.5 w-1.5 rounded-full bg-emerald-600" aria-hidden="true" />可用</span>
{selected?.project_role ? <span>{roleLabels[selected.project_role] ?? selected.project_role}</span> : null}
</span>
</span>
</SelectValue>
</SelectTrigger>
<SelectContent position="popper" sideOffset={8} animateContent={!keyboard}
className="acrylic-panel acrylic-panel-white z-[102] max-w-[calc(100vw-2rem)] rounded-xl border-[var(--surface-border)] shadow-[var(--shadow-panel)]">
{selection.projects.map((project) => (
<SelectItem key={project.project_id} value={project.project_id} className="min-h-16 rounded-lg py-2.5 text-sm [&>span:last-child]:min-w-0 [&>span:last-child]:whitespace-normal">
<span className="block break-words font-medium">{project.name ?? project.code ?? project.gs_workspace}</span>
{project.project_id === selection.selectedProjectId ? <span className="mt-1 block text-xs leading-5 text-slate-500">正在使用</span> : project.project_role ? <span className="mt-1 block text-xs leading-5 text-slate-500">{roleLabels[project.project_role] ?? project.project_role}</span> : null}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{error ? <p id={`${labelId}-error`} role="alert" className="mt-2 text-xs leading-5 text-rose-700">{error}</p> : null}
<Button type="submit" className="mt-6 h-11 w-full disabled:border-[var(--surface-divider)] disabled:bg-[var(--surface-control)] disabled:text-[var(--ink-muted)] disabled:opacity-100 disabled:shadow-none" disabled={projectId === selection.selectedProjectId} loading={pending} loadingLabel="正在进入项目">进入项目</Button>
</form>
</motion.section>
</DialogPrimitive.Content>
</DialogPortal>
</Dialog>
);
}
@@ -109,11 +109,11 @@ type ExecutionStep = {
};
type ConditionDetailPanelProps = {
onLocate?: (targets: import("../api/investigation-report").InvestigationMapTarget[]) => void;
onLocate?: (targets: import("../api/investigation-report").InvestigationMapTarget[]) => Promise<unknown> | void;
condition: ScheduledConditionItem;
dataSource?: WorkbenchRuntimeDataSource;
workOrderDataSource?: WorkbenchWorkOrderDataSource;
onContinueConversation: (discussion?: import("../api/investigation-report").InvestigationDiscussion) => void;
onContinueConversation: (discussion?: import("../api/investigation-report").InvestigationDiscussion) => Promise<boolean | void> | boolean | void;
onTaskDecision?: (taskId: string, actionId: string, expectedVersion: number, decision: OperationalTaskDecision, comment?: string) => Promise<unknown>;
onTaskExecute?: (taskId: string, actionId: string, expectedVersion: number) => Promise<unknown>;
onTaskDraftUpdate?: (taskId: string, actionId: string, expectedVersion: number, payload: Record<string, unknown>) => Promise<unknown>;
@@ -94,7 +94,7 @@ type ScheduledConditionFeedProps = {
onLoadTaskEvidenceSnapshot?: (taskId: string, evidenceId: string) => Promise<OperationalTaskDataSnapshot>;
onTaskRefresh?: () => void;
onLoadTaskReports?: (taskId: string, offset: number) => Promise<OperationalTaskReportPage>;
onLocate?: (targets: import("../api/investigation-report").InvestigationMapTarget[]) => void;
onLocate?: (targets: import("../api/investigation-report").InvestigationMapTarget[]) => Promise<unknown> | void;
onReportViewed?: (taskId: string, generation: number, revision: number) => void;
onRefresh?: () => void | Promise<void>;
};
@@ -369,14 +369,15 @@ export function ScheduledConditionFeed({
if (condition.operationalTask) {
onExpandAgent();
void Promise.resolve(onOpenTaskCollaboration?.(condition.operationalTask.task_id, discussion))
.catch((error) => showMapNotice({
if (!onOpenTaskCollaboration) return false;
return Promise.resolve(onOpenTaskCollaboration(condition.operationalTask.task_id, discussion))
.then(() => true)
.catch((error) => { showMapNotice({
id: "operational-task-collaboration",
tone: "error",
title: "Agent 协作打开失败",
message: error instanceof Error ? error.message : "无法打开这条任务的协作问答。"
}));
return;
}); return false; });
}
onExpandAgent();
@@ -1103,6 +1104,7 @@ function ConditionTimelineRow({
return (
<button
type="button"
data-condition-id={condition.id}
aria-pressed={selected}
onClick={onSelect}
className={cn(
@@ -232,7 +232,7 @@ export function ToolbarPanel({
if (renderedToolId === "geocoding") {
return (
<MapControlPanel
key="geocoding" title="地址定位" description="奉贤区 · 天地图地名搜索" icon={Icon}
key="geocoding" title="地址定位" description={geocoding.configured ? `${geocoding.region} · 天地图地名搜索` : "当前项目暂未配置地名搜索"} icon={Icon}
widthClassName={`${panelWidthClassName ?? "w-[324px] max-h-[calc(100dvh-13.25rem)]"} flex flex-col overflow-hidden`}
contentClassName="flex min-h-0 flex-1 flex-col"
visible={panelVisible}
@@ -1,10 +1,18 @@
import { AgentCollapsedRail, AgentCommandPanel, AgentPersona } from "@/features/agent";
import { useLayoutEffect, type ComponentProps } from "react";
import { useAgentPanelResize } from "../hooks/use-agent-panel-resize";
import { useEffect, useRef, type ComponentProps, type ReactNode } from "react";
import { usePanelRef } from "react-resizable-panels";
import { ResizableHandle, ResizablePanel, ResizablePanelGroup } from "@/shared/ui/resizable";
import {
clampAgentPanelWidth,
getAgentPanelMaxWidth,
getWorkbenchViewportLayout,
WORKBENCH_LAYOUT
} from "../layout/workbench-layout";
type AgentPanelProps = Omit<ComponentProps<typeof AgentCommandPanel>, "collapsing" | "onCollapse">;
type WorkbenchAgentPanelsProps = {
children: ReactNode;
panelProps: AgentPanelProps;
panelOpen: boolean;
panelCollapsing: boolean;
@@ -18,6 +26,7 @@ type WorkbenchAgentPanelsProps = {
};
export function WorkbenchAgentPanels({
children,
panelProps,
panelOpen,
panelCollapsing,
@@ -29,52 +38,100 @@ export function WorkbenchAgentPanels({
onExpandPanel,
onWidthCommit
}: WorkbenchAgentPanelsProps) {
const { handlePointerDown, panelRef, resizing, width } = useAgentPanelResize(
viewportWidth,
conditionExpanded
);
const panelRef = usePanelRef();
const groupElement = useRef<HTMLDivElement>(null);
const preferredWidth = useRef<number | null>(null);
const desktop = viewportWidth >= WORKBENCH_LAYOUT.desktopMinWidth;
const expanded = desktop && panelOpen;
const defaultWidth = getWorkbenchViewportLayout(viewportWidth).agentWidth;
useLayoutEffect(() => {
onWidthCommit?.(width);
}, [width, onWidthCommit]);
// Restore pixels after the group's ResizeObserver has measured the new
// viewport; a resize against its previous measurement would restore a ratio.
useEffect(() => {
const element = groupElement.current;
if (!element) return;
let frame = 0;
const restore = () => {
cancelAnimationFrame(frame);
frame = requestAnimationFrame(() => {
const target = expanded
? clampAgentPanelWidth(
preferredWidth.current ?? defaultWidth,
element.clientWidth,
conditionExpanded
)
: 0;
panelRef.current?.resize(target);
});
};
const observer = new ResizeObserver(restore);
observer.observe(element);
restore();
return () => {
cancelAnimationFrame(frame);
observer.disconnect();
};
}, [expanded, defaultWidth, viewportWidth, conditionExpanded, panelRef]);
return (
<div
ref={panelRef}
className={`pointer-events-none absolute bottom-0 left-0 top-14 z-50 hidden lg:block${resizing ? " select-none" : ""}`}
style={{ width: panelOpen ? width : 0 }}
>
{panelOpen ? (
<>
<AgentCommandPanel
{...panelProps}
presentation="desktop-dock"
collapsing={panelCollapsing}
onCollapse={onCollapsePanel}
/>
{!panelCollapsing ? (
<div
role="separator"
aria-label="调整 Agent 面板宽度"
aria-orientation="vertical"
data-resizing={resizing}
onPointerDown={handlePointerDown}
className="group pointer-events-auto absolute inset-y-0 -right-1.5 z-10 w-3 cursor-col-resize touch-none"
>
<span className="pointer-events-none absolute inset-y-0 left-[5px] w-px bg-transparent transition-colors duration-150 group-hover:bg-[var(--action-blue-hover)]/70 group-data-[resizing=true]:bg-[var(--action-blue)]/80 motion-reduce:transition-none" />
<span className="agent-resize-grip pointer-events-none absolute left-1/2 top-1/2 h-11 w-[3px] -translate-x-1/2 -translate-y-1/2 rounded-full bg-[var(--action-blue)] opacity-0 transition-opacity duration-150 group-hover:opacity-100 group-data-[resizing=true]:bg-[var(--action-blue)] group-data-[resizing=true]:opacity-100 motion-reduce:transition-none" />
</div>
) : null}
</>
) : (
<div className="absolute left-3 top-5">
<div className="pointer-events-none absolute inset-0">
<ResizablePanelGroup
id="workbench-columns"
elementRef={groupElement}
orientation="horizontal"
disabled={!expanded || panelCollapsing}
resizeTargetMinimumSize={{ fine: 12, coarse: 24 }}
onLayoutChanged={(layout, { isUserInteraction }) => {
if (isUserInteraction && expanded) {
// Keyboard callbacks precede the panel's DOM update. Use the new
// layout rather than getSize().inPixels, which still reads the old width.
const groupWidth = groupElement.current?.clientWidth;
if (groupWidth)
preferredWidth.current = Math.round((layout["agent-column"] * groupWidth) / 100);
}
}}
>
<ResizablePanel
id="agent-column"
panelRef={panelRef}
defaultSize={expanded ? defaultWidth : 0}
minSize={expanded ? WORKBENCH_LAYOUT.minAgentWidth : 0}
maxSize={expanded ? getAgentPanelMaxWidth(viewportWidth, conditionExpanded) : 0}
groupResizeBehavior="preserve-pixel-size"
onResize={({ inPixels }) => {
if (expanded && inPixels > 0) onWidthCommit?.(Math.round(inPixels));
}}
>
<div className="pointer-events-auto hidden h-full min-h-0 pt-14 lg:block">
{panelOpen ? (
<AgentCommandPanel
{...panelProps}
presentation="desktop-dock"
collapsing={panelCollapsing}
onCollapse={onCollapsePanel}
/>
) : null}
</div>
</ResizablePanel>
<ResizableHandle
withHandle
aria-label="调整 Agent 面板宽度"
disabled={!expanded || panelCollapsing}
className={`pointer-events-auto z-50 h-[calc(100%-3.5rem)] w-0 self-end ${expanded ? "" : "hidden"}`}
/>
<ResizablePanel id="main-column" minSize={0} className="relative h-full min-h-0">
{children}
</ResizablePanel>
</ResizablePanelGroup>
{!panelOpen ? (
<div className="pointer-events-none absolute left-0 top-14 z-50 hidden p-3 lg:block">
<AgentCollapsedRail
personaState={personaState}
statusLabel={statusLabel}
onExpand={onExpandPanel}
/>
</div>
)}
) : null}
</div>
);
}
@@ -1,5 +1,6 @@
import {
Activity,
ArrowRightLeft,
Bell,
Bot,
CheckCircle2,
@@ -17,7 +18,9 @@ import {
UserRound,
type LucideIcon
} from "lucide-react";
import type { ReactNode } from "react";
import { useRef, useState, type ReactNode } from "react";
import { AnimatePresence } from "motion/react";
import { ProjectSwitchDialog } from "./project-switch-dialog";
import {
MAP_COMPACT_RADIUS_CLASS_NAME,
MAP_ICON_CELL_RADIUS_CLASS_NAME,
@@ -39,6 +42,7 @@ import {
DropdownMenuSeparator,
DropdownMenuTrigger
} from "@/shared/ui/dropdown-menu";
import type { WorkbenchProject } from "../api/project-client";
import type { WorkbenchAlert, WorkbenchUser } from "../types";
import {
compactHeaderControlButtonClassName,
@@ -259,10 +263,22 @@ export function AlertMenu({
);
}
export type WorkbenchProjectSelection = {
projects: WorkbenchProject[];
selectedProjectId: string;
pendingProjectId: string | null;
error: string | null;
onSelectProject: (projectId: string) => void;
onOpen?: () => void;
onRefresh?: () => void;
refreshing?: boolean;
};
export function UserMenu({
open,
onOpenChange,
user,
projectSelection,
onRefreshTiles,
onShowDataStatus,
onShowShortcuts,
@@ -272,16 +288,23 @@ export function UserMenu({
open: boolean;
onOpenChange: (open: boolean) => void;
user: WorkbenchUser;
projectSelection?: WorkbenchProjectSelection;
onRefreshTiles: () => void;
onShowDataStatus: () => void;
onShowShortcuts: () => void;
onExportConfig: () => void;
onLogout?: () => Promise<void>;
}) {
const [projectDialogOpen, setProjectDialogOpen] = useState(false);
const [projectDialogKeyboard, setProjectDialogKeyboard] = useState(false);
const triggerRef = useRef<HTMLButtonElement>(null);
return (
<>
<DropdownMenu modal={false} open={open} onOpenChange={onOpenChange}>
<DropdownMenuTrigger asChild>
<button
ref={triggerRef}
type="button"
className={cn(
"group lg:h-8 lg:w-auto lg:justify-start lg:px-2",
@@ -297,8 +320,18 @@ export function UserMenu({
<ChevronDown size={14} className="hidden shrink-0 text-[var(--ink-muted)] transition group-hover:text-[var(--action-blue-hover)] group-data-[state=open]:rotate-180 group-data-[state=open]:text-[var(--action-blue-hover)] 2xl:block" aria-hidden="true" />
</button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className={cn("w-72", menuSurfaceClassName)}>
<DropdownMenuContent align="end" className={cn("z-[90] w-72", menuSurfaceClassName)}
onKeyDownCapture={() => setProjectDialogKeyboard(true)}
onPointerDownCapture={() => setProjectDialogKeyboard(false)}
onCloseAutoFocus={(event) => { if (projectDialogOpen) event.preventDefault(); }}>
<MenuHeader title={user.name} meta={user.role} icon={ShieldCheck} />
{projectSelection ? (
<>
<MenuAction icon={ArrowRightLeft} label="切换项目" description="选择要进入的供水项目"
onSelect={() => { onOpenChange(false); setProjectDialogOpen(true); projectSelection.onOpen?.(); }} />
<MenuSeparator />
</>
) : null}
<MenuSectionLabel>会话控制</MenuSectionLabel>
<MenuAction icon={Activity} label="查看运行状态" description="检查数据源与运行健康度" onSelect={onShowDataStatus} />
<MenuAction icon={RefreshCw} label="刷新地图瓦片" description="请求地图重新渲染业务图层" onSelect={onRefreshTiles} />
@@ -319,6 +352,12 @@ export function UserMenu({
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
<AnimatePresence>
{projectDialogOpen && projectSelection ? <ProjectSwitchDialog selection={projectSelection} keyboardOpened={projectDialogKeyboard}
onClose={() => setProjectDialogOpen(false)}
onRestoreFocus={() => triggerRef.current?.focus()} /> : null}
</AnimatePresence>
</>
);
}
@@ -20,7 +20,7 @@ import type {
WorkbenchUser
} from "../types";
import type { AnalysisArtifact, ArtifactRequestedView } from "../workspace/workspace-model";
import { AlertMenu, AnalysisViewMenu, UserMenu } from "./workbench-top-bar-menus";
import { AlertMenu, AnalysisViewMenu, UserMenu, type WorkbenchProjectSelection } from "./workbench-top-bar-menus";
import {
compactHeaderTextClassName,
headerControlButtonClassName,
@@ -34,6 +34,7 @@ export type WorkbenchTopBarProps = {
alerts: WorkbenchAlert[];
alertDataSource: WorkbenchAlertDataSource;
user: WorkbenchUser;
projectSelection?: WorkbenchProjectSelection;
conditionFeedVisible: boolean;
timelineVisible: boolean;
taskTickerAvailable: boolean;
@@ -71,6 +72,7 @@ export function WorkbenchTopBar({
alerts,
alertDataSource,
user,
projectSelection,
conditionFeedVisible,
timelineVisible,
taskTickerAvailable,
@@ -184,14 +186,14 @@ export function WorkbenchTopBar({
</button>
<button
type="button"
aria-label="外围样板管理"
aria-label="外围系统"
aria-pressed={peripheralSamplePanelOpen}
title="外围样板管理"
title="外围系统"
onClick={onTogglePeripheralSamplePanel}
className={cn("group px-2", headerControlButtonClassName)}
>
<span className={headerControlIconClassName}><RadioTower size={14} aria-hidden="true" /></span>
<span className={cn(compactHeaderTextClassName, "hidden xl:inline")}>外围样板</span>
<span className={cn(compactHeaderTextClassName, "hidden xl:inline")}>外围系统</span>
</button>
<div className="lg:hidden">
<TimelineToggle compact visible={timelineVisible} onToggle={onToggleTimeline} />
@@ -250,6 +252,7 @@ export function WorkbenchTopBar({
open={openMenu === "user"}
onOpenChange={createMenuOpenChange("user")}
user={user}
projectSelection={projectSelection}
onRefreshTiles={onRefreshTiles}
onShowDataStatus={onShowDataStatus}
onShowShortcuts={onShowShortcuts}
@@ -19,6 +19,7 @@ import {
} from "@/features/agent";
type AgentUiDataParts = {
session_created: Record<string, unknown>;
agent_message: Record<string, unknown>;
task_context: Record<string, unknown>;
execution_plan: Record<string, unknown>;
@@ -0,0 +1,76 @@
import { describe, expect, it, vi } from "vitest";
import type { ChatTransport, UIMessageChunk } from "ai";
import type { AgentApiClient } from "@/features/agent";
import { WorkbenchSessionResources } from "./workbench-session-resources";
import { createAgentRuntime, mergeHistoryMessages, resumeAgentRuntime, runtimeRunning } from "./agent-session-runtime";
import type { AgentUiMessage } from "./agent-session-message-state";
const message = (id: string, text = id): AgentUiMessage => ({ id, role: "assistant", parts: [{ type: "text", text }] });
describe("independent conversation runtimes", () => {
it("keeps the original response streaming after selecting another conversation", async () => {
const resources = new WorkbenchSessionResources();
let controller!: ReadableStreamDefaultController<UIMessageChunk>;
const transport: ChatTransport<AgentUiMessage> = {
sendMessages: async () => new ReadableStream({ start(stream) { controller = stream; } }),
reconnectToStream: async () => null,
};
const client = { refreshCredential: vi.fn(async () => {}), submitFrontendActionResult: vi.fn(async () => {}) } as unknown as AgentApiClient;
const first = createAgentRuntime(resources, "project:a", client, transport);
const second = createAgentRuntime(resources, "project:a", client, transport);
resources.activeAgent = first;
first.sessionId = "server-a";
const response = first.chat.sendMessage({ text: "核对城南压力" });
await vi.waitFor(() => expect(controller).toBeDefined());
controller.enqueue({ type: "start", messageId: "answer-a" });
controller.enqueue({ type: "text-start", id: "text-a" });
controller.enqueue({ type: "text-delta", id: "text-a", delta: "第一段" });
await vi.waitFor(() => expect(first.chat.messages.at(-1)?.parts).toEqual(expect.arrayContaining([expect.objectContaining({ text: "第一段" })])));
resources.activeAgent = second;
controller.enqueue({ type: "data-progress", data: { session_id: "another-session", title: "迟到的其他会话事件" } });
expect(runtimeRunning(first)).toBe(true);
controller.enqueue({ type: "data-credential_refresh_required", data: { request_id: "refresh-a", session_id: "server-a" } });
controller.enqueue({ type: "text-delta", id: "text-a", delta: ",后台完成" });
controller.enqueue({ type: "text-end", id: "text-a" });
controller.enqueue({ type: "finish", finishReason: "stop" });
controller.close();
await response;
expect(first.chat.messages.at(-1)?.parts).toEqual(expect.arrayContaining([expect.objectContaining({ text: "第一段,后台完成" })]));
expect(second.chat.messages).toEqual([]);
expect(first.sessionId).toBe("server-a");
expect(client.refreshCredential).toHaveBeenCalledWith("server-a", "refresh-a");
resources.dispose();
});
it("merges overlapping pages and a newer authoritative tail without duplicates", () => {
expect(mergeHistoryMessages([message("a"), message("b", "old")], [message("b", "new"), message("c")]))
.toEqual([message("a"), message("b", "new"), message("c")]);
expect(mergeHistoryMessages([message("c"), message("d")], [message("a"), message("b"), message("c", "new")]))
.toEqual([message("a"), message("b"), message("c", "new"), message("d")]);
});
it("routes background browser actions to a scoped refusal and keeps old message pages on resume", async () => {
const resources = new WorkbenchSessionResources();
const submit = vi.fn(async () => {});
const client = { submitFrontendActionResult: submit,
streamSession: vi.fn(async (_id, options) => {
options.onEvent({ type: "state", sessionId: "a", messages: [message("b", "new"), message("c")], isStreaming: true });
options.onEvent({ type: "frontend_action", sessionId: "a", data: {
version: "frontend-action@1", sessionId: "a", actionId: "action-a", toolCallId: "call-a", name: "locate_features",
params: {}, issuedAt: Date.now(), expiresAt: Date.now() + 15_000,
} });
options.onEvent({ type: "done", sessionId: "a", data: {} });
}),
} as unknown as AgentApiClient;
const transport = {} as ChatTransport<AgentUiMessage>;
const runtime = createAgentRuntime(resources, "project:a", client, transport, {
id: "a", sessionId: "a", title: "压力复核", createdAt: 1, updatedAt: 1, purpose: "ordinary_chat",
isTitleManuallyEdited: false, messages: [message("a"), message("b", "old")],
});
resumeAgentRuntime(resources, runtime);
await vi.waitFor(() => expect(runtime.controller).toBeUndefined());
expect(runtime.chat.messages).toEqual([message("a"), message("b", "new"), message("c")]);
expect(submit).toHaveBeenCalledWith("a", "action-a", expect.objectContaining({
status: "failed", error: expect.objectContaining({ code: "SESSION_NOT_ACTIVE" }),
}));
resources.dispose();
});
});
@@ -0,0 +1,203 @@
import { Chat } from "@ai-sdk/react";
import type { ChatTransport } from "ai";
import { parseFrontendActionRequest, type AgentApiClient, type AgentRunStatus, type AgentLoadedChatSession,
type AgentMessagePagination, type AgentSessionStreamEvent, type AgentSessionPurpose, type AgentTaskDiscussionContext, type AnswerUiSelection } from "@/features/agent";
import { showMapNotice } from "@/features/map/core";
import { applySessionStreamEvent, getDataString, toAgentChatMessages, toAgentUiMessages,
type AgentDataPart, type AgentUiMessage, type PermissionOverride, type QuestionOverride } from "./agent-session-message-state";
import type { WorkbenchSessionResources } from "./workbench-session-resources";
export type AgentReadingPosition = { messageId?: string; offset: number; atBottom: boolean };
export type AgentSessionRuntime = {
key: string;
scope: string;
client: AgentApiClient;
chat: Chat<AgentUiMessage>;
sessionId: string | null;
title: string;
topicId?: string | null;
purpose: AgentSessionPurpose;
taskId?: string;
draft: string;
reference?: AnswerUiSelection;
taskDiscussion?: { context: AgentTaskDiscussionContext; reportGeneration?: number | null };
permissionOverrides: Record<string, PermissionOverride>;
questionOverrides: Record<string, QuestionOverride>;
messagePage?: AgentMessagePagination;
readingPosition?: AgentReadingPosition;
loadedAt: number;
updatedAt: number;
resumed: boolean;
controller?: AbortController;
error?: string;
runStatus?: AgentRunStatus;
handlers?: {
onData: (part: AgentDataPart) => void;
onEvent: (event: AgentSessionStreamEvent) => void;
onError: (error: Error) => void;
onFinish: (status: AgentRunStatus) => void;
};
};
export function agentRuntimes(resources: WorkbenchSessionResources) {
return [...resources.agents.values()] as AgentSessionRuntime[];
}
export function runtimeRunning(runtime: AgentSessionRuntime) {
return runtime.resumed || runtime.chat.status === "submitted" || runtime.chat.status === "streaming";
}
export function runtimeNeedsInput(runtime: AgentSessionRuntime) {
return toAgentChatMessages(runtime.chat.messages, runtime.permissionOverrides, runtime.questionOverrides).some((message) =>
message.permissions?.some((permission) => permission.status === "pending") || message.questions?.some((question) => question.status === "pending"));
}
/** Server snapshots replace matching messages, while previously loaded pages retain their order. */
export function mergeHistoryMessages(current: AgentUiMessage[], incoming: AgentUiMessage[]) {
if (!current.length) return incoming;
if (!incoming.length) return current;
const firstOverlap = incoming.findIndex((message) => current.some((existing) => existing.id === message.id));
if (firstOverlap < 0) return [...current, ...incoming];
const index = current.findIndex((message) => message.id === incoming[firstOverlap].id);
const incomingById = new Map(incoming.map((message) => [message.id, message]));
const prefix = current.slice(0, index).filter((message) => !incomingById.has(message.id));
const suffix = current.slice(index).map((message) => incomingById.get(message.id) ?? message);
const known = new Set(suffix.map((message) => message.id));
return [...prefix, ...incoming.slice(0, firstOverlap), ...suffix, ...incoming.filter((message) => !known.has(message.id) && !incoming.slice(0, firstOverlap).includes(message))];
}
export function createAgentRuntime(resources: WorkbenchSessionResources, scope: string, client: AgentApiClient,
transport: ChatTransport<AgentUiMessage>, loaded?: AgentLoadedChatSession) {
const runtime = {
key: crypto.randomUUID(), scope, client, sessionId: loaded?.sessionId ?? null,
title: loaded?.title ?? "新对话", topicId: loaded?.topicId, purpose: loaded?.purpose ?? "ordinary_chat", taskId: loaded?.taskId,
draft: "", permissionOverrides: {}, questionOverrides: {}, messagePage: loaded?.messagePage,
loadedAt: loaded ? Date.now() : 0, updatedAt: loaded?.updatedAt ?? Date.now(), resumed: false, runStatus: loaded?.runStatus,
} as AgentSessionRuntime;
const active = () => resources.activeAgent === runtime;
const notify = () => queueMicrotask(() => resources.notify());
runtime.chat = new Chat<AgentUiMessage>({
id: runtime.key, transport, messages: toAgentUiMessages(loaded?.messages ?? []),
onData: (part) => {
if (resources.disposed) return;
const data = part as AgentDataPart;
const sessionId = getDataString(data.data, "session_id");
if (sessionId && runtime.sessionId && sessionId !== runtime.sessionId) return;
if (sessionId) runtime.sessionId = sessionId;
if (data.type === "data-session_title") runtime.title = getDataString(data.data, "title") ?? runtime.title;
if (data.type === "data-credential_refresh_required") {
void refreshRuntimeCredential(runtime, data.data);
} else if (!active() && data.type === "data-frontend_action") {
void rejectBackgroundAction(resources, runtime, data.data);
} else if (active()) runtime.handlers?.onData(data);
notify();
},
onError: (error) => { if (resources.disposed) return; runtime.error = error.message; runtime.runStatus = "error"; if (active()) runtime.handlers?.onError(error); notify(); },
onFinish: ({ isAbort, isError }) => {
if (resources.disposed) return;
runtime.loadedAt = Date.now();
runtime.updatedAt = Date.now();
runtime.runStatus = isAbort ? "aborted" : isError ? "error" : "completed";
if (active()) runtime.handlers?.onFinish(runtime.runStatus);
else notifyBackgroundCompletion(runtime);
notify();
},
});
resources.agents.set(runtime.key, runtime);
resources.disposers.add(() => { runtime.handlers = undefined; runtime.controller?.abort(); void runtime.chat.stop(); });
return runtime;
}
const credentialRequests = new WeakMap<AgentSessionRuntime, Set<string>>();
async function refreshRuntimeCredential(runtime: AgentSessionRuntime, data: Record<string, unknown>) {
const requestId = getDataString(data, "request_id");
if (!requestId || !runtime.sessionId) return;
const pending = credentialRequests.get(runtime) ?? new Set<string>();
credentialRequests.set(runtime, pending);
if (pending.has(requestId)) return;
pending.add(requestId);
try { await runtime.client.refreshCredential(runtime.sessionId, requestId); }
catch { pending.delete(requestId); runtime.error = "会话凭据续期失败,请重新登录后重试"; }
}
async function rejectBackgroundAction(resources: WorkbenchSessionResources, runtime: AgentSessionRuntime, data: Record<string, unknown>) {
const request = parseFrontendActionRequest(data);
if (!request || request.sessionId !== runtime.sessionId) return;
if (!resources.disposed) showMapNotice({ id: `agent-background-display-${runtime.key}`, tone: "info",
title: "后台对话需要展示结果", message: `回到“${runtime.title}”后重新请求地图或工作区展示。` });
await runtime.client.submitFrontendActionResult(request.sessionId, request.actionId, {
version: "frontend-action-result@1", actionId: request.actionId, status: "failed",
error: { code: "SESSION_NOT_ACTIVE", message: "返回对应会话后重新请求地图或工作区操作" }, completedAt: Date.now(),
}).catch(() => { runtime.error = "后台展示操作回执失败"; });
}
export function resumeAgentRuntime(resources: WorkbenchSessionResources, runtime: AgentSessionRuntime) {
if (!runtime.sessionId || runtime.controller || runtime.chat.status === "submitted" || runtime.chat.status === "streaming") return;
const controller = new AbortController();
runtime.controller = controller;
runtime.resumed = true;
runtime.runStatus = "running";
runtime.error = undefined;
void runtime.client.streamSession(runtime.sessionId, { signal: controller.signal, messageLimit: 40,
onEvent: (event) => {
if (resources.disposed) return;
const sessionId = event.type === "state" ? event.sessionId : event.sessionId ?? getDataString(event.data, "session_id");
if (sessionId && sessionId !== runtime.sessionId) return;
if (event.type === "state") {
const tail = toAgentUiMessages(event.messages);
const prior = runtime.chat.messages;
// Start filling a disconnected interval before reconciling the live tail.
if (prior.length && tail.length && !tail.some((message) => prior.some((old) => old.id === message.id))) {
const boundary = event.messagePage?.beforeCursor;
if (boundary) void fillHistoryGap(runtime, boundary, prior, controller.signal).then(() => resources.notify()).catch(() => {});
}
runtime.chat.messages = mergeHistoryMessages(prior, tail);
if (!runtime.messagePage) runtime.messagePage = event.messagePage;
runtime.resumed = event.isStreaming;
runtime.runStatus = event.runStatus ?? (event.isStreaming ? "running" : "completed");
} else {
if (event.type === "credential_refresh_required") void refreshRuntimeCredential(runtime, event.data);
else if (resources.activeAgent !== runtime && event.type === "frontend_action") void rejectBackgroundAction(resources, runtime, event.data);
runtime.chat.messages = applySessionStreamEvent(runtime.chat.messages, event);
if (event.type === "session_title") runtime.title = getDataString(event.data, "title") ?? runtime.title;
if (event.type === "done" || event.type === "error") {
runtime.resumed = false;
runtime.runStatus = event.type === "error" ? "error" : "completed";
runtime.updatedAt = Date.now();
}
}
if (resources.activeAgent === runtime && event.type !== "credential_refresh_required") runtime.handlers?.onEvent(event);
resources.notify();
},
}).catch((error: unknown) => {
if (!controller.signal.aborted) {
runtime.error = error instanceof Error ? error.message : "会话连接中断";
if (resources.activeAgent === runtime) runtime.handlers?.onError(new Error(runtime.error));
}
}).finally(() => {
if (runtime.resumed && !controller.signal.aborted && !runtime.error) runtime.error = "会话连接已断开,返回会话后重新连接";
if (runtime.controller === controller) { runtime.controller = undefined; runtime.resumed = false; }
runtime.loadedAt = Date.now();
if (!resources.disposed && !controller.signal.aborted && resources.activeAgent !== runtime) notifyBackgroundCompletion(runtime);
resources.notify();
});
}
function notifyBackgroundCompletion(runtime: AgentSessionRuntime) {
showMapNotice({ id: `agent-background-${runtime.key}`, tone: runtime.error || runtime.runStatus === "error" ? "error" : "info",
title: runtime.error || runtime.runStatus === "error" ? "后台对话处理失败" : runtime.runStatus === "aborted" ? "后台对话已停止" : "后台对话已完成",
message: runtime.error ?? runtime.title });
}
async function fillHistoryGap(runtime: AgentSessionRuntime, cursor: string, prior: AgentUiMessage[], signal: AbortSignal) {
let before: string | null = cursor;
const middle: AgentUiMessage[] = [];
while (before && !signal.aborted) {
const page = await runtime.client.loadOlderMessages(runtime.sessionId!, before, signal);
const messages = toAgentUiMessages(page.messages);
middle.unshift(...messages);
if (messages.some((message) => prior.some((old) => old.id === message.id))) break;
before = page.messagePage.beforeCursor;
}
if (!signal.aborted) runtime.chat.messages = mergeHistoryMessages(mergeHistoryMessages(prior, middle), runtime.chat.messages);
}
@@ -0,0 +1,33 @@
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { SWRConfig } from "swr";
import { expect, it, vi } from "vitest";
import type { AgentApiClient, AgentSessionPage } from "@/features/agent";
import { useAgentHistory } from "./use-agent-history";
import { WorkbenchSessionProvider } from "./workbench-session-provider";
it("keeps a late history refresh in its original project cache", async () => {
const clock = vi.spyOn(Date, "now").mockReturnValue(100);
const root = createRoot(document.createElement("div"));
const page = (id: string): AgentSessionPage => ({ sessions: [{ id, title: id, createdAt: 1, updatedAt: 1, purpose: "ordinary_chat" }], hasMore: false, nextCursor: null });
let finish!: (page: AgentSessionPage) => void;
const first = vi.fn().mockResolvedValueOnce(page("project-a-original")).mockImplementationOnce(() => new Promise<AgentSessionPage>((resolve) => { finish = resolve; }));
const second = vi.fn(async () => page("project-b-only"));
const clients = { a: { listSessionPage: first }, b: { listSessionPage: second } } as unknown as Record<"a" | "b", AgentApiClient>;
let history!: ReturnType<typeof useAgentHistory>;
function Probe({ scope }: { scope: "a" | "b" }) { history = useAgentHistory(clients[scope], scope); return null; }
const swrCache = new Map();
const render = (scope: "a" | "b") => root.render(createElement(WorkbenchSessionProvider, null,
createElement(SWRConfig, { value: { provider: () => swrCache, dedupingInterval: 0 } }, createElement(Probe, { scope }))));
try {
await act(async () => render("a"));
expect(history.recentSessions[0]?.id).toBe("project-a-original");
clock.mockReturnValue(61_000);
let pending!: Promise<void>;
await act(async () => { pending = history.ensure(); });
await act(async () => render("b"));
await act(async () => { finish(page("project-a-late-result")); await pending; });
expect(history.sessions.map((session) => session.id)).toEqual(["project-b-only"]);
expect(second).toHaveBeenCalledTimes(1);
} finally { await act(async () => root.unmount()); clock.mockRestore(); }
});
@@ -0,0 +1,82 @@
import { useCallback, useMemo, useRef, useState } from "react";
import useSWR from "swr";
import useSWRInfinite from "swr/infinite";
import type { AgentApiClient, AgentChatSessionSummary, AgentSessionPage } from "@/features/agent";
import { useWorkbenchSessionResources } from "./workbench-session-resources";
const TTL = 60_000;
export function useAgentHistory(client: AgentApiClient, scope: string) {
const resources = useWorkbenchSessionResources();
const [topicFilter, setTopicFilter] = useState<{ scope: string; id?: string }>({ scope });
const topicId = topicFilter.scope === scope ? topicFilter.id : undefined;
const setTopicId = useCallback((id: string | undefined) => setTopicFilter({ scope, id }), [scope]);
const [query, setQuery] = useState("");
const [open, setOpen] = useState(false);
const [enabled, setEnabled] = useState(false);
const [pendingUpdateKey, setPendingUpdateKey] = useState<string | null>(null);
const viewKey = JSON.stringify([scope, query, topicId]);
const view = useRef({ scope, query, topicId });
view.current = { scope, query, topicId };
const staged = useRef<{ key: string; page: AgentSessionPage } | null>(null);
const [orderVersion, setOrderVersion] = useState(0);
const key = useCallback((q: string, cursor?: string | null, topic?: string) => JSON.stringify(["history", scope, q, cursor ?? null, topic ?? null]), [scope]);
const fetchPage = useCallback((q: string, cursor?: string | null, force = false, topic?: string) => resources.cache.load(key(q, cursor, topic),
() => client.listSessionPage({ q, topicId: topic, includeCollaboration: true, cursor: cursor ?? undefined, signal: AbortSignal.timeout(15_000) }), TTL, { force }), [client, key, resources]);
const recent = useSWR(["agent-recent-sessions", scope], () => fetchPage(""), {
revalidateOnFocus: false, shouldRetryOnError: false,
});
const pages = useSWRInfinite<AgentSessionPage>(
(_index, previous: AgentSessionPage | null) => !enabled || (previous && !previous.hasMore) ? null
: ["agent-history-page", scope, query, previous?.nextCursor ?? null, topicId ?? null],
([, , q, cursor, topic]: [string, string, string, string | null, string | null]) => fetchPage(q, cursor, false, topic ?? undefined),
{ revalidateOnFocus: false, revalidateFirstPage: false, shouldRetryOnError: false, persistSize: false },
);
const sessions = useMemo(() => [...new Map((pages.data ?? (query || topicId ? [] : recent.data ? [recent.data] : []))
.flatMap((page) => page.sessions).map((session) => [session.id, session])).values()], [pages.data, query, recent.data, topicId]);
const refresh = useCallback(async () => {
const page = staged.current?.key === viewKey ? staged.current.page : await fetchPage(query, null, true, topicId);
if (view.current.scope !== scope || view.current.query !== query || view.current.topicId !== topicId) return;
staged.current = null;
await pages.mutate([page], { revalidate: false });
await pages.setSize(1);
if (!query && !topicId) await recent.mutate(page, { revalidate: false });
setPendingUpdateKey(null);
setOrderVersion((version) => version + 1);
}, [fetchPage, pages, query, recent, scope, topicId, viewKey]);
const ensure = useCallback(async () => {
setOpen(true);
setEnabled(true);
const stale = (resources.cache.peek(key(query, null, topicId))?.expiresAt ?? 0) <= Date.now();
const page = await fetchPage(query, null, false, topicId);
if (view.current.scope !== scope || view.current.query !== query || view.current.topicId !== topicId) return;
// Opening a window never invalidates a fresh page or hides existing content.
if (!pages.data?.length) await pages.mutate([page], { revalidate: false });
else if (stale) { staged.current = { key: viewKey, page }; setPendingUpdateKey(viewKey); }
if (!query && !topicId) await recent.mutate(page, { revalidate: false });
}, [fetchPage, key, pages, query, recent, resources, scope, topicId, viewKey]);
const update = useCallback(async (change: (sessions: AgentChatSessionSummary[]) => AgentChatSessionSummary[]) => {
resources.cache.updateMatching<AgentSessionPage>((cacheKey) => {
if (!cacheKey.startsWith('["history",')) return false;
const value = JSON.parse(cacheKey) as unknown[];
return value[0] === "history" && value[1] === scope;
}, (page) => ({ ...page, sessions: change(page.sessions) }));
const recentPage = resources.cache.peek<AgentSessionPage>(key(""))?.value;
if (recentPage) {
const next = { ...recentPage, sessions: change(recentPage.sessions) };
resources.cache.set(key(""), next, TTL);
if (view.current.scope === scope) await recent.mutate(next, { revalidate: false });
}
if (view.current.scope !== scope || view.current.query !== query || view.current.topicId !== topicId) return;
await pages.mutate((current) => current?.map((page) => ({ ...page, sessions: change(page.sessions) })), { revalidate: false });
// Search and later pages can now have different membership/order. Retain what is being read.
setPendingUpdateKey(viewKey);
}, [key, pages, query, recent, resources, scope, topicId, viewKey]);
return {
topicId, setTopicId, sessions, recentSessions: recent.data?.sessions ?? [], query, setQuery,
loading: (open ? pages.isLoading : recent.isLoading), error: pages.error ?? recent.error,
loadingMore: pages.isValidating, hasMore: pages.data?.at(-1)?.hasMore ?? recent.data?.hasMore ?? false,
loadMore: () => pages.setSize(pages.size + 1), refresh, ensure, update,
pendingUpdate: pendingUpdateKey === viewKey, isOpen: open, orderVersion, close: () => setOpen(false),
};
}
@@ -1,77 +0,0 @@
import {
useCallback,
useEffect,
useRef,
useState,
type PointerEvent as ReactPointerEvent
} from "react";
import {
clampAgentPanelWidth,
getWorkbenchViewportLayout
} from "../layout/workbench-layout";
export function useAgentPanelResize(viewportWidth: number, conditionExpanded = false) {
const panelRef = useRef<HTMLDivElement | null>(null);
const cleanupRef = useRef<(() => void) | null>(null);
const [width, setWidth] = useState<number | null>(null);
const [resizing, setResizing] = useState(false);
useEffect(() => () => cleanupRef.current?.(), []);
const handlePointerDown = useCallback(
(event: ReactPointerEvent<HTMLDivElement>) => {
if (event.button !== 0 || !panelRef.current) return;
event.preventDefault();
cleanupRef.current?.();
const startX = event.clientX;
const startWidth = panelRef.current.getBoundingClientRect().width;
const handle = event.currentTarget;
const pointerId = event.pointerId;
handle.setPointerCapture(pointerId);
setResizing(true);
const handlePointerMove = (pointerEvent: PointerEvent) => {
if (pointerEvent.pointerId !== pointerId) return;
pointerEvent.preventDefault();
setWidth(clampAgentPanelWidth(
startWidth + pointerEvent.clientX - startX,
window.innerWidth,
conditionExpanded
));
};
const stopResizing = (pointerEvent?: PointerEvent) => {
if (pointerEvent && pointerEvent.pointerId !== pointerId) return;
cleanupRef.current?.();
setResizing(false);
};
const handleBlur = () => stopResizing();
const cleanup = () => {
window.removeEventListener("pointermove", handlePointerMove);
window.removeEventListener("pointerup", stopResizing);
window.removeEventListener("pointercancel", stopResizing);
window.removeEventListener("blur", handleBlur);
if (handle.hasPointerCapture(pointerId)) handle.releasePointerCapture(pointerId);
cleanupRef.current = null;
};
cleanupRef.current = cleanup;
window.addEventListener("pointermove", handlePointerMove);
window.addEventListener("pointerup", stopResizing);
window.addEventListener("pointercancel", stopResizing);
window.addEventListener("blur", handleBlur);
},
[conditionExpanded]
);
return {
handlePointerDown,
panelRef,
resizing,
width: clampAgentPanelWidth(
width ?? getWorkbenchViewportLayout(viewportWidth).agentWidth,
viewportWidth,
conditionExpanded
)
};
}
@@ -1,5 +1,9 @@
import { describe, expect, it } from "vitest";
import { collectRecentAgentActivities } from "./use-agent-prompt-suggestions";
import { afterEach, describe, expect, it, vi } from "vitest";
import { act, createElement } from "react";
import { createRoot, type Root } from "react-dom/client";
import { collectRecentAgentActivities, useAgentPromptSuggestions } from "./use-agent-prompt-suggestions";
import { WorkbenchSessionProvider } from "./workbench-session-provider";
import type { ScheduledConditionItem } from "../types";
import type { AgentChatSessionSummary } from "@/features/agent";
describe("recent activities for Agent suggestions", () => {
@@ -21,3 +25,56 @@ describe("recent activities for Agent suggestions", () => {
expect(activities.filter((item) => item.kind === "session").map((item) => item.title)).toEqual(["updated-old-conversation"]);
});
});
describe("recommendation cache lifecycle", () => {
let root: Root | undefined;
afterEach(async () => { if (root) await act(async () => root!.unmount()); root = undefined; vi.restoreAllMocks(); });
it("reuses recommendations across history refresh, panel reopen and a new empty conversation", async () => {
const container = document.createElement("div");
root = createRoot(container);
const request = vi.fn(async () => [{ question: "核查当前压力", activityId: null }]);
const empty: never[] = [];
function Probe({ enabled, sessionId }: { enabled: boolean; sessionId: string | null }) {
const result = useAgentPromptSuggestions({ enabled, model: "fixture/model", cacheScope: "project:a", sessionId,
request, alerts: empty, alertDataSource: "backend", conditions: empty, runtimeDataSource: "backend", artifact: null, sessions: empty });
return createElement("p", null, result.suggestions[0]?.question ?? "loading");
}
for (let i = 0; i < 10; i++) {
await act(async () => root!.render(createElement(WorkbenchSessionProvider, null, createElement(Probe, { enabled: false, sessionId: null }))));
await act(async () => root!.render(createElement(WorkbenchSessionProvider, null, createElement(Probe, { enabled: true, sessionId: `empty-${i}` }))));
}
expect(request).toHaveBeenCalledTimes(1);
expect(container.textContent).toBe("核查当前压力");
});
it("ignores task heartbeat timestamps but regenerates when an activity changes status", async () => {
root = createRoot(document.createElement("div"));
const request = vi.fn(async () => [{ question: "复核任务证据", activityId: "task:task-a" }]);
const empty: never[] = [];
function Probe({ time, status }: { time: number; status: "running" | "completed" }) {
const condition: ScheduledConditionItem = { id: "task-a", kind: "condition", taskId: "scada-diagnosis", sessionId: "native-a",
title: "SCADA 证据复核", summary: "检查压力监测", riskLevel: "normal", scheduledAt: "2026-10-22T01:00:00Z", updatedAt: time, status };
useAgentPromptSuggestions({ enabled: true, model: "fixture/model", cacheScope: "project:a", sessionId: null, request,
alerts: empty, alertDataSource: "backend", conditions: [condition], runtimeDataSource: "backend", artifact: null, sessions: empty });
return null;
}
for (let i = 0; i < 10; i++) await act(async () => root!.render(createElement(WorkbenchSessionProvider, null,
createElement(Probe, { time: 1000 + i * 5000, status: "running" }))));
expect(request).toHaveBeenCalledTimes(1);
await act(async () => root!.render(createElement(WorkbenchSessionProvider, null, createElement(Probe, { time: 60000, status: "completed" }))));
expect(request).toHaveBeenCalledTimes(2);
});
it("isolates projects and caches generation errors instead of retrying each reopen", async () => {
root = createRoot(document.createElement("div"));
const request = vi.fn(async () => { throw new Error("unavailable"); });
const empty: never[] = [];
function Probe({ scope, enabled }: { scope: string; enabled: boolean }) {
useAgentPromptSuggestions({ enabled, cacheScope: scope, model: "fixture/model", sessionId: null,
request, alerts: empty, alertDataSource: "backend", conditions: empty, runtimeDataSource: "backend", artifact: null, sessions: empty });
return null;
}
for (const [scope, enabled] of [["a", true], ["a", false], ["a", true], ["b", true]] as const) {
await act(async () => root!.render(createElement(WorkbenchSessionProvider, null, createElement(Probe, { scope, enabled }))));
}
expect(request).toHaveBeenCalledTimes(2);
});
});
@@ -3,6 +3,8 @@ import type { AgentApiClient, AgentChatSessionSummary, AgentPromptSuggestion, Ag
import type { WorkbenchAlert, ScheduledConditionItem, WorkbenchAlertDataSource, WorkbenchRuntimeDataSource } from "../types";
import type { AnalysisArtifact } from "../workspace/workspace-model";
import { useWorkbenchSessionResources } from "./workbench-session-resources";
type ActivityInputs = {
alerts: WorkbenchAlert[];
alertDataSource: WorkbenchAlertDataSource;
@@ -44,38 +46,52 @@ export function collectRecentAgentActivities(input: ActivityInputs, now = Date.n
return [...new Map([...alerts, ...tasks, ...analyses, ...sessions].map((item) => [item.id, item])).values()];
}
export function useAgentPromptSuggestions({ enabled, model, sessionId, request, alerts, alertDataSource, conditions, runtimeDataSource, artifact, sessions }: ActivityInputs & {
export function useAgentPromptSuggestions({ enabled, model, cacheScope = "project", request, alerts, alertDataSource, conditions, runtimeDataSource, artifact, sessions }: ActivityInputs & {
enabled: boolean;
model: string;
sessionId: string | null;
cacheScope?: string;
request: AgentApiClient["generatePromptSuggestions"];
}) {
const { cache } = useWorkbenchSessionResources();
const activities = useMemo(() => collectRecentAgentActivities({ alerts, alertDataSource, conditions, runtimeDataSource, artifact, sessions }),
[alerts, alertDataSource, conditions, runtimeDataSource, artifact, sessions]);
const snapshot = useRef(activities);
useEffect(() => { snapshot.current = activities; }, [activities]);
const key = JSON.stringify([enabled, model, sessionId]);
const [state, setState] = useState<{ key: string; suggestions: DisplaySuggestion[]; loading: boolean; unavailable: boolean }>({
key: "", suggestions: [], loading: false, unavailable: false,
// Heartbeat timestamps change while the activity itself stays the same.
const digest = JSON.stringify([...activities].sort((a, b) => a.id.localeCompare(b.id)).map((activity) => ({
id: activity.id, kind: activity.kind, title: activity.title, summary: activity.summary,
status: activity.status, origin: activity.origin,
})));
const activitySnapshot = useRef(activities);
activitySnapshot.current = activities;
const key = JSON.stringify(["suggestions", cacheScope, model, digest]);
const [state, setState] = useState<{ scope: string; suggestions: DisplaySuggestion[]; loading: boolean; unavailable: boolean }>({
scope: cacheScope, suggestions: [], loading: false, unavailable: false,
});
useEffect(() => {
if (!enabled) return;
const controller = new AbortController();
const context = snapshot.current;
setState({ key, suggestions: [], loading: true, unavailable: false });
void request(context, model, controller.signal).then((suggestions) => {
if (controller.signal.aborted) return;
let disposed = false;
const previous = cache.peek<DisplaySuggestion[]>(key);
const apply = (suggestions: DisplaySuggestion[]) => {
if (!disposed) setState({ scope: cacheScope, suggestions, loading: false, unavailable: false });
};
if (previous?.value) apply(previous.value);
else setState((current) => ({ scope: cacheScope,
suggestions: current.scope === cacheScope ? current.suggestions : [], loading: true, unavailable: false }));
void cache.load(key, async () => {
const context = activitySnapshot.current;
const suggestions = await request(context, model, AbortSignal.timeout(60_000));
const sourceById = new Map(context.map((item) => [item.id, item]));
setState({ key, loading: false, unavailable: false, suggestions: suggestions.map((item) => {
return suggestions.map((item) => {
const source = item.activityId ? sourceById.get(item.activityId) : undefined;
return { ...item, sourceLabel: source
? `${source.origin === "demo" ? "演示" : ""}${activityLabels[source.kind]} · ${timeFormatter.format(new Date(source.occurred_at))}`
: "供水任务建议" };
}) });
}).catch(() => {
if (!controller.signal.aborted) setState({ key, suggestions: [], loading: false, unavailable: true });
});
}, 10 * 60_000, { errorTtl: 30_000 }).then(apply).catch(() => {
if (!disposed) setState((current) => ({ scope: cacheScope,
suggestions: current.scope === cacheScope ? current.suggestions : [], loading: false, unavailable: true }));
});
return () => controller.abort();
}, [enabled, key, model, request]);
return state.key === key ? state : { suggestions: [], loading: enabled, unavailable: false };
return () => { disposed = true; };
}, [cache, cacheScope, digest, enabled, key, model, request]);
return state.scope === cacheScope ? state : { suggestions: [], loading: enabled, unavailable: false };
}
@@ -0,0 +1,58 @@
import { act, createElement } from "react";
import { createRoot } from "react-dom/client";
import { SWRConfig } from "swr";
import { expect, it, vi } from "vitest";
import type { AgentApiClient, AgentTopic } from "@/features/agent";
import { useAgentTopics } from "./use-agent-topics";
import { WorkbenchSessionProvider } from "./workbench-session-provider";
it("reuses theme reads and keeps a late project result out of the personal theme list", async () => {
const topic = (id: string): AgentTopic => ({ id, name: id, createdAt: "2026-10-22T01:00:00Z", updatedAt: "2026-10-22T01:00:00Z" });
let finish!: (topics: AgentTopic[]) => void;
const projectRead = vi.fn(() => new Promise<AgentTopic[]>((resolve) => { finish = resolve; }));
const personalRead = vi.fn(async () => [topic("personal-theme")]);
const clients = { project: { listTopics: projectRead }, personal: { listTopics: personalRead } } as unknown as Record<"project" | "personal", AgentApiClient>;
const root = createRoot(document.createElement("div"));
const cache = new Map();
let topics!: ReturnType<typeof useAgentTopics>;
function Probe({ scope }: { scope: "project" | "personal" }) { topics = useAgentTopics(clients[scope], scope); return null; }
const render = (scope: "project" | "personal") => root.render(createElement(WorkbenchSessionProvider, null,
createElement(SWRConfig, { value: { provider: () => cache, dedupingInterval: 0 } }, createElement(Probe, { scope }))));
try {
await act(async () => render("project"));
let pending!: Promise<void>;
await act(async () => { pending = topics.ensure(); });
await act(async () => render("personal"));
await act(async () => { finish([topic("project-theme")]); await pending; });
expect(topics.topics.map((entry) => entry.id)).toEqual(["personal-theme"]);
for (let i = 0; i < 10; i++) await act(async () => { await topics.ensure(); });
expect(projectRead).toHaveBeenCalledTimes(1);
expect(personalRead).toHaveBeenCalledTimes(1);
} finally { await act(async () => root.unmount()); }
});
it("keeps a newly created topic selectable when the open menu's older read finishes later", async () => {
const topic = (id: string): AgentTopic => ({ id, name: id, createdAt: "2026-10-22T01:00:00Z", updatedAt: "2026-10-22T01:00:00Z" });
let finish!: (topics: AgentTopic[]) => void;
const client = {
listTopics: vi.fn(() => new Promise<AgentTopic[]>((resolve) => { finish = resolve; })),
createTopic: vi.fn(async () => topic("new-topic")),
} as unknown as AgentApiClient;
let topics!: ReturnType<typeof useAgentTopics>;
function Probe() { topics = useAgentTopics(client, "project:slow-read"); return null; }
const root = createRoot(document.createElement("div"));
const cache = new Map();
try {
await act(async () => root.render(createElement(WorkbenchSessionProvider, null,
createElement(SWRConfig, { value: { provider: () => cache, dedupingInterval: 0 } }, createElement(Probe)))));
let reading!: Promise<void>;
let creating!: Promise<AgentTopic>;
await act(async () => { reading = topics.ensure(); });
await act(async () => { creating = topics.create("new-topic"); });
await act(async () => { finish([topic("existing-topic")]); await reading; await creating; });
expect(topics.topics.map((entry) => entry.id)).toEqual(["existing-topic", "new-topic"]);
await act(async () => { await topics.ensure(); });
expect(topics.topics.map((entry) => entry.id)).toEqual(["existing-topic", "new-topic"]);
expect(client.listTopics).toHaveBeenCalledTimes(1);
} finally { await act(async () => root.unmount()); }
});
@@ -0,0 +1,33 @@
import { useCallback, useRef } from "react";
import useSWR from "swr";
import type { AgentApiClient, AgentTopic } from "@/features/agent";
import { useWorkbenchSessionResources } from "./workbench-session-resources";
const TTL = 5 * 60_000;
export function useAgentTopics(client: AgentApiClient, scope: string) {
const resources = useWorkbenchSessionResources();
const currentScope = useRef(scope);
currentScope.current = scope;
const key = JSON.stringify(["agent-topics", scope]);
const fetchTopics = useCallback(() => resources.cache.load(key, () => client.listTopics(), TTL), [client, key, resources]);
const state = useSWR(["agent-topics", scope], fetchTopics, { revalidateOnFocus: false, shouldRetryOnError: false });
const save = async (change: (current: AgentTopic[]) => AgentTopic[]) => {
const next = change(resources.cache.peek<AgentTopic[]>(key)?.value ?? state.data ?? []);
if (resources.disposed) return;
resources.cache.set(key, next, TTL);
if (currentScope.current === scope) await state.mutate(next, { revalidate: false });
};
const ensure = async () => {
const topics = await fetchTopics();
if (!resources.disposed && currentScope.current === scope) await state.mutate(topics, { revalidate: false });
};
return {
topics: state.data ?? [], loading: state.isLoading, error: state.error,
ensure,
// Finish the shared read before writing, so a late menu snapshot cannot replace the mutation.
create: async (name: string) => { await ensure(); const topic = await client.createTopic(name); await save((current) => [...current, topic]); return topic; },
rename: async (id: string, name: string) => { await ensure(); const topic = await client.renameTopic(id, name); await save((current) => current.map((entry) => entry.id === id ? topic : entry)); },
remove: async (id: string) => { await ensure(); await client.deleteTopic(id); await save((current) => current.filter((topic) => topic.id !== id)); },
};
}
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "../api/request-context";
import {
fetchElementGisProperties,
fetchSourceGisFeatureProperties,
@@ -18,7 +18,7 @@ const INITIAL_STATE: GisPropertiesState = { status: "idle", groups: [] };
export function useElementGisProperties(
feature: DetailFeature | null,
projectId: string | null,
getAccessToken?: AccessTokenProvider
getAccessToken?: WorkbenchAccess
) {
const [state, setState] = useState<GisPropertiesState>(INITIAL_STATE);
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useMemo, useRef, useState, type RefObject } from "react";
import type { FeatureCollection } from "geojson";
import type { Map as MapLibreMap, PaddingOptions } from "maplibre-gl";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "../api/request-context";
import { fetchOperationalTask, fetchOperationalTaskPresentationCursor, type OperationalTask } from "../api/operational-task-client";
import type { InvestigationMapTarget } from "../api/investigation-report";
import type { InvestigationOverlay, InvestigationPresentationCommand } from "../api/investigation-presentation";
@@ -13,7 +13,7 @@ import { InvestigationPresentationFollower } from "./investigation-presentation-
export type InvestigationChart = Extract<InvestigationPresentationCommand, { action: "open_chart" }>;
type Options = {
enabled: boolean; task: OperationalTask | null; projectId: string | null;
sync: WorkbenchSyncState; getAccessToken?: AccessTokenProvider;
sync: WorkbenchSyncState; getAccessToken?: WorkbenchAccess;
mapRef: RefObject<MapLibreMap | null>; mapReady: boolean;
controller: WorkbenchMapController; getPadding: () => PaddingOptions;
onClearLayers: () => void;
@@ -1,5 +1,8 @@
import { renderHook } from "@testing-library/react";
import type { Map as MapLibreMap } from "maplibre-gl";
import { describe, expect, it, vi } from "vitest";
import {
useMapInteractions,
clearMapFeatureInteractionState,
isPointOccludedByCityBuilding,
setMapFeatureInteractionState,
@@ -71,3 +74,17 @@ describe("map feature interaction state", () => {
expect(queryRenderedFeatures).not.toHaveBeenCalled();
});
});
it("suspends feature picking while the map is used to look up a place", () => {
const canvas = document.createElement("canvas");
const map = { on: vi.fn(), off: vi.fn(), getLayer: vi.fn(() => ({})), getCanvas: () => canvas };
const props = { enabled: false, mapRef: { current: map as unknown as MapLibreMap },
availableSourceIds: ["pipes"] as const, mapReady: true, onSelectFeature: vi.fn(), selectedFeature: null };
const { rerender } = renderHook(useMapInteractions, { initialProps: props });
expect(map.on).not.toHaveBeenCalled();
rerender({ ...props, enabled: true });
expect(map.on).toHaveBeenCalledWith("click", expect.any(Array), expect.any(Function));
rerender(props);
expect(map.off).toHaveBeenCalledWith("click", expect.any(Array), expect.any(Function));
});
@@ -58,6 +58,7 @@ export function isPointOccludedByCityBuilding(map: CityOcclusionMap, point: Poin
}
type UseMapInteractionsOptions = {
enabled?: boolean;
availableSourceIds: readonly WaterNetworkSourceId[];
mapRef: RefObject<MapLibreMap | null>;
mapReady: boolean;
@@ -66,6 +67,7 @@ type UseMapInteractionsOptions = {
};
export function useMapInteractions({
enabled = true,
availableSourceIds,
mapRef,
mapReady,
@@ -74,7 +76,7 @@ export function useMapInteractions({
}: UseMapInteractionsOptions) {
useEffect(() => {
const map = mapRef.current;
if (!mapReady || !map) return;
if (!mapReady || !map || !enabled) return;
let hoveredFeature: FeatureReference | null = null;
@@ -127,12 +129,15 @@ export function useMapInteractions({
map.on("click", hitLayerIds, handleClick);
return () => {
// eslint-disable-next-line react-hooks/exhaustive-deps -- Read the live owner ref to detect map disposal.
if (mapRef.current !== map) return;
clearHoveredFeature();
map.getCanvas().style.cursor = "";
map.off("mousemove", hitLayerIds, handleMouseMove);
map.off("mouseleave", hitLayerIds, handleMouseLeave);
map.off("click", hitLayerIds, handleClick);
};
}, [availableSourceIds, mapRef, mapReady, onSelectFeature, selectedFeature]);
}, [availableSourceIds, mapRef, mapReady, onSelectFeature, selectedFeature, enabled]);
useEffect(() => {
const map = mapRef.current;
@@ -142,7 +147,8 @@ export function useMapInteractions({
setMapFeatureInteractionState(map, next, { selected: true, hovered: false });
}
return () => {
if (next && map.getSource(next.source)) {
// eslint-disable-next-line react-hooks/exhaustive-deps -- Read the live owner ref to detect map disposal.
if (mapRef.current === map && next && map.getSource(next.source)) {
clearMapFeatureInteractionState(map, next, "selected");
}
};
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "../api/request-context";
import {
acknowledgeOperationalTaskNotification,
createOperationalRequestId,
@@ -23,7 +23,7 @@ import type { WorkbenchEvent } from "../api/workbench-sync-client";
import type { WorkbenchSyncState } from "./use-workbench-sync";
export type ManualInvestigationKind = "water_quality_complaint" | "burst_report";
export type ManualInvestigationKind = "water_quality_complaint" | "burst_report" | "scada_anomaly";
export type CreateInvestigationInput = {
kind: ManualInvestigationKind;
title: string;
@@ -66,7 +66,7 @@ export function selectHeaderNotifications(items: OperationalTaskNotification[])
}
export function useOperationalTasks(
getAccessToken: AccessTokenProvider | undefined,
getAccessToken: WorkbenchAccess | undefined,
sync: WorkbenchSyncState
) {
const syncEvents = sync.events;
File diff suppressed because it is too large Load Diff
@@ -40,6 +40,7 @@ export type WorkbenchDrawingAnnotation = {
};
type UseWorkbenchDrawingOptions = {
selectionEnabled?: boolean;
mapRef: RefObject<MapLibreMap | null>;
mapReady: boolean;
activeMode: WorkbenchDrawMode | null;
@@ -47,6 +48,7 @@ type UseWorkbenchDrawingOptions = {
};
export function useWorkbenchDrawing({
selectionEnabled = true,
mapRef,
mapReady,
activeMode,
@@ -134,7 +136,7 @@ export function useWorkbenchDrawing({
useEffect(() => {
const map = mapRef.current;
if (!mapReady || !map || activeMode) {
if (!mapReady || !map || activeMode || !selectionEnabled) {
return;
}
@@ -167,6 +169,9 @@ export function useWorkbenchDrawing({
});
return () => {
// The map owner may already have disposed this instance during project switching.
// eslint-disable-next-line react-hooks/exhaustive-deps -- Read the live owner ref to detect map disposal.
if (mapRef.current !== activeMap) return;
DRAWING_INTERACTIVE_LAYER_IDS.forEach((layerId) => {
if (activeMap.getLayer(layerId)) {
activeMap.off("click", layerId, handleDrawingClick);
@@ -175,7 +180,7 @@ export function useWorkbenchDrawing({
}
});
};
}, [activeMode, mapReady, mapRef]);
}, [activeMode, mapReady, mapRef, selectionEnabled]);
const updateDraft = useCallback(
(draft: DrawingDraftState | null) => {
@@ -1,17 +1,18 @@
import { act, cleanup, renderHook } from "@testing-library/react";
import type { Map as MapLibreMap } from "maplibre-gl";
import type { Map as MapLibreMap, MapMouseEvent } from "maplibre-gl";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { searchPlaces, type PlaceSearchItem, type PlaceSearchResults } from "../api/place-search-client";
import { reverseGeocodePoint, searchPlaces, type PlaceSearchItem, type PlaceSearchResults } from "../api/place-search-client";
import { locateGeocodingResult, markGeocodingLocation } from "../map/geocoding-location";
import { useWorkbenchGeocoding } from "./use-workbench-geocoding";
vi.mock("../api/place-search-client", () => ({ searchPlaces: vi.fn() }));
vi.mock("../api/place-search-client", () => ({ searchPlaces: vi.fn(), reverseGeocodePoint: vi.fn() }));
vi.mock("../map/geocoding-location", () => ({ locateGeocodingResult: vi.fn(), markGeocodingLocation: vi.fn() }));
const location: PlaceSearchItem = { id: "place-1", name: "南桥路", address: "奉贤区南桥路", longitude: 121.44, latitude: 31.22, category: "道路名", district: "奉贤区" };
const other = { ...location, id: "place-2", address: "奉贤区南桥路", longitude: 121.35, latitude: 30.77 };
const results: PlaceSearchResults = { items: [location, other], total: 2, truncated: false, region: "奉贤区" };
const remove = vi.fn();
const options = {
placeSearch: { enabled: true, provider: "tianditu" as const, admin_code: "310120", region: "奉贤区" },
active: true, projectId: "project-1", mapRef: { current: {} as MapLibreMap }, mapReady: true,
getPadding: () => ({ top: 48, right: 400, bottom: 48, left: 48 }), reducedMotion: true, onLocate: vi.fn()
};
@@ -22,6 +23,23 @@ beforeEach(() => {
afterEach(cleanup);
describe("place search selection lifecycle", () => {
it("disables search without project configuration, even for the original workspace", async () => {
const { result } = renderHook(useWorkbenchGeocoding, {
initialProps: { ...options, placeSearch: null }
});
act(() => result.current.changeAddress("南桥路"));
await act(() => result.current.search());
expect(result.current.configured).toBe(false);
expect(result.current.error).toBe("当前项目暂未配置地名搜索");
expect(searchPlaces).not.toHaveBeenCalled();
});
it("uses the selected project's configured region", async () => {
const { result } = renderHook(useWorkbenchGeocoding, {
initialProps: { ...options, placeSearch: { ...options.placeSearch, admin_code: "341126", region: "凤阳县" } }
});
expect(result.current.configured).toBe(true);
expect(result.current.region).toBe("凤阳县");
});
it("does not move until selection and replaces the previous marker", async () => {
vi.mocked(searchPlaces).mockResolvedValue(results);
const { result, rerender } = renderHook(useWorkbenchGeocoding, { initialProps: options });
@@ -84,3 +102,95 @@ describe("place search selection lifecycle", () => {
unmount();
});
});
function pickingMap() {
const canvas = document.createElement("canvas");
const listeners = new Map<string, (event: MapMouseEvent) => void>();
const map = {
on: vi.fn((name: string, handler: (event: MapMouseEvent) => void) => listeners.set(name, handler)),
off: vi.fn((name: string) => listeners.delete(name)),
getCanvas: () => canvas
};
return {
map: map as unknown as MapLibreMap,
canvas,
click: (longitude = location.longitude, latitude = location.latitude) => listeners.get("click")?.({
lngLat: { lng: longitude, lat: latitude }, preventDefault: vi.fn()
} as unknown as MapMouseEvent)
};
}
describe("map point place lookup", () => {
it("ends picking after a successful lookup and keeps the marker and camera unchanged", async () => {
const map = pickingMap();
const onPickingChange = vi.fn();
const props = { ...options, picking: true, onPickingChange, mapRef: { current: map.map } };
vi.mocked(reverseGeocodePoint).mockResolvedValue(location);
const { result, rerender } = renderHook(useWorkbenchGeocoding, { initialProps: props });
onPickingChange.mockClear();
expect(map.canvas.style.cursor).toBe("crosshair");
await act(async () => { map.click(); });
expect(result.current.result).toEqual(location);
expect(result.current.origin).toBe("map");
expect(result.current.choosing).toBe(false);
expect(onPickingChange).toHaveBeenCalledExactlyOnceWith(false);
expect(markGeocodingLocation).toHaveBeenCalledWith(map.map, location);
expect(locateGeocodingResult).not.toHaveBeenCalled();
act(() => result.current.locate());
expect(locateGeocodingResult).toHaveBeenCalledOnce();
rerender({ ...props, picking: false });
expect(map.canvas.style.cursor).toBe("");
expect(map.map.off).toHaveBeenCalledWith("click", expect.any(Function));
});
it("ignores an older point after a second click", async () => {
const map = pickingMap();
let first!: (value: PlaceSearchItem) => void;
let second!: (value: PlaceSearchItem) => void;
vi.mocked(reverseGeocodePoint)
.mockReturnValueOnce(new Promise((resolve) => { first = resolve; }))
.mockReturnValueOnce(new Promise((resolve) => { second = resolve; }));
const { result } = renderHook(() => useWorkbenchGeocoding({ ...options, picking: true, mapRef: { current: map.map } }));
act(() => map.click());
const firstSignal = vi.mocked(reverseGeocodePoint).mock.calls[0][4];
act(() => map.click(other.longitude, other.latitude));
expect(firstSignal?.aborted).toBe(true);
await act(async () => { second(other); });
await act(async () => { first(location); });
expect(result.current.result).toEqual(other);
});
it.each(["close", "project", "escape"])("aborts an outstanding map lookup on %s", async (action) => {
const map = pickingMap();
let resolve!: (value: PlaceSearchItem) => void;
vi.mocked(reverseGeocodePoint).mockReturnValue(new Promise((done) => { resolve = done; }));
const props = { ...options, picking: true, onPickingChange: vi.fn(), mapRef: { current: map.map } };
const { result, rerender } = renderHook(useWorkbenchGeocoding, { initialProps: props });
act(() => map.click());
const signal = vi.mocked(reverseGeocodePoint).mock.calls[0][4];
if (action === "close") rerender({ ...props, active: false });
if (action === "project") rerender({ ...props, projectId: "other-project" });
if (action === "escape") act(() => window.dispatchEvent(new KeyboardEvent("keydown", { key: "Escape" })));
expect(signal?.aborted).toBe(true);
await act(async () => { resolve(location); });
expect(result.current.result).toBeNull();
expect(result.current.pending).toBe(false);
expect(props.onPickingChange).toHaveBeenCalledWith(false);
});
it("shows a lookup error and accepts another point", async () => {
const map = pickingMap();
const onPickingChange = vi.fn();
vi.mocked(reverseGeocodePoint).mockRejectedValueOnce(new Error("取点超出项目范围")).mockResolvedValueOnce(location);
const { result } = renderHook(() => useWorkbenchGeocoding({ ...options, picking: true, onPickingChange, mapRef: { current: map.map } }));
onPickingChange.mockClear();
await act(async () => { map.click(); });
expect(result.current.error).toBe("取点超出项目范围");
expect(onPickingChange).not.toHaveBeenCalled();
await act(async () => { map.click(); });
expect(result.current.error).toBeNull();
expect(result.current.result).toEqual(location);
expect(onPickingChange).toHaveBeenCalledExactlyOnceWith(false);
});
});
@@ -1,13 +1,17 @@
import type { Map as MapLibreMap, PaddingOptions } from "maplibre-gl";
import type { Map as MapLibreMap, MapMouseEvent, PaddingOptions } from "maplibre-gl";
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import { searchPlaces, type PlaceSearchItem, type PlaceSearchResults } from "../api/place-search-client";
import type { WorkbenchAccess } from "../api/request-context";
import { reverseGeocodePoint, searchPlaces, type PlaceSearchItem, type PlaceSearchResults } from "../api/place-search-client";
import { locateGeocodingResult, markGeocodingLocation } from "../map/geocoding-location";
import type { PlaceSearchConfiguration } from "../api/project-client";
type GeocodingOptions = {
placeSearch?: PlaceSearchConfiguration | null;
active: boolean;
picking?: boolean;
onPickingChange?: (picking: boolean) => void;
projectId: string | null;
getAccessToken?: AccessTokenProvider;
getAccessToken?: WorkbenchAccess;
mapRef: RefObject<MapLibreMap | null>;
mapReady: boolean;
getPadding: () => PaddingOptions;
@@ -16,6 +20,10 @@ type GeocodingOptions = {
};
export function useWorkbenchGeocoding(options: GeocodingOptions) {
const configured = Boolean(options.placeSearch?.enabled);
const region = options.placeSearch?.region ?? "";
const picking = Boolean(options.active && configured && options.mapReady && options.picking);
const [origin, setOrigin] = useState<"search" | "map">("search");
const [address, setAddress] = useState("");
const [result, setResult] = useState<PlaceSearchItem | null>(null);
const [results, setResults] = useState<PlaceSearchResults | null>(null);
@@ -37,15 +45,20 @@ export function useWorkbenchGeocoding(options: GeocodingOptions) {
setResults(null);
setChoosing(true);
setError(null);
setOrigin("search");
}, [cancel]);
useEffect(() => {
clear();
setAddress("");
optionsRef.current.onPickingChange?.(false);
return () => requestRef.current?.abort();
}, [options.projectId, options.getAccessToken, clear]);
useEffect(() => {
if (!options.active) cancel();
}, [options.active, cancel]);
if (!options.active || !configured) {
cancel();
optionsRef.current.onPickingChange?.(false);
}
}, [options.active, configured, cancel]);
const locate = useCallback(() => {
const current = optionsRef.current;
@@ -59,18 +72,75 @@ export function useWorkbenchGeocoding(options: GeocodingOptions) {
const map = options.mapRef.current;
if (!map || !options.mapReady || !result) return;
const marker = markGeocodingLocation(map, result);
locate();
if (origin === "search") locate();
return () => { marker.remove(); };
}, [options.mapRef, options.mapReady, result, locate]);
}, [options.mapRef, options.mapReady, result, origin, locate]);
async function lookupPoint(longitude: number, latitude: number) {
const current = optionsRef.current;
if (!current.active || !current.picking || !current.placeSearch?.enabled) return;
clear();
setOrigin("map");
const controller = new AbortController();
requestRef.current = controller;
setPending(true);
try {
const item = await reverseGeocodePoint(longitude, latitude, current.projectId,
current.getAccessToken, controller.signal, current.placeSearch);
if (controller.signal.aborted || requestRef.current !== controller) return;
setResult(item);
setResults({ items: [item], total: 1, truncated: false, region: current.placeSearch.region });
setChoosing(false);
optionsRef.current.onPickingChange?.(false);
} catch (failure) {
if (controller.signal.aborted || requestRef.current !== controller) return;
setError(failure instanceof Error && failure.name === "TimeoutError"
? "地图取点查询超时,请重新取点"
: failure instanceof Error ? failure.message : "地图取点查询失败,请重新取点");
} finally {
if (requestRef.current === controller) { requestRef.current = null; setPending(false); }
}
}
const lookupPointRef = useRef(lookupPoint);
lookupPointRef.current = lookupPoint;
useEffect(() => {
const map = options.mapRef.current;
if (!picking || !map) return;
const canvas = map.getCanvas();
const previousCursor = canvas.style.cursor;
canvas.style.cursor = "crosshair";
const handleClick = (event: MapMouseEvent) => {
event.preventDefault();
const longitude = ((event.lngLat.lng + 180) % 360 + 360) % 360 - 180;
void lookupPointRef.current(longitude, event.lngLat.lat);
};
const handleKeyDown = (event: KeyboardEvent) => {
if (event.key !== "Escape") return;
event.preventDefault();
event.stopPropagation();
cancel();
optionsRef.current.onPickingChange?.(false);
};
map.on("click", handleClick);
window.addEventListener("keydown", handleKeyDown, true);
return () => {
map.off("click", handleClick);
canvas.style.cursor = previousCursor;
window.removeEventListener("keydown", handleKeyDown, true);
};
}, [picking, options.mapRef, cancel]);
async function search() {
optionsRef.current.onPickingChange?.(false);
clear();
if (!configured) { setError("当前项目暂未配置地名搜索"); return; }
if (!address.trim()) { setError("请输入需要搜索的地址或地名"); return; }
const controller = new AbortController();
requestRef.current = controller;
setPending(true);
try {
const value = await searchPlaces(address, options.projectId, options.getAccessToken, controller.signal);
const value = await searchPlaces(address, options.projectId, options.getAccessToken, controller.signal, options.placeSearch);
if (controller.signal.aborted || requestRef.current !== controller) return;
setResults(value);
} catch (failure) {
@@ -84,7 +154,12 @@ export function useWorkbenchGeocoding(options: GeocodingOptions) {
}
return {
address, result, results, choosing, pending, error, locate, search,
address, result, results, choosing, pending, error, locate, search, region, origin, picking,
togglePicking: () => {
cancel();
if (!picking) { clear(); setOrigin("map"); optionsRef.current.onLocate(); }
optionsRef.current.onPickingChange?.(!picking);
},
select: (id: string) => {
if (pending) return;
const item = results?.items.find((candidate) => candidate.id === id);
@@ -95,9 +170,10 @@ export function useWorkbenchGeocoding(options: GeocodingOptions) {
}
},
changeSelection: () => setChoosing(true),
enabled: options.mapReady,
changeAddress: (value: string) => { clear(); setAddress(value); },
clear: () => { clear(); setAddress(""); }
configured,
enabled: configured && options.mapReady,
changeAddress: (value: string) => { optionsRef.current.onPickingChange?.(false); clear(); setAddress(value); },
clear: () => { optionsRef.current.onPickingChange?.(false); clear(); setAddress(""); }
};
}
@@ -8,6 +8,7 @@ import { WorkbenchMapController } from "../map/workbench-map-controller";
export function useWorkbenchMapController({
mapRef,
geoserverWorkspace,
mapReady,
leftPanelOpen,
rightPanelOpen,
@@ -16,6 +17,7 @@ export function useWorkbenchMapController({
getScadaFeatures,
availableSourceIds
}: {
geoserverWorkspace?: string;
mapRef: RefObject<MapLibreMap | null>;
mapReady: boolean;
leftPanelOpen: boolean;
@@ -42,6 +44,7 @@ export function useWorkbenchMapController({
const controllerRef = useRef<WorkbenchMapController | null>(null);
if (!controllerRef.current) {
controllerRef.current = new WorkbenchMapController({
geoserverWorkspace,
getMap: () => mapRef.current,
isReady: () => valuesRef.current.mapReady,
getPadding: () => {
@@ -9,7 +9,7 @@ import type {
StyleSpecification
} from "maplibre-gl";
import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "../api/request-context";
import { env } from "@/shared/config/env";
import { fetchScadaSnapshot, type ScadaDevice } from "../api/scada-client";
import type { DetailFeature } from "../types";
@@ -62,6 +62,7 @@ declare global {
}
type UseWorkbenchMapOptions = {
featureInteractionsEnabled?: boolean;
containerRef: RefObject<HTMLDivElement | null>;
impactVisible: boolean;
layerVisibility: Record<string, boolean>;
@@ -71,7 +72,8 @@ type UseWorkbenchMapOptions = {
simulationOverlay: FeatureCollection<Geometry> | null;
allowDemoSimulation: boolean;
networkView?: NetworkViewParams | null;
getAccessToken?: AccessTokenProvider;
getAccessToken?: WorkbenchAccess;
geoserverWorkspace?: string;
};
type UseWorkbenchMapResult = {
@@ -132,6 +134,7 @@ const EMPTY_SIMULATION_COLLECTION: FeatureCollection = {
};
export function useWorkbenchMap({
featureInteractionsEnabled = true,
containerRef,
impactVisible,
layerVisibility,
@@ -141,6 +144,7 @@ export function useWorkbenchMap({
simulationOverlay,
allowDemoSimulation,
networkView,
geoserverWorkspace,
getAccessToken
}: UseWorkbenchMapOptions): UseWorkbenchMapResult {
const mapRef = useRef<MapLibreMap | null>(null);
@@ -199,7 +203,7 @@ export function useWorkbenchMap({
);
geoServerLayerProbeInFlightRef.current = true;
void resolveGeoServerLayerAvailability(requestAbortController.signal)
void resolveGeoServerLayerAvailability(requestAbortController.signal, geoserverWorkspace)
.then((availability) => {
if (lifecycleAbortController.signal.aborted) return;
setAvailableGeoServerSourceIds((current) =>
@@ -237,7 +241,7 @@ export function useWorkbenchMap({
geoServerLayerProbeInFlightRef.current = false;
window.clearTimeout(probeTimeout);
};
}, [geoServerLayerRefreshRevision]);
}, [geoServerLayerRefreshRevision, geoserverWorkspace]);
useEffect(() => {
impactVisibleRef.current = impactVisible;
@@ -306,7 +310,7 @@ export function useWorkbenchMap({
(map.getSource(SCADA_SOURCE_ID) as GeoJSONSource | undefined)?.setData(
scadaCollectionRef.current
);
const sources = createWaterNetworkSources(REQUIRED_GEOSERVER_SOURCE_IDS);
const sources = createWaterNetworkSources(REQUIRED_GEOSERVER_SOURCE_IDS, geoserverWorkspace);
REQUIRED_GEOSERVER_SOURCE_IDS.forEach((sourceId) => {
const source = sources[sourceId];
if (source) map.addSource(sourceId, source);
@@ -315,8 +319,10 @@ export function useWorkbenchMap({
map.addSource(SIMULATION_SOURCE_IDS.annotations, simulationSources.annotations);
map.addSource(SIMULATION_SOURCE_IDS.backendAnalysis, simulationSources.backendAnalysis);
syncSimulationSourceData(map, simulationOverlayRef.current, allowDemoSimulationRef.current);
await registerSupplyAssetImages(map);
const scadaRegistration = await registerScadaImages(map);
await registerSupplyAssetImages(map, scadaAbortController.signal);
if (scadaAbortController.signal.aborted) return;
const scadaRegistration = await registerScadaImages(map, scadaAbortController.signal);
if (scadaAbortController.signal.aborted) return;
const activeScadaBusinessLayers =
scadaRegistration.status === "unavailable"
? scadaFallbackBusinessLayers
@@ -444,13 +450,13 @@ export function useWorkbenchMap({
mapRef.current = null;
delete window.__waterNetworkMap;
};
}, [containerRef, getAccessToken]);
}, [containerRef, getAccessToken, geoserverWorkspace]);
useEffect(() => {
const map = mapRef.current;
if (!mapReady || !map) return;
syncDataDependentGeoServerLayers(map, availableGeoServerSourceIds, layerVisibility);
}, [availableGeoServerSourceIds, layerVisibility, mapReady]);
syncDataDependentGeoServerLayers(map, availableGeoServerSourceIds, layerVisibility, geoserverWorkspace);
}, [availableGeoServerSourceIds, layerVisibility, mapReady, geoserverWorkspace]);
useEffect(() => {
const map = mapRef.current;
@@ -462,6 +468,7 @@ export function useWorkbenchMap({
}, [mapReady, networkView]);
useMapInteractions({
enabled: featureInteractionsEnabled,
availableSourceIds: availableGeoServerSourceIds,
mapRef,
mapReady,
@@ -557,7 +564,8 @@ function syncSimulationSourceData(
function syncDataDependentGeoServerLayers(
map: MapLibreMap,
availableSourceIds: readonly GeoServerWaterNetworkSourceId[],
layerVisibility: Record<string, boolean>
layerVisibility: Record<string, boolean>,
workspace?: string
) {
const availableSourceIdSet = new Set<GeoServerWaterNetworkSourceId>(availableSourceIds);
@@ -574,7 +582,7 @@ function syncDataDependentGeoServerLayers(
const requestedOptionalSourceIds = DATA_DEPENDENT_GEOSERVER_SOURCE_IDS.filter((sourceId) =>
availableSourceIdSet.has(sourceId)
);
const sources = createWaterNetworkSources(requestedOptionalSourceIds);
const sources = createWaterNetworkSources(requestedOptionalSourceIds, workspace);
requestedOptionalSourceIds.forEach((sourceId) => {
if (!map.getSource(sourceId) && sources[sourceId]) {
map.addSource(sourceId, sources[sourceId]);
@@ -620,7 +628,8 @@ function addMissingDataDependentLayers(
layers: StyleSpecification["layers"],
beforeLayerCandidates: readonly string[],
availableSourceIdSet: ReadonlySet<GeoServerWaterNetworkSourceId>,
layerVisibility: Record<string, boolean>
layerVisibility: Record<string, boolean>,
workspace?: string
) {
const beforeLayerId = beforeLayerCandidates.find((layerId) => map.getLayer(layerId));
layers.forEach((layer) => {
@@ -18,6 +18,7 @@ function presentation(
systemRole: "user",
isSystemAdmin: false,
networkView: null,
placeSearch: null,
metadataAvailable: true,
accessContextAvailable: true,
...overrides
@@ -1,5 +1,5 @@
import { useEffect, useMemo, useState } from "react";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "../api/request-context";
import {
fetchWorkbenchProjectPresentation,
type WorkbenchProjectPresentation
@@ -14,11 +14,17 @@ const PROJECT_ROLE_LABELS: Record<string, string> = {
export function useWorkbenchProjectPresentation(
fallbackUser: WorkbenchUser,
getAccessToken?: AccessTokenProvider
getAccessToken?: WorkbenchAccess
) {
const [presentation, setPresentation] = useState<WorkbenchProjectPresentation | null>(null);
const [presentation, setPresentation] = useState<WorkbenchProjectPresentation | null>(
() => typeof getAccessToken === "object" ? getAccessToken.presentation ?? null : null
);
useEffect(() => {
if (typeof getAccessToken === "object" && getAccessToken.presentation) {
setPresentation(getAccessToken.presentation);
return;
}
const controller = new AbortController();
void fetchWorkbenchProjectPresentation(getAccessToken, controller.signal)
.then((value) => {
@@ -39,6 +45,7 @@ export function useWorkbenchProjectPresentation(
user,
projectId: presentation?.projectId ?? null,
networkView: presentation?.networkView ?? null,
placeSearch: presentation?.placeSearch ?? null,
dataSource: presentation?.metadataAvailable || presentation?.accessContextAvailable
? "backend" as const
: "fallback" as const
@@ -81,5 +81,6 @@ describe("workbench responsive layout", () => {
act(() => result.current.openAgentPanelForViewport());
expect(result.current.mobileSheet).toBe("agent");
expect(result.current.mobileSheetSnap).toBe("full");
});
});
@@ -96,7 +96,7 @@ export function useWorkbenchResponsiveLayout({
}
setMobileSheet("agent");
setMobileSheetSnap("half");
setMobileSheetSnap("full");
}
function handleConditionExpandedChange(nextExpanded: boolean) {
@@ -0,0 +1,47 @@
import { cleanup, renderHook, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { WorkbenchRequestContext } from "../api/request-context";
import type { WorkbenchSyncState } from "./use-workbench-sync";
import { useWorkbenchRuntimeData } from "./use-workbench-runtime-data";
vi.mock("../api/realtime-flow-client", () => ({
fetchRealtimePipeFlows: vi.fn().mockResolvedValue({ records: [], observedAt: null })
}));
const fengyangAccess: WorkbenchRequestContext = {
project: {
project_id: "b962c44e-8433-4a10-81e9-a64b70ac1152",
name: "凤阳(新版)",
code: "fengyang_v2",
gs_workspace: "fengyang_v2",
status: "active",
project_role: "member"
},
getAccessToken: async () => "test-token"
};
const sync = {
snapshot: null,
events: [],
status: "live",
error: null,
detailResetGeneration: 0,
acknowledgeEventsThrough: vi.fn(),
refresh: vi.fn().mockResolvedValue(undefined),
subscribePresentationEvents: vi.fn(() => () => undefined)
} as unknown as WorkbenchSyncState;
afterEach(cleanup);
describe("project-scoped workbench runtime data", () => {
it("shows mock scheduled conditions outside the demo project", async () => {
const { result } = renderHook(() => useWorkbenchRuntimeData(fengyangAccess, sync));
await waitFor(() => expect(result.current.scheduledConditionsLoading).toBe(false));
expect(result.current.scheduledConditions.length).toBeGreaterThan(0);
expect(result.current.scheduledConditions.every((condition) => condition.kind === "condition"))
.toBe(true);
expect(result.current.scenarios).toEqual([]);
});
});
@@ -1,5 +1,5 @@
import { useEffect, useState } from "react";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import { getWorkbenchProject, type WorkbenchAccess } from "../api/request-context";
import { env } from "@/shared/config/env";
import {
type WorkbenchRuntimeSnapshot
@@ -128,9 +128,11 @@ function isSameLocalOperationalDate(value: string, operationalDate: Date) {
}
export function useWorkbenchRuntimeData(
getAccessToken: AccessTokenProvider | undefined,
getAccessToken: WorkbenchAccess | undefined,
sync: WorkbenchSyncState
) {
const scopedProject = getWorkbenchProject(getAccessToken);
const allowDemoScenarios = !scopedProject || scopedProject.gs_workspace === "tjwater_next";
const [headerDataTime, setHeaderDataTime] = useState(INITIAL_HEADER_DATA_TIME);
const [mockConditions, setMockConditions] = useState<ScheduledConditionItem[]>([]);
const backendSnapshot: WorkbenchRuntimeSnapshot | null = sync.snapshot?.runtime ?? null;
@@ -252,7 +254,8 @@ export function useWorkbenchRuntimeData(
scheduledConditionsLoading,
realtimePipeFlows,
flowDataSource: realtimePipeFlows ? "realtime" as const : "mock" as const,
...resolvedRuntimeData
...resolvedRuntimeData,
scenarios: !allowDemoScenarios && resolvedRuntimeData.scenarioDataSource === "mock" ? [] : resolvedRuntimeData.scenarios
};
}
@@ -1,5 +1,5 @@
import { useCallback, useEffect, useRef, useState } from "react";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import type { WorkbenchAccess } from "../api/request-context";
import {
consumeWorkbenchEvents,
fetchWorkbenchSyncSnapshot,
@@ -45,7 +45,7 @@ export function shouldApplyWorkbenchSnapshot(input: {
&& (input.resetCursor || input.eventCursor >= input.currentCursor);
}
export function useWorkbenchSync(getAccessToken?: AccessTokenProvider): WorkbenchSyncState {
export function useWorkbenchSync(getAccessToken?: WorkbenchAccess): WorkbenchSyncState {
const channelRef = useRef(new WorkbenchEventChannel());
const [snapshot, setSnapshot] = useState<WorkbenchSyncSnapshot | null>(null);
const [events, setEvents] = useState<WorkbenchEvent[]>([]);
@@ -0,0 +1,8 @@
import { useEffect, useMemo, type ReactNode } from "react";
import { WorkbenchSessionContext, WorkbenchSessionResources } from "./workbench-session-resources";
export function WorkbenchSessionProvider({ children, owner }: { children: ReactNode; owner?: unknown }) {
const resources = useMemo(() => new WorkbenchSessionResources(owner), [owner]);
useEffect(() => { resources.retain(); return () => resources.release(); }, [resources]);
return <WorkbenchSessionContext.Provider key={resources.id} value={resources}>{children}</WorkbenchSessionContext.Provider>;
}
@@ -0,0 +1,34 @@
import { createContext, useContext, useState } from "react";
import type { AgentSessionRuntime } from "./agent-session-runtime";
import { ResourceCache } from "@/shared/cache/resource-cache";
export class WorkbenchSessionResources {
constructor(readonly owner?: unknown) {}
readonly id = crypto.randomUUID();
disposed = false;
readonly cache = new ResourceCache();
readonly agents = new Map<string, AgentSessionRuntime>();
readonly disposers = new Set<() => void>();
activeAgent: AgentSessionRuntime | null = null;
private listeners = new Set<() => void>();
private revision = 0;
private retainCount = 0;
subscribe = (listener: () => void) => { this.listeners.add(listener); return () => this.listeners.delete(listener); };
getSnapshot = () => this.revision;
notify() { if (!this.disposed) { this.revision++; this.listeners.forEach((listener) => listener()); } }
retain() { this.retainCount++; }
release() {
this.retainCount--;
// StrictMode immediately reacquires its lease; a real unmount releases it.
queueMicrotask(() => { if (this.retainCount === 0) this.dispose(); });
}
dispose() { this.disposed = true; this.activeAgent = null; this.disposers.forEach((dispose) => dispose()); this.disposers.clear(); this.cache.clear(); this.agents.clear(); }
}
export const WorkbenchSessionContext = createContext<WorkbenchSessionResources | null>(null);
export function useWorkbenchSessionResources() {
const provided = useContext(WorkbenchSessionContext);
const [fallback] = useState(() => new WorkbenchSessionResources());
return provided ?? fallback;
}
+1
View File
@@ -1,4 +1,5 @@
export { MapWorkbenchPage } from "./map-workbench-page";
export { ProjectWorkbench } from "./project-workbench";
export { WorkbenchMapController } from "./map/workbench-map-controller";
export type {
FeatureTarget,
@@ -4,7 +4,7 @@ export const WORKBENCH_LAYOUT = {
persistentConditionMinWidth: 1280,
wideMinWidth: 1536,
collapsedAgentWidth: 0,
collapsedAgentRailWidth: 72,
collapsedAgentRailWidth: 64,
minAgentWidth: 400,
maxAgentWidth: 640,
agentPanelLeftInset: 12,
+246 -134
View File
@@ -1,3 +1,4 @@
import { useReadingWorkspace } from "@/shared/ui/reading-workspace-context";
import {
useCallback,
useEffect,
@@ -10,6 +11,7 @@ import {
} from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { CalendarClock, Clock3 } from "lucide-react";
import { ReadingWorkspaceProvider } from "@/shared/ui/reading-workspace";
import {
AgentCommandPanel,
AgentPersona,
@@ -18,7 +20,8 @@ import {
type FrontendActionRequest,
type UIEnvelopePayload,
type AgentUiResult,
type AgentWorkspaceContextItem
type AgentWorkspaceContextItem,
type AnswerUiSelection
} from "@/features/agent";
import {
MapErrorNotice,
@@ -33,11 +36,13 @@ import {
} from "@/features/map/core";
import { env } from "@/shared/config/env";
import { waitForAgentPresentation } from "./map/agent-presentation";
import type { AccessTokenProvider } from "@/shared/auth/keycloak-auth";
import { getWorkbenchProject, type WorkbenchAccess } from "./api/request-context";
import type { WorkbenchProjectSelection } from "./components/workbench-top-bar-menus";
import { AgentTaskTicker } from "./components/agent-task-ticker";
import { AnalysisResultsPanel } from "./components/analysis-results-panel";
import { PeripheralSamplePanel } from "./peripheral-sample/peripheral-sample-panel";
import type { PeripheralWorkOrder } from "./peripheral-sample/client";
import type { PeripheralTestDataRecord, PeripheralWorkOrder } from "./peripheral-sample/client";
import { buildScadaAnomalyInvestigation } from "./peripheral-sample/scada-anomaly-agent-trigger";
import { MapDevPanel } from "./components/map-dev-panel";
import { InvestigationPresentationPanel } from "./components/investigation-presentation-panel";
import { MobileWorkbenchSheet } from "./components/mobile-workbench-sheet";
@@ -125,15 +130,22 @@ const ALERT_TIME_FORMATTER = new Intl.DateTimeFormat("zh-CN", {
hour12: false
});
export function MapWorkbenchPage({
user = WORKBENCH_USER,
onLogout,
getAccessToken
}: {
type MapWorkbenchPageProps = {
user?: WorkbenchUser;
onLogout?: () => Promise<void>;
getAccessToken?: AccessTokenProvider;
}) {
getAccessToken?: WorkbenchAccess;
projectSelection?: WorkbenchProjectSelection;
};
export function MapWorkbenchPage(props: MapWorkbenchPageProps) {
return <ReadingWorkspaceProvider><MapWorkbenchContent {...props} /></ReadingWorkspaceProvider>;
}
function MapWorkbenchContent({
user = WORKBENCH_USER,
onLogout,
getAccessToken,
projectSelection
}: MapWorkbenchPageProps) {
const readingWorkspace = useReadingWorkspace();
const hasMapboxToken = Boolean(env.TJWATER_MAPBOX_ACCESS_TOKEN);
const hasTiandituToken = Boolean(env.TJWATER_TIANDITU_TOKEN);
const hasOnlineBasemap = hasMapboxToken || hasTiandituToken;
@@ -145,6 +157,7 @@ export function MapWorkbenchPage({
const [investigationFollow, setInvestigationFollow] = useState(true);
const presentationLayerChangesRef = useRef(new Map<string, boolean>());
const [impactVisible, setImpactVisible] = useState(false);
const [geocodingPickActive, setGeocodingPickActive] = useState(false);
const [activeToolId, setActiveToolId] = useState<ToolbarToolId | null>(null);
const prefersReducedMotion = useReducedMotion();
const [taskTickerVisible, setTaskTickerVisible] = useState(true);
@@ -272,7 +285,8 @@ export function MapWorkbenchPage({
const activeSpatialOverlay = artifactWorkspace.activeArtifact?.spatialOverlay ?? null;
const activeArtifactHasSpatialView = Boolean(activeSpatialOverlay?.features.length);
const allowDemoSimulation =
artifactWorkspace.activeArtifact === null || artifactWorkspace.activeArtifact.origin === "demo";
(!getWorkbenchProject(getAccessToken) || getWorkbenchProject(getAccessToken)?.gs_workspace === "tjwater_next")
&& (artifactWorkspace.activeArtifact === null || artifactWorkspace.activeArtifact.origin === "demo");
const latestAnalysisAvailable = Boolean(
latestAnalysisArtifact?.blocks.some(
(block) =>
@@ -395,6 +409,44 @@ export function MapWorkbenchPage({
}
}
async function handleScadaAnomalyAgentTrigger(record: PeripheralTestDataRecord) {
showMapNotice({
id: "scada-anomaly-agent-trigger",
tone: "loading",
title: "SCADA 模拟异常已接收",
message: "正在建立结构化异常调查任务。",
duration: Infinity
});
try {
const task = await operationalTasks.createInvestigation(
buildScadaAnomalyInvestigation(record)
);
setPeripheralSamplePanelOpen(false);
openConditionWorkspaceForViewport();
const conditionId = operationalTaskConditionId(task.task_id);
setSelectedConditionId(conditionId);
setConditionFocusRequest((current) => ({
conditionId,
requestId: (current?.requestId ?? 0) + 1
}));
showMapNotice({
id: "scada-anomaly-agent-trigger",
tone: "success",
title: "已建立 SCADA 异常调查",
message: `关联模拟读数 ${record.record_id.slice(0, 8)},Agent 将按任务上下文核查。`
});
} catch (error) {
showMapNotice({
id: "scada-anomaly-agent-trigger",
tone: "error",
title: "异常调查任务创建失败",
message: error instanceof Error ? error.message : "Agent 事件入口当前不可用。"
});
throw error;
}
}
function openConditionWorkspaceForViewport() {
openConditionFeedForViewport();
}
@@ -422,6 +474,7 @@ export function MapWorkbenchPage({
scadaObservedAt,
refreshGeoServerLayers
} = useWorkbenchMap({
featureInteractionsEnabled: !geocodingPickActive,
containerRef: mapContainerRef,
impactVisible,
layerVisibility,
@@ -431,6 +484,7 @@ export function MapWorkbenchPage({
simulationOverlay: activeSpatialOverlay,
allowDemoSimulation,
networkView: projectPresentation.networkView,
geoserverWorkspace: getWorkbenchProject(getAccessToken)?.gs_workspace,
getAccessToken
});
const displayedDataTime =
@@ -439,6 +493,7 @@ export function MapWorkbenchPage({
: headerDataTime;
const { controller: mapController, state: mapControllerState } = useWorkbenchMapController({
mapRef,
geoserverWorkspace: getWorkbenchProject(getAccessToken)?.gs_workspace,
mapReady,
leftPanelOpen: false,
rightPanelOpen,
@@ -464,6 +519,12 @@ export function MapWorkbenchPage({
getPadding: () => mapRef.current ? getResponsiveWorkbenchPadding(mapRef.current, leftPanelOpen, rightPanelOpen, rightPanelExpanded, agentPanelWidth) : { top: 48, right: 48, bottom: 48, left: 48 }
});
const geocoding = useWorkbenchGeocoding({
picking: geocodingPickActive,
onPickingChange: (picking) => {
setGeocodingPickActive(picking);
if (picking) { setActiveDrawToolId(null); measurement.stop(); }
},
placeSearch: projectPresentation.placeSearch,
active: activeToolId === "geocoding",
projectId: projectPresentation.projectId,
getAccessToken, mapRef, mapReady,
@@ -479,7 +540,11 @@ export function MapWorkbenchPage({
}
});
function handleLocateInvestigationTargets(targets: InvestigationMapTarget[]) {
void presentation.locateTargets(targets).catch((error) => showMapNotice({ tone: "warning", title: "关联要素暂不可定位", message: error instanceof Error ? error.message : "地图当前不可用" }));
if (readingWorkspace?.active) readingWorkspace.setView(businessWorkspaceWidth >= 960 ? "map_split" : "map_only");
return presentation.locateTargets(targets).then(() => true).catch((error) => {
showMapNotice({ tone: "warning", title: "关联要素暂不可定位", message: error instanceof Error ? error.message : "地图当前不可用" });
return false;
});
}
useEffect(() => () => {
restorePresentationLayers();
@@ -502,6 +567,7 @@ export function MapWorkbenchPage({
[scheduledConditions]
);
const drawing = useWorkbenchDrawing({
selectionEnabled: !geocodingPickActive,
mapRef,
mapReady,
activeMode: activeDrawToolId,
@@ -516,6 +582,7 @@ export function MapWorkbenchPage({
});
const taskTickerAvailable = runningTickerConditions.length > 0;
const shouldShowTaskTicker =
!readingWorkspace?.active &&
!artifactActive &&
mobileSheet === null &&
!conditionFeedExpanded &&
@@ -933,20 +1000,24 @@ export function MapWorkbenchPage({
}
async function handleLoadAgentHistorySession(sessionId: string) {
if (sessionId !== agent.sessionId) {
mapController.clearScadaAnalysis();
}
await agent.loadHistorySession(sessionId);
const changesSession = sessionId !== agent.sessionId;
const loaded = await agent.loadHistorySession(sessionId);
if (!loaded) throw new Error("会话打开已取消");
if (changesSession) mapController.clearScadaAnalysis();
}
async function handleOpenTaskCollaboration(taskId: string, discussion?: InvestigationDiscussion) {
mapController.clearScadaAnalysis();
await agent.openTaskCollaboration(taskId, discussion);
const id = await agent.openTaskCollaboration(taskId, discussion);
if (discussion?.reference && id) agent.setContentReference(discussion.reference);
readingWorkspace?.close();
openAgentPanelForViewport();
}
async function handleDeleteAgentHistorySession(sessionId: string) {
const clearsActiveAnalysis = sessionId === agent.sessionId;
const deleted = await agent.deleteHistorySession(sessionId);
if (!deleted) throw new Error("会话删除失败,请重试");
if (deleted && clearsActiveAnalysis) {
mapController.clearScadaAnalysis();
}
@@ -1134,7 +1205,7 @@ export function MapWorkbenchPage({
? operationalTasks.tasks.find((item) => item.task_id === agent.sessionTaskId)
: undefined;
const promptSuggestions = useAgentPromptSuggestions({
enabled: agent.conversationScope === "project" && (isLargeScreen ? agent.panelOpen : mobileSheet === "agent") && agent.messages.length === 0 && !agent.streaming &&
enabled: (isLargeScreen ? agent.panelOpen : mobileSheet === "agent") && agent.messages.length === 0 && !agent.streaming &&
agent.sessionPurpose === "ordinary_chat" && agent.connectionStatus === "online" && !agent.sessionHistoryLoading &&
!scheduledConditionsLoading && !operationalTasks.loading,
model: agent.selectedModel,
@@ -1145,7 +1216,8 @@ export function MapWorkbenchPage({
conditions: scheduledConditions,
runtimeDataSource,
artifact: latestAnalysisArtifact ?? null,
sessions: agent.sessionHistory,
sessions: agent.recentSessions,
cacheScope: agent.cacheScope,
});
const agentPanelProps: Omit<
ComponentProps<typeof AgentCommandPanel>,
@@ -1155,6 +1227,25 @@ export function MapWorkbenchPage({
sessionTitle: agent.sessionTitle,
sessionHistory: agent.sessionHistory,
sessionHistoryLoading: agent.sessionHistoryLoading,
topicControls: agent.topicControls,
historyTopicId: agent.history.topicId,
onHistoryTopicChange: agent.history.setTopicId,
onMoveSessionToTopic: agent.moveSessionToTopic,
historyQuery: agent.history.query,
onHistoryQueryChange: agent.history.setQuery,
historyHasMore: agent.history.hasMore,
historyLoadingMore: agent.history.loadingMore,
historyError: agent.history.error ? "历史记录加载失败,请刷新重试" : undefined,
historyPendingUpdate: agent.history.pendingUpdate,
onHistoryOpen: agent.history.ensure,
onHistoryClose: agent.closeHistory,
onLoadMoreHistory: agent.history.loadMore,
hasOlderMessages: agent.hasOlderMessages,
loadingOlderMessages: agent.loadingOlderMessages,
onLoadOlderMessages: agent.loadOlderMessages,
readingPosition: agent.readingPosition,
onReadingPositionChange: agent.onReadingPositionChange,
backgroundStatus: agent.backgroundStatus,
promptSuggestions: promptSuggestions.suggestions,
promptSuggestionsLoading: promptSuggestions.loading,
promptSuggestionsUnavailable: promptSuggestions.unavailable,
@@ -1167,12 +1258,19 @@ export function MapWorkbenchPage({
onInputDeliveryChange: agent.setInputDelivery,
pendingInputs: agent.pendingInputs,
onPendingInputDeliveryChange: agent.updateInputDelivery,
onPendingInputEdit: (id) => agent.withdrawInput(id, true),
onPendingInputCancel: (id) => agent.withdrawInput(id, false),
onDownloadFile: async (path) => {
try { await agent.apiClient.downloadFile(path); }
catch (error) {
showMapNotice({ tone: "error", title: "文件下载失败", message: error instanceof Error ? error.message : "请稍后重试" });
}
},
messages: agent.messages,
streamRenderState: agent.streamRenderState,
modelOptions: agent.modelOptions,
selectedModel: agent.selectedModel,
conversationScope: agent.conversationScope,
onConversationScopeChange: agent.changeConversationScope,
currentProjectName: getWorkbenchProject(getAccessToken)?.name,
approvalMode: agent.approvalMode,
uiResults: activeAgentUiResults,
reviewPanel: collaborationReviewTask ? <TaskConversationReview task={collaborationReviewTask}
@@ -1185,6 +1283,11 @@ export function MapWorkbenchPage({
onRefresh={operationalTasks.refresh} /> : undefined,
workspaceContext: agentWorkspaceContext,
prompt: agent.promptDraft,
contentReference: agent.contentReference,
onContentReferenceChange: (value) => {
agent.setContentReference(value);
if (value) readingWorkspace?.close();
},
promptReference: collaborationReviewTask ? {
title: collaborationReviewTask.title,
placeholder: "可询问调查进展、讨论报告或补充信息",
@@ -1211,7 +1314,10 @@ export function MapWorkbenchPage({
onRefresh: agent.agentMessageInbox.refresh
} : undefined,
onSubmitPrompt: agent.submitPrompt,
onLocateAnswerFeatures: (target) => mapController.locateFeatures(target.layer, target.feature_ids, new AbortController().signal),
onLocateAnswerFeatures: async (target) => {
if (readingWorkspace?.active) readingWorkspace.setView(businessWorkspaceWidth >= 960 ? "map_split" : "map_only");
return mapController.locateFeatures(target.layer, target.feature_ids, new AbortController().signal);
},
onStopPrompt: agent.stopPrompt,
onReplyPermission: agent.replyPermission,
onReplyQuestion: agent.replyQuestion,
@@ -1241,6 +1347,7 @@ export function MapWorkbenchPage({
alerts={workbenchAlerts}
alertDataSource={alertDataSource}
user={projectPresentation.user}
projectSelection={projectSelection}
conditionFeedVisible={isLargeScreen ? shouldShowConditionFeed : mobileSheet === "condition"}
timelineVisible={timelineVisible}
taskTickerAvailable={taskTickerAvailable}
@@ -1298,113 +1405,7 @@ export function MapWorkbenchPage({
onClose={() => setPeripheralSamplePanelOpen(false)}
getAccessToken={getAccessToken}
onAgentTrigger={handlePeripheralWorkOrderAgentTrigger}
/>
<WorkbenchMainFrame
activeArtifact={artifactWorkspace.activeArtifact}
pendingArtifact={artifactWorkspace.pendingArtifact}
surfaceMode={artifactWorkspace.surfaceMode}
mapSplitAvailable={artifactWorkspace.mapSplitAvailable}
onOpenPendingArtifact={artifactWorkspace.openPreview}
onDestroyPendingArtifact={artifactWorkspace.destroyPreview}
onSetArtifactView={artifactWorkspace.setView}
onCollapseArtifact={artifactWorkspace.collapseArtifact}
onDestroyArtifact={artifactWorkspace.destroyArtifact}
timelineMode={timelineMode}
timelineBottom={timelineBottom}
timelineContent={
timelineVisible ? (
<>
<div className="hidden lg:block">
<OperationalTimeline
date={workspaceContext.operational.date}
cursorTime={workspaceContext.operational.cursorTime}
events={operationalEvents}
mode={timelineMode}
selectedEventId={workspaceContext.operational.selectedEventId}
onModeChange={setTimelineMode}
onSelectEvent={handleSelectOperationalEvent}
onClearSelection={handleClearOperationalSelection}
onReturnNow={handleReturnOperationalNow}
/>
</div>
<div
role="region"
aria-label="移动端运行时间轴摘要"
className="acrylic-control flex h-12 w-full items-center rounded-2xl border p-1 text-xs text-slate-700 lg:hidden"
>
<button
type="button"
aria-label="打开完整运行时间轴"
onClick={openTimelineForViewport}
className="flex h-10 min-w-0 flex-1 items-center gap-1.5 rounded-xl px-2 text-left transition-colors hover:bg-white/55 active:bg-white/75"
>
<Clock3 size={15} className="shrink-0 text-blue-600" aria-hidden="true" />
<span className="shrink-0 font-semibold">运行时间轴</span>
<span className="flex min-w-0 items-center gap-1.5 whitespace-nowrap text-[10px]">
<span className="text-slate-500">计划 {operationalSummary.planned}</span>
<span className="text-slate-500">执行 {operationalSummary.active}</span>
<span className="text-amber-700">关注 {operationalSummary.attention}</span>
<span className="text-rose-700">异常 {operationalSummary.exceptions}</span>
</span>
<span className="ml-auto hidden shrink-0 text-slate-500 min-[360px]:inline">
查看全天
</span>
</button>
</div>
</>
) : null
}
mapContent={
<div
ref={mapContainerRef}
className="map-grid absolute inset-0"
style={{ position: "absolute", inset: 0 }}
aria-label="供水管网地图"
/>
}
mapOverlay={
<div className="pointer-events-none absolute inset-x-0 bottom-0 top-14">
{investigationFollow && selectedInvestigationTask && !devPanelOpen ? <InvestigationPresentationPanel
task={selectedInvestigationTask} charts={presentation.charts} overlay={presentation.overlay} cameraPaused={presentation.cameraPaused}
status={presentation.status} error={presentation.error}
width={Math.min(380, Math.max(180, businessWorkspaceWidth - (rightPanelOpen ? (rightPanelExpanded ? (viewportWidth >= 1536 ? 960 : 880) : 432) + 64 : 64) - 24))}
relatedLayers={presentationRelatedLayers} onToggleLayer={handleTogglePresentationLayer}
onResumeCamera={presentation.resumeCamera} onCloseChart={presentation.closeChart} onToggleOverlay={presentation.toggleOverlay} onFitOverlay={presentation.fitOverlay}
/> : null}
{!devPanelOpen ? (
<>
<div className="pointer-events-auto absolute right-3 top-10 hidden lg:block">
<MapToolbar items={toolbarItems} />
</div>
<div className="pointer-events-auto absolute right-16 top-10 hidden lg:block">
<ToolbarPanel {...toolbarPanelProps} />
</div>
</>
) : null}
<div
className="absolute right-3 flex flex-col items-end gap-2 bottom-[var(--mobile-map-control-bottom)] transition-[bottom] duration-200 ease-out motion-reduce:transition-none lg:right-0 lg:bottom-[var(--desktop-map-scale-bottom)]"
style={
{
"--mobile-map-control-bottom": `${mobileOverlayLayout.mapControlBottom}px`,
"--desktop-map-scale-bottom": `${timelineScaleLayout.scaleBottom}px`
} as CSSProperties
}
>
<div className="flex items-end gap-2 lg:pr-2"
onPointerDownCapture={() => { if (investigationFollow) presentation.pauseCamera(); }}
onKeyDownCapture={() => { if (investigationFollow) presentation.pauseCamera(); }}>
<MapZoom
mapRef={mapRef}
mapReady={mapReady}
onHome={fitNetworkBounds}
reducedMotion={prefersReducedMotion ?? false}
/>
</div>
<MapScaleLine className="hidden lg:inline-flex" mapRef={mapRef} mapReady={mapReady} />
</div>
</div>
}
onScadaAnomalyTrigger={handleScadaAnomalyAgentTrigger}
/>
<WorkbenchAgentPanels
@@ -1418,10 +1419,119 @@ export function MapWorkbenchPage({
onCollapsePanel={agent.collapsePanel}
onExpandPanel={agent.expandPanel}
onWidthCommit={setAgentPanelWidth}
/>
>
<WorkbenchMainFrame
activeArtifact={artifactWorkspace.activeArtifact}
pendingArtifact={artifactWorkspace.pendingArtifact}
surfaceMode={artifactWorkspace.surfaceMode}
mapSplitAvailable={artifactWorkspace.mapSplitAvailable}
readingSplitAvailable={businessWorkspaceWidth >= 960}
onOpenPendingArtifact={artifactWorkspace.openPreview}
onDestroyPendingArtifact={artifactWorkspace.destroyPreview}
onSetArtifactView={artifactWorkspace.setView}
onCollapseArtifact={artifactWorkspace.collapseArtifact}
onDestroyArtifact={artifactWorkspace.destroyArtifact}
timelineMode={timelineMode}
timelineBottom={timelineBottom}
timelineContent={
timelineVisible ? (
<>
<div className="hidden lg:block">
<OperationalTimeline
date={workspaceContext.operational.date}
cursorTime={workspaceContext.operational.cursorTime}
events={operationalEvents}
mode={timelineMode}
selectedEventId={workspaceContext.operational.selectedEventId}
onModeChange={setTimelineMode}
onSelectEvent={handleSelectOperationalEvent}
onClearSelection={handleClearOperationalSelection}
onReturnNow={handleReturnOperationalNow}
/>
</div>
<div
role="region"
aria-label="移动端运行时间轴摘要"
className="acrylic-control flex h-12 w-full items-center rounded-2xl border p-1 text-xs text-slate-700 lg:hidden"
>
<button
type="button"
aria-label="打开完整运行时间轴"
onClick={openTimelineForViewport}
className="flex h-10 min-w-0 flex-1 items-center gap-1.5 rounded-xl px-2 text-left transition-colors hover:bg-white/55 active:bg-white/75"
>
<Clock3 size={15} className="shrink-0 text-blue-600" aria-hidden="true" />
<span className="shrink-0 font-semibold">运行时间轴</span>
<span className="flex min-w-0 items-center gap-1.5 whitespace-nowrap text-[10px]">
<span className="text-slate-500">计划 {operationalSummary.planned}</span>
<span className="text-slate-500">执行 {operationalSummary.active}</span>
<span className="text-amber-700">关注 {operationalSummary.attention}</span>
<span className="text-rose-700">异常 {operationalSummary.exceptions}</span>
</span>
<span className="ml-auto hidden shrink-0 text-slate-500 min-[360px]:inline">
查看全天
</span>
</button>
</div>
</>
) : null
}
mapContent={
<div
ref={mapContainerRef}
className="map-grid absolute inset-0"
style={{ position: "absolute", inset: 0 }}
aria-label="供水管网地图"
/>
}
mapOverlay={
<div className="pointer-events-none absolute inset-x-0 bottom-0 top-14">
{investigationFollow && selectedInvestigationTask && !devPanelOpen ? <InvestigationPresentationPanel
task={selectedInvestigationTask} charts={presentation.charts} overlay={presentation.overlay} cameraPaused={presentation.cameraPaused}
status={presentation.status} error={presentation.error}
width={Math.min(380, Math.max(180, businessWorkspaceWidth - (rightPanelOpen ? (rightPanelExpanded ? (viewportWidth >= 1536 ? 960 : 880) : 432) + 64 : 64) - 24))}
relatedLayers={presentationRelatedLayers} onToggleLayer={handleTogglePresentationLayer}
onResumeCamera={presentation.resumeCamera} onCloseChart={presentation.closeChart} onToggleOverlay={presentation.toggleOverlay} onFitOverlay={presentation.fitOverlay}
/> : null}
{!devPanelOpen ? (
<>
<div className="pointer-events-auto absolute right-3 top-10 hidden lg:block">
<MapToolbar items={toolbarItems} />
</div>
<div className="pointer-events-auto absolute right-16 top-10 hidden lg:block">
<ToolbarPanel {...toolbarPanelProps} />
</div>
</>
) : null}
<div
className="absolute right-3 flex flex-col items-end gap-2 bottom-[var(--mobile-map-control-bottom)] transition-[bottom] duration-200 ease-out motion-reduce:transition-none lg:right-0 lg:bottom-[var(--desktop-map-scale-bottom)]"
style={
{
"--mobile-map-control-bottom": `${mobileOverlayLayout.mapControlBottom}px`,
"--desktop-map-scale-bottom": `${timelineScaleLayout.scaleBottom}px`
} as CSSProperties
}
>
<div className="flex items-end gap-2 lg:pr-2"
onPointerDownCapture={() => { if (investigationFollow) presentation.pauseCamera(); }}
onKeyDownCapture={() => { if (investigationFollow) presentation.pauseCamera(); }}>
<MapZoom
mapRef={mapRef}
mapReady={mapReady}
onHome={fitNetworkBounds}
reducedMotion={prefersReducedMotion ?? false}
/>
</div>
<MapScaleLine className="hidden lg:inline-flex" mapRef={mapRef} mapReady={mapReady} />
</div>
</div>
}
/>
</WorkbenchAgentPanels>
{conditionFeedMounted ? (
<div className="absolute bottom-[calc(var(--workbench-timeline-height)+1.25rem)] right-16 top-24 z-50 hidden lg:block 2xl:[--workbench-condition-width:var(--workbench-condition-width-wide)]" style={devPanelOpen ? { display: "none" } : undefined}>
<div className="absolute bottom-[calc(var(--workbench-timeline-height)+1.25rem)] right-16 top-24 z-50 hidden lg:block 2xl:[--workbench-condition-width:var(--workbench-condition-width-wide)]" style={devPanelOpen || readingWorkspace?.active ? { display: "none" } : undefined}>
<ScheduledConditionFeed
presentation="desktop-floating"
conditions={scheduledConditions}
@@ -1469,7 +1579,7 @@ export function MapWorkbenchPage({
/>
) : null}
{mobileSheet === null && artifactWorkspace.surfaceMode !== "focus" ? (
{mobileSheet === null && !readingWorkspace?.active && artifactWorkspace.surfaceMode !== "focus" ? (
<div
className="absolute left-3 right-3 z-30 transition-[bottom] duration-200 ease-out motion-reduce:transition-none lg:hidden"
style={{ bottom: mobileOverlayLayout.mapControlBottom }}
@@ -1485,7 +1595,7 @@ export function MapWorkbenchPage({
{shouldShowTaskTicker ? (
<motion.div
key="agent-task-ticker-shell"
className="fixed left-1/2 right-auto top-24 z-50 w-[calc(100%-1.5rem)] [translate:-50%_0] md:absolute md:w-[var(--workbench-ticker-width)] 2xl:w-[var(--workbench-ticker-width-wide)]"
className="fixed left-1/2 right-auto top-24 z-50 w-[calc(100%-1.5rem)] [translate:-50%_0] md:absolute md:w-[var(--workbench-ticker-width)] lg:left-[calc((100%+var(--workbench-agent-current-width))/2)] lg:max-w-[calc(100%-var(--workbench-agent-current-width)-1.5rem)] 2xl:w-[var(--workbench-ticker-width-wide)]"
style={{ transformOrigin: "top center" }}
initial={
prefersReducedMotion
@@ -1521,7 +1631,7 @@ export function MapWorkbenchPage({
onClick={openAgentPanelForViewport}
className="acrylic-control grid h-11 w-11 shrink-0 place-items-center rounded-xl border text-violet-700"
>
<AgentPersona className="pointer-events-none h-8 w-8" state={agent.personaState} />
<AgentPersona className="pointer-events-none h-10 w-10" state={agent.personaState} />
</button>
{artifactWorkspace.surfaceMode !== "focus" ? (
<MapToolbar
@@ -1545,6 +1655,8 @@ export function MapWorkbenchPage({
{mobileSheet ? (
<MobileWorkbenchSheet
className={readingWorkspace?.active ? "hidden" : undefined}
suspended={Boolean(readingWorkspace?.active)}
label={
mobileSheet === "agent"
? "Agent 工作台抽屉"
@@ -33,23 +33,24 @@ export const REQUIRED_GEOSERVER_SOURCE_IDS: GeoServerWaterNetworkSourceId[] = SU
layer.sourceLayer !== undefined && layer.availability === "required"
).map((layer) => layer.id);
export function createGeoServerLayerHitsUrl(sourceId: DataDependentGeoServerSourceId) {
export function createGeoServerLayerHitsUrl(sourceId: DataDependentGeoServerSourceId, workspace = GEOSERVER_WORKSPACE) {
const params = new URLSearchParams({
service: "WFS",
version: "2.0.0",
request: "GetFeature",
typeNames: `${GEOSERVER_WORKSPACE}:${SOURCE_LAYERS[sourceId]}`,
typeNames: `${workspace}:${SOURCE_LAYERS[sourceId]}`,
resultType: "hits"
});
return new URL(`${MAP_URL}/${GEOSERVER_WORKSPACE}/ows?${params.toString()}`);
return new URL(`${MAP_URL}/${workspace}/ows?${params.toString()}`);
}
export async function fetchGeoServerLayerFeatureCount(
sourceId: DataDependentGeoServerSourceId,
signal?: AbortSignal
signal?: AbortSignal,
workspace = GEOSERVER_WORKSPACE
) {
const response = await fetch(createGeoServerLayerHitsUrl(sourceId), {
const response = await fetch(createGeoServerLayerHitsUrl(sourceId, workspace), {
headers: { Accept: "application/xml, text/xml" },
signal
});
@@ -74,12 +75,13 @@ export async function fetchGeoServerLayerFeatureCount(
}
export async function resolveGeoServerLayerAvailability(
signal?: AbortSignal
signal?: AbortSignal,
workspace = GEOSERVER_WORKSPACE
): Promise<GeoServerLayerAvailability> {
const results = await Promise.allSettled(
DATA_DEPENDENT_GEOSERVER_SOURCE_IDS.map(async (sourceId) => ({
sourceId,
count: await fetchGeoServerLayerFeatureCount(sourceId, signal)
count: await fetchGeoServerLayerFeatureCount(sourceId, signal, workspace)
}))
);
const availableOptionalSourceIds: DataDependentGeoServerSourceId[] = [];
@@ -63,13 +63,13 @@ export function escapeCqlLiteral(value: string) {
return `'${value.replaceAll("'", "''")}'`;
}
export function createMapFeatureWfsUrl(query: MapFeatureQuery) {
export function createMapFeatureWfsUrl(query: MapFeatureQuery, workspace = GEOSERVER_WORKSPACE) {
const idField = MAP_FEATURE_ID_FIELDS[query.sourceId];
const params = new URLSearchParams({
service: "WFS",
version: "2.0.0",
request: "GetFeature",
typeNames: `${GEOSERVER_WORKSPACE}:${SOURCE_LAYERS[query.sourceId]}`,
typeNames: `${workspace}:${SOURCE_LAYERS[query.sourceId]}`,
outputFormat: "application/json",
srsName: "EPSG:4326",
count: String(query.featureIds ? MAX_MAP_FEATURE_IDS : MAX_PIPE_FEATURES)
@@ -79,7 +79,7 @@ export function createMapFeatureWfsUrl(query: MapFeatureQuery) {
params.set("cql_filter", `"${idField}" IN (${query.featureIds.map(escapeCqlLiteral).join(",")})`);
}
return new URL(`${MAP_URL}/${GEOSERVER_WORKSPACE}/ows?${params.toString()}`);
return new URL(`${MAP_URL}/${workspace}/ows?${params.toString()}`);
}
export function normalizeMapFeatureCollection(value: unknown, maxFeatures: number): FeatureCollection | null {
+13
View File
@@ -131,3 +131,16 @@ function createImageMap(loadImage: (path: string) => Promise<{ data: { width: nu
addImage: ReturnType<typeof vi.fn>;
};
}
it("does not access a disposed map after SCADA image loading completes", async () => {
const controller = new AbortController();
let resolve!: (value: { data: { width: number; height: number } }) => void;
const map = createImageMap(() => new Promise((done) => { resolve = done; }));
const pending = registerScadaImages(map, controller.signal);
controller.abort();
resolve({ data: { width: 64, height: 64 } });
await expect(pending).resolves.toMatchObject({ status: "cancelled" });
expect(map.addImage).not.toHaveBeenCalled();
expect(map.loadImage).toHaveBeenCalledTimes(1);
});

Some files were not shown because too many files have changed in this diff Show More