Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
115 changes: 115 additions & 0 deletions .playwright/scripts/__tests__/workbench.e2e.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -72,3 +72,118 @@ test('builtin working copies back up continued edits, veto closure and recover a
await page.screenshot({ path: path.join(instance.artifactDirectory, 'recovered-and-saved.png'), animations: 'disabled' })
expect(diagnostics.console.filter(item => item.type === 'pageerror')).toEqual([])
})

test('task switching stays responsive during loading, failure and notification navigation', async ({ buddy }, testInfo) => {
const instance = await buddy.createInstance('task-switch')
const { app, page, diagnostics } = await instance.launch()
await app.evaluate((_electron, databasePath) => {
const { DatabaseSync } = process.getBuiltinModule('node:sqlite')
const db = new DatabaseSync(databasePath)
try {
const now = new Date().toISOString()
for (const id of ['a', 'b', 'c']) {
db.prepare('INSERT INTO conversations (id, title, active_branch_id, created_at, updated_at) VALUES (?, ?, ?, ?, ?)').run(id, `Task ${id.toUpperCase()}`, `branch-${id}`, now, now)
db.prepare('INSERT INTO conversation_branches (id, conversation_id, created_at) VALUES (?, ?, ?)').run(`branch-${id}`, id, now)
db.prepare('INSERT INTO messages (id, conversation_id, branch_id, role, content_json, created_at) VALUES (?, ?, ?, ?, ?, ?)').run(`message-${id}`, id, `branch-${id}`, 'user', JSON.stringify({ text: `Content ${id.toUpperCase()}` }), now)
}
db.prepare('INSERT INTO conversation_branches (id, conversation_id, created_at) VALUES (?, ?, ?)').run('notified-branch', 'b', now)
db.prepare('INSERT INTO messages (id, conversation_id, branch_id, role, content_json, created_at) VALUES (?, ?, ?, ?, ?, ?)').run('notified-message', 'b', 'notified-branch', 'user', JSON.stringify({ text: 'Notification target content' }), now)
db.prepare('INSERT INTO runs (id, conversation_id, branch_id, triggering_message_id, provider, model, purpose, status, started_at, completed_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)').run('notified-run', 'b', 'notified-branch', 'notified-message', 'fixture', 'fixture', 'chat', 'completed', now, now)
}
finally { db.close() }
}, path.join(instance.home, 'buddy/buddy.sqlite3'))
await page.reload()
const row = id => page.locator(`[data-task-id="${id}"] .desktop-task-sidebar__task`)
const editor = page.locator('.desktop-chat-composer__prosemirror:visible')
const title = page.locator('.workbench-pane-title:visible')
await row('a').click()
await expect(editor).toBeVisible()
await editor.fill('Saved while switching')
await app.evaluate(({ ipcMain }) => {
const probe = globalThis.taskSwitchProbe = { events: [], gates: new Map(), fail: null }
for (const [stage, channel] of [
['get', 'lexora:buddy:conversations:get'],
['draft', 'lexora:buddy:composer-drafts:open'],
['branches', 'lexora:buddy:conversations:list-branches'],
['timeline', 'lexora:buddy:conversations:list-timeline'],
]) {
const handler = ipcMain._invokeHandlers.get(channel)
ipcMain.removeHandler(channel)
ipcMain.handle(channel, async (event, input) => {
const id = input.conversationId ?? input.scope?.conversationId
probe.events.push({ id, stage, phase: 'start', at: Date.now() })
await probe.gates.get(`${stage}:${id}`)?.promise
if (stage === 'get' && probe.fail === id)
throw new Error('Isolated task read failure')
const result = await handler(event, input)
probe.events.push({ id, stage, phase: 'end', at: Date.now() })
return result
})
}
})
const block = key => app.evaluate((_electron, key) => {
globalThis.taskSwitchProbe.gates.set(key, Promise.withResolvers())
}, key)
const release = key => app.evaluate((_electron, key) => {
const gates = globalThis.taskSwitchProbe.gates
gates.get(key)?.resolve()
gates.delete(key)
}, key)
await block('draft:b')
const clickedAt = Date.now()
await row('b').click()
await expect(title).toHaveText('Task B')
await expect(row('b')).toHaveClass(/is-active/)
await expect(page.getByTestId('task-loading')).toHaveAttribute('aria-busy', 'true')
const loadingVisibleMs = Date.now() - clickedAt
await expect.poll(() => app.evaluate(() => globalThis.taskSwitchProbe.events.some(event => event.id === 'b' && event.stage === 'timeline' && event.phase === 'end'))).toBe(true)
expect(await app.evaluate(() => globalThis.taskSwitchProbe.events.some(event => event.id === 'b' && event.stage === 'draft' && event.phase === 'end'))).toBe(false)
await page.screenshot({ path: path.join(instance.artifactDirectory, 'task-loading-light.png'), animations: 'disabled' })
await page.evaluate(() => window.lexoraDesktop.settings.update({ desktop: { theme: 'dark' } }))
await page.screenshot({ path: path.join(instance.artifactDirectory, 'task-loading-dark.png'), animations: 'disabled' })
await page.evaluate(() => window.lexoraDesktop.settings.update({ desktop: { theme: 'light' } }))
await app.evaluate(({ BrowserWindow }) => BrowserWindow.getAllWindows()[0].setSize(980, 640))
await expect.poll(() => page.evaluate(() => window.innerWidth)).toBe(980)
expect(await page.getByTestId('task-loading').evaluate(element => element.scrollWidth <= element.clientWidth)).toBe(true)
await page.screenshot({ path: path.join(instance.artifactDirectory, 'task-loading-narrow.png'), animations: 'disabled' })
await row('c').click()
await expect(title).toHaveText('Task C')
await expect(editor).toBeVisible()
await release('draft:b')
await expect.poll(() => app.evaluate(() => globalThis.taskSwitchProbe.events.some(event => event.id === 'b' && event.stage === 'draft' && event.phase === 'end'))).toBe(true)
await expect(title).toHaveText('Task C')
await row('a').click()
await expect(editor).toHaveText('Saved while switching')

await app.evaluate(() => {
globalThis.taskSwitchProbe.fail = 'b'
})
await row('b').click()
const failed = page.getByTestId('task-loading').getByRole('alert')
await expect(failed).toContainText('视图加载失败')
await row('a').click()
await expect(editor).toHaveText('Saved while switching')
await row('b').click()
await expect(failed).toBeVisible()
await app.evaluate(() => {
globalThis.taskSwitchProbe.fail = null
})
await failed.getByRole('button', { name: '重试', exact: true }).click()
await expect(editor).toBeVisible()
await expect(page.getByTestId('task-loading')).toHaveCount(0)

await row('a').click()
await expect(editor).toHaveText('Saved while switching')
await block('get:b')
await app.evaluate(({ BrowserWindow }) => {
BrowserWindow.getAllWindows()[0].webContents.send('lexora:app:open-target', { conversationId: 'b', runId: 'notified-run' })
})
await expect(title).toHaveText('Task B')
await expect(page.getByTestId('task-loading')).toBeVisible()
await release('get:b')
await expect.poll(() => page.evaluate(async () => (await window.lexoraDesktop.localChat.conversations.get('b')).activeBranchId)).toBe('notified-branch')
await expect(page.locator('.desktop-chat-page')).toContainText('Notification target content')
await page.screenshot({ path: path.join(instance.artifactDirectory, 'task-notification-target.png'), animations: 'disabled' })
await testInfo.attach('task-load-timing', { body: JSON.stringify({ loadingVisibleMs, requests: await app.evaluate(() => globalThis.taskSwitchProbe.events) }, null, 2), contentType: 'application/json' })
expect(diagnostics.console.filter(item => item.type === 'pageerror')).toEqual([])
})
4 changes: 2 additions & 2 deletions apps/buddy/src/app/bootstrap/DesktopAppProvider.vue
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ useProvideExtensionContext({ settingsLocation: settingsRegistry.extensionLocatio
onScopeDispose(workbench.controller.subscribe(() => void nextTick(extensionViews.layout)))
const selectedTask = workbench.activeTask
const resources = useTaskResourcePanel({
activeConversationId: computed(() => selectedTask.value?.workspace.session.activeConversationId.value ?? null),
activeConversationId: workbench.activeTaskId,
activeDraftId: computed(() => selectedTask.value?.workspace.composer.draftId.value ?? null),
activeBranchId: computed(() => selectedTask.value?.workspace.session.activeBranchId.value ?? null),
activeRunId: computed(() => selectedTask.value?.workspace.execution.activeRun.value?.id
Expand Down Expand Up @@ -183,7 +183,7 @@ const navigation = useDesktopNavigation({
router,
ready,
session: {
activeTaskId: computed(() => selectedTask.value?.session.activeTaskId.value ?? null),
activeTaskId: workbench.activeTaskId,
spaceId: computed(() => selectedTask.value?.session.spaceId.value ?? null),
navigationVersion: () => workbench.navigationVersion,
openTask: (id, signal) => workbench.openTask(id, signal),
Expand Down
3 changes: 3 additions & 0 deletions apps/buddy/src/app/workbench/ActiveTaskProjection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import type { WorkbenchController } from '@/workbench/services/WorkbenchControll
import { computed, shallowRef } from 'vue'

export class ActiveTaskProjection {
readonly #taskId = shallowRef<string | null>(null)
readonly taskId = computed(() => this.#taskId.value)
readonly #active = shallowRef<TaskCapability | null>(null)
readonly current = computed(() => this.#active.value)
readonly #subscriptions: (() => void)[]
Expand All @@ -23,6 +25,7 @@ export class ActiveTaskProjection {
reconcile(): void {
const pane = this.controller.pane(this.controller.layout.activePane)
const view = pane?.view ? this.controller.layout.views[pane.view] : null
this.#taskId.value = view?.resource.scheme === 'task' ? view.resource.id : null
const task = view ? this.pool.peek(view.resource) : undefined
this.#active.value = task?.workspace.restoration.state.value === 'ready' ? task : null
}
Expand Down
32 changes: 14 additions & 18 deletions apps/buddy/src/app/workbench/DesktopTaskContribution.vue
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,13 @@ import { useMessage } from 'naive-ui'
import { computed, onScopeDispose, shallowRef, watch } from 'vue'
import { useTaskEnvironment } from '@/modules/tasks'
import { DesktopTaskEditor, DesktopTaskViewProvider } from '@/modules/tasks/ui'
import { useWorkbench } from '@/workbench/browser/workbenchContext'
import WorkbenchPaneActions from '@/workbench/browser/WorkbenchPaneActions.vue'
import WorkbenchPaneTitle from '@/workbench/browser/WorkbenchPaneTitle.vue'
import DesktopTaskLoading from './DesktopTaskLoading.vue'
import { useDesktopWorkbenchContext } from './desktopWorkbenchContext'

const props = defineProps<{ view: WorkbenchView, visible: boolean }>()
const workbench = useDesktopWorkbenchContext()
const { labels } = useWorkbench()
const environment = useTaskEnvironment()
const task = shallowRef<TaskCapability | null>(null)
const failed = shallowRef(false)
Expand All @@ -30,20 +29,21 @@ watch(() => task.value?.session.spaceId.value, (spaceId) => {
if (props.view.resource.scheme === 'draft' && task.value && props.view.resource.data.spaceId !== spaceId)
workbench.controller.updateView(props.view.id, { resource: { ...props.view.resource, data: { spaceId: spaceId ?? null } } })
})
let disposed = false
onScopeDispose(() => disposed = true)
let loadVersion = 0
onScopeDispose(() => loadVersion++)
async function load() {
if (!taskResource.value)
return
const version = ++loadVersion
failed.value = false
try {
const loaded = await workbench.pool.open(props.view.resource)
if (disposed)
if (version !== loadVersion)
return
task.value = loaded
}
catch {
if (!disposed) {
if (version === loadVersion) {
failed.value = true
workbench.controller.navigation.fail(props.view.id)
}
Expand All @@ -67,16 +67,12 @@ watch(() => task.value?.session.currentTitle.value, (title) => {
</template>
</DesktopTaskEditor>
</DesktopTaskViewProvider>
<div v-else class="desktop-workbench-view__fallback">
<span>{{ failed ? labels.failed : labels.loading }}</span><button v-if="failed" type="button" @click="load">
{{ labels.retry }}
</button>
</div>
<DesktopTaskLoading v-else :failed="failed" @retry="load">
<template #title>
<WorkbenchPaneTitle :view="view" />
</template>
<template #actions>
<WorkbenchPaneActions :view-id="view.id" @split="workbench.newTask(typeof view.resource.data.spaceId === 'string' ? view.resource.data.spaceId : null, workbench.controller.owner(view.id)?.id, $event)" />
</template>
</DesktopTaskLoading>
</template>

<style scoped>
.desktop-workbench-view__fallback { margin: auto; display: flex; gap: 12px; color: var(--buddy-text-secondary); }
.desktop-workbench-view__output { flex: 1; min-height: 0; overflow: auto; padding: 12px 16px; font-size: 11px; }
.desktop-workbench-view__run { display: flex; gap: 14px; padding: 3px 0; color: var(--buddy-text-secondary); }
.desktop-workbench-view__run code { overflow: hidden; text-overflow: ellipsis; }
</style>
57 changes: 57 additions & 0 deletions apps/buddy/src/app/workbench/DesktopTaskLoading.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
<script setup lang="ts">
import { NButton, NSkeleton, NSpin } from 'naive-ui'
import { useWorkbench } from '@/workbench/browser/workbenchContext'

defineProps<{ failed: boolean }>()
defineEmits<{ retry: [] }>()
const { labels } = useWorkbench()
</script>

<template>
<section class="desktop-task-loading" :aria-busy="!failed" data-testid="task-loading">
<header class="desktop-task-loading__header">
<div class="desktop-task-loading__title">
<slot name="title" />
</div>
<slot name="actions" />
</header>
<div v-if="failed" class="desktop-task-loading__failure" role="alert">
<span>{{ labels.failed }}</span>
<NButton size="small" @click="$emit('retry')">
{{ labels.retry }}
</NButton>
</div>
<template v-else>
<div class="desktop-task-loading__content">
<div class="desktop-task-loading__status" role="status">
<NSpin :size="16" />
<span>{{ labels.loading }}</span>
</div>
<div class="desktop-task-loading__skeleton" aria-hidden="true">
<div v-for="index in 2" :key="index" class="desktop-task-loading__message">
<NSkeleton width="80px" height="14px" />
<NSkeleton text :repeat="3" />
</div>
</div>
</div>
<div class="desktop-task-loading__composer" aria-hidden="true">
<NSkeleton height="88px" :sharp="false" />
</div>
</template>
</section>
</template>

<style scoped>
.desktop-task-loading { display: flex; flex: 1; min-width: 0; min-height: 0; flex-direction: column; }
.desktop-task-loading__header { display: flex; flex: none; align-items: center; gap: 0.85rem; height: var(--buddy-region-header-height); border-bottom: 1px solid var(--buddy-border-subtle); background: var(--buddy-surface-base); padding: 0 0.75rem 0 1rem; }
.desktop-task-loading__title { flex: 1; min-width: 0; font-size: 0.88rem; font-weight: 660; }
.desktop-task-loading__content { flex: 1; min-height: 0; overflow: hidden; width: min(100%, 800px); margin: 0 auto; padding: 24px; }
.desktop-task-loading__status { display: flex; align-items: center; gap: 8px; color: var(--buddy-text-secondary); font-size: 12px; }
.desktop-task-loading__skeleton { display: grid; gap: 32px; margin-top: 28px; }
.desktop-task-loading__message { display: grid; gap: 12px; }
.desktop-task-loading__composer { flex: none; width: min(100%, 800px); margin: 0 auto; padding: 12px 24px 24px; }
.desktop-task-loading__failure { flex: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 16px; color: var(--buddy-text-secondary); }
@media (prefers-reduced-motion: reduce) {
.desktop-task-loading :deep(.n-skeleton), .desktop-task-loading :deep(.n-spin-body) { animation: none !important; }
}
</style>
2 changes: 1 addition & 1 deletion apps/buddy/src/app/workbench/DesktopWorkbenchArea.vue
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ function focusContext() {
<WorkbenchLayout v-model:sidebar-collapsed="collapsed" v-model:sidebar-width="width" :language="language" :context-visible="(tasksVisible || bindings.contextPanelGlobal.value) && bindings.resources.isOpen.value" :sidebar-collapsible="tasksVisible" :sidebar-resizable="tasksVisible">
<template v-if="tasksVisible" #sidebar>
<WorkbenchMountPoint target="workbench.sidebar">
<DesktopTaskIndexView :pending-task-ids="pendingTaskIds" :index="bindings.taskIndex" :active-task-id="bindings.workbench.activeTask.value?.session.activeTaskId.value ?? null" @open-task="bindings.workbench.openTask" @new-task="bindings.workbench.newTask" />
<DesktopTaskIndexView :pending-task-ids="pendingTaskIds" :index="bindings.taskIndex" :active-task-id="bindings.workbench.activeTaskId.value" @open-task="bindings.workbench.openTask" @new-task="bindings.workbench.newTask" />
</WorkbenchMountPoint>
</template>
<div v-show="tasksVisible" class="desktop-workbench-area__tasks">
Expand Down
11 changes: 7 additions & 4 deletions apps/buddy/src/app/workbench/TaskWorkspacePool.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export class TaskWorkspacePool {
readonly #changes = new Emitter<TaskWorkspaceChange>(() => console.error('TASK_WORKSPACE_OBSERVER_FAILED'))
readonly onDidChange = this.#changes.event
readonly #options: Omit<UseTaskCapabilityOptions, 'initialTarget'>
readonly #entries = new Map<string, { task: TaskCapability, scope: EffectScope }>()
readonly #entries = new Map<string, { task: TaskCapability, scope: EffectScope, ready: boolean }>()
readonly #leases = new Map<TaskCapability, number>()
readonly #loading = new Map<string, Promise<TaskCapability>>()
readonly #adopt: (previous: ResourceRef, task: TaskCapability, id: string) => void
Expand All @@ -30,7 +30,8 @@ export class TaskWorkspacePool {
}

peek(resource: ResourceRef): TaskCapability | undefined {
return this.#entries.get(resourceKey(resource))?.task
const entry = this.#entries.get(resourceKey(resource))
return entry?.ready ? entry.task : undefined
}

open(resource: ResourceRef): Promise<TaskCapability> {
Expand Down Expand Up @@ -77,17 +78,19 @@ export class TaskWorkspacePool {
const previous = currentResource
currentResource = { scheme: 'task', id, data: {} }
this.#entries.delete(resourceKey(previous))
this.#entries.set(resourceKey(currentResource), { task, scope })
this.#entries.set(resourceKey(currentResource), { task, scope, ready: true })
this.#options.onDraftCommitted?.(draftId, id)
this.#adopt(previous, task, id)
this.#changes.fire(Object.freeze({ kind: 'adopted', resource: currentResource, previous }))
},
}))!
this.#entries.set(resourceKey(resource), { task, scope })
const entry = { task, scope, ready: false }
this.#entries.set(resourceKey(resource), entry)
try {
await task.initialize()
if (this.#disposed || this.#entries.get(resourceKey(currentResource))?.task !== task || task.workspace.restoration.state.value !== 'ready')
throw new Error('TASK_RESTORATION_FAILED')
entry.ready = true
this.#changes.fire(Object.freeze({ kind: 'ready', resource: currentResource }))
return task
}
Expand Down
Loading