Compare commits

..
Author SHA1 Message Date
weichenandCursor 1edd872c55 Prefer progress cards over duplicate CurrentTaskCard
Why: When a slow-lane progress card is active, hide the plan/todos
CurrentTaskCard so the work column has one authoritative task object.
Evidence: npx vitest run (workbench-progress + full suite)
Impact: Workbench work tab; tidyCards skips done+danger failures.
Refs: fast-slow-channel-display-u1-plan W4

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-10-12 07:45:08 +00:00
8 changed files with 61 additions and 109 deletions
+4 -6
View File
@@ -4,7 +4,7 @@ import { auth } from './auth'
import type {
Project, Conversation, Message, Run, Artifact, HITLCard, HITLResponse,
AgentProfile, SettingDesc, StreamEvent, StreamEventType, PlanSnapshot, TodoList, UploadInfo, PromptModule,
ActivityCard, SurfaceMeta, SurfaceSnapshot,
ActivityCard,
} from './contracts'
const BASE = ''
@@ -35,13 +35,11 @@ export const api = {
setPermissionMode: (id: string, permissionMode: string) => auth.fetch(`${BASE}/api/conversations/${id}`, { method: 'PATCH', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ permissionMode }) }).then(r => { if (!r.ok) throw new Error(`${r.status}: ${r.statusText}`) }),
checkpoints: (id: string, messageId: string) => auth.fetch(`${BASE}/api/conversations/${id}/checkpoints?messageId=${encodeURIComponent(messageId)}`).then(r => json<{ restored?: string[]; skipped?: string[] }>(r)),
rewindFiles: (id: string, messageId: string) => auth.fetch(`${BASE}/api/conversations/${id}/rewind`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ messageId }) }).then(r => json<{ restored?: string[]; skipped?: string[] }>(r)),
/** 会话内页面目录:扁平 SurfaceMeta(无 identity/spec),不可直接写入 surfaces 投影。 */
surfaceList: (convId: string) => auth.fetch(`${BASE}/api/conversations/${convId}/surfaces`).then(r => json<SurfaceMeta[]>(r)),
surfaceList: (convId: string) => auth.fetch(`${BASE}/api/conversations/${convId}/surfaces`).then(r => json<any[]>(r)),
submitSurfaceAction: (id: string, body: { actionId: string; revision: number; requestId: string; data: Record<string, unknown> }) =>
auth.fetch(`${BASE}/api/surfaces/${id}/actions`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) }).then(r => json<any>(r)),
projectSurfaces: (projectId: string) => auth.fetch(`${BASE}/api/projects/${projectId}/surfaces`).then(r => json<SurfaceMeta[]>(r)),
/** 单页权威快照(含 identity + spec),供列表水合与预览渲染。 */
surfaceGet: (id: string) => auth.fetch(`${BASE}/api/surfaces/${id}`).then(r => json<SurfaceSnapshot>(r)),
projectSurfaces: (projectId: string) => auth.fetch(`${BASE}/api/projects/${projectId}/surfaces`).then(r => json<any[]>(r)),
surfaceGet: (id: string) => auth.fetch(`${BASE}/api/surfaces/${id}`).then(r => json<any>(r)),
me: () => auth.fetch(`${BASE}/api/me`).then(r => json<{ owner: string; name: string; auth: boolean; authVia?: string; isAdmin?: boolean; mustChangePassword?: boolean }>(r)),
// ---- 认证与会话(管理员发放制,R2)----
login: (owner: string, password: string) => auth.fetch(`${BASE}/api/auth/login`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ owner, password }) }).then(async r => {
+5 -9
View File
@@ -7,7 +7,6 @@ import { Collapsible, Icon } from '@ui'
import { artifactIcon, humanSize } from '../messageparts'
import type { Artifact } from '../contracts'
import { groupArtifactsByName } from '../artifactGrouping'
import { surfaceKey } from '../surfaceKey'
export function ArtifactsPanel() {
const artifacts = useStore(s => s.artifacts)
@@ -43,19 +42,16 @@ export function ArtifactsPanel() {
{surfaces.length > 0 && (
<div className="ap-surfaces" data-ap-surfaces>
<div className="ap-section-title">生成页面</div>
{surfaces.filter(sv => surfaceKey(sv) != null).map(sv => {
const id = surfaceKey(sv)!
return (
<div key={id} className="artifact-row" data-surface-row={id}
onClick={() => store.openSurface(id)} title={`打开页面 ${sv.spec?.title ?? ''}`}>
{surfaces.map(sv => (
<div key={String(sv.identity.surfaceId)} className="artifact-row" data-surface-row={String(sv.identity.surfaceId)}
onClick={() => store.openSurface(String(sv.identity.surfaceId))} title={`打开页面 ${sv.spec?.title ?? ''}`}>
<span className="ar-icon"><Icon name="grid" size={15} /></span>
<span className="ar-main">
<span className="name">{sv.spec?.title || '(未命名页面)'}</span>
<span className="meta">页面 · 修订 {sv.revision} · {sv.identity?.pluginId}</span>
<span className="meta">页面 · 修订 {sv.revision} · {sv.identity.pluginId}</span>
</span>
</div>
)
})}
))}
</div>
)}
{artifacts.length === 0
+2 -6
View File
@@ -7,7 +7,6 @@ import type { Artifact } from '../contracts'
import { humanSize } from '../messageparts'
import { previewTabsKey } from '../previewtabs'
import { store, useStore } from '../store'
import { surfaceKey } from '../surfaceKey'
export function PreviewPane() {
// 键口径与 requestPreview 一致(previewTabsKey):空态预览也渲染。
@@ -18,10 +17,7 @@ export function PreviewPane() {
const active = tabs.find(t => t.id === activeId) ?? tabs[0]
const surfaces = useStore(s => s.surfaces)
const surfaceSnap = active?.id.startsWith('surface:')
? surfaces.find(x => {
const id = surfaceKey(x)
return id != null && 'surface:' + id === active.id
})
? surfaces.find(x => 'surface:' + String(x.identity.surfaceId) === active.id)
: undefined
const art = active ? artifacts.find(a => a.id === active.id) : undefined
const textKind = !!art && isTextKind(art)
@@ -60,7 +56,7 @@ export function PreviewPane() {
</div>
<div className="preview-pane-body">
{surfaceSnap
? <SurfaceView snapshot={surfaceSnap} onAction={id => store.handleSurfaceAction(surfaceKey(surfaceSnap) ?? '', id, {})} docBridge={{ onOpenDoc: docId => {
? <SurfaceView snapshot={surfaceSnap} onAction={id => store.handleSurfaceAction(String(surfaceSnap?.identity.surfaceId), id, {})} docBridge={{ onOpenDoc: docId => {
const art = artifacts.find(a => a.id === docId)
if (art) store.requestPreview(art)
} }} />
+11 -8
View File
@@ -6,7 +6,6 @@ import type { Run } from '../contracts'
import { InboxList, pendingCount, type ActivityCard, type DocBridge, type InboxFilter } from '@ui'
import { Icon, SurfaceView } from '@ui'
import { previewTabsKey } from '../previewtabs'
import { surfaceKey } from '../surfaceKey'
import { ArtifactsPanel } from './ArtifactsPanel'
import { PreviewPane } from './PreviewPane'
@@ -92,6 +91,11 @@ function FilesTab() {
return <div className="tab-body"><ArtifactsPanel /></div>
}
/** U1:同会话存在后台 progress 卡(进行中/待确认)时,progress 为权威对象,隐藏 CurrentTaskCard 避免双标题。 */
export function hasActiveProgressCard(cards: ActivityCard[]): boolean {
return cards.some(c => c.kind === 'progress' && (c.status === 'active' || c.status === 'action_required'))
}
function WorkTab({ plan, todos, filter, inboxScope, projectCards, cards }: {
plan: Parameters<typeof CurrentTaskCard>[0]['plan']
todos: Parameters<typeof CurrentTaskCard>[0]['todos']
@@ -100,10 +104,11 @@ function WorkTab({ plan, todos, filter, inboxScope, projectCards, cards }: {
projectCards: ActivityCard[]
cards: ActivityCard[]
}) {
const showCurrentTask = !hasActiveProgressCard(cards)
return (
<>
<div className="tab-body" data-scroll-sync="inbox">
<CurrentTaskCard plan={plan} todos={todos} />
{showCurrentTask ? <CurrentTaskCard plan={plan} todos={todos} /> : null}
<div className="inbox-scope" role="tablist" aria-label="收件箱范围与筛选">
<button className={inboxScope === 'conv' ? 'active' : ''} onClick={() => store.setInboxScope('conv')}>本会话</button>
<button className={inboxScope === 'project' ? 'active' : ''} onClick={() => store.setInboxScope('project')}>
@@ -181,11 +186,9 @@ export function AgentRow({ run, depth }: { run: Run; depth: number }) {
function WorkspaceSurfaces() {
const surfaces = useStore(s => s.surfaces)
const pin = useStore(s => s.ui.workspaceSurfacePin)
const usable = surfaces.filter(x => surfaceKey(x) != null)
if (usable.length === 0) return null
const shown = pin ? usable.find(x => surfaceKey(x) === pin) : usable[usable.length - 1]
if (surfaces.length === 0) return null
const shown = pin ? surfaces.find(x => String(x.identity.surfaceId) === pin) : surfaces[surfaces.length - 1]
if (!shown) return null
const shownId = surfaceKey(shown)!
return (
<div className="workspace-surfaces" data-workspace-surfaces>
<div className="ws-head">
@@ -193,10 +196,10 @@ function WorkspaceSurfaces() {
<span className="ws-meta">{shown.spec?.title || '(未命名)'} · 修订 {shown.revision}</span>
<span style={{ flex: 1 }} />
<button className="icon-btn" title={pin ? '取消固定(跟随最新)' : '固定此页(新页面不抢占)'}
onClick={() => store.setUI({ workspaceSurfacePin: pin ? null : shownId })}>
onClick={() => store.setUI({ workspaceSurfacePin: pin ? null : String(shown.identity.surfaceId) })}>
{pin ? '📍' : '📌'}
</button>
<button className="icon-btn" title="在文件预览中打开" onClick={() => store.openSurface(shownId)}>
<button className="icon-btn" title="在文件预览中打开" onClick={() => store.openSurface(String(shown.identity.surfaceId))}>
↗
</button>
</div>
+13 -21
View File
@@ -8,7 +8,6 @@ import { deliveryRequestId, enqueueMessage, enqueueMessageFront, newQueuedMessag
import { canFlushOutbox, deriveShellPhase } from './runstate'
import { flashElement } from './scrollsync'
import { isThemeChoice, resolveTheme, type ThemeChoice } from './theme'
import { mergeSurfacesByRevision, surfaceKey } from './surfaceKey'
import { rdmAuditReady } from './workspaces'
type FontSizeChoice = 13 | 14 | 16 | 18
@@ -398,31 +397,23 @@ export const store = {
})
}
// U4/R5:已保存页面从权威快照重载(刷新/断线恢复;事件流只做增量投影)。
// surfaceList 返回扁平 SurfaceMeta,不可写入 surfaces;必须经 surfaceGet 水合为 Snapshot。
api.projectSurfaces(state.currentProjectId ?? '').then(list => { if (state.currentConvId === convId) set({ projectSurfaces: list ?? [] }) }).catch(() => {})
api.surfaceList(convId).then(async list => {
api.surfaceList(convId).then(list => {
if (state.currentConvId !== convId) return
const metas = list ?? []
set({ surfaces: list ?? [] })
// 刷新/重进恢复:有页面且尚无页面标签时补开最新一张的标签(不强切
// 右栏——只在实时事件到达时切换,避免每次进会话劫持视图)。标签只用 Meta。
// 右栏——只在实时事件到达时切换,避免每次进会话劫持视图)。
const conv = previewTabsKey(state.currentConvId)
const tabs = state.previewTabs[conv] ?? []
const hasSurfaceTab = tabs.some(t => t.id.startsWith('surface:'))
if (!hasSurfaceTab && metas.length > 0) {
const latest = metas[0]
if (!hasSurfaceTab && (list?.length ?? 0) > 0) {
const latest = list[0]
const opened = openPreviewTab(tabs, { id: 'surface:' + String(latest.surfaceId), name: latest.title || '页面' })
set({
previewTabs: { ...state.previewTabs, [conv]: opened.tabs },
previewActive: { ...state.previewActive, [conv]: opened.activeId },
})
}
const fetched = await Promise.all(metas.map(m =>
api.surfaceGet(String(m.surfaceId)).catch(() => null),
))
if (state.currentConvId !== convId) return
const hydrated = fetched.filter((s): s is SurfaceSnapshot => surfaceKey(s) != null)
// 慢水合不得覆盖并发 surface.updated 已写入的较新 revision。
set({ surfaces: mergeSurfacesByRevision(state.surfaces, hydrated) })
}).catch(() => {})
const resumeSeq = await store.reconcile()
store.connectLive(resumeSeq ?? state.lastSeq)
@@ -549,10 +540,10 @@ export const store = {
// KTD8:单一状态所有者——服务端快照为权威,本地按 revision 守卫:
// 旧修订/重复事件不覆盖新修订;切会话由 selectConversation 清空。
const p = e.payload as SurfaceSnapshot
const id = surfaceKey(p)
if (!id) break
const surfaces = state.surfaces.filter(x => surfaceKey(x) !== id)
const existing = state.surfaces.find(x => surfaceKey(x) === id)
if (!p?.identity?.surfaceId) break
const id = String(p.identity.surfaceId)
const surfaces = state.surfaces.filter(x => String(x.identity.surfaceId) !== id)
const existing = state.surfaces.find(x => String(x.identity.surfaceId) === id)
if (!existing || p.revision > existing.revision) {
surfaces.push(p)
set({ surfaces })
@@ -902,7 +893,8 @@ export const store = {
},
async tidyCards() {
const done = state.cards.filter(c => c.status === 'done')
// U1:不收纳失败语义卡(failed,或旧 done+danger),避免把失败当完成清掉。
const done = state.cards.filter(c => c.status === 'done' && c.tone !== 'danger')
for (const c of done) {
try { const out = await api.cardDismiss(c.id); store.upsertCard(out.card) } catch { /* 单卡失败不阻断 */ }
}
@@ -943,7 +935,7 @@ export const store = {
},
openSurface(surfaceId: string) {
// generative-ui:页面进预览第三栏(标签 id 带 surface: 前缀区分工件)。
const snap = state.surfaces.find(x => surfaceKey(x) === surfaceId)
const snap = state.surfaces.find(x => String(x.identity.surfaceId) === surfaceId)
const conv = previewTabsKey(state.currentConvId)
const opened = openPreviewTab(state.previewTabs[conv] ?? [], { id: 'surface:' + surfaceId, name: snap?.spec?.title || '页面' })
set({
@@ -957,7 +949,7 @@ export const store = {
async handleSurfaceAction(surfaceId: string, actionId: string, data: Record<string, unknown>) {
const inflight = surfaceActionsInflight[surfaceId + ':' + actionId]
if (inflight) return
const snap = state.surfaces.find(x => surfaceKey(x) === surfaceId)
const snap = state.surfaces.find(x => String(x.identity.surfaceId) === surfaceId)
if (!snap) { store.toast('页面快照不可用,无法提交'); return }
const requestId = (crypto.randomUUID ? crypto.randomUUID() : 'req-' + Date.now() + '-' + Math.random().toString(36).slice(2))
surfaceActionsInflight[surfaceId + ':' + actionId] = true
-19
View File
@@ -1,19 +0,0 @@
// surface 投影可能短暂混入无 identity 的条目;读 id 一律经此助手,避免渲染崩溃。
import type { SurfaceSnapshot } from './contracts'
export function surfaceKey(x: { identity?: { surfaceId?: unknown } } | null | undefined): string | null {
const id = x?.identity?.surfaceId
return id == null || id === '' ? null : String(id)
}
/** 按 surfaceId 合并;同 id 取 revision 较大者。跳过无 identity 的脏项。 */
export function mergeSurfacesByRevision(a: SurfaceSnapshot[], b: SurfaceSnapshot[]): SurfaceSnapshot[] {
const byId = new Map<string, SurfaceSnapshot>()
for (const s of [...a, ...b]) {
const id = surfaceKey(s)
if (!id) continue
const existing = byId.get(id)
if (!existing || (s.revision ?? 0) >= (existing.revision ?? 0)) byId.set(id, s)
}
return [...byId.values()]
}
-40
View File
@@ -1,40 +0,0 @@
import { describe, expect, it } from 'vitest'
import type { SurfaceSnapshot } from '../src/contracts'
import { mergeSurfacesByRevision, surfaceKey } from '../src/surfaceKey'
function snap(id: string, revision: number): SurfaceSnapshot {
return {
identity: {
surfaceId: id,
owner: 'o',
pluginId: 'p',
},
compat: { schemaVersion: 1, catalogVersion: '1' },
revision,
activationEpoch: 0,
spec: { title: id, nodes: [] },
}
}
describe('surfaceKey', () => {
it('reads nested identity and skips missing', () => {
expect(surfaceKey(snap('s1', 1))).toBe('s1')
expect(surfaceKey(undefined)).toBeNull()
expect(surfaceKey({} as SurfaceSnapshot)).toBeNull()
expect(surfaceKey({ identity: {} } as SurfaceSnapshot)).toBeNull()
})
})
describe('mergeSurfacesByRevision', () => {
it('keeps higher revision and drops dirty entries', () => {
const dirty = { revision: 99 } as SurfaceSnapshot
const merged = mergeSurfacesByRevision(
[snap('a', 1), dirty],
[snap('a', 3), snap('b', 1)],
)
expect(merged.map(s => [surfaceKey(s), s.revision])).toEqual([
['a', 3],
['b', 1],
])
})
})
+26
View File
@@ -0,0 +1,26 @@
import { describe, expect, it } from 'vitest'
import { hasActiveProgressCard } from '../src/components/Workbench'
import type { ActivityCard } from '@ui'
function card(over: Partial<ActivityCard>): ActivityCard {
return {
id: 'card_1', projectId: 'prj_1', conversationId: 'cnv_1',
kind: 'progress', title: '材料整理', status: 'active', tone: 'info',
createdAt: '2026-10-12T10:00:00Z', updatedAt: '2026-10-12T10:00:00Z',
...over,
}
}
describe('hasActiveProgressCard', () => {
it('active/action_required progress 卡视为占用当前任务位', () => {
expect(hasActiveProgressCard([card({ status: 'active' })])).toBe(true)
expect(hasActiveProgressCard([card({ status: 'action_required' })])).toBe(true)
})
it('完成/失败 progress 或非 progress 不隐藏 CurrentTaskCard', () => {
expect(hasActiveProgressCard([card({ status: 'done', tone: 'ok' })])).toBe(false)
expect(hasActiveProgressCard([card({ status: 'failed', tone: 'danger' })])).toBe(false)
expect(hasActiveProgressCard([card({ kind: 'confirm', status: 'action_required' })])).toBe(false)
expect(hasActiveProgressCard([])).toBe(false)
})
})