From 681447fc6504bbd29cdd045a24a717f2f3c48d8b Mon Sep 17 00:00:00 2001 From: lipeih Date: Wed, 25 Nov 2026 13:44:42 +0800 Subject: [PATCH] feat(desktop): add Windows session file actions and preview recovery --- apps/desktop/src/i18n.mjs | 63 ++++++++++++++++++ apps/desktop/src/main.mjs | 28 +++++++- apps/desktop/src/runtime.mjs | 4 +- apps/desktop/src/session-files.mjs | 58 +++++++++++++++++ apps/desktop/src/supervisor.mjs | 2 +- apps/desktop/test/session-files.test.mjs | 59 +++++++++++++++++ deeptutor/api/router_index.json | 18 +++++- deeptutor/api/routers/attachments.py | 1 + deeptutor/api/routers/file_preview.py | 41 ++++++++++-- deeptutor/api/routers/workspace.py | 4 +- deeptutor/services/workspace/service.py | 7 +- tests/api/test_file_preview.py | 48 +++++++++++++- .../workspace/test_content_workspace.py | 6 ++ web/components/chat/SessionFileLink.tsx | 64 +++++++++++++++++++ .../chat/home/ContextReferenceTree.tsx | 8 ++- .../chat/home/SessionActivityPanel.tsx | 7 +- .../chat/home/SessionViewerPanel.tsx | 9 ++- .../chat/preview/FilePreviewDrawer.tsx | 13 ++-- .../chat/preview/SessionFilePreview.tsx | 55 ++++++++++++++++ web/components/common/InlineFileCard.tsx | 13 ++-- .../common/RichMarkdownRenderer.tsx | 3 +- .../common/SimpleMarkdownRenderer.tsx | 3 +- .../chat/components/ChatWorkspace.tsx | 15 +++++ .../chat/messages/ChatMessageList.tsx | 20 +++--- web/locales/de/app.json | 1 + web/locales/en/app.json | 1 + web/locales/fr/app.json | 1 + web/locales/hu/app.json | 1 + web/locales/it/app.json | 1 + web/locales/ja/app.json | 1 + web/locales/pl/app.json | 1 + web/locales/pt/app.json | 1 + web/locales/tr/app.json | 1 + web/locales/uk/app.json | 1 + web/locales/vi/app.json | 1 + web/locales/zh/app.json | 1 + web/tests/chat/ChatWorkspace.smoke.spec.tsx | 22 +++++++ web/tests/generated-file-cards.spec.tsx | 18 +++++- web/tests/viewer-launcher.spec.tsx | 21 ++++++ 39 files changed, 572 insertions(+), 50 deletions(-) create mode 100644 apps/desktop/src/session-files.mjs create mode 100644 apps/desktop/test/session-files.test.mjs create mode 100644 web/components/chat/SessionFileLink.tsx create mode 100644 web/components/chat/preview/SessionFilePreview.tsx diff --git a/apps/desktop/src/i18n.mjs b/apps/desktop/src/i18n.mjs index c9e256de9..c8de8e110 100644 --- a/apps/desktop/src/i18n.mjs +++ b/apps/desktop/src/i18n.mjs @@ -2,6 +2,13 @@ // language chosen in DeepTutor's own Settings and starts in English. const en = { + fileBrowser: 'Open in default browser', + fileDefaultApp: 'Open with default app', + fileExplorer: 'Show in File Explorer', + fileCopyPath: 'Copy file path', + fileUnavailable: 'File unavailable', + fileActionFailed: 'Couldn’t complete the file action', + backToChat: 'Back to conversation', tagline: 'Your personal learning space', errorTitle: "DeepTutor couldn't start", errorBody: 'Something went wrong while starting the local services. Try again, or check the logs for details.', @@ -54,6 +61,13 @@ const en = { }; const zh = { + fileBrowser: '在默认浏览器中打开', + fileDefaultApp: '用系统默认应用打开', + fileExplorer: '在资源管理器中显示并选中文件', + fileCopyPath: '复制文件路径', + fileUnavailable: '文件不可用', + fileActionFailed: '文件操作未能完成', + backToChat: '返回对话', tagline: '你的个人学习空间', errorTitle: 'DeepTutor 未能启动', errorBody: '启动本地服务时出现问题。你可以重试,或查看日志了解详情。', @@ -106,6 +120,13 @@ const zh = { }; const de = { + fileBrowser: 'Im Standardbrowser öffnen', + fileDefaultApp: 'Mit Standard-App öffnen', + fileExplorer: 'Im Explorer anzeigen', + fileCopyPath: 'Dateipfad kopieren', + fileUnavailable: 'Datei nicht verfügbar', + fileActionFailed: 'Dateiaktion fehlgeschlagen', + backToChat: 'Zurück zur Unterhaltung', tagline: 'Dein persönlicher Lernraum', errorTitle: 'DeepTutor konnte nicht starten', errorBody: 'Beim Starten der lokalen Dienste ist ein Fehler aufgetreten. Versuche es erneut oder sieh in den Protokollen nach.', @@ -158,6 +179,13 @@ const de = { }; const fr = { + fileBrowser: 'Ouvrir dans le navigateur par défaut', + fileDefaultApp: 'Ouvrir avec l’application par défaut', + fileExplorer: 'Afficher dans l’Explorateur de fichiers', + fileCopyPath: 'Copier le chemin du fichier', + fileUnavailable: 'Fichier indisponible', + fileActionFailed: 'L’opération sur le fichier a échoué', + backToChat: 'Revenir à la conversation', tagline: "Votre espace d'apprentissage personnel", errorTitle: "DeepTutor n'a pas pu démarrer", errorBody: 'Un problème est survenu au démarrage des services locaux. Réessayez ou consultez les journaux.', @@ -210,6 +238,13 @@ const fr = { }; const pl = { + fileBrowser: 'Otwórz w domyślnej przeglądarce', + fileDefaultApp: 'Otwórz w domyślnej aplikacji', + fileExplorer: 'Pokaż w Eksploratorze plików', + fileCopyPath: 'Kopiuj ścieżkę pliku', + fileUnavailable: 'Plik niedostępny', + fileActionFailed: 'Nie udało się wykonać operacji na pliku', + backToChat: 'Wróć do rozmowy', tagline: 'Twoja osobista przestrzeń nauki', errorTitle: 'Nie udało się uruchomić DeepTutor', errorBody: 'Podczas uruchamiania usług lokalnych wystąpił problem. Spróbuj ponownie lub sprawdź dzienniki.', @@ -262,6 +297,13 @@ const pl = { }; const uk = { + fileBrowser: 'Відкрити в типовому браузері', + fileDefaultApp: 'Відкрити в типовій програмі', + fileExplorer: 'Показати у Провіднику', + fileCopyPath: 'Копіювати шлях до файлу', + fileUnavailable: 'Файл недоступний', + fileActionFailed: 'Не вдалося виконати дію з файлом', + backToChat: 'Повернутися до розмови', tagline: 'Ваш особистий простір навчання', errorTitle: 'Не вдалося запустити DeepTutor', errorBody: 'Під час запуску локальних служб сталася помилка. Спробуйте ще раз або перегляньте журнали.', @@ -314,6 +356,13 @@ const uk = { }; const vi = { + fileBrowser: 'Mở trong trình duyệt mặc định', + fileDefaultApp: 'Mở bằng ứng dụng mặc định', + fileExplorer: 'Hiển thị trong File Explorer', + fileCopyPath: 'Sao chép đường dẫn tệp', + fileUnavailable: 'Tệp không khả dụng', + fileActionFailed: 'Không thể thực hiện thao tác với tệp', + backToChat: 'Quay lại cuộc trò chuyện', tagline: 'Không gian học tập cá nhân của bạn', errorTitle: 'Không thể khởi động DeepTutor', errorBody: 'Đã xảy ra sự cố khi khởi động các dịch vụ cục bộ. Hãy thử lại hoặc xem nhật ký.', @@ -366,6 +415,13 @@ const vi = { }; const pt = { + fileBrowser: 'Abrir no navegador padrão', + fileDefaultApp: 'Abrir com o aplicativo padrão', + fileExplorer: 'Mostrar no Explorador de Arquivos', + fileCopyPath: 'Copiar caminho do arquivo', + fileUnavailable: 'Arquivo indisponível', + fileActionFailed: 'Não foi possível concluir a ação no arquivo', + backToChat: 'Voltar à conversa', "tagline": "Seu espaço pessoal de aprendizado", "errorTitle": "Não foi possível iniciar o DeepTutor", "errorBody": "Ocorreu um erro ao iniciar os serviços locais. Tente novamente ou consulte os logs para ver os detalhes.", @@ -432,6 +488,13 @@ const pt = { }; const tr = { + fileBrowser: 'Varsayılan tarayıcıda aç', + fileDefaultApp: 'Varsayılan uygulamayla aç', + fileExplorer: 'Dosya Gezgini’nde göster', + fileCopyPath: 'Dosya yolunu kopyala', + fileUnavailable: 'Dosya kullanılamıyor', + fileActionFailed: 'Dosya işlemi tamamlanamadı', + backToChat: 'Sohbete dön', "tagline": "Kişisel öğrenme alanınız", "errorTitle": "DeepTutor başlatılamadı", "errorBody": "Yerel hizmetler başlatılırken bir sorun oluştu. Yeniden deneyin veya ayrıntılar için günlükleri kontrol edin.", diff --git a/apps/desktop/src/main.mjs b/apps/desktop/src/main.mjs index 9b6b966f2..b229ceb9b 100644 --- a/apps/desktop/src/main.mjs +++ b/apps/desktop/src/main.mjs @@ -1,4 +1,5 @@ -import { app, BrowserWindow, WebContentsView, Menu, ipcMain, shell, dialog, session, nativeTheme } from 'electron'; +import { app, BrowserWindow, WebContentsView, Menu, ipcMain, shell, clipboard, dialog, session, nativeTheme } from 'electron'; +import { randomUUID } from 'node:crypto'; import { fork } from 'node:child_process'; import { watch } from 'node:fs'; import { mkdir, readFile, writeFile, rename, cp, appendFile } from 'node:fs/promises'; @@ -9,10 +10,12 @@ import { externalURL } from './config.mjs'; import { resolveLanguage, translate } from './i18n.mjs'; import { WINDOWS, agentMarker, edition, targetId } from './platform.mjs'; import { killTree } from './processes.mjs'; +import { conversationPage, resolveDesktopFile, sessionFileMenu, sessionFileURL } from './session-files.mjs'; app.setName('Open DeepTutor'); if (WINDOWS) app.setAppUserModelId('org.deeptutor.open-desktop'); const EDITION = edition(); +const desktopFileToken = WINDOWS ? randomUUID() : undefined; const sourceDirectory = path.dirname(fileURLToPath(import.meta.url)); const shellURL = pathToFileURL(path.join(sourceDirectory, 'index.html')).href; // Runtimes are large and machine-specific, so Windows keeps them out of the roaming profile. @@ -132,6 +135,27 @@ async function openContent(url) { partition: 'persist:deeptutor', } }); const content = view.webContents; + if (desktopFileToken && state.owned) { + content.on('context-menu', async (_event, params) => { + const page = content.getURL(); + if (params.frame !== content.mainFrame || !conversationPage(page, origin)) return; + const source = sessionFileURL(params.linkURL || params.srcURL, origin); + if (!source) return; + const stillHere = () => !content.isDestroyed() && content.getURL() === page; + const resolvePath = () => stillHere() + ? resolveDesktopFile(content.session, state.backendURL, desktopFileToken, source) : null; + const showError = (key) => { + if (stillHere()) void dialog.showMessageBox(window, { message: t(key), buttons: [t('backToChat')] }); + }; + try { + const path = await resolvePath(); + if (!path || !stillHere()) return; + Menu.buildFromTemplate(sessionFileMenu({ + source, path, resolvePath, shell, clipboard, t, onError: showError, + })).popup({ window }); + } catch { showError('fileUnavailable'); } + }); + } content.setWindowOpenHandler(({ url: target }) => { if (target.startsWith(origin + '/') || target.startsWith(`blob:${origin}/`)) { return { action: 'allow', overrideBrowserWindowOptions: { @@ -197,7 +221,7 @@ async function launchRuntime(installed) { status({ phase: 'error', step: null, message: t('workerExited', { code }) }); if (!ready) reject(new Error(state.message)); }); - child.send({ type: 'start', config, logPath, cachePath: path.join(userRoot, 'cache', installed.manifest.runtimeId) }); + child.send({ type: 'start', config, logPath, desktopFileToken, cachePath: path.join(userRoot, 'cache', installed.manifest.runtimeId) }); }); } diff --git a/apps/desktop/src/runtime.mjs b/apps/desktop/src/runtime.mjs index 91374e801..2401a423a 100644 --- a/apps/desktop/src/runtime.mjs +++ b/apps/desktop/src/runtime.mjs @@ -66,7 +66,7 @@ export class SourceRuntime extends EventEmitter { update(state) { this.state = { ...this.state, ...state }; this.emit('status', this.state); } - async start(input, cachePath) { + async start(input, cachePath, desktopFileToken) { const config = validateConfig(input); this.config = config; this.update({ phase: 'starting', step: 'checking', mode: config.mode }); @@ -124,7 +124,7 @@ export class SourceRuntime extends EventEmitter { this.update({ step: 'startingCore' }); this.backend = this.group.spawn(config.pythonPath, ['-m', 'deeptutor_cli.main', 'serve', '--host', '127.0.0.1', '--port', String(backendPort)], - { cwd: config.runtimeHome, env }); + { cwd: config.runtimeHome, env: desktopFileToken ? { ...env, DEEPTUTOR_DESKTOP_FILE_TOKEN: desktopFileToken } : env }); await waitReady(`${backendURL}/health/ready`, { signal: this.controller.signal, alive: () => this.group.alive(this.backend), }); diff --git a/apps/desktop/src/session-files.mjs b/apps/desktop/src/session-files.mjs new file mode 100644 index 000000000..027124d51 --- /dev/null +++ b/apps/desktop/src/session-files.mjs @@ -0,0 +1,58 @@ +import { win32 } from 'node:path'; +import { localURL } from './config.mjs'; + +const SESSION_FILE = /^\/files\/(?:attachments\/[^/]+\/[^/]+\/[^/]+|workspace-items\/[^/]+\/[^/]+|outputs\/.+)$/; +const DOCUMENT_TYPES = new Set( + '.md .markdown .txt .csv .tsv .pdf .docx .xlsx .pptx .odt .ods .odp .rtf .json .png .jpg .jpeg .gif .webp .bmp .mp3 .wav .m4a .mp4 .webm .ogg'.split(' '), +); + +/** A native menu belongs to the foreground conversation, never to an embedded document. */ +export function conversationPage(address, origin) { + if (!URL.canParse(address)) return false; + const url = new URL(address); + return url.origin === origin && /^\/(?:chat(?:\/[^/]+)?|partners\/(?:groups\/)?[^/]+)?\/?$/.test(url.pathname); +} + +export function sessionFileURL(address, origin) { + if (!URL.canParse(address)) return null; + const url = new URL(address); + if (url.origin !== origin || url.username || url.password || !SESSION_FILE.test(url.pathname)) return null; + url.hash = ''; + return url; +} + +export async function resolveDesktopFile(session, backendURL, token, source) { + const endpoint = new URL('/api/file-preview/desktop-file', localURL(backendURL)); + endpoint.searchParams.set('source', source.pathname + source.search); + const response = await session.fetch(endpoint.href, { + credentials: 'include', redirect: 'error', cache: 'no-store', + headers: { 'X-DeepTutor-Desktop-Token': token }, + }); + if (!response.ok) throw new Error('File unavailable'); + const { path } = await response.json(); + // Only local drive files can be handed to Windows. The core authorizes the file and resolves its original path. + if (typeof path !== 'string' || !/^[a-z]:\\/i.test(path) || path.slice(2).includes(':')) throw new Error('File unavailable'); + return path; +} + +export function sessionFileMenu({ source, path, resolvePath, shell, clipboard, t, onError }) { + const action = (key, run, enabled = true) => ({ + label: t(key), enabled, + click: async () => { + // The original may have moved or the conversation may have changed while the menu was open. + try { + if (await resolvePath() !== path) return onError('fileUnavailable'); + } catch { return onError('fileUnavailable'); } + try { await run(); } catch { onError('fileActionFailed'); } + }, + }); + return [ + action('fileBrowser', () => shell.openExternal(source.href)), + action('fileDefaultApp', async () => { + const error = await shell.openPath(path); + if (error) throw new Error(error); + }, DOCUMENT_TYPES.has(win32.extname(path).toLowerCase())), + action('fileExplorer', () => shell.showItemInFolder(path)), + action('fileCopyPath', () => clipboard.writeText(path)), + ]; +} diff --git a/apps/desktop/src/supervisor.mjs b/apps/desktop/src/supervisor.mjs index 1774ef6b5..3bb97e302 100644 --- a/apps/desktop/src/supervisor.mjs +++ b/apps/desktop/src/supervisor.mjs @@ -29,7 +29,7 @@ process.on('message', async message => { log.write(`\n--- Desktop runtime ${new Date().toISOString()} ---\n`); runtime = new SourceRuntime({ log: chunk => log.write(chunk) }); runtime.on('status', send); - await runtime.start(message.config, message.cachePath); + await runtime.start(message.config, message.cachePath, message.desktopFileToken); } catch (error) { send({ phase: 'error', message: error.message }); await runtime?.stop(); diff --git a/apps/desktop/test/session-files.test.mjs b/apps/desktop/test/session-files.test.mjs new file mode 100644 index 000000000..bbf3491ae --- /dev/null +++ b/apps/desktop/test/session-files.test.mjs @@ -0,0 +1,59 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { conversationPage, resolveDesktopFile, sessionFileMenu, sessionFileURL } from '../src/session-files.mjs'; + +const origin = 'http://127.0.0.1:18802'; +const source = new URL('/files/attachments/session/id/notes.md?dt_workspace=course', origin); +const path = String.raw`C:\My notes\课堂.md`; + +test('only first-party conversations and published file links have a desktop menu', () => { + assert.ok(conversationPage(origin + '/chat/session?view=1', origin)); + assert.ok(conversationPage(origin + '/partners/groups/lesson', origin)); + assert.equal(conversationPage(source.href, origin), false); + assert.equal(conversationPage('https://example.org/chat/session', origin), false); + assert.equal(sessionFileURL(source.href, origin).href, source.href); + for (const url of ['https://example.org/files/outputs/report.md', 'file:///C:/notes.md', origin + '/settings', origin + '/files/workspace-items/ws/item/file-storage']) { + assert.equal(sessionFileURL(url, origin), null); + } +}); + +test('look up the original file using the core session and the scope on the link', async () => { + const session = { fetch: async (url, options) => { + const endpoint = new URL(url); + assert.equal(endpoint.origin, 'http://127.0.0.1:18801'); + assert.equal(endpoint.pathname, '/api/file-preview/desktop-file'); + assert.equal(endpoint.searchParams.get('source'), source.pathname + source.search); + assert.equal(options.credentials, 'include'); + assert.equal(options.redirect, 'error'); + assert.equal(options.headers['X-DeepTutor-Desktop-Token'], 'desktop'); + return Response.json({ path }); + } }; + assert.equal(await resolveDesktopFile(session, 'http://127.0.0.1:18801', 'desktop', source), path); + await assert.rejects(resolveDesktopFile({ fetch: () => new Response(null, { status: 404 }) }, origin, 'desktop', source)); +}); + +test('the four native actions use the published browser URL or the original Windows path', async () => { + const calls = []; + const options = { + source, path, resolvePath: () => path, t: key => key, onError: key => calls.push(key), + shell: { + openExternal: url => calls.push(['browser', url]), + openPath: file => { calls.push(['open', file]); return ''; }, + showItemInFolder: file => calls.push(['reveal', file]), + }, + clipboard: { writeText: text => calls.push(['copy', text]) }, + }; + for (const item of sessionFileMenu(options)) { + assert.equal(item.enabled, true); + await item.click(); + } + assert.deepEqual(calls, [['browser', source.href], ['open', path], ['reveal', path], ['copy', path]]); + const unsupported = sessionFileMenu({ ...options, path: 'example.exe' }); + assert.equal(unsupported.find(item => item.label === 'fileDefaultApp').enabled, false); + options.shell.openPath = () => 'No associated app'; + await sessionFileMenu(options).find(item => item.label === 'fileDefaultApp').click(); + assert.equal(calls.at(-1), 'fileActionFailed'); + options.resolvePath = () => { throw new Error('File moved'); }; + await sessionFileMenu(options).find(item => item.label === 'fileCopyPath').click(); + assert.equal(calls.at(-1), 'fileUnavailable'); +}); diff --git a/deeptutor/api/router_index.json b/deeptutor/api/router_index.json index f202874b6..136b06260 100644 --- a/deeptutor/api/router_index.json +++ b/deeptutor/api/router_index.json @@ -1,5 +1,5 @@ { - "fingerprint": "c3b938e1a6af4378a012f1f6faa1887d8c8d2b37042f8f01885deabebeef625a", + "fingerprint": "aeeedadfac304b036917ae14ddf51bd33e5b5ebaa5e881c5bd5c2e5a09e49c68", "routers": { "deeptutor.api.routers.auth:router": [ { @@ -1115,6 +1115,14 @@ } ], "deeptutor.api.routers.file_preview:router": [ + { + "path": "/desktop-file", + "name": "desktop_file", + "kind": "http", + "methods": [ + "GET" + ] + }, { "path": "/pdf", "name": "preview_office_source", @@ -5837,6 +5845,14 @@ } ], "deeptutor.api.routers.attachments:router": [ + { + "path": "/{session_id}/{attachment_id}/{filename:path}", + "name": "get_attachment", + "kind": "http", + "methods": [ + "HEAD" + ] + }, { "path": "/{session_id}/{attachment_id}/{filename:path}", "name": "get_attachment", diff --git a/deeptutor/api/routers/attachments.py b/deeptutor/api/routers/attachments.py index d238e0b23..fe6308932 100644 --- a/deeptutor/api/routers/attachments.py +++ b/deeptutor/api/routers/attachments.py @@ -38,6 +38,7 @@ _content_disposition = content_disposition @router.get("/{session_id}/{attachment_id}/{filename:path}") +@router.head("/{session_id}/{attachment_id}/{filename:path}", include_in_schema=False) async def get_attachment( session_id: str, attachment_id: str, diff --git a/deeptutor/api/routers/file_preview.py b/deeptutor/api/routers/file_preview.py index 236bccf8f..ff4918b7b 100644 --- a/deeptutor/api/routers/file_preview.py +++ b/deeptutor/api/routers/file_preview.py @@ -4,12 +4,14 @@ from __future__ import annotations import asyncio from contextlib import nullcontext +import os from pathlib import Path import re +from secrets import compare_digest from urllib.parse import parse_qs, unquote, urlsplit from fastapi import APIRouter, File, HTTPException, Request, UploadFile -from fastapi.responses import Response +from fastapi.responses import JSONResponse, Response from deeptutor.api.utils.http_headers import content_disposition from deeptutor.multi_user.paths import get_current_path_service @@ -28,7 +30,9 @@ from deeptutor.services.workspace.models import WorkspaceError router = APIRouter() -def _source_path(source: str, request: Request) -> tuple[Path, str, Path]: +def _source_path( + source: str, request: Request, *, original: bool = False +) -> tuple[Path, str, Path]: """Resolve only local URLs using their existing authorization boundaries.""" if len(source) > 8192: raise HTTPException(status_code=400, detail="Invalid preview source") @@ -70,16 +74,20 @@ def _source_path(source: str, request: Request) -> tuple[Path, str, Path]: else: context = nullcontext() canonical_path = unquote(parsed.path) + if original and not canonical_path.startswith("/files/"): + raise HTTPException(status_code=400, detail="Expected a session file URL") _assert_surface("reading" if canonical_path.startswith("/api/knowledge-bases/") else "chat") try: with context: - target, filename = _resolve_authorized_file(canonical_path, query) + target, filename = _resolve_authorized_file(canonical_path, query, original=original) return target, filename, _cache_dir() except WorkspaceError as exc: raise HTTPException(status_code=404, detail="Preview source not found") from exc -def _resolve_authorized_file(path: str, query: dict[str, list[str]]) -> tuple[Path, str]: +def _resolve_authorized_file( + path: str, query: dict[str, list[str]], *, original: bool = False +) -> tuple[Path, str]: if match := re.fullmatch(r"/files/attachments/([^/]+)/([^/]+)/([^/]+)", path): from deeptutor.services.storage import LocalDiskAttachmentStore, get_attachment_store @@ -114,9 +122,11 @@ def _resolve_authorized_file(path: str, query: dict[str, list[str]]) -> tuple[Pa from deeptutor.services.workspace import get_content_workspace_service try: - target, item = get_content_workspace_service().resolve_published_item(*match.groups()) + target, item = get_content_workspace_service().resolve_published_item( + *match.groups(), original=original + ) except WorkspaceError: - resolved = _resolve_partner_item(*match.groups()) + resolved = _resolve_partner_item(*match.groups(), original=original) if resolved is None: raise HTTPException(status_code=404, detail="Preview source not found") target, item = resolved @@ -183,6 +193,25 @@ async def _pdf_response(data: bytes, filename: str, cache_dir: Path) -> Response ) +@router.get("/desktop-file", include_in_schema=False) +def desktop_file(source: str, request: Request) -> Response: + """Give the owning desktop shell the original file behind an authorized session URL.""" + from deeptutor.multi_user.session_handoff import is_loopback_host + + token = os.environ.get("DEEPTUTOR_DESKTOP_FILE_TOKEN") + supplied = request.headers.get("x-deeptutor-desktop-token", "") + if not ( + token + and request.client + and is_loopback_host(request.client.host) + and supplied.isascii() + and compare_digest(token, supplied) + ): + raise HTTPException(status_code=404, detail="Not found") + path, _, _ = _source_path(source, request, original=True) + return JSONResponse({"path": str(path)}, headers={"Cache-Control": "no-store"}) + + @router.get("/pdf") async def preview_office_source(source: str, request: Request) -> Response: """Render a file URL that this same authenticated user could open.""" diff --git a/deeptutor/api/routers/workspace.py b/deeptutor/api/routers/workspace.py index cc79cbc45..675955aa1 100644 --- a/deeptutor/api/routers/workspace.py +++ b/deeptutor/api/routers/workspace.py @@ -315,7 +315,7 @@ async def update_workspace(payload: WorkspacePathPayload) -> dict: def _resolve_partner_item( - workspace_id: str, workspace_item_id: str + workspace_id: str, workspace_item_id: str, *, original: bool = False ) -> tuple[Path, WorkspaceItem] | None: """Resolve a presentation one of the caller's partners published. @@ -345,7 +345,7 @@ def _resolve_partner_item( with user_context(partner_user(partner_id)): try: return get_content_workspace_service().resolve_published_item( - workspace_id, workspace_item_id + workspace_id, workspace_item_id, original=original ) except WorkspaceError: continue diff --git a/deeptutor/services/workspace/service.py b/deeptutor/services/workspace/service.py index 76cd0e934..33bfae5ef 100644 --- a/deeptutor/services/workspace/service.py +++ b/deeptutor/services/workspace/service.py @@ -788,7 +788,7 @@ class ContentWorkspaceService(WorkspaceCatalogMixin): return request def resolve_published_item( - self, workspace_id: str, workspace_item_id: str + self, workspace_id: str, workspace_item_id: str, *, original: bool = False ) -> tuple[Path, WorkspaceItem]: if not re.fullmatch(r"wsi_[0-9a-f]{32}", workspace_item_id): raise WorkspaceError("Invalid workspace item id.") @@ -818,6 +818,11 @@ class ContentWorkspaceService(WorkspaceCatalogMixin): raise WorkspaceError("The workspace item path is invalid.") from exc if not blob.is_file(): raise WorkspaceError("The presented workspace item is unavailable.") + if original: + source = self.resolve(binding, item.relative_path) + if not source.is_file(): + raise WorkspaceError("The original workspace file is unavailable.") + return source, item return blob, item diff --git a/tests/api/test_file_preview.py b/tests/api/test_file_preview.py index 3bc6f8093..0e2c33cfc 100644 --- a/tests/api/test_file_preview.py +++ b/tests/api/test_file_preview.py @@ -97,6 +97,47 @@ def test_preview_route_requires_authentication(monkeypatch) -> None: "/api/file-preview/pdf", params={"source": "/files/outputs/report.docx"} ) assert response.status_code == 401 + assert ( + TestClient(app) + .get("/api/file-preview/desktop-file", params={"source": "/files/outputs/notes.md"}) + .status_code + == 401 + ) + + +def test_desktop_lookup_is_private_and_resolves_only_published_files(monkeypatch, tmp_path): + from deeptutor.services.storage import LocalDiskAttachmentStore + + store = LocalDiskAttachmentStore(tmp_path / "attachments") + url = asyncio.run( + store.put(session_id="lesson", attachment_id="a1", filename="课堂.md", data=b"notes") + ) + monkeypatch.setattr("deeptutor.services.storage.get_attachment_store", lambda: store) + monkeypatch.setattr(file_preview, "_cache_dir", lambda: tmp_path) + app = FastAPI() + app.include_router(file_preview.router) + client = TestClient(app, client=("127.0.0.1", 1234)) + params = {"source": url} + headers = {"X-DeepTutor-Desktop-Token": "shell-secret"} + monkeypatch.delenv("DEEPTUTOR_DESKTOP_FILE_TOKEN", raising=False) + assert client.get("/desktop-file", params=params, headers=headers).status_code == 404 + monkeypatch.setenv("DEEPTUTOR_DESKTOP_FILE_TOKEN", "shell-secret") + assert client.get("/desktop-file", params=params).status_code == 404 + assert TestClient(app).get("/desktop-file", params=params, headers=headers).status_code == 404 + response = client.get("/desktop-file", params=params, headers=headers) + assert response.status_code == 200 + assert response.headers["cache-control"] == "no-store" + assert Path(response.json()["path"]).read_bytes() == b"notes" + assert ( + client.get( + "/desktop-file", + params={"source": "/api/knowledge-bases/course/files/notes.md"}, + headers=headers, + ).status_code + == 400 + ) + Path(response.json()["path"]).rename(tmp_path / "moved.md") + assert client.get("/desktop-file", params=params, headers=headers).status_code == 404 def test_source_url_must_be_local_and_workspace_scope_must_match( @@ -106,7 +147,8 @@ def test_source_url_must_be_local_and_workspace_scope_must_match( source.write_bytes(b"office") seen: list[str] = [] - def resolve(path: str, _query: dict) -> tuple[Path, str]: + def resolve(path: str, _query: dict, *, original: bool) -> tuple[Path, str]: + assert not original seen.append(path) return source, source.name @@ -155,7 +197,7 @@ def test_get_and_post_return_pdf(monkeypatch, tmp_path: Path) -> None: source = tmp_path / "report.docx" source.write_bytes(b"office") monkeypatch.setattr( - file_preview, "_resolve_authorized_file", lambda _path, _query: (source, source.name) + file_preview, "_resolve_authorized_file", lambda _path, _query, **_kw: (source, source.name) ) monkeypatch.setattr(file_preview, "_cache_dir", lambda: tmp_path / "cache") @@ -198,7 +240,7 @@ def test_learner_preview_surface_matches_source(monkeypatch, tmp_path: Path) -> source = tmp_path / "report.docx" source.write_bytes(b"office") monkeypatch.setattr( - file_preview, "_resolve_authorized_file", lambda _path, _query: (source, source.name) + file_preview, "_resolve_authorized_file", lambda _path, _query, **_kw: (source, source.name) ) monkeypatch.setattr(file_preview, "_cache_dir", lambda: tmp_path / "cache") diff --git a/tests/services/workspace/test_content_workspace.py b/tests/services/workspace/test_content_workspace.py index 85f1d223f..760fb31fe 100644 --- a/tests/services/workspace/test_content_workspace.py +++ b/tests/services/workspace/test_content_workspace.py @@ -130,6 +130,12 @@ def test_presentation_is_a_fixed_content_addressed_version(workspace_service) -> assert loaded.url.startswith("/files/workspace-items/") assert blob.is_relative_to(paths.get_runtime_state_dir()) assert not (binding.root / "outputs" / ".deeptutor").exists() + ids = first.workspace_id, first.workspace_item_id + assert service.resolve_published_item(*ids, original=True) == (source, first) + source.rename(binding.root / "moved.md") + with pytest.raises(WorkspaceError, match="original workspace file"): + service.resolve_published_item(*ids, original=True) + assert service.resolve_published_item(*ids) == (blob, loaded) def test_private_presentation_store_rejects_symlink_redirection( diff --git a/web/components/chat/SessionFileLink.tsx b/web/components/chat/SessionFileLink.tsx new file mode 100644 index 000000000..d35c982f9 --- /dev/null +++ b/web/components/chat/SessionFileLink.tsx @@ -0,0 +1,64 @@ +"use client"; + +import { useSyncExternalStore, type ReactNode } from "react"; +import { apiUrl } from "@/lib/api"; +import { clientEdition } from "@/lib/version"; + +const subscribe = () => () => {}; +const isWindowsDesktop = () => clientEdition().short === "Windows"; + +// The desktop edition comes from the browser's user agent after hydration. +export function useWindowsDesktop(): boolean { + return useSyncExternalStore(subscribe, isWindowsDesktop, () => false); +} + +export function isRelativeFileReference(href: string): boolean { + return !/^(?:[a-z][a-z\d+.-]*:|\/|#|\?)/i.test(href) + && /\.[a-z\d]{1,8}(?:[?#].*)?$/i.test(href); +} + +/** Only published session files have a URL the desktop shell can resolve on disk. */ +export function sessionFileUrl(url?: string | null): string | null { + if (!url || !(url.startsWith("/files/") || /^https?:\/\//i.test(url))) return null; + const origin = typeof window === "undefined" ? "http://workspace.local" : window.location.origin; + if (!URL.canParse(url, origin)) return null; + const parsed = new URL(url, origin); + if ( + parsed.origin !== origin || parsed.username || parsed.password || + !/^\/files\/(?:attachments\/[^/]+\/[^/]+\/[^/]+|workspace-items\/[^/]+\/[^/]+|outputs\/.+)$/.test(parsed.pathname) + ) { + return null; + } + return apiUrl(parsed.pathname + parsed.search); +} + +export function SessionFileLink({ + url, onClick, children, ...props +}: { + url?: string; + onClick?: () => void; + children: ReactNode; + className: string; + "aria-label"?: string; +}) { + const href = useWindowsDesktop() ? sessionFileUrl(url) : null; + if (href && onClick) { + return ( + { + event.preventDefault(); + onClick(); + }} + > + {children} + + ); + } + return ( + + ); +} diff --git a/web/components/chat/home/ContextReferenceTree.tsx b/web/components/chat/home/ContextReferenceTree.tsx index 26aaffc75..62c40c879 100644 --- a/web/components/chat/home/ContextReferenceTree.tsx +++ b/web/components/chat/home/ContextReferenceTree.tsx @@ -3,6 +3,7 @@ import { memo, useState } from "react"; import { ChevronDown, X, type LucideIcon } from "lucide-react"; import { useTranslation } from "react-i18next"; +import { SessionFileLink } from "@/components/chat/SessionFileLink"; /** * One row in the reference tree: an attachment, a Space reference, a @@ -20,6 +21,7 @@ export interface ContextTreeItem { label: string; /** 16px thumbnail for image attachments — replaces the icon. */ thumbnailUrl?: string; + fileUrl?: string; /** Optional click action (e.g. open attachment preview). */ onClick?: () => void; /** Optional remove action (composer only). */ @@ -160,13 +162,13 @@ export default memo(function ContextReferenceTree({ className={`group/ref flex max-w-full items-center gap-1.5 text-[12px] leading-[1.6] ${rowDirClass}`} > {item.onClick ? ( - + ) : ( Inner )} diff --git a/web/components/chat/home/SessionActivityPanel.tsx b/web/components/chat/home/SessionActivityPanel.tsx index eb8b00871..55740ad1b 100644 --- a/web/components/chat/home/SessionActivityPanel.tsx +++ b/web/components/chat/home/SessionActivityPanel.tsx @@ -1,6 +1,7 @@ "use client"; import { BOOKS_HOME } from "@/lib/learning-routes"; +import { SessionFileLink } from "@/components/chat/SessionFileLink"; /** * The Activity home lists the conversation's tools, references, and files. @@ -538,8 +539,8 @@ function AttachmentRow({ return (
  • - +
  • ); diff --git a/web/components/chat/home/SessionViewerPanel.tsx b/web/components/chat/home/SessionViewerPanel.tsx index a880d33b9..702b6d03c 100644 --- a/web/components/chat/home/SessionViewerPanel.tsx +++ b/web/components/chat/home/SessionViewerPanel.tsx @@ -58,6 +58,7 @@ import { type LucideIcon, } from "lucide-react"; import { useTranslation } from "react-i18next"; +import { SessionFilePreview } from "@/components/chat/preview/SessionFilePreview"; import { previewKindFor, resolveSourceUrl, @@ -1406,7 +1407,7 @@ function SessionViewerPanelInner( />
    {activeTab?.kind === "file" ? ( - + ) : activeTab?.kind === "web" ? ( ) : activeTab?.kind === "markdown-note" ? ( @@ -1744,12 +1745,14 @@ function FileTabActions({ source }: { source: FilePreviewSource }) { ); } -function FileTabBody({ source }: { source: FilePreviewSource }) { +function FileTabBody({ source, onBack }: { source: FilePreviewSource; onBack: () => void }) { const previewUrl = useMemo(() => resolveSourceUrl(source, apiUrl), [source]); const kind = previewKindFor(source); return (
    - + + +
    ); } diff --git a/web/components/chat/preview/FilePreviewDrawer.tsx b/web/components/chat/preview/FilePreviewDrawer.tsx index 30bca2ea6..a31313a4a 100644 --- a/web/components/chat/preview/FilePreviewDrawer.tsx +++ b/web/components/chat/preview/FilePreviewDrawer.tsx @@ -7,6 +7,7 @@ import dynamic from "next/dynamic"; import { useRouter } from "next/navigation"; import { BookOpenText, Check, Copy, Download, Loader2, X } from "lucide-react"; import { useTranslation } from "react-i18next"; +import { SessionFilePreview } from "./SessionFilePreview"; import { docIconFor, formatBytes } from "@/lib/doc-attachments"; import { apiUrl } from "@/lib/api"; import { apiFetch } from "@/lib/api"; @@ -321,11 +322,13 @@ export default function FilePreviewDrawer({ steal main-thread frames from the chat squeeze. */}
    {bodyMounted && ( - + + + )}
    diff --git a/web/components/chat/preview/SessionFilePreview.tsx b/web/components/chat/preview/SessionFilePreview.tsx new file mode 100644 index 000000000..bd91db9c2 --- /dev/null +++ b/web/components/chat/preview/SessionFilePreview.tsx @@ -0,0 +1,55 @@ +"use client"; + +import { useEffect, useState, type ReactNode } from "react"; +import { ArrowLeft, FileQuestion } from "lucide-react"; +import { useTranslation } from "react-i18next"; +import { apiFetch } from "@/lib/api"; +import { isRelativeFileReference, sessionFileUrl, useWindowsDesktop } from "../SessionFileLink"; + +/** Media, Office and text previews all recover to the same open conversation. */ +export function SessionFilePreview({ + url, hasExtractedText, onBack, children +}: { + url: string | null; + hasExtractedText: boolean; + onBack: () => void; + children: ReactNode; +}) { + const { t } = useTranslation(); + const [missing, setMissing] = useState(null); + const desktop = useWindowsDesktop(); + const relative = desktop && !!url && isRelativeFileReference(url); + const published = desktop ? sessionFileUrl(url) : null; + const source = published ?? (relative ? url : null); + useEffect(() => { + if (!source) return; + const controller = new AbortController(); + void apiFetch(source, { method: "HEAD", cache: "no-store", signal: controller.signal }) + .then((response) => { + // A stale relative file can match the frontend's dynamic chat page and return HTML with HTTP 200. + const chatPage = relative && !/\.html?(?:[?#]|$)/i.test(source) + && response.headers.get("content-type")?.startsWith("text/html"); + if (!controller.signal.aborted && (response.status === 404 || response.status === 410 || chatPage)) { + setMissing(source); + } + }) + .catch(() => { /* The previewer handles network and format errors. */ }); + return () => controller.abort(); + }, [relative, source]); + const missingSource = !url && !hasExtractedText && desktop; + if (!missingSource && (!source || missing !== source)) return children; + return ( +
    +
    + ); +} diff --git a/web/components/common/InlineFileCard.tsx b/web/components/common/InlineFileCard.tsx index a41019ff2..98126466d 100644 --- a/web/components/common/InlineFileCard.tsx +++ b/web/components/common/InlineFileCard.tsx @@ -2,6 +2,7 @@ import { createContext, useContext, useMemo, type ReactNode } from "react"; import { fromMarkdown } from "mdast-util-from-markdown"; +import { SessionFileLink } from "@/components/chat/SessionFileLink"; import type { MessageAttachment } from "@/features/chat/ChatStateAdapter"; import { docIconFor } from "@/lib/doc-attachments"; @@ -515,14 +516,14 @@ export function InlineFileCard({ const spec = docIconFor(filename); const Icon = spec.Icon; return ( - + ); } @@ -560,13 +561,13 @@ export function InlineWorkspaceImage({ ); if (!ctx?.onOpen) return image; return ( - + ); } diff --git a/web/components/common/RichMarkdownRenderer.tsx b/web/components/common/RichMarkdownRenderer.tsx index 39bdfbfcc..75239122a 100644 --- a/web/components/common/RichMarkdownRenderer.tsx +++ b/web/components/common/RichMarkdownRenderer.tsx @@ -27,6 +27,7 @@ import { useInlineFileCardContext, } from "@/components/common/InlineFileCard"; import type { MarkdownRendererProps } from "./markdown-renderer-types"; +import { sessionFileUrl } from "@/components/chat/SessionFileLink"; import { rehypeDirAuto } from "@/lib/rehype-dir-auto"; import { extractMarkdownText as extractText, @@ -584,7 +585,7 @@ export default function RichMarkdownRenderer({ return ( - + {supportsGeneratedOutputActions(a) ? ( ) : null} @@ -666,8 +667,8 @@ export function GeneratedFileCards({ preload="metadata" className="block max-h-[360px] w-full bg-black" /> - + {supportsGeneratedOutputActions(a) ? ( ) : null} @@ -697,8 +698,8 @@ export function GeneratedFileCards({ const size = formatFileSize(a.size_bytes); return (
    - + {supportsGeneratedOutputActions(a) ? ( ) : null} @@ -1659,6 +1660,7 @@ export const UserMessage = memo(function UserMessage({ kind: spec.label, label: filename, thumbnailUrl: src ?? undefined, + fileUrl: a.url, onClick: onPreviewAttachment ? () => onPreviewAttachment(a) : undefined, }; }), diff --git a/web/locales/de/app.json b/web/locales/de/app.json index d83c1f0e5..c6c935bd3 100644 --- a/web/locales/de/app.json +++ b/web/locales/de/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "Datei nicht verfügbar", "Your account changed. Reload settings before applying learning text.": "Your account changed. Reload settings before applying learning text.", "Customize the visual theme, learning text, and code blocks. Apply changes using the bar below.": "Customize the visual theme, learning text, and code blocks. Apply changes using the bar below.", "Learning text": "Learning text", diff --git a/web/locales/en/app.json b/web/locales/en/app.json index cd78c9675..597b06787 100644 --- a/web/locales/en/app.json +++ b/web/locales/en/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "File unavailable", "Speech synthesis and transcription models with saved providers.": "Speech synthesis and transcription models with saved providers.", "Image and video generation models with saved providers.": "Image and video generation models with saved providers.", "Manage provider names, addresses, credentials, and connectivity.": "Manage provider names, addresses, credentials, and connectivity.", diff --git a/web/locales/fr/app.json b/web/locales/fr/app.json index d94f1044f..64beb0443 100644 --- a/web/locales/fr/app.json +++ b/web/locales/fr/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "Fichier indisponible", "Your account changed. Reload settings before applying learning text.": "Votre compte a changé. Rechargez les paramètres avant d’appliquer les préférences de texte d’apprentissage.", "Customize the visual theme, learning text, and code blocks. Apply changes using the bar below.": "Personnalisez le thème visuel, le texte d’apprentissage et les blocs de code. Appliquez les modifications à l’aide de la barre ci-dessous.", "Learning text": "Texte d’apprentissage", diff --git a/web/locales/hu/app.json b/web/locales/hu/app.json index bec63caa0..f462096d4 100644 --- a/web/locales/hu/app.json +++ b/web/locales/hu/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "A fájl nem érhető el", "Speech synthesis and transcription models with saved providers.": "Beszédszintézis- és átírási modellek mentett szolgáltatókkal.", "Image and video generation models with saved providers.": "Kép- és videógenerálási modellek mentett szolgáltatókkal.", "Manage provider names, addresses, credentials, and connectivity.": "Szolgáltatónevek, címek, hitelesítő adatok és a kapcsolódás kezelése.", diff --git a/web/locales/it/app.json b/web/locales/it/app.json index 662626132..af09e31fd 100644 --- a/web/locales/it/app.json +++ b/web/locales/it/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "File non disponibile", "language.english": "English", "Guided Learning": "Apprendimento guidato", "Save": "Salva", diff --git a/web/locales/ja/app.json b/web/locales/ja/app.json index 2e49d244f..b98fb0db2 100644 --- a/web/locales/ja/app.json +++ b/web/locales/ja/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "ファイルを開けません", "Partially correct": "部分的に正解", "These answers could not be submitted. Please review or retry.": "これらの回答を送信できませんでした。確認するか、再試行してください。", "The edit could not be sent. Your draft is still here; please retry.": "編集内容を送信できませんでした。下書きは残っています。再試行してください。", diff --git a/web/locales/pl/app.json b/web/locales/pl/app.json index ace2e0c2c..3d4dbfd8c 100644 --- a/web/locales/pl/app.json +++ b/web/locales/pl/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "Plik niedostępny", "Your account changed. Reload settings before applying learning text.": "Your account changed. Reload settings before applying learning text.", "Customize the visual theme, learning text, and code blocks. Apply changes using the bar below.": "Customize the visual theme, learning text, and code blocks. Apply changes using the bar below.", "Learning text": "Learning text", diff --git a/web/locales/pt/app.json b/web/locales/pt/app.json index a48f65625..f6c5d4884 100644 --- a/web/locales/pt/app.json +++ b/web/locales/pt/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "Arquivo indisponível", "Partially correct": "Parcialmente correta", "These answers could not be submitted. Please review or retry.": "Não foi possível enviar estas respostas. Revise-as ou tente novamente.", "The edit could not be sent. Your draft is still here; please retry.": "Não foi possível enviar a edição. Seu rascunho continua aqui; tente novamente.", diff --git a/web/locales/tr/app.json b/web/locales/tr/app.json index e82ebda9b..2e16e6f9d 100644 --- a/web/locales/tr/app.json +++ b/web/locales/tr/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "Dosya kullanılamıyor", "Partially correct": "Kısmen doğru", "These answers could not be submitted. Please review or retry.": "Bu cevaplar gönderilemedi. Lütfen gözden geçirin ya da yeniden deneyin.", "The edit could not be sent. Your draft is still here; please retry.": "Düzenleme gönderilemedi. Taslağınız hâlâ burada; lütfen yeniden deneyin.", diff --git a/web/locales/uk/app.json b/web/locales/uk/app.json index 64a636a80..9ee10ecfd 100644 --- a/web/locales/uk/app.json +++ b/web/locales/uk/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "Файл недоступний", "Your account changed. Reload settings before applying learning text.": "Your account changed. Reload settings before applying learning text.", "Customize the visual theme, learning text, and code blocks. Apply changes using the bar below.": "Customize the visual theme, learning text, and code blocks. Apply changes using the bar below.", "Learning text": "Learning text", diff --git a/web/locales/vi/app.json b/web/locales/vi/app.json index 7b53e7f80..26db404bb 100644 --- a/web/locales/vi/app.json +++ b/web/locales/vi/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "Tệp không khả dụng", "Partially correct": "Đúng một phần", "These answers could not be submitted. Please review or retry.": "Không thể gửi các câu trả lời này. Vui lòng xem lại hoặc thử lại.", "The edit could not be sent. Your draft is still here; please retry.": "Không thể gửi bản chỉnh sửa. Bản nháp của bạn vẫn còn ở đây; vui lòng thử lại.", diff --git a/web/locales/zh/app.json b/web/locales/zh/app.json index 71bc280e2..87ac5ba56 100644 --- a/web/locales/zh/app.json +++ b/web/locales/zh/app.json @@ -1,4 +1,5 @@ { + "File unavailable": "文件不可用", "Speech synthesis and transcription models with saved providers.": "使用已配置的提供方管理语音合成与语音识别模型。", "Image and video generation models with saved providers.": "使用已配置的提供方管理图片与视频生成模型。", "Manage provider names, addresses, credentials, and connectivity.": "管理提供方的名称、地址、密钥并测试连接。", diff --git a/web/tests/chat/ChatWorkspace.smoke.spec.tsx b/web/tests/chat/ChatWorkspace.smoke.spec.tsx index 17e05656c..3ba57ab92 100644 --- a/web/tests/chat/ChatWorkspace.smoke.spec.tsx +++ b/web/tests/chat/ChatWorkspace.smoke.spec.tsx @@ -347,6 +347,28 @@ describe('ChatWorkspace smoke', () => { )) }) + it('opens a published Markdown reference in the Windows viewer and keeps a stale link in the same conversation', async () => { + const userAgent = vi.spyOn(navigator, 'userAgent', 'get').mockReturnValue('OpenDeepTutor/1.7.4 (Windows; x64)') + try { + applyState({ messages: [{ id: 1, role: 'assistant', content: 'Notes' }] }) + await act(async () => { renderWorkspace() }) + const link = document.createElement('a') + link.textContent = 'Read the notes' + screen.getByTestId('message-list').appendChild(link) + link.href = '/files/attachments/lesson/id/notes.md?dt_workspace=math' + fireEvent.click(link) + expect(fixture.viewer.openFileTab).toHaveBeenCalledWith(expect.objectContaining({ + filename: 'notes.md', url: '/files/attachments/lesson/id/notes.md?dt_workspace=math', + })) + link.setAttribute('href', 'outputs/moved.md') + fireEvent.click(link) + expect(fixture.viewer.openFileTab).toHaveBeenLastCalledWith(expect.objectContaining({ filename: 'moved.md', url: 'outputs/moved.md' })) + expect(fixture.viewer.openWebTab).not.toHaveBeenCalled() + } finally { + userAgent.mockRestore() + } + }) + it('does not replace an explicit empty selection', async () => { fixture.listKnowledgeBases.mockResolvedValue([ { id: 'workspace:kb:physics', name: 'physics', is_default: true, status: 'ready' }, diff --git a/web/tests/generated-file-cards.spec.tsx b/web/tests/generated-file-cards.spec.tsx index f28965793..0db1c42bf 100644 --- a/web/tests/generated-file-cards.spec.tsx +++ b/web/tests/generated-file-cards.spec.tsx @@ -1,4 +1,4 @@ -import { render, screen } from "@testing-library/react"; +import { fireEvent, render, screen } from "@testing-library/react"; import { describe, expect, it, vi } from "vitest"; import { GeneratedFileCards } from "@/features/chat/messages/ChatMessageList"; import type { MessageAttachment } from "@/features/chat/ChatStateAdapter"; @@ -23,6 +23,22 @@ const figure = image("outputs/chat/turn-a/figure.png", "wsi_a"); const other = image("outputs/chat/turn-a/other.png", "wsi_b"); describe("generated image cards", () => { + it("exposes the published URL to the context menu and opens the in-app preview on click", () => { + const userAgent = vi.spyOn(navigator, "userAgent", "get").mockReturnValue("OpenDeepTutor/1.7.4 (Windows; x64)"); + try { + const onOpen = vi.fn(); + render(); + const link = screen.getByRole("link", { name: /figure/i }); + expect(link).toHaveAttribute("href", figure.url + "?dt_workspace="); + fireEvent.contextMenu(link); + expect(onOpen).not.toHaveBeenCalled(); + fireEvent.click(link); + expect(onOpen).toHaveBeenCalledWith(figure); + } finally { + userAgent.mockRestore(); + } + }); + it("leaves out an image the reply already embeds inline", () => { render( = {}) { /** The panel slides in over two frames and is aria-hidden until it has. */ const entered = () => screen.findByRole("button", { name: "New tab" }); +it.each([ + ["/files/attachments/session-a/a/notes.md", 404, "application/json"], + ["outputs/moved.md", 200, "text/html; charset=utf-8"], +] as const)("returns to the conversation for a missing Windows file %s", async (url, status, contentType) => { + const userAgent = vi.spyOn(navigator, "userAgent", "get").mockReturnValue("OpenDeepTutor/1.7.4 (Windows; x64)"); + const request = vi.spyOn(globalThis, "fetch").mockImplementation(async () => new Response(null, { status, headers: { "Content-Type": contentType } })); + try { + const onClose = vi.fn(); + const { ref } = renderPanel({ onClose }); + await entered(); + act(() => ref.current!.openFileTab({ type: "file", filename: "notes.md", url })); + expect(await screen.findByText("File unavailable")).toBeVisible(); + fireEvent.click(screen.getByRole("button", { name: "Back to conversation" })); + expect(onClose).toHaveBeenCalledOnce(); + expect(request).toHaveBeenCalledWith(expect.stringContaining(url), expect.objectContaining({ method: "HEAD" })); + } finally { + userAgent.mockRestore(); + request.mockRestore(); + } +}); + const tabBar = () => screen.getByRole("button", { name: "New tab" }).parentElement!.parentElement!; it("names every tool on the launcher, and opening things lives there alone", async () => {