Files
Agent-System-Frontend/src/store.ts
weichen 1d6b8a64a6 Add login page, forced password change, and admin user management
Why: accounts are admin-issued (user decision 2026-09-30, no self
registration); initial and admin-reset passwords must force a change on
first login.

Evidence:
- LoginPage: password (primary) + API key tabs; ChangePasswordGate
  blocks the app until the forced change completes (mismatch/length
  validation inline); App auth state machine checking -> login ->
  mustchange -> ok, session cookie flows through fetch automatically.
- Account menu gains change-password and admin-only user management;
  AdminUsersModal: create account (random initial password generator,
  admin checkbox), reset password, status table (ADMIN/USER, pending
  change chips).
- Fixed a real bug found in the headless walk: menu toggles passed
  e.currentTarget into the setState updater where React nulls it by
  render time, so anchor was null and the menu never rendered; capture
  the element before the updater.
- Headless journey on the real binary with --auth on: admin bootstrap
  via CLI -> first-login forced change -> app; admin creates bob (bob
  sees no user management); alice reset via CLI -> forced change on
  next login; API-key tab login; logout; zero console errors. npm run
  build + vitest green; make test full suite exit 0.

Impact: replaces the old API-key-only LoginGate; embedded no-auth mode
unchanged (no login page shown).

Refs: proposal 2026-09-30-ui-redesign-and-auth.md section 5 (R2,
admin-issued variant)
2026-09-30 11:16:47 +00:00

