feat(panel): add formula-safe CSV/Markdown export, compact vertical action menus, and local file export with reveal toast

This commit is contained in:
fish
2026-11-22 11:54:20 +09:00
parent 6da4d3479c
commit a98fda8b44
25 changed files with 3817 additions and 117 deletions
+1252 -8
View File
File diff suppressed because it is too large Load Diff
+38
View File
@@ -17,6 +17,7 @@ import {
trackEndpointRequestStart, trackEndpointRequestStart,
} from './endpoint-registry.mjs'; } from './endpoint-registry.mjs';
import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs'; import { isLocalHostRequest, readLocalAsync } from './http-helpers.mjs';
import { revealLocalExportFile, writeLocalExportFile } from './file-exporter.mjs';
import { clearScannerRuntimeMemos } from './local-scanner.mjs'; import { clearScannerRuntimeMemos } from './local-scanner.mjs';
import { import {
SETTINGS_FILE, SETTINGS_FILE,
@@ -735,6 +736,33 @@ export function executeSessionMigrationMigrateAction(data = undefined, opts = {}
}; };
} }
export function executeExportFileAction(data, opts = {}) {
const result = writeLocalExportFile(data || {}, {
...(opts?.exportDir ? { overrideDir: opts.exportDir } : {}),
...(opts?.homeDir ? { homeDir: opts.homeDir } : {}),
...(opts?.fallbackDataDir ? { fallbackDataDir: opts.fallbackDataDir } : {}),
});
return {
status: Number(result.status || (result.ok ? 200 : 400)),
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(result),
};
}
export function executeRevealFileAction(data, opts = {}) {
const result = revealLocalExportFile(data?.filePath, {
...(opts?.platform ? { platform: opts.platform } : {}),
...(typeof opts?.spawnFn === 'function' ? { spawnFn: opts.spawnFn } : {}),
});
return {
status: Number(result.status || (result.ok ? 200 : 400)),
contentType: 'application/json',
headers: { 'Cache-Control': 'no-store' },
body: JSON.stringify(result),
};
}
const BRIDGE_ROUTE_LOOKUP = new Map( const BRIDGE_ROUTE_LOOKUP = new Map(
BRIDGE_API_ROUTE_DEFS.map((r) => [`${r.method}:${r.path}`, r.action]) BRIDGE_API_ROUTE_DEFS.map((r) => [`${r.method}:${r.path}`, r.action])
); );
@@ -757,6 +785,12 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
if (isPlainObject(data) && data.__sessionMigrationAction === 'migrate') { if (isPlainObject(data) && data.__sessionMigrationAction === 'migrate') {
return executeSessionMigrationMigrateAction(data.payload || data, opts); return executeSessionMigrationMigrateAction(data.payload || data, opts);
} }
if (isPlainObject(data) && data.__exportFileAction === 'save') {
return executeExportFileAction(data.payload || data, opts);
}
if (isPlainObject(data) && data.__exportFileAction === 'reveal') {
return executeRevealFileAction(data.payload || data, opts);
}
return executeSettingsAction(data); return executeSettingsAction(data);
case 'accounts_get': case 'accounts_get':
return executeAccountCredentialAction(undefined, opts); return executeAccountCredentialAction(undefined, opts);
@@ -778,6 +812,10 @@ export async function dispatchBridgeApiRequest(pathname, method, data, opts = un
return executeSessionMigrationCatalogAction(data, opts); return executeSessionMigrationCatalogAction(data, opts);
case 'session_migration_migrate': case 'session_migration_migrate':
return executeSessionMigrationMigrateAction(data, opts); return executeSessionMigrationMigrateAction(data, opts);
case 'export_file':
return executeExportFileAction(data, opts);
case 'reveal_file':
return executeRevealFileAction(data, opts);
default: default:
return { return {
status: 404, status: 404,
+230
View File
@@ -0,0 +1,230 @@
/**
* @fileoverview 本机安全文本文件导出及系统文件管理器定位模块 (`file-exporter.mjs`)。
* 仅允许导出受控白名单文本扩展名(.json / .csv / .md / .txt),严格清洗文件名防止路径穿越,
* 并仅对本次进程实际导出的文件路径开放系统文件管理器定位能力。
*/
import { spawn } from 'node:child_process';
import { existsSync, mkdirSync, statSync, writeFileSync } from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import { DATA_DIR } from './config.mjs';
export const MAX_EXPORT_FILE_BYTES = 8 * 1024 * 1024;
export const ALLOWED_EXPORT_EXTENSIONS = Object.freeze(['.json', '.csv', '.md', '.txt']);
const ALLOWED_EXT_SET = new Set(ALLOWED_EXPORT_EXTENSIONS);
const MAX_RECENT_EXPORT_TRACK = 64;
const recentExportedPaths = new Set();
function recordExportedPath(absPath) {
const normalized = path.resolve(String(absPath || ''));
if (!normalized) return;
if (recentExportedPaths.has(normalized)) {
recentExportedPaths.delete(normalized);
}
recentExportedPaths.add(normalized);
while (recentExportedPaths.size > MAX_RECENT_EXPORT_TRACK) {
const oldest = recentExportedPaths.values().next().value;
if (!oldest) break;
recentExportedPaths.delete(oldest);
}
}
export function isAuthorizedExportPath(filePath) {
const normalized = path.resolve(String(filePath || ''));
return Boolean(normalized && recentExportedPaths.has(normalized));
}
function inferExtensionFromMime(mimeType) {
const lower = String(mimeType || '').toLowerCase();
if (lower.includes('csv')) return '.csv';
if (lower.includes('markdown')) return '.md';
if (lower.includes('plain')) return '.txt';
return '.json';
}
/**
* 严格净化导出文件名:剥离目录段、过滤系统非法字符,并强制收敛到允许的文本扩展名白名单。
*
* @param {string} rawFilename
* @param {string} [mimeType]
* @returns {{ fileName: string, baseName: string, ext: string }}
*/
export function sanitizeLocalExportFilename(rawFilename, mimeType = '') {
const leaf = path.basename(String(rawFilename || '').replace(/\\/g, '/')).trim();
const parsedExt = path.extname(leaf).toLowerCase();
const ext = ALLOWED_EXT_SET.has(parsedExt) ? parsedExt : inferExtensionFromMime(mimeType);
const rawBase = ALLOWED_EXT_SET.has(parsedExt) ? leaf.slice(0, -parsedExt.length) : leaf;
const cleanedBase = rawBase
.replace(/[<>:"/\\|?*\x00-\x1f]/g, '-')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^[.\-_]+|[.\-_]+$/g, '')
.slice(0, 80);
const baseName = cleanedBase || 'export';
return {
fileName: `${baseName}${ext}`,
baseName,
ext,
};
}
/**
* 解析本机导出目录:优先使用用户系统 Downloads 目录,不存在时自动回退到插件 `.data/exports`。
*
* @param {{ overrideDir?: string, homeDir?: string, fallbackDataDir?: string }} [options]
* @returns {{ dirPath: string, source: 'override' | 'downloads' | 'data_exports' }}
*/
export function resolveExportDirectory({
overrideDir = '',
homeDir = os.homedir(),
fallbackDataDir = DATA_DIR,
} = {}) {
const custom = String(overrideDir || '').trim();
if (custom) {
const resolved = path.resolve(custom);
mkdirSync(resolved, { recursive: true });
return { dirPath: resolved, source: 'override' };
}
const downloadsDir = homeDir ? path.join(homeDir, 'Downloads') : '';
if (downloadsDir) {
try {
if (existsSync(downloadsDir) && statSync(downloadsDir).isDirectory()) {
return { dirPath: path.resolve(downloadsDir), source: 'downloads' };
}
} catch {
// ignore stat errors and fall back cleanly
}
}
const exportsDir = path.resolve(path.join(fallbackDataDir || DATA_DIR, 'exports'));
mkdirSync(exportsDir, { recursive: true });
return { dirPath: exportsDir, source: 'data_exports' };
}
/**
* 将文本导出内容安全落盘到本机目录,遇同名文件自动追加 `(1)`、`(2)` 避免覆盖已有导出。
*
* @param {{ filename?: string, content?: string, mimeType?: string }} payload
* @param {{ overrideDir?: string, homeDir?: string, fallbackDataDir?: string }} [options]
* @returns {{ ok: boolean, status: number, filePath?: string, dirPath?: string, fileName?: string, bytes?: number, source?: string, error?: string }}
*/
export function writeLocalExportFile(payload = {}, options = {}) {
if (!payload || typeof payload !== 'object') {
return { ok: false, status: 400, error: 'Invalid export payload' };
}
if (typeof payload.content !== 'string') {
return { ok: false, status: 400, error: 'Export content must be a string' };
}
const byteLen = Buffer.byteLength(payload.content, 'utf8');
if (byteLen > MAX_EXPORT_FILE_BYTES) {
return { ok: false, status: 413, error: 'Export file exceeds size limit' };
}
const { baseName, ext } = sanitizeLocalExportFilename(payload.filename, payload.mimeType);
const { dirPath, source } = resolveExportDirectory(options);
let targetPath = '';
let finalFileName = '';
for (let attempt = 0; attempt < 1000; attempt += 1) {
const candidateName = attempt === 0 ? `${baseName}${ext}` : `${baseName} (${attempt})${ext}`;
const candidatePath = path.join(dirPath, candidateName);
try {
writeFileSync(candidatePath, payload.content, { encoding: 'utf8', flag: 'wx' });
targetPath = path.resolve(candidatePath);
finalFileName = candidateName;
break;
} catch (err) {
if (err && err.code === 'EEXIST') continue;
return {
ok: false,
status: 500,
error: err?.message || 'Failed to write export file',
};
}
}
if (!targetPath) {
const fallbackName = `${baseName}-${Date.now()}${ext}`;
const fallbackPath = path.join(dirPath, fallbackName);
try {
writeFileSync(fallbackPath, payload.content, { encoding: 'utf8', flag: 'wx' });
targetPath = path.resolve(fallbackPath);
finalFileName = fallbackName;
} catch (err) {
return {
ok: false,
status: 500,
error: err?.message || 'Failed to write export file',
};
}
}
recordExportedPath(targetPath);
return {
ok: true,
status: 200,
filePath: targetPath,
dirPath,
fileName: finalFileName,
bytes: byteLen,
source,
};
}
/**
* 在系统文件管理器中定位并高亮选中由本进程刚导出的受控文件。
*
* @param {string} filePath
* @param {{ platform?: string, spawnFn?: typeof spawn }} [options]
* @returns {{ ok: boolean, status: number, filePath?: string, error?: string }}
*/
export function revealLocalExportFile(
filePath,
{ platform = process.platform, spawnFn = spawn } = {}
) {
const raw = String(filePath || '').trim();
if (!raw || /[\r\n"]/.test(raw)) {
return { ok: false, status: 400, error: 'Invalid file path' };
}
const resolved = path.resolve(raw);
if (!isAuthorizedExportPath(resolved)) {
return { ok: false, status: 403, error: 'Path is not an authorized export file' };
}
if (!existsSync(resolved)) {
return { ok: false, status: 404, error: 'Exported file no longer exists' };
}
try {
let child = null;
if (platform === 'win32') {
child = spawnFn('explorer.exe', [`/select,"${resolved}"`], {
detached: true,
stdio: 'ignore',
windowsVerbatimArguments: true,
windowsHide: false,
});
} else if (platform === 'darwin') {
child = spawnFn('open', ['-R', resolved], {
detached: true,
stdio: 'ignore',
});
} else {
child = spawnFn('xdg-open', [path.dirname(resolved)], {
detached: true,
stdio: 'ignore',
});
}
child?.on?.('error', () => {});
child?.unref?.();
return { ok: true, status: 200, filePath: resolved };
} catch (err) {
return {
ok: false,
status: 500,
error: err?.message || 'Failed to open file manager',
};
}
}
+41 -1
View File
@@ -21,6 +21,7 @@ import { ensureCliStatusLineConfigured } from './cli-statusline-config.mjs';
import { syncCloudCatalog } from './plugin-updater.mjs'; import { syncCloudCatalog } from './plugin-updater.mjs';
const MAX_JSON_BODY_BYTES = 1024 * 1024; const MAX_JSON_BODY_BYTES = 1024 * 1024;
const MAX_EXPORT_JSON_BODY_BYTES = 8 * 1024 * 1024;
const AUTH_COOKIE_NAME = 'ag_um_token'; const AUTH_COOKIE_NAME = 'ag_um_token';
const NO_STORE_HEADERS = { const NO_STORE_HEADERS = {
'Cache-Control': 'no-store, no-cache, must-revalidate', 'Cache-Control': 'no-store, no-cache, must-revalidate',
@@ -511,12 +512,32 @@ export function createStandaloneWebServer(options = {}) {
} }
if (pathname.startsWith('/api/')) { if (pathname.startsWith('/api/')) {
if (
(pathname === '/api/export-file' || pathname === '/api/reveal-file') &&
!isLoopbackRemoteAddress(req.socket?.remoteAddress)
) {
sendResponse(
res,
403,
'application/json; charset=utf-8',
JSON.stringify({
ok: false,
fallbackBrowser: true,
error: 'Local file export is restricted to loopback clients',
})
);
return;
}
let data = undefined; let data = undefined;
if (method === 'GET') { if (method === 'GET') {
data = Object.fromEntries(urlObj.searchParams.entries()); data = Object.fromEntries(urlObj.searchParams.entries());
delete data.token; delete data.token;
} else if (method === 'POST') { } else if (method === 'POST') {
const rawBody = await readRawBody(req, MAX_JSON_BODY_BYTES); const maxBody =
pathname === '/api/export-file' || pathname === '/api/settings'
? MAX_EXPORT_JSON_BODY_BYTES
: MAX_JSON_BODY_BYTES;
const rawBody = await readRawBody(req, maxBody);
if (rawBody.trim()) { if (rawBody.trim()) {
try { try {
data = JSON.parse(rawBody); data = JSON.parse(rawBody);
@@ -532,6 +553,25 @@ export function createStandaloneWebServer(options = {}) {
} else { } else {
data = {}; data = {};
} }
if (
pathname === '/api/settings' &&
data &&
typeof data === 'object' &&
typeof data.__exportFileAction === 'string' &&
!isLoopbackRemoteAddress(req.socket?.remoteAddress)
) {
sendResponse(
res,
403,
'application/json; charset=utf-8',
JSON.stringify({
ok: false,
fallbackBrowser: true,
error: 'Local file export is restricted to loopback clients',
})
);
return;
}
} else { } else {
sendResponse( sendResponse(
res, res,
+6 -1
View File
@@ -71,6 +71,7 @@ const overlayMethods = Object.fromEntries(
); );
const BRIDGE_MAX_BODY_BYTES = 64 * 1024; const BRIDGE_MAX_BODY_BYTES = 64 * 1024;
const BRIDGE_MAX_EXPORT_BODY_BYTES = 8 * 1024 * 1024;
const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS); const ALLOWED_BRIDGE_PATHS = new Set(BRIDGE_API_PATHS);
/** /**
@@ -1342,12 +1343,16 @@ export function createWindowBridgeController(options) {
return; return;
} }
const maxBodyBytes =
parsedUrl.pathname === '/api/export-file'
? BRIDGE_MAX_EXPORT_BODY_BYTES
: BRIDGE_MAX_BODY_BYTES;
const chunks = []; const chunks = [];
let totalBytes = 0; let totalBytes = 0;
let aborted = false; let aborted = false;
req.on('data', (chunk) => { req.on('data', (chunk) => {
totalBytes += chunk.length; totalBytes += chunk.length;
if (totalBytes > BRIDGE_MAX_BODY_BYTES) { if (totalBytes > maxBodyBytes) {
aborted = true; aborted = true;
res.writeHead(413, { 'Content-Type': 'application/json' }); res.writeHead(413, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Payload too large' })); res.end(JSON.stringify({ error: 'Payload too large' }));
+2 -2
View File
@@ -4,11 +4,11 @@
<meta charset="utf-8"> <meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="viewport" content="width=device-width, initial-scale=1">
<title>用量监控</title> <title>用量监控</title>
<link rel="stylesheet" href="/styles.css?v=1795315495603"> <link rel="stylesheet" href="/styles.css?v=1795316060647">
<script src="/preload.js"></script> <script src="/preload.js"></script>
</head> </head>
<body> <body>
<div id="app-root"></div> <div id="app-root"></div>
<script src="/app.js?v=1795315495603"></script> <script src="/app.js?v=1795316060647"></script>
</body> </body>
</html> </html>
+3
View File
@@ -531,11 +531,14 @@ export function buildBundle(panelDir = PANEL_DIR) {
'src/core/formatters.js', 'src/core/formatters.js',
'src/core/stepInspector.js', 'src/core/stepInspector.js',
'src/core/settingsBackup.js', 'src/core/settingsBackup.js',
'src/core/reportExporter.js',
'src/core/httpClient.js', 'src/core/httpClient.js',
'src/store/uiStore.js', 'src/store/uiStore.js',
'src/core/fileExportClient.js',
'src/store/telemetryStore.js', 'src/store/telemetryStore.js',
'src/components/ui/TopLongPillNav.js', 'src/components/ui/TopLongPillNav.js',
'src/components/ui/CustomSelect.js', 'src/components/ui/CustomSelect.js',
'src/components/ui/ActionMenu.js',
'src/components/ui/CustomNumberInput.js', 'src/components/ui/CustomNumberInput.js',
'src/components/ui/CustomDateTimePicker.js', 'src/components/ui/CustomDateTimePicker.js',
'src/components/ui/CustomScrollbar.js', 'src/components/ui/CustomScrollbar.js',
@@ -38,6 +38,8 @@ export const BRIDGE_API_ROUTE_DEFS = Object.freeze([
method: 'POST', method: 'POST',
action: 'session_migration_migrate', action: 'session_migration_migrate',
}), }),
Object.freeze({ path: '/api/export-file', method: 'POST', action: 'export_file' }),
Object.freeze({ path: '/api/reveal-file', method: 'POST', action: 'reveal_file' }),
]); ]);
export const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path)); export const BRIDGE_API_PATHS = Object.freeze(BRIDGE_API_ROUTE_DEFS.map((r) => r.path));
+127 -3
View File
@@ -5,16 +5,17 @@
*/ */
import { defineComponent } from './core/component.js'; import { defineComponent } from './core/component.js';
import { h, patchAttr } from './core/domPatch.js'; import { h, patchAttr, patchClasses, patchText } from './core/domPatch.js';
import { isWindowOverlayMode } from './core/httpClient.js'; import { isWindowOverlayMode } from './core/httpClient.js';
import { i18nStore } from './i18n/index.js'; import { createSvgIcon } from './icons/SvgIcon.js';
import { i18nStore, t } from './i18n/index.js';
import { import {
fetchTelemetry, fetchTelemetry,
normalizeClientWindowMountMode, normalizeClientWindowMountMode,
resolveScopedConversation, resolveScopedConversation,
telemetryStore, telemetryStore,
} from './store/telemetryStore.js'; } from './store/telemetryStore.js';
import { getViewTabs, uiStore } from './store/uiStore.js'; import { dismissUiToast, getViewTabs, uiStore } from './store/uiStore.js';
import { BridgeStatusNotice } from './components/settings/BridgeStatusNotice.js'; import { BridgeStatusNotice } from './components/settings/BridgeStatusNotice.js';
import { TopSessionHeader } from './components/layout/TopSessionHeader.js'; import { TopSessionHeader } from './components/layout/TopSessionHeader.js';
import { TopLongPillNav } from './components/ui/TopLongPillNav.js'; import { TopLongPillNav } from './components/ui/TopLongPillNav.js';
@@ -105,6 +106,116 @@ export const App = defineComponent({
settingsView.el, settingsView.el,
]); ]);
const toastMsgEl = h('span', { className: 'app-toast-msg' });
const toastDetailEl = h('span', { className: 'app-toast-detail text-mono', hidden: true });
let activeToastAction = null;
let activeToastId = 0;
let toastAutoTimer = null;
let toastRemainingMs = 0;
let toastStartedAt = 0;
function clearToastTimer() {
if (toastAutoTimer) {
clearTimeout(toastAutoTimer);
toastAutoTimer = null;
}
}
function scheduleToastAutoClose(toastId, delayMs) {
clearToastTimer();
if (!(delayMs > 0)) return;
toastRemainingMs = delayMs;
toastStartedAt = Date.now();
toastAutoTimer = setTimeout(() => {
toastAutoTimer = null;
dismissUiToast(toastId);
}, delayMs);
}
const toastActionLabelEl = h('span');
const toastActionBtn = h(
'button',
{
type: 'button',
className: 'app-toast-action',
hidden: true,
onclick: () => {
const fn = activeToastAction;
if (typeof fn === 'function') fn();
},
},
[createSvgIcon('folder', { size: 12 }), toastActionLabelEl]
);
const toastCloseBtn = h(
'button',
{
type: 'button',
className: 'app-toast-close',
'aria-label': t('export.closeToast'),
title: t('export.closeToast'),
onclick: () => dismissUiToast(activeToastId),
},
[createSvgIcon('close', { size: 11 })]
);
const toastEl = h(
'div',
{
className: 'app-toast',
role: 'status',
'aria-live': 'polite',
hidden: true,
onMouseenter: () => {
if (toastAutoTimer) {
const elapsed = Date.now() - toastStartedAt;
toastRemainingMs = Math.max(800, toastRemainingMs - elapsed);
clearToastTimer();
}
},
onMouseleave: () => {
if (activeToastId && toastRemainingMs > 0 && !toastAutoTimer) {
scheduleToastAutoClose(activeToastId, toastRemainingMs);
}
},
},
[
h('div', { className: 'app-toast-body' }, [toastMsgEl, toastDetailEl]),
toastActionBtn,
toastCloseBtn,
]
);
function syncToastState(toast) {
if (!toast || !toast.message) {
clearToastTimer();
activeToastId = 0;
activeToastAction = null;
toastRemainingMs = 0;
patchAttr(toastEl, 'hidden', true);
return;
}
activeToastId = toast.id;
activeToastAction = toast.onAction;
patchText(toastMsgEl, toast.message);
const hasDetail = Boolean(toast.detail);
patchAttr(toastDetailEl, 'hidden', !hasDetail);
if (hasDetail) {
patchText(toastDetailEl, toast.detail);
patchAttr(toastDetailEl, 'title', toast.detail);
}
const hasAction = Boolean(toast.actionLabel && typeof toast.onAction === 'function');
patchAttr(toastActionBtn, 'hidden', !hasAction);
if (hasAction) {
patchText(toastActionLabelEl, toast.actionLabel);
}
patchClasses(toastEl, {
'tone-ok': toast.tone === 'ok',
'tone-info': toast.tone === 'info',
'tone-warn': toast.tone === 'warn',
});
patchAttr(toastEl, 'hidden', false);
scheduleToastAutoClose(toast.id, toast.durationMs);
}
const shellEl = h( const shellEl = h(
'main', 'main',
{ {
@@ -137,6 +248,7 @@ export const App = defineComponent({
h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]), h('div', { className: 'top-deck' }, [sessionHeader.el, topPillNav.el]),
bannerSlotEl, bannerSlotEl,
stageEl, stageEl,
toastEl,
] ]
); );
@@ -203,19 +315,29 @@ export const App = defineComponent({
() => syncStepsBadge() () => syncStepsBadge()
); );
const unsubToast = uiStore.subscribe(
(st) => st.toast,
(toast) => syncToastState(toast)
);
syncToastState(uiStore.getState().toast);
const unsubI18n = i18nStore.subscribe( const unsubI18n = i18nStore.subscribe(
(st) => st.locale, (st) => st.locale,
() => { () => {
syncStepsBadge(); syncStepsBadge();
globalBridgeNotice.refs.refreshLabels(); globalBridgeNotice.refs.refreshLabels();
patchAttr(bannerSlotEl, 'hidden', globalBridgeNotice.el.hasAttribute('hidden')); patchAttr(bannerSlotEl, 'hidden', globalBridgeNotice.el.hasAttribute('hidden'));
patchAttr(toastCloseBtn, 'aria-label', t('export.closeToast'));
patchAttr(toastCloseBtn, 'title', t('export.closeToast'));
} }
); );
onCleanup(() => { onCleanup(() => {
clearToastTimer();
unsubUi(); unsubUi();
unsubStepCount(); unsubStepCount();
unsubScopeBadge(); unsubScopeBadge();
unsubToast();
unsubI18n(); unsubI18n();
globalBridgeNotice.destroy(); globalBridgeNotice.destroy();
sessionHeader.destroy(); sessionHeader.destroy();
@@ -232,6 +354,8 @@ export const App = defineComponent({
sessionHeader, sessionHeader,
topPillNav, topPillNav,
globalBridgeNotice, globalBridgeNotice,
toastEl,
toastActionBtn,
overviewView, overviewView,
consumptionView, consumptionView,
stepsView, stepsView,
@@ -0,0 +1,162 @@
/**
* @fileoverview 紧凑竖向三点 (`⋮`) 下拉单选操作菜单组件 (`ActionMenu.js`)。
* 兼容 Shadow DOM (`composedPath`) 外部点击收起及 Escape 键盘关闭,供用量统计、调用明细等工具栏复用。
*/
import { defineComponent } from '../../core/component.js';
import { h, isEventInside, patchAttr, patchClasses, patchText } from '../../core/domPatch.js';
import { createSvgIcon } from '../../icons/SvgIcon.js';
export const ActionMenu = defineComponent({
name: 'ActionMenu',
setup({ props, onCleanup }) {
let isOpen = false;
let currentItems = Array.isArray(props?.items) ? props.items.slice() : [];
const align = props?.align === 'left' ? 'left' : 'right';
const triggerBtn = h(
'button',
{
type: 'button',
className: `action-menu-trigger${props?.buttonClassName ? ` ${props.buttonClassName}` : ''}`,
'aria-haspopup': 'menu',
'aria-expanded': 'false',
'aria-label': props?.ariaLabel || 'More actions',
title: props?.ariaLabel || 'More actions',
onclick: (e) => {
e?.stopPropagation?.();
if (isOpen) {
close();
} else {
open();
}
},
},
[createSvgIcon('more-vertical', { size: 13 })]
);
const menuEl = h('div', {
className: `action-menu-popover${align === 'left' ? ' align-left' : ' align-right'}`,
role: 'menu',
hidden: true,
});
const rootEl = h(
'div',
{
className: `action-menu${props?.className ? ` ${props.className}` : ''}`,
},
[triggerBtn, menuEl]
);
let itemBtns = [];
function rebuildItems(items) {
currentItems = Array.isArray(items) ? items.slice() : [];
menuEl.textContent = '';
itemBtns = currentItems.map((item) => {
const iconNode = item.icon ? createSvgIcon(item.icon, { size: 12 }) : null;
const labelNode = h('span', { className: 'action-menu-item-label', text: item.label || '' });
const btn = h(
'button',
{
type: 'button',
role: 'menuitem',
className: 'action-menu-item',
'data-action-key': item.key || '',
title: item.title || '',
disabled: Boolean(item.disabled),
onclick: (e) => {
e?.stopPropagation?.();
close();
if (!item.disabled && typeof item.onSelect === 'function') {
item.onSelect();
}
},
},
iconNode ? [iconNode, labelNode] : [labelNode]
);
menuEl.appendChild(btn);
return { key: item.key, btn, labelNode };
});
}
function open() {
if (isOpen) return;
isOpen = true;
patchClasses(rootEl, { 'is-open': true });
patchAttr(triggerBtn, 'aria-expanded', 'true');
patchAttr(menuEl, 'hidden', false);
}
function close() {
if (!isOpen) return;
isOpen = false;
patchClasses(rootEl, { 'is-open': false });
patchAttr(triggerBtn, 'aria-expanded', 'false');
patchAttr(menuEl, 'hidden', true);
}
function onDocPointerDown(e) {
if (!isOpen) return;
if (isEventInside(e, rootEl)) return;
close();
}
function onDocKeyDown(e) {
if (!isOpen) return;
if (e?.key === 'Escape') {
e.preventDefault?.();
close();
triggerBtn.focus?.();
}
}
rebuildItems(currentItems);
if (typeof document !== 'undefined') {
document.addEventListener?.('pointerdown', onDocPointerDown, true);
document.addEventListener?.('click', onDocPointerDown, true);
document.addEventListener?.('keydown', onDocKeyDown, true);
}
onCleanup(() => {
if (typeof document !== 'undefined') {
document.removeEventListener?.('pointerdown', onDocPointerDown, true);
document.removeEventListener?.('click', onDocPointerDown, true);
document.removeEventListener?.('keydown', onDocKeyDown, true);
}
});
return {
el: rootEl,
refs: {
triggerBtn,
menuEl,
getItemBtn: (key) => itemBtns.find((it) => it.key === key)?.btn || null,
isOpen: () => isOpen,
open,
close,
setItems: (nextItems) => {
rebuildItems(nextItems);
},
setAriaLabel: (label) => {
patchAttr(triggerBtn, 'aria-label', label);
patchAttr(triggerBtn, 'title', label);
},
setHidden: (hidden) => {
if (hidden) close();
patchAttr(rootEl, 'hidden', Boolean(hidden));
},
updateItemLabels: (labelMap) => {
for (const it of itemBtns) {
const entry = labelMap?.[it.key];
if (!entry) continue;
if (entry.label !== undefined) patchText(it.labelNode, entry.label);
if (entry.title !== undefined) patchAttr(it.btn, 'title', entry.title);
}
},
},
};
},
});
+219
View File
@@ -0,0 +1,219 @@
/**
* @fileoverview 统一文本文件导出及剪贴板复制客户端 (`fileExportClient.js`)。
* 优先调用本机后端 `/api/export-file` 落盘到用户 Downloads(或插件 `.data/exports`)并返回真实绝对路径,
* 同时通过全局 Toast 清晰展示保存位置并提供「打开位置」快捷按钮;
* 当后端不可达或处于远程浏览器访问时,自动平滑降级到 `showSaveFilePicker` 或浏览器 Blob 下载并给出明确提示。
*/
import { t } from '../i18n/index.js';
import { showUiToast } from '../store/uiStore.js';
import { callSidecarApi, isWindowOverlayMode } from './httpClient.js';
import { triggerTextFileDownload } from './settingsBackup.js';
import { copyPlainTextToClipboard } from './stepInspector.js';
function isHostEmbeddedWebview() {
if (typeof window === 'undefined') return false;
return Boolean(window.sidecar?.fetch) || isWindowOverlayMode();
}
function getPickerTypesForFilename(filename, mimeType) {
const lower = String(filename || '').toLowerCase();
if (lower.endsWith('.csv') || String(mimeType || '').includes('csv')) {
return [{ description: 'CSV', accept: { 'text/csv': ['.csv'] } }];
}
if (lower.endsWith('.md') || String(mimeType || '').includes('markdown')) {
return [{ description: 'Markdown', accept: { 'text/markdown': ['.md'] } }];
}
return [{ description: 'JSON', accept: { 'application/json': ['.json'] } }];
}
/**
* 调用本机后端在系统文件管理器中打开并高亮选中已导出的文件。
* 兼容热更新后常驻父进程 `main.mjs` 尚未注册新路由的场景,自动回退至 `POST /api/settings` 穿透转发至最新 Worker。
*
* @param {string} filePath
* @returns {Promise<boolean>}
*/
export async function revealExportedFile(filePath) {
if (!filePath) return false;
try {
const res = await callSidecarApi('/api/reveal-file', {
method: 'POST',
body: { filePath },
cdpTimeoutMs: 4000,
});
if (res?.ok) return true;
} catch (err) {
if (err?.httpStatus === 403) return false;
}
try {
const fallbackRes = await callSidecarApi('/api/settings', {
method: 'POST',
body: { __exportFileAction: 'reveal', payload: { filePath } },
cdpTimeoutMs: 4000,
});
return Boolean(fallbackRes?.ok);
} catch {
return false;
}
}
async function requestLocalBackendExport(payload) {
let remoteForbidden = false;
try {
const res = await callSidecarApi('/api/export-file', {
method: 'POST',
body: payload,
cdpTimeoutMs: 6000,
});
if (res && res.ok && res.filePath) {
return { res, remoteForbidden: false };
}
if (res && res.fallbackBrowser) {
return { res: null, remoteForbidden: true };
}
} catch (err) {
if (err?.httpStatus === 403) {
remoteForbidden = true;
}
}
if (remoteForbidden) {
return { res: null, remoteForbidden: true };
}
// 兼容热更新后常驻父进程 main.mjs 尚未重注册 /api/export-file 的场景,回退经 POST /api/settings 穿透至最新 Worker
try {
const fallbackRes = await callSidecarApi('/api/settings', {
method: 'POST',
body: { __exportFileAction: 'save', payload },
cdpTimeoutMs: 6000,
});
if (fallbackRes && fallbackRes.ok && fallbackRes.filePath) {
return { res: fallbackRes, remoteForbidden: false };
}
} catch {
// 忽略回退异常,交由下方分环境处理
}
return { res: null, remoteForbidden: false };
}
/**
* 统一文本导出入口:优先本机后端落盘(返回精确路径 + 支持一键打开所在目录),
* 仅在真正独立浏览器上下文(非 Sidecar / 非 Electron 宿主)下降级为浏览器保存,避免宿主静默吞掉 Blob 下载后误报成功。
*
* @param {string} filename
* @param {string} content
* @param {string} [mimeType='text/plain;charset=utf-8']
* @returns {Promise<{ ok: boolean, mode: 'local' | 'picker' | 'browser' | 'cancelled' | 'failed', filePath?: string, fileName?: string }>}
*/
export async function exportTextFileWithFeedback(
filename,
content,
mimeType = 'application/json;charset=utf-8'
) {
const safeName = String(filename || 'export.txt');
const text = String(content ?? '');
// 1. 优先通过本机后端落盘到 Downloads(含 /api/settings 穿透兼容旧常驻 main.mjs)
const { res: localRes } = await requestLocalBackendExport({
filename: safeName,
content: text,
mimeType,
});
if (localRes && localRes.ok && localRes.filePath) {
const savedPath = String(localRes.filePath);
const savedName = String(localRes.fileName || safeName);
showUiToast({
message: t('export.savedLocal', { file: savedName }),
detail: savedPath,
actionLabel: t('export.openFolder'),
onAction: () => {
void revealExportedFile(savedPath);
},
tone: 'ok',
durationMs: 7000,
});
return { ok: true, mode: 'local', filePath: savedPath, fileName: savedName };
}
// 2. 在 Antigravity Sidecar / 双栖 Electron 宿主内,<a download> 会被静默吞掉,绝不误报“已下载到浏览器”
if (isHostEmbeddedWebview()) {
showUiToast({
message: t('export.failed'),
detail: t('export.hostUnavailable'),
tone: 'warn',
durationMs: 5200,
});
return { ok: false, mode: 'failed' };
}
// 3. 普通独立浏览器原生「另存为」对话框
if (typeof window !== 'undefined' && typeof window.showSaveFilePicker === 'function') {
try {
const handle = await window.showSaveFilePicker({
suggestedName: safeName,
types: getPickerTypesForFilename(safeName, mimeType),
});
const writable = await handle.createWritable();
await writable.write(text);
await writable.close();
const pickedName = handle.name || safeName;
showUiToast({
message: t('export.savedPicked', { file: pickedName }),
tone: 'ok',
durationMs: 4200,
});
return { ok: true, mode: 'picker', fileName: pickedName };
} catch (err) {
if (err && err.name === 'AbortError') {
return { ok: false, mode: 'cancelled' };
}
// 沙箱/iframe 抛出 SecurityError 等时继续降级到 Blob 下载
}
}
// 4. 独立浏览器标准 Blob 兜底下载
const ok = triggerTextFileDownload(safeName, text, mimeType);
if (ok) {
showUiToast({
message: t('export.savedBrowser', { file: safeName }),
detail: t('export.savedBrowserHint'),
tone: 'info',
durationMs: 5000,
});
return { ok: true, mode: 'browser', fileName: safeName };
}
showUiToast({
message: t('export.failed'),
tone: 'warn',
durationMs: 3600,
});
return { ok: false, mode: 'failed' };
}
/**
* 复制文本到剪贴板并弹出轻量提示条。
*
* @param {string} text
* @param {string} successMessage
* @returns {Promise<boolean>}
*/
export async function copyTextWithFeedback(text, successMessage) {
const ok = await copyPlainTextToClipboard(text);
if (ok) {
showUiToast({
message: successMessage || t('export.copied'),
tone: 'ok',
durationMs: 2400,
});
} else {
showUiToast({
message: t('export.copyFailed'),
tone: 'warn',
durationMs: 3200,
});
}
return ok;
}
+525
View File
@@ -0,0 +1,525 @@
/**
* @fileoverview RFC-4180 防公式注入 CSV 导出及 Markdown 诊断报告生成纯函数模块 (`reportExporter.js`)。
* 零外部依赖、单遍 O(N) 拼接,供「按步查看」和「用量统计」视图复用。
*/
import {
formatAnomalyKindLabel,
formatCompactDateTime,
formatMetric,
formatSpeedMetric,
formatTokensPrecise,
formatUsd,
mergeModelsByDisplayName,
resolveModelDisplayInfo,
} from './formatters.js';
const PLAIN_SIGNED_NUMBER_RE = /^[+-]?\d+(\.\d+)?$/;
/**
* RFC-4180 安全转义单个 CSV 单元格,并防御电子表格公式注入(`=`, `+`, `-`, `@`, `\t`, `\r`)。
*
* @param {unknown} value
* @returns {string}
*/
export function escapeCsvCell(value) {
if (value === null || value === undefined) return '';
let str = String(value);
if (str.length > 0) {
const first = str[0];
if (
(first === '=' ||
first === '@' ||
first === '\t' ||
first === '\r' ||
((first === '+' || first === '-') && !PLAIN_SIGNED_NUMBER_RE.test(str.trim())))
) {
str = `'${str}`;
}
}
if (/[",\r\n]/.test(str)) {
return `"${str.replace(/"/g, '""')}"`;
}
return str;
}
function csvRow(cells) {
return cells.map(escapeCsvCell).join(',');
}
/**
* 生成安全跨平台导出文件名(剔除非法路径字符并附加 `YYYYMMDD-HHmm` 时间戳)。
*
* @param {string} baseName
* @param {string} ext
* @param {number} [nowMs]
* @returns {string}
*/
export function sanitizeExportFilename(baseName, ext = 'csv', nowMs = Date.now()) {
const cleanBase = String(baseName || 'usage-report')
.replace(/[\\/:*?"<>|\r\n\t]+/g, '-')
.replace(/\s+/g, '-')
.replace(/-+/g, '-')
.replace(/^-|-$/g, '')
.slice(0, 48) || 'usage-report';
const d = new Date(Number.isFinite(nowMs) ? nowMs : Date.now());
const pad = (n) => String(n).padStart(2, '0');
const stamp = `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}-${pad(d.getHours())}${pad(d.getMinutes())}`;
const cleanExt = String(ext || 'csv').replace(/^\.+/, '');
return `${cleanBase}-${stamp}.${cleanExt}`;
}
function escapeMdCell(value) {
return String(value ?? '—')
.replace(/\r?\n/g, ' ')
.replace(/\|/g, '\\|')
.trim();
}
/**
* 将当前步骤列表导出为带 UTF-8 BOM 的 RFC-4180 安全 CSV 字符串(Excel 打开中文零乱码)。
*
* @param {Array<object>} steps
* @param {{ displaySettings?: object, includeBom?: boolean }} [opts]
* @returns {string}
*/
export function buildStepsCsv(steps, { displaySettings = {}, includeBom = true } = {}) {
const list = Array.isArray(steps) ? steps : [];
const header = csvRow([
'step',
'timestamp',
'agent',
'model',
'raw_model_id',
'tok_per_sec',
'ttft_sec',
'duration_sec',
'input_tokens',
'cache_read_tokens',
'output_tokens',
'thinking_tokens',
'response_tokens',
'context_tokens',
'cache_hit_pct',
'cost_usd',
'compaction',
'anomaly_count',
'anomalies',
'prompt',
]);
const rows = [header];
for (let i = 0; i < list.length; i += 1) {
const st = list[i];
if (!st) continue;
const mInfo = resolveModelDisplayInfo(st, displaySettings);
const inTok = Number(st.inputTokens || 0);
const cacheTok = Number(st.cacheReadTokens || 0);
const outTok = Number(st.outputTokens || 0);
const thinkTok = Number(st.thinkingTokens || 0);
const replyTok =
st.responseTokens != null ? Number(st.responseTokens) : Math.max(0, outTok - thinkTok);
const promptTok = inTok + cacheTok;
const cachePct =
st.cacheHitPct != null && Number.isFinite(Number(st.cacheHitPct))
? Number(st.cacheHitPct).toFixed(1)
: promptTok > 0
? ((cacheTok / promptTok) * 100).toFixed(1)
: '0.0';
const ctxTok = Number(st.contextTokens || promptTok + outTok);
const anomCount = Number(st.anomaly?.count || 0);
const anomDesc =
anomCount > 0
? Object.entries(st.anomaly?.kinds || {})
.map(([k, v]) => `${k}:${v}`)
.join(';') || String(st.anomaly?.primaryKind || 'error')
: '';
rows.push(
csvRow([
st.stepIndex ?? '',
st.createdAtMs ? new Date(st.createdAtMs).toISOString() : '',
st.agentLabel || st.agentBadge || (st.isSubagent ? st.agentId || 'subagent' : 'main'),
mInfo.text,
st.rawModelId || st.modelKey || '',
st.tokPerSec != null && Number.isFinite(Number(st.tokPerSec))
? Number(st.tokPerSec).toFixed(2)
: '',
st.ttftSec != null && Number.isFinite(Number(st.ttftSec))
? Number(st.ttftSec).toFixed(3)
: '',
st.durationSec != null && Number.isFinite(Number(st.durationSec))
? Number(st.durationSec).toFixed(3)
: '',
inTok,
cacheTok,
outTok,
thinkTok,
replyTok,
ctxTok,
cachePct,
st.costUsd != null && Number.isFinite(Number(st.costUsd))
? Number(st.costUsd).toFixed(6)
: '',
st.isCompactionStep ? 'true' : 'false',
anomCount,
anomDesc,
String(st.turnPrompt || st.rootTurnPrompt || '').replace(/\r?\n/g, ' ').trim(),
])
);
}
return `${includeBom ? '\uFEFF' : ''}${rows.join('\r\n')}\r\n`;
}
/**
* 生成当前会话(或筛选后步骤子集)的可分享 Markdown 诊断报告。
*
* @param {Array<object>} steps
* @param {{ title?: string, cascadeId?: string, displaySettings?: object, filterNote?: string }} [opts]
* @returns {string}
*/
export function buildStepsMarkdownReport(
steps,
{ title = '', cascadeId = '', displaySettings = {}, filterNote = '' } = {}
) {
const list = Array.isArray(steps) ? steps : [];
let sumIn = 0;
let sumCache = 0;
let sumOut = 0;
let sumCost = 0;
let tpsSum = 0;
let tpsCnt = 0;
let ttftSum = 0;
let ttftCnt = 0;
let anomSteps = 0;
let anomTotal = 0;
let compactionCount = 0;
const byModel = new Map();
for (let i = 0; i < list.length; i += 1) {
const st = list[i];
if (!st) continue;
const inTok = Number(st.inputTokens || 0);
const cacheTok = Number(st.cacheReadTokens || 0);
const outTok = Number(st.outputTokens || 0);
const cost = Number(st.costUsd || 0);
sumIn += inTok;
sumCache += cacheTok;
sumOut += outTok;
if (Number.isFinite(cost) && cost > 0) sumCost += cost;
if (!st.isCompactionStep && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0) {
tpsSum += Number(st.tokPerSec);
tpsCnt += 1;
}
if (!st.isCompactionStep && Number.isFinite(Number(st.ttftSec)) && Number(st.ttftSec) >= 0) {
ttftSum += Number(st.ttftSec);
ttftCnt += 1;
}
if (st.isCompactionStep) compactionCount += 1;
const ac = Number(st.anomaly?.count || 0);
if (ac > 0) {
anomSteps += 1;
anomTotal += ac;
}
const mInfo = resolveModelDisplayInfo(st, displaySettings);
const mKey = mInfo.text || 'Unknown';
let mAcc = byModel.get(mKey);
if (!mAcc) {
mAcc = {
label: mKey,
calls: 0,
inTok: 0,
cacheTok: 0,
outTok: 0,
cost: 0,
tpsSum: 0,
tpsCnt: 0,
};
byModel.set(mKey, mAcc);
}
mAcc.calls += 1;
mAcc.inTok += inTok;
mAcc.cacheTok += cacheTok;
mAcc.outTok += outTok;
if (Number.isFinite(cost) && cost > 0) mAcc.cost += cost;
if (!st.isCompactionStep && Number.isFinite(Number(st.tokPerSec)) && Number(st.tokPerSec) > 0) {
mAcc.tpsSum += Number(st.tokPerSec);
mAcc.tpsCnt += 1;
}
}
const totalTok = sumIn + sumCache + sumOut;
const promptTok = sumIn + sumCache;
const cacheHitPct = promptTok > 0 ? ((sumCache / promptTok) * 100).toFixed(1) : '0.0';
const avgTps = tpsCnt > 0 ? formatSpeedMetric(tpsSum / tpsCnt, ' tok/s') : '—';
const avgTtft = ttftCnt > 0 ? formatMetric(ttftSum / ttftCnt, 's') : '—';
const heading = title ? `# ${title}` : '# Session Telemetry Report';
const lines = [
heading,
'',
...(cascadeId ? [`- **Session ID**: \`${cascadeId}\``] : []),
...(filterNote ? [`- **Scope**: ${filterNote}`] : []),
`- **Steps**: ${list.length}${compactionCount > 0 ? ` (${compactionCount} compaction)` : ''}${anomTotal > 0 ? ` · **Anomalies**: ${anomTotal} across ${anomSteps} steps` : ''}`,
`- **Total Tokens**: ${formatTokensPrecise(totalTok)} (Input ${formatTokensPrecise(sumIn)} / Cache ${formatTokensPrecise(sumCache)} · ${cacheHitPct}% / Output ${formatTokensPrecise(sumOut)})`,
`- **Est. Cost**: ${formatUsd(sumCost, { precise: sumCost > 0 && sumCost < 0.1 })} · **Avg Speed**: ${avgTps} · **Avg TTFT**: ${avgTtft}`,
];
const sortedModels = Array.from(byModel.values()).sort(
(a, b) => b.cost - a.cost || b.inTok + b.cacheTok + b.outTok - (a.inTok + a.cacheTok + a.outTok)
);
if (sortedModels.length > 0) {
lines.push(
'',
'## Model Breakdown',
'',
'| Model | Calls | Total Tokens | Cache Hit | Avg Speed | Est. Cost |',
'| --- | ---: | ---: | ---: | ---: | ---: |'
);
for (const m of sortedModels) {
const mTotal = m.inTok + m.cacheTok + m.outTok;
const mPrompt = m.inTok + m.cacheTok;
const mCache = mPrompt > 0 ? `${((m.cacheTok / mPrompt) * 100).toFixed(1)}%` : '0.0%';
const mTps = m.tpsCnt > 0 ? formatSpeedMetric(m.tpsSum / m.tpsCnt, ' tok/s') : '—';
lines.push(
`| ${escapeMdCell(m.label)} | ${m.calls} | ${formatTokensPrecise(mTotal)} | ${mCache} | ${mTps} | ${formatUsd(m.cost, { precise: m.cost > 0 && m.cost < 0.1 })} |`
);
}
}
const topCostly = list
.filter((st) => Number(st?.costUsd || 0) > 0)
.slice()
.sort((a, b) => Number(b.costUsd || 0) - Number(a.costUsd || 0))
.slice(0, 5);
if (topCostly.length > 0) {
lines.push(
'',
'## Top Costliest Steps',
'',
'| Step | Time | Model | Speed | TTFT | Context | Cost |',
'| ---: | --- | --- | ---: | ---: | ---: | ---: |'
);
for (const st of topCostly) {
const mInfo = resolveModelDisplayInfo(st, displaySettings);
const timeStr = st.createdAtMs ? formatCompactDateTime(st.createdAtMs) : '—';
const ctxTok = Number(
st.contextTokens ||
Number(st.inputTokens || 0) + Number(st.cacheReadTokens || 0) + Number(st.outputTokens || 0)
);
lines.push(
`| #${st.stepIndex ?? '—'} | ${timeStr} | ${escapeMdCell(mInfo.text)} | ${formatSpeedMetric(st.tokPerSec, ' tok/s')} | ${formatMetric(st.ttftSec, 's')} | ${formatTokensPrecise(ctxTok)} | ${formatUsd(st.costUsd, { precise: true })} |`
);
}
}
if (anomTotal > 0) {
const anomKindTotals = new Map();
for (const st of list) {
if (!st?.anomaly?.kinds) continue;
for (const [k, v] of Object.entries(st.anomaly.kinds)) {
const n = Number(v || 0);
if (n > 0) anomKindTotals.set(k, (anomKindTotals.get(k) || 0) + n);
}
}
if (anomKindTotals.size > 0) {
const summary = Array.from(anomKindTotals.entries())
.sort((a, b) => b[1] - a[1])
.map(([k, v]) => `${formatAnomalyKindLabel(k)} ×${v}`)
.join(', ');
lines.push('', `**Anomaly Summary**: ${summary}`);
}
}
return `${lines.join('\n')}\n`;
}
/**
* 将历史用量统计视图当前区间数据导出为结构化 CSV(含摘要、模型、项目、会话及趋势明细)。
*
* @param {object} consumption
* @param {Array<object>} modelBreakdown
* @param {{ displaySettings?: object, includeBom?: boolean }} [opts]
* @returns {string}
*/
export function buildConsumptionCsv(
consumption,
modelBreakdown = [],
{ displaySettings = {}, includeBom = true } = {}
) {
const cons = consumption || {};
const acc = cons.account || {};
const range = cons.selectedRange || {};
const models = mergeModelsByDisplayName(modelBreakdown || [], displaySettings, {
preferLabelInShort: true,
});
const workspaces = Array.isArray(cons.topWorkspaces) ? cons.topWorkspaces : [];
const sessions = Array.isArray(cons.topConversations) ? cons.topConversations : [];
const trend = Array.isArray(cons.trendSeries) ? cons.trendSeries : [];
const rows = [
csvRow(['section', 'name', 'calls', 'input_tokens', 'cache_read_tokens', 'output_tokens', 'total_tokens', 'cache_hit_pct', 'cost_usd', 'extra']),
csvRow([
'summary',
range.label || range.key || 'all',
Number(acc.calls || 0),
Number(acc.inputTokens || 0),
Number(acc.cacheReadTokens || 0),
Number(acc.outputTokens || 0),
Number(acc.totalTokens || 0),
Number(acc.cacheHitPct || 0).toFixed(1),
Number(acc.costUsd || 0).toFixed(4),
`saved_usd=${Number(acc.savedCostUsd || 0).toFixed(4)}`,
]),
];
for (const m of models) {
rows.push(
csvRow([
'model',
m.displayText || m.label || m.shortName || '—',
Number(m.calls || 0),
Number(m.inputTokens || 0),
Number(m.cacheReadTokens || 0),
Number(m.outputTokens || 0),
Number(m.totalTokens || 0),
Number(m.cacheHitPct || 0).toFixed(1),
Number(m.costUsd || 0).toFixed(4),
m.avgTokPerSec != null ? `avg_tps=${Number(m.avgTokPerSec).toFixed(1)}` : '',
])
);
}
for (const w of workspaces) {
rows.push(
csvRow([
'project',
w.label || w.workspacePath || 'unbound',
Number(w.calls || 0),
Number(w.inputTokens || 0),
Number(w.cacheReadTokens || 0),
Number(w.responseTokens || 0) + Number(w.thinkingTokens || 0),
Number(w.totalTokens || 0),
Number(w.cacheHitPct || 0).toFixed(1),
Number(w.costUsd || 0).toFixed(4),
`sessions=${Number(w.sessionCount || 0)}`,
])
);
}
for (const c of sessions) {
rows.push(
csvRow([
'session',
c.title || c.cascadeId || '—',
Number(c.calls || 0),
Number(c.inputTokens || 0),
Number(c.cacheReadTokens || 0),
Number(c.responseTokens || 0) + Number(c.thinkingTokens || 0),
Number(c.totalTokens || 0),
Number(c.cacheHitPct || 0).toFixed(1),
Number(c.costUsd || 0).toFixed(4),
c.sourceName || c.appSource || '',
])
);
}
for (const slot of trend) {
if (!slot || !(Number(slot.tokens || 0) > 0 || Number(slot.calls || 0) > 0)) continue;
rows.push(
csvRow([
'trend',
slot.fullLabel || slot.label || '',
Number(slot.calls || 0),
Number(slot.inputTokens || 0),
Number(slot.cacheReadTokens || 0),
Number(slot.outputTokens || 0),
Number(slot.tokens || 0),
'',
Number(slot.costUsd || 0).toFixed(4),
slot.granularity || '',
])
);
}
return `${includeBom ? '\uFEFF' : ''}${rows.join('\r\n')}\r\n`;
}
/**
* 生成历史用量统计当前区间的 Markdown 汇总报告。
*
* @param {object} consumption
* @param {Array<object>} modelBreakdown
* @param {{ displaySettings?: object }} [opts]
* @returns {string}
*/
export function buildConsumptionMarkdownReport(
consumption,
modelBreakdown = [],
{ displaySettings = {} } = {}
) {
const cons = consumption || {};
const acc = cons.account || {};
const range = cons.selectedRange || {};
const models = mergeModelsByDisplayName(modelBreakdown || [], displaySettings, {
preferLabelInShort: true,
});
const workspaces = Array.isArray(cons.topWorkspaces) ? cons.topWorkspaces : [];
const sessions = Array.isArray(cons.topConversations) ? cons.topConversations : [];
const rangeLabel = range.label || range.key || 'All Time';
const lines = [
`# Usage Report · ${rangeLabel}`,
'',
`- **Total Tokens**: ${formatTokensPrecise(acc.totalTokens || 0)} (${Number(acc.calls || 0)} calls)`,
`- **Est. Cost**: ${formatUsd(acc.costUsd || 0)} (Cache Saved ${formatUsd(acc.savedCostUsd || 0)})`,
`- **Cache Hit Rate**: ${Number(acc.cacheHitPct || 0).toFixed(1)}% (Input ${formatTokensPrecise(acc.inputTokens || 0)} / Cache ${formatTokensPrecise(acc.cacheReadTokens || 0)} / Output ${formatTokensPrecise(acc.outputTokens || 0)})`,
];
if (models.length > 0) {
lines.push(
'',
'## Models',
'',
'| Model | Calls | Tokens | Cache Hit | Avg Speed | Est. Cost |',
'| --- | ---: | ---: | ---: | ---: | ---: |'
);
for (const m of models) {
lines.push(
`| ${escapeMdCell(m.displayText || m.label || m.shortName)} | ${Number(m.calls || 0)} | ${formatTokensPrecise(m.totalTokens || 0)} | ${Number(m.cacheHitPct || 0).toFixed(1)}% | ${m.avgTokPerSec != null ? formatSpeedMetric(m.avgTokPerSec, ' tok/s') : '—'} | ${formatUsd(m.costUsd || 0)} |`
);
}
}
if (workspaces.length > 0) {
lines.push(
'',
'## Projects',
'',
'| Project | Sessions | Calls | Tokens | Cache Hit | Est. Cost |',
'| --- | ---: | ---: | ---: | ---: | ---: |'
);
for (const w of workspaces) {
lines.push(
`| ${escapeMdCell(w.label || w.workspacePath || 'Unbound')} | ${Number(w.sessionCount || 0)} | ${Number(w.calls || 0)} | ${formatTokensPrecise(w.totalTokens || 0)} | ${Number(w.cacheHitPct || 0).toFixed(1)}% | ${formatUsd(w.costUsd || 0)} |`
);
}
}
if (sessions.length > 0) {
lines.push(
'',
'## Top Sessions',
'',
'| Session | Calls | Tokens | Cache Hit | Est. Cost |',
'| --- | ---: | ---: | ---: | ---: |'
);
for (const c of sessions.slice(0, 8)) {
lines.push(
`| ${escapeMdCell(c.title || c.cascadeId)} | ${Number(c.calls || 0)} | ${formatTokensPrecise(c.totalTokens || 0)} | ${Number(c.cacheHitPct || 0).toFixed(1)}% | ${formatUsd(c.costUsd || 0)} |`
);
}
}
return `${lines.join('\n')}\n`;
}
+26
View File
@@ -266,6 +266,13 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'cons.workspaceUnbound': 'Unbound Workspace', 'cons.workspaceUnbound': 'Unbound Workspace',
'cons.workspaceSessions': '{count} sessions', 'cons.workspaceSessions': '{count} sessions',
'cons.workspaceJumpTip': 'Click to inspect latest session in this project', 'cons.workspaceJumpTip': 'Click to inspect latest session in this project',
'cons.exportMenuAria': 'Export and report actions',
'cons.exportCsv': 'Export CSV',
'cons.exportCsvTip': 'Export current usage range as CSV',
'cons.exportCsvDone': 'Exported',
'cons.exportMd': 'Copy Markdown Report',
'cons.exportMdTip': 'Copy Markdown summary report for current range',
'cons.exportMdDone': 'Usage Markdown report copied',
'cons.topConvsEmpty': 'No session usage in this range', 'cons.topConvsEmpty': 'No session usage in this range',
'cons.topConvsSortAria': 'Sort sessions ranking', 'cons.topConvsSortAria': 'Sort sessions ranking',
'cons.topConvsSortCost': 'Cost', 'cons.topConvsSortCost': 'Cost',
@@ -402,6 +409,25 @@ export const I18N_MESSAGES_EN_US = Object.freeze({
'steps.inspContextCostLabel': 'Context / Cost', 'steps.inspContextCostLabel': 'Context / Cost',
'steps.inspPromptTitle': 'Turn Prompt', 'steps.inspPromptTitle': 'Turn Prompt',
'steps.inspRowClickTip': 'Click row to inspect step details', 'steps.inspRowClickTip': 'Click row to inspect step details',
'steps.exportMenuAria': 'Export and report actions',
'steps.exportCsv': 'Export CSV',
'steps.exportCsvTip': 'Export current steps table as CSV',
'steps.exportCsvDone': 'Exported',
'steps.exportMd': 'Copy Markdown Report',
'steps.exportMdTip': 'Copy Markdown diagnostic report for current steps',
'steps.exportMdDone': 'Steps Markdown report copied',
// Export & Toast Feedback
'export.savedLocal': 'Exported {file}',
'export.savedPicked': 'Saved {file}',
'export.savedBrowser': 'Downloaded {file}',
'export.savedBrowserHint': 'Saved via browser default Downloads folder',
'export.openFolder': 'Show in Folder',
'export.failed': 'Export failed, please retry',
'export.hostUnavailable': 'Local export channel unavailable; please restart Antigravity and retry',
'export.copied': 'Copied to clipboard',
'export.copyFailed': 'Copy failed, check clipboard permissions',
'export.closeToast': 'Dismiss notification',
// Step Table Columns (Headers & Option Labels) // Step Table Columns (Headers & Option Labels)
'stepCol.step.th': 'Step', 'stepCol.step.th': 'Step',
+26
View File
@@ -266,6 +266,13 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'cons.workspaceUnbound': '未绑定工作区', 'cons.workspaceUnbound': '未绑定工作区',
'cons.workspaceSessions': '{count} 会话', 'cons.workspaceSessions': '{count} 会话',
'cons.workspaceJumpTip': '点击跳转到该项目最近会话', 'cons.workspaceJumpTip': '点击跳转到该项目最近会话',
'cons.exportMenuAria': '导出及报告选项',
'cons.exportCsv': '导出 CSV',
'cons.exportCsvTip': '导出当前统计区间用量明细为 CSV',
'cons.exportCsvDone': '已导出',
'cons.exportMd': '复制 Markdown 报告',
'cons.exportMdTip': '复制当前统计区间 Markdown 汇总报告',
'cons.exportMdDone': '已复制用量 Markdown 报告',
'cons.topConvsEmpty': '当前时间范围暂无会话消耗记录', 'cons.topConvsEmpty': '当前时间范围暂无会话消耗记录',
'cons.topConvsSortAria': '会话排行排序方式', 'cons.topConvsSortAria': '会话排行排序方式',
'cons.topConvsSortCost': '费用', 'cons.topConvsSortCost': '费用',
@@ -402,6 +409,25 @@ export const I18N_MESSAGES_ZH_CN = Object.freeze({
'steps.inspContextCostLabel': '上下文 / 费用', 'steps.inspContextCostLabel': '上下文 / 费用',
'steps.inspPromptTitle': '本轮提问', 'steps.inspPromptTitle': '本轮提问',
'steps.inspRowClickTip': '点击查看单步详情', 'steps.inspRowClickTip': '点击查看单步详情',
'steps.exportMenuAria': '导出及报告选项',
'steps.exportCsv': '导出 CSV',
'steps.exportCsvTip': '导出当前步骤明细为 CSV 文件',
'steps.exportCsvDone': '已导出',
'steps.exportMd': '复制 Markdown 报告',
'steps.exportMdTip': '复制当前步骤 Markdown 诊断报告',
'steps.exportMdDone': '已复制步骤 Markdown 报告',
// Export & Toast Feedback
'export.savedLocal': '已导出 {file}',
'export.savedPicked': '已保存 {file}',
'export.savedBrowser': '已下载 {file}',
'export.savedBrowserHint': '文件已交给浏览器默认下载目录',
'export.openFolder': '打开位置',
'export.failed': '导出失败,请稍后重试',
'export.hostUnavailable': '本机导出通道暂未就绪,请重启 Antigravity 后重试',
'export.copied': '已复制到剪贴板',
'export.copyFailed': '复制失败,请检查剪贴板权限',
'export.closeToast': '关闭提示',
// Step Table Columns (Headers & Option Labels) // Step Table Columns (Headers & Option Labels)
'stepCol.step.th': '步序', 'stepCol.step.th': '步序',
+13
View File
@@ -105,6 +105,19 @@ export const SVG_ICON_DEFS = Object.freeze({
{ tag: 'path', attrs: { d: 'M8 10.2V2.6M5 5.4L8 2.4l3 3' } }, { tag: 'path', attrs: { d: 'M8 10.2V2.6M5 5.4L8 2.4l3 3' } },
{ tag: 'path', attrs: { d: 'M2.6 11.4v1.4a1 1 0 0 0 1 1h8.8a1 1 0 0 0 1-1v-1.4' } }, { tag: 'path', attrs: { d: 'M2.6 11.4v1.4a1 1 0 0 0 1 1h8.8a1 1 0 0 0 1-1v-1.4' } },
], ],
'more-vertical': [
{ tag: 'circle', attrs: { cx: '8', cy: '3.6', r: '1.15', fill: 'currentColor', stroke: 'none' } },
{ tag: 'circle', attrs: { cx: '8', cy: '8', r: '1.15', fill: 'currentColor', stroke: 'none' } },
{ tag: 'circle', attrs: { cx: '8', cy: '12.4', r: '1.15', fill: 'currentColor', stroke: 'none' } },
],
folder: [
{
tag: 'path',
attrs: {
d: 'M2.2 4.3a1.3 1.3 0 0 1 1.3-1.3h3l1.3 1.5h4.7a1.3 1.3 0 0 1 1.3 1.3v5.9a1.3 1.3 0 0 1-1.3 1.3H3.5a1.3 1.3 0 0 1-1.3-1.3V4.3z',
},
},
],
grip: [ grip: [
{ tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '6', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
{ tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } }, { tag: 'circle', attrs: { cx: '10', cy: '4', r: '1.05', fill: 'currentColor', stroke: 'none' } },
+33
View File
@@ -22,8 +22,41 @@ export const uiStore = createReactiveStore({
settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps' settingsStructureTab: 'mount', // 'mount' | 'hover' | 'overview' | 'steps'
selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId> selectedAgentScope: 'all', // 'all' | 'main' | <subagent cascadeId>
ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId> ctxInspectorAgentId: 'auto', // 'auto' | 'main' | <subagent cascadeId>
toast: null, // { id, message, detail, actionLabel, onAction, tone, durationMs }
}); });
let toastSeq = 0;
/**
* 触发全局底部轻量通知条(用于文件导出路径提示、一键定位文件夹及剪贴板复制反馈)。
*
* @param {{ message: string, detail?: string, actionLabel?: string, onAction?: (() => void) | null, tone?: 'ok' | 'info' | 'warn', durationMs?: number }} toastConfig
* @returns {number}
*/
export function showUiToast(toastConfig) {
if (!toastConfig || !toastConfig.message) return 0;
toastSeq += 1;
uiStore.setState({
toast: {
id: toastSeq,
message: String(toastConfig.message),
detail: toastConfig.detail ? String(toastConfig.detail) : '',
actionLabel: toastConfig.actionLabel ? String(toastConfig.actionLabel) : '',
onAction: typeof toastConfig.onAction === 'function' ? toastConfig.onAction : null,
tone: toastConfig.tone || 'ok',
durationMs: Number(toastConfig.durationMs) >= 0 ? Number(toastConfig.durationMs) : 5200,
},
});
return toastSeq;
}
export function dismissUiToast(toastId = 0) {
const cur = uiStore.getState().toast;
if (!cur) return;
if (toastId && cur.id !== toastId) return;
uiStore.setState({ toast: null });
}
export function getVisibleMonitorView(state = uiStore.getState()) { export function getVisibleMonitorView(state = uiStore.getState()) {
return state.monitorVisible ? state.activeView : null; return state.monitorVisible ? state.activeView : null;
} }
+209
View File
@@ -1071,3 +1071,212 @@
opacity: 0.28; opacity: 0.28;
cursor: default; cursor: default;
} }
/* --- 紧凑竖向三点操作菜单 (ActionMenu) --- */
.action-menu {
position: relative;
display: inline-flex;
align-items: center;
flex-shrink: 0;
}
.action-menu[hidden] {
display: none !important;
}
.action-menu-trigger {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
padding: 0;
border: 1px solid transparent;
border-radius: var(--radius-xs);
background: transparent;
color: var(--text-muted);
cursor: pointer;
transition:
background-color var(--dur-instant) var(--ease-fast),
color var(--dur-instant) var(--ease-fast),
border-color var(--dur-instant) var(--ease-fast);
}
.action-menu-trigger:hover,
.action-menu.is-open .action-menu-trigger {
background: var(--surface-hover);
color: var(--text-primary);
}
.action-menu-popover {
position: absolute;
top: calc(100% + 4px);
z-index: 45;
min-width: 152px;
padding: 4px;
border-radius: var(--radius-sm);
border: 1px solid var(--border-hairline);
background: var(--surface-panel);
box-shadow: var(--shadow-popover);
display: flex;
flex-direction: column;
gap: 2px;
}
.action-menu-popover.align-right {
right: 0;
}
.action-menu-popover.align-left {
left: 0;
}
.action-menu-popover[hidden] {
display: none !important;
}
.action-menu-item {
display: flex;
align-items: center;
gap: 7px;
width: 100%;
padding: 6px 9px;
border: none;
border-radius: var(--radius-xs);
background: transparent;
color: var(--text-primary);
font-family: var(--font-sans);
font-size: var(--fs-sm);
line-height: 1.25;
text-align: left;
white-space: nowrap;
cursor: pointer;
transition:
background-color var(--dur-instant) var(--ease-fast),
color var(--dur-instant) var(--ease-fast);
}
.action-menu-item:hover:not(:disabled) {
background: var(--surface-hover);
}
.action-menu-item:disabled {
opacity: 0.45;
cursor: default;
}
.action-menu-item-label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
/* --- 全局底部轻量导出 / 复制提示条 (App Toast) --- */
.app-toast {
position: absolute;
left: 12px;
right: 12px;
bottom: 12px;
z-index: 60;
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
border-radius: var(--radius-sm);
border: 1px solid var(--border-hairline);
background: var(--surface-panel);
box-shadow: var(--shadow-popover);
color: var(--text-primary);
pointer-events: auto;
}
.app-toast[hidden] {
display: none !important;
}
.app-toast-body {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
min-width: 0;
}
.app-toast-msg {
font-size: var(--fs-sm);
font-weight: 600;
line-height: 1.25;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.app-toast.tone-ok .app-toast-msg {
color: var(--metric-ok);
}
.app-toast.tone-warn .app-toast-msg {
color: var(--metric-warn);
}
.app-toast-detail {
font-size: var(--fs-xs);
line-height: 1.25;
color: var(--text-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.app-toast-detail[hidden] {
display: none !important;
}
.app-toast-action {
display: inline-flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
height: 24px;
padding: 0 9px;
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
background: var(--accent-primary-soft);
color: var(--accent-primary);
font-family: var(--font-sans);
font-size: var(--fs-xs);
font-weight: 600;
cursor: pointer;
white-space: nowrap;
transition: background-color var(--dur-instant) var(--ease-fast);
}
.app-toast-action:hover {
background: color-mix(in srgb, var(--accent-primary) 22%, transparent);
}
.app-toast-action[hidden] {
display: none !important;
}
.app-toast-close {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 20px;
height: 20px;
padding: 0;
border: none;
border-radius: var(--radius-xs);
background: transparent;
color: var(--text-muted);
cursor: pointer;
}
.app-toast-close:hover {
background: var(--surface-hover);
color: var(--text-primary);
}
+12
View File
@@ -776,6 +776,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
/* --- 7. 全景悬浮窗与工具提示浮层:零边框 + 空气阴影 + 0.15s 平滑跟随过渡 --- */ /* --- 7. 全景悬浮窗与工具提示浮层:零边框 + 空气阴影 + 0.15s 平滑跟随过渡 --- */
[data-modern-ui="true"] .select-menu, [data-modern-ui="true"] .select-menu,
[data-modern-ui="true"] .action-menu-popover,
[data-modern-ui="true"] .app-toast,
[data-modern-ui="true"] .dt-popover, [data-modern-ui="true"] .dt-popover,
[data-modern-ui="true"] .sstep-tooltip { [data-modern-ui="true"] .sstep-tooltip {
border: none; border: none;
@@ -784,6 +786,16 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
animation: anim-modern-tip-fade 120ms var(--ease-modern); animation: anim-modern-tip-fade 120ms var(--ease-modern);
} }
[data-modern-ui="true"] .action-menu-trigger:hover,
[data-modern-ui="true"] .action-menu.is-open .action-menu-trigger,
[data-modern-ui="true"] .action-menu-item:hover:not(:disabled) {
background: var(--modern-surface-hover);
}
[data-modern-ui="true"] .app-toast-action {
border: none;
}
[data-modern-ui="true"] .select-search-wrap { [data-modern-ui="true"] .select-search-wrap {
border: none; border: none;
background: var(--modern-surface-subtle); background: var(--modern-surface-subtle);
@@ -14,6 +14,14 @@
gap: 6px; gap: 6px;
} }
.cons-overview-controls {
display: inline-flex;
align-items: center;
gap: 4px;
margin-left: auto;
min-width: 0;
}
.cons-overview-head .segmented { .cons-overview-head .segmented {
gap: 1px; gap: 1px;
} }
+79 -2
View File
@@ -33,8 +33,18 @@ import {
resolveDeterministicModelColor, resolveDeterministicModelColor,
} from '../core/formatters.js'; } from '../core/formatters.js';
import { scaleBucketsExact } from '../../shared/telemetry-display-rules.mjs'; import { scaleBucketsExact } from '../../shared/telemetry-display-rules.mjs';
import {
buildConsumptionCsv,
buildConsumptionMarkdownReport,
sanitizeExportFilename,
} from '../core/reportExporter.js';
import {
copyTextWithFeedback,
exportTextFileWithFeedback,
} from '../core/fileExportClient.js';
import { i18nStore, isEnglishLocale, t } from '../i18n/index.js'; import { i18nStore, isEnglishLocale, t } from '../i18n/index.js';
import { createSvgIcon } from '../icons/SvgIcon.js'; import { createSvgIcon } from '../icons/SvgIcon.js';
import { ActionMenu } from '../components/ui/ActionMenu.js';
import { import {
prefetchConsumptionPresets, prefetchConsumptionPresets,
selectConsumptionTimeRange, selectConsumptionTimeRange,
@@ -208,6 +218,56 @@ export const ConsumptionView = defineComponent({
const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.replyAndThink', { resp: 0, think: 0 }) }); const outputSubText = h('span', { className: 'text-muted text-mono', style: 'font-size: var(--fs-md);', text: t('cons.replyAndThink', { resp: 0, think: 0 }) });
const overviewSegBar = createFourSegmentBar(); const overviewSegBar = createFourSegmentBar();
const consExportMenu = ActionMenu({
ariaLabel: t('cons.exportMenuAria'),
className: 'cons-export-menu',
items: [
{
key: 'csv',
icon: 'download',
label: t('cons.exportCsv'),
title: t('cons.exportCsvTip'),
onSelect: () => {
const cons = latestSlice?.consumption;
if (!cons) return;
const displaySettings = {
modelDisplayMode: latestSlice?.modelDisplayMode,
showUpstreamModel: latestSlice?.showUpstreamModel,
orchestratorIdMode: latestSlice?.orchestratorIdMode,
};
const csv = buildConsumptionCsv(cons, latestSlice?.modelBreakdown || [], {
displaySettings,
});
const rKey = cons.selectedRange?.key || latestSlice?.range || 'all';
void exportTextFileWithFeedback(
sanitizeExportFilename(`usage-${rKey}`, 'csv'),
csv,
'text/csv;charset=utf-8'
);
},
},
{
key: 'md',
icon: 'copy',
label: t('cons.exportMd'),
title: t('cons.exportMdTip'),
onSelect: () => {
const cons = latestSlice?.consumption;
if (!cons) return;
const displaySettings = {
modelDisplayMode: latestSlice?.modelDisplayMode,
showUpstreamModel: latestSlice?.showUpstreamModel,
orchestratorIdMode: latestSlice?.orchestratorIdMode,
};
const md = buildConsumptionMarkdownReport(cons, latestSlice?.modelBreakdown || [], {
displaySettings,
});
void copyTextWithFeedback(md, t('cons.exportMdDone'));
},
},
],
});
consExportMenu.refs.setHidden(true);
const totalTokensLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.totalTokens') }); const totalTokensLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.totalTokens') });
const estCostLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.estCost') }); const estCostLabel = h('span', { className: 'text-muted', style: 'font-size: var(--fs-md);', text: t('cons.estCost') });
const cacheHitRateLabel = h('span', { text: t('cons.cacheHitRate') }); const cacheHitRateLabel = h('span', { text: t('cons.cacheHitRate') });
@@ -220,7 +280,10 @@ export const ConsumptionView = defineComponent({
h('span', { className: 'panel-title' }, [ h('span', { className: 'panel-title' }, [
dateSpanBadge, dateSpanBadge,
]), ]),
timeFilterSwitch.el, h('div', { className: 'cons-overview-controls' }, [
timeFilterSwitch.el,
consExportMenu.el,
]),
]), ]),
customRangeBar, customRangeBar,
h('div', { className: 'cons-box cons-unified-matrix' }, [ h('div', { className: 'cons-box cons-unified-matrix' }, [
@@ -1725,6 +1788,7 @@ export const ConsumptionView = defineComponent({
think: formatTokensPrecise(thinkingTokens), think: formatTokensPrecise(thinkingTokens),
}) })
); );
consExportMenu.refs.setHidden(!(totalTokens > 0 || Number(acct.calls || 0) > 0));
overviewSegBar.update({ overviewSegBar.update({
inputTokens, inputTokens,
@@ -2174,6 +2238,11 @@ export const ConsumptionView = defineComponent({
patchText(newInputLabel, t('cons.newInput')); patchText(newInputLabel, t('cons.newInput'));
patchText(cacheReadLabel, t('cons.cacheRead')); patchText(cacheReadLabel, t('cons.cacheRead'));
patchText(outputUsageLabel, t('cons.outputUsage')); patchText(outputUsageLabel, t('cons.outputUsage'));
consExportMenu.refs.setAriaLabel(t('cons.exportMenuAria'));
consExportMenu.refs.updateItemLabels({
csv: { label: t('cons.exportCsv'), title: t('cons.exportCsvTip') },
md: { label: t('cons.exportMd'), title: t('cons.exportMdTip') },
});
patchText(trendTitleSpan, t('cons.trendTitle')); patchText(trendTitleSpan, t('cons.trendTitle'));
rankingTabSwitch.setProps({ rankingTabSwitch.setProps({
ariaLabel: t('cons.rankTabAria'), ariaLabel: t('cons.rankTabAria'),
@@ -2216,6 +2285,7 @@ export const ConsumptionView = defineComponent({
unsub(); unsub();
unsubView(); unsubView();
unsubI18n(); unsubI18n();
consExportMenu.destroy();
trendChart.destroy?.(); trendChart.destroy?.();
rankingTabSwitch.destroy(); rankingTabSwitch.destroy();
modelsSortSwitch.destroy(); modelsSortSwitch.destroy();
@@ -2228,7 +2298,14 @@ export const ConsumptionView = defineComponent({
return { return {
el: rootEl, el: rootEl,
refs: { timeFilterSwitch, startPicker, endPicker, viewScrollbar, breakdownPopoverEl }, refs: {
timeFilterSwitch,
startPicker,
endPicker,
viewScrollbar,
breakdownPopoverEl,
consExportMenu,
},
}; };
}, },
}); });
+57 -1
View File
@@ -41,7 +41,17 @@ import {
findPrevAgentContextTokens, findPrevAgentContextTokens,
getStepSelectionKey, getStepSelectionKey,
} from '../core/stepInspector.js'; } from '../core/stepInspector.js';
import {
buildStepsCsv,
buildStepsMarkdownReport,
sanitizeExportFilename,
} from '../core/reportExporter.js';
import {
copyTextWithFeedback,
exportTextFileWithFeedback,
} from '../core/fileExportClient.js';
import { createSvgIcon, patchSvgIcon } from '../icons/SvgIcon.js'; import { createSvgIcon, patchSvgIcon } from '../icons/SvgIcon.js';
import { ActionMenu } from '../components/ui/ActionMenu.js';
import { getEffectiveLocale, i18nStore, t } from '../i18n/index.js'; import { getEffectiveLocale, i18nStore, t } from '../i18n/index.js';
import { import {
formatAgentLabel, formatAgentLabel,
@@ -453,10 +463,49 @@ export const StepsDetailView = defineComponent({
{ className: 'steps-quick-chips', hidden: true }, { className: 'steps-quick-chips', hidden: true },
quickChipBtns.map((c) => c.btn) quickChipBtns.map((c) => c.btn)
); );
const stepsExportMenu = ActionMenu({
ariaLabel: t('steps.exportMenuAria'),
className: 'steps-export-menu',
items: [
{
key: 'csv',
icon: 'download',
label: t('steps.exportCsv'),
title: t('steps.exportCsvTip'),
onSelect: () => {
if (currentTableSteps.length === 0) return;
const csv = buildStepsCsv(currentTableSteps, {
displaySettings: currentDisplaySettings,
});
const title = latestSlice?.activeConversation?.title || latestSlice?.cascadeId || 'steps';
void exportTextFileWithFeedback(
sanitizeExportFilename(`steps-${title}`, 'csv'),
csv,
'text/csv;charset=utf-8'
);
},
},
{
key: 'md',
icon: 'copy',
label: t('steps.exportMd'),
title: t('steps.exportMdTip'),
onSelect: () => {
if (currentTableSteps.length === 0) return;
const md = buildStepsMarkdownReport(currentTableSteps, {
title: latestSlice?.activeConversation?.title || '',
cascadeId: latestSlice?.cascadeId || latestSlice?.activeConversation?.cascadeId || '',
displaySettings: currentDisplaySettings,
});
void copyTextWithFeedback(md, t('steps.exportMdDone'));
},
},
],
});
const stepsFilterToolbarEl = h( const stepsFilterToolbarEl = h(
'div', 'div',
{ className: 'steps-filter-toolbar', hidden: true }, { className: 'steps-filter-toolbar', hidden: true },
[stepSearchWrapEl, stepQuickChipsEl] [stepSearchWrapEl, stepQuickChipsEl, stepsExportMenu.el]
); );
// --- 点击行展开的单步透视诊断抽屉 --- // --- 点击行展开的单步透视诊断抽屉 ---
@@ -991,6 +1040,11 @@ export const StepsDetailView = defineComponent({
patchAttr(inspCloseBtn, 'aria-label', t('steps.inspCloseAria')); patchAttr(inspCloseBtn, 'aria-label', t('steps.inspCloseAria'));
patchAttr(inspCloseBtn, 'title', t('steps.inspCloseAria')); patchAttr(inspCloseBtn, 'title', t('steps.inspCloseAria'));
if (!inspCopyTimer) patchText(inspCopyLabel, t('steps.inspCopy')); if (!inspCopyTimer) patchText(inspCopyLabel, t('steps.inspCopy'));
stepsExportMenu.refs.setAriaLabel(t('steps.exportMenuAria'));
stepsExportMenu.refs.updateItemLabels({
csv: { label: t('steps.exportCsv'), title: t('steps.exportCsvTip') },
md: { label: t('steps.exportMd'), title: t('steps.exportMdTip') },
});
lastAnomalyStripSig = ''; lastAnomalyStripSig = '';
lineMetricSwitch.setProps({ lineMetricSwitch.setProps({
modelValue: selectedLineMetric, modelValue: selectedLineMetric,
@@ -1997,6 +2051,7 @@ export const StepsDetailView = defineComponent({
clearTimeout(inspCopyTimer); clearTimeout(inspCopyTimer);
inspCopyTimer = null; inspCopyTimer = null;
} }
stepsExportMenu.destroy();
panelEl.removeEventListener?.('keydown', onPanelKeydown); panelEl.removeEventListener?.('keydown', onPanelKeydown);
modelsAnalyticsPane.removeEventListener('scroll', onModelsPaneScroll); modelsAnalyticsPane.removeEventListener('scroll', onModelsPaneScroll);
unsubUi(); unsubUi();
@@ -2029,6 +2084,7 @@ export const StepsDetailView = defineComponent({
stepsFilterToolbarEl, stepsFilterToolbarEl,
stepSearchInput, stepSearchInput,
stepQuickChipsEl, stepQuickChipsEl,
stepsExportMenu,
stepInspectorDrawerEl, stepInspectorDrawerEl,
modelsAnomalyStripEl, modelsAnomalyStripEl,
modelsListEl, modelsListEl,
@@ -11,8 +11,8 @@ import { setI18nLanguage, t } from '../../i18n/index.js';
import { import {
buildExportableSettingsJson, buildExportableSettingsJson,
parseImportedSettingsJson, parseImportedSettingsJson,
triggerTextFileDownload,
} from '../../core/settingsBackup.js'; } from '../../core/settingsBackup.js';
import { exportTextFileWithFeedback } from '../../core/fileExportClient.js';
import { import {
normalizeClientModelDisplayMode, normalizeClientModelDisplayMode,
normalizeClientOrchestratorIdMode, normalizeClientOrchestratorIdMode,
@@ -544,14 +544,19 @@ export const SettingsOtherTab = defineComponent({
{ {
type: 'button', type: 'button',
className: 'btn-secondary', className: 'btn-secondary',
onClick: () => { onClick: async () => {
const json = buildExportableSettingsJson(latestSettings || {}); const json = buildExportableSettingsJson(latestSettings || {});
triggerTextFileDownload( const res = await exportTextFileWithFeedback(
'antigravity-usage-monitor-settings.json', 'antigravity-usage-monitor-settings.json',
json, json,
'application/json;charset=utf-8' 'application/json;charset=utf-8'
); );
showMaintFeedback(t('settings.oth.exportDone'), 2400); if (res?.ok) {
showMaintFeedback(
res.filePath ? `${t('settings.oth.exportDone')} · ${res.filePath}` : t('settings.oth.exportDone'),
4200
);
}
}, },
}, },
[createSvgIcon('download', { size: 12 }), exportJsonBtnText] [createSvgIcon('download', { size: 12 }), exportJsonBtnText]
+229
View File
@@ -1466,6 +1466,215 @@ html[data-standalone="true"] .app-shell {
cursor: default; cursor: default;
} }
/* --- 紧凑竖向三点操作菜单 (ActionMenu) --- */
.action-menu {
position: relative;
display: inline-flex;
align-items: center;
flex-shrink: 0;
}
.action-menu[hidden] {
display: none !important;
}
.action-menu-trigger {
display: inline-flex;
align-items: center;
justify-content: center;
width: 24px;
height: 24px;
padding: 0;
border: 1px solid transparent;
border-radius: var(--radius-xs);
background: transparent;
color: var(--text-muted);
cursor: pointer;
transition:
background-color var(--dur-instant) var(--ease-fast),
color var(--dur-instant) var(--ease-fast),
border-color var(--dur-instant) var(--ease-fast);
}
.action-menu-trigger:hover,
.action-menu.is-open .action-menu-trigger {
background: var(--surface-hover);
color: var(--text-primary);
}
.action-menu-popover {
position: absolute;
top: calc(100% + 4px);
z-index: 45;
min-width: 152px;
padding: 4px;
border-radius: var(--radius-sm);
border: 1px solid var(--border-hairline);
background: var(--surface-panel);
box-shadow: var(--shadow-popover);
display: flex;
flex-direction: column;
gap: 2px;
}
.action-menu-popover.align-right {
right: 0;
}
.action-menu-popover.align-left {
left: 0;
}
.action-menu-popover[hidden] {
display: none !important;
}
.action-menu-item {
display: flex;
align-items: center;
gap: 7px;
width: 100%;
padding: 6px 9px;
border: none;
border-radius: var(--radius-xs);
background: transparent;
color: var(--text-primary);
font-family: var(--font-sans);
font-size: var(--fs-sm);
line-height: 1.25;
text-align: left;
white-space: nowrap;
cursor: pointer;
transition:
background-color var(--dur-instant) var(--ease-fast),
color var(--dur-instant) var(--ease-fast);
}
.action-menu-item:hover:not(:disabled) {
background: var(--surface-hover);
}
.action-menu-item:disabled {
opacity: 0.45;
cursor: default;
}
.action-menu-item-label {
flex: 1;
min-width: 0;
overflow: hidden;
text-overflow: ellipsis;
}
/* --- 全局底部轻量导出 / 复制提示条 (App Toast) --- */
.app-toast {
position: absolute;
left: 12px;
right: 12px;
bottom: 12px;
z-index: 60;
display: flex;
align-items: center;
gap: 8px;
padding: 8px 10px;
border-radius: var(--radius-sm);
border: 1px solid var(--border-hairline);
background: var(--surface-panel);
box-shadow: var(--shadow-popover);
color: var(--text-primary);
pointer-events: auto;
}
.app-toast[hidden] {
display: none !important;
}
.app-toast-body {
display: flex;
flex-direction: column;
gap: 2px;
flex: 1;
min-width: 0;
}
.app-toast-msg {
font-size: var(--fs-sm);
font-weight: 600;
line-height: 1.25;
color: var(--text-primary);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.app-toast.tone-ok .app-toast-msg {
color: var(--metric-ok);
}
.app-toast.tone-warn .app-toast-msg {
color: var(--metric-warn);
}
.app-toast-detail {
font-size: var(--fs-xs);
line-height: 1.25;
color: var(--text-muted);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.app-toast-detail[hidden] {
display: none !important;
}
.app-toast-action {
display: inline-flex;
align-items: center;
gap: 4px;
flex-shrink: 0;
height: 24px;
padding: 0 9px;
border: 1px solid var(--border-hairline);
border-radius: var(--radius-xs);
background: var(--accent-primary-soft);
color: var(--accent-primary);
font-family: var(--font-sans);
font-size: var(--fs-xs);
font-weight: 600;
cursor: pointer;
white-space: nowrap;
transition: background-color var(--dur-instant) var(--ease-fast);
}
.app-toast-action:hover {
background: color-mix(in srgb, var(--accent-primary) 22%, transparent);
}
.app-toast-action[hidden] {
display: none !important;
}
.app-toast-close {
display: inline-flex;
align-items: center;
justify-content: center;
flex-shrink: 0;
width: 20px;
height: 20px;
padding: 0;
border: none;
border-radius: var(--radius-xs);
background: transparent;
color: var(--text-muted);
cursor: pointer;
}
.app-toast-close:hover {
background: var(--surface-hover);
color: var(--text-primary);
}
/* --- src/styles/views-overview.css --- */ /* --- src/styles/views-overview.css --- */
/* /*
* 实时概览视图与通用面板卡片样式表 (views-overview.css). * 实时概览视图与通用面板卡片样式表 (views-overview.css).
@@ -2229,6 +2438,14 @@ html[data-standalone="true"] .app-shell {
gap: 6px; gap: 6px;
} }
.cons-overview-controls {
display: inline-flex;
align-items: center;
gap: 4px;
margin-left: auto;
min-width: 0;
}
.cons-overview-head .segmented { .cons-overview-head .segmented {
gap: 1px; gap: 1px;
} }
@@ -8310,6 +8527,8 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
/* --- 7. 全景悬浮窗与工具提示浮层:零边框 + 空气阴影 + 0.15s 平滑跟随过渡 --- */ /* --- 7. 全景悬浮窗与工具提示浮层:零边框 + 空气阴影 + 0.15s 平滑跟随过渡 --- */
[data-modern-ui="true"] .select-menu, [data-modern-ui="true"] .select-menu,
[data-modern-ui="true"] .action-menu-popover,
[data-modern-ui="true"] .app-toast,
[data-modern-ui="true"] .dt-popover, [data-modern-ui="true"] .dt-popover,
[data-modern-ui="true"] .sstep-tooltip { [data-modern-ui="true"] .sstep-tooltip {
border: none; border: none;
@@ -8318,6 +8537,16 @@ html[data-standalone="true"][data-modern-ui="true"] .app-shell {
animation: anim-modern-tip-fade 120ms var(--ease-modern); animation: anim-modern-tip-fade 120ms var(--ease-modern);
} }
[data-modern-ui="true"] .action-menu-trigger:hover,
[data-modern-ui="true"] .action-menu.is-open .action-menu-trigger,
[data-modern-ui="true"] .action-menu-item:hover:not(:disabled) {
background: var(--modern-surface-hover);
}
[data-modern-ui="true"] .app-toast-action {
border: none;
}
[data-modern-ui="true"] .select-search-wrap { [data-modern-ui="true"] .select-search-wrap {
border: none; border: none;
background: var(--modern-surface-subtle); background: var(--modern-surface-subtle);
@@ -1126,10 +1126,12 @@ test('P1 audit fixes: shared third-party pool & route single-source, pure frozen
assert.equal(normalizeI18nLanguage('system'), 'auto'); assert.equal(normalizeI18nLanguage('system'), 'auto');
assert.equal(typeof isEquivalentTelemetry, 'function'); assert.equal(typeof isEquivalentTelemetry, 'function');
assert.equal(BRIDGE_API_ROUTE_DEFS.length, 12); assert.equal(BRIDGE_API_ROUTE_DEFS.length, 14);
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/bridge/relaunch')); assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/bridge/relaunch'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/session-migration/catalog')); assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/session-migration/catalog'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/session-migration/migrate')); assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/session-migration/migrate'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/export-file'));
assert.ok(BRIDGE_API_ROUTE_DEFS.some((r) => r.path === '/api/reveal-file'));
// 1. Third-party pool parity across backend, CLI statusline, and frontend metricRegistry // 1. Third-party pool parity across backend, CLI statusline, and frontend metricRegistry
const h = backendHarness(); const h = backendHarness();
@@ -1221,100 +1221,6 @@ test('Feature 9: workspace/project cost aggregation (full + fast paths) and Proj
assert.equal(telemetryStore.getState().selectedConversationId, 'ws-conv-b1'); assert.equal(telemetryStore.getState().selectedConversationId, 'ws-conv-b1');
}); });
test('Feature 13: TopSessionHeader exposes project/workspace tags on sessions and filters by workspace name', async (t) => {
const { TopSessionHeader } = await import('../src/components/layout/TopSessionHeader.js');
const now = Date.now();
const harn = backendHarness({
cache: {
'proj-conv-1': {
cascadeId: 'proj-conv-1',
title: 'Fix auth bug',
workspaceUri: 'file:///F%3A/repos/billing-service',
steps: [{ stepIndex: 1, modelKey: 'MODEL_PLACEHOLDER_M18', inputTokens: 1000, outputTokens: 100, createdAtMs: now - 5000 }],
},
'proj-conv-2': {
cascadeId: 'proj-conv-2',
title: 'Fix auth bug',
workspaceUri: 'file:///F%3A/repos/web-dashboard',
steps: [{ stepIndex: 1, modelKey: 'MODEL_PLACEHOLDER_M18', inputTokens: 1000, outputTokens: 100, createdAtMs: now - 10000 }],
},
},
summaries: {
'proj-conv-1': { summary: 'Fix auth bug', stepCount: 1, lastModifiedTime: new Date(now - 5000).toISOString() },
'proj-conv-2': { summary: 'Fix auth bug', stepCount: 1, lastModifiedTime: new Date(now - 10000).toISOString() },
},
});
const payload = await harn.buildTelemetryPayloadInternal('proj-conv-1');
const convById = new Map((payload.conversations || []).map((c) => [c.cascadeId, c]));
assert.equal(convById.get('proj-conv-1')?.workspaceName, 'billing-service');
assert.equal(convById.get('proj-conv-2')?.workspaceName, 'web-dashboard');
const prevDoc = globalThis.document;
const prevWin = globalThis.window;
const prevLocale = i18nStore.getState().locale;
const prevUi = uiStore.getState();
const prevTel = telemetryStore.getState();
const { document } = createMockDom();
globalThis.document = document;
globalThis.window = {
innerWidth: 960,
innerHeight: 720,
addEventListener() {},
removeEventListener() {},
};
let header = null;
t.after(() => {
header?.destroy?.();
setI18nLanguage(prevLocale);
uiStore.setState(prevUi, { sync: true });
telemetryStore.setState(prevTel, { sync: true });
globalThis.document = prevDoc;
globalThis.window = prevWin;
});
setI18nLanguage('zh-CN');
uiStore.setState({ activeView: 'overview', monitorVisible: true }, { sync: true });
telemetryStore.setState(
{
selectedConversationId: '',
telemetry: {
...payload,
conversations: [
...payload.conversations,
...Array.from({ length: 6 }, (_, i) => ({
cascadeId: `pad-${i}`,
title: `Other session ${i}`,
stepCount: 2,
workspaceName: 'misc-repo',
})),
],
},
},
{ sync: true }
);
header = TopSessionHeader();
document.body.appendChild(header.el);
header.refs.convSelect.open();
const optionEls = header.refs.convSelect.el.querySelectorAll('.select-option');
const billingOpt = optionEls.find((el) => (el.textContent || '').includes('billing-service'));
assert.ok(billingOpt, 'Session dropdown option displays workspaceName tag');
const searchInput = header.refs.convSelect.el.querySelector('.select-search-input');
assert.ok(searchInput, 'Search input present for >6 sessions');
searchInput.value = 'web-dashboard';
searchInput.dispatchEvent({ type: 'input', target: searchInput });
const visibleOpts = header.refs.convSelect.el
.querySelectorAll('.select-option')
.filter((el) => !el.hasAttribute('hidden'));
assert.equal(visibleOpts.length, 1);
assert.match(visibleOpts[0].textContent, /web-dashboard/);
});
test('Feature 10: StepsDetailView live search, dynamic diagnostic chips, and click-to-inspect step drawer', async (t) => { test('Feature 10: StepsDetailView live search, dynamic diagnostic chips, and click-to-inspect step drawer', async (t) => {
const { const {
computeStepQuickChipCounts, computeStepQuickChipCounts,
@@ -1508,3 +1414,509 @@ test('Feature 10: StepsDetailView live search, dynamic diagnostic chips, and cli
rows[0].onclick(); rows[0].onclick();
assert.equal(view.refs.stepInspectorDrawerEl.hasAttribute('hidden'), true); assert.equal(view.refs.stepInspectorDrawerEl.hasAttribute('hidden'), true);
}); });
test('Feature 11: RFC-4180 formula-safe CSV and Markdown report export for Steps and Consumption views', async () => {
const {
escapeCsvCell,
sanitizeExportFilename,
buildStepsCsv,
buildStepsMarkdownReport,
buildConsumptionCsv,
buildConsumptionMarkdownReport,
} = await import('../src/core/reportExporter.js');
// 1. Formula injection neutralization and RFC-4180 quoting
assert.equal(escapeCsvCell('=CMD("calc")'), `"'=CMD(""calc"")"` );
assert.equal(escapeCsvCell('+SUM(A1:A2)'), `'+SUM(A1:A2)`);
assert.equal(escapeCsvCell('@evil'), `'@evil`);
assert.equal(escapeCsvCell('-12.5'), '-12.5'); // genuine signed numbers preserved
assert.equal(escapeCsvCell('hello, "world"\nline2'), '"hello, ""world""\nline2"');
const fname = sanitizeExportFilename('my:bad/title*name?', 'csv', Date.UTC(2026, 10, 22, 8, 5));
assert.match(fname, /^my-bad-title-name-\d{8}-\d{4}\.csv$/);
// 2. Steps CSV (UTF-8 BOM + safe cells) & Markdown report
const sampleSteps = [
{
stepIndex: 2,
createdAtMs: Date.UTC(2026, 10, 22, 9, 0, 0),
modelShort: '4-neon',
modelLabel: 'Gemini 4 Neon',
rawModelId: 'gemini-4-neon',
tokPerSec: 55.2,
ttftSec: 2.4,
durationSec: 6.8,
inputTokens: 10_000,
cacheReadTokens: 90_000,
outputTokens: 500,
thinkingTokens: 300,
responseTokens: 200,
contextTokens: 100_500,
cacheHitPct: 90,
costUsd: 0.145,
turnPrompt: '=HYPERLINK("http://x"), "test"',
},
];
const stepsCsv = buildStepsCsv(sampleSteps);
assert.equal(stepsCsv.startsWith('\uFEFFstep,timestamp,'), true);
assert.match(stepsCsv, /"'=HYPERLINK\(""http:\/\/x""\), ""test"""/);
assert.match(stepsCsv, /0\.145000/);
const stepsMd = buildStepsMarkdownReport(sampleSteps, {
title: 'Perf Audit',
cascadeId: 'cid-export-1',
});
assert.match(stepsMd, /# Perf Audit/);
assert.match(stepsMd, /## Model Breakdown/);
assert.match(stepsMd, /## Top Costliest Steps/);
assert.match(stepsMd, /#2/);
// 3. Consumption CSV & Markdown report (including models + projects + sessions)
const cons = {
selectedRange: { key: '7d', label: '近7天' },
account: {
calls: 12,
inputTokens: 100_000,
cacheReadTokens: 800_000,
outputTokens: 50_000,
totalTokens: 950_000,
cacheHitPct: 88.9,
costUsd: 2.35,
savedCostUsd: 1.45,
},
topWorkspaces: [
{
label: 'usage-monitor',
sessionCount: 3,
calls: 12,
inputTokens: 100_000,
cacheReadTokens: 800_000,
responseTokens: 30_000,
thinkingTokens: 20_000,
totalTokens: 950_000,
cacheHitPct: 88.9,
costUsd: 2.35,
},
],
topConversations: [
{
cascadeId: 'cid-1',
title: 'Refactor',
sourceName: 'CLI',
calls: 12,
inputTokens: 100_000,
cacheReadTokens: 800_000,
responseTokens: 30_000,
thinkingTokens: 20_000,
totalTokens: 950_000,
cacheHitPct: 88.9,
costUsd: 2.35,
},
],
trendSeries: [
{ label: '11/22', fullLabel: '2026-11-22', calls: 12, tokens: 950_000, costUsd: 2.35 },
],
};
const models = [
{
label: '4-neon',
shortName: '4-neon',
calls: 12,
inputTokens: 100_000,
cacheReadTokens: 800_000,
outputTokens: 50_000,
totalTokens: 950_000,
cacheHitPct: 88.9,
avgTokPerSec: 52.1,
costUsd: 2.35,
},
];
const consCsv = buildConsumptionCsv(cons, models);
assert.equal(consCsv.startsWith('\uFEFFsection,name,'), true);
assert.match(consCsv, /project,usage-monitor,12,/);
assert.match(consCsv, /trend,2026-11-22,12,/);
const consMd = buildConsumptionMarkdownReport(cons, models);
assert.match(consMd, /# Usage Report · 近7天/);
assert.match(consMd, /## Models/);
assert.match(consMd, /## Projects/);
assert.match(consMd, /usage-monitor/);
assert.match(consMd, /## Top Sessions/);
});
test('Feature 13: TopSessionHeader exposes project/workspace tags on sessions and filters by workspace name', async (t) => {
const { TopSessionHeader } = await import('../src/components/layout/TopSessionHeader.js');
const now = Date.now();
const harn = backendHarness({
cache: {
'proj-conv-1': {
cascadeId: 'proj-conv-1',
title: 'Fix auth bug',
workspaceUri: 'file:///F%3A/repos/billing-service',
steps: [{ stepIndex: 1, modelKey: 'MODEL_PLACEHOLDER_M18', inputTokens: 1000, outputTokens: 100, createdAtMs: now - 5000 }],
},
'proj-conv-2': {
cascadeId: 'proj-conv-2',
title: 'Fix auth bug',
workspaceUri: 'file:///F%3A/repos/web-dashboard',
steps: [{ stepIndex: 1, modelKey: 'MODEL_PLACEHOLDER_M18', inputTokens: 1000, outputTokens: 100, createdAtMs: now - 10000 }],
},
},
summaries: {
'proj-conv-1': { summary: 'Fix auth bug', stepCount: 1, lastModifiedTime: new Date(now - 5000).toISOString() },
'proj-conv-2': { summary: 'Fix auth bug', stepCount: 1, lastModifiedTime: new Date(now - 10000).toISOString() },
},
});
const payload = await harn.buildTelemetryPayloadInternal('proj-conv-1');
const convById = new Map((payload.conversations || []).map((c) => [c.cascadeId, c]));
assert.equal(convById.get('proj-conv-1')?.workspaceName, 'billing-service');
assert.equal(convById.get('proj-conv-2')?.workspaceName, 'web-dashboard');
const prevDoc = globalThis.document;
const prevWin = globalThis.window;
const prevLocale = i18nStore.getState().locale;
const prevUi = uiStore.getState();
const prevTel = telemetryStore.getState();
const { document } = createMockDom();
globalThis.document = document;
globalThis.window = {
innerWidth: 960,
innerHeight: 720,
addEventListener() {},
removeEventListener() {},
};
let header = null;
t.after(() => {
header?.destroy?.();
setI18nLanguage(prevLocale);
uiStore.setState(prevUi, { sync: true });
telemetryStore.setState(prevTel, { sync: true });
globalThis.document = prevDoc;
globalThis.window = prevWin;
});
setI18nLanguage('zh-CN');
uiStore.setState({ activeView: 'overview', monitorVisible: true }, { sync: true });
telemetryStore.setState(
{
selectedConversationId: '',
telemetry: {
...payload,
conversations: [
...payload.conversations,
...Array.from({ length: 6 }, (_, i) => ({
cascadeId: `pad-${i}`,
title: `Other session ${i}`,
stepCount: 2,
workspaceName: 'misc-repo',
})),
],
},
},
{ sync: true }
);
header = TopSessionHeader();
document.body.appendChild(header.el);
header.refs.convSelect.open();
const optionEls = header.refs.convSelect.el.querySelectorAll('.select-option');
const billingOpt = optionEls.find((el) => (el.textContent || '').includes('billing-service'));
assert.ok(billingOpt, 'Session dropdown option displays workspaceName tag');
const searchInput = header.refs.convSelect.el.querySelector('.select-search-input');
assert.ok(searchInput, 'Search input present for >6 sessions');
searchInput.value = 'web-dashboard';
searchInput.dispatchEvent({ type: 'input', target: searchInput });
const visibleOpts = header.refs.convSelect.el
.querySelectorAll('.select-option')
.filter((el) => !el.hasAttribute('hidden'));
assert.equal(visibleOpts.length, 1);
assert.match(visibleOpts[0].textContent, /web-dashboard/);
});
test('Feature 14: compact vertical ActionMenu replaces export bars, backend exports files safely with reveal whitelist and toast feedback', async (t) => {
const { mkdtempSync, readFileSync, rmSync } = await import('node:fs');
const os = await import('node:os');
const path = await import('node:path');
const {
sanitizeLocalExportFilename,
writeLocalExportFile,
revealLocalExportFile,
} = await import('../backend/file-exporter.mjs');
const { dispatchBridgeApiRequest } = await import('../backend/api-actions.mjs');
const { dismissUiToast } = await import('../src/store/uiStore.js');
// 1. Filename sanitization blocks traversal and enforces allowlist extensions
const safe1 = sanitizeLocalExportFilename('../../evil<script>.exe', 'text/csv');
assert.equal(safe1.ext, '.csv');
assert.equal(safe1.fileName.includes('..'), false);
assert.equal(safe1.fileName.includes('/'), false);
// 2. Backend write avoids overwrite collisions and enforces reveal whitelist
const tempExportDir = mkdtempSync(path.join(os.tmpdir(), 'ag-export-test-'));
t.after(() => {
try {
rmSync(tempExportDir, { recursive: true, force: true });
} catch {}
});
const exp1 = writeLocalExportFile(
{ filename: 'usage-today.csv', content: 'a,b\n1,2\n', mimeType: 'text/csv' },
{ overrideDir: tempExportDir }
);
assert.equal(exp1.ok, true);
assert.equal(exp1.fileName, 'usage-today.csv');
assert.equal(readFileSync(exp1.filePath, 'utf8'), 'a,b\n1,2\n');
const exp2 = writeLocalExportFile(
{ filename: 'usage-today.csv', content: 'a,b\n3,4\n', mimeType: 'text/csv' },
{ overrideDir: tempExportDir }
);
assert.equal(exp2.ok, true);
assert.equal(exp2.fileName, 'usage-today (1).csv');
// Unauthorized arbitrary path must be rejected (403)
const denied = revealLocalExportFile(path.join(tempExportDir, 'not-exported.txt'), {
platform: 'win32',
spawnFn: () => {
throw new Error('Should never spawn for unauthorized path');
},
});
assert.equal(denied.ok, false);
assert.equal(denied.status, 403);
// Authorized exported path spawns explorer /select,"<path>" cleanly
const spawnCalls = [];
const revealed = revealLocalExportFile(exp1.filePath, {
platform: 'win32',
spawnFn: (cmd, args, opts) => {
spawnCalls.push({ cmd, args, opts });
return { on() {}, unref() {} };
},
});
assert.equal(revealed.ok, true);
assert.equal(spawnCalls.length, 1);
assert.equal(spawnCalls[0].cmd, 'explorer.exe');
assert.equal(spawnCalls[0].args[0], `/select,"${exp1.filePath}"`);
// 3. Bridge API dispatch handles /api/export-file and /api/reveal-file
const apiSave = await dispatchBridgeApiRequest(
'/api/export-file',
'POST',
{ filename: 'prefs.json', content: '{"ok":true}\n', mimeType: 'application/json' },
{ exportDir: tempExportDir }
);
assert.equal(apiSave.status, 200);
const apiSaveBody = JSON.parse(apiSave.body);
assert.equal(apiSaveBody.ok, true);
assert.equal(apiSaveBody.fileName, 'prefs.json');
const apiReveal = await dispatchBridgeApiRequest(
'/api/reveal-file',
'POST',
{ filePath: apiSaveBody.filePath },
{
platform: 'win32',
spawnFn: (cmd, args) => {
spawnCalls.push({ cmd, args });
return { on() {}, unref() {} };
},
}
);
assert.equal(apiReveal.status, 200);
assert.equal(spawnCalls.length, 2);
// 4. Frontend ConsumptionView places ActionMenu in overview header (no bottom .cons-export-strip) and shows path toast
const prevDoc = globalThis.document;
const prevWin = globalThis.window;
const prevFetch = globalThis.fetch;
const prevLocale = i18nStore.getState().locale;
const prevUi = { ...uiStore.getState() };
const prevTel = { ...telemetryStore.getState() };
const { document } = createMockDom();
globalThis.document = document;
globalThis.window = {
addEventListener: () => {},
removeEventListener: () => {},
requestAnimationFrame: (cb) => {
cb();
return 1;
},
cancelAnimationFrame: () => {},
};
const apiCalls = [];
globalThis.fetch = async (url, init) => {
const parsedBody = init?.body ? JSON.parse(init.body) : {};
apiCalls.push({ url, method: init?.method || 'GET', body: parsedBody });
if (String(url).includes('/api/export-file')) {
return {
ok: true,
status: 200,
json: async () => ({
ok: true,
filePath: apiSaveBody.filePath,
dirPath: tempExportDir,
fileName: 'usage-7d.csv',
}),
};
}
if (String(url).includes('/api/reveal-file')) {
return {
ok: true,
status: 200,
json: async () => ({ ok: true, filePath: parsedBody.filePath }),
};
}
return { ok: true, status: 200, json: async () => ({}) };
};
let view = null;
t.after(() => {
view?.destroy?.();
dismissUiToast();
setI18nLanguage(prevLocale);
uiStore.setState(prevUi, { sync: true });
telemetryStore.setState(prevTel, { sync: true });
globalThis.document = prevDoc;
globalThis.window = prevWin;
globalThis.fetch = prevFetch;
});
setI18nLanguage('zh-CN');
uiStore.setState({ activeView: 'consumption', monitorVisible: true, toast: null }, { sync: true });
telemetryStore.setState(
{
selectedTimeRange: '7d',
customStartMs: 0,
customEndMs: 0,
telemetry: {
settings: {},
consumption: {
revision: 31,
selectedRange: { key: '7d', label: '近7天' },
account: {
calls: 5,
totalTokens: 500_000,
inputTokens: 100_000,
cacheReadTokens: 380_000,
outputTokens: 20_000,
responseTokens: 12_000,
thinkingTokens: 8_000,
costUsd: 1.2,
savedCostUsd: 0.8,
cacheHitPct: 79.2,
},
topConversations: [],
topWorkspaces: [],
trendSeries: [],
sourcesBreakdown: [],
monthlyYear: 2026,
monthlySeries: [],
},
modelBreakdown: [],
},
},
{ sync: true }
);
view = ConsumptionView();
document.body.appendChild(view.el);
assert.equal(view.el.querySelectorAll('.cons-export-strip').length, 0, 'Bottom export strip removed');
assert.ok(
view.el.querySelector('.cons-overview-head .cons-export-menu .action-menu-trigger'),
'Compact vertical 3-dot trigger lives inside overview header'
);
const menu = view.refs.consExportMenu;
assert.equal(menu.refs.isOpen(), false);
menu.refs.triggerBtn.dispatchEvent({ type: 'click', stopPropagation: () => {} });
assert.equal(menu.refs.isOpen(), true);
const csvItem = menu.refs.getItemBtn('csv');
assert.ok(csvItem);
csvItem.dispatchEvent({ type: 'click', stopPropagation: () => {} });
assert.equal(menu.refs.isOpen(), false);
await new Promise((r) => setTimeout(r, 15));
const toast = uiStore.getState().toast;
assert.ok(toast, 'Export displays global toast');
assert.match(toast.message, /usage-7d\.csv/);
assert.equal(toast.detail, apiSaveBody.filePath);
assert.equal(toast.actionLabel, '打开位置');
assert.equal(typeof toast.onAction, 'function');
// Clicking toast action calls /api/reveal-file with exact saved path
toast.onAction();
await new Promise((r) => setTimeout(r, 15));
const revealCall = apiCalls.find((c) => String(c.url).includes('/api/reveal-file'));
assert.ok(revealCall, 'Open Folder action invokes /api/reveal-file');
assert.equal(revealCall.body.filePath, apiSaveBody.filePath);
// 5. Fallback via POST /api/settings (__exportFileAction) when sticky main.mjs returns 404 for new routes
const { exportTextFileWithFeedback, revealExportedFile } = await import(
'../src/core/fileExportClient.js'
);
const fallbackCalls = [];
globalThis.window.sidecar = {
fetch: async (url, init) => {
const parsedBody = init?.body ? JSON.parse(init.body) : {};
fallbackCalls.push({ url, body: parsedBody });
if (String(url).includes('/api/export-file') || String(url).includes('/api/reveal-file')) {
return { ok: false, status: 404, json: async () => ({ error: 'Not found' }) };
}
if (String(url).includes('/api/settings') && parsedBody.__exportFileAction === 'save') {
const out = await dispatchBridgeApiRequest('/api/settings', 'POST', parsedBody, {
exportDir: tempExportDir,
});
return { ok: out.status === 200, status: out.status, json: async () => JSON.parse(out.body) };
}
if (String(url).includes('/api/settings') && parsedBody.__exportFileAction === 'reveal') {
const out = await dispatchBridgeApiRequest('/api/settings', 'POST', parsedBody, {
platform: 'win32',
spawnFn: (cmd, args) => {
spawnCalls.push({ cmd, args });
return { on() {}, unref() {} };
},
});
return { ok: out.status === 200, status: out.status, json: async () => JSON.parse(out.body) };
}
return { ok: false, status: 500, json: async () => ({ error: 'Unexpected' }) };
},
};
const fallbackRes = await exportTextFileWithFeedback(
'hotreload-settings.json',
'{"theme":"blue"}\n',
'application/json;charset=utf-8'
);
assert.equal(fallbackRes.ok, true);
assert.equal(fallbackRes.mode, 'local');
assert.equal(fallbackRes.fileName, 'hotreload-settings.json');
assert.equal(readFileSync(fallbackRes.filePath, 'utf8'), '{"theme":"blue"}\n');
assert.ok(
fallbackCalls.some((c) => c.url === '/api/settings' && c.body.__exportFileAction === 'save'),
'Falls back to POST /api/settings when sticky main.mjs returns 404'
);
const revealFallbackOk = await revealExportedFile(fallbackRes.filePath);
assert.equal(revealFallbackOk, true);
assert.ok(
fallbackCalls.some((c) => c.url === '/api/settings' && c.body.__exportFileAction === 'reveal')
);
// 6. Inside host embedded Webview, total backend failure never fakes a browser download toast
globalThis.window.sidecar = {
fetch: async () => ({ ok: false, status: 500, json: async () => ({ error: 'Down' }) }),
};
const failedRes = await exportTextFileWithFeedback('broken.csv', 'a,b\n', 'text/csv');
assert.equal(failedRes.ok, false);
assert.equal(failedRes.mode, 'failed');
assert.equal(uiStore.getState().toast?.tone, 'warn');
});