feat(browser): add picture-in-picture task preview
parent
815d32d3a9
commit
462999ec3f
|
|
@ -42,6 +42,8 @@ WeKnora 使用 Tencent/BrowserSkill 的官方 daemon 和扩展执行浏览器操
|
|||
|
||||
结果卡片展示控制台消息与堆栈、网络请求状态与错误、脚本返回值及具体失败原因;较长结果会截断并提示。小预览展示最近动作、动作耗时、已知页面地址和最近错误;页面地址去掉账号、查询参数和片段。耗时在动作执行期间更新,结束后固定。
|
||||
|
||||
支持 Document Picture-in-Picture 的浏览器可点击预览标题栏的“弹出悬浮窗”,把同一个预览和暂停、继续、结束按钮移到置顶窗口。切换标签页时继续同步画面;关闭悬浮窗或点击“返回对话小窗”会恢复页内预览,不结束浏览器任务。任务结束、切换会话或离开对话页面时关闭该会话的悬浮窗。此功能依赖安全上下文(HTTPS 或本机 localhost)及用户点击;不支持的浏览器保留页内小窗,打开失败时显示提示并允许重试。悬浮窗依赖原页面,不能在关闭 WeKnora 页面后独立运行。
|
||||
|
||||
模型调用采用扁平参数,例如 `{"method":"navigate","url":"https://example.com"}`、`{"method":"click","ref":"e3"}`、`{"method":"observe"}`。Schema 不再提供 `params` 字段,旧的嵌套格式直接拒绝。服务端校验所选动作的必填字段、字段类型及定位条件,再将参数转换为 BrowserSkill 原生 RPC 信封;会话和设备 ID 始终由服务端绑定。
|
||||
|
||||
`wait_ms` 的外层参数为 `duration_ms`,范围 0–10000 毫秒;工具描述、参数 schema 和执行前校验保持一致。命令超时或中断后暂停任务,不自动重放点击/提交。前端显示具体浏览器动作与可读错误,结果卡片分别展示网页内容、截图或标签列表,不展示原始协议 JSON。标签组统一显示 WeKnora,不再附带内部任务 ID。
|
||||
|
|
@ -105,6 +107,16 @@ BROWSERSKILL_TEST_TASK_WINDOW=0 # 可选:通过扩展界面切换后台标签
|
|||
|
||||
补丁中的 `task-focus.browser.test.ts` 使用独立 Chrome 与原生 CDP 验证后台绘制、内容读取、截图和释放后的可见性恢复,避免 Playwright 默认的焦点模拟掩盖问题。在应用补丁后的 BrowserSkill 源码中,设置 `BSK_GEOMETRY_CHROME` 为测试 Chrome 路径,再执行 `pnpm --filter @browser-skill/extension exec vitest run src/browser-driver/__tests__/task-focus.browser.test.ts`(Node 20 另需 `NODE_OPTIONS=--experimental-websocket`)。
|
||||
|
||||
仅验证预览组件的真实 PiP 窗口(使用模拟任务 API,不需要扩展或模型):
|
||||
|
||||
```bash
|
||||
BROWSERSKILL_TEST_CHROMIUM=/absolute/path/to/Chrome \
|
||||
BROWSERSKILL_TEST_PLAYWRIGHT=/absolute/path/to/playwright-core/index.mjs \
|
||||
node frontend/scripts/verify-browser-preview-pip.mjs
|
||||
```
|
||||
|
||||
该验收覆盖真实弹出/还原、窗口样式、切换标签页后同步、隐藏页面分支、共享操作按钮、会话切换清理及不支持/打开失败的回退。
|
||||
|
||||
### 输入框选择本机浏览器
|
||||
|
||||
扩展弹窗中的“任务打开方式”提供“独立窗口(默认,保持可见)”和“后台标签组”。未保存偏好时默认使用独立窗口,已主动选择后台标签组的用户保持原设置。设置保存在本机扩展中,仅对新浏览器任务生效;已有任务需要先结束,或使用新对话。独立窗口不额外创建 Chrome 标签组,开始时会打开到前台,后续创建、选择任务标签只在该窗口内切换;请手动与聊天窗口并排放置。完全遮挡或最小化仍可能导致读取变慢,因此此模式不是不可见后台运行的性能保证。结束任务只清理明确归属于任务的标签,用户后来移入窗口的页面会保留。
|
||||
|
|
|
|||
|
|
@ -0,0 +1,170 @@
|
|||
// Opt-in integration test: a real PiP window and the production Vue component,
|
||||
// with a simulated browser-task API. No extension, model or user account is used.
|
||||
import assert from 'node:assert/strict';
|
||||
import { fileURLToPath, pathToFileURL } from 'node:url';
|
||||
import { mkdtemp, rm } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { createServer } from 'vite';
|
||||
import vue from '@vitejs/plugin-vue';
|
||||
|
||||
const executablePath = process.env.BROWSERSKILL_TEST_CHROMIUM;
|
||||
const playwrightPath = process.env.BROWSERSKILL_TEST_PLAYWRIGHT;
|
||||
assert.ok(executablePath && playwrightPath, 'Set BROWSERSKILL_TEST_CHROMIUM and BROWSERSKILL_TEST_PLAYWRIGHT');
|
||||
const { chromium } = await import(pathToFileURL(playwrightPath).href);
|
||||
const root = fileURLToPath(new URL('../', import.meta.url));
|
||||
const cacheDir = await mkdtemp(join(tmpdir(), 'weknora-pip-vite-'));
|
||||
const status = { enabled: true, selected: true, connected: true, task_id: 'fixture', paused: false, idle: false, action: 'observe', action_elapsed_ms: 1000 };
|
||||
const calls = [];
|
||||
const entry = `
|
||||
import {createApp,h,ref} from 'vue';
|
||||
import {createPinia} from 'pinia';
|
||||
import TDesign from 'tdesign-vue-next';
|
||||
import 'tdesign-vue-next/es/style/index.css';
|
||||
import i18n from '/src/i18n/index.ts';
|
||||
import Preview from '/src/views/chat/components/BrowserTaskPreview.vue';
|
||||
const session = ref('pip-test');
|
||||
const app = createApp({setup(){return ()=>h('main',{style:'position:relative;width:900px;height:700px'},[
|
||||
h('button',{onClick:()=>session.value = session.value === 'pip-test' ? 'other-test' : 'pip-test'},'Switch conversation'),
|
||||
h(Preview,{key:session.value,sessionId:session.value})
|
||||
])}});
|
||||
app.use(createPinia()).use(i18n).use(TDesign).mount('#app');
|
||||
`;
|
||||
const server = await createServer({
|
||||
root, cacheDir, configFile: false, plugins: [vue(), {
|
||||
name: 'pip-fixture',
|
||||
resolveId(id) { if (id === '/pip-fixture.js') return '\0pip-fixture'; },
|
||||
load(id) { if (id === '\0pip-fixture') return entry; },
|
||||
configureServer(server) {
|
||||
server.middlewares.use(async (req, res, next) => {
|
||||
if (req.url === '/pip-fixture.html') {
|
||||
res.setHeader('Content-Type', 'text/html');
|
||||
res.end(await server.transformIndexHtml(req.url, '<!doctype html><html><head></head><body><div id="app"></div><script type="module" src="/pip-fixture.js"></script></body></html>'));
|
||||
} else if (req.url?.match(/^\/api\/v1\/sessions\/(pip-test|other-test)\/local-browser$/)) {
|
||||
let body = '';
|
||||
for await (const chunk of req) body += chunk;
|
||||
const action = body ? JSON.parse(body).action : 'status';
|
||||
calls.push({ action, url: req.url });
|
||||
if (action === 'pause') status.paused = true;
|
||||
if (action === 'resume') status.paused = false;
|
||||
if (action === 'stop') status.selected = false;
|
||||
const data = action === 'preview' ? {
|
||||
// Valid one-pixel PNG: this test verifies delivery, not image recognition.
|
||||
image_base64: 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+aD1sAAAAASUVORK5CYII=',
|
||||
format: 'png', captured_at: new Date().toISOString(),
|
||||
} : status;
|
||||
res.setHeader('Content-Type', 'application/json');
|
||||
res.end(JSON.stringify({ success: true, data }));
|
||||
} else next();
|
||||
});
|
||||
},
|
||||
}], resolve: { alias: { '@': root + 'src' } },
|
||||
server: { host: '127.0.0.1', port: 0 },
|
||||
});
|
||||
let browser;
|
||||
async function until(check, label) {
|
||||
const deadline = Date.now() + 15000;
|
||||
while (!await check()) {
|
||||
assert.ok(Date.now() < deadline, `Timed out: ${label}`);
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
}
|
||||
}
|
||||
try {
|
||||
await server.listen();
|
||||
const url = server.resolvedUrls.local[0] + 'pip-fixture.html';
|
||||
browser = await chromium.launch({ executablePath, headless: false });
|
||||
const context = await browser.newContext();
|
||||
await context.addInitScript(() => localStorage.setItem('locale', 'en-US'));
|
||||
const page = await context.newPage();
|
||||
const errors = [];
|
||||
page.on('pageerror', error => errors.push(error.message));
|
||||
await page.goto(url);
|
||||
const preview = page.locator('.browser-task-preview');
|
||||
const open = page.getByRole('button', { name: 'Pop out preview', exact: true });
|
||||
await open.waitFor();
|
||||
await page.waitForFunction(() => document.querySelector('.preview-image img')?.naturalWidth > 0);
|
||||
const heading = await page.locator('.preview-heading').boundingBox();
|
||||
await page.mouse.move(heading.x + 30, heading.y + 15);
|
||||
await page.mouse.down();
|
||||
await page.mouse.move(heading.x - 120, heading.y - 70);
|
||||
await page.mouse.up();
|
||||
const savedPosition = await preview.evaluate(el => ({ left: el.style.left, top: el.style.top }));
|
||||
assert.ok(savedPosition.left && savedPosition.top, 'preview was dragged before pop-out');
|
||||
// A rejected request must leave the existing UI usable and allow a retry.
|
||||
await page.evaluate(() => {
|
||||
const api = window.documentPictureInPicture;
|
||||
const real = api.requestWindow.bind(api);
|
||||
api.requestWindow = () => { api.requestWindow = real; return Promise.reject(new Error('fixture rejection')); };
|
||||
});
|
||||
await open.click();
|
||||
await page.getByRole('alert').filter({ hasText: 'Could not open the floating window' }).waitFor();
|
||||
await open.click();
|
||||
await page.waitForFunction(() => window.documentPictureInPicture.window?.document.querySelector('.is-pip'));
|
||||
assert.equal(await preview.count(), 0, 'only one preview is rendered');
|
||||
assert.equal(await page.evaluate(() => {
|
||||
const w = documentPictureInPicture.window;
|
||||
return w.getComputedStyle(w.document.querySelector('.is-pip')).position;
|
||||
}), 'static', 'scoped component styles are available in PiP');
|
||||
// The live theme follows the opener, without reopening the window.
|
||||
await page.evaluate(() => document.documentElement.setAttribute('data-theme', 'dark'));
|
||||
await page.waitForFunction(() => documentPictureInPicture.window.document.documentElement.getAttribute('data-theme') === 'dark');
|
||||
const other = await context.newPage();
|
||||
await other.goto('about:blank');
|
||||
await other.bringToFront();
|
||||
// Chrome may keep the opener visible while its document PiP is visible.
|
||||
// First verify real tab switching, then explicitly exercise the hidden branch.
|
||||
const switched = calls.filter(call => call.action === 'preview').length;
|
||||
await until(() => calls.filter(call => call.action === 'preview').length >= switched + 2, 'preview after switching tabs');
|
||||
await page.evaluate(() => {
|
||||
Object.defineProperty(document, 'hidden', { configurable: true, get: () => true });
|
||||
document.dispatchEvent(new Event('visibilitychange'));
|
||||
});
|
||||
const before = calls.filter(call => call.action === 'preview').length;
|
||||
await until(() => calls.filter(call => call.action === 'preview').length >= before + 2, 'preview updates with hidden opener');
|
||||
await page.evaluate(() => { delete document.hidden; document.dispatchEvent(new Event('visibilitychange')); });
|
||||
const clickPip = name => page.evaluate(name => {
|
||||
const button = [...documentPictureInPicture.window.document.querySelectorAll('button')].find(button => button.textContent.trim() === name || button.getAttribute('aria-label') === name);
|
||||
if (!button) throw new Error('Missing PiP button: ' + name);
|
||||
button.click();
|
||||
}, name);
|
||||
await clickPip('Pause browser');
|
||||
await until(() => status.paused, 'pause command');
|
||||
await page.waitForFunction(() => documentPictureInPicture.window.document.body.textContent.includes('Resume browser'));
|
||||
await clickPip('Resume browser');
|
||||
await until(() => !status.paused, 'resume command');
|
||||
await page.waitForFunction(() => !documentPictureInPicture.window.document.querySelector('.preview-actions button').disabled);
|
||||
await clickPip('Return to conversation');
|
||||
await until(() => preview.count(), 'PiP returns to page');
|
||||
assert.equal(status.selected, true, 'closing PiP does not stop browser work');
|
||||
assert.deepEqual(await preview.evaluate(el => ({ left: el.style.left, top: el.style.top })), savedPosition, 'restore the dragged page position');
|
||||
await page.bringToFront();
|
||||
await open.click();
|
||||
await page.waitForFunction(() => documentPictureInPicture.window?.document.querySelector('.is-pip'));
|
||||
await page.evaluate(() => documentPictureInPicture.window.close());
|
||||
await preview.waitFor();
|
||||
await open.click();
|
||||
await page.waitForFunction(() => documentPictureInPicture.window?.document.querySelector('.is-pip'));
|
||||
await page.getByRole('button', { name: 'Switch conversation', exact: true }).click();
|
||||
await page.waitForFunction(() => !documentPictureInPicture.window);
|
||||
await preview.waitFor();
|
||||
await open.click();
|
||||
await page.waitForFunction(() => documentPictureInPicture.window?.document.querySelector('.is-pip'));
|
||||
await clickPip('End browser task');
|
||||
await until(() => !status.selected, 'stop command');
|
||||
await page.waitForFunction(() => !documentPictureInPicture.window);
|
||||
assert.equal(await preview.count(), 0);
|
||||
assert.ok(calls.some(call => call.action === 'stop' && call.url.includes('/other-test/')), 'new conversation controls only its own task');
|
||||
assert.deepEqual(errors, [], 'no Vue or cross-document runtime errors');
|
||||
// Feature detection must keep the current page preview on unsupported browsers.
|
||||
status.selected = true;
|
||||
const unsupported = await context.newPage();
|
||||
await unsupported.addInitScript(() => Object.defineProperty(window, 'documentPictureInPicture', { value: undefined }));
|
||||
await unsupported.goto(url);
|
||||
await unsupported.locator('.browser-task-preview').waitFor();
|
||||
assert.equal(await unsupported.getByRole('button', { name: 'Pop out preview', exact: true }).count(), 0);
|
||||
console.log('PASS: real PiP open/restore, scoped styles/theme, background frames, shared pause/resume/stop, session teardown, rejection retry and unsupported fallback');
|
||||
} finally {
|
||||
await browser?.close();
|
||||
await server.close();
|
||||
await rm(cacheDir, { recursive: true, force: true });
|
||||
}
|
||||
|
|
@ -0,0 +1,142 @@
|
|||
import assert from 'node:assert/strict'
|
||||
import test from 'node:test'
|
||||
import { createRenderer, nextTick, ref } from 'vue'
|
||||
import { useDocumentPictureInPicture } from './useDocumentPictureInPicture.ts'
|
||||
|
||||
function attributes() {
|
||||
const values = new Map<string, string>()
|
||||
return {
|
||||
getAttribute: (key: string) => values.get(key) ?? null,
|
||||
setAttribute: (key: string, value: string) => values.set(key, value),
|
||||
removeAttribute: (key: string) => values.delete(key),
|
||||
}
|
||||
}
|
||||
function fakeDocument() {
|
||||
const nodes: any[] = []
|
||||
return {
|
||||
baseURI: 'https://weknora.test/chat', title: '', nodes,
|
||||
documentElement: attributes(), body: attributes(),
|
||||
head: { append: (node: any) => nodes.push(node) },
|
||||
styleSheets: [{ href: '/assets/app.css', disabled: false, media: { mediaText: '' } }],
|
||||
createElement: (tag: string) => ({ tag }),
|
||||
}
|
||||
}
|
||||
function fakeWindow() {
|
||||
const events = new EventTarget()
|
||||
return Object.assign(events, {
|
||||
document: fakeDocument(), closed: false,
|
||||
close() { if (!this.closed) { this.closed = true; events.dispatchEvent(new Event('pagehide')) } },
|
||||
})
|
||||
}
|
||||
function harness(requestWindow?: () => Promise<any>) {
|
||||
const originals = { window: globalThis.window, document: globalThis.document, observer: globalThis.MutationObserver }
|
||||
const source = fakeDocument()
|
||||
const observers: { callback: () => void; disconnected: boolean }[] = []
|
||||
const opener: any = { isSecureContext: true, documentPictureInPicture: requestWindow ? { requestWindow } : undefined }
|
||||
opener.top = opener
|
||||
globalThis.window = opener
|
||||
globalThis.document = source as unknown as Document
|
||||
globalThis.MutationObserver = class {
|
||||
disconnected = false
|
||||
constructor(public callback: () => void) { observers.push(this) }
|
||||
observe() {}
|
||||
disconnect() { this.disconnected = true }
|
||||
} as unknown as typeof MutationObserver
|
||||
const renderer = createRenderer<any, any>({
|
||||
patchProp() {}, insert() {}, remove() {}, setText() {}, setElementText() {},
|
||||
createElement: () => ({}), createText: () => ({}), createComment: () => ({}),
|
||||
parentNode: () => null, nextSibling: () => null,
|
||||
})
|
||||
const selected = ref(true), title = ref('Browser preview')
|
||||
let pip!: ReturnType<typeof useDocumentPictureInPicture>
|
||||
const app = renderer.createApp({ setup() { pip = useDocumentPictureInPicture(selected, () => title.value); return () => null } })
|
||||
app.mount({})
|
||||
return { pip, selected, title, source, observers, unmount: () => app.unmount(), restore() {
|
||||
app.unmount()
|
||||
globalThis.window = originals.window
|
||||
globalThis.document = originals.document
|
||||
globalThis.MutationObserver = originals.observer
|
||||
} }
|
||||
}
|
||||
|
||||
test('PiP preserves task selection, synchronizes title/theme and releases window resources', async () => {
|
||||
const windows: ReturnType<typeof fakeWindow>[] = []
|
||||
const h = harness(async () => { const win = fakeWindow(); windows.push(win); return win })
|
||||
try {
|
||||
h.source.documentElement.setAttribute('class', 'dark')
|
||||
await h.pip.open()
|
||||
assert.equal(h.pip.target.value, windows[0]!.document.body)
|
||||
assert.equal(windows[0]!.document.documentElement.getAttribute('class'), 'dark')
|
||||
assert.ok(windows[0]!.document.nodes.some(node => node.tag === 'link' && node.href === '/assets/app.css'))
|
||||
h.title.value = '预览'
|
||||
await nextTick()
|
||||
assert.equal(windows[0]!.document.title, '预览')
|
||||
h.source.documentElement.setAttribute('class', 'light')
|
||||
h.observers[0]!.callback()
|
||||
assert.equal(windows[0]!.document.documentElement.getAttribute('class'), 'light')
|
||||
windows[0]!.close()
|
||||
assert.equal(h.pip.target.value, null)
|
||||
assert.equal(h.selected.value, true, 'closing PiP does not stop the task')
|
||||
assert.equal(h.observers[0]!.disconnected, true)
|
||||
await h.pip.open()
|
||||
h.selected.value = false
|
||||
assert.equal(windows[1]!.closed, true, 'ending the task closes PiP')
|
||||
assert.equal(h.pip.target.value, null)
|
||||
} finally { h.restore() }
|
||||
})
|
||||
|
||||
test('unsupported API and rejected opening keep the page preview available for retry', async () => {
|
||||
const unsupported = harness()
|
||||
try {
|
||||
assert.equal(unsupported.pip.supported, false)
|
||||
await unsupported.pip.open()
|
||||
assert.equal(unsupported.pip.target.value, null)
|
||||
} finally { unsupported.restore() }
|
||||
let reject = true
|
||||
const h = harness(async () => { if (reject) throw new Error('denied'); return fakeWindow() })
|
||||
try {
|
||||
await assert.rejects(h.pip.open(), /denied/)
|
||||
assert.equal(h.pip.target.value, null)
|
||||
assert.equal(h.pip.opening.value, false)
|
||||
assert.equal(h.selected.value, true)
|
||||
reject = false
|
||||
await h.pip.open()
|
||||
assert.ok(h.pip.target.value)
|
||||
} finally { h.restore() }
|
||||
})
|
||||
|
||||
test('opening is single-flight and a late window is closed after unmount', async () => {
|
||||
let resolve!: (win: any) => void, requests = 0
|
||||
const h = harness(() => { requests++; return new Promise(r => { resolve = r }) })
|
||||
try {
|
||||
const opening = h.pip.open()
|
||||
await h.pip.open()
|
||||
assert.equal(requests, 1)
|
||||
assert.equal(h.pip.opening.value, true)
|
||||
h.unmount()
|
||||
const late = fakeWindow()
|
||||
resolve(late)
|
||||
await opening
|
||||
assert.equal(late.closed, true)
|
||||
assert.equal(h.pip.target.value, null)
|
||||
} finally { h.restore() }
|
||||
})
|
||||
|
||||
test('stale opening cannot replace or close a newly selected task window', async () => {
|
||||
const pending: ((win: any) => void)[] = []
|
||||
const h = harness(() => new Promise(r => pending.push(r)))
|
||||
try {
|
||||
const oldOpen = h.pip.open()
|
||||
h.selected.value = false
|
||||
h.selected.value = true
|
||||
const newOpen = h.pip.open()
|
||||
const current = fakeWindow(), stale = fakeWindow()
|
||||
pending[1]!(current)
|
||||
await newOpen
|
||||
pending[0]!(stale)
|
||||
await oldOpen
|
||||
assert.equal(stale.closed, true)
|
||||
assert.equal(current.closed, false)
|
||||
assert.equal(h.pip.target.value, current.document.body)
|
||||
} finally { h.restore() }
|
||||
})
|
||||
|
|
@ -0,0 +1,104 @@
|
|||
import { onBeforeUnmount, ref, shallowRef, watch, type Ref } from 'vue'
|
||||
|
||||
interface DocumentPictureInPicture {
|
||||
requestWindow(options: { width: number; height: number }): Promise<Window>
|
||||
}
|
||||
|
||||
/** A single Vue Teleport destination, owned by the mounted task preview. */
|
||||
export function useDocumentPictureInPicture(selected: Ref<boolean>, title: () => string) {
|
||||
const api = (window as Window & { documentPictureInPicture?: DocumentPictureInPicture }).documentPictureInPicture
|
||||
const supported = !!api && window.isSecureContext && window.top === window
|
||||
const target = shallowRef<HTMLElement | null>(null)
|
||||
const opening = ref(false)
|
||||
let ownedWindow: Window | null = null
|
||||
let disposeStyles: (() => void) | undefined
|
||||
let generation = 0
|
||||
let disposed = false
|
||||
|
||||
function close() {
|
||||
generation++
|
||||
opening.value = false
|
||||
target.value = null
|
||||
disposeStyles?.()
|
||||
disposeStyles = undefined
|
||||
const previous = ownedWindow
|
||||
ownedWindow = null
|
||||
previous?.close()
|
||||
}
|
||||
|
||||
async function open() {
|
||||
if (!supported || !api || disposed || !selected.value || opening.value || ownedWindow) return
|
||||
const current = ++generation
|
||||
opening.value = true
|
||||
let created: Window | undefined
|
||||
try {
|
||||
// Keep this call synchronous with the button click (transient activation).
|
||||
created = await api.requestWindow({ width: 360, height: 440 })
|
||||
if (disposed || current !== generation || !selected.value || created.closed) {
|
||||
created.close()
|
||||
return
|
||||
}
|
||||
ownedWindow = created
|
||||
disposeStyles = copyPreviewStyles(document, created.document)
|
||||
created.document.title = title()
|
||||
const pip = created
|
||||
pip.addEventListener('pagehide', () => {
|
||||
if (ownedWindow === pip) close()
|
||||
}, { once: true })
|
||||
target.value = pip.document.body
|
||||
} catch (error) {
|
||||
created?.close()
|
||||
if (!disposed && current === generation) {
|
||||
close()
|
||||
throw error
|
||||
}
|
||||
} finally {
|
||||
if (current === generation) opening.value = false
|
||||
}
|
||||
}
|
||||
|
||||
watch(selected, value => { if (!value) close() }, { flush: 'sync' })
|
||||
watch(title, value => { if (ownedWindow) ownedWindow.document.title = value })
|
||||
onBeforeUnmount(() => { disposed = true; close() })
|
||||
return { supported, target, opening, open, close }
|
||||
}
|
||||
|
||||
function copyPreviewStyles(source: Document, destination: Document) {
|
||||
const base = destination.createElement('base')
|
||||
base.href = source.baseURI
|
||||
destination.head.append(base)
|
||||
for (const sheet of Array.from(source.styleSheets)) {
|
||||
if (sheet.disabled) continue
|
||||
// Keep linked CSS at its original URL so relative font/image URLs resolve.
|
||||
if (sheet.href) {
|
||||
const link = destination.createElement('link')
|
||||
link.rel = 'stylesheet'
|
||||
link.href = sheet.href
|
||||
link.media = sheet.media.mediaText
|
||||
link.disabled = sheet.disabled
|
||||
destination.head.append(link)
|
||||
} else {
|
||||
const style = destination.createElement('style')
|
||||
style.textContent = Array.from(sheet.cssRules, rule => rule.cssText).join('\n')
|
||||
style.media = sheet.media.mediaText
|
||||
destination.head.append(style)
|
||||
}
|
||||
}
|
||||
const syncTheme = () => {
|
||||
for (const [from, to] of [[source.documentElement, destination.documentElement], [source.body, destination.body]]) {
|
||||
for (const name of ['class', 'style', 'lang', 'dir', 'theme-mode', 'tdesign-theme', 'data-theme']) {
|
||||
const value = from!.getAttribute(name)
|
||||
if (value === null) to!.removeAttribute(name)
|
||||
else to!.setAttribute(name, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
syncTheme()
|
||||
const observer = new MutationObserver(syncTheme)
|
||||
observer.observe(source.documentElement, { attributes: true })
|
||||
observer.observe(source.body, { attributes: true })
|
||||
const reset = destination.createElement('style')
|
||||
reset.textContent = 'html, body { margin: 0 !important; padding: 0 !important; width: 100% !important; height: 100% !important; overflow: auto !important; background: var(--td-bg-color-container); }'
|
||||
destination.head.append(reset)
|
||||
return () => observer.disconnect()
|
||||
}
|
||||
|
|
@ -1,5 +1,9 @@
|
|||
export default {
|
||||
localBrowser: {
|
||||
pipOpen: "Pop out preview",
|
||||
pipReturn: "Return to conversation",
|
||||
pipFailed: "Could not open the floating window. Please try again.",
|
||||
|
||||
captureScreenshot: "Capture screenshot",
|
||||
navigationIncomplete: "Navigation did not reach the requested loading phase. Check the current page.",
|
||||
noEntries: "No entries returned.",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
export default {
|
||||
localBrowser: {
|
||||
pipOpen: "プレビューを別ウィンドウで表示",
|
||||
pipReturn: "会話内のプレビューに戻す",
|
||||
pipFailed: "フローティングウィンドウを開けませんでした。もう一度お試しください。",
|
||||
|
||||
captureScreenshot: "スクリーンショットを取得",
|
||||
navigationIncomplete: "ページの読み込みが指定の段階に達しませんでした。現在のページを確認してください。",
|
||||
noEntries: "記録はありません。",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
export default {
|
||||
localBrowser: {
|
||||
pipOpen: "미리보기 팝업 열기",
|
||||
pipReturn: "대화 내 미리보기로 돌아가기",
|
||||
pipFailed: "플로팅 창을 열 수 없습니다. 다시 시도해 주세요.",
|
||||
|
||||
captureScreenshot: "스크린샷 캡처",
|
||||
navigationIncomplete: "페이지가 요청한 로드 단계에 도달하지 못했습니다. 현재 페이지를 확인하세요.",
|
||||
noEntries: "반환된 기록이 없습니다.",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
export default {
|
||||
localBrowser: {
|
||||
pipOpen: "Открыть плавающее окно",
|
||||
pipReturn: "Вернуть предпросмотр в чат",
|
||||
pipFailed: "Не удалось открыть плавающее окно. Повторите попытку.",
|
||||
|
||||
captureScreenshot: "Сделать снимок страницы",
|
||||
navigationIncomplete: "Страница не достигла нужного этапа загрузки. Проверьте её состояние.",
|
||||
noEntries: "Записи отсутствуют.",
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
export default {
|
||||
localBrowser: {
|
||||
pipOpen: "弹出悬浮窗",
|
||||
pipReturn: "返回对话小窗",
|
||||
pipFailed: "无法打开悬浮窗,请重试。",
|
||||
|
||||
captureScreenshot: "截取网页画面",
|
||||
navigationIncomplete: "导航未达到目标加载阶段,请检查当前页面。",
|
||||
noEntries: "没有返回记录。",
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
<template>
|
||||
<aside v-if="status.selected" ref="previewElement" class="browser-task-preview" :class="{ 'is-dragging': dragging }" :style="positionStyle" :aria-label="t('localBrowser.preview')">
|
||||
<div class="preview-heading" @pointerdown="startDrag" @pointermove="moveDrag" @pointerup="stopDrag" @pointercancel="stopDrag" @lostpointercapture="stopDrag"><BrowserIcon class="preview-browser-icon" width="20" height="20" /><strong>{{ t('localBrowser.local') }}</strong><span>{{ t(!status.connected ? 'localBrowser.offline' : status.stopping ? 'localBrowser.stopping' : status.paused ? 'localBrowser.paused' : status.needs_help ? 'localBrowser.needHelp' : status.task_id ? 'localBrowser.connected' : 'localBrowser.waiting') }}</span></div>
|
||||
<Teleport :to="pipTarget || 'body'" :disabled="!pipTarget">
|
||||
<aside v-if="status.selected" ref="previewElement" class="browser-task-preview" :class="{ 'is-dragging': dragging, 'is-pip': !!pipTarget }" :style="pipTarget ? {} : positionStyle" :aria-label="t('localBrowser.preview')">
|
||||
<div class="preview-heading" @pointerdown="!pipTarget && startDrag($event)" @pointermove="moveDrag" @pointerup="stopDrag" @pointercancel="stopDrag" @lostpointercapture="stopDrag"><BrowserIcon class="preview-browser-icon" width="20" height="20" /><strong>{{ t('localBrowser.local') }}</strong><span>{{ t(!status.connected ? 'localBrowser.offline' : status.stopping ? 'localBrowser.stopping' : status.paused ? 'localBrowser.paused' : status.needs_help ? 'localBrowser.needHelp' : status.task_id ? 'localBrowser.connected' : 'localBrowser.waiting') }}</span>
|
||||
<button v-if="pipSupported" class="preview-popout" :disabled="pipOpening" :title="t(pipTarget ? 'localBrowser.pipReturn' : 'localBrowser.pipOpen')" :aria-label="t(pipTarget ? 'localBrowser.pipReturn' : 'localBrowser.pipOpen')" @pointerdown.stop @click="togglePictureInPicture"><t-icon :name="pipTarget ? 'fullscreen-exit' : 'fullscreen'" size="16px" /></button>
|
||||
</div>
|
||||
<button class="preview-image" :disabled="!status.connected || !status.task_id || busy || status.stopping" :aria-label="t('localBrowser.locateWindow')" @click="act('focus')">
|
||||
<img v-if="preview" :src="preview" :alt="t('localBrowser.preview')" />
|
||||
<span v-else>{{ t(status.connected ? 'localBrowser.waiting' : 'localBrowser.reconnectShort') }}</span>
|
||||
|
|
@ -11,33 +14,50 @@
|
|||
<p v-if="status.last_error" class="preview-error">{{ status.last_error }}</p>
|
||||
<p class="preview-sync" role="status">{{ t(!status.connected ? 'localBrowser.reconnectShort' : status.idle ? 'localBrowser.previewIdle' : previewStale ? 'localBrowser.previewStale' : preview ? 'localBrowser.previewLive' : 'localBrowser.previewLoading') }}</p>
|
||||
<p v-if="status.needs_help" class="preview-help"><span v-if="status.help_prompt">{{ status.help_prompt }}<br /></span>{{ t('localBrowser.helpHint') }}</p>
|
||||
<p v-if="pipFailed" class="preview-error" role="alert">{{ t('localBrowser.pipFailed') }}</p>
|
||||
<p v-if="error" class="preview-error" role="alert">{{ error }}</p>
|
||||
<p class="preview-scope">{{ t('localBrowser.controlScope') }}</p>
|
||||
<div class="preview-actions">
|
||||
<t-button v-if="status.connected" :title="t(status.paused ? 'localBrowser.resume' : 'localBrowser.pauseHint')" size="small" theme="default" variant="text" :disabled="busy || status.stopping" @click="act(status.paused ? 'resume' : 'pause')">{{ t(status.paused ? 'localBrowser.resume' : 'localBrowser.pause') }}</t-button>
|
||||
<t-button v-else size="small" theme="default" variant="text" @click="uiStore.openSettings('browserconnection')">{{ t('localBrowser.settingsTitle') }}</t-button>
|
||||
<t-button v-else size="small" theme="default" variant="text" @click="openBrowserSettings">{{ t('localBrowser.settingsTitle') }}</t-button>
|
||||
<t-button :title="t('localBrowser.stopHint')" size="small" theme="default" variant="text" :disabled="busy || status.stopping" @click="act('stop')">{{ t('localBrowser.stop') }}</t-button>
|
||||
</div>
|
||||
</aside>
|
||||
</Teleport>
|
||||
</template>
|
||||
<script setup lang="ts">
|
||||
import { onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { computed, onBeforeUnmount, onMounted, ref, watch } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { get, post } from '@/utils/request'
|
||||
import { useUIStore } from '@/stores/ui'
|
||||
import { browserActionLabel, browserPageAddress } from '@/utils/browserToolDisplay'
|
||||
import BrowserIcon from '@/components/icons/BrowserIcon.vue'
|
||||
import { useFloatingPreviewDrag } from '@/composables/useFloatingPreviewDrag'
|
||||
const previewElement = ref<HTMLElement | null>(null)
|
||||
const { positionStyle, dragging, startDrag, moveDrag, stopDrag } = useFloatingPreviewDrag(previewElement)
|
||||
import { useDocumentPictureInPicture } from '@/composables/useDocumentPictureInPicture'
|
||||
const props = defineProps<{ sessionId: string }>()
|
||||
const { t } = useI18n(), uiStore = useUIStore()
|
||||
const status = ref({ enabled: false, selected: false, connected: false, paused: false, idle: false, needs_help: false, help_prompt: '', task_id: '', action: '', action_elapsed_ms: 0, page_url: '', last_error: '', stopping: false })
|
||||
const busy = ref(false), error = ref(''), preview = ref(''), previewStale = ref(false)
|
||||
const { supported: pipSupported, target: pipTarget, opening: pipOpening, open: openPiP, close: closePiP } = useDocumentPictureInPicture(computed(() => status.value.selected), () => t('localBrowser.preview'))
|
||||
const previewElement = ref<HTMLElement | null>(null)
|
||||
const { positionStyle, dragging, startDrag, moveDrag, stopDrag } = useFloatingPreviewDrag(computed(() => pipTarget.value ? null : previewElement.value))
|
||||
const pipFailed = ref(false)
|
||||
async function togglePictureInPicture() {
|
||||
pipFailed.value = false
|
||||
if (pipTarget.value) { closePiP(); window.focus(); return }
|
||||
try { await openPiP() }
|
||||
catch { if (alive) pipFailed.value = true }
|
||||
}
|
||||
function openBrowserSettings() {
|
||||
closePiP()
|
||||
window.focus()
|
||||
uiStore.openSettings('browserconnection')
|
||||
}
|
||||
|
||||
let lastFrame = 0
|
||||
const endpoint = `/api/v1/sessions/${encodeURIComponent(props.sessionId)}/local-browser`
|
||||
const controller = new AbortController()
|
||||
let alive = true, timer: ReturnType<typeof setTimeout> | undefined, revision = 0
|
||||
let alive = true, cancelTimer: (() => void) | undefined, revision = 0
|
||||
async function act(action: string) {
|
||||
if (busy.value) return
|
||||
busy.value = true; error.value = ''; revision++
|
||||
|
|
@ -52,7 +72,7 @@ async function poll() {
|
|||
if (polling || !alive) return
|
||||
polling = true
|
||||
try {
|
||||
if (!busy.value && !document.hidden) {
|
||||
if (!busy.value && (!document.hidden || pipTarget.value)) {
|
||||
const current = revision
|
||||
const result = await get<{ data: typeof status.value }>(endpoint, { signal: controller.signal })
|
||||
if (!alive || current !== revision) return
|
||||
|
|
@ -64,11 +84,21 @@ async function poll() {
|
|||
}
|
||||
}
|
||||
} catch { /* Background polling does not replace explicit action errors. */ }
|
||||
finally { polling = false; if (alive) { previewStale.value = !!preview.value && Date.now() - lastFrame > 5000; timer = setTimeout(poll, !status.value.enabled ? 30000 : status.value.selected && !status.value.idle ? 1000 : 5000) } }
|
||||
finally {
|
||||
polling = false
|
||||
if (alive) {
|
||||
previewStale.value = !!preview.value && Date.now() - lastFrame > 5000
|
||||
// Schedule in the visible PiP document when the conversation is in the background.
|
||||
const timerWindow = pipTarget.value?.ownerDocument.defaultView || window
|
||||
const timer = timerWindow.setTimeout(poll, !status.value.enabled ? 30000 : status.value.selected && !status.value.idle ? 1000 : 5000)
|
||||
cancelTimer = () => timerWindow.clearTimeout(timer)
|
||||
}
|
||||
}
|
||||
}
|
||||
const onVisible = () => { if (!document.hidden) { clearTimeout(timer); void poll() } }
|
||||
const onVisible = () => { cancelTimer?.(); if (!document.hidden || pipTarget.value) void poll() }
|
||||
watch(pipTarget, onVisible, { flush: 'post' })
|
||||
onMounted(() => { document.addEventListener('visibilitychange', onVisible); void poll() })
|
||||
onBeforeUnmount(() => { alive = false; document.removeEventListener('visibilitychange', onVisible); revision++; clearTimeout(timer); controller.abort(); preview.value = '' })
|
||||
onBeforeUnmount(() => { alive = false; document.removeEventListener('visibilitychange', onVisible); revision++; cancelTimer?.(); controller.abort(); preview.value = '' })
|
||||
</script>
|
||||
<style scoped>
|
||||
.browser-task-preview { position: absolute; right: 20px; bottom: 16px; width: 240px; max-width: calc(100% - 40px); max-height: calc(100% - 24px); box-sizing: border-box; z-index: 5; overflow: auto; background: var(--td-bg-color-container); border: 1px solid var(--td-component-border); border-radius: 12px; box-shadow: 0 4px 20px #0000000d; }
|
||||
|
|
@ -80,4 +110,11 @@ onBeforeUnmount(() => { alive = false; document.removeEventListener('visibilityc
|
|||
.preview-help { color: var(--td-brand-color); }
|
||||
.preview-actions { display: flex; flex-wrap: wrap; gap: 4px; justify-content: space-between; padding: 5px 8px; }.preview-error { margin: 8px 12px; color: var(--td-error-color); font-size: 12px; line-height: 1.5; }
|
||||
@media(max-width:720px){.browser-task-preview { right: 12px; bottom: 12px; width: 200px; }.preview-image { height: 100px; }}
|
||||
.preview-popout { display: grid; place-items: center; flex-shrink: 0; padding: 3px; border: 0; border-radius: 4px; background: transparent; color: var(--td-text-color-secondary); cursor: pointer; }
|
||||
.preview-popout:hover { background: var(--td-bg-color-secondarycontainer); color: var(--td-brand-color); }
|
||||
.preview-popout:focus-visible { outline: 2px solid var(--td-brand-color); }
|
||||
.preview-popout:disabled { opacity: .5; cursor: wait; }
|
||||
.browser-task-preview.is-pip { position: static; width: 100%; max-width: none; min-height: 100%; max-height: none; border: 0; border-radius: 0; box-shadow: none; }
|
||||
.is-pip .preview-heading { cursor: default; }
|
||||
.is-pip .preview-image { height: clamp(126px, 45vh, 480px); }
|
||||
</style>
|
||||
|
|
|
|||
Loading…
Reference in New Issue