diff --git a/CHANGELOG.md b/CHANGELOG.md index d71a1916..9c22a801 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,26 @@ All notable changes to **BotArk** (formerly BotHub) are documented in this file. +## [0.18.0] - 2026-11-30 + +### Added + +- **Portable packages and portable data directory** (#87): added a Windows `portable` target (`BotArk-Portable--x64.exe`) alongside the NSIS installer. Startup resolves the data directory in order of `--user-data-dir=`, `PORTABLE_EXECUTABLE_DIR`, or a sibling `BotArkData` folder / `.botark-portable` marker (next to the executable on Windows/Linux, or next to `BotArk.app` on macOS). Portable mode skips the legacy `BotHub` migration, creates missing directories, and falls back to the default `userData` with a warning when the location is read-only. + +### Changed + +- **Smaller production bundles and on-demand inspector**: enabled `build.minify` for Electron main, preload, and renderer (`electron-vite` defaults to unminified output), cutting total JS from 5.06 MB to 2.65 MB. Lazy-loaded the right-side `InfoPanel` and its platform inspectors on first open, reducing the renderer entry chunk from 2,048.81 kB to 729.07 kB. +- **Incremental Markdown streaming**: `MarkdownText` caches completed blocks separated by blank lines outside fenced code blocks in a bounded, locale- and handler-aware cache, so streaming appends only re-parse the trailing block instead of the full reply on every chunk. Stabilized `MessageBubble` link callbacks so memoized bubbles skip re-parsing and subtree reconciliation across unrelated renders. In 5 interleaved A/B pairs (`node scripts/bench/compare.mjs`), parser-only time for 80 incremental renders of a 30-section report dropped from 8.73 ms to 3.67 ms (-58.0%), and 40 full re-renders dropped from 26.20 ms to 20.78 ms (-20.7%). +- **Debounced collaboration room persistence**: room updates use the 350 ms debounced, lazy-serialized storage path already used by direct chats, flush on `pagehide`, and cancel queued writes when clearing saved data. + +### Fixed + +- **Grok Connect stream framing and memory bounds**: `WatchGrokBotTranscripts` rejects frame headers above 4 MiB immediately and reassembles fragmented frames with one copy per completed frame instead of concatenating the buffer on every read. In interleaved A/B sampling, median decode time for a 2 MiB frame delivered in 1 KiB chunks dropped from 110.84 ms to 26.91 ms (-75.7%). +- **Grok background watch cursor growth**: removed roster agents and conversations now drop their stale cursors without dropping incremental watch registrations from sending messages, listing agents, or reading transcripts, and standalone session pins keep only the latest viewed session per agent. +- **DS Bot duplicate relay connections**: concurrent relay connects share one in-flight connection, preventing leaked WebSockets and duplicated stream deltas across `ensureRelayClient` and connection probes. +- **MCP slow tool discovery**: the connect timeout is cleared as soon as the transport connects, so servers that connect quickly but take longer to finish paginated `tools/list` are no longer torn down prematurely. +- **Non-blocking macOS signature check**: replaced the synchronous `spawnSync` `codesign` probe (up to 3.5 s on the main thread) with a single-flight async `spawn` shared by the security vault status and auto-updater. + ## [0.17.1] - 2026-11-28 ### Changed diff --git a/README.md b/README.md index f9923323..6f32015f 100644 --- a/README.md +++ b/README.md @@ -217,8 +217,17 @@ Download the latest installer from [**GitHub Releases**](https://github.com/qyba | **macOS (Apple Silicon M1–M4)** | `BotArk--arm64.dmg` | ✅ **Apple Developer ID signed & notarized** — drag into `Applications` and open directly | | **macOS (Intel x64)** | `BotArk--x64.dmg` | ✅ **Apple Developer ID signed & notarized** — no Gatekeeper prompts | | **Windows 10 / 11 (64-bit)** | `BotArk-Setup--x64.exe` | One-click NSIS installer (preserves local data across upgrades) | +| **Windows 10 / 11 Portable (64-bit)** | `BotArk-Portable--x64.exe` | No installer; stores all data in `BotArkData` beside the `.exe` | | **Android 8.0+** | `BotArk--android.apk` | Signed universal APK — standalone mode + LAN QR sync | +#### Portable mode + +- On **Windows**, run `BotArk-Portable--x64.exe` from any writable folder or USB drive. BotArk creates `BotArkData` beside the `.exe` and stores all accounts, sessions, and settings there. +- On **macOS**, unzip `BotArk--arm64.zip` or `BotArk--x64.zip` to a writable folder or USB drive. Create an empty `BotArkData` folder or an empty `.botark-portable` file in the same folder as `BotArk.app`, then open `BotArk.app`. +- To pick a custom data directory on any platform, launch BotArk with `--user-data-dir=`. This flag overrides portable mode and the legacy `BotHub` migration. + +If the portable location is read-only, BotArk logs a warning and falls back to the default `userData` directory instead of crashing at startup. + ### 2. Add Your First Agent or Room 1. Press **`⌘N` / `Ctrl+N`** (or click **`+`** at the top-left) to connect any of the 6 platforms or launch a **Multi-Agent Collaboration Room**. diff --git a/android/BotArk/app/build.gradle.kts b/android/BotArk/app/build.gradle.kts index d7e7bb2f..281e2778 100644 --- a/android/BotArk/app/build.gradle.kts +++ b/android/BotArk/app/build.gradle.kts @@ -13,8 +13,8 @@ android { applicationId = "com.qybaihe.botark" minSdk = 26 targetSdk = 35 - versionCode = 18 - versionName = "0.17.1" + versionCode = 19 + versionName = "0.18.0" testInstrumentationRunner = "androidx.test.runner.AndroidJUnitRunner" } diff --git a/docs/readme/README_zh.md b/docs/readme/README_zh.md index 84f4c046..2d2cf0ba 100644 --- a/docs/readme/README_zh.md +++ b/docs/readme/README_zh.md @@ -210,8 +210,17 @@ BotArk 直接对接各平台原生通信协议,右侧操作台(`⌘I`)会 | **macOS(Apple 芯片 M1–M4)** | `BotArk-<版本号>-arm64.dmg` | ✅ **Apple Developer ID 签名与官方公证**,拖入「应用程序」双击直开,无拦截提示 | | **macOS(Intel 芯片)** | `BotArk-<版本号>-x64.dmg` | ✅ **Apple Developer ID 签名与官方公证**,安装即用 | | **Windows 10 / 11(64 位)** | `BotArk-Setup-<版本号>-x64.exe` | NSIS 一键安装向导(版本升级自动保留本地账号数据) | +| **Windows 10 / 11 便携版(64 位)** | `BotArk-Portable-<版本号>-x64.exe` | 免安装,账号、会话与设置全部保存在同目录的 `BotArkData` 文件夹 | | **Android 8.0+** | `BotArk-<版本号>-android.apk` | 官方签名安装包,支持独立直连与桌面端扫码同步 | +#### 便携模式 + +- 在 **Windows** 上,将 `BotArk-Portable-<版本号>-x64.exe` 放到任意可写文件夹或 U 盘直接运行。程序会在 `.exe` 同目录自动创建 `BotArkData`,所有账号、会话与设置都保存在其中。 +- 在 **macOS** 上,将 `BotArk-<版本号>-arm64.zip` 或 `BotArk-<版本号>-x64.zip` 解压到可写文件夹或 U 盘,在 `BotArk.app` 同级目录新建空的 `BotArkData` 文件夹(或空的 `.botark-portable` 文件),再打开 `BotArk.app`。 +- 如需手动指定数据目录,可在启动时添加 `--user-data-dir=<路径>` 参数,该参数的优先级高于便携模式与旧版 `BotHub` 数据迁移。 + +若便携目录为只读(例如只读镜像),BotArk 会输出警告并回退到默认 `userData` 目录,不会在启动时崩溃。 + ### 2. 添加首个账号或组建协作室 1. 按 **`⌘N` / `Ctrl+N`**(或点击侧边栏左上角 **`+`**)接入六大平台账号,或一键创建**多 Agent 协作室**;如需批量导入或配置代理池,打开左下角 **「设置与账号」**。 diff --git a/electron.vite.config.ts b/electron.vite.config.ts index 015c702e..347be122 100644 --- a/electron.vite.config.ts +++ b/electron.vite.config.ts @@ -3,13 +3,16 @@ import { rendererAlias, rendererPlugins, sharedAlias } from './vite.shared.mts' export default defineConfig({ main: { - resolve: { alias: sharedAlias } + resolve: { alias: sharedAlias }, + build: { minify: true } }, preload: { - resolve: { alias: sharedAlias } + resolve: { alias: sharedAlias }, + build: { minify: true } }, renderer: { resolve: { alias: rendererAlias }, - plugins: rendererPlugins() + plugins: rendererPlugins(), + build: { minify: true } } }) diff --git a/ios/BotArk/BotArk.xcodeproj/project.pbxproj b/ios/BotArk/BotArk.xcodeproj/project.pbxproj index 99129eb7..9179bab6 100644 --- a/ios/BotArk/BotArk.xcodeproj/project.pbxproj +++ b/ios/BotArk/BotArk.xcodeproj/project.pbxproj @@ -380,7 +380,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 13; + CURRENT_PROJECT_VERSION = 14; DEBUG_INFORMATION_FORMAT = dwarf; ENABLE_STRICT_OBJC_MSGSEND = YES; ENABLE_TESTABILITY = YES; @@ -399,7 +399,7 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 17.0; - MARKETING_VERSION = 0.17.1; + MARKETING_VERSION = 0.18.0; MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE; MTL_FAST_MATH = YES; ONLY_ACTIVE_ARCH = YES; @@ -447,7 +447,7 @@ CLANG_WARN_UNREACHABLE_CODE = YES; CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; COPY_PHASE_STRIP = NO; - CURRENT_PROJECT_VERSION = 13; + CURRENT_PROJECT_VERSION = 14; DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; ENABLE_NS_ASSERTIONS = NO; ENABLE_STRICT_OBJC_MSGSEND = YES; @@ -460,7 +460,7 @@ GCC_WARN_UNUSED_FUNCTION = YES; GCC_WARN_UNUSED_VARIABLE = YES; IPHONEOS_DEPLOYMENT_TARGET = 17.0; - MARKETING_VERSION = 0.17.1; + MARKETING_VERSION = 0.18.0; MTL_ENABLE_DEBUG_INFO = NO; MTL_FAST_MATH = YES; PRODUCT_NAME = "$(TARGET_NAME)"; diff --git a/ios/BotArk/project.yml b/ios/BotArk/project.yml index 733e731a..f95c87a6 100644 --- a/ios/BotArk/project.yml +++ b/ios/BotArk/project.yml @@ -10,8 +10,8 @@ settings: base: SWIFT_VERSION: "5.9" IPHONEOS_DEPLOYMENT_TARGET: "17.0" - MARKETING_VERSION: "0.17.1" - CURRENT_PROJECT_VERSION: "13" + MARKETING_VERSION: "0.18.0" + CURRENT_PROJECT_VERSION: "14" PRODUCT_NAME: "$(TARGET_NAME)" TARGETED_DEVICE_FAMILY: "1,2" SUPPORTS_MAC_DESIGNED_FOR_IPHONE_IPAD: NO diff --git a/package-lock.json b/package-lock.json index 3c7990d6..d7b1cd81 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "botark", - "version": "0.17.1", + "version": "0.18.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "botark", - "version": "0.17.1", + "version": "0.18.0", "hasInstallScript": true, "license": "MIT", "dependencies": { diff --git a/package.json b/package.json index d4081dd4..18179c15 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "botark", - "version": "0.17.1", + "version": "0.18.0", "goxfBuild": 15, "private": false, "description": "BotArk — all your personal AI agents in one native desktop workspace", diff --git a/scripts/bench/compare.mjs b/scripts/bench/compare.mjs new file mode 100644 index 00000000..219f38e3 --- /dev/null +++ b/scripts/bench/compare.mjs @@ -0,0 +1,69 @@ +import { execFileSync } from 'node:child_process' +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { loadavg } from 'node:os' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..') +const baselineDir = resolve(process.argv[2] || resolve(root, '.worktrees/baseline')) +const rounds = Math.max(1, Number(process.env.BOTARK_AB_ROUNDS || 5)) +const outDir = resolve(root, '.cache/bench') +mkdirSync(outDir, { recursive: true }) + +function sample(cwd, tag) { + const resultsFile = resolve(cwd, `.cache/bench/ab-${tag}.jsonl`) + mkdirSync(dirname(resultsFile), { recursive: true }) + if (existsSync(resultsFile)) rmSync(resultsFile) + execFileSync( + process.execPath, + [resolve(root, 'node_modules/vitest/vitest.mjs'), 'run', '--config', 'scripts/bench/vitest.config.mts'], + { cwd, env: { ...process.env, NODE_ENV: 'production', BOTARK_BENCH_RESULTS: resultsFile }, stdio: ['ignore', 'pipe', 'pipe'] } + ) + return readFileSync(resultsFile, 'utf8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line)) +} + +const median = (xs) => { + const sorted = [...xs].sort((a, b) => a - b) + const mid = Math.floor(sorted.length / 2) + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2 +} + +const series = new Map() +let errors = 0 +for (let round = 0; round < rounds; round++) { + for (const [side, dir] of [['before', baselineDir], ['after', root]]) { + for (const row of sample(dir, side)) { + errors += row.errors + const key = `${row.metric}:${side}` + if (!series.has(key)) series.set(key, { values: [], work: row.work }) + series.get(key).values.push(row.valueMs) + } + } + console.log(`completed round ${round + 1}/${rounds}`) +} + +const metrics = [...new Set([...series.keys()].map((k) => k.replace(/:(before|after)$/, '')))] +const lines = [ + '# Interleaved A/B benchmark report', + '', + `- Before: \`${execFileSync('git', ['-C', baselineDir, 'rev-parse', '--short', 'HEAD'], { encoding: 'utf8' }).trim()}\``, + `- After: \`${execFileSync('git', ['rev-parse', '--short', 'HEAD'], { cwd: root, encoding: 'utf8' }).trim()}\``, + `- Rounds: ${rounds} alternating A/B pairs (NODE_ENV=production), errors: ${errors}`, + `- Host load average during run: ${loadavg().map((n) => n.toFixed(2)).join(', ')}`, + '', + '| Metric | Before median ms (range) | After median ms (range) | Delta |', + '| :--- | ---: | ---: | ---: |' +] +for (const metric of metrics) { + const before = series.get(`${metric}:before`) + const after = series.get(`${metric}:after`) + const bMed = median(before.values) + const aMed = median(after.values) + const delta = ((aMed - bMed) / bMed) * 100 + const fmt = (s) => `${median(s.values).toFixed(2)} (${Math.min(...s.values).toFixed(2)}..${Math.max(...s.values).toFixed(2)})` + lines.push(`| \`${metric}\` | ${fmt(before)} | ${fmt(after)} | ${delta >= 0 ? '+' : ''}${delta.toFixed(1)}% |`) + console.log(`${metric}: ${fmt(before)} -> ${fmt(after)} (${delta.toFixed(1)}%)`) +} +const report = lines.join('\n') + '\n' +writeFileSync(resolve(outDir, 'ab-report.md'), report) +if (errors > 0) process.exit(1) diff --git a/scripts/bench/perf.bench.test.tsx b/scripts/bench/perf.bench.test.tsx new file mode 100644 index 00000000..259a78c3 --- /dev/null +++ b/scripts/bench/perf.bench.test.tsx @@ -0,0 +1,178 @@ +import { performance } from 'node:perf_hooks' +import { appendFileSync, mkdirSync } from 'node:fs' +import { dirname, resolve } from 'node:path' +import { expect, it } from 'vitest' +import { renderToStaticMarkup } from 'react-dom/server' +import { MarkdownText } from '@/components/chat/MarkdownText' +import { GrokConnectClient } from '@main/grok/connectClient' + +const RESULTS_FILE = process.env.BOTARK_BENCH_RESULTS || resolve('.cache/bench/results.jsonl') + +function record(metric: string, valueMs: number, work: number, errors: number, extra?: Record) { + mkdirSync(dirname(RESULTS_FILE), { recursive: true }) + appendFileSync(RESULTS_FILE, JSON.stringify({ metric, valueMs, work, errors, ...extra }) + '\n') +} + +function encodeFrame(flags: number, value: unknown): Buffer { + const payload = Buffer.from(JSON.stringify(value), 'utf8') + const out = Buffer.alloc(5 + payload.length) + out[0] = flags + out.writeUInt32BE(payload.length, 1) + payload.copy(out, 5) + return out +} + +function buildMarkdownReport(sections: number): string { + const parts: string[] = [] + for (let i = 0; i < sections; i++) { + parts.push( + `## Section ${i}: Architecture & Protocol Review`, + '', + `This paragraph reviews **adapter ${i}** with \`inlineCode(${i})\`, a [reference](https://example.com/doc/${i}), and ~~deprecated~~ notes.`, + '', + `- [x] Verify envelope framing for session ${i}`, + `- [ ] Check reconnect backoff and timeout handling`, + `- Stream chunk ordering & idempotency key ${i}`, + '', + '| Platform | Status | Latency |', + '| :--- | :--- | ---: |', + `| Grok Bot | online | ${12 + i} ms |`, + `| Hermes | streaming | ${20 + i} ms |`, + '', + '```ts', + `export function checkSession${i}(id: string): boolean {`, + ` return id.length > 0 && id.startsWith('sess_')`, + `}`, + '```', + '' + ) + } + return parts.join('\n') +} + +it('bench: streams a Markdown report across 80 incremental renders', () => { + const full = buildMarkdownReport(30) + const steps = 80 + let errors = 0 + let lastHtml = '' + const start = performance.now() + for (let step = 1; step <= steps; step++) { + const slice = full.slice(0, Math.floor((full.length * step) / steps)) + try { + lastHtml = renderToStaticMarkup() + } catch { + errors++ + } + } + const elapsed = performance.now() - start + expect(errors).toBe(0) + expect(lastHtml).toContain('checkSession29') + expect(lastHtml).toContain(' { + const full = buildMarkdownReport(30) + let errors = 0 + let lastHtml = '' + const start = performance.now() + for (let i = 0; i < 40; i++) { + try { + lastHtml = renderToStaticMarkup() + } catch { + errors++ + } + } + const elapsed = performance.now() - start + expect(errors).toBe(0) + expect(lastHtml).toContain('checkSession29') + record('markdown_rerender_40x_ms', elapsed, full.length * 40, errors, { bytes: full.length, renders: 40 }) +}) + +it('bench: reassembles a 2 MiB Connect frame from 1 KiB chunks', async () => { + const payload = Buffer.from(JSON.stringify({ data: 'A'.repeat(2 * 1024 * 1024) }), 'utf8') + const wire = Buffer.alloc(5 + payload.length) + wire.writeUInt32BE(payload.length, 1) + payload.copy(wire, 5) + const trailer = encodeFrame(0x02, {}) + const full = Buffer.concat([wire, trailer]) + + const client = new GrokConnectClient({ + auth: { accessToken: 'bench-token' }, + fetchImpl: async () => new Response(new ReadableStream({ + start(controller) { + for (let offset = 0; offset < full.length; offset += 1024) { + controller.enqueue(full.subarray(offset, Math.min(offset + 1024, full.length))) + } + controller.close() + } + }), { status: 200 }) + }) + + let bytes = 0 + let errors = 0 + const start = performance.now() + try { + for await (const frame of client.watchTranscripts({ cursors: [] })) { + bytes += JSON.stringify(frame).length + } + } catch { + errors++ + } + const elapsed = performance.now() - start + expect(errors).toBe(0) + expect(bytes).toBeGreaterThan(2 * 1024 * 1024) + record('connect_2mib_frame_ms', elapsed, full.length, errors, { wireBytes: full.length }) +}) + +it('bench: decodes 300 Connect frames delivered in 1 KiB TCP chunks', async () => { + const frames: Buffer[] = [] + for (let i = 0; i < 300; i++) { + frames.push(encodeFrame(0x00, { + rows: { + agentId: 'agent-bench', + generation: 1, + entries: [{ + entryId: `entry-${i}`, + seq: String(i + 1), + updatedSeq: String(i + 1), + kind: 'send-message', + role: 'assistant', + content: `Reply ${i}: `.padEnd(1800, 'x') + }] + } + })) + } + frames.push(encodeFrame(0x02, {})) + const wire = Buffer.concat(frames) + const chunks: Uint8Array[] = [] + for (let offset = 0; offset < wire.length; offset += 1024) { + chunks.push(wire.subarray(offset, Math.min(offset + 1024, wire.length))) + } + + const client = new GrokConnectClient({ + auth: { accessToken: 'bench-token' }, + fetchImpl: async () => new Response(new ReadableStream({ + start(controller) { + for (const chunk of chunks) controller.enqueue(chunk) + controller.close() + } + }), { status: 200 }) + }) + + let count = 0 + let errors = 0 + const start = performance.now() + try { + for await (const frame of client.watchTranscripts({ cursors: [{ agent_id: 'agent-bench' }] })) { + const rows = frame['rows'] as { entries?: unknown[] } | undefined + if (rows?.entries?.length) count++ + } + } catch { + errors++ + } + const elapsed = performance.now() - start + expect(errors).toBe(0) + expect(count).toBe(300) + record('connect_stream_300_frames_ms', elapsed, wire.length, errors, { frames: count, wireBytes: wire.length }) +}) diff --git a/scripts/bench/run.mjs b/scripts/bench/run.mjs new file mode 100644 index 00000000..c3d50bce --- /dev/null +++ b/scripts/bench/run.mjs @@ -0,0 +1,64 @@ +import { execFileSync } from 'node:child_process' +import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { dirname, resolve } from 'node:path' +import { fileURLToPath } from 'node:url' + +const root = resolve(dirname(fileURLToPath(import.meta.url)), '../..') +const runs = Math.max(1, Number(process.env.BOTARK_BENCH_RUNS || 5)) +const resultsFile = resolve(root, '.cache/bench/results.jsonl') +const summaryFile = resolve(root, '.cache/bench/summary.json') +mkdirSync(dirname(resultsFile), { recursive: true }) + +const samples = new Map() +let totalErrors = 0 +let totalWork = 0 + +for (let run = 0; run < runs; run++) { + if (existsSync(resultsFile)) rmSync(resultsFile) + try { + execFileSync( + process.execPath, + [resolve(root, 'node_modules/vitest/vitest.mjs'), 'run', '--config', 'scripts/bench/vitest.config.mts'], + { + cwd: root, + env: { ...process.env, NODE_ENV: 'production', BOTARK_BENCH_RESULTS: resultsFile }, + stdio: ['ignore', 'pipe', 'pipe'] + } + ) + } catch (error) { + process.stderr.write(error.stdout?.toString() ?? '') + process.stderr.write(error.stderr?.toString() ?? '') + process.exit(1) + } + const lines = readFileSync(resultsFile, 'utf8').trim().split('\n').filter(Boolean).map((line) => JSON.parse(line)) + for (const row of lines) { + totalErrors += row.errors + if (!samples.has(row.metric)) samples.set(row.metric, { values: [], work: row.work }) + samples.get(row.metric).values.push(row.valueMs) + } +} + +const median = (xs) => { + const sorted = [...xs].sort((a, b) => a - b) + const mid = Math.floor(sorted.length / 2) + return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2 +} + +const summary = {} +for (const [metric, { values, work }] of samples) { + const med = median(values) + summary[metric] = { + medianMs: Number(med.toFixed(3)), + minMs: Number(Math.min(...values).toFixed(3)), + maxMs: Number(Math.max(...values).toFixed(3)), + runs: values.length, + work + } + totalWork += work + console.log(`${metric}: median ${med.toFixed(2)} ms (range ${Math.min(...values).toFixed(2)}..${Math.max(...values).toFixed(2)} ms, n=${values.length})`) +} +writeFileSync(summaryFile, JSON.stringify({ errors: totalErrors, summary }, null, 2) + '\n') + +const primary = summary.markdown_stream_80_steps_ms?.medianMs ?? 0 +console.log(JSON.stringify({ value: primary, errors: totalErrors, work: totalWork })) +if (totalErrors > 0) process.exit(1) diff --git a/scripts/bench/vitest.config.mts b/scripts/bench/vitest.config.mts new file mode 100644 index 00000000..6318627b --- /dev/null +++ b/scripts/bench/vitest.config.mts @@ -0,0 +1,18 @@ +import { resolve } from 'node:path' +import { defineConfig } from 'vitest/config' +import { rendererAlias } from '../../vite.shared.mts' + +export default defineConfig({ + resolve: { + alias: { + ...rendererAlias, + '@main': resolve('src/main') + } + }, + test: { + include: ['scripts/bench/**/*.bench.test.{ts,tsx}'], + environment: 'node', + testTimeout: 60_000, + hookTimeout: 60_000 + } +}) diff --git a/scripts/smoke/electron-smoke.mjs b/scripts/smoke/electron-smoke.mjs new file mode 100644 index 00000000..ce0fb9ae --- /dev/null +++ b/scripts/smoke/electron-smoke.mjs @@ -0,0 +1,157 @@ +import { spawn } from 'node:child_process' +import { existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs' +import { createRequire } from 'node:module' +import { resolve } from 'node:path' +import { pathToFileURL } from 'node:url' +import WebSocket from 'ws' + +const require = createRequire(import.meta.url) +const electronBin = require('electron') +const root = resolve(import.meta.dirname, '../..') +const profile = resolve(root, `.cache/smoke-profile-${process.pid}`) +mkdirSync(profile, { recursive: true }) + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)) + +async function waitFor(fn, timeoutMs, label) { + const start = Date.now() + while (Date.now() - start < timeoutMs) { + const value = await fn() + if (value) return value + await sleep(100) + } + throw new Error(`Timed out waiting for ${label}`) +} + +const { ELECTRON_RUN_AS_NODE: _runAsNode, ...cleanEnv } = process.env +const child = spawn(electronBin, [ + '.', + `--user-data-dir=${profile}`, + '--remote-debugging-port=0', + '--no-sandbox' +], { cwd: root, env: cleanEnv, stdio: ['ignore', 'pipe', 'pipe'] }) + +let stderr = '' +child.stderr.on('data', (b) => { stderr += String(b) }) + +let ws +let msgId = 0 +const pending = new Map() +const exceptions = [] +const consoleErrors = [] +const loadedScripts = new Set() + +function send(method, params = {}) { + const id = ++msgId + return new Promise((resolveSend, rejectSend) => { + pending.set(id, { resolveSend, rejectSend }) + ws.send(JSON.stringify({ id, method, params })) + }) +} + +async function evaluate(expression) { + const res = await send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true }) + if (res.exceptionDetails) throw new Error(res.exceptionDetails.text || 'evaluate failed') + return res.result?.value +} + +try { + const portFile = resolve(profile, 'DevToolsActivePort') + await waitFor(() => existsSync(portFile) && readFileSync(portFile, 'utf8').trim().split('\n')[0], 20_000, 'DevToolsActivePort') + const port = readFileSync(portFile, 'utf8').trim().split('\n')[0] + const target = await waitFor(async () => { + const list = await fetch(`http://127.0.0.1:${port}/json/list`).then((r) => r.json()).catch(() => []) + return list.find((t) => t.type === 'page' && t.url.startsWith('file://')) + }, 20_000, 'renderer page target') + + ws = new WebSocket(target.webSocketDebuggerUrl) + await new Promise((ok, fail) => { ws.once('open', ok); ws.once('error', fail) }) + ws.on('message', (raw) => { + const msg = JSON.parse(String(raw)) + if (msg.id && pending.has(msg.id)) { + const { resolveSend, rejectSend } = pending.get(msg.id) + pending.delete(msg.id) + if (msg.error) rejectSend(new Error(msg.error.message)) + else resolveSend(msg.result) + return + } + if (msg.method === 'Runtime.exceptionThrown') { + exceptions.push(msg.params.exceptionDetails?.exception?.description || msg.params.exceptionDetails?.text) + } else if (msg.method === 'Runtime.consoleAPICalled' && msg.params.type === 'error') { + consoleErrors.push(msg.params.args.map((a) => a.value ?? a.description ?? '').join(' ')) + } else if (msg.method === 'Network.responseReceived') { + const url = msg.params.response?.url ?? '' + if (url.endsWith('.js')) loadedScripts.add(url.split('/').pop()) + } + }) + + await send('Runtime.enable') + await send('Page.enable') + await send('Network.enable') + await send('Page.addScriptToEvaluateOnNewDocument', { + source: `(() => { + if (sessionStorage.getItem('smoke-seeded')) return + sessionStorage.setItem('smoke-seeded', '1') + localStorage.setItem('BOTHUB_E2E', '1') + localStorage.setItem('bothub-prefs-v1', JSON.stringify({ state: { locale: 'en', theme: 'light' }, version: 0 })) + localStorage.setItem('bothub-workspace-v1', JSON.stringify({ + state: { + groups: [], + accounts: { 'acc-smoke': { id: 'acc-smoke', platformId: 'hermes', displayName: 'Smoke', handle: 'smoke', status: 'offline' } }, + bots: [{ id: 'bot-smoke', name: 'Smoke Bot', platformId: 'hermes', emoji: '🤖', accountIds: ['acc-smoke'], activeAccountId: 'acc-smoke', groupId: null, pinned: false, unread: 0, createdAt: 1 }], + messages: { 'bot-smoke': [{ id: 'm1', botId: 'bot-smoke', accountId: 'acc-smoke', role: 'assistant', text: '**Hello** smoke', createdAt: 1 }] }, + selectedBotId: 'bot-smoke', + infoPanelOpen: false, + collapsedGroups: {}, + dismissedGrokAgents: [], + dismissedDsBotAgents: [], + webSessionByBot: {}, + sidebarCollapsed: false, + sidebarWidth: 260 + }, + version: 0 + })) + })()` + }) + const entryUrl = pathToFileURL(resolve(root, 'out/renderer/index.html')).href + '?e2e=1' + await send('Page.navigate', { url: entryUrl }) + + await waitFor(() => evaluate(`Boolean(document.querySelector('nav') && document.querySelector('main') && document.querySelector('main').textContent.includes('Hello smoke'))`), 20_000, 'seeded chat render') + await sleep(500) + + const entryLoaded = [...loadedScripts].some((f) => f.startsWith('index-')) + const infoLoadedBefore = [...loadedScripts].some((f) => f.startsWith('InfoPanel-')) + const mainText = await evaluate(`document.querySelector('main').textContent`) + + await evaluate(`window.__bothub.store.getState().toggleInfoPanel()`) + await waitFor(() => [...loadedScripts].some((f) => f.startsWith('InfoPanel-')), 10_000, 'lazy InfoPanel chunk') + await waitFor(() => evaluate(`Boolean(document.querySelector('aside')?.textContent.includes('Smoke Bot'))`), 10_000, 'InfoPanel content') + await sleep(300) + + const result = { + entryLoaded, + infoLoadedBefore, + infoLoadedAfter: true, + mainRendered: mainText.includes('Hello smoke'), + exceptions, + consoleErrors, + scriptsLoaded: loadedScripts.size + } + console.log(JSON.stringify(result, null, 2)) + if (!entryLoaded || infoLoadedBefore || !result.mainRendered || exceptions.length || consoleErrors.length) { + process.exitCode = 1 + } +} catch (error) { + console.error('Smoke failed:', error.message) + if (exceptions.length) console.error('Exceptions:', exceptions) + if (consoleErrors.length) console.error('Console errors:', consoleErrors) + if (stderr) console.error('Electron stderr tail:', stderr.slice(-1500)) + process.exitCode = 1 +} finally { + try { ws?.close() } catch {} + child.kill('SIGTERM') + await Promise.race([new Promise((r) => child.once('exit', r)), sleep(2000)]) + if (child.exitCode === null) child.kill('SIGKILL') + rmSync(profile, { recursive: true, force: true }) + process.exit(process.exitCode ?? 0) +} diff --git a/src/adapters/grokbot/GrokBotAdapter.ts b/src/adapters/grokbot/GrokBotAdapter.ts index 011fcaae..1384f49f 100644 --- a/src/adapters/grokbot/GrokBotAdapter.ts +++ b/src/adapters/grokbot/GrokBotAdapter.ts @@ -94,8 +94,10 @@ function findTranscriptReply(payload: unknown, afterMessageId?: string): GrokRep (row.id === afterMessageId || row.clientNonce === afterMessageId)) : -1 if (afterMessageId && anchor === -1) return undefined const requestId = rows[anchor]?.requestId - return rows.slice(anchor + 1).findLast((row) => (row.role === 'assistant' || row.role === 'bot') && !row.isStreaming && - (!requestId || !row.requestId || row.requestId === requestId) && + const following = rows.slice(anchor + 1) + const nextPrompt = anchor >= 0 ? following.findIndex((row) => row.role === 'user') : -1 + return following.findLast((row, index) => (row.role === 'assistant' || row.role === 'bot') && !row.isStreaming && + (requestId && row.requestId ? row.requestId === requestId : nextPrompt < 0 || index < nextPrompt) && Boolean(row.text.trim() || row.widgets?.length || row.richWidgets?.length || row.media?.length)) } @@ -613,7 +615,7 @@ export class GrokBotAdapter implements PlatformAdapter { message: { ...bubble, id: replyId ? (replyId.startsWith('grok_') ? replyId : `grok_${replyId}`) : createId('msg'), - conversationId: message.conversationId, accountId: message.accountId, + conversationId: message.conversationId, accountId: message.accountId, agentId, sessionId: sessionId || undefined, createdAt: Date.now() } }) diff --git a/src/adapters/grokbot/grokReply.test.ts b/src/adapters/grokbot/grokReply.test.ts index 951965ec..fde5d26c 100644 --- a/src/adapters/grokbot/grokReply.test.ts +++ b/src/adapters/grokbot/grokReply.test.ts @@ -27,6 +27,16 @@ describe('extractReplyText', () => { expect(extractReplyText(page({ id: 'a1', role: 'assistant', text: 'old answer' }), 'u2')).toBe('') }) + it('does not attach an unlabelled reply after a later user prompt to an earlier turn', () => { + const p = page( + { id: 'u1', role: 'user', text: 'room prompt' }, + { id: 'u2', role: 'user', text: 'direct prompt' }, + { id: 'a2', role: 'assistant', text: 'direct reply' } + ) + expect(extractReplyText(p, 'u1')).toBe('') + expect(extractReplyText(p, 'u2')).toBe('direct reply') + }) + it('without an anchor returns the newest assistant text', () => { expect(extractReplyText(page({ id: 'a1', role: 'assistant', text: 'hi' }))).toBe('hi') }) diff --git a/src/adapters/types.ts b/src/adapters/types.ts index 083d28fe..d7b1a57a 100644 --- a/src/adapters/types.ts +++ b/src/adapters/types.ts @@ -105,6 +105,7 @@ export interface SendReceipt { export interface IncomingMessage { sessionId?: string + agentId?: string id: string conversationId: string accountId: string diff --git a/src/main/dsbot/dsBotClient.test.ts b/src/main/dsbot/dsBotClient.test.ts index 58367941..510b0b48 100644 --- a/src/main/dsbot/dsBotClient.test.ts +++ b/src/main/dsbot/dsBotClient.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest' -import { WebSocketServer } from 'ws' +import { WebSocketServer, type WebSocket } from 'ws' const tempDir = mkdtempSync(join(tmpdir(), 'botark-dsbot-test-')) @@ -73,6 +73,13 @@ describe('dsBotClient (MCP, Channel SSE, and Encrypted Relay)', () => { let relayHttpServer: Server let relayWss: WebSocketServer let relayPort = 0 + let relayConnectionCount = 0 + let relayHandshakeDelayMs = 0 + const relaySessions = new Set<{ + ws: WebSocket + ready: boolean + sendEncrypted: (msg: Record) => void + }>() const channelCalls: Array<{ endpoint: string; payload: unknown }> = [] const sseClients: Array<(chunk: string) => void> = [] @@ -281,8 +288,9 @@ describe('dsBotClient (MCP, Channel SSE, and Encrypted Relay)', () => { relayHttpServer = createServer() relayWss = new WebSocketServer({ server: relayHttpServer, path: '/v1/link' }) relayWss.on('connection', (ws) => { + relayConnectionCount++ let clientDeviceId = '' - const connId = 'conn-relay-1' + const connId = `conn-relay-${relayConnectionCount}` let noise: DsBotNoiseIkSession | null = null const inCodec = new DsBotSecureMessageCodec() const outCodec = new DsBotSecureMessageCodec() @@ -292,18 +300,24 @@ describe('dsBotClient (MCP, Channel SSE, and Encrypted Relay)', () => { ws.send(JSON.stringify({ v: 1, id: `srv-${Date.now()}`, type, timestamp: Date.now(), payload })) } - const sendEncrypted = (msg: Record) => { - if (!noise) return - const bytes = new TextEncoder().encode(JSON.stringify(msg)) - for (const chunk of outCodec.encode(bytes)) { - sendFrame('relay', { - connectionId: connId, - targetDeviceId: clientDeviceId, - counter: counter++, - ciphertext: toBase64Url(noise.encrypt(chunk)) - }) + const session = { + ws, + ready: false, + sendEncrypted: (msg: Record) => { + if (!noise) return + const bytes = new TextEncoder().encode(JSON.stringify(msg)) + for (const chunk of outCodec.encode(bytes)) { + sendFrame('relay', { + connectionId: connId, + targetDeviceId: clientDeviceId, + counter: counter++, + ciphertext: toBase64Url(noise.encrypt(chunk)) + }) + } } } + relaySessions.add(session) + ws.on('close', () => relaySessions.delete(session)) ws.on('message', (raw) => { const frame = JSON.parse(raw.toString()) as { type: string; payload: Record } @@ -333,12 +347,17 @@ describe('dsBotClient (MCP, Channel SSE, and Encrypted Relay)', () => { return } const step2 = noise.writeHandshake(encodeHandshakeHello({ name: 'HomeMac-DSBot' })) - sendFrame('secure.handshake', { - connectionId: connId, - targetDeviceId: clientDeviceId, - step: 2, - data: toBase64Url(step2) - }) + const acceptHandshake = () => { + session.ready = true + sendFrame('secure.handshake', { + connectionId: connId, + targetDeviceId: clientDeviceId, + step: 2, + data: toBase64Url(step2) + }) + } + if (relayHandshakeDelayMs > 0) setTimeout(acceptHandshake, relayHandshakeDelayMs) + else acceptHandshake() } else if (frame.type === 'relay' && noise) { const assembled = inCodec.decode(noise.decrypt(fromBase64Url(String(frame.payload.ciphertext)))) if (!assembled) return @@ -362,30 +381,33 @@ describe('dsBotClient (MCP, Channel SSE, and Encrypted Relay)', () => { } } else if (ep === 'send') { setTimeout(() => { - sendEncrypted({ - v: 1, - id: 'ev-1', - type: 'event', - timestamp: Date.now(), - payload: { event: 'stream', data: { botId: 'chief', attemptId: 'r1', phase: 'start' } } - }) - sendEncrypted({ - v: 1, - id: 'ev-2', - type: 'event', - timestamp: Date.now(), - payload: { event: 'stream', data: { botId: 'chief', attemptId: 'r1', text: 'Encrypted reply!' } } - }) - sendEncrypted({ - v: 1, - id: 'ev-3', - type: 'event', - timestamp: Date.now(), - payload: { event: 'stream', data: { botId: 'chief', attemptId: 'r1', phase: 'end' } } - }) + for (const peer of relaySessions) { + if (!peer.ready || peer.ws.readyState !== peer.ws.OPEN) continue + peer.sendEncrypted({ + v: 1, + id: 'ev-1', + type: 'event', + timestamp: Date.now(), + payload: { event: 'stream', data: { botId: 'chief', attemptId: 'r1', phase: 'start' } } + }) + peer.sendEncrypted({ + v: 1, + id: 'ev-2', + type: 'event', + timestamp: Date.now(), + payload: { event: 'stream', data: { botId: 'chief', attemptId: 'r1', text: 'Encrypted reply!' } } + }) + peer.sendEncrypted({ + v: 1, + id: 'ev-3', + type: 'event', + timestamp: Date.now(), + payload: { event: 'stream', data: { botId: 'chief', attemptId: 'r1', phase: 'end' } } + }) + } }, 20) } - sendEncrypted({ + session.sendEncrypted({ v: 1, id: `res-${req.id}`, type: 'rpc.response', @@ -409,7 +431,10 @@ describe('dsBotClient (MCP, Channel SSE, and Encrypted Relay)', () => { await Promise.all([ new Promise((r) => mcpServer.close(() => r())), new Promise((r) => channelServer.close(() => r())), - new Promise((r) => relayWss.close(() => relayHttpServer.close(() => r()))) + new Promise((r) => { + for (const ws of relayWss.clients) ws.terminate() + relayWss.close(() => relayHttpServer.close(() => r())) + }) ]) rmSync(tempDir, { recursive: true, force: true }) }) @@ -573,4 +598,46 @@ describe('dsBotClient (MCP, Channel SSE, and Encrypted Relay)', () => { }) expect(res.replyText).toBe('Encrypted reply!') }) + + it('shares a single in-flight relay connection across concurrent calls without duplicating stream deltas', async () => { + const accountId = 'acc_ds_relay_singleflight' + const keys = generateX25519KeyPair() + const existingRelay = { + relayServer: `ws://127.0.0.1:${relayPort}/v1/link`, + hostDeviceId, + hostKey: hostKeys.publicKey, + deviceId: deviceIdForPublicKey(keys.publicKey), + publicKey: keys.publicKey, + privateKey: keys.privateKey, + accessToken: 'relay_token_singleflight' + } + await saveDsBotAccount({ + accountId, + mode: 'relay', + expectedRevision: getDsBotAccountRevision(accountId), + ...existingRelay + }) + + relayHandshakeDelayMs = 30 + const connectionsBefore = relayConnectionCount + const deltas: string[] = [] + try { + const [sent, probe] = await Promise.all([ + sendDsBotMessage({ + accountId, + agentId: 'bot:chief', + text: 'Concurrent ping', + callbacks: { onDelta: (d) => deltas.push(d.text) } + }), + probeDsBotConnection({ accountId, mode: 'relay', existingRelay }) + ]) + + expect(probe.authenticated).toBe(true) + expect(relayConnectionCount - connectionsBefore).toBe(1) + expect(sent.replyText).toBe('Encrypted reply!') + expect(deltas).toEqual(['Encrypted reply!', 'Encrypted reply!']) + } finally { + relayHandshakeDelayMs = 0 + } + }) }) diff --git a/src/main/dsbot/dsBotClient.ts b/src/main/dsbot/dsBotClient.ts index cf0fa0c8..e59b3c0d 100644 --- a/src/main/dsbot/dsBotClient.ts +++ b/src/main/dsbot/dsBotClient.ts @@ -28,7 +28,12 @@ import { parseDsBotPairingUri, randomBase64UrlToken } from './dsBotNoise' -import { DsBotRelayClient, type DsBotRelayEvent } from './dsBotRelay' +import { + DsBotRelayClient, + type DsBotRelayEvent, + type DsBotRelayHost, + type DsBotRelayIdentity +} from './dsBotRelay' import { detectLocalDsBotDiskConfig, getDsBotAccount, @@ -137,6 +142,7 @@ interface ActiveTurnTracker { } const activeRelays = new Map() +const activeRelayConnects = new Map>() const activeChannelFeeds = new Map() const activeTurns = new Map() const accountBotNameMap = new Map>() @@ -331,6 +337,66 @@ async function mcpCallTool( } } +function connectRelayClient( + accountId: string, + options: { + host: DsBotRelayHost + identity: DsBotRelayIdentity + pairingCode?: string + }, + reuseExisting: boolean +): Promise { + if (reuseExisting) { + const existing = activeRelays.get(accountId) + if (existing?.connected) return Promise.resolve(existing) + const inFlight = activeRelayConnects.get(accountId) + if (inFlight) return inFlight + } + + const isCurrent = () => activeRelayConnects.get(accountId) === promise + const promise = (async () => { + const proxyUrl = await loadAccountProxyUrl(accountId).catch(() => undefined) + if (!isCurrent()) { + throw new DsBotApiError('DS Bot 加密连接已取消或已被替换', 400, 'connect_superseded') + } + const agent = proxyUrl ? proxyWsAgent(proxyUrl) : undefined + const client = new DsBotRelayClient({ + host: options.host, + identity: options.identity, + clientName: 'BotArk Desktop', + ...(options.pairingCode ? { pairingCode: options.pairingCode } : {}), + agent + }) + + client.onEvent((ev) => handleNativeFeedEvent(accountId, ev)) + client.onClose(() => { + if (activeRelays.get(accountId) === client) { + activeRelays.delete(accountId) + } + }) + + try { + await client.connect() + if (!isCurrent()) { + throw new DsBotApiError('DS Bot 加密连接已取消或已被替换', 400, 'connect_superseded') + } + const previous = activeRelays.get(accountId) + if (previous && previous !== client) previous.close() + activeRelays.set(accountId, client) + return client + } catch (error) { + client.close() + throw error + } finally { + if (isCurrent()) { + activeRelayConnects.delete(accountId) + } + } + })() + activeRelayConnects.set(accountId, promise) + return promise +} + async function ensureRelayClient(account: ResolvedDsBotAccount): Promise { const existing = activeRelays.get(account.accountId) if (existing?.connected) return existing @@ -339,34 +405,23 @@ async function ensureRelayClient(account: ResolvedDsBotAccount): Promise undefined) - const agent = proxyUrl ? proxyWsAgent(proxyUrl) : undefined - const client = new DsBotRelayClient({ - host: { - server: account.relayServer, - hostDeviceId: account.hostDeviceId, - hostKey: account.hostKey - }, - identity: { - deviceId: account.deviceId, - publicKey: account.publicKey, - privateKey: account.privateKey, - accessToken: account.accessToken + return connectRelayClient( + account.accountId, + { + host: { + server: account.relayServer, + hostDeviceId: account.hostDeviceId, + hostKey: account.hostKey + }, + identity: { + deviceId: account.deviceId, + publicKey: account.publicKey, + privateKey: account.privateKey, + accessToken: account.accessToken + } }, - clientName: 'BotArk Desktop', - agent - }) - - client.onEvent((ev) => handleNativeFeedEvent(account.accountId, ev)) - client.onClose(() => { - if (activeRelays.get(account.accountId) === client) { - activeRelays.delete(account.accountId) - } - }) - - await client.connect() - activeRelays.set(account.accountId, client) - return client + true + ) } function handleNativeFeedEvent(accountId: string, ev: DsBotRelayEvent): void { @@ -514,12 +569,14 @@ export function stopDsBotLiveConnection(accountId: string): void { if (accountId === '*') { for (const [, ctrl] of activeChannelFeeds) ctrl.abort() activeChannelFeeds.clear() + activeRelayConnects.clear() for (const [, relay] of activeRelays) relay.close() activeRelays.clear() return } activeChannelFeeds.get(accountId)?.abort() activeChannelFeeds.delete(accountId) + activeRelayConnects.delete(accountId) activeRelays.get(accountId)?.close() activeRelays.delete(accountId) } @@ -754,7 +811,6 @@ export async function probeDsBotConnection(args: { } // Relay mode (either fresh pairing via pairingUri, or reconnecting existing identity) - const agent = proxyUrl ? proxyWsAgent(proxyUrl) : undefined let relayInfo = args.existingRelay let pairingCode: string | undefined @@ -787,39 +843,24 @@ export async function probeDsBotConnection(args: { } } - // Reuse existing live relay when re-checking without a fresh pairing URI - const existingLive = !pairingCode ? activeRelays.get(args.accountId) : undefined - const client = - existingLive?.connected - ? existingLive - : new DsBotRelayClient({ - host: { - server: relayInfo.relayServer, - hostDeviceId: relayInfo.hostDeviceId, - hostKey: relayInfo.hostKey - }, - identity: { - deviceId: relayInfo.deviceId, - publicKey: relayInfo.publicKey, - privateKey: relayInfo.privateKey, - accessToken: relayInfo.accessToken - }, - clientName: 'BotArk Desktop', - pairingCode, - agent - }) - - if (!client.connected) { - client.onEvent((ev) => handleNativeFeedEvent(args.accountId, ev)) - client.onClose(() => { - if (activeRelays.get(args.accountId) === client) { - activeRelays.delete(args.accountId) - } - }) - await client.connect() - activeRelays.get(args.accountId)?.close() - activeRelays.set(args.accountId, client) - } + const client = await connectRelayClient( + args.accountId, + { + host: { + server: relayInfo.relayServer, + hostDeviceId: relayInfo.hostDeviceId, + hostKey: relayInfo.hostKey + }, + identity: { + deviceId: relayInfo.deviceId, + publicKey: relayInfo.publicKey, + privateKey: relayInfo.privateKey, + accessToken: relayInfo.accessToken + }, + ...(pairingCode ? { pairingCode } : {}) + }, + !pairingCode + ) const [hello, state] = await Promise.all([ client.callBot<{ plugin?: { version?: string } }>('hello', { api: [1] }).catch(() => null), diff --git a/src/main/grok/connectClient.test.ts b/src/main/grok/connectClient.test.ts index c2289479..22ba8307 100644 --- a/src/main/grok/connectClient.test.ts +++ b/src/main/grok/connectClient.test.ts @@ -2,6 +2,7 @@ import { describe, expect, it, vi } from 'vitest' import { createCursorChecksum, GrokConnectClient, + GrokConnectError, GROK_SAND_CLIENT_VERSION, GROK_SERVICES, GROK_USER_MESSAGE_INITIATOR, @@ -176,8 +177,19 @@ describe('GrokConnectClient (Sand 0.79.3 wire protocol)', () => { } }) + const fetchImpl = vi.fn(async (input: string | URL | Request, init?: RequestInit) => { + const request = new Request(input, init) + expect(request.headers.get('content-type')).toBe('application/connect+json') + const requestBytes = Buffer.from(await request.arrayBuffer()) + expect(requestBytes).toEqual(encodeConnectFrame(0, { + cursors: [{ agent_id: 'agent-1', after_updated_seq: '4' }], + include_unlisted_agents: true, + inline_body_max_bytes: 262_144 + })) + return new Response(stream, { status: 200 }) + }) const client = new GrokConnectClient({ - fetchImpl: (async () => new Response(stream, { status: 200 })) as typeof fetch, + fetchImpl, auth: { accessToken: 'tok_redacted_test', machineId: 'machine-1' } }) @@ -219,4 +231,59 @@ describe('GrokConnectClient (Sand 0.79.3 wire protocol)', () => { expect(cancel).toHaveBeenCalledOnce() expect(stream.locked).toBe(false) }) + + it('rejects an oversized frame length from the 5-byte header alone and cancels the stream', async () => { + const header = Buffer.alloc(5) + header[0] = 0x00 + header.writeUInt32BE(0xffff_ffff, 1) + let fallbackClose: ReturnType | undefined + const cancel = vi.fn(() => { + if (fallbackClose) clearTimeout(fallbackClose) + }) + const stream = new ReadableStream({ + start(controller) { + controller.enqueue(header) + fallbackClose = setTimeout(() => controller.close(), 50) + }, + cancel + }) + const client = new GrokConnectClient({ + auth: { accessToken: 'fixture' }, + fetchImpl: async () => new Response(stream) + }) + + const frames = client.watchTranscripts({ cursors: [] }) + await expect(frames.next()).rejects.toBeInstanceOf(GrokConnectError) + expect(cancel).toHaveBeenCalledOnce() + expect(stream.locked).toBe(false) + }) + + it('decodes a 2 MiB JSON frame delivered in 1 KiB chunks within 500 ms', async () => { + const text = 'x'.repeat(2 * 1024 * 1024) + const expected = { agentId: 'agent-large', text } + const wire = encodeConnectFrame(0x00, expected) + const stream = new ReadableStream({ + start(controller) { + for (let offset = 0; offset < wire.length; offset += 1024) { + controller.enqueue(wire.subarray(offset, offset + 1024)) + } + controller.enqueue(encodeConnectFrame(0x02, {})) + controller.close() + } + }) + const client = new GrokConnectClient({ + auth: { accessToken: 'fixture' }, + fetchImpl: async () => new Response(stream) + }) + + const started = performance.now() + const seen: Array> = [] + for await (const frame of client.watchTranscripts({ cursors: [] })) { + seen.push(frame) + } + const elapsedMs = performance.now() - started + + expect(seen).toEqual([expected]) + expect(elapsedMs).toBeLessThan(500) + }) }) diff --git a/src/main/grok/connectClient.ts b/src/main/grok/connectClient.ts index 15349caf..624ae631 100644 --- a/src/main/grok/connectClient.ts +++ b/src/main/grok/connectClient.ts @@ -29,6 +29,9 @@ export const GROK_SERVICES: Record = { /** Match Grok Bot.app 1.1.0 sand client identity (`main-core.cjs`). */ export const GROK_SAND_CLIENT_VERSION = '1.1.0' +/** Upper bound for a single Connect envelope payload on `WatchGrokBotTranscripts`. */ +export const MAX_WATCH_FRAME_BYTES = 4 * 1024 * 1024 + /** Protobuf enum values from `0.79.3` `proto.cjs`. */ export const GROK_USER_MESSAGE_INITIATOR = { UNSPECIFIED: 0, @@ -791,10 +794,14 @@ export class GrokConnectClient { include_unlisted_agents: req.includeUnlistedAgents ?? true, inline_body_max_bytes: req.inlineBodyMaxBytes ?? 262_144 } + const payload = new TextEncoder().encode(JSON.stringify(body)) + const envelope = new Uint8Array(5 + payload.length) + new DataView(envelope.buffer).setUint32(1, payload.length) + envelope.set(payload, 5) const res = await this.fetchImpl(url, { method: 'POST', headers, - body: JSON.stringify(body), + body: envelope, signal }) if (!res.ok) { @@ -813,21 +820,50 @@ export class GrokConnectClient { const cancel = () => { void reader.cancel().catch(() => undefined) } signal?.addEventListener('abort', cancel, { once: true }) const decoder = new TextDecoder() - let buffer = Buffer.alloc(0) + const header = Buffer.alloc(5) + let chunks: Buffer[] = [] + let bufferedBytes = 0 try { while (true) { signal?.throwIfAborted() const { done, value } = await reader.read() signal?.throwIfAborted() if (done) break - buffer = Buffer.concat([buffer, Buffer.from(value)]) - while (buffer.length >= 5) { + if (value.byteLength > 0) { + chunks.push(Buffer.from(value)) + bufferedBytes += value.byteLength + } + while (bufferedBytes >= 5) { signal?.throwIfAborted() - const flags = buffer[0]! - const len = buffer.readUInt32BE(1) - if (buffer.length < 5 + len) break - const payload = buffer.subarray(5, 5 + len) - buffer = buffer.subarray(5 + len) + if (chunks[0]!.length >= 5) { + chunks[0]!.copy(header, 0, 0, 5) + } else { + let copied = 0 + for (const chunk of chunks) { + const count = Math.min(chunk.length, 5 - copied) + chunk.copy(header, copied, 0, count) + copied += count + if (copied === 5) break + } + } + const flags = header[0]! + const len = header.readUInt32BE(1) + if (len > MAX_WATCH_FRAME_BYTES) { + throw new GrokConnectError( + 0, + `Watch frame length ${len} exceeds the ${MAX_WATCH_FRAME_BYTES}-byte limit`, + 'frame_too_large' + ) + } + const frameLength = 5 + len + if (bufferedBytes < frameLength) break + if (chunks.length > 1) { + chunks = [Buffer.concat(chunks, bufferedBytes)] + } + const frame = chunks[0]! + const payload = Buffer.from(frame.subarray(5, frameLength)) + bufferedBytes -= frameLength + chunks = bufferedBytes > 0 ? [frame.subarray(frameLength)] : [] if (flags & 0x02) { if (payload.length) { try { diff --git a/src/main/grok/grokRpc.test.ts b/src/main/grok/grokRpc.test.ts index ab3dc1bc..1bab351c 100644 --- a/src/main/grok/grokRpc.test.ts +++ b/src/main/grok/grokRpc.test.ts @@ -17,6 +17,46 @@ const reply = (id: string, seq: string, fields: Record = {}) => entry_id: id, seq, kind: 'send-message', content: id, ...fields }) +it('waits for a delayed group file link after a Grok progress reply', async () => { + vi.useFakeTimers() + const controller = new AbortController() + const progress = reply('progress', '9', { content: '好的,我来查阅资料,整理后发给大家。' }) + const deliverable = reply('deliverable', '10', { + content: '[FINAL]\n[报告](https://example.test/report.pdf)' + }) + const watchTranscripts = async function* (_params: unknown, signal: AbortSignal) { + yield rows([user, progress]) + yield { agent_state: { ...wireScope, is_running: false } } + if (!signal.aborted) { + await new Promise((resolve) => { + const timer = setTimeout(resolve, 29_000) + signal.addEventListener('abort', () => { clearTimeout(timer); resolve() }, { once: true }) + }) + } + if (!signal.aborted) yield rows([deliverable]) + } + const listTranscriptEntries = async () => ({ entries: [user, progress] }) + const delivered = vi.fn() + const result = watchUntilReply({ watchTranscripts, listTranscriptEntries } as unknown as GrokConnectClient, { + ...scope, conversationId: 'room-turn-fixture', afterMessageId: 'nonce', timeoutMs: 90_000, signal: controller.signal + }).then(delivered, () => undefined) + try { + await vi.advanceTimersByTimeAsync(5_000) + expect(delivered).not.toHaveBeenCalled() + await vi.advanceTimersByTimeAsync(28_000) + expect(delivered).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + messages: [ + expect.objectContaining({ messageId: 'grok_progress', text: progress.content }), + expect.objectContaining({ messageId: 'grok_deliverable', text: deliverable.content }) + ] + })) + } finally { + controller.abort() + await result + vi.useRealTimers() + } +}) + it('recovers a completed zero-cursor reply when the replay omits its user anchor', async () => { const listTranscriptEntries = vi.fn(async () => ({ entries: [user] })) const getSendStatus = vi.fn(async () => ({ echo_entry_id: 'echo' })) @@ -84,3 +124,125 @@ it('stops the stream and rejects on renderer cancellation', async () => { await rejected expect(watchTranscripts.mock.calls[0]?.[1]?.aborted).toBe(true) }) + +it.each(['direct-grok', 'room-turn-grok'])('recovers the current reply on a silent stream for %s', async (conversationId) => { + vi.useFakeTimers() + const controller = new AbortController() + const watchTranscripts = vi.fn(async function* (_params: unknown, signal: AbortSignal) { + await new Promise((resolve) => signal.addEventListener('abort', () => resolve(), { once: true })) + }) + const listTranscriptEntries = vi.fn(async () => ({ + entries: [ + reply('older-reply', '7'), + user, + reply('answer', '9'), + { ...user, entry_id: 'another-question', seq: '10', client_nonce: 'different', request_id: 'different' }, + reply('answer-to-another-question', '11') + ] + })) + const delivered = vi.fn() + const result = watchUntilReply({ watchTranscripts, listTranscriptEntries } as unknown as GrokConnectClient, { + ...scope, conversationId, afterUpdatedSeq: '7', afterMessageId: 'nonce', timeoutMs: 60_000, signal: controller.signal + }).then(delivered, () => undefined) + try { + await vi.advanceTimersByTimeAsync(8_000) + expect(listTranscriptEntries).toHaveBeenCalledWith( + expect.objectContaining({ agentId: 'agent', sessionId: 'session', limit: 40 }), expect.any(AbortSignal) + ) + expect(delivered).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + text: 'answer', messages: [expect.objectContaining({ messageId: 'grok_answer' })] + })) + } finally { + controller.abort() + await result + vi.useRealTimers() + } +}) + +it.each(['prompt', 'reply'])('uses history order when a zero-sequence %s was seen first', async (first) => { + vi.useFakeTimers() + const controller = new AbortController() + const started = Date.now() + const currentPrompt = { ...user, seq: '0', timestampMs: 101 } + const answer = reply('answer', '0', { timestampMs: 101 }) + const olderPrompt = { ...currentPrompt, entry_id: 'earlier', client_nonce: 'earlier-nonce', request_id: 'earlier-turn' } + const watchTranscripts = async function* (_params: unknown, signal: AbortSignal) { + yield rows([first === 'prompt' ? currentPrompt : answer]) + if (!signal.aborted) { + await new Promise((resolve) => signal.addEventListener('abort', () => resolve(), { once: true })) + } + } + const listTranscriptEntries = async () => Date.now() - started < 4_000 + ? { entries: [], hasMore: false } + : { entries: [olderPrompt, reply('old', '0', { timestampMs: 101 }), currentPrompt, answer] } + const delivered = vi.fn() + const result = watchUntilReply({ watchTranscripts, listTranscriptEntries } as unknown as GrokConnectClient, { + ...scope, afterMessageId: 'nonce', timeoutMs: 60_000, signal: controller.signal + }).then(delivered, () => undefined) + try { + await vi.advanceTimersByTimeAsync(8_000) + expect(delivered).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ + messages: [expect.objectContaining({ messageId: 'grok_answer' })] + })) + } finally { + controller.abort() + await result + vi.useRealTimers() + } +}) + +it('keeps receiving live replies while a history request is slow', async () => { + vi.useFakeTimers() + const controller = new AbortController() + const watchTranscripts = async function* (_params: unknown, signal: AbortSignal) { + await new Promise((resolve) => { + const timer = setTimeout(resolve, 5_000) + signal.addEventListener('abort', () => { clearTimeout(timer); resolve() }, { once: true }) + }) + if (!signal.aborted) yield rows([user, reply('live-reply', '9')]) + } + const listTranscriptEntries = vi.fn(async (_req: unknown, signal: AbortSignal) => { + if (!signal.aborted) { + await new Promise((resolve) => signal.addEventListener('abort', () => resolve(), { once: true })) + } + return { entries: [] } + }) + const delivered = vi.fn() + const result = watchUntilReply({ watchTranscripts, listTranscriptEntries } as unknown as GrokConnectClient, { + ...scope, afterMessageId: 'nonce', timeoutMs: 60_000, signal: controller.signal + }).then(delivered, () => undefined) + try { + await vi.advanceTimersByTimeAsync(8_000) + expect(listTranscriptEntries).toHaveBeenCalledOnce() + expect(delivered).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ text: 'live-reply' })) + } finally { + controller.abort() + await result + vi.useRealTimers() + } +}) + +it('checks the next prompt across history pages before assigning an unidentified reply', async () => { + vi.useFakeTimers() + const controller = new AbortController() + const watchTranscripts = async function* (_params: unknown, signal: AbortSignal) { + await new Promise((resolve) => signal.addEventListener('abort', () => resolve(), { once: true })) + } + const getSendStatus = async () => ({ echo_entry_id: 'echo' }) + const listTranscriptEntries = vi.fn(async ({ beforeSeq }: { beforeSeq?: string }) => beforeSeq + ? { entries: [user, { ...user, entry_id: 'another-question', seq: '9', client_nonce: 'different', request_id: 'different' }], hasMore: false } + : { entries: [reply('another-answers', '49')], nextBeforeSeq: '10' }) + const delivered = vi.fn() + const result = watchUntilReply({ watchTranscripts, listTranscriptEntries, getSendStatus } as unknown as GrokConnectClient, { + ...scope, afterUpdatedSeq: '7', afterMessageId: 'nonce', timeoutMs: 8_500, signal: controller.signal + }).then(delivered, () => undefined) + try { + await vi.advanceTimersByTimeAsync(9_000) + expect(listTranscriptEntries).toHaveBeenCalledWith(expect.objectContaining({ beforeSeq: '10' }), expect.any(AbortSignal)) + expect(delivered).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ messages: [] })) + } finally { + controller.abort() + await result + vi.useRealTimers() + } +}) diff --git a/src/main/grok/grokRpc.ts b/src/main/grok/grokRpc.ts index 4c8e1a61..e9b42298 100644 --- a/src/main/grok/grokRpc.ts +++ b/src/main/grok/grokRpc.ts @@ -78,6 +78,29 @@ function fail(error: unknown): GrokRpcResponse { } const GROK_REPLY_SETTLE_MS = 12_000 +const GROK_ROOM_PROGRESS_GRACE_MS = 60_000 +const GROK_REPLY_HISTORY_INTERVAL_MS = 4_000 +const GROK_REPLY_HISTORY_TIMEOUT_MS = 6_000 +const GROK_REPLY_HISTORY_MAX_PAGES = 8 + +function followsGrokEntry( + entry: ParsedGrokTranscriptEntry, + previous: ParsedGrokTranscriptEntry, + order: number | undefined, + previousOrder: number | undefined +): boolean { + const seq = grokSeq(entry.seq) + const previousSeq = grokSeq(previous.seq) + if (seq > 0n && previousSeq > 0n) return seq > previousSeq + const updated = grokSeq(entry.updatedSeq) + const previousUpdated = grokSeq(previous.updatedSeq) + if (updated > 0n && previousUpdated > 0n) return updated > previousUpdated + if (previous.hasTimestamp && entry.hasTimestamp && entry.createdAtMs !== previous.createdAtMs) { + return entry.createdAtMs > previous.createdAtMs + } + return Boolean(previous.requestId && entry.requestId === previous.requestId) || + (previousOrder !== undefined && order !== undefined && order > previousOrder) +} interface GrokReplyBubble { messageId: string @@ -88,6 +111,13 @@ interface GrokReplyBubble { media?: MuseMediaPartView[] } +function isRoomProgressReply(bubble: GrokReplyBubble): boolean { + const text = bubble.text.trim() + if (!text || text.length > 160 || bubble.media?.length || bubble.widgets?.length || bubble.richWidgets?.length) return false + if (/\[(?:FINAL|HANDOFF|TOOL)\]|(?:https?|grok(?:att|store|doc)):\/\/|\r?\n|已经|已完成|已生成|已整理|查到了|如下|见附件|\b(?:here (?:is|are)|attached|finished)\b/i.test(text)) return false + return /(?:我(?:先|来|会|将|这就|正在)|让我)[^。!?\n]{0,24}(?:查|搜|检索|整理|生成|制作|准备|撰写|导出|汇总)|稍(?:等|候)|\b(?:let me|i(?:['’]ll| will))\s+(?:check|look|search|prepare|gather|compile|create|generate|draft)\b/i.test(text) +} + export async function watchUntilReply( client: GrokConnectClient, args: { @@ -112,6 +142,7 @@ export async function watchUntilReply( const credentialSignal = activeGrokCredentialSignal(args.accountId) const signal = AbortSignal.any([ac.signal, credentialSignal, ...(args.signal ? [args.signal] : [])]) const { accountId, agentId, sessionId } = args + const isRoomTurn = args.conversationId?.startsWith('room-turn-') === true const watchHandle = getGrokAccountWatch(accountId) const streamsInBackground = watchHandle?.watchesSession(agentId, sessionId) ?? false const revisions = new GrokEntryRevisions() @@ -124,14 +155,15 @@ export async function watchUntilReply( let generation = 0 let anchor: ParsedGrokTranscriptEntry | undefined let anchorOrder: number | undefined + let nextPrompt: { entry: ParsedGrokTranscriptEntry; order?: number } | undefined let received = 0 const entryOrder = new Map() let echoEntryId: string | undefined - let anchorLookup: Promise | undefined let nextAnchorLookupAt = 0 let turnFailed: { code: string; summary: string } | undefined let isAgentRunning = false let settleTimer: ReturnType | undefined + let roomProgressUntil: number | undefined const assertCurrent = () => { signal.throwIfAborted() @@ -143,44 +175,63 @@ export async function watchUntilReply( ) const armSettle = (ms: number) => { clearTimeout(settleTimer) + if (isRoomTurn && bubbles.size && [...bubbles.values()].every(({ bubble }) => isRoomProgressReply(bubble))) { + roomProgressUntil ??= Date.now() + GROK_ROOM_PROGRESS_GRACE_MS + ms = Math.max(0, roomProgressUntil - Date.now()) + } else { + roomProgressUntil = undefined + } settleTimer = setTimeout(() => ac.abort(), ms) } - const lookupAnchor = async (): Promise => { + const lookupEchoEntryId = async (readSignal: AbortSignal): Promise => { if (!sentId) return undefined try { - const status = asObj(await client.getSendStatus({ agentId, sessionId, messageId: sentId }, signal)) - assertCurrent() - echoEntryId = str(status?.['echoEntryId'] ?? status?.['echo_entry_id']) || undefined - } catch { assertCurrent() } + const status = asObj(await client.getSendStatus({ agentId, sessionId, messageId: sentId }, readSignal)) + readSignal.throwIfAborted() + return str(status?.['echoEntryId'] ?? status?.['echo_entry_id']) || undefined + } catch { + readSignal.throwIfAborted() + return undefined + } + } + + const readTurnHistory = async (readSignal: AbortSignal, lookupEchoFirst = false) => { + let echoId = echoEntryId + if (lookupEchoFirst && !echoId) echoId = await lookupEchoEntryId(readSignal) + const matches = (entry: ParsedGrokTranscriptEntry) => isAnchor(entry) || + Boolean(echoId && entry.entryId === echoId) const page = await readGrokTranscriptGap(client, { agentId, sessionId }, { - floor: afterSeq, stopAt: (entry) => isAnchor(entry) || Boolean(echoEntryId && entry.entryId === echoEntryId), signal + floor: 0n, stopAt: matches, signal: readSignal, maxPages: GROK_REPLY_HISTORY_MAX_PAGES }) - assertCurrent() - let candidate = page.entries.find(isAnchor) - if (!candidate && echoEntryId) { - const stub = page.entries.find((entry) => entry.entryId === echoEntryId && entry.bodyOmitted) - if (stub) { - const hydrated = await hydrateGrokEntry(client, agentId, sessionId, stub, signal) - if (isAnchor(hydrated)) candidate = hydrated - } + let index = page.entries.findIndex(matches) + if (index < 0 && !echoId && !lookupEchoFirst) { + echoId = await lookupEchoEntryId(readSignal) + index = page.entries.findIndex(matches) } - return candidate + const entry = page.entries[index] + const prompt = entry?.bodyOmitted ? await hydrateGrokEntry(client, agentId, sessionId, entry, readSignal) : entry + const verified = prompt?.role === 'user' && matches(prompt) + return { echoId, generation: page.generation, entries: verified ? [prompt, ...page.entries.slice(index + 1)] : [] } } - const acceptEntries = async (entries: ParsedGrokTranscriptEntry[]) => { + const acceptEntries = async (entries: ParsedGrokTranscriptEntry[], advanceCursor = true, readSignal = signal) => { const hydrated: Array<{ entry: ParsedGrokTranscriptEntry; order: number }> = [] for (const entry of entries) { assertCurrent() const seq = grokSeq(entry.updatedSeq) - if (seq > cursor) cursor = seq - const parsed = await hydrateGrokEntry(client, agentId, sessionId, entry, signal) + if (advanceCursor && seq > cursor) cursor = seq + const parsed = await hydrateGrokEntry(client, agentId, sessionId, entry, readSignal) assertCurrent() const order = ++received hydrated.push({ entry: parsed, order }) - if (isAnchor(parsed) && (anchorOrder === undefined || !anchor)) { - anchor = parsed - anchorOrder = order + if (isAnchor(parsed)) { + if (!anchor || anchorOrder === undefined) { + anchor = parsed + anchorOrder = order + } else if (!advanceCursor && parsed.entryId === anchor.entryId) { + anchorOrder = order + } } } for (const { entry, order } of hydrated) { @@ -195,41 +246,45 @@ export async function watchUntilReply( pending.delete(oldest) entryOrder.delete(oldest) } + } else if (!advanceCursor && pending.has(entry.entryId)) { + entryOrder.set(entry.entryId, order) } } if (sentId && !anchor && pending.size && Date.now() >= nextAnchorLookupAt) { - anchorLookup ??= lookupAnchor().catch(() => undefined).finally(() => { - nextAnchorLookupAt = Date.now() + 1000 - anchorLookup = undefined - }) - anchor = await anchorLookup + const history = await readTurnHistory(readSignal, true).catch(() => undefined) + nextAnchorLookupAt = Date.now() + 1000 assertCurrent() + echoEntryId ??= history?.echoId + anchor = history?.entries[0] + const following = history?.entries.slice(1).find((entry) => entry.role === 'user') + if (following) nextPrompt = { entry: following } + } + if (sentId && !anchor) return false + if (anchor) { + for (const candidate of hydrated) { + const { entry, order } = candidate + if (entry.role !== 'user' || isAnchor(entry) || !followsGrokEntry(entry, anchor, order, anchorOrder)) continue + if (!nextPrompt || nextPrompt.entry.entryId === entry.entryId || + followsGrokEntry(nextPrompt.entry, entry, nextPrompt.order, order)) nextPrompt = candidate + } } - if (sentId && !anchor) return + let receivedReply = false for (const entry of [...pending.values()].sort(compareGrokEntries)) { pending.delete(entry.entryId) const order = entryOrder.get(entry.entryId) entryOrder.delete(entry.entryId) if (anchor?.requestId && entry.requestId && anchor.requestId !== entry.requestId) continue - const seq = grokSeq(entry.seq) - const anchorSeq = grokSeq(anchor?.seq) - const updated = grokSeq(entry.updatedSeq) - const anchorUpdated = grokSeq(anchor?.updatedSeq) - if (anchor) { - const followsAnchor = seq > 0n && anchorSeq > 0n ? seq > anchorSeq - : updated > 0n && anchorUpdated > 0n ? updated > anchorUpdated - : anchor.hasTimestamp && entry.hasTimestamp && entry.createdAtMs !== anchor.createdAtMs - ? entry.createdAtMs > anchor.createdAtMs - : Boolean(anchor.requestId && entry.requestId === anchor.requestId) || - (anchorOrder !== undefined && order !== undefined && order > anchorOrder) - if (!followsAnchor) continue - } + if (anchor && !followsGrokEntry(entry, anchor, order, anchorOrder)) continue + const matchesRequest = Boolean(anchor?.requestId && entry.requestId === anchor.requestId) + if (nextPrompt && !matchesRequest && !followsGrokEntry(nextPrompt.entry, entry, nextPrompt.order, order)) continue if (entry.role === 'tool' && entry.toolCall) { collectedTools.set(entry.toolCall.id, entry.toolCall) continue } - const media = await watchHandle?.resolveMediaUrls(client, agentId, sessionId, entry.media, signal) ?? entry.media + // Room messages retain file references so the original account can resolve them on demand. + const media = isRoomTurn ? entry.media + : await watchHandle?.resolveMediaUrls(client, agentId, sessionId, entry.media, readSignal) ?? entry.media assertCurrent() if (!entry.text && !entry.widgets?.length && !entry.richWidgets?.length && !media?.length) continue const messageId = `grok_${entry.entryId}` @@ -238,13 +293,15 @@ export async function watchUntilReply( tools: collectedTools.size ? [...collectedTools.values()] : undefined } bubbles.set(messageId, { entry, bubble }) - if (!streamsInBackground) broadcastGrokEvent({ + receivedReply = true + if (isRoomTurn || !streamsInBackground) broadcastGrokEvent({ type: 'stream', accountId, conversationId: args.conversationId, agentId, sessionId: sessionId || undefined, ...bubble, done: !entry.isStreaming }) if (entry.isStreaming) clearTimeout(settleTimer) else armSettle(isAgentRunning ? GROK_REPLY_SETTLE_MS : 2_200) } + return receivedReply } const resetGeneration = (next: number) => { @@ -257,76 +314,118 @@ export async function watchUntilReply( collectedTools.clear() anchor = undefined anchorOrder = undefined + nextPrompt = undefined nextAnchorLookupAt = 0 + roomProgressUntil = undefined clearTimeout(settleTimer) } + let applied = Promise.resolve() + const applyInOrder = (update: () => Promise) => { + const next = applied.then(update) + applied = next.catch(() => undefined) + return next + } + + let historyTimer: ReturnType | undefined + let historyTask: Promise | undefined + const scheduleHistoryRead = () => { + if (!sentId || signal.aborted || turnFailed || historyTask) return + clearTimeout(historyTimer) + historyTimer = setTimeout(() => { + const readSignal = AbortSignal.any([signal, AbortSignal.timeout(GROK_REPLY_HISTORY_TIMEOUT_MS)]) + // The request runs alongside the live stream. Only applying results needs to be ordered. + historyTask = readTurnHistory(readSignal).then((history) => applyInOrder(async () => { + assertCurrent() + readSignal.throwIfAborted() + if (turnFailed || (history.generation !== undefined && generation !== 0 && history.generation !== generation)) return + echoEntryId ??= history.echoId + if (history.entries.length) await acceptEntries(history.entries, false, readSignal) + })).catch(() => undefined).finally(() => { + historyTask = undefined + scheduleHistoryRead() + }) + }, GROK_REPLY_HISTORY_INTERVAL_MS) + } + try { let failures = 0 let gapFloor: bigint | undefined let lastBackfilled: bigint | undefined + scheduleHistoryRead() while (!signal.aborted && !turnFailed) { assertCurrent() let reconnect = false try { if (gapFloor !== undefined) { const result = await readGrokTranscriptGap(client, { agentId, sessionId }, { floor: gapFloor, signal }) - if (result.generation !== undefined && result.generation > generation) resetGeneration(result.generation) - await acceptEntries(result.entries) - const watermark = grokSeq(result.watermark) - if (watermark > cursor) cursor = watermark + await applyInOrder(async () => { + if (result.generation !== undefined && result.generation > generation) resetGeneration(result.generation) + await acceptEntries(result.entries) + const watermark = grokSeq(result.watermark) + if (watermark > cursor) cursor = watermark + }) gapFloor = undefined } for await (const frame of client.watchTranscripts({ cursors: [{ agent_id: agentId, generation, after_updated_seq: cursor.toString(), session_id: sessionId }], includeUnlistedAgents: false }, signal)) { - assertCurrent() - const tf = asObj(frame['turn_failed'] ?? frame['turnFailed']) - if (tf && matchesScope(tf)) { - const related = str(tf['messageId'] ?? tf['message_id'] ?? tf['clientNonce'] ?? tf['client_nonce']) - if (related && sentId && related !== sentId && related !== echoEntryId && related !== anchor?.entryId) continue - turnFailed = { - code: str(tf['code'] ?? 'TURN_FAILED'), - summary: str(tf['summary'] ?? 'Grok Bot 执行该轮对话失败') + let endStream = false + await applyInOrder(async () => { + assertCurrent() + const tf = asObj(frame['turn_failed'] ?? frame['turnFailed']) + if (tf && matchesScope(tf)) { + const related = str(tf['messageId'] ?? tf['message_id'] ?? tf['clientNonce'] ?? tf['client_nonce']) + if (related && sentId && related !== sentId && related !== echoEntryId && related !== anchor?.entryId) return + turnFailed = { + code: str(tf['code'] ?? 'TURN_FAILED'), + summary: str(tf['summary'] ?? 'Grok Bot 执行该轮对话失败') + } + if (!streamsInBackground) broadcastGrokEvent({ + type: 'turn_failed', accountId, agentId, sessionId: sessionId || undefined, + turnId: str(tf['turnId'] ?? tf['turn_id']) || undefined, ...turnFailed + }) + endStream = true + return } - if (!streamsInBackground) broadcastGrokEvent({ - type: 'turn_failed', accountId, agentId, sessionId: sessionId || undefined, - turnId: str(tf['turnId'] ?? tf['turn_id']) || undefined, ...turnFailed - }) - break - } - const state = asObj(frame['agent_state'] ?? frame['agentState']) - if (state && matchesScope(state)) { - isAgentRunning = Boolean(state['isRunning'] ?? state['is_running']) || - Boolean(state['isComposingMessage'] ?? state['is_composing_message']) - if (isAgentRunning) clearTimeout(settleTimer) - else if ([...bubbles.values()].some(({ entry }) => !entry.isStreaming)) armSettle(1_800) - } - const cleared = asObj(frame['cleared']) - if (cleared && matchesScope(cleared)) { - const next = Number(cleared['newGeneration'] ?? cleared['new_generation']) - if (Number.isSafeInteger(next) && next > generation) resetGeneration(next) - } - const expired = asObj(frame['cursor_too_old'] ?? frame['cursorTooOld']) - if (expired && matchesScope(expired)) { - gapFloor = cursor - if (lastBackfilled !== cursor) { - lastBackfilled = cursor - cursor = 0n - reconnect = true + const state = asObj(frame['agent_state'] ?? frame['agentState']) + if (state && matchesScope(state)) { + isAgentRunning = Boolean(state['isRunning'] ?? state['is_running']) || + Boolean(state['isComposingMessage'] ?? state['is_composing_message']) + if (isAgentRunning) { + if (roomProgressUntil === undefined) clearTimeout(settleTimer) + } else if ([...bubbles.values()].some(({ entry }) => !entry.isStreaming)) { + armSettle(1_800) + } } - break - } - const rows = grokRows(frame) - if (!rows || !matchesScope(rows)) continue - const frameGeneration = Number(rows['generation'] ?? generation) - if (!Number.isSafeInteger(frameGeneration) || frameGeneration < generation) continue - if (frameGeneration > generation) { - if (generation !== 0) resetGeneration(frameGeneration) - else generation = frameGeneration - } - await acceptEntries(transcriptEntries(rows, agentId, sessionId)) + const cleared = asObj(frame['cleared']) + if (cleared && matchesScope(cleared)) { + const next = Number(cleared['newGeneration'] ?? cleared['new_generation']) + if (Number.isSafeInteger(next) && next > generation) resetGeneration(next) + } + const expired = asObj(frame['cursor_too_old'] ?? frame['cursorTooOld']) + if (expired && matchesScope(expired)) { + gapFloor = cursor + if (lastBackfilled !== cursor) { + lastBackfilled = cursor + cursor = 0n + reconnect = true + } + endStream = true + return + } + const rows = grokRows(frame) + if (!rows || !matchesScope(rows)) return + const frameGeneration = Number(rows['generation'] ?? generation) + if (!Number.isSafeInteger(frameGeneration) || frameGeneration < generation) return + if (frameGeneration > generation) { + if (generation !== 0) resetGeneration(frameGeneration) + else generation = frameGeneration + } + if (await acceptEntries(transcriptEntries(rows, agentId, sessionId))) scheduleHistoryRead() + }) + if (endStream) break } } catch (error) { if (signal.aborted) break @@ -348,6 +447,8 @@ export async function watchUntilReply( ac.abort() clearTimeout(timer) clearTimeout(settleTimer) + clearTimeout(historyTimer) + await historyTask } } diff --git a/src/main/grok/grokTranscriptWatch.ts b/src/main/grok/grokTranscriptWatch.ts index 56f05f53..09738416 100644 --- a/src/main/grok/grokTranscriptWatch.ts +++ b/src/main/grok/grokTranscriptWatch.ts @@ -61,12 +61,13 @@ export function isGrokSendAnchor(entry: ParsedGrokTranscriptEntry, messageId: st export async function readGrokTranscriptGap( client: GrokConnectClient, scope: { agentId: string; sessionId: string }, - opts: { floor: bigint; signal: AbortSignal; stopAt?: (entry: ParsedGrokTranscriptEntry) => boolean } + opts: { floor: bigint; signal: AbortSignal; stopAt?: (entry: ParsedGrokTranscriptEntry) => boolean; maxPages?: number } ): Promise<{ entries: ParsedGrokTranscriptEntry[]; generation?: number; watermark: string }> { const entries: ParsedGrokTranscriptEntry[] = [] let generation: number | undefined let watermark = '0' let beforeSeq: string | undefined + let pagesLeft = opts.maxPages ?? Infinity do { opts.signal.throwIfAborted() const page = asObj(await client.listTranscriptEntries({ ...scope, beforeSeq, limit: 40 }, opts.signal)) ?? {} @@ -85,7 +86,7 @@ export async function readGrokTranscriptGap( return opts.stopAt?.(entry) || (seq > 0n && seq <= opts.floor) })) break beforeSeq = nextTranscriptPage(page, batch, beforeSeq) - } while (beforeSeq) + } while (beforeSeq && --pagesLeft > 0) return { entries: entries.sort(compareGrokEntries), generation, watermark } } diff --git a/src/main/grok/grokWatchManager.test.ts b/src/main/grok/grokWatchManager.test.ts index 06af2107..74de8299 100644 --- a/src/main/grok/grokWatchManager.test.ts +++ b/src/main/grok/grokWatchManager.test.ts @@ -1,6 +1,10 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import type { GrokMainEvent } from '@shared/ipc' -import { ensureGrokAccountWatch, stopGrokAccountWatch } from './grokWatchManager' +import { + ensureGrokAccountWatch, + restartGrokAccountWatch, + stopGrokAccountWatch +} from './grokWatchManager' import type { GrokConnectClient } from './connectClient' function b64Json(obj: unknown): string { @@ -18,6 +22,19 @@ const assistant = (id: string, seq: number, text = id, streaming = false) => ({ entry_id: id, kind: 'send-message', seq: String(seq), content: text, is_streaming: streaming }) +function watchHarness(watermarks: Record = {}) { + const listTranscriptEntries = vi.fn(async ({ sessionId }: { agentId: string; sessionId: string }) => ({ + generation: 3, + current_updated_seq: watermarks[sessionId] ?? '0', + entries: [] + })) + const watchTranscripts = vi.fn(async function* (_req: unknown, signal?: AbortSignal) { + await untilAborted(signal) + }) + const client = { listTranscriptEntries, watchTranscripts } as unknown as GrokConnectClient + return { client, listTranscriptEntries, watchTranscripts } +} + describe('grokWatchManager', () => { const accountId = 'acc_watch_test' @@ -399,4 +416,245 @@ describe('grokWatchManager', () => { watch.rebindNetwork() await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(2), { timeout: 300 }) }) + + it('prunes removed session cursors on updateTargets while preserving active cursor watermarks', async () => { + const listTranscriptEntries = vi.fn(async ({ sessionId }: { sessionId: string }) => ({ + generation: 3, + current_updated_seq: sessionId === 'keep' ? '7' : '0', + entries: [] + })) + const watchTranscripts = vi.fn(async function* (_req: unknown, signal?: AbortSignal) { + await untilAborted(signal) + }) + const client = { listTranscriptEntries, watchTranscripts } as unknown as GrokConnectClient + const watch = ensureGrokAccountWatch({ + accountId, + emit: vi.fn(), + createClient: async () => client, + targets: [ + { agentId: 'agent', sessionId: 'old' }, + { agentId: 'agent', sessionId: 'keep' } + ] + }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(1)) + expect(watch.watchesSession('agent', 'old')).toBe(true) + + watch.updateTargets([], undefined, [ + { agentId: 'agent', sessionId: 'keep' }, + { agentId: 'agent', sessionId: 'next' } + ]) + + expect(watch.watchesSession('agent', 'old')).toBe(false) + expect(watch.watchesSession('agent', 'keep')).toBe(true) + expect(watch.watchesSession('agent', 'next')).toBe(true) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(2)) + expect(watchTranscripts.mock.calls[1]?.[0]).toEqual({ + cursors: [ + { agent_id: 'agent', generation: 3, after_updated_seq: '7', session_id: 'keep' }, + { agent_id: 'agent', generation: 3, after_updated_seq: '0', session_id: 'next' } + ] + }) + expect(listTranscriptEntries.mock.calls.map(([req]) => req.sessionId)).toEqual(['old', 'keep', 'next']) + }) + + it('preserves roster agent and conversation cursors when sendMessage binds a session target', async () => { + const { client, watchTranscripts, listTranscriptEntries } = watchHarness({ s1: '5' }) + const opts = { accountId, emit: vi.fn(), createClient: async () => client } + ensureGrokAccountWatch({ ...opts, agentIds: ['a', 'b'], conversationMap: { a: 'conv-a' } }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(1)) + + ensureGrokAccountWatch({ + ...opts, + targets: [{ agentId: 'a', sessionId: 's1', conversationId: 'conv-a' }] + }) + + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(2)) + expect(watchTranscripts.mock.calls[1]?.[0]).toEqual({ + cursors: [ + { agent_id: 'a', generation: 3, after_updated_seq: '0', session_id: '' }, + { agent_id: 'b', generation: 3, after_updated_seq: '0', session_id: '' }, + { agent_id: 'a', generation: 3, after_updated_seq: '5', session_id: 's1' } + ] + }) + expect(listTranscriptEntries.mock.calls.map(([req]) => `${req.agentId}:${req.sessionId}`)).toEqual([ + 'a:', + 'b:', + 'a:s1' + ]) + }) + + it('keeps conversation-bound cursors when listAgents prunes a removed agent cursor', async () => { + const { client, watchTranscripts, listTranscriptEntries } = watchHarness({ s1: '5' }) + const opts = { accountId, emit: vi.fn(), createClient: async () => client } + const watch = ensureGrokAccountWatch({ + ...opts, + agentIds: ['a', 'b'], + conversationMap: { a: 'conv-a' } + }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(1)) + + ensureGrokAccountWatch({ + ...opts, + targets: [{ agentId: 'a', sessionId: 's1', conversationId: 'conv-a' }] + }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(2)) + + ensureGrokAccountWatch({ ...opts, agentIds: ['a'] }) + + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(3)) + expect(watch.watchesSession('b', '')).toBe(false) + expect(watch.watchesSession('a', '')).toBe(true) + expect(watch.watchesSession('a', 's1')).toBe(true) + expect(watchTranscripts.mock.calls[2]?.[0]).toEqual({ + cursors: [ + { agent_id: 'a', generation: 3, after_updated_seq: '0', session_id: '' }, + { agent_id: 'a', generation: 3, after_updated_seq: '5', session_id: 's1' } + ] + }) + expect(listTranscriptEntries.mock.calls.map(([req]) => `${req.agentId}:${req.sessionId}`)).toEqual([ + 'a:', + 'b:', + 'a:s1' + ]) + }) + + it('prunes a removed conversation session cursor on full sync while keeping surviving watermarks', async () => { + const { client, watchTranscripts, listTranscriptEntries } = watchHarness({ s1: '7', s2: '9' }) + const opts = { accountId, emit: vi.fn(), createClient: async () => client } + const watch = ensureGrokAccountWatch({ + ...opts, + agentIds: ['a'], + conversationMap: { a: ['conv-1', 'conv-2'] } + }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(1)) + + ensureGrokAccountWatch({ + ...opts, + targets: [ + { agentId: 'a', sessionId: 's1', conversationId: 'conv-1' }, + { agentId: 'a', sessionId: 's2', conversationId: 'conv-2' } + ] + }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(2)) + expect(watch.watchesSession('a', '')).toBe(true) + + watch.updateTargets(['a'], { a: 'conv-1' }) + + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(3)) + expect(watch.watchesSession('a', 's2')).toBe(false) + expect(watch.watchesSession('a', 's1')).toBe(true) + expect(watch.watchesSession('a', '')).toBe(true) + expect(watchTranscripts.mock.calls[2]?.[0]).toEqual({ + cursors: [ + { agent_id: 'a', generation: 3, after_updated_seq: '0', session_id: '' }, + { agent_id: 'a', generation: 3, after_updated_seq: '7', session_id: 's1' } + ] + }) + expect(listTranscriptEntries.mock.calls.map(([req]) => `${req.agentId}:${req.sessionId}`)).toEqual([ + 'a:', + 'a:s1', + 'a:s2' + ]) + }) + + it('keeps only the latest standalone session pin per agent across incremental updates', async () => { + const { client, watchTranscripts } = watchHarness({ s1: '4', s2: '8' }) + const opts = { accountId, emit: vi.fn(), createClient: async () => client } + const watch = ensureGrokAccountWatch({ ...opts, agentIds: ['a'] }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(1)) + + ensureGrokAccountWatch({ ...opts, targets: [{ agentId: 'a', sessionId: 's1' }] }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(2)) + expect(watch.watchesSession('a', 's1')).toBe(true) + + ensureGrokAccountWatch({ ...opts, agentIds: ['a'] }) + expect(watch.watchesSession('a', 's1')).toBe(true) + expect(watchTranscripts).toHaveBeenCalledTimes(2) + + ensureGrokAccountWatch({ ...opts, targets: [{ agentId: 'a', sessionId: 's2' }] }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(3)) + expect(watch.watchesSession('a', 's1')).toBe(false) + expect(watch.watchesSession('a', 's2')).toBe(true) + + ensureGrokAccountWatch({ ...opts, agentIds: ['a'] }) + expect(watch.watchesSession('a', 's1')).toBe(false) + expect(watchTranscripts).toHaveBeenCalledTimes(3) + expect(watchTranscripts.mock.calls[2]?.[0]).toEqual({ + cursors: [ + { agent_id: 'a', generation: 3, after_updated_seq: '0', session_id: '' }, + { agent_id: 'a', generation: 3, after_updated_seq: '8', session_id: 's2' } + ] + }) + }) + + it('supersedes a standalone pin only when a conversation target matches or moves forward', async () => { + const { client, watchTranscripts } = watchHarness({ s1: '2', s3: '9' }) + const opts = { accountId, emit: vi.fn(), createClient: async () => client } + const watch = ensureGrokAccountWatch({ + ...opts, + agentIds: ['a'], + targets: [{ agentId: 'a', sessionId: 's2' }] + }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(1)) + + ensureGrokAccountWatch({ + ...opts, + targets: [{ agentId: 'a', sessionId: 's1', conversationId: 'conv-old' }] + }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(2)) + + ensureGrokAccountWatch({ ...opts, agentIds: ['a'] }) + expect(watch.watchesSession('a', 's2')).toBe(true) + expect(watch.watchesSession('a', 's1')).toBe(true) + expect(watchTranscripts).toHaveBeenCalledTimes(2) + + ensureGrokAccountWatch({ + ...opts, + targets: [{ agentId: 'a', sessionId: 's2', conversationId: 'conv-current' }] + }) + watch.updateTargets(['a'], { a: 'conv-old' }) + expect(watch.watchesSession('a', 's2')).toBe(false) + expect(watch.watchesSession('a', 's1')).toBe(true) + + ensureGrokAccountWatch({ + ...opts, + targets: [{ agentId: 'a', sessionId: 's3', conversationId: 'conv-current' }] + }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(3)) + expect(watch.watchesSession('a', 's3')).toBe(true) + + watch.updateTargets(['a'], { a: 'conv-old' }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(4)) + expect(watch.watchesSession('a', 's3')).toBe(false) + expect(watchTranscripts.mock.calls[3]?.[0]).toEqual({ + cursors: [ + { agent_id: 'a', generation: 3, after_updated_seq: '0', session_id: '' }, + { agent_id: 'a', generation: 3, after_updated_seq: '2', session_id: 's1' } + ] + }) + }) + + it('does not carry standalone session pins across restart or stop', async () => { + const { client, watchTranscripts } = watchHarness() + const opts = { accountId, emit: vi.fn(), createClient: async () => client } + ensureGrokAccountWatch({ ...opts, agentIds: ['a'], targets: [{ agentId: 'a', sessionId: 's1' }] }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(1)) + + restartGrokAccountWatch(accountId) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(2)) + expect(watchTranscripts.mock.calls[1]?.[0]).toEqual({ cursors: [] }) + + ensureGrokAccountWatch({ ...opts, agentIds: ['a'] }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(3)) + expect(watchTranscripts.mock.calls[2]?.[0]).toEqual({ + cursors: [{ agent_id: 'a', generation: 3, after_updated_seq: '0', session_id: '' }] + }) + + stopGrokAccountWatch(accountId) + ensureGrokAccountWatch({ ...opts, agentIds: ['a'] }) + await vi.waitFor(() => expect(watchTranscripts).toHaveBeenCalledTimes(4)) + expect(watchTranscripts.mock.calls[3]?.[0]).toEqual({ + cursors: [{ agent_id: 'a', generation: 3, after_updated_seq: '0', session_id: '' }] + }) + }) }) diff --git a/src/main/grok/grokWatchManager.ts b/src/main/grok/grokWatchManager.ts index 5c713845..709c14fb 100644 --- a/src/main/grok/grokWatchManager.ts +++ b/src/main/grok/grokWatchManager.ts @@ -52,7 +52,7 @@ export interface GrokAccountWatchHandle { rebindNetwork: () => void watchesSession: (agentId: string, sessionId: string) => boolean updateTargets: ( - agentIds: string[], + agentIds?: string[], conversationMap?: Record, targets?: GrokWatchTarget[] ) => void @@ -71,6 +71,15 @@ function maxSeqStr(a: string, b: string): string { return grokSeq(a) >= grokSeq(b) ? a : b } +function sessionAtOrAfter(sessionId: string, pinned: string): boolean { + if (sessionId === pinned) return true + if (!sessionId) return false + if (/^\d+$/.test(sessionId) && /^\d+$/.test(pinned)) { + return BigInt(sessionId) > BigInt(pinned) + } + return sessionId > pinned +} + const ACTIVITY_LABELS: Record = { '1': { text: '正在执行命令…', emoji: '⚡' }, GROK_BOT_AGENT_ACTIVITY_CODE_RUNNING_COMMAND: { text: '正在执行命令…', emoji: '⚡' }, @@ -108,6 +117,7 @@ class AccountWatchController implements GrokAccountWatchHandle { private readonly emit: (event: GrokMainEvent) => void private readonly cursors = new Map() private readonly conversations = new Map() + private readonly standalonePins = new Map() private readonly conversationsByScope = new Map>() private readonly boundAgents = new Set() private readonly approvals = new Map() @@ -168,11 +178,12 @@ class AccountWatchController implements GrokAccountWatchHandle { } updateTargets( - agentIds: string[], + agentIds?: string[], conversationMap?: Record, targets: GrokWatchTarget[] = [] ): void { - const size = this.cursors.size + const previousKeys = new Set(this.cursors.keys()) + const liveKeys = new Set() if (conversationMap) { const previous = new Map(this.conversations) this.conversations.clear() @@ -182,17 +193,49 @@ class AccountWatchController implements GrokAccountWatchHandle { if (!conversationId) continue const old = previous.get(conversationId) const sessionId = old?.agentId === agentId ? old.sessionId : '' + liveKeys.add(grokSessionKey(agentId, sessionId)) this.cursor(agentId, sessionId) this.conversations.set(conversationId, { agentId, sessionId }) } } + } else { + for (const { agentId, sessionId } of this.conversations.values()) { + liveKeys.add(grokSessionKey(agentId, sessionId)) + } + } + if (Array.isArray(agentIds)) { + for (const id of agentIds) { + if (!id) continue + liveKeys.add(grokSessionKey(id, '')) + this.cursor(id, '') + } + } else { + for (const cursor of this.cursors.values()) { + if (!cursor.sessionId) liveKeys.add(grokSessionKey(cursor.agentId, '')) + } } - for (const id of agentIds) if (id) this.cursor(id, '') for (const target of targets) { const { agentId, sessionId, conversationId } = target if (!agentId || typeof sessionId !== 'string') continue + liveKeys.add(grokSessionKey(agentId, sessionId)) this.cursor(agentId, sessionId) - if (conversationId) this.conversations.set(conversationId, target) + if (conversationId) { + this.conversations.set(conversationId, target) + const pinned = this.standalonePins.get(agentId) + if (pinned !== undefined && sessionAtOrAfter(sessionId, pinned)) { + this.standalonePins.delete(agentId) + } + } else if (sessionId) { + this.standalonePins.set(agentId, sessionId) + } + } + for (const [agentId, sessionId] of this.standalonePins) { + liveKeys.add(grokSessionKey(agentId, sessionId)) + } + for (const key of this.cursors.keys()) { + if (liveKeys.has(key)) continue + this.cursors.delete(key) + this.recentTools.delete(key) } if (conversationMap || targets.some((target) => target.conversationId)) { this.conversationsByScope.clear() @@ -205,7 +248,8 @@ class AccountWatchController implements GrokAccountWatchHandle { this.boundAgents.add(target.agentId) } } - if (!this.stopped && (!this.loopPromise || this.cursors.size !== size)) { + const changed = previousKeys.size !== liveKeys.size || [...liveKeys].some((key) => !previousKeys.has(key)) + if (!this.stopped && (!this.loopPromise || changed)) { this.triggerReconnect() } } @@ -668,7 +712,7 @@ export function ensureGrokAccountWatch(opts: { }) watches.set(opts.accountId, ctrl) } - ctrl.updateTargets(opts.agentIds ?? [], opts.conversationMap, opts.targets) + ctrl.updateTargets(opts.agentIds, opts.conversationMap, opts.targets) return ctrl } diff --git a/src/main/index.ts b/src/main/index.ts index 20f7cf87..77af3695 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -5,7 +5,7 @@ import { getNativeDisplayLocale, setNativeDisplayLocale } from './nativeDisplayC import { registerSlackIpc, stopSlack } from './slack/slackIpc' import { registerWorkspaceIpc, stopWorkspaces } from './mcp/hub' import { registerWorkspacePortalIpc, stopWorkspacePortals } from './mcp/workspacePortal' -import { appendFileSync, existsSync } from 'node:fs' +import { appendFileSync } from 'node:fs' import { join } from 'node:path' import { app, autoUpdater, BrowserWindow, ipcMain, Menu, type Rectangle } from 'electron' import { SETTINGS_MENU_CHANNEL } from '@shared/settingsMenu' @@ -45,6 +45,7 @@ import { hasPopouts, registerPopoutIpc, restorePopouts } from './goxfPopout' import { openInApp, registerInAppIpc } from './goxfInApp' import { allowHarkLiveViewFrames } from './goxfLiveView' import { hideToTray, registerTrayIpc, startTray } from './goxfTray' +import { resolveUserDataDir } from './portableDataDir' try { app.commandLine?.appendSwitch?.('disable-blink-features', 'AutomationControlled') @@ -120,25 +121,22 @@ app.on('open-url', (event, url) => { dispatchCueCallback(url) }) -// Seamless upgrade from legacy "bothub" userData directory: if an existing user -// already has accounts/sessions in Application Support/bothub and no new botark -// directory yet, preserve their exact userData directory automatically. -try { - const appData = app.getPath('appData') - const newUserData = join(appData, 'botark') - const legacyUserData = join(appData, 'bothub') - const legacyHasData = - existsSync(join(legacyUserData, 'Partitions')) || - existsSync(join(legacyUserData, 'grok-sand-tokens.json')) - const newHasData = - existsSync(join(newUserData, 'Partitions')) || - existsSync(join(newUserData, 'grok-sand-tokens.json')) || - existsSync(join(newUserData, 'cue-tokens.json')) - if (!isPortable() && existsSync(legacyUserData) && (legacyHasData || !existsSync(newUserData)) && !newHasData) { - app.setPath('userData', legacyUserData) +// GOXF fork: goxfPortable (first import) already pinned userData for our portable builds; upstream's +// resolver handles --user-data-dir and the legacy bothub dir for everything else. +if (!isPortable()) { + const userDataResolution = resolveUserDataDir({ + argv: process.argv, + env: process.env, + platform: process.platform, + execPath: process.execPath, + exePath: app.getPath('exe'), + appDataPath: app.getPath('appData'), + defaultUserDataPath: app.getPath('userData') + }) + if (userDataResolution.warning) { + console.warn(userDataResolution.warning) } -} catch { - /* ignore */ + app.setPath('userData', userDataResolution.dir) } // Two instances share userData and race on every JSON store and on diff --git a/src/main/macCodeSignature.test.ts b/src/main/macCodeSignature.test.ts new file mode 100644 index 00000000..03b38f9e --- /dev/null +++ b/src/main/macCodeSignature.test.ts @@ -0,0 +1,120 @@ +import { EventEmitter } from 'node:events' +import { mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const dir = mkdtempSync(join(tmpdir(), 'botark-codesign-')) +const spawnMock = vi.fn() +const spawnSyncMock = vi.fn((..._args: unknown[]) => { throw new Error('spawnSync blocks the main process') }) + +vi.mock('node:child_process', () => ({ + spawn: (...args: unknown[]) => spawnMock(...args), + spawnSync: (...args: unknown[]) => spawnSyncMock(...args) +})) + +vi.mock('electron', () => ({ + app: { + getPath: () => dir, + isPackaged: true + }, + ipcMain: { handle: vi.fn() }, + safeStorage: { + isEncryptionAvailable: () => true, + isAsyncEncryptionAvailable: async () => true, + getSelectedStorageBackend: () => 'keychain' + }, + session: { fromPartition: () => ({ setProxy: vi.fn(async () => undefined) }) } +})) + +vi.mock('./webContentsViewManager', () => ({ + partitionForAccount: (id: string) => `persist:bothub-account-${id}` +})) + +const loadVault = async () => { + vi.resetModules() + return import('./securityVault') +} + +const originalPlatform = process.platform + +function fakeCodesignChild() { + const child = new EventEmitter() as EventEmitter & { + stdout: EventEmitter + stderr: EventEmitter + kill: ReturnType + } + child.stdout = new EventEmitter() + child.stderr = new EventEmitter() + child.kill = vi.fn() + return child +} + +beforeEach(() => { + spawnMock.mockReset() + spawnSyncMock.mockClear() + Object.defineProperty(process, 'platform', { value: 'darwin', configurable: true }) +}) + +afterEach(() => { + Object.defineProperty(process, 'platform', { value: originalPlatform, configurable: true }) + vi.useRealTimers() +}) + +afterAll(() => rmSync(dir, { recursive: true, force: true })) + +describe('inspectMacCodeSignature', () => { + it('inspects codesign asynchronously without blocking the event loop and caches the result', async () => { + const { getSecurityVaultStatus, inspectMacCodeSignature } = await loadVault() + const child = fakeCodesignChild() + spawnMock.mockReturnValue(child) + + let settled = false + const pending = getSecurityVaultStatus().then((status) => { + settled = true + return status + }) + await new Promise((r) => setTimeout(r, 10)) + expect(settled).toBe(false) + expect(spawnSyncMock).not.toHaveBeenCalled() + expect(spawnMock).toHaveBeenCalledTimes(1) + expect(spawnMock.mock.calls[0]?.[0]).toBe('/usr/bin/codesign') + + child.stderr.emit('data', Buffer.from('Executable=/Applications/BotArk.app/Contents/MacOS/BotArk\nAuthority=Developer ID Application: BotArk (TEAMID)\n')) + child.emit('close', 0) + + const status = await pending + expect(status.codeSigned).toBe(true) + expect(status.signingAuthority).toBe('Developer ID Application: BotArk (TEAMID)') + await expect(inspectMacCodeSignature()).resolves.toEqual({ codeSigned: true, authority: 'Developer ID Application: BotArk (TEAMID)' }) + expect(spawnMock).toHaveBeenCalledTimes(1) + }) + + it('shares one in-flight codesign process across concurrent callers and fails closed on error', async () => { + const { inspectMacCodeSignature } = await loadVault() + const child = fakeCodesignChild() + spawnMock.mockReturnValue(child) + + const first = inspectMacCodeSignature() + const second = inspectMacCodeSignature() + expect(spawnMock).toHaveBeenCalledTimes(1) + child.emit('error', new Error('codesign missing')) + child.emit('close', 1) + + await expect(first).resolves.toEqual({ codeSigned: false }) + await expect(second).resolves.toEqual({ codeSigned: false }) + }) + + it('terminates a stalled codesign process after the deadline and reports unsigned', async () => { + const { inspectMacCodeSignature } = await loadVault() + vi.useFakeTimers() + const child = fakeCodesignChild() + spawnMock.mockReturnValue(child) + + const pending = inspectMacCodeSignature() + await vi.advanceTimersByTimeAsync(3_500) + expect(child.kill).toHaveBeenCalledWith('SIGKILL') + child.emit('close', null) + await expect(pending).resolves.toEqual({ codeSigned: false }) + }) +}) diff --git a/src/main/mcp/hub.test.ts b/src/main/mcp/hub.test.ts index d9b7e7e1..8cb37b36 100644 --- a/src/main/mcp/hub.test.ts +++ b/src/main/mcp/hub.test.ts @@ -6,6 +6,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { parse } from 'yaml' import { Client } from '@modelcontextprotocol/sdk/client/index.js' import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js' +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js' import { Server } from '@modelcontextprotocol/sdk/server/index.js' import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js' import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js' @@ -575,4 +576,63 @@ describe('workspace MCP hub', () => { stdioEchoScript('custom_kept') ]) }) + + it('keeps a fast-connected server alive when tools/list finishes after the connect timeout', async () => { + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair() + const mcp = new Server({ name: 'slow-tools', version: '1' }, { capabilities: { tools: {} } }) + let markListStarted!: () => void + const listStarted = new Promise((resolve) => { + markListStarted = resolve + }) + mcp.setRequestHandler(ListToolsRequestSchema, async () => { + markListStarted() + // Under VITEST, CONNECT_TIMEOUT_MS is 2_500 and LIST_TOOLS_TIMEOUT_MS is 4_000. + await new Promise((resolve) => setTimeout(resolve, 3_000)) + return { tools: [{ name: 'slow_ping', inputSchema: { type: 'object' } }] } + }) + await mcp.connect(serverTransport) + + const realConnect = Client.prototype.connect + const connectSpy = vi.spyOn(Client.prototype, 'connect').mockImplementation(function ( + this: Client, + _transport, + options + ) { + return realConnect.call(this, clientTransport, options) + }) + + vi.useFakeTimers() + try { + await request('room', { + op: 'upsert', + server: { + name: 'slow-tools', + transport: 'streamable-http', + url: 'http://127.0.0.1:9/mcp' + } + }) + const outcome = request('room', { op: 'start', server: 'slow-tools' }).then( + (view) => ({ ok: true as const, view }), + (error: unknown) => ({ ok: false as const, error }) + ) + + await listStarted + await vi.advanceTimersByTimeAsync(2_600) + await vi.advanceTimersByTimeAsync(1_000) + + const result = await outcome + expect(result.ok ? undefined : result.error).toBeUndefined() + if (!result.ok) throw result.error + expect(result.view.servers.find((s) => s.name === 'slow-tools')).toMatchObject({ + running: true, + toolCount: 1 + }) + expect(result.view.tools.some((t) => t.name.endsWith('__slow_ping'))).toBe(true) + } finally { + connectSpy.mockRestore() + vi.useRealTimers() + await stopWorkspaces() + await mcp.close() + } + }) }) diff --git a/src/main/mcp/hub.ts b/src/main/mcp/hub.ts index f50c6c5b..837404ed 100644 --- a/src/main/mcp/hub.ts +++ b/src/main/mcp/hub.ts @@ -659,6 +659,7 @@ async function startExternal( throw new Error(`无效的 MCP 配置(${name}):缺少 command 或 url`) } + clearTimeout(timeoutTimer) assertStarting() const tools: WorkspaceTool[] = [] diff --git a/src/main/portableDataDir.test.ts b/src/main/portableDataDir.test.ts new file mode 100644 index 00000000..9f3b888e --- /dev/null +++ b/src/main/portableDataDir.test.ts @@ -0,0 +1,295 @@ +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { resolveUserDataDir, type UserDataDirContext } from './portableDataDir' + +let root = '' +const readOnlyDirs: string[] = [] + +beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'botark-portable-')) +}) + +afterEach(() => { + for (const dir of readOnlyDirs.splice(0)) { + chmodSync(dir, 0o755) + } + rmSync(root, { recursive: true, force: true }) +}) + +function makeReadOnly(dir: string): void { + mkdirSync(dir, { recursive: true }) + readOnlyDirs.push(dir) + chmodSync(dir, 0o555) +} + +function makeContext(overrides: Partial = {}): UserDataDirContext { + const appDataPath = join(root, 'appData') + return { + argv: [], + env: {}, + platform: 'win32', + execPath: join(root, 'extracted', 'BotArk.exe'), + exePath: join(root, 'bin', 'BotArk.exe'), + appDataPath, + defaultUserDataPath: join(appDataPath, 'botark'), + ...overrides + } +} + +function seedLegacyBothub(appDataPath: string): string { + const legacy = join(appDataPath, 'bothub') + mkdirSync(join(legacy, 'Partitions'), { recursive: true }) + return legacy +} + +describe('resolveUserDataDir', () => { + it('creates BotArkData under PORTABLE_EXECUTABLE_DIR on Windows', () => { + const portableExeDir = join(root, 'PortableDrive') + mkdirSync(portableExeDir) + const ctx = makeContext({ + env: { PORTABLE_EXECUTABLE_DIR: portableExeDir } + }) + + const result = resolveUserDataDir(ctx) + + expect(result).toEqual({ + source: 'portable', + dir: join(portableExeDir, 'BotArkData') + }) + expect(readdirSync(join(portableExeDir, 'BotArkData'))).toEqual([]) + }) + + it('prefers PORTABLE_EXECUTABLE_DIR over a marker next to the extracted exe', () => { + const portableExeDir = join(root, 'PortableDrive') + const extractedDir = join(root, 'extracted') + mkdirSync(portableExeDir) + mkdirSync(extractedDir) + writeFileSync(join(extractedDir, '.botark-portable'), '') + + const result = resolveUserDataDir(makeContext({ + env: { PORTABLE_EXECUTABLE_DIR: portableExeDir } + })) + + expect(result.dir).toBe(join(portableExeDir, 'BotArkData')) + }) + + it.each(['win32', 'linux'])('uses an existing BotArkData folder next to the executable on %s', (platform) => { + const exeDir = join(root, 'bin') + const dataDir = join(exeDir, 'BotArkData') + mkdirSync(dataDir, { recursive: true }) + + const result = resolveUserDataDir(makeContext({ platform })) + + expect(result).toEqual({ source: 'portable', dir: dataDir }) + }) + + it('creates BotArkData next to the executable when a .botark-portable marker exists', () => { + const exeDir = join(root, 'bin') + mkdirSync(exeDir) + writeFileSync(join(exeDir, '.botark-portable'), '') + + const result = resolveUserDataDir(makeContext()) + + expect(result).toEqual({ source: 'portable', dir: join(exeDir, 'BotArkData') }) + expect(existsSync(join(exeDir, 'BotArkData'))).toBe(true) + }) + + it('stays on default userData when no marker or BotArkData folder exists next to the executable', () => { + const ctx = makeContext() + mkdirSync(join(root, 'bin')) + + expect(resolveUserDataDir(ctx)).toEqual({ + source: 'default', + dir: ctx.defaultUserDataPath + }) + }) + + it('detects a sibling BotArkData folder next to BotArk.app on macOS', () => { + const dataDir = join(root, 'BotArkData') + const execPath = join(root, 'BotArk.app', 'Contents', 'MacOS', 'BotArk') + mkdirSync(dataDir) + + const result = resolveUserDataDir(makeContext({ platform: 'darwin', execPath })) + + expect(result).toEqual({ source: 'portable', dir: dataDir }) + }) + + it('creates BotArkData next to BotArk.app on macOS when .botark-portable exists', () => { + const execPath = join(root, 'BotArk.app', 'Contents', 'MacOS', 'BotArk') + mkdirSync(join(root, 'BotArk.app', 'Contents', 'MacOS'), { recursive: true }) + writeFileSync(join(root, '.botark-portable'), '') + + const result = resolveUserDataDir(makeContext({ platform: 'darwin', execPath })) + + expect(result).toEqual({ source: 'portable', dir: join(root, 'BotArkData') }) + expect(existsSync(join(root, 'BotArkData'))).toBe(true) + }) + + it('ignores markers inside the macOS bundle or outside a .app bundle', () => { + const appMacos = join(root, 'BotArk.app', 'Contents', 'MacOS') + mkdirSync(appMacos, { recursive: true }) + writeFileSync(join(appMacos, '.botark-portable'), '') + + expect(resolveUserDataDir(makeContext({ platform: 'darwin', execPath: join(appMacos, 'BotArk') })).source) + .toBe('default') + + const bareDir = join(root, 'bare') + mkdirSync(bareDir) + writeFileSync(join(bareDir, '.botark-portable'), '') + expect(resolveUserDataDir(makeContext({ platform: 'darwin', execPath: join(bareDir, 'BotArk') })).source) + .toBe('default') + }) + + it('lets an explicit --user-data-dir CLI arg win over portable mode and legacy migration', () => { + const portableExeDir = join(root, 'PortableDrive') + const cliDir = join(root, 'CliData') + const exeDir = join(root, 'bin') + mkdirSync(portableExeDir) + mkdirSync(exeDir) + writeFileSync(join(exeDir, '.botark-portable'), '') + seedLegacyBothub(join(root, 'appData')) + + const equalsArg = resolveUserDataDir(makeContext({ + argv: ['BotArk.exe', `--user-data-dir=${cliDir}`, '--open-grok-login'], + env: { PORTABLE_EXECUTABLE_DIR: portableExeDir } + })) + expect(equalsArg).toEqual({ source: 'cli', dir: cliDir }) + + const spacedArg = resolveUserDataDir(makeContext({ + argv: ['BotArk.exe', '--user-data-dir', cliDir], + env: { PORTABLE_EXECUTABLE_DIR: portableExeDir } + })) + expect(spacedArg).toEqual({ source: 'cli', dir: cliDir }) + }) + + it('uses the last non-empty --user-data-dir and ignores empty values', () => { + const portableExeDir = join(root, 'PortableDrive') + mkdirSync(portableExeDir) + + const repeated = resolveUserDataDir(makeContext({ + argv: ['BotArk.exe', '--user-data-dir=first', '--user-data-dir=second'] + })) + expect(repeated).toEqual({ source: 'cli', dir: join(process.cwd(), 'second') }) + + const empty = resolveUserDataDir(makeContext({ + argv: ['BotArk.exe', '--user-data-dir=', '--user-data-dir', '--open-grok-login'], + env: { PORTABLE_EXECUTABLE_DIR: portableExeDir } + })) + expect(empty).toEqual({ source: 'portable', dir: join(portableExeDir, 'BotArkData') }) + }) + + it('takes precedence over the legacy bothub migration', () => { + const ctx = makeContext() + const legacy = seedLegacyBothub(ctx.appDataPath) + const portableExeDir = join(root, 'PortableDrive') + mkdirSync(portableExeDir) + + const result = resolveUserDataDir({ + ...ctx, + env: { PORTABLE_EXECUTABLE_DIR: portableExeDir } + }) + + expect(legacy).not.toBe(result.dir) + expect(result).toEqual({ source: 'portable', dir: join(portableExeDir, 'BotArkData') }) + }) + + it('takes precedence over legacy bothub migration on macOS via a sibling marker', () => { + const execPath = join(root, 'BotArk.app', 'Contents', 'MacOS', 'BotArk') + const ctx = makeContext({ platform: 'darwin', execPath }) + seedLegacyBothub(ctx.appDataPath) + mkdirSync(join(root, 'BotArk.app', 'Contents', 'MacOS'), { recursive: true }) + writeFileSync(join(root, '.botark-portable'), '') + + const result = resolveUserDataDir(ctx) + + expect(result).toEqual({ source: 'portable', dir: join(root, 'BotArkData') }) + }) + + // Windows ignores chmod read-only bits on directories, so permission-denied + // directory fixtures only apply on POSIX. Windows fallback is covered below. + it.skipIf(process.platform === 'win32')('falls back to default userData with a warning when the portable parent is read-only', () => { + const portableExeDir = join(root, 'ReadOnlyDmg') + makeReadOnly(portableExeDir) + + const result = resolveUserDataDir(makeContext({ + env: { PORTABLE_EXECUTABLE_DIR: portableExeDir } + })) + + expect(result.source).toBe('fallback') + expect(result.dir).toBe(join(root, 'appData', 'botark')) + expect(result.warning).toContain(join(portableExeDir, 'BotArkData')) + expect(existsSync(join(portableExeDir, 'BotArkData'))).toBe(false) + }) + + it.skipIf(process.platform === 'win32')('falls back to default userData with a warning when an existing BotArkData folder is read-only', () => { + const exeDir = join(root, 'bin') + const dataDir = join(exeDir, 'BotArkData') + makeReadOnly(dataDir) + + const result = resolveUserDataDir(makeContext()) + + expect(result.source).toBe('fallback') + expect(result.dir).toBe(join(root, 'appData', 'botark')) + expect(result.warning).toContain(dataDir) + }) + + it('falls back to default userData when PORTABLE_EXECUTABLE_DIR is a regular file', () => { + const portableExeFile = join(root, 'NotADirectory') + writeFileSync(portableExeFile, 'file') + + const result = resolveUserDataDir(makeContext({ + env: { PORTABLE_EXECUTABLE_DIR: portableExeFile } + })) + + expect(result.source).toBe('fallback') + expect(result.dir).toBe(join(root, 'appData', 'botark')) + expect(result.warning).toBeDefined() + }) + + it('falls back without throwing when BotArkData is a regular file', () => { + const exeDir = join(root, 'bin') + mkdirSync(exeDir) + writeFileSync(join(exeDir, '.botark-portable'), '') + writeFileSync(join(exeDir, 'BotArkData'), 'not a directory') + + const result = resolveUserDataDir(makeContext()) + + expect(result.source).toBe('fallback') + expect(result.dir).toBe(join(root, 'appData', 'botark')) + expect(result.warning).toBeDefined() + }) + + it('skips legacy bothub migration when portable mode falls back to default userData', () => { + const portableExeFile = join(root, 'NotADirectory') + writeFileSync(portableExeFile, 'file') + const ctx = makeContext({ env: { PORTABLE_EXECUTABLE_DIR: portableExeFile } }) + const legacy = seedLegacyBothub(ctx.appDataPath) + + const result = resolveUserDataDir(ctx) + + expect(result.dir).toBe(ctx.defaultUserDataPath) + expect(result.dir).not.toBe(legacy) + expect(result.source).toBe('fallback') + }) + + it('keeps the legacy bothub migration when portable mode is not active', () => { + const ctx = makeContext() + const legacy = seedLegacyBothub(ctx.appDataPath) + + expect(resolveUserDataDir(ctx)).toEqual({ source: 'legacy', dir: legacy }) + + mkdirSync(join(ctx.appDataPath, 'botark', 'Partitions'), { recursive: true }) + expect(resolveUserDataDir(ctx)).toEqual({ source: 'default', dir: ctx.defaultUserDataPath }) + }) + + it('leaves no write-probe files behind in a writable portable directory', () => { + const portableExeDir = join(root, 'PortableDrive') + mkdirSync(portableExeDir) + + resolveUserDataDir(makeContext({ env: { PORTABLE_EXECUTABLE_DIR: portableExeDir } })) + + expect(readdirSync(join(portableExeDir, 'BotArkData'))).toEqual([]) + }) +}) diff --git a/src/main/portableDataDir.ts b/src/main/portableDataDir.ts new file mode 100644 index 00000000..cc157ba7 --- /dev/null +++ b/src/main/portableDataDir.ts @@ -0,0 +1,160 @@ +import { closeSync, existsSync, mkdirSync, openSync, statSync, unlinkSync } from 'node:fs' +import { basename, dirname, join, resolve } from 'node:path' + +const CLI_FLAG = '--user-data-dir' +const PORTABLE_DATA_DIRNAME = 'BotArkData' +const PORTABLE_MARKER = '.botark-portable' + +export interface UserDataDirContext { + argv: readonly string[] + env: Readonly> + platform: string + execPath: string + exePath: string + appDataPath: string + defaultUserDataPath: string +} + +export type UserDataDirResolution = + | { source: 'cli' | 'portable' | 'legacy' | 'default'; dir: string; warning?: undefined } + | { source: 'fallback'; dir: string; warning: string } + +function unquote(value: string): string { + const trimmed = value.trim() + const first = trimmed[0] + if (trimmed.length >= 2 && (first === '"' || first === "'") && trimmed.endsWith(first)) { + return trimmed.slice(1, -1).trim() + } + return trimmed +} + +function findCliUserDataDir(argv: readonly string[]): string | null { + let found: string | null = null + for (let i = 0; i < argv.length; i++) { + const arg = argv[i]! + if (arg.startsWith(`${CLI_FLAG}=`)) { + const value = unquote(arg.slice(CLI_FLAG.length + 1)) + if (value) found = value + } else if (arg === CLI_FLAG) { + const next = argv[i + 1] + if (next && !next.startsWith('--')) { + const value = unquote(next) + if (value) found = value + i++ + } + } + } + return found ? resolve(found) : null +} + +function isDirectory(path: string): boolean { + try { + return statSync(path).isDirectory() + } catch { + return false + } +} + +function macAppParentDir(execPath: string): string | null { + const macosDir = dirname(execPath) + if (basename(macosDir) !== 'MacOS') return null + const contentsDir = dirname(macosDir) + if (basename(contentsDir) !== 'Contents') return null + const bundleDir = dirname(contentsDir) + const bundleName = basename(bundleDir) + if (!bundleName.endsWith('.app') || bundleName.length <= '.app'.length) return null + return dirname(bundleDir) +} + +function findPortableCandidate(context: UserDataDirContext): string | null { + // electron-builder's Windows portable launcher unpacks into %TEMP% and sets + // PORTABLE_EXECUTABLE_DIR to the folder that holds the original .exe. + const portableExeDir = context.env['PORTABLE_EXECUTABLE_DIR']?.trim() + if (portableExeDir) return join(resolve(portableExeDir), PORTABLE_DATA_DIRNAME) + + const anchorDir = context.platform === 'darwin' + ? macAppParentDir(context.execPath) + : context.exePath + ? dirname(context.exePath) + : null + if (!anchorDir) return null + + const dataDir = join(anchorDir, PORTABLE_DATA_DIRNAME) + if (isDirectory(dataDir) || existsSync(join(anchorDir, PORTABLE_MARKER))) { + return dataDir + } + return null +} + +function ensureWritableDir(dir: string): void { + mkdirSync(dir, { recursive: true }) + if (!isDirectory(dir)) { + throw new Error('not a directory') + } + // Windows ignores directory read-only attributes in accessSync, so probe an + // actual file create + delete to prove stores can persist here. + const probe = join(dir, `.botark-write-probe-${process.pid}-${Date.now()}`) + let fd: number | undefined + try { + fd = openSync(probe, 'wx', 0o600) + } finally { + if (fd !== undefined) { + try { + closeSync(fd) + } catch { + /* ignore */ + } + } + try { + unlinkSync(probe) + } catch { + /* ignore */ + } + } +} + +function resolveLegacyUserDataDir(appDataPath: string): string | null { + try { + const newUserData = join(appDataPath, 'botark') + const legacyUserData = join(appDataPath, 'bothub') + const legacyHasData = + existsSync(join(legacyUserData, 'Partitions')) || + existsSync(join(legacyUserData, 'grok-sand-tokens.json')) + const newHasData = + existsSync(join(newUserData, 'Partitions')) || + existsSync(join(newUserData, 'grok-sand-tokens.json')) || + existsSync(join(newUserData, 'cue-tokens.json')) + if (existsSync(legacyUserData) && (legacyHasData || !existsSync(newUserData)) && !newHasData) { + return legacyUserData + } + } catch { + /* ignore */ + } + return null +} + +export function resolveUserDataDir(context: UserDataDirContext): UserDataDirResolution { + const cliDir = findCliUserDataDir(context.argv) + if (cliDir) return { source: 'cli', dir: cliDir } + + let portableCandidate: string | null = null + try { + portableCandidate = findPortableCandidate(context) + if (portableCandidate) { + ensureWritableDir(portableCandidate) + return { source: 'portable', dir: portableCandidate } + } + } catch (error) { + const reason = error instanceof Error ? error.message : String(error) + const target = portableCandidate ?? context.defaultUserDataPath + return { + source: 'fallback', + dir: context.defaultUserDataPath, + warning: `[bothub] portable data directory "${target}" is not writable (${reason}); using "${context.defaultUserDataPath}"` + } + } + + const legacyDir = resolveLegacyUserDataDir(context.appDataPath) + if (legacyDir) return { source: 'legacy', dir: legacyDir } + return { source: 'default', dir: context.defaultUserDataPath } +} diff --git a/src/main/securityVault.ts b/src/main/securityVault.ts index e3033713..cc0a0a0a 100644 --- a/src/main/securityVault.ts +++ b/src/main/securityVault.ts @@ -9,7 +9,7 @@ * `hardenVaultFilePermissions`) surfaced in the Right-Side Inspector & Settings. * 3. Shared macOS `Developer ID Application` code-signature detector for `updater.ts`. */ -import { spawnSync } from 'node:child_process' +import { spawn } from 'node:child_process' import { chmodSync, existsSync, statSync } from 'node:fs' import { join } from 'node:path' import { app, ipcMain, safeStorage } from 'electron' @@ -236,46 +236,63 @@ function clearPublicVaultSecrets(): Promise { ))) } -let cachedSignatureInfo: { codeSigned: boolean; authority?: string } | null = null +type MacSignatureInfo = { codeSigned: boolean; authority?: string } +let signaturePromise: Promise | undefined /** * Inspect whether the running macOS `.app` bundle carries a valid - * `Developer ID Application` signature (cached per process). + * `Developer ID Application` signature without blocking the main process + * (single-flight, cached per process). */ -export function inspectMacCodeSignature(): { codeSigned: boolean; authority?: string } { - if (cachedSignatureInfo) return cachedSignatureInfo +export function inspectMacCodeSignature(): Promise { + if (signaturePromise) return signaturePromise if (process.platform !== 'darwin' || !app.isPackaged) { - cachedSignatureInfo = { codeSigned: process.platform !== 'darwin' && Boolean(app.isPackaged) } - return cachedSignatureInfo + signaturePromise = Promise.resolve({ codeSigned: process.platform !== 'darwin' && Boolean(app.isPackaged) }) + return signaturePromise } - try { + signaturePromise = new Promise((resolve) => { const exe = process.execPath const appIdx = exe.indexOf('.app/') const bundlePath = appIdx > 0 ? exe.slice(0, appIdx + 4) : exe - // `codesign -dv` normally writes its signature metadata to stderr. - const result = spawnSync('/usr/bin/codesign', ['-dv', '--verbose=2', bundlePath], { - encoding: 'utf8', - stdio: ['ignore', 'pipe', 'pipe'], - timeout: 3_500 - }) - if (result.status === 0 && !result.error) { - return parseCodesignOutput(`${result.stdout ?? ''}\n${result.stderr ?? ''}`) + let child: ReturnType + try { + // `codesign -dv` writes its signature metadata to stderr. + child = spawn('/usr/bin/codesign', ['-dv', '--verbose=2', bundlePath], { + stdio: ['ignore', 'pipe', 'pipe'] + }) + } catch { + resolve({ codeSigned: false }) + return } - } catch { - /* codesign is unavailable */ - } - cachedSignatureInfo = { codeSigned: false } - return cachedSignatureInfo -} - -function parseCodesignOutput(raw: string): { codeSigned: boolean; authority?: string } { - const match = /^Authority=(Developer ID Application:[^\r\n]+)$/m.exec(raw) - if (match?.[1]) { - cachedSignatureInfo = { codeSigned: true, authority: match[1].trim() } - return cachedSignatureInfo - } - cachedSignatureInfo = { codeSigned: false } - return cachedSignatureInfo + let stdout = '' + let stderr = '' + let settled = false + const finish = (info: MacSignatureInfo) => { + if (settled) return + settled = true + clearTimeout(timer) + resolve(info) + } + const timer = setTimeout(() => { + child.kill('SIGKILL') + }, 3_500) + child.stdout?.on('data', (chunk: Buffer) => { + if (stdout.length < 65_536) stdout += chunk.toString('utf8') + }) + child.stderr?.on('data', (chunk: Buffer) => { + if (stderr.length < 65_536) stderr += chunk.toString('utf8') + }) + child.on('error', () => finish({ codeSigned: false })) + child.on('close', (code) => { + if (code !== 0) { + finish({ codeSigned: false }) + return + } + const match = /^Authority=(Developer ID Application:[^\r\n]+)$/m.exec(`${stdout}\n${stderr}`) + finish(match?.[1] ? { codeSigned: true, authority: match[1].trim() } : { codeSigned: false }) + }) + }) + return signaturePromise } function countEntriesInStore(filePath: string): number { @@ -359,8 +376,7 @@ export function hardenVaultFilePermissions(): number { export async function getSecurityVaultStatus( req: VaultStatusRequest = {} ): Promise { - const keychainAvailable = await isVaultEncryptionAvailable() - const sig = inspectMacCodeSignature() + const [keychainAvailable, sig] = await Promise.all([isVaultEncryptionAvailable(), inspectMacCodeSignature()]) const stores = AUDITED_STORES.map(auditStoreFile) let accountAudit: SecurityAccountAudit | undefined diff --git a/src/main/updater.ts b/src/main/updater.ts index 9e5f1d48..662eb794 100644 --- a/src/main/updater.ts +++ b/src/main/updater.ts @@ -30,10 +30,10 @@ const SIGNING_ERROR = /ShipIt|code signature|代码不含资源|did not pass val * Unsigned/ad-hoc builds fall back to opening the GitHub Release download page; * Developer ID signed + notarized builds support native Squirrel auto-install. */ -function canAutoInstall(): boolean { +async function canAutoInstall(): Promise { if (!app.isPackaged) return false if (process.platform === 'darwin') { - return inspectMacCodeSignature().codeSigned + return (await inspectMacCodeSignature()).codeSigned } return true } @@ -109,8 +109,8 @@ async function checkViaGitHubApi(attempt: UpdateCheck): Promise { } } -function configure(): void { - const auto = canAutoInstall() && hasAppUpdateConfig() +async function configure(): Promise { + const auto = (await canAutoInstall()) && hasAppUpdateConfig() autoUpdater.autoDownload = auto autoUpdater.autoInstallOnAppQuit = auto autoUpdater.allowPrerelease = false @@ -163,7 +163,7 @@ function configure(): void { } async function runCheck(attempt: UpdateCheck): Promise { - if (canAutoInstall() && hasAppUpdateConfig()) { + if ((await canAutoInstall()) && hasAppUpdateConfig()) { try { const result = await autoUpdater.checkForUpdates() if (result) { @@ -200,8 +200,8 @@ function check(manual = false): Promise { return attempt.done } -function installOrOpenRelease(): void { - if (canAutoInstall() && downloaded) { +async function installOrOpenRelease(): Promise { + if ((await canAutoInstall()) && downloaded) { autoUpdater.quitAndInstall(false, true) return } @@ -214,7 +214,7 @@ export function registerUpdaterIpc(): void { return { ok: true as const } }) ipcMain.handle(UPDATE_CHANNELS.install, async () => { - installOrOpenRelease() + await installOrOpenRelease() return { ok: true as const } }) ipcMain.handle(UPDATE_CHANNELS.version, () => app.getVersion()) @@ -223,7 +223,7 @@ export function registerUpdaterIpc(): void { export function startAutoUpdater(): void { if (started) return started = true - configure() + void configure() // Delay first background check so the window can load. setTimeout(() => { diff --git a/src/renderer/src/App.tsx b/src/renderer/src/App.tsx index b0f687e8..c0820e2e 100644 --- a/src/renderer/src/App.tsx +++ b/src/renderer/src/App.tsx @@ -9,7 +9,6 @@ import { startWorkspaceSync } from '@/services/workspaceSync' import { startPopoutHost } from '@/services/popoutSync' import { usePanes } from '@/store/paneStore' import { AppShell } from '@/components/layout/AppShell' -import { InfoPanel } from '@/components/info/InfoPanel' import { hasSeenOnboarding } from '@/components/onboarding/onboardingState' import { Sidebar } from '@/components/sidebar/Sidebar' import { GoxfUpdateBanner } from '@/components/update/GoxfUpdateBanner' @@ -30,6 +29,7 @@ const RoomView = lazy(() => import('@/rooms/RoomView').then(({ RoomView }) => ({ const RoomInspectorPanel = lazy(() => import('@/rooms/RoomInspectorPanel').then(({ RoomInspectorPanel }) => ({ default: RoomInspectorPanel })) ) +const InfoPanel = lazy(() => import('@/components/info/InfoPanel').then(({ InfoPanel }) => ({ default: InfoPanel }))) const AddBotDialog = lazy(() => import('@/components/add-bot/AddBotDialog').then(({ AddBotDialog }) => ({ default: AddBotDialog }))) const OnboardingDialog = lazy(() => import('@/components/onboarding/OnboardingGuide').then(({ OnboardingDialog }) => ({ default: OnboardingDialog })) @@ -38,7 +38,7 @@ const CommandPalette = lazy(() => import('@/components/palette/CommandPalette').then(({ CommandPalette }) => ({ default: CommandPalette })) ) -function OnDemandDialog({ open, children }: { open: boolean; children: ReactNode }) { +function OnDemandMount({ open, children }: { open: boolean; children: ReactNode }) { const [hasOpened, setHasOpened] = useState(open) useEffect(() => { if (open) setHasOpened(true) @@ -289,24 +289,24 @@ export default function App() { {view === 'board' ? ( boardPicked && setBoardPicked(undefined)} /> - ) : view === 'collab' && activeRoom ? : } + ) : view === 'collab' && activeRoom ? : } } /> - + - - + + - - + + - - + + - + ) } diff --git a/src/renderer/src/components/chat/MarkdownText.test.ts b/src/renderer/src/components/chat/MarkdownText.test.ts new file mode 100644 index 00000000..b0d61373 --- /dev/null +++ b/src/renderer/src/components/chat/MarkdownText.test.ts @@ -0,0 +1,115 @@ +import { createElement, isValidElement, type ReactNode } from 'react' +import { renderToStaticMarkup } from 'react-dom/server' +import { afterEach, expect, it } from 'vitest' +import { usePrefsStore } from '@/store/prefsStore' +import { MarkdownText, renderMarkdownBlocks } from './MarkdownText' + +const originalLocale = usePrefsStore.getState().locale + +afterEach(() => { + usePrefsStore.setState({ locale: originalLocale }) +}) + +const COMPLEX_MARKDOWN = [ + '# Title', + '', + 'Intro paragraph with **bold**, *italic*, `code`, and [link](https://example.com).', + 'Second line of the same paragraph.', + '', + '```ts', + 'const a = 1', + '', + 'const b = 2 // blank line inside fence', + '```', + '', + '| Col A | Col B |', + '| :--- | ---: |', + '| x | 1 |', + '| y | 2 |', + '', + '- [x] Done item', + '- [ ] Todo item', + '', + '1. First', + '2. Second', + '', + '> Quote line 1', + '> Quote line 2', + '', + '[[hatch_widget:secret]]', + '', + 'Inline file `workspace/docs/report.md` and ![img](https://example.com/a.png).', + '', + 'Trailing paragraph without newline' +].join('\n') + +function findButtons(node: ReactNode): Array<{ props: { title?: string; onClick?: () => void } }> { + if (Array.isArray(node)) return node.flatMap(findButtons) + if (!isValidElement(node)) return [] + const el = node as { type?: unknown; props: { title?: string; onClick?: () => void; children?: ReactNode } } + const here = el.type === 'button' ? [el] : [] + return [...here, ...findButtons(el.props.children)] +} + +it('renders every streaming prefix identically to a full parse of that prefix', () => { + for (let end = 1; end <= COMPLEX_MARKDOWN.length; end += 7) { + const prefix = COMPLEX_MARKDOWN.slice(0, end) + const streamed = renderToStaticMarkup(createElement(MarkdownText, { text: prefix })) + const direct = renderToStaticMarkup(createElement(MarkdownText, { text: prefix })) + expect(streamed).toBe(direct) + } + const full = renderToStaticMarkup(createElement(MarkdownText, { text: COMPLEX_MARKDOWN })) + expect(full).toContain('Trailing paragraph without newline') + expect(full).not.toContain('hatch_widget') + expect(full).toContain('blank line inside fence') +}) + +it('keeps full-document HTML unchanged after rendering overlapping prefixes and sibling docs', () => { + const baseline = renderToStaticMarkup(createElement('div', null, renderMarkdownBlocks(COMPLEX_MARKDOWN, { locale: 'en', onFileLinkClick: () => {} }))) + const chunks = COMPLEX_MARKDOWN.split('\n\n') + let acc = '' + for (const chunk of chunks) { + acc = acc ? `${acc}\n\n${chunk}` : chunk + renderToStaticMarkup(createElement('div', null, renderMarkdownBlocks(acc, { locale: 'en', onFileLinkClick: () => {} }))) + renderToStaticMarkup(createElement('div', null, renderMarkdownBlocks(`Other doc\n\n${acc}`, { locale: 'en', suppressWorkspaceImages: true }))) + } + const afterWarmup = renderToStaticMarkup(createElement('div', null, renderMarkdownBlocks(COMPLEX_MARKDOWN, { locale: 'en', onFileLinkClick: () => {} }))) + expect(afterWarmup).toBe(baseline) +}) + +it('calls the latest file-link handler even when identical block text was rendered before', () => { + const text = 'Open `workspace/a.md` now' + const calls: string[] = [] + renderMarkdownBlocks(text, { locale: 'en', onFileLinkClick: () => { calls.push('stale') } }) + const nodes = renderMarkdownBlocks(text, { + locale: 'en', + onFileLinkClick: (path, label) => { calls.push(`${path}:${label}`) } + }) + const buttons = findButtons(nodes) + expect(buttons.length).toBeGreaterThan(0) + buttons[0]!.props.onClick?.() + expect(calls).toEqual(['workspace/a.md:workspace/a.md']) +}) + +it('does not reuse blocks across different file-link or workspace-image flags', () => { + const text = '![uniquealt](workspace/pic.png)' + const plain = renderToStaticMarkup(createElement('div', null, renderMarkdownBlocks(text, { locale: 'en' }))) + const suppressed = renderToStaticMarkup(createElement('div', null, renderMarkdownBlocks(text, { locale: 'en', suppressWorkspaceImages: true }))) + const clickable = renderToStaticMarkup(createElement('div', null, renderMarkdownBlocks(text, { locale: 'en', onFileLinkClick: () => {} }))) + expect(plain).toContain('uniquealt') + expect(plain).not.toContain(' { + usePrefsStore.setState({ locale: 'en' }) + const text = 'Open `workspace/a.md` now' + const en = renderToStaticMarkup(createElement(MarkdownText, { text, onFileLinkClick: () => {} })) + expect(en).toContain('Click to open a raw preview') + usePrefsStore.setState({ locale: 'zh' }) + const zh = renderToStaticMarkup(createElement(MarkdownText, { text, onFileLinkClick: () => {} })) + expect(zh).toContain('点击原生打开预览') +}) diff --git a/src/renderer/src/components/chat/MarkdownText.tsx b/src/renderer/src/components/chat/MarkdownText.tsx index b2cfba17..6ceee076 100644 --- a/src/renderer/src/components/chat/MarkdownText.tsx +++ b/src/renderer/src/components/chat/MarkdownText.tsx @@ -1,9 +1,10 @@ import { desktopCopy, useDesktopLocale } from '@/lib/desktopCopy' -import { type ReactNode, memo, useState } from 'react' +import { type ReactNode, Fragment, createElement, memo, useMemo, useRef, useState } from 'react' import { Check, Copy, Download, Image as ImageIcon, ZoomIn } from 'lucide-react' import { cn } from '@/lib/cn' import { ImageLightbox, ImageOverlayButton, LIGHTBOX_ATTR } from './ImageLightbox' import { t } from '@/lib/i18n' +import { usePrefsStore } from '@/store/prefsStore' /** * Full-featured native Markdown renderer for Muse / Grok Bot replies & reports: @@ -292,7 +293,7 @@ function renderInline( } else if ( onFileLinkClick && (href.startsWith('workspace/') || - /^(sediment|dotfile|dotatt|harkatt|harkfile):\/\//i.test(href) || + /^(sediment|dotfile|dotatt|harkatt|harkfile|grokatt|grokstore|grokdoc):\/\//i.test(href) || /\.(md|markdown|txt|json|csv|html|htm|pdf|png|jpe?g|gif|webp|svg|py|ts|tsx|js|sh|sql|yaml|yml)$/i.test(href)) ) { nodes.push( @@ -646,6 +647,83 @@ function removeHatchWidgets(text: string): string { return pieces.join('') } +interface MarkdownBlockOptions { + locale: string + onFileLinkClick?: (path: string, label: string) => void + suppressWorkspaceImages?: boolean + onLinkClick?: (href: string, label: string) => boolean +} + +const BLOCK_CACHE_LIMIT = 400 +const blockCache = new Map() +const handlerIds = new WeakMap() +let nextHandlerId = 1 + +function handlerId(fn?: Function): number { + if (!fn) return 0 + let id = handlerIds.get(fn) + if (!id) { + id = nextHandlerId++ + handlerIds.set(fn, id) + } + return id +} + +function cachedBlock(key: string, parse: () => ReactNode[]): ReactNode[] { + const hit = blockCache.get(key) + if (hit) { + blockCache.delete(key) + blockCache.set(key, hit) + return hit + } + const nodes = parse() + blockCache.set(key, nodes) + if (blockCache.size > BLOCK_CACHE_LIMIT) { + blockCache.delete(blockCache.keys().next().value!) + } + return nodes +} + +/** + * Blocks separated by a blank line outside a fenced code block never change + * when more text is appended, so streaming only re-parses the trailing block. + */ +export function renderMarkdownBlocks(text: string, options: MarkdownBlockOptions): ReactNode[] { + const cleaned = removeHatchWidgets(text).replace(/\r\n/g, '\n') + const lines = cleaned.split('\n') + const flags = `${options.locale}|${handlerId(options.onFileLinkClick)}|${options.suppressWorkspaceImages ? 1 : 0}|${handlerId(options.onLinkClick)}` + const out: ReactNode[] = [] + let blockStart = 0 + let hasContent = false + let inFence = false + let key = 0 + + const append = (from: number, to: number, cacheable: boolean) => { + if (from >= to) return + const slice = lines.slice(from, to).join('\n') + const nodes = cacheable + ? cachedBlock(`${flags}|${slice}`, () => renderBlocks(slice, options.onFileLinkClick, options.suppressWorkspaceImages, options.onLinkClick)) + : renderBlocks(slice, options.onFileLinkClick, options.suppressWorkspaceImages, options.onLinkClick) + out.push(createElement(Fragment, { key: key++ }, nodes)) + } + + for (let i = 0; i < lines.length; i++) { + const line = lines[i]! + if (line.trimStart().startsWith('```')) inFence = !inFence + if (!inFence && !line.trim()) { + if (hasContent) { + append(blockStart, i, true) + blockStart = i + 1 + hasContent = false + } + } else if (line.trim()) { + hasContent = true + } + } + append(blockStart, lines.length, false) + return out +} + export const MarkdownText = memo(function MarkdownText({ text, className, @@ -659,12 +737,31 @@ export const MarkdownText = memo(function MarkdownText({ suppressWorkspaceImages?: boolean onLinkClick?: (href: string, label: string) => boolean }) { - if (!/[*_`#\-|>~\[\]]|\n\d+\.|https?:\/\//.test(text) && !text.includes('```')) { + const locale = usePrefsStore((s) => s.locale) + const handlersRef = useRef({ onFileLinkClick, onLinkClick }) + handlersRef.current = { onFileLinkClick, onLinkClick } + const [dispatchers] = useState(() => ({ + fileLink: (path: string, label: string) => handlersRef.current.onFileLinkClick?.(path, label), + link: (href: string, label: string) => handlersRef.current.onLinkClick?.(href, label) ?? false + })) + const hasFileLink = Boolean(onFileLinkClick) + const hasLink = Boolean(onLinkClick) + const plain = !/[*_`#\-|>~\[\]]|\n\d+\.|https?:\/\//.test(text) && !text.includes('```') + const nodes = useMemo( + () => plain ? null : renderMarkdownBlocks(text, { + locale, + onFileLinkClick: hasFileLink ? dispatchers.fileLink : undefined, + suppressWorkspaceImages, + onLinkClick: hasLink ? dispatchers.link : undefined + }), + [plain, text, locale, hasFileLink, hasLink, suppressWorkspaceImages, dispatchers] + ) + if (plain) { return {text} } return (
- {renderBlocks(text, onFileLinkClick, suppressWorkspaceImages, onLinkClick)} + {nodes}
) }) diff --git a/src/renderer/src/components/chat/MediaPreview.tsx b/src/renderer/src/components/chat/MediaPreview.tsx index 82ba20e3..5bb4c9f5 100644 --- a/src/renderer/src/components/chat/MediaPreview.tsx +++ b/src/renderer/src/components/chat/MediaPreview.tsx @@ -12,6 +12,8 @@ import { useBotStore } from '@/store/botStore' import type { ChatMediaPart, ChatMessage } from '@/types' import type { NativeDocumentTarget } from './NativeDocumentDialog' +type MediaScope = Pick + function isHttp(path: string): boolean { return /^https?:\/\//i.test(path) } @@ -218,7 +220,7 @@ async function downloadDotMedia(accountId: string, part: ChatMediaPart) { return { dataBase64: d.dataBase64, mimeType: d.mimeType, filename: d.filename || d.name } } -async function downloadGrokMedia(accountId: string, part: ChatMediaPart) { +async function downloadGrokMedia(accountId: string, part: ChatMediaPart, scope?: MediaScope) { const grok = getBridge()?.grok if (!grok?.rpc) throw new Error('Grok download unavailable') const storeState = useBotStore.getState() @@ -229,7 +231,8 @@ async function downloadGrokMedia(accountId: string, part: ChatMediaPart) { const dl = await grok.rpc({ accountId, op: 'downloadAttachment', - agentId: ownerBot?.selectedAgentId, + agentId: scope?.agentId ?? ownerBot?.selectedAgentId, + sessionId: scope?.sessionId, path: part.path, name: part.name }) @@ -264,7 +267,8 @@ async function downloadCueMedia(accountId: string, part: ChatMediaPart) { async function fetchPlatformMediaBytes( accountId: string, - part: ChatMediaPart + part: ChatMediaPart, + scope?: MediaScope ): Promise<{ dataBase64: string; mimeType: string; filename?: string } | null> { const rawPath = (part.path || '').trim() if (rawPath.startsWith('data:')) { @@ -288,7 +292,7 @@ async function fetchPlatformMediaBytes( return downloadDotMedia(accountId, part) } if (isGrokMedia(accountId, rawPath)) { - return downloadGrokMedia(accountId, part) + return downloadGrokMedia(accountId, part, scope) } if (isCueMedia(accountId, rawPath)) { return downloadCueMedia(accountId, part) @@ -310,7 +314,8 @@ export function WorkspaceImage({ part, accountId, mine, - tile + tile, + scope }: { part: ChatMediaPart accountId?: string @@ -318,6 +323,7 @@ export function WorkspaceImage({ mine?: boolean /** One of several pictures: an equal-height tile, clickable anywhere. */ tile?: boolean + scope?: MediaScope }) { useDesktopLocale() const initialDirectSrc = @@ -345,7 +351,7 @@ export function WorkspaceImage({ let cancelled = false void (async () => { try { - const fetched = await fetchPlatformMediaBytes(accountId, part) + const fetched = await fetchPlatformMediaBytes(accountId, part, scope) if (cancelled) return if (!fetched?.dataBase64) { setFailed(true) @@ -370,7 +376,7 @@ export function WorkspaceImage({ return () => { cancelled = true } - }, [accountId, part, src, failed, retryNonce]) + }, [accountId, part, scope, src, failed, retryNonce]) const [fitWidth, setFitWidth] = useState(null) const [aspect, setAspect] = useState() @@ -461,10 +467,12 @@ export function WorkspaceImage({ function WorkspaceAV({ part, accountId, + scope, kind }: { part: ChatMediaPart accountId?: string + scope?: MediaScope kind: 'audio' | 'video' }) { useDesktopLocale() @@ -472,8 +480,8 @@ function WorkspaceAV({ const directSrc = /^data:(?:audio|video)\//i.test(path) || (isHttp(path) && !needsAuthProxyHttpUrl(path)) ? path : null const [retryNonce, setRetryNonce] = useState(0) const source = useMemo(() => ({ - accountId, part: { path, name, mimeType, imageId, kind: mediaKind }, kind, retryNonce - }), [accountId, path, name, mimeType, imageId, mediaKind, kind, retryNonce]) + accountId, part: { path, name, mimeType, imageId, kind: mediaKind }, kind, scope, retryNonce + }), [accountId, path, name, mimeType, imageId, mediaKind, kind, scope, retryNonce]) const [proxySrc, setProxySrc] = useState<{ source: typeof source; url: string }>() const [failedSource, setFailedSource] = useState() const [proxySource, setProxySource] = useState() @@ -490,7 +498,7 @@ function WorkspaceAV({ let objectUrl: string | null = null void (async () => { try { - const fetched = await fetchPlatformMediaBytes(owner, media) + const fetched = await fetchPlatformMediaBytes(owner, media, source.scope) if (cancelled) return if (!fetched?.dataBase64) { setFailedSource(source) @@ -585,11 +593,13 @@ function WorkspaceAV({ export const MediaPreview = memo(function MediaPreview({ parts, accountId, + scope, onOpenDoc, mine }: { parts: ChatMediaPart[] accountId?: string + scope?: MediaScope onOpenDoc?: (target: NativeDocumentTarget) => void mine?: boolean }) { @@ -618,7 +628,7 @@ export const MediaPreview = memo(function MediaPreview({ try { const rawPath = (part.path || '').trim() const isHttpUrl = /^https?:\/\//i.test(rawPath) - const fetched = await fetchPlatformMediaBytes(accountId, part) + const fetched = await fetchPlatformMediaBytes(accountId, part, scope) const dataBase64 = fetched?.dataBase64 || '' const mimeType = fetched?.mimeType || part.mimeType || 'application/octet-stream' @@ -665,6 +675,17 @@ export const MediaPreview = memo(function MediaPreview({ ? part.mimeType || desktopCopy("可预览 / 下载文件", "Files you can preview or download") : part.path const key = part.path || part.name || 'part' + const openPart = () => { + if (!accountId || !onOpenDoc) return + onOpenDoc({ + accountId, + title: part.name || (!isHttpUrl ? part.path.split('/').pop() : undefined) || 'Document', + path: part.path, + mimeType: part.mimeType, + agentId: scope?.agentId, + sessionId: scope?.sessionId + }) + } return (
  • {looksLikeImage(part) ? ( - + ) : looksLikeAudio(part) ? ( - + ) : looksLikeVideo(part) ? ( - + ) : (
    )} @@ -1428,13 +1430,7 @@ const MessageBubbleBody = memo(function MessageBubbleBody({ text={message.text} suppressWorkspaceImages={media.length > 0} onLinkClick={handleMarkdownLinkClick} - onFileLinkClick={(path, label) => - openDocument({ - accountId: message.accountId, - title: label || path.split('/').pop() || 'Document', - path - }) - } + onFileLinkClick={handleFileLinkClick} /> )} diff --git a/src/renderer/src/components/chat/NativeDocumentDialog.tsx b/src/renderer/src/components/chat/NativeDocumentDialog.tsx index 9fd07c99..783e3507 100644 --- a/src/renderer/src/components/chat/NativeDocumentDialog.tsx +++ b/src/renderer/src/components/chat/NativeDocumentDialog.tsx @@ -20,11 +20,12 @@ export interface NativeDocumentTarget { mimeType?: string platformId?: string agentId?: string + sessionId?: string } function documentTargetKey(target: NativeDocumentTarget): string { return JSON.stringify([ - target.platformId, target.accountId, target.agentId, target.path, target.title, + target.platformId, target.accountId, target.agentId, target.sessionId, target.path, target.title, target.mimeType, target.markdown, target.html ]) } @@ -109,6 +110,7 @@ async function loadDocument(target: NativeDocumentTarget): Promise attempt(room.title, () => stopRoom(room.id)))) await attempt(t('Collaboration rooms'), () => { useRooms.setState({ rooms: [], speakers: {}, turnProgress: {}, errors: {}, externalAudiences: {} }) - localStorage.removeItem('botark-collaboration-rooms') + clearRoomPersistence() if (localStorage.getItem('botark-collaboration-rooms') !== null) { throw new Error(t('Could not remove the saved collaboration rooms')) } diff --git a/src/renderer/src/lib/conversationExport.ts b/src/renderer/src/lib/conversationExport.ts index 3aee336b..b839c92f 100644 --- a/src/renderer/src/lib/conversationExport.ts +++ b/src/renderer/src/lib/conversationExport.ts @@ -57,7 +57,7 @@ export function buildRoomJson(room: CollabRoom, exportedAt = new Date()): string const { id, title, mode, brief, createdAt, finalId, members } = room return exportJson({ room: { id, title, mode, brief, createdAt, finalId, members: members.map(({ botId, name, platform }) => ({ botId, name, platform })) } - }, room.messages, exportedAt) + }, room.messages.map(({ mediaSource: _source, ...message }) => message), exportedAt) } export function sanitizeExportFilename(name: string, ext: string): string { diff --git a/src/renderer/src/rooms/RoomTranscript.tsx b/src/renderer/src/rooms/RoomTranscript.tsx index 77943a3f..dd6467a2 100644 --- a/src/renderer/src/rooms/RoomTranscript.tsx +++ b/src/renderer/src/rooms/RoomTranscript.tsx @@ -243,7 +243,7 @@ const RoomMessageRow = memo(function RoomMessageRow({ {cleanText && } {message.media && message.media.length > 0 && (
    - openDoc(target)} />
    )} diff --git a/src/renderer/src/rooms/model.ts b/src/renderer/src/rooms/model.ts index 66f735a3..475481f8 100644 --- a/src/renderer/src/rooms/model.ts +++ b/src/renderer/src/rooms/model.ts @@ -30,6 +30,7 @@ export interface RoomMessage { id: string author: string text: string + mediaSource?: Pick references?: RoomReference[] /** Files pasted with a human message; sent to the member that answers it (if its platform takes them). Not persisted with their data. */ attachments?: AttachmentMeta[] @@ -234,7 +235,7 @@ type RoomReply = | { kind: 'final'; text: string } | { kind: 'post'; text: string; botIds: string[] } -export function classifyRoomReply(reply: string, speakerId: string, roster: RoomMember[], room: CollabRoom): RoomReply { +export function classifyRoomReply(reply: string, speakerId: string, roster: RoomMember[], room: CollabRoom, hasMedia = false): RoomReply { if (isToolRequest(reply)) return { kind: 'tool', text: reply } const isCoordinator = speakerId === room.coordinatorId const canDelegate = isCoordinator || (!room.coordinatorId && room.mode === 'auto') @@ -243,7 +244,7 @@ export function classifyRoomReply(reply: string, speakerId: string, roster: Room if ((!room.coordinatorId || isCoordinator) && isFinal(reply)) { const body = stripFinalPrefix(reply) - if (!body.trim()) return { kind: 'post', text: body, botIds: [] } + if (!body.trim() && !hasMedia) return { kind: 'post', text: body, botIds: [] } const target = canDelegate ? directHandoff(body, roster) : undefined if (!target || target.botId === speakerId || !room.members.some((m) => m.botId === target.botId)) { return { kind: 'final', text: reply } diff --git a/src/renderer/src/rooms/roomLive.ts b/src/renderer/src/rooms/roomLive.ts index ad9ea8f3..6e73ef77 100644 --- a/src/renderer/src/rooms/roomLive.ts +++ b/src/renderer/src/rooms/roomLive.ts @@ -1,5 +1,7 @@ import { create } from 'zustand' import type { AdapterEvent, PlatformAdapter } from '@adapters/types' +import { getBridge } from '@/lib/bridge' +import { stripFinalPrefix } from './model' /** * GOXF: what the member answering in a group chat is doing right now, like its @@ -65,3 +67,26 @@ export function trackRoomTurn( } }) } + +/** + * Upstream #89: Grok streams a room turn's reply on its bridge (not as adapter + * deltas), so feed those snapshots into the same live bubble. + */ +export function trackGrokRoomStream( + roomId: string, + accountId: string, + conversationId: string, + agentId: string | undefined, + signal: AbortSignal +): () => void { + const parts = new Map() + return getBridge()?.grok?.onEvent?.((event) => { + if (signal.aborted || event.type !== 'stream' || event.conversationId !== conversationId || + event.accountId !== accountId || (agentId && event.agentId !== agentId)) return + // Each event is the whole bubble so far (it may be rewritten), so replace rather than grow. + const text = stripFinalPrefix(event.text) + if (text.trim()) parts.set(event.messageId, text) + else parts.delete(event.messageId) + patch(roomId, { text: [...parts.values()].join('\n\n') || undefined }) + }) ?? (() => {}) +} diff --git a/src/renderer/src/rooms/roomPersistence.test.ts b/src/renderer/src/rooms/roomPersistence.test.ts new file mode 100644 index 00000000..91bf3a0b --- /dev/null +++ b/src/renderer/src/rooms/roomPersistence.test.ts @@ -0,0 +1,83 @@ +import { afterEach, beforeEach, expect, it, vi } from 'vitest' +import type { CollabRoom } from './model' +import { + clearRoomPersistence, + flushRoomPersistence, + renameRoom, + updateRoomConfig, + useRooms +} from './roomStore' + +const KEY = 'botark-collaboration-rooms' + +function memoryStorage() { + const map = new Map() + return { + getItem: vi.fn((key: string) => map.get(key) ?? null), + setItem: vi.fn((key: string, value: string) => { map.set(key, String(value)) }), + removeItem: vi.fn((key: string) => { map.delete(key) }), + clear: vi.fn(() => map.clear()), + key: vi.fn((index: number) => [...map.keys()][index] ?? null), + get length() { return map.size } + } +} + +let storage: ReturnType + +beforeEach(() => { + vi.useFakeTimers() + storage = memoryStorage() + vi.stubGlobal('localStorage', storage) + useRooms.setState({ rooms: [], speakers: {}, liveReplies: {}, turnProgress: {}, errors: {} }) + storage.setItem.mockClear() +}) + +afterEach(() => { + flushRoomPersistence() + useRooms.setState({ rooms: [] }) + vi.useRealTimers() + vi.unstubAllGlobals() +}) + +function seedRoom(): CollabRoom { + const room: CollabRoom = { id: 'room-persist', title: 'Initial', brief: '', members: [], mode: 'manual', limit: 4, messages: [] } + useRooms.setState({ rooms: [room] }) + vi.advanceTimersByTime(400) + storage.setItem.mockClear() + return room +} + +it('coalesces a burst of room updates into one deferred serialization and write', () => { + const room = seedRoom() + renameRoom(room.id, 'Step 1') + renameRoom(room.id, 'Step 2') + renameRoom(room.id, 'Step 3') + updateRoomConfig(room.id, { limit: 6 }) + updateRoomConfig(room.id, { limit: 8 }) + renameRoom(room.id, 'Final title') + + expect(storage.setItem).not.toHaveBeenCalled() + vi.advanceTimersByTime(350) + expect(storage.setItem).toHaveBeenCalledTimes(1) + const saved = JSON.parse(storage.getItem(KEY) ?? '{}') as { state: { rooms: CollabRoom[] } } + expect(saved.state.rooms[0]).toMatchObject({ id: room.id, title: 'Final title', limit: 8 }) +}) + +it('flushes pending room state immediately on demand', () => { + const room = seedRoom() + renameRoom(room.id, 'Before hide') + expect(storage.setItem).not.toHaveBeenCalled() + flushRoomPersistence() + expect(storage.setItem).toHaveBeenCalledTimes(1) + expect(storage.getItem(KEY)).toContain('Before hide') +}) + +it('cancels any queued room write when persistence is cleared', () => { + const room = seedRoom() + renameRoom(room.id, 'Should not reappear') + clearRoomPersistence() + expect(storage.getItem(KEY)).toBeNull() + vi.advanceTimersByTime(1000) + expect(storage.setItem).not.toHaveBeenCalled() + expect(storage.getItem(KEY)).toBeNull() +}) diff --git a/src/renderer/src/rooms/roomStore.ts b/src/renderer/src/rooms/roomStore.ts index a22477f0..e45be2f6 100644 --- a/src/renderer/src/rooms/roomStore.ts +++ b/src/renderer/src/rooms/roomStore.ts @@ -1,7 +1,7 @@ import { create } from 'zustand' import { persist, type PersistStorage } from 'zustand/middleware' import { adapterRegistry } from '@adapters/registry' -import { AdapterError, type AttachmentMeta, type ConnectionStatus, type MuseMediaPart, type MuseToolCall, type SendReceipt } from '@adapters/types' +import { AdapterError, type AttachmentMeta, type ConnectionStatus, type MuseMediaPart, type MuseToolCall, type IncomingMessage, type SendReceipt } from '@adapters/types' import { createId } from '@shared/id' import { getBridge } from '@/lib/bridge' import { cancelPlatformTurn, useBotStore } from '@/store/botStore' @@ -12,10 +12,12 @@ import { freshRoomSession, isGlobalAdmin, isHumanRoomMessage, + isFinal, mentions, normalizeMentionName, refusesRoomFrame, roomRecipient, + stripFinalPrefix, turnPrompt, type CollabRoom, type RoomMember, @@ -24,7 +26,7 @@ import { } from './model' import { requestedTool } from './toolRequests' import { snapshotMembers, teamStatusBlock } from './adminContext' -import { clearRoomLive, trackRoomTurn } from './roomLive' +import { clearRoomLive, trackGrokRoomStream, trackRoomTurn } from './roomLive' import { joinReplyParts, postedBodies } from './replyParts' import { createWidgetCollector, dropInlineWidgetData, hasWidgets, sanitizeStoredWidgets } from './replyWidgets' import { attachmentOnlyText, sendableAttachments } from './roomAttachments' @@ -45,6 +47,7 @@ interface RoomState { slackDestinations: Record rooms: CollabRoom[] speakers: Record + liveReplies: Record turnProgress: Record /** GOXF: tool calls of the reply being written right now, per room. */ liveTools: Record @@ -59,19 +62,31 @@ function roomStorageBacking(): Storage | undefined { } } +const ROOMS_STORAGE_KEY = 'botark-collaboration-rooms' let storedRooms: { backing: Storage name: string - value: string | null rooms?: CollabRoom[] version?: number } | undefined -const safeRoomStorage = createSafeStorage(roomStorageBacking, () => { storedRooms = undefined }) +const safeRoomStorage = createSafeStorage(roomStorageBacking, () => { storedRooms = undefined }, { debounceMs: 350 }) + +export const flushRoomPersistence = safeRoomStorage.flush + +export function clearRoomPersistence(): void { + storedRooms = undefined + safeRoomStorage.removeItem(ROOMS_STORAGE_KEY) +} + +if (typeof window !== 'undefined') { + window.addEventListener?.('pagehide', flushRoomPersistence) +} + const roomStorage: PersistStorage> = { getItem(name) { const backing = roomStorageBacking() const value = safeRoomStorage.getItem(name) - storedRooms = backing ? { backing, name, value } : undefined + storedRooms = backing ? { backing, name } : undefined return value ? JSON.parse(value) : null }, setItem(name, item) { @@ -80,12 +95,11 @@ const roomStorage: PersistStorage> = { const previous = storedRooms?.backing === backing && storedRooms.name === name ? storedRooms : undefined if (previous?.rooms === item.state.rooms && previous.version === item.version) return // Picture data stays in memory only: localStorage is small, and the member already received it. - const value = JSON.stringify(item, (key, v) => + storedRooms = { backing, name, rooms: item.state.rooms, version: item.version } + safeRoomStorage.setItem(name, () => JSON.stringify(item, (key, v) => key === 'dataBase64' ? undefined : key === 'media' && Array.isArray(v) ? v.filter((part: MuseMediaPart) => !part.path?.startsWith('data:')) - : dropInlineWidgetData(key, v)) - storedRooms = { backing, name, value, rooms: item.state.rooms, version: item.version } - if (value !== previous?.value) safeRoomStorage.setItem(name, value) + : dropInlineWidgetData(key, v))) }, removeItem(name) { storedRooms = undefined @@ -98,6 +112,7 @@ export const useRooms = create()( (): RoomState => ({ rooms: [], speakers: {}, + liveReplies: {}, turnProgress: {}, liveTools: {}, errors: {}, @@ -105,7 +120,7 @@ export const useRooms = create()( externalAudiences: {} }), { - name: 'botark-collaboration-rooms', + name: ROOMS_STORAGE_KEY, storage: roomStorage, partialize: (s) => ({ rooms: s.rooms }), onRehydrateStorage: () => (state) => { @@ -758,6 +773,19 @@ function continueWithLatePost(roomId: string, postId: string, targets: string[]) void submitBrief(roomId, post.text, { author: post.author, messageId: post.id, continueFrom: members }) } +type RoomIncomingReply = Pick + +/** Upstream #89: the agent/session a Grok file link or picture belongs to, so its preview can be fetched. */ +function roomMediaSource(incoming: RoomIncomingReply[], member: RoomMember, sessionId?: string): RoomMessage['mediaSource'] { + const source = incoming.find((m) => m.media?.length || (member.platform === 'grok' && /grok(?:att|store|doc):\/\//i.test(m.text))) + return source ? { + accountId: member.accountId, + platform: member.platform, + agentId: source.agentId ?? member.agentId, + sessionId: source.sessionId ?? sessionId + } : undefined +} + async function memberReply(room: CollabRoom, member: RoomMember, trigger: RoomMessage, signal: AbortSignal) { const adapter = adapterRegistry.get(member.platform) const bot = useBotStore @@ -797,8 +825,10 @@ async function memberReply(room: CollabRoom, member: RoomMember, trigger: RoomMe for (const tool of list) tools.set(tool.id, tool) useRooms.setState((s) => ({ liveTools: { ...s.liveTools, [room.id]: [...tools.values()] } })) } + const incoming = new Map() const stopMessages = adapter.onMessage((m) => { if (m.conversationId !== conversationId || m.accountId !== member.accountId) return + if (m.text.trim() || m.media?.length) incoming.set(m.id, m) if (m.text.trim()) replies.set(m.id, m.text) addTools(m.tools) widgets.add(m) @@ -815,10 +845,15 @@ async function memberReply(room: CollabRoom, member: RoomMember, trigger: RoomMe : undefined let sessionId = member.sessionId const stopLive = trackRoomTurn(room.id, adapter, member.accountId, conversationId, () => sessionId) + // Upstream #89: Grok streams its reply on the bridge, not as adapter deltas. + const stopGrokLive = member.platform === 'grok' + ? trackGrokRoomStream(room.id, member.accountId, conversationId, member.agentId, signal) + : undefined const unsubscribe = () => { stopMessages() stopDeltas?.() stopLive() + stopGrokLive?.() } const hermesSessionKey = member.platform === 'hermes' ? member.hermesSessionKey || `${room.id}-${member.botId}` : undefined @@ -924,8 +959,13 @@ async function memberReply(room: CollabRoom, member: RoomMember, trigger: RoomMe watchLateReply(room.id, member, adapter, conversationId, trigger.id) throw new RoomTurnError(NO_REPLY_ERROR, true) } + const resolvedSessionId = receipt.sessionId || sessionId + // Upstream #89: a Grok [FINAL] in its own last bubble still ends the round, keeping the bubbles before it. + const tail = [...incoming.values()].findLast((m) => m.text.trim())?.text + const finalBubble = member.platform === 'grok' && tail && isFinal(tail) && !isFinal(text) && text.endsWith(tail) ? tail : undefined return { - text, sessionId: receipt.sessionId || sessionId, hermesSessionKey, + text, finalBubble, sessionId: resolvedSessionId, hermesSessionKey, + mediaSource: roomMediaSource([...incoming.values()], member, resolvedSessionId), tools: [...tools.values()], media, widgets: widgets.snapshot() } } catch (error) { @@ -1091,6 +1131,7 @@ export async function submitBrief( speakers: { ...s.speakers, [id]: member.name }, turnProgress: { ...s.turnProgress, [id]: { turn: turn + 1, limit: current.limit } } })) + const postId = createId('post') const pending = memberReply(current, member, next.trigger, signal) pendingTurns.set(pendingKey, pending) let reply: Awaited @@ -1143,20 +1184,25 @@ export async function submitBrief( const latest = roomById(id) if (!latest) break // Use the roster from the prompt to resolve names, then deliver by current bot ID. - const classified = classifyRoomReply(reply.text, member.botId, current.members, latest) + const classified = classifyRoomReply(reply.finalBubble ?? reply.text, member.botId, current.members, latest, reply.media.length > 0 || hasWidgets(reply.widgets)) const currentMembers = new Map(latest.members.map((m) => [m.botId, m])) const targets = classified.kind === 'post' ? classified.botIds : [] const done = classified.kind === 'final' const toolRequest = classified.kind === 'tool' + const postText = reply.finalBubble + ? [done ? '[FINAL]' : '', reply.text.slice(0, -reply.finalBubble.length).trimEnd(), + done ? stripFinalPrefix(classified.text) : classified.text].filter(Boolean).join('\n\n') + : classified.text const post: RoomMessage = { - id: createId('post'), + id: postId, author: member.name, authorBotId: member.botId, ...(done ? { final: true } : {}), ...(toolRequest ? { localOnly: true } : {}), - text: classified.text, + text: postText, ...(reply.tools.length ? { tools: reply.tools } : {}), ...(reply.media.length ? { media: reply.media } : {}), + ...(reply.mediaSource ? { mediaSource: reply.mediaSource } : {}), ...reply.widgets, createdAt: Date.now() } @@ -1169,11 +1215,14 @@ export async function submitBrief( ...m, cursor, sessionId: reply.sessionId, hermesSessionKey: reply.hermesSessionKey } : m) : latest.members - update(id, (r) => ({ - ...r, - finalId: done ? post.id : undefined, - messages: appendPost ? [...r.messages, post] : r.messages, - members + useRooms.setState((s) => ({ + rooms: s.rooms.map((r) => r.id === id ? { + ...r, + finalId: done ? post.id : undefined, + messages: appendPost ? [...r.messages, post] : r.messages, + members + } : r), + liveReplies: { ...s.liveReplies, [id]: undefined } })) // A follow-up typed during this turn still gets its answer. if (done && !queue.some(({ trigger }) => isHumanRoomMessage(trigger))) break diff --git a/src/renderer/src/rooms/rooms.test.ts b/src/renderer/src/rooms/rooms.test.ts index ca5d80f8..ee7381f3 100644 --- a/src/renderer/src/rooms/rooms.test.ts +++ b/src/renderer/src/rooms/rooms.test.ts @@ -1,12 +1,16 @@ import { afterEach, expect, it, vi } from 'vitest' import { adapterRegistry } from '@adapters/registry' import { AdapterError, type IncomingMessage, type OutgoingMessage, type PlatformAdapter, type SendReceipt } from '@adapters/types' +import type { GrokMainEvent } from '@shared/ipc' import type { Bot } from '@/types' +import { buildRoomJson } from '@/lib/conversationExport' import { useBotStore } from '@/store/botStore' import { mentions, roomMarkdown, splitMentionSegments, stripFinalPrefix, turnPrompt, type CollabRoom, type RoomMember } from './model' +import { useRoomLive } from './roomLive' import { clearRoomTranscript, deleteRoom, + flushRoomPersistence, renameRoom, setRoomAdministrator, stopRoom, @@ -20,7 +24,7 @@ import { const members = ['Muse', 'Dot'].map((name) => ({ name, botId: name, platform: 'dot' as const, accountId: name, cursor: 0 })) function fixture( mode: CollabRoom['mode'], - respond: (m: OutgoingMessage) => Promise, + respond: (m: OutgoingMessage) => Promise>, limit = 8, roster: RoomMember[] = members ) { @@ -35,11 +39,11 @@ function fixture( onMessage: (listener: typeof emit) => { emit = listener; return () => {} }, sendMessage: async (m: OutgoingMessage): Promise => { const response = await respond(m) - const { text, sessionId } = typeof response === 'string' ? { text: response, sessionId: undefined } : response - const message = { ...m, text, createdAt: 1, id: 'fixture' } + const data = typeof response === 'string' ? { text: response } : response + const message = { ...m, ...data, createdAt: 1, id: 'fixture' } emit({ ...message, conversationId: 'private-chat', text: '@Dot wrong transcript' }) emit(message) - return { messageId: 'receipt', acceptedAt: 1, sessionId } + return { messageId: 'receipt', acceptedAt: 1, sessionId: data.sessionId } } } as unknown as PlatformAdapter) } @@ -48,6 +52,54 @@ afterEach(() => { vi.restoreAllMocks() vi.unstubAllGlobals() }) + +it('shows Grok text before a room turn completes and stores one final reply with its files', async () => { + let emitLive: ((event: GrokMainEvent) => void) | undefined + const unsubscribe = vi.fn() + vi.stubGlobal('window', { electron: { grok: { onEvent: (listener: typeof emitLive) => { + emitLive = listener + return unsubscribe + } } } }) + const grok: RoomMember = { + ...members[0]!, botId: 'grok', name: 'Grok', platform: 'grok', + agentId: 'fixture-agent', sessionId: 'fixture-session' + } + const media = [{ kind: 'file' as const, path: 'grokatt://fixture/report.pdf', name: 'report.pdf' }] + let finishResponse!: () => void + const response = new Promise((resolve) => { finishResponse = resolve }) + let request: OutgoingMessage | undefined + fixture('manual', async (message) => { + request = message + await response + return { text: '[FINAL]\n请查收报告', media, sessionId: grok.sessionId } + }, 8, [grok, members[1]!]) + const run = submitBrief('room', '@Grok 生成报告') + try { + await vi.waitFor(() => expect(request).toBeDefined()) + const send = request! + const event = { + type: 'stream' as const, accountId: send.accountId, agentId: send.agentId!, + sessionId: send.sessionId, messageId: 'fixture-live', text: '我来整理资料', done: false + } + emitLive?.({ ...event, conversationId: 'another-turn' }) + expect(useRoomLive.getState().live['room']?.text).toBeUndefined() + emitLive?.({ ...event, conversationId: send.conversationId }) + expect(useRoomLive.getState().live['room']?.text).toBe(event.text) + emitLive?.({ ...event, conversationId: send.conversationId, text: '[FINAL]\n请查收报告', media, done: true }) + expect(useRoomLive.getState().live['room']?.text).toBe('请查收报告') + expect(useRooms.getState().rooms[0]?.messages.filter((message) => message.authorBotId)).toEqual([]) + } finally { + finishResponse() + await run + } + expect(unsubscribe).toHaveBeenCalledOnce() + expect(useRoomLive.getState().live['room']).toBeUndefined() + const room = useRooms.getState().rooms[0]! + expect(room.messages.filter((message) => message.authorBotId)).toEqual([ + expect.objectContaining({ text: '[FINAL]\n请查收报告', media, final: true }) + ]) + expect(buildRoomJson(room)).not.toContain('mediaSource') +}) it('routes complete names once and ignores email addresses', () => { expect(mentions('x@Muse.io @MuseExtra @Dot @Muse @Dot', members).map((m) => m.name)).toEqual(['Dot', 'Muse']) }) @@ -781,7 +833,8 @@ it('only advances the cursor with a platform session and replays context until t expect(calls[2]?.text).not.toContain('First reply') }) -it('skips serialization for transient updates and skips writes for an equivalent rooms payload', () => { +it('skips persistence for transient updates and flushes changed rooms once per burst', () => { + vi.useFakeTimers() const data = new Map() const setItem = vi.fn((name: string, value: string) => { data.set(name, value) }) vi.stubGlobal('localStorage', { @@ -789,18 +842,31 @@ it('skips serialization for transient updates and skips writes for an equivalent setItem, removeItem: (name: string) => data.delete(name) }) - const toJSON = vi.fn(() => ({ id: 'storage-room' })) - const room = { id: 'storage-room', title: 'Storage', toJSON } as unknown as CollabRoom - useRooms.setState({ rooms: [room] }) - useRooms.setState({ speakers: { [room.id]: 'Muse' }, turnProgress: { [room.id]: { turn: 1, limit: 8 } } }) - useRooms.setState({ errors: { [room.id]: 'Transient error' } }) - expect(toJSON).toHaveBeenCalledOnce() - expect(setItem).toHaveBeenCalledOnce() - useRooms.setState({ rooms: [{ ...room }] }) - expect(toJSON).toHaveBeenCalledTimes(2) - expect(setItem).toHaveBeenCalledOnce() - useRooms.setState({ rooms: [] }) - expect(setItem).toHaveBeenCalledTimes(2) + try { + const toJSON = vi.fn(function (this: { id: string; brief?: string }) { return { id: this.id, brief: this.brief } }) + const room = { id: 'storage-room', title: 'Storage', toJSON } as unknown as CollabRoom + useRooms.setState({ rooms: [room] }) + flushRoomPersistence() + expect(toJSON).toHaveBeenCalledOnce() + expect(setItem).toHaveBeenCalledOnce() + useRooms.setState({ speakers: { [room.id]: 'Muse' }, turnProgress: { [room.id]: { turn: 1, limit: 8 } } }) + useRooms.setState({ errors: { [room.id]: 'Transient error' } }) + vi.advanceTimersByTime(500) + expect(toJSON).toHaveBeenCalledOnce() + expect(setItem).toHaveBeenCalledOnce() + useRooms.setState({ rooms: [{ ...room, brief: 'first' }] }) + useRooms.setState({ rooms: [{ ...room, brief: 'latest' }] }) + expect(toJSON).toHaveBeenCalledOnce() + vi.advanceTimersByTime(350) + expect(toJSON).toHaveBeenCalledTimes(2) + expect(setItem).toHaveBeenCalledTimes(2) + expect(data.get('botark-collaboration-rooms')).toContain('latest') + useRooms.setState({ rooms: [] }) + vi.advanceTimersByTime(350) + expect(setItem).toHaveBeenCalledTimes(3) + } finally { + vi.useRealTimers() + } }) it('recovers invalid tool JSON locally and continues queued peers', async () => { diff --git a/tests/e2e/group-rooms.e2e.test.ts b/tests/e2e/group-rooms.e2e.test.ts index 0df83280..4870b1c2 100644 --- a/tests/e2e/group-rooms.e2e.test.ts +++ b/tests/e2e/group-rooms.e2e.test.ts @@ -10,9 +10,12 @@ vi.mock('electron', async () => { import { adapterRegistry } from '@adapters/registry' import { AntigravityAdapter } from '@adapters/antigravity/AntigravityAdapter' import { GrokBotAdapter } from '@adapters/grokbot/GrokBotAdapter' +import type { GrokRequest } from '@adapters/grokbot/grokRequests' import { DotAdapter } from '@adapters/dot/DotAdapter' import { setGrokAuth } from '@adapters/grokbot/tokenStore' import { runDotRpc } from '@main/dot/dotIpc' +import { GrokConnectClient } from '@main/grok/connectClient' +import { watchUntilReply } from '@main/grok/grokRpc' import { importDotCredentialsFromRaw, getStoredDotAccount } from '@main/dot/dotClient' import { partitionForAccount } from '@main/webContentsViewManager' import { mentions, roomMarkdown, type CollabRoom } from '@/rooms/model' @@ -215,6 +218,102 @@ describe('Area 3: Group Creation, Conversation & Single-Bot Remove/Move', () => expect(received[0]!.text).toContain('Hydrated Grok Room Reply') }) + it.each(['text', 'file', 'link', 'delayed link'])('posts a Grok %s reply when only transcript history contains it', async (type) => { + const accountId = 'grok-room-recovery' + const botId = 'grok-room-bot' + const controller = new AbortController() + const sent: string[] = [] + let sentAt = 0 + const file = { path: 'grokatt://fixture/report.pdf', name: 'report.pdf', mimeType: 'application/pdf' } + const fileLink = '[报告](grokatt://fixture/attachment-id)' + const progress = '我来整理资料。' + const client = new GrokConnectClient({ + auth: { accessToken: 'fixture' }, + fetchImpl: async (input) => { + const url = String(input) + if (url.endsWith('/WatchGrokBotTranscripts')) { + return new Response(new ReadableStream()) + } + if (url.endsWith('/ListGrokBotTranscriptEntries')) { + const echo = { entry_id: 'echo', client_nonce: sent[0], seq: '10', kind: 'message', content: 'Room prompt' } + if (type === 'delayed link') { + return Response.json({ entries: [ + echo, + { entry_id: 'progress', seq: '11', kind: 'send-message', content: progress }, + ...(Date.now() - sentAt >= 29_000 + ? [{ entry_id: 'answer', seq: '12', kind: 'send-message', content: '[FINAL]\n' + fileLink }] + : []) + ] }) + } + return Response.json({ entries: [ + echo, + { + entry_id: 'answer', seq: '11', kind: 'send-message', + content: type === 'text' ? 'Recovered room answer' : type === 'link' ? fileLink : '', + ...(type === 'file' ? { attachments: [file] } : {}) + } + ] }) + } + throw new Error(`Unexpected mock request: ${url}`) + } + }) + vi.stubGlobal('window', { electron: { grok: { + onEvent: () => () => {}, + rpc: async (req: GrokRequest) => { + if (req.op === 'listAgents') return { ok: true, data: { agents: [{ id: 'agent' }] } } + if (req.op === 'sendUserMessage') { + sent.push(req.messageId) + sentAt = Date.now() + } + if (req.op === 'watchUntilReply') return { ok: true, data: await watchUntilReply(client, { + ...req, sessionId: req.sessionId ?? '', signal: controller.signal + }) } + return { ok: true, data: {} } + } + } } }) + setGrokAuth({ accountId, signedIn: true }) + const grok = new GrokBotAdapter() + await grok.connect(accountId) + vi.spyOn(adapterRegistry, 'get').mockReturnValue(grok) + useBotStore.setState({ + bots: [ + { id: botId, name: 'Grok', platformId: 'grok', selectedAgentId: type === 'text' ? 'agent' : undefined, accountIds: [accountId], activeAccountId: accountId } as Bot, + { id: 'observer', name: 'Observer', platformId: 'dot', accountIds: ['observer-account'], activeAccountId: 'observer-account' } as Bot + ], + accounts: { + [accountId]: { id: accountId, platformId: 'grok', displayName: 'Grok', handle: 'fixture', status: 'online' }, + 'observer-account': { id: 'observer-account', platformId: 'dot', displayName: 'Observer', handle: 'fixture', status: 'online' } + } + }) + const room = addRoom('协作室回传测试', [botId, 'observer'], 'manual', 4) + useRooms.setState((state) => ({ rooms: state.rooms.map((item) => item.id === room.id + ? { ...item, members: item.members.map((member) => member.botId === botId + ? { ...member, sessionId: 'fixture-room-session' } + : member) } + : item) })) + vi.useFakeTimers() + const turn = submitBrief(room.id, '@Grok answer in this room') + try { + await vi.advanceTimersByTimeAsync(type === 'delayed link' ? 37_000 : 8_000) + const messages = useRooms.getState().rooms.find((item) => item.id === room.id)?.messages + const mediaSource = { accountId, platform: 'grok', agentId: 'agent', sessionId: 'fixture-room-session' } + expect(messages?.filter((item) => item.authorBotId === botId)).toEqual([ + expect.objectContaining(type === 'file' ? { + text: '', + media: [{ ...file, kind: 'file' }], + mediaSource + } : type === 'link' ? { text: fileLink, mediaSource } + : type === 'delayed link' ? { text: ['[FINAL]', progress, fileLink].join('\n\n'), final: true, mediaSource } + : { text: 'Recovered room answer' }) + ]) + expect(sent).toHaveLength(1) + } finally { + controller.abort() + await turn + vi.useRealTimers() + } + }) + it('E2E-T1-A3-04: Dot Room botId Non-Overwrite & native Thread Continuity', async (ctx) => { await importDotCredentialsFromRaw( 'acc_dot_keep_id',