517 lines
18 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// 应用状态:服务端权威(事件 + Query 对账),前端 store 是投影。
// useSyncExternalStore 驱动;live 流式部件为会话内临时态,run 终态后由消息树对账收敛。
import { useSyncExternalStore } from 'react'
import { api, connectEvents } from './api'
import type {
Project, Conversation, Message, Run, Artifact, HITLCard, PlanSnapshot, TodoList,
AgentProfile, StreamEvent, PluginPanel, ActivityCard,
} from './contracts'
export interface ContextObs {
items: string[]
truncations?: string[]
estChars: number
}
export interface LiveState {
runId: string
phase: string
thinking: string
text: string
toolCalls: { name: string; status?: string; summary?: string }[]
agentNotes: Record<string, string>
startedAt: number
}
export interface UIState {
leftWidth: number
leftCollapsed: boolean
rightWidth: number
rightCollapsed: boolean
rightTab: string
theme: 'dark' | 'light'
autoCollapseProcess: boolean
settingsOpen: boolean
trackerRunId: string | null
viewingArtifact: Artifact | null
activeWorkspace: string | null
taskOrg: 'project' | 'timeline'
showArchived: boolean
lastProjectId: string | null
adminUsersOpen: boolean
changePwOpen: boolean
}
export interface Me { owner: string; name: string; auth: boolean; isAdmin?: boolean; mustChangePassword?: boolean }
interface AppState {
contextObs: Record<string, ContextObs>
projects: Project[]
currentProjectId: string | null
tasks: Conversation[]
me: Me | null
currentConvId: string | null
messages: Message[]
runs: Run[]
activeHitl: HITLCard[]
lastSeq: number
live: LiveState | null
plan: PlanSnapshot | null
todos: TodoList | null
artifacts: Artifact[]
cards: ActivityCard[]
profiles: AgentProfile[]
pluginPanels: PluginPanel[]
serverWorkspaces: { id: string; title: string; icon?: string; shortcut?: string; body?: any[] }[]
ui: UIState
connected: boolean
error: string | null
toast: string | null
}
const DEFAULT_UI: UIState = {
leftWidth: 260,
leftCollapsed: false,
rightWidth: 340,
rightCollapsed: false,
rightTab: 'inbox',
activeWorkspace: null,
theme: 'dark',
autoCollapseProcess: true,
settingsOpen: false,
trackerRunId: null,
viewingArtifact: null,
taskOrg: 'project',
showArchived: false,
lastProjectId: null,
adminUsersOpen: false,
changePwOpen: false,
}
function loadUI(): UIState {
try {
const raw = localStorage.getItem('as.ui')
if (raw) return { ...DEFAULT_UI, ...JSON.parse(raw) }
} catch { /* ignore */ }
return { ...DEFAULT_UI }
}
let state: AppState = {
contextObs: {},
projects: [], currentProjectId: null, tasks: [], me: null, currentConvId: null,
messages: [], runs: [], activeHitl: [], lastSeq: 0, live: null,
plan: null, todos: null, artifacts: [], cards: [], profiles: [], pluginPanels: [],
serverWorkspaces: [],
ui: loadUI(), connected: false, error: null, toast: null,
}
const listeners = new Set<() => void>()
function set(patch: Partial<AppState>) {
state = { ...state, ...patch }
listeners.forEach(l => l())
}
function setUI(patch: Partial<UIState>) {
const ui = { ...state.ui, ...patch }
state = { ...state, ui }
try { localStorage.setItem('as.ui', JSON.stringify(ui)) } catch { /* ignore */ }
applyTheme(ui.theme)
listeners.forEach(l => l())
}
function applyTheme(theme: string) {
document.documentElement.dataset.theme = theme
}
let sse: { close: () => void } | null = null
export function useStore<T>(selector: (s: AppState) => T): T {
return useSyncExternalStore(
(cb) => { listeners.add(cb); return () => listeners.delete(cb) },
() => selector(state),
)
}
export const store = {
getState: () => state,
async refreshProjects() {
try {
const projects = await api.listProjects()
const current = projects.find(p => p.id === state.currentProjectId) ?? projects.find(p => p.id === state.ui.lastProjectId) ?? projects[0]
set({ projects, currentProjectId: current?.id ?? null, error: null })
if (current) await store.openProject(current.id)
} catch (e) {
set({ error: String(e) })
}
store.refreshTasks()
store.refreshMe()
},
// 跨项目任务列表(方案 A 侧栏数据源):归档视图切换时带 includeArchived 重取。
async refreshTasks(includeArchived = state.ui.showArchived) {
try { set({ tasks: await api.listTasks(includeArchived) }) } catch { /* 列表竞态,静默 */ }
},
async refreshMe() {
try { set({ me: await api.me() }) } catch { /* 身份不可用时侧栏只显示通用入口 */ }
},
async createProject(name: string) {
const p = await api.createProject(name)
await store.refreshProjects()
store.toast(`项目「${p.name}」已创建`)
return p
},
async openProject(projectId: string) {
set({ currentProjectId: projectId })
store.setUI({ lastProjectId: projectId })
await store.refreshArtifacts(projectId)
},
/** 新建任务(=会话):默认当前项目上下文;显式 projectId 用于"新建于指定项目"。 */
async createTask(projectId?: string) {
const pid = projectId ?? state.currentProjectId
if (!pid) { store.toast('请先创建项目'); return }
const c = await api.createConversation(pid)
await store.refreshTasks()
await store.openTask(c.id)
},
/** 兼容旧入口(⌘/命令总线) */
async createConversation(title?: string) {
if (title) store.toast('已在当前项目创建任务')
await store.createTask()
},
/** 打开任务:跨项目点击时切换项目上下文(工件/上传归属正确)。 */
async openTask(convId: string) {
const t = state.tasks.find(x => x.id === convId)
if (t && t.projectId !== state.currentProjectId) await store.openProject(t.projectId)
await store.openConversation(convId)
},
async pinTask(convId: string, pinned: boolean) {
const tasks = state.tasks.map(t => t.id === convId ? { ...t, pinned } : t)
set({ tasks })
try { await api.setConversationFlags(convId, { pinned }) } catch (e) { store.toast(`置顶失败:${e}`); store.refreshTasks() }
},
async archiveTask(convId: string, archived: boolean) {
const tasks = state.tasks.map(t => t.id === convId ? { ...t, archived } : t)
set({ tasks })
try {
await api.setConversationFlags(convId, { archived })
if (state.currentConvId === convId && archived) store.toast('任务已归档')
} catch (e) { store.toast(`归档失败:${e}`) }
store.refreshTasks()
},
async openConversation(convId: string) {
if (sse) { sse.close(); sse = null }
set({ currentConvId: convId, messages: [], runs: [], activeHitl: [], lastSeq: 0, live: null, plan: null, todos: null, cards: [] })
await store.reconcile()
await store.connectLive()
},
// 终态对账:以 Query 的权威消息树/运行树/游标为准收敛。
async reconcile() {
if (!state.currentConvId) return
try {
const d = await api.conversationDetail(state.currentConvId)
const liveRunActive = state.live && !isTerminal(d.runs.find(r => r.id === state.live!.runId)?.status)
set({
messages: d.messages,
runs: d.runs,
activeHitl: d.activeHitl,
lastSeq: Math.max(state.lastSeq, d.lastSeq),
live: liveRunActive ? state.live : null,
connected: true,
})
const [plan, todos] = await Promise.all([api.getPlan(d.conversation.id), api.getTodos(d.conversation.id)])
set({ plan, todos })
store.refreshCards(d.conversation.id)
store.refreshTasks()
} catch (e) {
set({ error: String(e) })
}
},
connectLive() {
if (!state.currentConvId) return
const convId = state.currentConvId
sse = connectEvents(convId, state.lastSeq, {
onOpen: () => set({ connected: true }),
onError: () => set({ connected: false }),
onEvent: e => store.applyEvent(e),
})
},
applyEvent(e: StreamEvent) {
switch (e.type) {
case 'message.delta': {
const p = e.payload as { index: number; text: string }
set({ live: touchLive(e.runId ?? '', l => { l.text += p.text }) })
break
}
case 'thinking.delta': {
const p = e.payload as { index: number; text: string }
set({ live: touchLive(e.runId ?? '', l => { l.thinking += p.text }) })
break
}
case 'tool.call': {
const p = e.payload as { callId: string; name: string }
set({ live: touchLive(e.runId ?? '', l => { l.toolCalls.push({ name: p.name }) }) })
break
}
case 'tool.result': {
const p = e.payload as { callId: string; status: string; summary?: string }
set({ live: touchLive(e.runId ?? '', l => {
for (let i = l.toolCalls.length - 1; i >= 0; i--) {
if (l.toolCalls[i].status === undefined) { l.toolCalls[i] = { ...l.toolCalls[i], status: p.status, summary: p.summary }; break }
}
}) })
break
}
case 'run.phase': {
const p = e.payload as { phase: string }
set({ live: touchLive(e.runId ?? '', l => { l.phase = p.phase }) })
break
}
case 'hitl.request': {
store.reconcile()
break
}
case 'hitl.resolved': {
set({ activeHitl: state.activeHitl.filter(c => c.id !== (e.payload as { cardId: string }).cardId) })
break
}
case 'agent.spawn': {
const p = e.payload as { agentRun: string; name: string; task: string }
set({ live: touchLive(e.runId ?? '', l => { l.agentNotes = { ...l.agentNotes, [p.agentRun]: `已派生 ${p.name}:${p.task}` } }) })
break
}
case 'agent.progress': {
const p = e.payload as { agentRun: string; note?: string }
set({ live: touchLive(e.runId ?? '', l => { if (p.note) l.agentNotes = { ...l.agentNotes, [p.agentRun]: p.note! } }) })
break
}
case 'agent.result': {
const p = e.payload as { agentRun: string; summary?: string }
set({ live: touchLive(e.runId ?? '', l => { l.agentNotes = { ...l.agentNotes, [p.agentRun]: p.summary ?? '完成' } }) })
store.reconcile()
break
}
case 'plan.update': {
const p = e.payload as { plan: PlanSnapshot }
set({ plan: p.plan })
break
}
case 'todo.update': {
const p = e.payload as { list: TodoList }
set({ todos: p.list })
break
}
case 'card.created':
case 'card.updated': {
const p = e.payload as { card: ActivityCard }
if (p?.card) store.upsertCard(p.card)
break
}
case 'card.status': {
const p = e.payload as { cardId: string; status: ActivityCard['status']; tone?: string }
const cards = state.cards.map(c => c.id === p.cardId ? { ...c, status: p.status, tone: p.tone ?? c.tone } : c)
set({ cards })
break
}
case 'card.resolved': {
const p = e.payload as { cardId: string }
const cards = state.cards.map(c => c.id === p.cardId ? { ...c, status: 'resolved' as const } : c)
set({ cards })
break
}
case 'artifact.created': {
if (state.currentProjectId) store.refreshArtifacts(state.currentProjectId)
break
}
case 'run.completed': {
const p = e.payload as { usage?: unknown; context?: ContextObs }
if (p?.context && e.runId) {
set({ contextObs: { ...state.contextObs, [e.runId]: p.context } })
}
setTimeout(() => store.reconcile(), 250)
break
}
case 'run.failed':
case 'error': {
// 终态:短暂延迟后对账(等待消息树落库),折叠过程输出。
setTimeout(() => store.reconcile(), 250)
break
}
}
},
async sendMessage(text: string, attachmentIds: string[]) {
if (!state.currentConvId) return
try {
const out = await api.sendMessage(state.currentConvId, text, attachmentIds)
if (out.command) {
store.toast(out.reply ?? `命令 ${out.command} 已执行`)
if (out.conversation) await store.openConversation(out.conversation.id)
else await store.reconcile()
return
}
if (out.run) {
// 竞态保护:POST 返回前 SSE 事件可能已先行到达并累积(同 run),
// 此时保留已累积的 live,只补挂用户消息;否则初始化空 live。
if (!state.live || state.live.runId !== out.run.id) {
set({ live: { runId: out.run.id, phase: 'thinking', thinking: '', text: '', toolCalls: [], agentNotes: {}, startedAt: Date.now() } })
}
set({ messages: [...state.messages, out.message] })
store.connectIfNeeded()
}
} catch (e) {
store.toast(`发送失败:${e}`)
await store.reconcile()
}
},
connectIfNeeded() {
if (!sse && state.currentConvId) store.connectLive()
},
async cancelActive() {
const active = state.runs.find(r => !isTerminal(r.status))
if (!active) return
await api.cancelRun(active.id).catch(() => undefined)
setTimeout(() => store.reconcile(), 200)
},
async resolveHITL(cardId: string, resp: { choiceId?: string; freeText?: string }) {
try {
const out = await api.resolveHITL(cardId, resp)
set({ activeHitl: state.activeHitl.filter(c => c.id !== cardId) })
if (out.pivoted && out.pivotText) {
await store.sendMessage(out.pivotText, [])
}
} catch (e) {
store.toast(`HITL 解析失败:${e}`)
}
},
upsertCard(card: ActivityCard) {
const i = state.cards.findIndex(c => c.id === card.id)
const cards = i >= 0 ? state.cards.map(c => c.id === card.id ? card : c) : [card, ...state.cards]
set({ cards })
},
async refreshCards(convId: string) {
try { set({ cards: await api.listCards(convId) }) } catch { /* 会话竞态,静默 */ }
},
// 卡片动作:确认投影卡(来源 hitl:)路由回 HITL 解析(恢复挂起 run,服务端同步销项);
// 其余卡走卡片动作 API,并把服务端持久化的回执消息追加进本地时间线(id 一致,对账不重复)。
async cardAction(card: ActivityCard, actionId: string, freeText?: string) {
const hitlRef = card.body?.find(n => n.type === 'kv')?.kv?.find(([k]) => k === '来源')?.[1]
if (hitlRef?.startsWith('hitl:')) {
await store.resolveHITL(hitlRef.slice(5), actionId ? { choiceId: actionId } : { freeText })
return
}
try {
const out = await api.cardAction(card.id, actionId, freeText)
store.upsertCard(out.card)
if (out.receipt) set({ messages: [...state.messages, out.receipt as Message] })
} catch (e) {
store.toast(`操作失败:${e}`)
}
},
async cardPin(card: ActivityCard, pinned: boolean) {
try { store.upsertCard((await api.cardPin(card.id, pinned)).card) } catch (e) { store.toast(`置顶失败:${e}`) }
},
async cardDismiss(card: ActivityCard) {
try { store.upsertCard((await api.cardDismiss(card.id)).card) } catch (e) { store.toast(`关闭失败:${e}`) }
},
async refreshArtifacts(projectId: string) {
try {
const artifacts = await api.listArtifacts(projectId)
set({ artifacts })
} catch { /* 项目删除竞态等,静默 */ }
},
async refreshProfiles() {
try { set({ profiles: await api.listProfiles() }) } catch { /* ignore */ }
},
async refreshPlugins() {
try {
const list = await api.listPlugins() as { panels?: PluginPanel[] }[]
const panels = list.flatMap(p => p.panels ?? [])
set({ pluginPanels: panels })
} catch { /* ignore */ }
try {
const ws = await api.listWorkspaces()
set({ serverWorkspaces: ws ?? [] })
} catch { /* ignore */ }
},
async uploadAttachment(file: File): Promise<string | null> {
if (!state.currentProjectId) return null
try {
const up = await api.upload(state.currentProjectId, file)
store.toast(`已上传 ${up.filename}${up.parsed ? `(解析:${up.parsed.meta.parser})` : ''}`)
await store.refreshArtifacts(state.currentProjectId)
return up.artifactId
} catch (e) {
store.toast(`上传失败:${e}`)
return null
}
},
setUI,
toggleLeft() { setUI({ leftCollapsed: !state.ui.leftCollapsed }) },
toggleRight() { setUI({ rightCollapsed: !state.ui.rightCollapsed }) },
openWorkspace(id: string) { setUI({ activeWorkspace: id }) },
/** 收纳策略(T5):一键收纳已完成卡(done→dismissed;resolved 盖章留痕不动)。 */
async tidyCards() {
const done = state.cards.filter(c => c.status === 'done')
for (const c of done) {
try { const out = await api.cardDismiss(c.id); store.upsertCard(out.card) } catch { /* 单卡失败不阻断 */ }
}
if (done.length > 0) store.toast(`已收纳 ${done.length} 张完成卡`)
},
closeWorkspace() { setUI({ activeWorkspace: null }) },
openInbox(cardId?: string) {
setUI({ rightCollapsed: false, rightTab: 'inbox' })
if (cardId) setTimeout(() => {
document.querySelector(`[data-card-id="${cardId}"]`)?.scrollIntoView({ behavior: 'smooth', block: 'center' })
}, 60)
},
openTracker(runId: string) { setUI({ trackerRunId: runId }) },
viewArtifact(a: Artifact | null) { setUI({ viewingArtifact: a }) },
openSettings(open: boolean) { setUI({ settingsOpen: open }) },
toast(msg: string) {
set({ toast: msg })
setTimeout(() => { if (state.toast === msg) set({ toast: null }) }, 2600)
},
}
function touchLive(_runId: string, mutate: (l: LiveState) => void): LiveState | null {
const base = state.live ?? { runId: _runId, phase: 'thinking', thinking: '', text: '', toolCalls: [], agentNotes: {}, startedAt: Date.now() }
const next: LiveState = { ...base, toolCalls: [...base.toolCalls], agentNotes: { ...base.agentNotes } }
mutate(next)
return next
}
export function isTerminal(status?: string): boolean {
return status === 'completed' || status === 'failed' || status === 'cancelled' || status === 'interrupted'
}
export function activeRun(runs: Run[]): Run | undefined {
return runs.find(r => !isTerminal(r.status))
}