fix(client): restore host-confirmed workspace order

This commit is contained in:
_Kerman
2026-08-11 17:51:31 +08:00
parent 7222a99e33
commit 6898b06160
8 changed files with 60 additions and 21 deletions
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write .agents/notes/implemented/feature/2026-08-11-workspace-sidebar-order-and-folding.md
2026-08-11-workspace-sidebar-order-and-folding.md: 223f164b12415e98e5c21ce472e8094dfc13747f
2026-08-11-workspace-sidebar-order-and-folding.zh.md: dc3ca4fb3a75f2dca289394df088d0efee08f4f2
2026-08-11-workspace-sidebar-order-and-folding.md: dd3c00f07f2e6c67450aecdf74d6e501cbc56402
2026-08-11-workspace-sidebar-order-and-folding.zh.md: 14b353b50522547658e9a0cd4851cbfd4bdb7d1d
@@ -16,7 +16,7 @@ Workspace groups themselves had no user-controlled durable order. Browser-native
The Workspace registry owns a durable `workspaceIds` order and exposes `insertBefore(id, beforeId?)` with DOM `insertBefore` semantics. The Host RPC `workspace.insertBefore` returns the complete committed order, and a pure order mutation emits `host/workspace-order-changed` with the same complete order. Unknown source or anchor ids reject as `workspace-not-found`; self-anchored and already-positioned moves do not write.
The client installs a Workspace drag optimistically. Request and frame generations ensure that only the latest unary echo can replace local order and that a newer Host frame outranks an older response; a latest rejected request restores the preceding order. Every successful list baseline restores Host order so reconnects adopt durable changes made elsewhere.
The client installs a Workspace drag optimistically. Request and frame generations ensure that only the latest unary echo can replace local order and that a newer Host frame outranks an older response; a latest rejected request restores the last complete order accepted from a Host baseline, frame, or current unary echo. Every successful list baseline restores Host order so reconnects adopt durable changes made elsewhere.
### Session folding and view order
@@ -28,7 +28,7 @@ The combined view menu offers **Manual** and **Last updated** over one browser-l
Workspace hit testing uses the complete rendered group section, including visible Session rows. One insertion boundary is shared by the preceding group's lower half and the following group's upper half, and the indicator is an absolutely positioned line that does not affect layout. A tree-body overlay draws the first boundary at the same negative offset outside the scrolling clip, so its hollow leading circle remains visible without moving the list. During a Session drag, document-level `dragover` and `drop` handlers accept the native operation; if release occurs outside the Workspace list, `dragend` commits the last valid marker.
Search is a header action while collapsed and expands across the title and trailing actions. An outside click collapses an empty search but retains a non-empty query. Compact Workspace and Session rows, a 24px bottom fade, and the absence of per-Workspace Session counts preserve vertical space without removing navigation affordances.
Search is a header action while collapsed and expands across the title and trailing actions. An outside click collapses a query that is empty after trimming but retains a non-empty query. Compact Workspace and Session rows, a 24px bottom fade, and the absence of per-Workspace Session counts preserve vertical space without removing navigation affordances.
## Alternatives considered
@@ -53,4 +53,4 @@ Search is a header action while collapsed and expands across the title and trail
## Testing
Domain and Host tests cover durable Workspace moves, no-op and invalid anchors, restart recovery, full-order RPC responses, and order frames. Runtime tests cover optimistic order, frame/response precedence, rejection rollback, reconnect baselines, and New Session target priority. UI tests cover five-row folding, transient expansion reset, order-preserving mode switches, one-time recent-update promotion, selected view indicators, expanded-section Workspace hit testing, an unclipped first insertion boundary, outside-list Session drops, search collapse rules, and compact CSS dimensions.
Domain and Host tests cover durable Workspace moves, no-op and invalid anchors, restart recovery, full-order RPC responses, and order frames. Runtime tests cover optimistic order, frame/response precedence, overlapping rejection rollback to Host-confirmed order, reconnect baselines, and New Session target priority. UI tests cover five-row folding, transient expansion reset, order-preserving mode switches, one-time recent-update promotion, selected view indicators, expanded-section Workspace hit testing, an unclipped first insertion boundary, outside-list Session drops, search collapse rules, and compact CSS dimensions.
@@ -16,7 +16,7 @@ Workspace 分组本身没有用户可控的持久顺序。浏览器原生拖拽
Workspace 注册表持有持久 `workspaceIds` 顺序,并提供采用 DOM `insertBefore` 语义的 `insertBefore(id, beforeId?)`。Host RPC `workspace.insertBefore` 返回完整的已提交顺序;单纯顺序变更通过 `host/workspace-order-changed` 推送同一份完整顺序。未知来源或锚点 id 以 `workspace-not-found` 拒绝;以自身为锚点或移动到当前位置不会写入。
客户端对 Workspace 拖拽进行乐观安装。请求代次与帧代次保证只有最新一元回声可以替换本地顺序,且更新的 Host 帧优先于旧响应;最新请求被拒时恢复此前顺序。每次成功的列表基线都会恢复 Host 顺序,因此重连会接纳其他位置提交的持久变更。
客户端对 Workspace 拖拽进行乐观安装。请求代次与帧代次保证只有最新一元回声可以替换本地顺序,且更新的 Host 帧优先于旧响应;最新请求被拒时恢复最近一份由 Host 基线、帧或当前一元回声确认的完整顺序。每次成功的列表基线都会恢复 Host 顺序,因此重连会接纳其他位置提交的持久变更。
### Session 折叠与视图顺序
@@ -28,7 +28,7 @@ Workspace 注册表持有持久 `workspaceIds` 顺序,并提供采用 DOM `ins
Workspace 命中测试使用完整渲染分组区段,包括可见 Session 行。前一分组的下半部与后一分组的上半部共享同一条插入边界,指示器是一条不影响布局的绝对定位横线。树主体覆盖层会在滚动裁切区外以相同的负偏移绘制第一条边界,因此左侧空心圆保持可见,列表位置也不会改变。Session 拖拽期间,文档级 `dragover``drop` 处理器会接受原生操作;若在 Workspace 列表外松手,`dragend` 会提交最后一个有效标记。
搜索在折叠时是区头操作,展开后占据标题与尾部操作的空间。点击外部会收起搜索,但保留非空查询。紧凑的 Workspace 与 Session 行、24px 底部渐隐以及取消每个 Workspace 的 Session 数量共同节省纵向空间,同时保留导航入口。
搜索在折叠时是区头操作,展开后占据标题与尾部操作的空间。查询经清除首尾空白后为空时,点击外部会收起搜索;非空查询则会保留。紧凑的 Workspace 与 Session 行、24px 底部渐隐以及取消每个 Workspace 的 Session 数量共同节省纵向空间,同时保留导航入口。
## 考虑过的替代方案
@@ -53,4 +53,4 @@ Workspace 命中测试使用完整渲染分组区段,包括可见 Session 行
## 测试
领域与 Host 测试覆盖持久 Workspace 移动、无操作与无效锚点、重启恢复、完整顺序 RPC 响应和顺序帧。运行时测试覆盖乐观顺序、帧/响应优先级、拒绝回滚、重连基线以及 New Session 目标优先级。UI 测试覆盖五行折叠、临时展开重置、保持顺序的模式切换、一次性最近更新置顶、当前视图标记、展开区段的 Workspace 命中、未裁切的第一条插入边界、列表外 Session 松手、搜索收起规则和紧凑 CSS 尺寸。
领域与 Host 测试覆盖持久 Workspace 移动、无操作与无效锚点、重启恢复、完整顺序 RPC 响应和顺序帧。运行时测试覆盖乐观顺序、帧/响应优先级、重叠拒绝后恢复 Host 已确认顺序、重连基线以及 New Session 目标优先级。UI 测试覆盖五行折叠、临时展开重置、保持顺序的模式切换、一次性最近更新置顶、当前视图标记、展开区段的 Workspace 命中、未裁切的第一条插入边界、列表外 Session 松手、搜索收起规则和紧凑 CSS 尺寸。
+2 -2
View File
@@ -2,5 +2,5 @@
# side as of the last confirmed-consistent state. Both languages carry equal authority;
# after editing either side, bring the other along and re-record with:
# pnpm run verify-translation-pairing --write packages/client/runtime/README.md
README.md: 5ac081d6f257bc1c3a7d8a2dd75234f72f209da7
README.zh.md: 15a1a4602fbb4ae6bd56d728b17782da8cfa4693
README.md: ef07addd9955ee6158013f3932ea407969ddf314
README.zh.md: 1d154d1470a7864a4bdbb4b36c5143fa23a9dc68
+1 -1
View File
@@ -13,7 +13,7 @@ The callback returns one synchronous disposer or an iterable of disposers. A gen
## Workspace and Session lists
Workspace and Session lists have independent monotone `pending``ready` baseline phases and separate refresh activity/error state. Incremental upsert/removal/order frames and unary mutation echoes arriving during a list request replay over its response. Every successful Workspace baseline re-establishes Host-durable Workspace order so reconnects adopt changes committed while this client was offline. `WorkspacesService.insertBefore` installs an optimistic order immediately; only the latest unary echo may replace it, a newer Host order frame outranks an older echo, and a latest rejected request rolls back. Removed Workspace ids retain process-local tombstones so late changed frames cannot resurrect them. Workspace recency is derived only after both baselines are ready and never changes Workspace list order.
Workspace and Session lists have independent monotone `pending``ready` baseline phases and separate refresh activity/error state. Incremental upsert/removal/order frames and unary mutation echoes arriving during a list request replay over its response. Every successful Workspace baseline re-establishes Host-durable Workspace order so reconnects adopt changes committed while this client was offline. `WorkspacesService.insertBefore` installs an optimistic order immediately; only the latest unary echo may replace it, a newer Host order frame outranks an older echo, and a latest rejected request restores the last Host-confirmed order rather than an earlier uncommitted drag. Removed Workspace ids retain process-local tombstones so late changed frames cannot resurrect them. Workspace recency is derived only after both baselines are ready and never changes Workspace list order.
`SessionSummary.pendingInteraction` classifies the live user action blocking a Session as `approval`, `plan-review`, or `question`. `SessionManager` tracks answerable requested/resolved mux frames by their stable request identities even before a Session object is instantiated; pre-instantiation buffering retains every live request, replaces replay duplicates, and removes resolved requests so the list status always has a matching answerable `PendingWait` when the Session is opened. The first pending question takes presentation priority over concurrent approvals to match composer routing, while only a request that satisfies the plan-review composer's binary rendering constraints keeps the distinct `plan-review` status. The state is connection-generation scoped: disconnect clears it, and mux-open replay restores only requests that remain pending.
+1 -1
View File
@@ -13,7 +13,7 @@
## Workspace 与 Session 列表
Workspace 和 Session 列表各自具有单调的 `pending``ready` 基线阶段,也有各自的刷新活动/错误状态。列表请求期间到达的增量插入或更新/移除/顺序帧与一元变更回显会在其响应之上回放。每次成功的 Workspace 基线都会重新建立 Host 持久 Workspace 顺序,因此重连会接纳该客户端离线期间提交的变更。`WorkspacesService.insertBefore` 会立即安装乐观顺序;只有最新一元回声可以替换它,更新的 Host 顺序帧优先于旧回声,而最新请求被拒时会回滚。已移除的 Workspace id 会保留进程本地删除标记,避免延迟到达的 changed 帧将其复活。Workspace 新近程度只在两条基线都 ready 后派生,且绝不改变 Workspace 列表顺序。
Workspace 和 Session 列表各自具有单调的 `pending``ready` 基线阶段,也有各自的刷新活动/错误状态。列表请求期间到达的增量插入或更新/移除/顺序帧与一元变更回显会在其响应之上回放。每次成功的 Workspace 基线都会重新建立 Host 持久 Workspace 顺序,因此重连会接纳该客户端离线期间提交的变更。`WorkspacesService.insertBefore` 会立即安装乐观顺序;只有最新一元回声可以替换它,更新的 Host 顺序帧优先于旧回声,而最新请求被拒时会恢复最近一次由 Host 确认的顺序,不会恢复更早且尚未提交的拖拽。已移除的 Workspace id 会保留进程本地删除标记,避免延迟到达的 changed 帧将其复活。Workspace 新近程度只在两条基线都 ready 后派生,且绝不改变 Workspace 列表顺序。
`SessionSummary.pendingInteraction` 将阻塞 Session 的实时用户操作分类为 `approval``plan-review``question``SessionManager` 依据稳定的请求标识跟踪可应答请求的 requested/resolved mux 帧,即使 `Session` 对象尚未实例化也不例外;实例化前的缓冲会保留每个仍有效的请求,替换回放产生的重复项,并移除已解决的请求,因此打开 Session 时,列表状态始终有一个对应的可应答 `PendingWait`。审批与问题并发时,第一个 pending 问题具有更高的呈现优先级,以匹配 composer 路由;只有满足 plan-review composer 二元呈现约束的请求才会保留独立的 `plan-review` 状态。该状态的作用域限定在连接代次内:断连时清除,mux 打开时的回放只恢复仍处于 pending 的请求。
@@ -55,6 +55,8 @@ export class WorkspaceManager {
private orderRequestGeneration = 0
/** Increments on order frames so a later remote commit outranks an older unary echo. */
private orderFrameGeneration = 0
/** Last complete order accepted from a Host baseline, frame, or current unary echo. */
private committedOrder: WorkspaceId[] = []
/**
* Ids this process has seen removed, kept for the connection's lifetime so
* a late changed frame or a stale baseline row cannot resurrect a deleted
@@ -171,8 +173,8 @@ export class WorkspaceManager {
): Promise<RpcResult<{ workspaceIds: WorkspaceId[] }>> {
const requestGeneration = ++this.orderRequestGeneration
const frameGeneration = this.orderFrameGeneration
const previousOrder = this.itemViews().map(workspace => workspace.workspaceId)
this.installOrder(insertIdBefore(previousOrder, workspaceId, beforeWorkspaceId))
const localOrder = this.itemViews().map(workspace => workspace.workspaceId)
this.installOrder(insertIdBefore(localOrder, workspaceId, beforeWorkspaceId))
let result: RpcResult<{ workspaceIds: WorkspaceId[] }>
try {
;({ result } = await this.api.workspace.insertBefore({
@@ -182,16 +184,16 @@ export class WorkspaceManager {
} catch (error) {
if (requestGeneration === this.orderRequestGeneration
&& frameGeneration === this.orderFrameGeneration) {
this.installOrder(previousOrder)
this.installOrder(this.committedOrder)
}
throw error
}
if (result.ok && requestGeneration === this.orderRequestGeneration
&& frameGeneration === this.orderFrameGeneration) {
this.installOrder(result.value.workspaceIds)
this.installOrder(result.value.workspaceIds, true)
} else if (!result.ok && requestGeneration === this.orderRequestGeneration
&& frameGeneration === this.orderFrameGeneration) {
this.installOrder(previousOrder)
this.installOrder(this.committedOrder)
}
return result
}
@@ -239,7 +241,7 @@ export class WorkspaceManager {
else if (envelope.payload.type === 'host/workspace-removed') this.remove(envelope.payload.workspaceId)
else if (envelope.payload.type === 'host/workspace-order-changed') {
this.orderFrameGeneration++
this.installOrder(envelope.payload.workspaceIds)
this.installOrder(envelope.payload.workspaceIds, true)
}
else if (envelope.payload.type === 'host/archived-sessions-changed') {
this.installArchived(envelope.payload.archivedSessionIds)
@@ -292,9 +294,12 @@ export class WorkspaceManager {
this.notifier.markDirty()
}
/** Reorder known Workspace objects by a complete Host id sequence. */
private installOrder(workspaceIds: readonly WorkspaceId[]): void {
this.refreshFrames?.push({ type: 'order', workspaceIds })
/** Reorder known Workspace objects, optionally recording a Host-committed sequence. */
private installOrder(workspaceIds: readonly WorkspaceId[], committed = false): void {
if (committed) {
this.refreshFrames?.push({ type: 'order', workspaceIds })
this.committedOrder = [...workspaceIds]
}
const rank = new Map(workspaceIds.map((id, index) => [id, index]))
const items = [...this.items].sort((left, right) => {
const leftId = left.getSnapshot().view?.workspaceId
@@ -317,6 +322,9 @@ export class WorkspaceManager {
// late unary response cannot roll back a newer frame.
const installed = index === -1 ? undefined : this.items[index]?.getSnapshot().view
if (installed !== undefined && Date.parse(view.updatedAt) < Date.parse(installed.updatedAt)) return
if (!this.committedOrder.includes(view.workspaceId)) {
this.committedOrder = [view.workspaceId, ...this.committedOrder]
}
if (identity !== undefined) {
this.items = index === -1
? [identity, ...this.items]
@@ -334,6 +342,7 @@ export class WorkspaceManager {
private remove(workspaceId: WorkspaceId, direct = false): void {
this.refreshFrames?.push({ type: 'remove', workspaceId })
this.removedIds.add(workspaceId)
this.committedOrder = this.committedOrder.filter(id => id !== workspaceId)
const items = this.items.filter(item =>
item.getSnapshot().view?.workspaceId !== workspaceId)
if (items.length === this.items.length) {
@@ -367,6 +376,7 @@ export class WorkspaceManager {
installed.set(view.workspaceId, workspace)
}
this.items = [...installed.values()]
this.committedOrder = views.map(view => view.workspaceId)
}
private itemViews(): readonly WorkspaceView[] {
@@ -115,6 +115,35 @@ describe('WorkspaceManager', () => {
expect(manager.getSnapshot().items.map(item => item.workspaceId)).toEqual(['one', 'three', 'two'])
})
it('rolls overlapping rejected reorders back to the last Host-confirmed order', async () => {
const api = new FakeApiClient()
api.onWorkspaceList = () => Promise.resolve(ok({
items: [workspace('one'), workspace('two'), workspace('three')] as never[],
}))
const manager = new WorkspaceManager(api)
await manager.refresh()
const firstGate = deferred<Awaited<ReturnType<FakeApiClient['onWorkspaceInsertBefore']>>>()
const secondGate = deferred<Awaited<ReturnType<FakeApiClient['onWorkspaceInsertBefore']>>>()
let request = 0
api.onWorkspaceInsertBefore = () => request++ === 0 ? firstGate.promise : secondGate.promise
const first = manager.insertBefore(wid('three'), wid('one'))
const second = manager.insertBefore(wid('two'), wid('three'))
expect(manager.getSnapshot().items.map(item => item.workspaceId)).toEqual(['two', 'three', 'one'])
firstGate.resolve(err({
code: 'workspace-not-found', message: 'first rejected', details: { workspaceId: 'three' },
}))
await expect(first).resolves.toMatchObject({ ok: false })
expect(manager.getSnapshot().items.map(item => item.workspaceId)).toEqual(['two', 'three', 'one'])
secondGate.resolve(err({
code: 'workspace-not-found', message: 'second rejected', details: { workspaceId: 'two' },
}))
await expect(second).resolves.toMatchObject({ ok: false })
expect(manager.getSnapshot().items.map(item => item.workspaceId)).toEqual(['one', 'two', 'three'])
})
it('replays removal over an in-flight baseline and ignores duplicate or late updates', async () => {
const api = new FakeApiClient()
const gate = deferred<Awaited<ReturnType<FakeApiClient['onWorkspaceList']>>>()