Skip to content

armgit / Orkas

Public Imported from GitHub
0

Orkas is an open-source (MIT), local-first AI team for your desktop: a Commander turns your goal into to-dos and coordinates 16 built-in specialist agents plus Claude Code, Codex, OpenCode, OpenClaw and Hermes, with projects, scheduled automations and connectors. Free app for macOS & Windows; built-in models or your own keys.

Preserve standalone preview window and media lifecycle

wyt407b2881c8dc
diff --git a/src/main/features/preview_windows.ts b/src/main/features/preview_windows.ts
index 18f5cc08..90a0e651 100644
--- a/src/main/features/preview_windows.ts
+++ b/src/main/features/preview_windows.ts
@@ -7,7 +7,6 @@ import { createLogger } from '../logger';
import { hardenedWebPreferences, installExternalNavigationGuard, installHtmlPreviewNavigationGuard } from '../util/window-security';
import { registerUserSwitchHook } from './user-switch-hooks';
import { subscribeBus } from './group_chat';
-import { commercialWebAppFailure, isCommercialWebAppFailure, requireLocalAppType, storedAppType } from './web_apps/commercial-entry';
// Host-only window chrome. Generated applications retain the existing iframe
// sandbox and acquire their SDK instance from their own trusted renderer.
@@ -36,7 +35,9 @@ const sourceSchema = z.discriminatedUnion('kind', [
]);
export type PreviewSource = z.infer<typeof sourceSchema>;
type Record = { win: BrowserWindow; owner: WebContents; uid: string; source: PreviewSource; dirty: boolean;
- ready: boolean; next?: PreviewSource; dispose?: () => void };
+ ready: boolean; next?: PreviewSource; dispose?: () => void;
+ revealPending?: boolean;
+ artifactRevision?: number };
const records = new Map<number, Record>();
const owners = new Map<WebContents, { windows: Set<BrowserWindow>; dispose: () => void }>();
const log = createLogger('preview-windows');
@@ -48,6 +49,10 @@ function sourceKey(source: PreviewSource): string {
return JSON.stringify([source.kind, source.options.cid, source.options.projectId, source.kind === 'file' ? source.path : source.src]);
}
+function canReplaceContent(current: PreviewSource, next: PreviewSource): boolean {
+ return ['image', 'file', 'video'].includes(current.kind) && ['image', 'file', 'video'].includes(next.kind);
+}
+
function owned(uid: string, sender: WebContents): Record {
const record = records.get(sender.id);
if (!record || record.uid !== uid || record.win.isDestroyed()) throw new Error('Preview is unavailable.');
@@ -56,6 +61,12 @@ function owned(uid: string, sender: WebContents): Record {
export function isPreviewContents(sender: WebContents): boolean { return records.has(sender.id); }
+function showPreview(record: Record) {
+ if (record.win.isDestroyed() || !record.win.isFocusable()) return;
+ if (record.win.isMinimized()) record.win.restore();
+ record.win.show(); record.win.focus();
+}
+
function cancelOwnerRequests(record: Record) {
for (const [key, request] of pending) if (request.preview === record.win.id) {
pending.delete(key); request.finish({ ok: false });
@@ -66,53 +77,70 @@ export function readyPreview(uid: string, sender: WebContents) {
const record = owned(uid, sender);
record.ready = true;
if (record.next) sender.send('preview-windows:replace-request', {});
+ else if (record.revealPending) {
+ record.revealPending = false;
+ showPreview(record);
+ }
}
export async function replacePreview(uid: string, sender: WebContents, accepted: unknown) {
const record = owned(uid, sender);
+ if (!record.ready) return;
const source = record.next;
record.next = undefined;
- if (accepted !== true || !source || !record.ready) return;
+ if (accepted !== true || !source) {
+ if (record.revealPending) { record.revealPending = false; showPreview(record); }
+ return;
+ }
+ // A dirty editor stays visible for its discard dialog; once accepted it
+ // can release its content through the same path as a clean preview.
+ const inPlace = canReplaceContent(record.source, source);
+ if (record.revealPending && !inPlace) record.win.hide();
record.ready = false;
record.dispose?.(); record.dispose = undefined;
cancelOwnerRequests(record);
+ if (sourceKey(record.source) !== sourceKey(source)) record.artifactRevision = undefined;
record.source = source;
record.dirty = false;
+ // The existing renderer releases its old media and acknowledges the new
+ // source through readyPreview before the window is raised. No navigation.
+ if (inPlace) {
+ initializePreview(uid, sender);
+ return { source };
+ }
// Recreate only the document: preserve native window position, size and
// maximized state, and release the old document's media/SDK resources.
- await record.win.loadFile(path.join(SRC_ROOT, 'renderer', 'preview.html'));
+ try {
+ await record.win.loadFile(path.join(SRC_ROOT, 'renderer', 'preview.html'));
+ } catch (error) {
+ // A failed document cannot signal readiness. Release the hidden window so
+ // the next click can create a working preview, as on an initial load failure.
+ if (!record.win.isDestroyed()) record.win.destroy();
+ throw error;
+ }
}
export async function openPreview(uid: string, owner: WebContents, payload: unknown) {
if ((JSON.stringify(payload)?.length || 0) > 8 * 1024 * 1024) throw new Error('Preview is too large.');
const source = sourceSchema.parse(payload);
- try {
- const saved = await import('./saved_apps');
- if (source.kind === 'app') requireLocalAppType(await saved.resolveSavedAppType(uid, source.appId));
- else if (source.kind === 'artifact') requireLocalAppType(await saved.resolveArtifactAppType(uid, source.cid, source.artifactId));
- else if (source.kind === 'file') {
- if (source.options.cid) requireLocalAppType(await saved.boundAppType(uid, source.options.cid));
- const file = source.options.absPath || source.path;
- if (path.isAbsolute(file)) {
- requireLocalAppType(await saved.managedPathAppType(uid, file));
- requireLocalAppType(storedAppType(path.dirname(file)));
- }
- }
- } catch (error) { if (isCommercialWebAppFailure(error)) return commercialWebAppFailure(); throw error; }
if (records.has(owner.id)) throw new Error('Open previews from the main window.');
const existing = [...records.values()].find(r => r.uid === uid && r.owner === owner
&& (source.kind === 'app' ? sourceKey(r.source) === sourceKey(source) : r.source.kind !== 'app'));
if (existing) {
- if (existing.win.isFocusable()) {
- if (existing.win.isMinimized()) existing.win.restore();
- existing.win.show(); existing.win.focus();
- }
if (source.kind !== 'app') {
const unchanged = source.kind !== 'image' && sourceKey(existing.source) === sourceKey(source);
existing.next = unchanged ? undefined : source;
+ if (existing.next) {
+ // Raise the window only after replacement. File and media swaps keep the shell
+ // visible in place; other kinds hide the document being navigated away.
+ existing.revealPending = true;
+ if (!existing.dirty && !canReplaceContent(existing.source, source)) existing.win.hide();
+ } else if (existing.ready) existing.revealPending = false;
if (existing.next && existing.ready) existing.win.webContents.send('preview-windows:replace-request', {});
}
- return { windowId: existing.win.id };
+ if (!existing.revealPending || existing.dirty) showPreview(existing);
+ // Only an app window's opener needs to know its open was a refocus.
+ return { windowId: existing.win.id, ...(source.kind === 'app' ? { reused: true } : {}) };
}
const parent = BrowserWindow.fromWebContents(owner);
if (!parent || parent.isDestroyed()) throw new Error('Preview is unavailable.');
@@ -163,7 +191,7 @@ export async function openPreview(uid: string, owner: WebContents, payload: unkn
});
try {
await win.loadFile(path.join(SRC_ROOT, 'renderer', 'preview.html'));
- if (!win.isDestroyed() && win.isFocusable()) { win.show(); win.focus(); }
+ if (!record.revealPending) showPreview(record);
return { windowId: win.id };
} catch (error) { destroy(); throw error; }
}
@@ -178,6 +206,17 @@ export function initializePreview(uid: string, sender: WebContents) {
if (event.type === 'message' && !sender.isDestroyed()) sender.send('preview-windows:gallery-refresh', {});
});
}
+ if (source.kind === 'artifact' && !record.dispose) {
+ record.dispose = subscribeBus(uid, source.cid, event => {
+ if (event.type !== 'artifact_created' || event.artifact.id !== source.artifactId
+ || !Number.isSafeInteger(event.artifact.revision)
+ || event.artifact.revision! <= (record.artifactRevision ?? 0) || sender.isDestroyed()) return;
+ record.artifactRevision = event.artifact.revision;
+ if (record.next && sourceKey(record.next) !== sourceKey(source)) return;
+ record.next = { ...source, title: event.artifact.title };
+ if (record.ready) sender.send('preview-windows:replace-request', {});
+ });
+ }
return { source };
}
diff --git a/src/renderer/modules/chat-file-viewer.js b/src/renderer/modules/chat-file-viewer.js
index 322f13bd..586d3b22 100644
--- a/src/renderer/modules/chat-file-viewer.js
+++ b/src/renderer/modules/chat-file-viewer.js
@@ -49,6 +49,7 @@ let _viewerTitle = null;
let _viewerRevealBtn = null;
let _viewerAddLibraryBtn = null;
let _viewerSaveAppBtn = null;
+let _viewerSaveNewAppBtn = null;
let _viewerMdActions = null;
let _viewerKeyHandler = null;
let _viewerCurrentPath = null;
@@ -63,6 +64,9 @@ let _viewerDirty = false;
let _viewerDiscardConfirmPending = false;
let _viewerRenderSeq = 0;
let _viewerBlobUrl = null;
+let _viewerMediaCleanup = null;
+let _viewerLibraryRestoreTimer = null;
+let _viewerSaveRestoreTimer = null;
let _viewerHtmlCanvasResizeHandler = null;
let _viewerPdfPreviewSeq = 0;
let _viewerPdfPreviewState = null;
@@ -288,10 +292,12 @@ async function _viewerShowAlert(message, action) {
}
}
-function _scheduleAddLibraryButtonRestore(original) {
- setTimeout(() => {
+function _scheduleAddLibraryButtonRestore(original, seq) {
+ if (seq !== _viewerRenderSeq) return;
+ clearTimeout(_viewerLibraryRestoreTimer);
+ _viewerLibraryRestoreTimer = setTimeout(() => {
try {
- if (!_viewerAddLibraryBtn) return;
+ if (!_viewerAddLibraryBtn || seq !== _viewerRenderSeq) return;
_viewerAddLibraryBtn.innerHTML = original;
_viewerAddLibraryBtn.disabled = false;
} catch (_) {
@@ -303,10 +309,12 @@ function _scheduleAddLibraryButtonRestore(original) {
}, 1500);
}
-function _scheduleSaveAppButtonRestore(path, original) {
- setTimeout(() => {
+function _scheduleSaveAppButtonRestore(path, original, seq) {
+ if (seq !== _viewerRenderSeq) return;
+ clearTimeout(_viewerSaveRestoreTimer);
+ _viewerSaveRestoreTimer = setTimeout(() => {
try {
- if (!_viewerSaveAppBtn) return;
+ if (!_viewerSaveAppBtn || seq !== _viewerRenderSeq) return;
_viewerSaveAppBtn.innerHTML = original;
_refreshSaveAppButton(path);
} catch (_) {
@@ -475,6 +483,10 @@ function _setViewerButtonLabel(btn, label) {
function _setSaveAppVisible(visible) {
if (!_viewerSaveAppBtn) return;
_viewerSaveAppBtn.hidden = !visible;
+ if (_viewerSaveNewAppBtn) {
+ _viewerSaveNewAppBtn.hidden = !visible || _viewerSaveAppBtn.dataset.hasTarget !== 'true';
+ _viewerSaveNewAppBtn.disabled = !visible;
+ }
_viewerSaveAppBtn.disabled = !visible;
}
@@ -526,6 +538,9 @@ function _ensureViewer() {
<button type="button" class="chat-file-viewer-save-app" aria-label="${saveAppLabel}" title="${saveAppLabel}" data-tooltip="${saveAppLabel}" hidden>
${_viewerSaveAppButtonHtml(saveAppLabel)}
</button>
+ <button type="button" class="chat-file-viewer-save-new-app" hidden>
+ ${_viewerSaveAppButtonHtml('', 'plus')}
+ </button>
<button type="button" class="chat-file-viewer-reveal" aria-label="${revealLabel}" title="${revealLabel}" data-tooltip="${revealLabel}">${folderIcon}</button>
<button type="button" class="modal-close-btn chat-file-viewer-close" aria-label="${closeLabel}" title="${closeLabel}" data-tooltip="${closeLabel}">${_viewerUiIconHtml('x', 'modal-close-icon')}</button>
</div>
@@ -541,6 +556,8 @@ function _ensureViewer() {
_viewerRevealBtn = root.querySelector('.chat-file-viewer-reveal');
_viewerAddLibraryBtn = root.querySelector('.chat-file-viewer-add-library');
_viewerSaveAppBtn = root.querySelector('.chat-file-viewer-save-app');
+ _viewerSaveNewAppBtn = root.querySelector('.chat-file-viewer-save-new-app');
+ _viewerSaveNewAppBtn.addEventListener('click', () => _onSaveAppClick('new'));
_viewerMdActions = root.querySelector('.chat-file-viewer-md-actions');
// i18n change → re-label the icon-only buttons. Same lazy listener pattern
@@ -555,7 +572,8 @@ function _ensureViewer() {
const cl = _viewerLabel('chat.preview_close_title', 'Close');
const rl = _viewerLabel('chat.preview_reveal_title', 'Open in folder');
const al = _viewerLabel('chat.preview_add_library_title', 'Add to Library');
- const sl = _viewerLabel('apps.save_from_file_action', 'Save as app');
+ const sl = s?.dataset.hasTarget === 'true' ? _viewerLabel('apps.update_original', 'Update original app') : _viewerLabel('apps.save_from_file_action', 'Save as app');
+ _setViewerButtonLabel(_viewerSaveNewAppBtn, _viewerLabel('apps.save_new', 'Save new app'));
_setViewerButtonLabel(c, cl);
_setViewerButtonLabel(r, rl);
if (a) {
@@ -571,7 +589,7 @@ function _ensureViewer() {
root.querySelector('.chat-file-viewer-close').addEventListener('click', closeChatFileViewer);
_viewerRevealBtn.addEventListener('click', _onRevealClick);
_viewerAddLibraryBtn.addEventListener('click', _onAddLibraryClick);
- _viewerSaveAppBtn.addEventListener('click', _onSaveAppClick);
+ _viewerSaveAppBtn.addEventListener('click', () => _onSaveAppClick());
return root;
}
@@ -589,6 +607,11 @@ async function _confirmDiscardViewerEdits() {
}
function _teardownViewerContent(reason = 'replaced') {
+ clearTimeout(_viewerLibraryRestoreTimer);
+ clearTimeout(_viewerSaveRestoreTimer);
+ _viewerLibraryRestoreTimer = _viewerSaveRestoreTimer = null;
+ _viewerMediaCleanup?.();
+ _viewerMediaCleanup = null;
_viewerFinishPdfPreview(reason);
_viewerFinishHtmlPreview(reason);
if (_viewerEditController) {
@@ -648,10 +671,10 @@ async function _onRevealClick() {
}
async function _onAddLibraryClick() {
+ const seq = _viewerRenderSeq;
const p = _viewerCurrentPath;
if (!p || !_viewerCurrentCid || !_viewerAddLibraryBtn || _viewerAddLibraryBtn.disabled) return;
if (!_viewerCanAddToLibrary(p, { projectScoped: _viewerLibraryProjectScoped })) return;
- const startedAt = Date.now();
const label = _viewerLabel('chat.preview_add_library_title', 'Add to Library');
const doneLabel = _viewerLabel('chat.preview_add_library_done', 'Added');
const original = _viewerAddLibraryButtonHtml(label);
@@ -677,7 +700,7 @@ async function _onAddLibraryClick() {
return;
} finally {
if (!res || !res.ok) {
- _scheduleAddLibraryButtonRestore(original);
+ _scheduleAddLibraryButtonRestore(original, seq);
}
}
@@ -692,7 +715,7 @@ async function _onAddLibraryClick() {
const scope = res.scope === 'project' ? 'project' : (res.scope === 'global' ? 'global' : 'unknown');
window.OrkasPreviewHost?.filesChanged();
try {
- _viewerAddLibraryBtn.innerHTML = _viewerAddLibraryButtonHtml(doneLabel, 'check');
+ if (seq === _viewerRenderSeq) _viewerAddLibraryBtn.innerHTML = _viewerAddLibraryButtonHtml(doneLabel, 'check');
if (scope === 'global' && typeof currentView !== 'undefined' && currentView === 'contexts' && typeof loadContexts === 'function') {
loadContexts();
}
@@ -705,7 +728,7 @@ async function _onAddLibraryClick() {
error_code: 'file_viewer_presentation_failed',
});
} finally {
- _scheduleAddLibraryButtonRestore(original);
+ _scheduleAddLibraryButtonRestore(original, seq);
}
}
@@ -717,22 +740,27 @@ function _viewerFileActionPayload(path) {
}
async function _refreshSaveAppButton(path) {
+ const seq = _viewerRenderSeq;
if (!_viewerSaveAppBtn) return;
_setSaveAppVisible(false);
if (!path) return;
try {
const inspected = await window.orkas.invoke('savedApps.inspectBundleFromPath', _viewerFileActionPayload(path));
- if (!_isViewerOpen() || _viewerCurrentPath !== path) return;
+ if (seq !== _viewerRenderSeq || !_isViewerOpen() || _viewerCurrentPath !== path) return;
const canSave = !!(inspected && inspected.ok !== false && (inspected.canSave || inspected.reason === 'app_bundle_root'));
+ _viewerSaveAppBtn.dataset.hasTarget = String(!!inspected?.target);
+ _setViewerButtonLabel(_viewerSaveAppBtn, _viewerLabel(inspected?.target ? 'apps.update_original' : 'apps.save_from_file_action', 'Save as app'));
+ _setViewerButtonLabel(_viewerSaveNewAppBtn, _viewerLabel('apps.save_new', 'Save new app'));
_setSaveAppVisible(canSave);
} catch {
- if (!_isViewerOpen() || _viewerCurrentPath !== path) return;
+ if (seq !== _viewerRenderSeq || !_isViewerOpen() || _viewerCurrentPath !== path) return;
_viewerLog.warn('inspect app bundle failed', { error_code: 'inspect_failed' });
_setSaveAppVisible(false);
}
}
-async function _onSaveAppClick() {
+async function _onSaveAppClick(mode = 'auto') {
+ const seq = _viewerRenderSeq;
const p = _viewerCurrentPath;
if (!p || !_viewerSaveAppBtn || _viewerSaveAppBtn.disabled) return;
if (_viewerDirty) {
@@ -751,18 +779,17 @@ async function _onSaveAppClick() {
}
let res;
try {
- res = await window.orkas.invoke('savedApps.saveFromPath', _viewerFileActionPayload(p));
+ res = await window.OrkasAppSave.save('savedApps.saveFromPath', {..._viewerFileActionPayload(p), ...(mode === 'new' ? {mode} : {})}, _viewerLabel);
+ if (res?.canceled) {
+ _scheduleSaveAppButtonRestore(p, original, seq);
+ return;
+ }
} catch (err) {
const failure = _viewerStableFailure(err, 'saved_app_save_failed', 'ipc');
_viewerLogFailure('file_preview_save_app', failure);
// Raw errors may hold local paths; the failure is logged by code only.
await _viewerShowAlert(_viewerLabel('apps.save_failed', 'Could not save the app'), 'file_preview_save_app_presentation');
- _scheduleSaveAppButtonRestore(p, original);
- return;
- }
- if (window.OrkasCommercialEntry?.isFailure(res)) {
- _scheduleSaveAppButtonRestore(p, original);
- await window.OrkasCommercialEntry.show();
+ _scheduleSaveAppButtonRestore(p, original, seq);
return;
}
if (!res || res.ok === false) {
@@ -773,12 +800,12 @@ async function _onSaveAppClick() {
? _viewerLabel('apps.save_root_folder_required', 'Move the HTML and its resources into a separate folder, then save as an app again.')
: _viewerLabel('apps.save_failed', 'Could not save the app');
await _viewerShowAlert(message, 'file_preview_save_app_presentation');
- _scheduleSaveAppButtonRestore(p, original);
+ _scheduleSaveAppButtonRestore(p, original, seq);
return;
}
window.OrkasPreviewHost?.filesChanged();
try {
- _viewerSaveAppBtn.innerHTML = _viewerSaveAppButtonHtml(doneLabel, 'check');
+ if (seq === _viewerRenderSeq) _viewerSaveAppBtn.innerHTML = _viewerSaveAppButtonHtml(doneLabel, 'check');
if (typeof uiToast === 'function') uiToast(doneLabel, { variant: 'success' });
else if (typeof uiAlert === 'function') await uiAlert(doneLabel);
if (typeof loadSavedApps === 'function') loadSavedApps(true);
@@ -788,7 +815,7 @@ async function _onSaveAppClick() {
error_code: 'file_viewer_presentation_failed',
});
}
- _scheduleSaveAppButtonRestore(p, original);
+ _scheduleSaveAppButtonRestore(p, original, seq);
}
async function _openViewerShell(displayName, opts) {
@@ -806,10 +833,13 @@ async function _openViewerShell(displayName, opts) {
_viewerLibraryProjectScoped = !!projectId || _viewerConversationIsProjectScoped(cid);
if (_viewerRevealBtn) _viewerRevealBtn.hidden = !absPath;
if (_viewerAddLibraryBtn) {
+ _viewerAddLibraryBtn.disabled = false;
+ _viewerAddLibraryBtn.innerHTML = _viewerAddLibraryButtonHtml(_viewerLabel('chat.preview_add_library_title', 'Add to Library'));
_viewerAddLibraryBtn.hidden = !cid || !_viewerCanAddToLibrary(absPath || displayName || kind, {
projectScoped: _viewerLibraryProjectScoped,
});
}
+ if (_viewerSaveAppBtn) _viewerSaveAppBtn.innerHTML = _viewerSaveAppButtonHtml(_viewerLabel('apps.save_from_file_action', 'Save as app'));
void _refreshSaveAppButton(_viewerCurrentPath);
_viewerTitle.textContent = displayName || '';
// `is-markdown` / `is-text` switch the body to a flex column so an editor
@@ -840,8 +870,12 @@ async function closeChatFileViewer(opts) {
const force = !!(opts && opts.force);
if (!force && !(await _confirmDiscardViewerEdits())) return false;
_viewerRenderSeq += 1;
- _viewerEl.classList.remove('is-open');
- _viewerEl.setAttribute('aria-hidden', 'true');
+ // A video handoff replaces only the media surface; keep its shell visible
+ // throughout teardown so the compositor does not retire the entire viewer.
+ if (!force || !opts?.keepShell) {
+ _viewerEl.classList.remove('is-open');
+ _viewerEl.setAttribute('aria-hidden', 'true');
+ }
// Drop iframe / blob src so big preview docs can be GC'd promptly when
// the user closes the overlay. Without this, hidden iframes keep the
// PDFium / HTML document alive in memory until the next reopen.
@@ -1133,40 +1167,13 @@ function _applyViewerVideoPlayback(video, opts) {
};
seek();
if (playback.autoplay) play();
- if (video.readyState < 1) {
- video.addEventListener('loadedmetadata', () => {
- seek();
- play();
- }, { once: true });
- }
+ const onMetadata = () => { seek(); play(); };
+ if (video.readyState < 1) video.addEventListener('loadedmetadata', onMetadata, { once: true });
+ return () => video.removeEventListener('loadedmetadata', onMetadata);
}
async function _renderVideoBody(absPath, displayName, cid, projectId, playbackOpts) {
- const seq = await _openViewerShell(displayName, { kind: 'video', absPath, cid, projectId });
- if (!seq) return;
- const url = _chatMediaLocalUrl(absPath);
- const wrap = document.createElement('div');
- wrap.className = 'chat-file-viewer-video-wrap';
- wrap.dataset.chatVideoPlaybackSurface = 'floating_player';
- const video = document.createElement('video');
- video.className = 'chat-file-viewer-video';
- video.controls = true;
- video.setAttribute('controlslist', 'nodownload nofullscreen noremoteplayback');
- video.setAttribute('disablepictureinpicture', '');
- video.setAttribute('disableremoteplayback', '');
- video.setAttribute('playsinline', '');
- video.preload = 'metadata';
- wrap.appendChild(video);
- video.addEventListener('loadedmetadata', () => {
- if (seq === _viewerRenderSeq) _viewerFinishLoading(wrap);
- }, { once: true });
- video.addEventListener('error', () => {
- if (seq === _viewerRenderSeq) _viewerFinishLoading(wrap);
- }, { once: true });
- _viewerShowLoading();
- _viewerAppendLoadingResource(wrap);
- _applyViewerVideoPlayback(video, playbackOpts);
- video.src = url;
+ return openChatVideoUrlViewer(_chatMediaLocalUrl(absPath), displayName, { ...playbackOpts, absPath, cid, projectId });
}
async function openChatVideoUrlViewer(src, displayName, opts) {
@@ -1190,15 +1197,25 @@ async function openChatVideoUrlViewer(src, displayName, opts) {
video.setAttribute('playsinline', '');
video.preload = 'metadata';
wrap.appendChild(video);
- video.addEventListener('loadedmetadata', () => {
+ const finish = () => {
if (seq === _viewerRenderSeq) _viewerFinishLoading(wrap);
- }, { once: true });
- video.addEventListener('error', () => {
- if (seq === _viewerRenderSeq) _viewerFinishLoading(wrap);
- }, { once: true });
+ };
+ video.addEventListener('loadedmetadata', finish, { once: true });
+ video.addEventListener('error', finish, { once: true });
_viewerShowLoading();
_viewerAppendLoadingResource(wrap);
- _applyViewerVideoPlayback(video, opts);
+ const cancelPlayback = _applyViewerVideoPlayback(video, opts);
+ _viewerMediaCleanup = () => {
+ // Detaching a playing video alone does not release its decoder or cancel
+ // a pending metadata callback. Clear the source before removing the node.
+ wrap.classList.add('chat-file-viewer-loading-resource');
+ video.removeEventListener('loadedmetadata', finish);
+ video.removeEventListener('error', finish);
+ cancelPlayback?.();
+ video.pause();
+ video.removeAttribute('src');
+ video.load();
+ };
video.src = url;
}
@@ -1219,14 +1236,20 @@ async function _renderAudioBody(absPath, displayName, cid, projectId) {
</div>
`;
const audio = wrap.querySelector('.chat-file-viewer-audio');
- audio.addEventListener('loadedmetadata', () => {
+ const finish = () => {
if (seq === _viewerRenderSeq) _viewerFinishLoading(wrap);
- }, { once: true });
- audio.addEventListener('error', () => {
- if (seq === _viewerRenderSeq) _viewerFinishLoading(wrap);
- }, { once: true });
+ };
+ audio.addEventListener('loadedmetadata', finish, { once: true });
+ audio.addEventListener('error', finish, { once: true });
_viewerShowLoading();
_viewerAppendLoadingResource(wrap);
+ _viewerMediaCleanup = () => {
+ audio.removeEventListener('loadedmetadata', finish);
+ audio.removeEventListener('error', finish);
+ audio.pause();
+ audio.removeAttribute('src');
+ audio.load();
+ };
audio.src = url;
}
@@ -1426,9 +1449,8 @@ async function openChatFileViewer(absPath, displayName, opts) {
if (window.OrkasPreviewWindows) {
if (!(await _ensureViewerFileExists(absPath, opts?.cid, opts?.projectId))) return;
if (_kindOf(absPath) === 'image') return window.OrkasPreviewWindows.image(_chatMediaLocalUrl(absPath), displayName || absPath.split(/[\\/]/).pop(), { ...opts, absPath });
- const result = await window.OrkasPreviewWindows.open({ kind: 'file', path: absPath, title: displayName || absPath.split(/[\\/]/).pop(), options: window.OrkasPreviewWindows.options(opts) });
- if (window.OrkasCommercialEntry?.isFailure(result)) await window.OrkasCommercialEntry.show();
- return result;
+ if (_kindOf(absPath) === 'video') return openChatVideoUrlViewer(_chatMediaLocalUrl(absPath), displayName || absPath.split(/[\\/]/).pop(), { ...opts, absPath });
+ return window.OrkasPreviewWindows.open({ kind: 'file', path: absPath, title: displayName || absPath.split(/[\\/]/).pop(), options: window.OrkasPreviewWindows.options(opts) });
}
const cid = (opts && opts.cid) || null;
const projectId = (opts && opts.projectId) || null;
diff --git a/src/renderer/modules/chat-lightbox.js b/src/renderer/modules/chat-lightbox.js
index 9fdeaceb..e00d43ea 100644
--- a/src/renderer/modules/chat-lightbox.js
+++ b/src/renderer/modules/chat-lightbox.js
@@ -543,6 +543,7 @@ function openChatImageLightbox(src, alt, opts) {
if (title) title.textContent = alt || '';
if (window.OrkasPreviewHost) document.title = alt || 'Orkas';
_setLightboxLoading(true);
+ _releaseLightboxImage(_lightboxImg);
const settle = () => {
if (loadSeq !== _lightboxLoadSeq) return;
_clearLightboxLoadListeners();
@@ -599,7 +600,7 @@ function _releaseLightboxImage(image) {
image.removeAttribute('src');
}
-function closeChatImageLightbox() {
+function closeChatImageLightbox(opts) {
if (!_lightboxEl) return;
_lightboxLoadSeq += 1;
_clearLightboxLoadListeners();
@@ -627,7 +628,7 @@ function closeChatImageLightbox() {
document.removeEventListener('keydown', _lightboxKeyHandler);
_lightboxKeyHandler = null;
}
- window.OrkasPreviewHost?.close();
+ if (!opts?.force) window.OrkasPreviewHost?.close();
}
// Document-level delegation: any markdown-rendered chat image
diff --git a/src/renderer/modules/preview-host.js b/src/renderer/modules/preview-host.js
index e12d8e78..26e15f4f 100644
--- a/src/renderer/modules/preview-host.js
+++ b/src/renderer/modules/preview-host.js
@@ -9,8 +9,11 @@ const _convLog = createLogger('preview-host');
'use strict';
let closing = false;
let replacing = false;
+ let replaceAgain = false;
let refreshTimer = null;
let projectScoped = false;
+ let sourceGeneration = 0;
+ let disposeVideoToolbar = null;
async function close() {
if (closing) return;
closing = true;
@@ -39,8 +42,9 @@ const _convLog = createLogger('preview-host');
_updateLightboxNavigation();
}
async function loadGalleryPage(gallery, before) {
+ const generation = sourceGeneration;
const response = await window.orkas.invoke('previewWindows.requestOwner', { kind: 'gallery', before });
- if (!response?.ok || !Array.isArray(response.items)) return;
+ if (closing || generation !== sourceGeneration || !response?.ok || !Array.isArray(response.items)) return;
merge(gallery, response.items, before != null);
if (before != null) gallery.nextCursor = response.nextCursor;
}
@@ -49,11 +53,30 @@ const _convLog = createLogger('preview-host');
filesChanged: () => window.orkas.invoke('previewWindows.filesChanged', {}).catch(() => {}) };
window.orkas.onPushEvent('preview-windows:close-request', requestClose);
window.orkas.onPushEvent('preview-windows:replace-request', async () => {
- if (replacing || closing) return;
+ if (closing) return;
+ if (replacing) { replaceAgain = true; return; }
replacing = true;
try {
- const accepted = await _confirmDiscardViewerEdits();
- await window.orkas.invoke('previewWindows.replace', { accepted });
+ do {
+ replaceAgain = false;
+ const accepted = await _confirmDiscardViewerEdits();
+ const result = await window.orkas.invoke('previewWindows.replace', { accepted });
+ if (result?.source && !closing) {
+ sourceGeneration += 1;
+ clearTimeout(refreshTimer);
+ refreshTimer = null;
+ disposeVideoToolbar?.();
+ disposeVideoToolbar = null;
+ // Release the old content before any stat/read request for the next
+ // file. Keep each lazily-created shell and its fixed listeners.
+ closeChatImageLightbox({ force: true });
+ await closeChatFileViewer({ force: true, keepShell: result.source.kind === 'video' });
+ document.getElementById('preview-loading').hidden = false;
+ await renderSource(result.source);
+ }
+ } while (replaceAgain && !closing);
+ } catch (_) {
+ await showFailure();
} finally { replacing = false; }
});
window.orkas.onPushEvent('preview-windows:gallery-refresh', () => {
@@ -69,6 +92,8 @@ const _convLog = createLogger('preview-host');
if (!result?.ok) await uiAlert(t('artifact.open_failed'));
};
function setupVideoToolbar() {
+ disposeVideoToolbar?.();
+ disposeVideoToolbar = null;
const viewer = document.querySelector('.chat-file-viewer');
const video = viewer?.querySelector('video');
if (!video) return;
@@ -82,18 +107,28 @@ const _convLog = createLogger('preview-host');
};
for (const event of ['pointermove', 'pointerdown', 'focusin', 'focusout']) viewer.addEventListener(event, wake);
for (const event of ['play', 'pause', 'ended', 'error']) video.addEventListener(event, wake);
- window.addEventListener('pagehide', () => clearTimeout(idleTimer), { once: true });
+ disposeVideoToolbar = () => {
+ clearTimeout(idleTimer);
+ for (const event of ['pointermove', 'pointerdown', 'focusin', 'focusout']) viewer.removeEventListener(event, wake);
+ for (const event of ['play', 'pause', 'ended', 'error']) video.removeEventListener(event, wake);
+ viewer.classList.remove('is-video-idle');
+ };
wake();
}
+ window.addEventListener('pagehide', () => { disposeVideoToolbar?.(); }, { once: true });
+ function applySourceContext(s) {
+ currentCid = s.options?.cid || s.cid || null;
+ projectScoped = !!s.options?.projectScoped;
+ document.title = s.title || 'Orkas';
+ }
async function initialize() {
await initI18n();
const result = await window.orkas.invoke('previewWindows.initialize');
if (!result?.ok || !result.source) throw new Error('preview_unavailable');
- const s = result.source;
- currentCid = s.options?.cid || s.cid || null;
- projectScoped = !!s.options?.projectScoped;
- document.title = s.title || 'Orkas';
- document.getElementById('preview-loading').hidden = true;
+ await renderSource(result.source, result);
+ }
+ async function renderSource(s, result = {}) {
+ applySourceContext(s);
if (s.kind === 'image') {
const gallery = s.gallery ? { ...s.gallery, selectedKey: s.gallery.items[s.gallery.index]?.key, src: s.src, busy: false } : null;
openChatImageLightbox(s.src, s.title, { ...s.options, gallery });
@@ -108,12 +143,17 @@ const _convLog = createLogger('preview-host');
if (!info?.ok || !info.url) throw new Error('application_unavailable');
window.openSavedAppPreview(info, s.title);
} else if (s.kind === 'artifact') window.openChatArtifactViewer(s);
+ document.getElementById('preview-loading').hidden = true;
setupVideoToolbar();
await window.orkas.invoke('previewWindows.ready');
}
- initialize().catch(async () => {
+ async function showFailure() {
document.getElementById('preview-loading').hidden = true;
+ // A replacement window is hidden until this document can be presented,
+ // including its failure dialog when initialization could not finish.
+ await window.orkas.invoke('previewWindows.ready');
await uiAlert(t('chat.preview_window_failed'));
await close();
- });
+ }
+ initialize().catch(showFailure);
})();
diff --git a/src/renderer/modules/preview-windows.js b/src/renderer/modules/preview-windows.js
index 141ccadd..54989c63 100644
--- a/src/renderer/modules/preview-windows.js
+++ b/src/renderer/modules/preview-windows.js
@@ -5,7 +5,6 @@
async function open(source) {
try {
const result = await window.orkas.invoke('previewWindows.open', source);
- if (window.OrkasCommercialEntry?.isFailure(result)) return result;
if (!result?.ok) throw new Error('preview_open_failed');
return result;
} catch (_) {
diff --git a/src/renderer/preview.html b/src/renderer/preview.html
index 46a3e2ee..8b5c4c79 100644
--- a/src/renderer/preview.html
+++ b/src/renderer/preview.html
@@ -23,6 +23,7 @@
<script src="./modules/text-view-edit.js"></script>
<script src="./modules/math.js"></script>
<script src="./modules/chat-lightbox.js"></script>
+ <script src="./modules/app-save-recovery.js"></script>
<script src="./modules/chat-file-viewer.js"></script>
<script src="./modules/dropdown-placement.js"></script>
<script src="./modules/connector-action-dialog.js"></script>
diff --git a/test/e2e/chat_lightbox_e2e_gallery.spec.ts b/test/e2e/chat_lightbox_e2e_gallery.spec.ts
index 3e044669..d067177a 100644
--- a/test/e2e/chat_lightbox_e2e_gallery.spec.ts
+++ b/test/e2e/chat_lightbox_e2e_gallery.spec.ts
@@ -9,12 +9,29 @@ const renderer = path.resolve(__dirname, '../../src/renderer');
const svg = 'data:image/svg+xml,' + encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" width="640" height="360"><rect width="640" height="360" fill="steelblue"/></svg>');
const picture = (id: string) => `<img id="${id}" class="chat-md-img" src="${svg}#${id}" alt="${id}">`;
+const capturedLogs = new WeakMap<Page, Array<{ level: string; message: string }>>();
+test.afterEach(async ({ page }, testInfo) => {
+ const captured = capturedLogs.get(page) || [];
+ await testInfo.attach('browser-log-audit.json', {
+ body: JSON.stringify({ total: captured.length,
+ unexpected: captured.map(log => ({ ...log, message: log.message.replace(/file:\/\/\/\S+/g, '[local-file]') })) }),
+ contentType: 'application/json',
+ });
+ expect(captured).toEqual([]);
+});
+
// Real renderer scripts and browser events; only IPC/history data is controlled.
// This suite owns gallery UI integration, not backend history or file permissions.
async function setup(page: Page, content: string) {
const errors: string[] = [];
- page.on('pageerror', (error) => errors.push(error.message));
+ const captured: Array<{ level: string; message: string }> = [];
+ capturedLogs.set(page, captured);
+ page.on('pageerror', (error) => {
+ errors.push(error.message);
+ captured.push({ level: 'error', message: error.message });
+ });
page.on('console', (message) => {
+ captured.push({ level: message.type(), message: message.text() });
if (message.type() === 'error' || message.type() === 'warning') errors.push(message.text());
});
await page.setContent(`<textarea id="composer"></textarea><div id="chat-history" class="chat-history">${content}</div><div class="chat-history">${picture('other-task')}</div>`);
diff --git a/test/e2e/preview_windows_e2e_lifecycle.spec.ts b/test/e2e/preview_windows_e2e_lifecycle.spec.ts
index 4a05bf97..907179ad 100644
--- a/test/e2e/preview_windows_e2e_lifecycle.spec.ts
+++ b/test/e2e/preview_windows_e2e_lifecycle.spec.ts
@@ -1,7 +1,7 @@
-import { appendFileSync, readFileSync } from 'node:fs';
+import { appendFileSync, readFileSync, writeFileSync } from 'node:fs';
import path from 'node:path';
import sharp from 'sharp';
-import { expect, test } from './fixtures/orkas';
+import { expect, test, OrkasTestApp } from './fixtures/orkas';
for (const locale of ['zh', 'en']) {
test(`attachment markdown images retain local file actions without empty chrome (${locale})`, async ({ modelOrkas: orkas }, info) => {
@@ -69,6 +69,128 @@ for (const locale of ['zh', 'en']) {
});
}
+test.describe('video replacement presentation', () => {
+ test.use({ orkas: async ({}, use, testInfo) => {
+ const app = new OrkasTestApp(testInfo, { nativeWindowVisible: true });
+ try { await app.launch(); await use(app); }
+ finally { await app.dispose(); }
+ } });
+
+ test('a second video never brings the previous video to the foreground while replacement is pending', async ({ orkas }, info) => {
+ const files = ['red', 'blue'].map(color => path.join(orkas.userWorkspaceRoot, `${color}.webm`));
+ await orkas.electronApp!.evaluate(async (_electron, args) => {
+ const req = (process as any).mainModule.require.bind((process as any).mainModule);
+ const { ffmpeg } = req(args.module).bundledFfmpegPaths();
+ for (const [index, file] of args.files.entries()) {
+ await new Promise<void>((resolve, reject) => req('node:child_process').execFile(ffmpeg, [
+ '-hide_banner', '-loglevel', 'error', '-y', '-f', 'lavfi',
+ '-i', `color=c=${index ? 'blue' : 'red'}:size=1920x1080:rate=30`, '-t', '1', '-an',
+ '-c:v', 'libvpx', '-threads', '1', file,
+ ], { windowsHide: true, timeout: 30000 }, (error: Error | null) => error ? reject(error) : resolve()));
+ }
+ }, { module: path.resolve(__dirname, '../../src/main/util/bundled-runtime.ts'), files });
+ const open = (file: string) => orkas.page!.evaluate(args =>
+ (window as any).openChatVideoUrlViewer((window as any)._chatMediaLocalUrl(args.file), args.title, { autoplay: true }),
+ { file, title: path.basename(file) });
+ const preview = await orkas.openPreview(() => open(files[0]));
+ const native = await orkas.electronApp!.browserWindow(preview);
+ expect(await native.evaluate(win => win.isFocusable())).toBe(true);
+ await expect(preview.locator('video')).toBeVisible();
+ await expect.poll(() => preview.locator('video').evaluate((video: HTMLVideoElement) => video.readyState)).toBeGreaterThanOrEqual(2);
+ const originalBounds = await native.evaluate(win => win.getBounds());
+ await native.evaluate(win => {
+ (win as any).previewHideCount = 0;
+ (win as any).previewHideCalls = 0;
+ const hide = win.hide.bind(win);
+ win.hide = () => { (win as any).previewHideCalls += 1; hide(); };
+ win.on('hide', () => { (win as any).previewHideCount += 1; });
+ });
+ await expect(preview.locator('.chat-file-viewer-share')).toHaveCount(0);
+ // Hold the old document alive to expose the interval that used to flash.
+ await preview.evaluate(() => {
+ (window as any).previousVideo = document.querySelector('video');
+ const shell = document.querySelector('.chat-file-viewer')!;
+ (window as any).videoShellHidden = false;
+ (window as any).videoShellObserver = new MutationObserver(() => {
+ if (!shell.classList.contains('is-open')) (window as any).videoShellHidden = true;
+ });
+ (window as any).videoShellObserver.observe(shell, { attributes: true, attributeFilter: ['class'] });
+ (window as any)._confirmDiscardViewerEdits = () => new Promise(resolve => {
+ (window as any).releaseReplacement = () => {
+ (window as any)._confirmDiscardViewerEdits = async () => true;
+ resolve(true);
+ };
+ });
+ });
+ await open(files[1]);
+ await expect.poll(() => native.evaluate(win => win.isVisible())).toBe(true);
+ await expect(preview).toHaveTitle('red.webm');
+ await expect.poll(() => preview.evaluate(() => typeof (window as any).releaseReplacement)).toBe('function');
+ await preview.evaluate(() => (window as any).releaseReplacement());
+ await expect(preview).toHaveTitle('blue.webm');
+ await expect(preview.locator('.chat-share-overlay')).toHaveCount(0);
+ await expect.poll(() => native.evaluate(win => win.isVisible())).toBe(true);
+ await expect(preview.locator('video')).toBeVisible();
+ await expect.poll(() => preview.locator('video').evaluate((video: HTMLVideoElement) => video.readyState)).toBeGreaterThanOrEqual(2);
+ expect(await preview.locator('video').evaluate((video: HTMLVideoElement) => video.currentSrc)).toContain('blue.webm');
+ expect(await preview.evaluate(() => {
+ const old = (window as any).previousVideo as HTMLVideoElement;
+ return { connected: old.isConnected, paused: old.paused, source: old.getAttribute('src'), state: old.readyState };
+ })).toEqual({ connected: false, paused: true, source: null, state: 0 });
+ expect(await preview.evaluate(() => (window as any).videoShellHidden)).toBe(false);
+ await preview.evaluate(() => { (window as any).videoShellObserver.disconnect(); delete (window as any).previousVideo; });
+ expect(await native.evaluate(win => win.getBounds())).toEqual(originalBounds);
+ await preview.screenshot({ path: info.outputPath('replacement-video.png') });
+ await native.evaluate(win => win.setSize(480, 360));
+ await preview.screenshot({ path: info.outputPath('replacement-video-small.png') });
+ const cdp = await orkas.electronApp!.context().newCDPSession(preview);
+ const resources = async () => {
+ await cdp.send('HeapProfiler.collectGarbage');
+ const heap = await cdp.send('Runtime.getHeapUsage');
+ const dom = await cdp.send('Memory.getDOMCounters');
+ return { heapBytes: heap.usedSize, ...dom };
+ };
+ const cpu = async () => {
+ const pid = await native.evaluate(win => win.webContents.getOSProcessId());
+ return orkas.electronApp!.evaluate(({ app }, pid) => app.getAppMetrics().find(metric => metric.pid === pid)?.cpu.cumulativeCPUUsage || 0, pid);
+ };
+ const before = await resources();
+ const cpuBefore = await cpu();
+ const timeOrigin = await preview.evaluate(() => performance.timeOrigin);
+ await preview.evaluate(() => { (window as any).originalViewerShell = document.querySelector('.chat-file-viewer'); });
+ let documentLoads = 0;
+ preview.on('domcontentloaded', () => { documentLoads += 1; });
+ const latencyMs: number[] = [];
+ for (let index = 0; index < 12; index += 1) {
+ const file = files[index % 2];
+ const started = performance.now();
+ await open(file);
+ await preview.waitForFunction(title => {
+ const video = document.querySelector('video');
+ return document.title === title && video && video.readyState >= 2;
+ }, path.basename(file), { polling: 10 });
+ latencyMs.push(Math.round((performance.now() - started) * 10) / 10);
+ }
+ const after = await resources();
+ const visibility = await native.evaluate(win => ({ hideCalls: (win as any).previewHideCalls, hideEvents: (win as any).previewHideCount }));
+ const metrics = { visibility, switches: latencyMs.length, latencyMs, documentLoads, rendererCpuSeconds: (await cpu()) - cpuBefore, before, after };
+ writeFileSync(info.outputPath('video-switch-performance.json'), JSON.stringify(metrics, null, 2));
+ await info.attach('video-switch-performance', { body: JSON.stringify(metrics), contentType: 'application/json' });
+ expect(await preview.evaluate(() => performance.timeOrigin)).toBe(timeOrigin);
+ expect(await preview.evaluate(() => (window as any).originalViewerShell === document.querySelector('.chat-file-viewer'))).toBe(true);
+ expect(documentLoads).toBe(0);
+ expect(await native.evaluate(win => (win as any).previewHideCount)).toBe(0);
+ expect(await preview.locator('video').count()).toBe(1);
+ // After collection, switching must not retain a document or listener set per video.
+ expect(after.documents).toBeLessThanOrEqual(before.documents);
+ expect(after.jsEventListeners).toBeLessThanOrEqual(before.jsEventListeners + 2);
+ await cdp.detach();
+ // Native destruction may finish before Playwright receives the key-up ack.
+ await preview.keyboard.press('Escape').catch(error => { if (!preview.isClosed()) throw error; });
+ await expect.poll(() => preview.isClosed()).toBe(true);
+ });
+});
+
test('task previews share one native window while different applications remain open together', async ({ orkas }, info) => {
const page = orkas.page!;
const expectBackgroundWindows = async () => {
@@ -372,5 +494,91 @@ test('presentation fills the native window and retains its slide content on resi
expect(actions.x + actions.width).toBeLessThanOrEqual(width);
await preview.screenshot({ path: info.outputPath(`ppt-window-${width}.png`) });
}
+ const timeOrigin = await preview.evaluate(() => performance.timeOrigin);
+ const blob = await frame.getAttribute('src');
+ await preview.evaluate(() => {
+ (window as any).oldOfficeFrame = document.querySelector('.chat-file-viewer-office');
+ (window as any).revokedPreviewUrls = [];
+ const revoke = URL.revokeObjectURL.bind(URL);
+ URL.revokeObjectURL = url => { (window as any).revokedPreviewUrls.push(url); revoke(url); };
+ });
+ const note = orkas.createWorkspaceFile('after-office.txt', 'Office resources released');
+ await orkas.page!.evaluate(file => (window as any).openChatFileViewer(file), note);
+ await expect(preview.locator('.chat-file-viewer-body')).toContainText('Office resources released');
+ expect(await preview.evaluate(() => (window as any).revokedPreviewUrls)).toContain(blob);
+ expect(await preview.evaluate(() => (window as any).oldOfficeFrame.contentWindow === null)).toBe(true);
+ await orkas.page!.evaluate(file => (window as any).openChatFileViewer(file), file);
+ await expect(frame.contentFrame().locator('body')).toContainText('Quarterly review');
+ expect(await frame.getAttribute('src')).not.toBe(blob);
+ expect(await preview.evaluate(() => performance.timeOrigin)).toBe(timeOrigin);
await orkas.closePreview(preview);
});
+
+test('mixed file previews reuse shells and release retired images audio and iframe documents', async ({ orkas }, info) => {
+ const text = orkas.createWorkspaceFile('reuse.txt', 'Text preview remains readable');
+ const image = orkas.createWorkspaceFile('reuse.svg', '<svg xmlns="http://www.w3.org/2000/svg" width="800" height="600"><rect width="800" height="600" fill="#4263eb"/></svg>');
+ const html = orkas.createWorkspaceFile('reuse.html', '<!doctype html><h1>HTML preview</h1>');
+ const open = (file: string) => orkas.page!.evaluate(file => (window as any).openChatFileViewer(file, file.split(/[\\/]/).pop()), file);
+ const preview = await orkas.openPreview(() => open(text));
+ const settled = async (file: string) => {
+ await preview.waitForFunction(name => document.title === name && (
+ name.endsWith('.svg') ? !!document.querySelector<HTMLImageElement>('.chat-lightbox-img')?.naturalWidth
+ : name.endsWith('.html') ? !!document.querySelector('.chat-file-viewer-html:not(.chat-file-viewer-loading-resource)') && !document.querySelector('.chat-file-viewer-body[aria-busy]')
+ : document.querySelector('.chat-file-viewer-body')?.textContent?.includes('Text preview remains readable')
+ ), path.basename(file), { polling: 10 });
+ };
+ await settled(text);
+ // Warm both shells and the HTML parser before measuring repeated use.
+ for (const file of [image, html, text]) { await open(file); await settled(file); }
+ const cdp = await orkas.electronApp!.context().newCDPSession(preview);
+ const resources = async () => {
+ await cdp.send('HeapProfiler.collectGarbage');
+ return { ...(await cdp.send('Memory.getDOMCounters')), heapBytes: (await cdp.send('Runtime.getHeapUsage')).usedSize };
+ };
+ const native = await orkas.electronApp!.browserWindow(preview);
+ const pid = await native.evaluate(win => win.webContents.getOSProcessId());
+ const cpu = () => orkas.electronApp!.evaluate(({ app }, pid) => app.getAppMetrics().find(m => m.pid === pid)?.cpu.cumulativeCPUUsage || 0, pid);
+ const before = await resources(), cpuBefore = await cpu();
+ const timeOrigin = await preview.evaluate(() => performance.timeOrigin);
+ await preview.evaluate(() => { (window as any).originalShell = document.querySelector('.chat-file-viewer'); });
+ let documentLoads = 0;
+ preview.on('domcontentloaded', () => { documentLoads += 1; });
+ const latencyMs: number[] = [];
+ for (let index = 0; index < 12; index += 1) {
+ const file = [image, html, text][index % 3];
+ const started = performance.now();
+ await open(file); await settled(file);
+ latencyMs.push(Math.round((performance.now() - started) * 10) / 10);
+ }
+ const after = await resources();
+ const metrics = { latencyMs, documentLoads, rendererCpuSeconds: (await cpu()) - cpuBefore, before, after };
+ writeFileSync(info.outputPath('file-switch-performance.json'), JSON.stringify(metrics, null, 2));
+ await preview.screenshot({ path: info.outputPath('reused-text.png') });
+ expect(await preview.evaluate(() => performance.timeOrigin)).toBe(timeOrigin);
+ expect(await preview.evaluate(() => (window as any).originalShell === document.querySelector('.chat-file-viewer'))).toBe(true);
+ expect(documentLoads).toBe(0);
+ expect(after.documents).toBeLessThanOrEqual(before.documents);
+ expect(after.jsEventListeners).toBeLessThanOrEqual(before.jsEventListeners + 2);
+ await open(image); await settled(image);
+ await preview.screenshot({ path: info.outputPath('reused-image.png') });
+ await preview.evaluate(() => { (window as any).oldImage = document.querySelector('.chat-lightbox-img'); });
+ await open(html); await settled(html);
+ expect(await preview.evaluate(() => (window as any).oldImage.getAttribute('src'))).toBeNull();
+ await preview.screenshot({ path: info.outputPath('reused-html.png') });
+ await preview.evaluate(() => { (window as any).oldFrame = document.querySelector('iframe'); });
+ await open(text); await settled(text);
+ expect(await preview.evaluate(() => ({ connected: (window as any).oldFrame.isConnected, window: (window as any).oldFrame.contentWindow }))).toEqual({ connected: false, window: null });
+ const wav = path.join(orkas.userWorkspaceRoot, 'reuse.wav');
+ const bytes = Buffer.alloc(44 + 16000);
+ bytes.write('RIFF'); bytes.writeUInt32LE(bytes.length - 8, 4); bytes.write('WAVEfmt ', 8); bytes.writeUInt32LE(16, 16);
+ bytes.writeUInt16LE(1, 20); bytes.writeUInt16LE(1, 22); bytes.writeUInt32LE(8000, 24); bytes.writeUInt32LE(16000, 28);
+ bytes.writeUInt16LE(2, 32); bytes.writeUInt16LE(16, 34); bytes.write('data', 36); bytes.writeUInt32LE(16000, 40);
+ writeFileSync(wav, bytes);
+ await open(wav);
+ await expect(preview.locator('audio')).toBeVisible();
+ await preview.evaluate(async () => { const audio = document.querySelector('audio')!; (window as any).oldAudio = audio; await audio.play(); });
+ await open(text); await settled(text);
+ expect(await preview.evaluate(() => { const a = (window as any).oldAudio; return { paused: a.paused, source: a.getAttribute('src'), state: a.readyState, connected: a.isConnected }; }))
+ .toEqual({ paused: true, source: null, state: 0, connected: false });
+ await cdp.detach();
+});
diff --git a/test/main/features/preview-windows.test.ts b/test/main/features/preview-windows.test.ts
index cfca19f4..bb90f023 100644
--- a/test/main/features/preview-windows.test.ts
+++ b/test/main/features/preview-windows.test.ts
@@ -1,7 +1,7 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import * as path from 'node:path';
-const runtime = vi.hoisted(() => ({ windows: [] as any[], hook: null as any, nextId: 0, appType: 'local', unsubscribe: vi.fn() }));
+const runtime = vi.hoisted(() => ({ windows: [] as any[], hook: null as any, nextId: 0, unsubscribe: vi.fn(), bus: null as any }));
vi.mock('electron', async () => {
const { EventEmitter } = await import('node:events');
class Contents extends EventEmitter {
@@ -14,7 +14,10 @@ vi.mock('electron', async () => {
id = ++runtime.nextId;
webContents = new Contents();
dead = false;
- show = vi.fn(); focus = vi.fn(); restore = vi.fn();
+ visible = false;
+ show = vi.fn(() => { this.visible = true; });
+ hide = vi.fn(() => { this.visible = false; });
+ focus = vi.fn(); restore = vi.fn();
isMinimized = () => false;
isFocusable = () => this.options.focusable !== false;
isDestroyed = () => this.dead;
@@ -26,14 +29,8 @@ vi.mock('electron', async () => {
}
return { BrowserWindow: Window, shell: { openExternal: vi.fn() }, screen: { getDisplayMatching: () => ({ workArea: { x: 0, y: 0, width: 1440, height: 900 } }) } };
});
-vi.mock('../../../src/main/features/saved_apps', () => ({
- resolveSavedAppType: async () => runtime.appType,
- resolveArtifactAppType: async () => runtime.appType,
- boundAppType: async () => undefined,
- managedPathAppType: async () => undefined,
-}));
vi.mock('../../../src/main/features/user-switch-hooks', () => ({ registerUserSwitchHook: (_name: string, fn: any) => { runtime.hook = fn; } }));
-vi.mock('../../../src/main/features/group_chat', () => ({ subscribeBus: () => runtime.unsubscribe }));
+vi.mock('../../../src/main/features/group_chat', () => ({ subscribeBus: (_uid: string, _cid: string, callback: any) => { runtime.bus = callback; return runtime.unsubscribe; } }));
vi.mock('../../../src/main/logger', () => ({ createLogger: () => ({ warn: vi.fn() }) }));
import { BrowserWindow } from 'electron';
@@ -42,24 +39,136 @@ import { openPreview, initializePreview, closePreview, setPreviewDirty, requestP
beforeEach(() => {
for (const win of runtime.windows) win.destroy();
runtime.windows.length = 0;
- runtime.appType = 'local';
runtime.unsubscribe.mockClear();
});
describe('independent preview ownership and lifecycle', () => {
- it.each(['web', 'cloud'])('refuses a %s preview before allocating, focusing or reusing a window', async appType => {
+ it('keeps the video window visible without reloading or raising stale content, including rapid selections', async () => {
const main = new BrowserWindow({});
- const local = { kind: 'app', appId: 'a', title: 'App' };
- await openPreview('user-a', main.webContents, local);
- const previous = runtime.windows[1]; previous.focus.mockClear(); previous.show.mockClear();
- runtime.appType = appType;
- for (const source of [local, { kind: 'artifact', cid: 'task', artifactId: 'result', title: 'Result' }]) {
- expect(await openPreview('user-a', main.webContents, source)).toMatchObject({ ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' });
- expect(runtime.windows).toHaveLength(2);
- expect(previous.focus).not.toHaveBeenCalled(); expect(previous.show).not.toHaveBeenCalled();
- }
+ const video = (name: string) => ({ kind: 'video', src: `chat-media://local/${name}.mp4`, title: name, options: {} });
+ await openPreview('user-a', main.webContents, video('first'));
+ const child = runtime.windows.at(-1);
+ readyPreview('user-a', child.webContents);
+ child.show.mockClear(); child.focus.mockClear();
+ await openPreview('user-a', main.webContents, video('second'));
+ expect(child.visible).toBe(true);
+ expect(child.show).not.toHaveBeenCalled();
+ expect(child.focus).not.toHaveBeenCalled();
+ expect(await replacePreview('user-a', child.webContents, true)).toEqual({ source: video('second') });
+ await openPreview('user-a', main.webContents, video('last'));
+ readyPreview('user-a', child.webContents);
+ expect(child.visible).toBe(true);
+ expect(child.show).not.toHaveBeenCalled();
+ expect(await replacePreview('user-a', child.webContents, true)).toEqual({ source: video('last') });
+ expect(initializePreview('user-a', child.webContents).source).toEqual(video('last'));
+ expect(child.loadFile).toHaveBeenCalledTimes(1);
+ expect(child.hide).not.toHaveBeenCalled();
+ readyPreview('user-a', child.webContents);
+ expect(child.visible).toBe(true);
+ expect(child.focus).toHaveBeenCalledOnce();
+ expect(runtime.windows).toHaveLength(2);
+ });
+
+ it('switches files and images in place, releases the previous gallery, and preserves a selection received while loading', async () => {
+ const main = new BrowserWindow({});
+ const image = (cid: string) => ({ kind: 'image', src: `chat-media://local/${cid}.png`, title: cid, options: { cid },
+ gallery: { cid, index: 0, nextCursor: null, items: [{ key: cid, src: cid, alt: cid }] } });
+ await openPreview('user-a', main.webContents, image('first'));
+ const child = runtime.windows.at(-1);
+ initializePreview('user-a', child.webContents); readyPreview('user-a', child.webContents);
+ const pending = requestPreviewOwner('user-a', child.webContents, { kind: 'gallery' });
+ const file = { kind: 'file', path: '/fixture/note.txt', title: 'Note', options: {} };
+ await openPreview('user-a', main.webContents, file);
+ expect(await replacePreview('user-a', child.webContents, true)).toEqual({ source: file });
+ expect(await pending).toEqual({ ok: false });
+ expect(runtime.unsubscribe).toHaveBeenCalledOnce();
+ await openPreview('user-a', main.webContents, image('latest'));
+ // A duplicate acknowledgement must not consume the pending selection.
+ await replacePreview('user-a', child.webContents, true);
+ readyPreview('user-a', child.webContents);
+ expect(await replacePreview('user-a', child.webContents, true)).toEqual({ source: image('latest') });
+ child.webContents.send.mockClear();
+ runtime.bus({ type: 'message' });
+ expect(child.webContents.send).toHaveBeenCalledWith('preview-windows:gallery-refresh', {});
+ readyPreview('user-a', child.webContents);
+ expect(child.loadFile).toHaveBeenCalledTimes(1);
+ expect(child.hide).not.toHaveBeenCalled();
+ });
+
+ it('restores the current preview if a pending selection is superseded by the current source', async () => {
+ const main = new BrowserWindow({});
+ const first = { kind: 'video', src: 'chat-media://local/first.mp4', title: 'First', options: {} };
+ await openPreview('user-a', main.webContents, first);
+ const child = runtime.windows.at(-1);
+ readyPreview('user-a', child.webContents);
+ await openPreview('user-a', main.webContents, { ...first, src: 'chat-media://local/second.mp4' });
+ expect(child.visible).toBe(true);
+ await openPreview('user-a', main.webContents, first);
+ await replacePreview('user-a', child.webContents, true);
+ expect(child.visible).toBe(true);
+ expect(initializePreview('user-a', child.webContents).source).toEqual(first);
+ expect(child.loadFile).toHaveBeenCalledTimes(1);
});
+ it('allows reopening after a replacement document fails to load instead of leaving a hidden window stuck', async () => {
+ const main = new BrowserWindow({});
+ const first = { kind: 'video', src: 'chat-media://local/first.mp4', title: 'First', options: {} };
+ const next = { kind: 'artifact', cid: 'task', artifactId: 'result', title: 'App' };
+ await openPreview('user-a', main.webContents, first);
+ const child = runtime.windows.at(-1);
+ readyPreview('user-a', child.webContents);
+ await openPreview('user-a', main.webContents, next);
+ child.loadFile.mockRejectedValueOnce(new Error('Fixture document load failure'));
+ await expect(replacePreview('user-a', child.webContents, true)).rejects.toThrow('Fixture document load failure');
+ expect(child.dead).toBe(true);
+ await openPreview('user-a', main.webContents, next);
+ const reopened = runtime.windows.at(-1);
+ expect(reopened).not.toBe(child);
+ expect(reopened.visible).toBe(true);
+ expect(initializePreview('user-a', reopened.webContents).source).toEqual(next);
+ });
+
+ it('keeps unsaved edits and their confirmation visible until replacement is accepted', async () => {
+ const main = new BrowserWindow({});
+ const file = { kind: 'file', path: '/fixture/note.md', title: 'Note', options: {} };
+ const video = { kind: 'video', src: 'chat-media://local/next.mp4', title: 'Next', options: {} };
+ await openPreview('user-a', main.webContents, file);
+ const child = runtime.windows.at(-1);
+ readyPreview('user-a', child.webContents);
+ setPreviewDirty('user-a', child.webContents, true);
+ await openPreview('user-a', main.webContents, video);
+ expect(child.visible).toBe(true);
+ await replacePreview('user-a', child.webContents, false);
+ expect(child.visible).toBe(true);
+ expect(initializePreview('user-a', child.webContents).source).toEqual(file);
+ await openPreview('user-a', main.webContents, video);
+ await replacePreview('user-a', child.webContents, true);
+ expect(child.visible).toBe(true);
+ expect(child.loadFile).toHaveBeenCalledTimes(1);
+ readyPreview('user-a', child.webContents);
+ expect(child.visible).toBe(true);
+ });
+
+ it('refreshes an open artifact in the same native window only for a newer revision of that app', async () => {
+ const main = new BrowserWindow({});
+ const source = { kind: 'artifact', cid: 'task', artifactId: 'one', title: 'Draft' };
+ await openPreview('user-a', main.webContents, source);
+ const child = runtime.windows.at(-1);
+ initializePreview('user-a', child.webContents); readyPreview('user-a', child.webContents);
+ expect(runtime.bus).toBeTypeOf('function');
+ runtime.bus({ type: 'artifact_created', artifact: { id: 'other', revision: 2 } });
+ expect(child.webContents.send).not.toHaveBeenCalled();
+ runtime.bus({ type: 'artifact_created', artifact: { id: 'one', title: 'Corrected', revision: 2 } });
+ expect(child.webContents.send).toHaveBeenCalledWith('preview-windows:replace-request', {});
+ await replacePreview('user-a', child.webContents, true);
+ expect(runtime.windows).toHaveLength(2);
+ expect(initializePreview('user-a', child.webContents).source).toEqual({ ...source, title: 'Corrected' });
+ readyPreview('user-a', child.webContents);
+ child.webContents.send.mockClear();
+ runtime.bus({ type: 'artifact_created', artifact: { id: 'one', title: 'Old', revision: 1 } });
+ runtime.bus({ type: 'artifact_created', artifact: { id: 'one', title: 'Corrected', revision: 2 } });
+ expect(child.webContents.send).not.toHaveBeenCalled();
+ });
it.each([false, true])('inherits owner focusability across every preview kind, including reopening minimized windows: %s', async (focusable) => {
const sources = [
{ kind: 'app', appId: 'a', title: 'App' },
@@ -78,8 +187,14 @@ describe('independent preview ownership and lifecycle', () => {
expect(child.show).toHaveBeenCalledTimes(focusable ? 1 : 0);
expect(child.focus).toHaveBeenCalledTimes(focusable ? 1 : 0);
if (!focusable) expect(child.options.webPreferences.backgroundThrottling).toBe(false);
+ readyPreview('user-a', child.webContents);
child.isMinimized = () => true;
- expect(await openPreview('user-a', main.webContents, source)).toEqual(result);
+ expect(await openPreview('user-a', main.webContents, source)).toEqual({ ...result, ...(source.kind === 'app' ? { reused: true } : {}) });
+ // Images refresh their gallery even when reopening the same selection.
+ if (source.kind === 'image') {
+ await replacePreview('user-a', child.webContents, true);
+ readyPreview('user-a', child.webContents);
+ }
expect(child.restore).toHaveBeenCalledTimes(focusable ? 1 : 0);
expect(child.show).toHaveBeenCalledTimes(focusable ? 2 : 0);
expect(child.focus).toHaveBeenCalledTimes(focusable ? 2 : 0);
@@ -160,7 +275,7 @@ describe('independent preview ownership and lifecycle', () => {
expect(initializePreview('user-a', child.webContents).source).toEqual(sources[index]);
expect(child.dead).toBe(false);
}
- expect(await openPreview('user-a', main.webContents, sources[0])).toEqual(opened[0]);
+ expect(await openPreview('user-a', main.webContents, sources[0])).toEqual({...opened[0], reused: true});
runtime.hook('user-a', 'user-b');
expect(runtime.windows.slice(1).every(child => child.dead && !isPreviewContents(child.webContents))).toBe(true);
expect(main.webContents.listenerCount('destroyed')).toBe(0);
diff --git a/test/renderer/chat-file-viewer.test.ts b/test/renderer/chat-file-viewer.test.ts
index 69b15d4a..f33a50ac 100644
--- a/test/renderer/chat-file-viewer.test.ts
+++ b/test/renderer/chat-file-viewer.test.ts
@@ -105,7 +105,7 @@ describe('file preview availability feedback', () => {
throw new Error(privateError);
});
const openChatImageLightbox = vi.fn();
- const context = vm.createContext({
+ const context = vm.createContext({ clearTimeout, setTimeout,
window: { orkas: { invoke } },
createLogger: () => ({ warn: (...args: unknown[]) => warnings.push(args), info: () => {}, error: () => {} }),
uiConfirm: vi.fn(async () => true),
@@ -139,7 +139,7 @@ describe('file preview availability feedback', () => {
setAttribute: vi.fn(),
};
const setDirty = vi.fn();
- const context = vm.createContext({
+ const context = vm.createContext({ clearTimeout, setTimeout,
window: { orkas: { invoke }, OrkasPreviewHost: { setDirty } },
createLogger: () => ({ warn: (...args: unknown[]) => warnings.push(args), info: () => {}, error: () => {} }),
uiConfirm: vi.fn(async () => false),
@@ -180,7 +180,7 @@ describe('file preview availability feedback', () => {
const uiToast = vi.fn();
const uiConfirm = vi.fn(async () => false);
const openChatImageLightbox = vi.fn();
- const context = vm.createContext({
+ const context = vm.createContext({ clearTimeout, setTimeout,
window: { orkas: { invoke } }, uiToast, uiConfirm, openChatImageLightbox,
console,
});
@@ -261,6 +261,25 @@ describe('chat-file-viewer › _viewerCanAddToLibrary', () => {
});
});
+describe('file-backed native video entry', () => {
+ it.each([true, false])('preserves file validation and playback context when normalizing a video source: exists=%s', async (exists) => {
+ const open = vi.fn();
+ const context: any = vm.createContext({ clearTimeout, setTimeout,
+ window: { orkas: { invoke: async () => ({ ok: true, exists, isFile: true }) },
+ OrkasPreviewWindows: { open, options: (value: unknown) => value } },
+ uiToast: vi.fn(),
+ });
+ vm.runInContext(readFileSync(require.resolve('../../src/renderer/modules/chat-file-viewer.js'), 'utf8'), context);
+ await context.openChatFileViewer('/fixture/clip.mp4', 'Clip', { cid: 'task', projectId: 'project', autoplay: true, startTime: 2 });
+ if (exists) expect(open).toHaveBeenCalledWith({ kind: 'video', src: 'chat-media://local/fixture/clip.mp4', title: 'Clip',
+ options: { cid: 'task', projectId: 'project', autoplay: true, startTime: 2, absPath: '/fixture/clip.mp4' } });
+ else {
+ expect(open).not.toHaveBeenCalled();
+ expect(context.uiToast).toHaveBeenCalledOnce();
+ }
+ });
+});
+
describe('chat-file-viewer › _viewerVideoPlaybackOptions', () => {
it('keeps explicit autoplay and a positive start time', () => {
expect(_viewerVideoPlaybackOptions({ autoplay: true, startTime: 12.5 })).toEqual({ autoplay: true, startTime: 12.5 });
diff --git a/test/renderer/file-preview-loading.test.ts b/test/renderer/file-preview-loading.test.ts
index b7498e6a..4f29f115 100644
--- a/test/renderer/file-preview-loading.test.ts
+++ b/test/renderer/file-preview-loading.test.ts
@@ -43,7 +43,6 @@ describe('file preview loading states', () => {
'_renderPdfBody',
'_renderHtmlBody',
'_renderOfficeBody',
- '_renderVideoBody',
'openChatVideoUrlViewer',
'_renderAudioBody',
'_renderMarkdownBody',
diff --git a/test/renderer/preview-host.test.ts b/test/renderer/preview-host.test.ts
index 6e8ba74e..87d40ab5 100644
--- a/test/renderer/preview-host.test.ts
+++ b/test/renderer/preview-host.test.ts
@@ -12,6 +12,66 @@ function host() {
}
const item = (key: string) => ({ key, src: key, alt: key });
+describe('in-place preview replacement', () => {
+ it('renders the latest queued selection and its context before acknowledging readiness', async () => {
+ const handlers = new Map<string, () => Promise<void>>();
+ const video = (title: string) => ({ kind: 'video', src: title, title, options: { cid: title, projectScoped: true } });
+ const opened: string[] = [];
+ let replacements = 0;
+ const invoke = vi.fn(async (channel: string) => {
+ if (channel === 'previewWindows.replace') return { ok: true, source: video(++replacements === 1 ? 'second' : 'latest') };
+ if (channel === 'previewWindows.ready' && replacements === 1) {
+ await handlers.get('preview-windows:replace-request')!();
+ }
+ return { ok: true };
+ });
+ const context: any = { createLogger: () => ({}), initI18n: () => new Promise(() => {}),
+ _confirmDiscardViewerEdits: async () => true,
+ openChatVideoUrlViewer: async (_src: string, title: string) => { opened.push(title); },
+ closeChatImageLightbox: vi.fn(), closeChatFileViewer: vi.fn(), clearTimeout,
+ document: { title: '', querySelector: () => null, getElementById: () => ({ hidden: true }) },
+ window: { orkas: { invoke, onPushEvent: (event: string, handler: any) => handlers.set(event, handler) }, addEventListener: vi.fn() } };
+ vm.runInNewContext(readFileSync(path.resolve(__dirname, '../../src/renderer/modules/preview-host.js'), 'utf8'), context);
+ await handlers.get('preview-windows:replace-request')!();
+ expect(opened).toEqual(['second', 'latest']);
+ expect(context.document.title).toBe('latest');
+ expect(context.window.OrkasPreviewHost.projectScopedFor('latest')).toBe(true);
+ expect(context.window.OrkasPreviewHost.projectScopedFor('second')).toBe(false);
+ expect(invoke.mock.calls.map(([channel]) => channel)).toEqual([
+ 'previewWindows.replace', 'previewWindows.ready', 'previewWindows.replace', 'previewWindows.ready',
+ ]);
+ });
+});
+
+describe('retired gallery requests', () => {
+ it('ignores a late image-list reply after switching to a different file', async () => {
+ const handlers = new Map<string, () => Promise<void>>();
+ let resolvePage: (result: any) => void = () => {};
+ const invoke = vi.fn(async (channel: string) => {
+ if (channel === 'previewWindows.requestOwner') return new Promise(resolve => { resolvePage = resolve; });
+ if (channel === 'previewWindows.replace') return { source: { kind: 'file', path: '/new.txt', title: 'New', options: {} } };
+ return { ok: true };
+ });
+ const cleared: string[] = [];
+ const context: any = { clearTimeout, createLogger: () => ({}), initI18n: () => new Promise(() => {}),
+ _confirmDiscardViewerEdits: async () => true, _updateLightboxNavigation: vi.fn(),
+ closeChatImageLightbox: (opts: any) => { expect(opts.force).toBe(true); cleared.push('image'); },
+ closeChatFileViewer: (opts: any) => { expect(opts.force).toBe(true); cleared.push('file'); },
+ openChatFileViewer: async () => { expect(cleared).toEqual(['image', 'file']); }, _isViewerOpen: () => true,
+ document: { title: '', querySelector: () => null, getElementById: () => ({ hidden: true }) },
+ window: { orkas: { invoke, onPushEvent: (name: string, fn: any) => handlers.set(name, fn) }, addEventListener: vi.fn() } };
+ vm.runInNewContext(readFileSync(path.resolve(__dirname, '../../src/renderer/modules/preview-host.js'), 'utf8'), context);
+ const gallery = { items: [item('old')], nextCursor: 10 };
+ const request = context.window.OrkasPreviewHost.loadGalleryPage(gallery, 10);
+ await handlers.get('preview-windows:replace-request')!();
+ resolvePage({ ok: true, items: [item('late')], nextCursor: null });
+ await request;
+ expect(gallery).toEqual({ items: [item('old')], nextCursor: 10 });
+ expect(context._updateLightboxNavigation).not.toHaveBeenCalled();
+ expect(context.document.title).toBe('New');
+ });
+});
+
describe('native image history', () => {
it('keeps chronological order when a refresh overlaps a shorter opening snapshot and when older pages arrive', async () => {
const { api, invoke } = host();
@@ -60,12 +120,54 @@ describe('non-conversation image previews', () => {
});
-it('preserves a structured commercial refusal for the invoking viewer to present', async () => {
- const receipt = { ok: false, code: 'E_COMMERCIAL_REQUIRED', feature: 'web_apps' };
+it('presents one localized error when the main preview adapter rejects an open', async () => {
+ const receipt = { ok: false, code: 'E_MANIFEST' };
const alert = vi.fn(), invoke = vi.fn(async () => receipt);
- const context: any = { uiAlert: alert, window: { orkas: { invoke, onPushEvent: vi.fn() } } };
- vm.runInNewContext(readFileSync(path.resolve(__dirname, '../../src/renderer/modules/commercial-entry.js'), 'utf8'), context);
+ const context: any = { t: (key:string) => key, uiAlert: alert, window: { orkas: { invoke, onPushEvent: vi.fn() } } };
vm.runInNewContext(readFileSync(path.resolve(__dirname, '../../src/renderer/modules/preview-windows.js'), 'utf8'), context);
- await expect(context.window.OrkasPreviewWindows.open({ kind: 'file', path: '/fixture/app.html' })).resolves.toBe(receipt);
- expect(alert).not.toHaveBeenCalled(); expect(invoke).toHaveBeenCalledOnce();
+ await expect(context.window.OrkasPreviewWindows.open({ kind: 'file', path: '/fixture/app.html' })).resolves.toEqual({ok:false});
+ expect(alert).toHaveBeenCalledExactlyOnceWith('chat.preview_window_failed');
+ expect(invoke).toHaveBeenCalledExactlyOnceWith('previewWindows.open', {kind:'file',path:'/fixture/app.html'});
+});
+
+
+describe('saved app window readiness and failure recovery', () => {
+ async function openAppWindow(openInApp: () => Promise<any>) {
+ const invoke = vi.fn(async (channel: string) => {
+ if (channel === 'previewWindows.initialize') return {ok:true,source:{kind:'app',appId:'fixture-app',title:'Fixture app'}};
+ if (channel === 'savedApps.openInApp') return openInApp();
+ return {ok:true};
+ });
+ const context: any = {
+ createLogger: () => ({}), initI18n: async () => {}, uiAlert: vi.fn(async () => {}), t: (key: string) => key,
+ _confirmDiscardViewerEdits: async () => true, refreshLangFromMain: async () => {},
+ document: {title:'',getElementById:() => ({hidden:false}),querySelector:() => null},
+ window: {orkas:{invoke,onPushEvent:vi.fn()},addEventListener:vi.fn(),openSavedAppPreview:vi.fn()},
+ };
+ vm.runInNewContext(readFileSync(path.resolve(__dirname, '../../src/renderer/modules/preview-host.js'), 'utf8'), context);
+ await vi.waitFor(() => expect(invoke.mock.calls.some(([channel]) => channel === 'previewWindows.ready' || channel === 'previewWindows.close')).toBe(true));
+ return {invoke,context};
+ }
+
+ it('mounts the app before acknowledging a ready native window', async () => {
+ const {invoke,context} = await openAppWindow(async () => ({ok:true,url:'chat-app://fixture/index.html'}));
+ expect(context.window.openSavedAppPreview).toHaveBeenCalledExactlyOnceWith({ok:true,url:'chat-app://fixture/index.html'},'Fixture app');
+ const ready = invoke.mock.calls.findIndex(([channel]) => channel === 'previewWindows.ready');
+ expect(invoke.mock.invocationCallOrder[ready]).toBeGreaterThan(context.window.openSavedAppPreview.mock.invocationCallOrder[0]);
+ expect(context.document.title).toBe('Fixture app');
+ expect(context.uiAlert).not.toHaveBeenCalled();
+ expect(invoke.mock.calls.some(([channel]) => channel === 'previewWindows.close')).toBe(false);
+ });
+
+ it('presents the failure dialog before closing and never mounts a rejected runtime', async () => {
+ const {invoke,context} = await openAppWindow(async () => ({ok:false,code:'E_MANIFEST',error:'Private localized path'}));
+ await vi.waitFor(() => expect(invoke).toHaveBeenCalledWith('previewWindows.close'));
+ expect(context.window.openSavedAppPreview).not.toHaveBeenCalled();
+ expect(context.uiAlert).toHaveBeenCalledExactlyOnceWith('chat.preview_window_failed');
+ const ready = invoke.mock.calls.findIndex(([channel]) => channel === 'previewWindows.ready');
+ const close = invoke.mock.calls.findIndex(([channel]) => channel === 'previewWindows.close');
+ expect(ready).toBeGreaterThanOrEqual(0);
+ expect(invoke.mock.invocationCallOrder[ready]).toBeLessThan(context.uiAlert.mock.invocationCallOrder[0]);
+ expect(invoke.mock.invocationCallOrder[close]).toBeGreaterThan(context.uiAlert.mock.invocationCallOrder[0]);
+ });
});
diff --git a/test/renderer/video-viewer-lifecycle.test.ts b/test/renderer/video-viewer-lifecycle.test.ts
new file mode 100644
index 00000000..03f21b19
--- /dev/null
+++ b/test/renderer/video-viewer-lifecycle.test.ts
@@ -0,0 +1,147 @@
+import { readFileSync } from 'node:fs';
+import path from 'node:path';
+import vm from 'node:vm';
+import { describe, expect, it, vi } from 'vitest';
+
+class Element extends EventTarget {
+ children: Element[] = [];
+ attributes = new Map<string, string>();
+ classes = new Set<string>();
+ className = '';
+ dataset = {};
+ classList = { add: (...names: string[]) => names.forEach(name => this.classes.add(name)),
+ remove: (...names: string[]) => names.forEach(name => this.classes.delete(name)) };
+ appendChild(child: Element) { this.children.push(child); }
+ contains(child: Element): boolean { return this.children.includes(child) || this.children.some(node => node.contains(child)); }
+ setAttribute(name: string, value: string) { this.attributes.set(name, value); }
+ removeAttribute(name: string) { this.attributes.delete(name); }
+ getAttribute(name: string) { return this.attributes.get(name) ?? null; }
+ set innerHTML(_value: string) { this.children = []; }
+ querySelector() { return null; }
+}
+
+class Video extends Element {
+ readyState = 0;
+ currentTime = 0;
+ duration = 10;
+ paused = true;
+ play = vi.fn(async () => { this.paused = false; });
+ pause = vi.fn(() => { this.paused = true; });
+ load = vi.fn(() => { this.readyState = 0; });
+ set src(value: string) { this.setAttribute('src', value); }
+}
+
+function viewer() {
+ const videos: Video[] = [];
+ const body = new Element();
+ const context = vm.createContext({
+ window: {}, escapeHtml: String, body, setTimeout, clearTimeout,
+ document: { addEventListener: vi.fn(), createElement: (tag: string) => {
+ if (tag !== 'video') return new Element();
+ const video = new Video(); videos.push(video); return video;
+ } },
+ });
+ vm.runInContext(readFileSync(path.resolve(__dirname, '../../src/renderer/modules/chat-file-viewer.js'), 'utf8'), context);
+ // Isolate native shell construction; exercise the real media creation,
+ // teardown, pending playback callbacks and loading-state ownership.
+ vm.runInContext(`var originalOpenViewerShell = _openViewerShell; _viewerBody = body;
+ _openViewerShell = async () => { _teardownViewerContent(); return ++_viewerRenderSeq; };`, context);
+ return { body, videos, context,
+ open: (src: string) => context.openChatVideoUrlViewer(src, src, { autoplay: true, startTime: 3 }),
+ openLocal: () => context._renderVideoBody('/fixture/local.mp4', 'Local', null, null, { autoplay: true }),
+ close: () => context._teardownViewerContent('closed') };
+}
+
+describe('video media lifecycle', () => {
+ it.each(['local', 'url'])('keeps the %s player reachable through the delegated playback surface', async entry => {
+ const h = viewer();
+ if (entry === 'local') await h.openLocal();
+ else await h.open('https://example.com/preview.mp4');
+ expect(h.body.children).toHaveLength(1);
+ expect(h.body.children[0].dataset).toEqual({ chatVideoPlaybackSurface: 'floating_player' });
+ expect(h.body.children[0].children).toEqual([h.videos[0]]);
+ h.close();
+ expect(h.videos[0].getAttribute('src')).toBeNull();
+ });
+
+ it('releases a pending video and ignores its late metadata/errors while the new video loads', async () => {
+ const h = viewer();
+ await h.open('chat-media://local/first.mp4');
+ const old = h.videos[0];
+ await h.open('chat-media://local/second.mp4');
+ const current = h.videos[1];
+ expect(old.paused).toBe(true);
+ expect(old.getAttribute('src')).toBeNull();
+ expect(old.load).toHaveBeenCalledOnce();
+ const oldPlayCount = old.play.mock.calls.length;
+ old.dispatchEvent(new Event('loadedmetadata'));
+ old.dispatchEvent(new Event('error'));
+ expect(old.play).toHaveBeenCalledTimes(oldPlayCount);
+ expect(h.body.getAttribute('aria-busy')).toBe('true');
+ current.dispatchEvent(new Event('loadedmetadata'));
+ expect(h.body.getAttribute('aria-busy')).toBeNull();
+ expect(current.currentTime).toBe(3);
+ h.close();
+ expect(current.paused).toBe(true);
+ expect(current.getAttribute('src')).toBeNull();
+ expect(h.body.children).toHaveLength(0);
+ });
+
+ it('settles a failed video and can open another video without keeping its source alive', async () => {
+ const h = viewer();
+ await h.openLocal();
+ const failed = h.videos[0];
+ failed.dispatchEvent(new Event('error'));
+ expect(h.body.getAttribute('aria-busy')).toBeNull();
+ await h.open('chat-media://local/recovered.mp4');
+ h.videos[1].dispatchEvent(new Event('loadedmetadata'));
+ expect(failed.getAttribute('src')).toBeNull();
+ expect(h.body.contains(failed)).toBe(false);
+ expect(h.body.contains(h.videos[1])).toBe(true);
+ expect(h.body.getAttribute('aria-busy')).toBeNull();
+ });
+});
+
+
+describe('file action ownership after replacement', () => {
+ it('resets completed action icons and disabled buttons when opening the next file', async () => {
+ const h = viewer();
+ h.context.window.uiIconHtml = (name: string) => name;
+ vm.runInContext(`
+ _viewerEl = body; _ensureViewer = () => body; _viewerTitle = {};
+ _viewerAddLibraryBtn = { innerHTML: 'check', disabled: true };
+ _viewerSaveAppBtn = { innerHTML: 'check' };
+ _refreshSaveAppButton = async () => {};
+ `, h.context);
+ await h.context.originalOpenViewerShell('next.html', { kind: 'html', absPath: '/next.html' });
+ expect(vm.runInContext('_viewerSaveAppBtn.innerHTML', h.context)).toBe('layout-grid');
+ expect(vm.runInContext('_viewerAddLibraryBtn.innerHTML', h.context)).toBe('database');
+ expect(vm.runInContext('_viewerAddLibraryBtn.disabled', h.context)).toBe(false);
+ });
+
+ it('does not apply an old bundle inspection or delayed library-button reset to a newly opened file', async () => {
+ vi.useFakeTimers();
+ try {
+ const h = viewer();
+ let finish: (value: any) => void = () => {};
+ h.context.window.orkas = { invoke: () => new Promise(resolve => { finish = resolve; }) };
+ vm.runInContext(`
+ _viewerCurrentPath = '/same.html'; _viewerCurrentCid = 'first';
+ _viewerSaveAppBtn = { dataset: {}, hidden: false };
+ _viewerAddLibraryBtn = { innerHTML: 'first', disabled: true };
+ _setSaveAppVisible = value => { _viewerSaveAppBtn.hidden = !value; };
+ _setViewerButtonLabel = () => {};
+ _isViewerOpen = () => true;
+ `, h.context);
+ const inspect = h.context._refreshSaveAppButton('/same.html');
+ h.context._scheduleAddLibraryButtonRestore('first', 0);
+ vm.runInContext(`_viewerRenderSeq++; _viewerCurrentCid = 'next';
+ _viewerAddLibraryBtn.innerHTML = 'next'; _viewerSaveAppBtn.hidden = true;`, h.context);
+ finish({ ok: true, canSave: true, target: {} });
+ await inspect;
+ await vi.runAllTimersAsync();
+ expect(vm.runInContext('_viewerSaveAppBtn.hidden', h.context)).toBe(true);
+ expect(vm.runInContext('_viewerAddLibraryBtn.innerHTML', h.context)).toBe('next');
+ } finally { vi.useRealTimers(); }
+ });
+});