Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/apps/desktop/capabilities/default.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "OpenBitFun default capabilities",
"windows": ["main", "agent-companion-pet", "spotlight", "frontend-update-confirm"],
"windows": ["main", "agent-companion-pet", "spotlight", "frontend-update-confirm", "detached-canvas-*"],
"permissions": [
"log:default",
"autostart:default",
Expand Down
10 changes: 9 additions & 1 deletion src/web-ui/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -403,7 +403,8 @@
<script>
(function () {
var params = new URLSearchParams(window.location.search);
var isPetWindow = params.get('openbitfunWindow') === 'agent-companion';
var windowKind = params.get('openbitfunWindow');
var isPetWindow = windowKind === 'agent-companion';
var messages = window.__OPENBITFUN_RESOLVE_BOOTSTRAP_MESSAGES__();
var locale = window.__OPENBITFUN_RESOLVE_BOOTSTRAP_LOCALE__();
var startupOverlay = document.getElementById('openbitfun-startup-overlay');
Expand All @@ -421,6 +422,13 @@
return;
}

// Auxiliary windows mount without the product shell, so nothing will
// ever emit the overlay-hidden signal. Their chrome is their own.
if (windowKind === 'detached-canvas') {
if (startupOverlay) startupOverlay.remove();
return;
}

var hint = document.querySelector('.splash-screen__message');
var controls = document.querySelector('[data-startup-window-controls]');
function setButtonLabel(button, label) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
/**
* Canvas host for a detached window.
*
* Boots empty, asks the docking window for the scope it handed over, and owns
* that scope until it is recalled or this window closes. Everything the user
* does here stays in this window's stores; only the finished scope travels back.
*/

import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { CornerUpLeft } from 'lucide-react';
import { Icon, IconButton, Tooltip } from '@openbitfun/ui';
import { ContentCanvas } from '../panels/content-canvas';
import {
DETACHED_CANVAS_CHANNEL,
createDetachedCanvasToken,
type DetachedCanvasMessage,
type DetachedCanvasWindowParams,
} from '../panels/content-canvas/transfer/detachedCanvasProtocol';
import {
applyAgentCanvasScopeState,
readAgentCanvasScopeState,
type CanvasStoreState,
} from '../panels/content-canvas/stores';
import { createCanvasTransferChannel } from '@/infrastructure/runtime/canvasTransferChannel';
import { closeCurrentWindow } from '@/infrastructure/runtime/detachedWindow';
import { useI18n } from '@/infrastructure/i18n';
import { createLogger } from '@/shared/utils/logger';

import './DetachedCanvasWindow.scss';

const log = createLogger('DetachedCanvasHost');

/** The docking window may still be mounting when this window comes up. */
const HANDSHAKE_RETRY_INTERVAL_MS = 600;
const HANDSHAKE_MAX_ATTEMPTS = 25;

export interface DetachedCanvasHostProps {
params: DetachedCanvasWindowParams;
}

export const DetachedCanvasHost: React.FC<DetachedCanvasHostProps> = ({ params }) => {
const { t } = useI18n('components');
const [isReady, setIsReady] = useState(false);
const ownsScopeRef = useRef(false);
const channel = useMemo(
() => createCanvasTransferChannel(DETACHED_CANVAS_CHANNEL, `detached-${createDetachedCanvasToken()}`),
[],
);

/** Hand the live scope back. Safe to call more than once. */
const returnScope = useCallback(() => {
if (!ownsScopeRef.current) return;
ownsScopeRef.current = false;
const snapshot = readAgentCanvasScopeState();
channel.publish({
sourceId: channel.sourceId,
token: params.token,
kind: 'returned',
state: snapshot.state,
});
}, [channel, params.token]);

const returnAndClose = useCallback(() => {
returnScope();
// Give the transport a frame to flush before the window goes away.
window.setTimeout(() => { void closeCurrentWindow(); }, 0);
}, [returnScope]);

useEffect(() => {
const unsubscribe = channel.subscribe((message: DetachedCanvasMessage) => {
if (message.token !== params.token) return;
if (message.kind === 'snapshot') {
if (message.scopeKey !== params.scopeKey) return;
applyAgentCanvasScopeState(params.scopeKey, message.state as CanvasStoreState);
ownsScopeRef.current = true;
setIsReady(true);
channel.publish({ sourceId: channel.sourceId, token: params.token, kind: 'ready' });
return;
}
if (message.kind === 'recall') {
returnAndClose();
}
});
return unsubscribe;
}, [channel, params.scopeKey, params.token, returnAndClose]);

// Ask repeatedly until the docking window answers: a single early handshake
// would be lost if that window is still finishing its own mount.
useEffect(() => {
let attempts = 0;
const request = () => {
if (ownsScopeRef.current || attempts >= HANDSHAKE_MAX_ATTEMPTS) return;
attempts += 1;
channel.publish({
sourceId: channel.sourceId,
token: params.token,
kind: 'handshake',
scopeKey: params.scopeKey,
});
};
request();
const timer = window.setInterval(() => {
if (ownsScopeRef.current || attempts >= HANDSHAKE_MAX_ATTEMPTS) {
window.clearInterval(timer);
return;
}
request();
}, HANDSHAKE_RETRY_INTERVAL_MS);
return () => window.clearInterval(timer);
}, [channel, params.scopeKey, params.token]);

// A window closed by the user (window chrome, OS shortcut) must still return
// its scope; `pagehide` is the last point where the transport is usable.
useEffect(() => {
const handleHide = () => returnScope();
window.addEventListener('pagehide', handleHide);
window.addEventListener('beforeunload', handleHide);
return () => {
window.removeEventListener('pagehide', handleHide);
window.removeEventListener('beforeunload', handleHide);
};
}, [returnScope]);

useEffect(() => {
if (!isReady) return;
log.debug('Detached canvas window owns its scope', { scopeKey: params.scopeKey });
}, [isReady, params.scopeKey]);

const toolbarActions = (
<Tooltip content={t('canvas.returnToMainWindow')} placement="bottom">
<IconButton
size="sm"
aria-label={t('canvas.returnToMainWindow')}
icon={<Icon glyph={CornerUpLeft} size="sm" />}
onClick={event => {
event.stopPropagation();
returnAndClose();
}}
/>
</Tooltip>
);

return (
<div
className="openbitfun-detached-canvas"
data-openbitfun-component="content-canvas"
data-openbitfun-part="root"
data-openbitfun-mode="agent"
data-openbitfun-state={isReady ? undefined : 'empty'}
>
{isReady ? (
<ContentCanvas
workspacePath={params.workspacePath || undefined}
mode="agent"
isSceneActive
onCollapsePanel={returnAndClose}
toolbarActions={toolbarActions}
missionControlEnabled={false}
emptyState={(
<div
className="openbitfun-detached-canvas__empty-state"
data-openbitfun-component="content-canvas"
data-openbitfun-part="emptyContent"
>
<p>{t('canvas.noContentOpen')}</p>
</div>
)}
/>
) : (
<div
className="openbitfun-detached-canvas__connecting"
data-openbitfun-component="content-canvas"
data-openbitfun-part="emptyContent"
role="status"
>
{t('canvas.detachedConnecting')}
</div>
)}
</div>
);
};

DetachedCanvasHost.displayName = 'DetachedCanvasHost';

export default DetachedCanvasHost;
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/**
* Detached canvas window chrome. The window has no app shell around it, so the
* root owns the surface color the canvas used to inherit from the session scene.
*/

.openbitfun-detached-canvas {
display: flex;
flex-direction: column;
width: 100vw;
height: 100vh;
min-width: 0;
min-height: 0;
overflow: hidden;
background: var(--openbitfun-color-surface-canvas);
color: var(--openbitfun-color-content-primary);
font-family: var(--openbitfun-type-body-sm-font-family);
font-size: var(--openbitfun-type-body-sm-font-size);
font-weight: var(--openbitfun-type-body-sm-font-weight);
line-height: var(--openbitfun-type-body-sm-line-height);
letter-spacing: var(--openbitfun-type-body-sm-letter-spacing);

> * {
flex: 1 1 auto;
min-width: 0;
min-height: 0;
}

&__connecting,
&__empty-state {
display: grid;
place-items: center;
flex: 1;
min-width: 0;
min-height: 0;
padding: var(--openbitfun-space-6);
color: var(--openbitfun-color-content-muted);
text-align: center;
}

&--invalid {
place-items: center;
color: var(--openbitfun-color-content-muted);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
/**
* Root of the detached canvas window (`?openbitfunWindow=detached-canvas`).
*
* The window starts empty and receives its scope from the docking window, so it
* only needs the providers the canvas itself reads: workspace context for file
* resolution and the runtime window adapter it already has.
*/

import React, { useEffect, useMemo } from 'react';
import { WorkspaceProvider } from '@/infrastructure/contexts/WorkspaceProvider';
import { useI18n } from '@/infrastructure/i18n';
import {
readDetachedCanvasWindowParams,
type DetachedCanvasWindowParams,
} from '../panels/content-canvas/transfer/detachedCanvasProtocol';
import DetachedCanvasHost from './DetachedCanvasHost';

import './DetachedCanvasWindow.scss';

export const DetachedCanvasWindow: React.FC = () => {
const { t } = useI18n('components');
const params = useMemo<DetachedCanvasWindowParams | null>(
() => (typeof window === 'undefined' ? null : readDetachedCanvasWindowParams(window.location.search)),
[],
);

useEffect(() => {
if (!params) return;
document.title = params.title || t('canvas.detachedWindowTitle');
}, [params, t]);

if (!params) {
return (
<div
className="openbitfun-detached-canvas openbitfun-detached-canvas--invalid"
data-openbitfun-component="content-canvas"
data-openbitfun-part="emptyContent"
role="alert"
>
{t('canvas.detachedWindowInvalid')}
</div>
);
}

return (
<WorkspaceProvider>
<DetachedCanvasHost params={params} />
</WorkspaceProvider>
);
};

DetachedCanvasWindow.displayName = 'DetachedCanvasWindow';

export default DetachedCanvasWindow;
2 changes: 2 additions & 0 deletions src/web-ui/src/app/components/DetachedCanvasWindow/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { DetachedCanvasWindow, default } from './DetachedCanvasWindow';
export type { DetachedCanvasHostProps } from './DetachedCanvasHost';
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ import { normalizePath } from '@/shared/utils/pathUtils';

// ==================== Store State Types ====================

interface CanvasStoreState {
export interface CanvasStoreState {
/** Live content scope, committed with scope swaps and excluded from snapshots. */
scopeKey?: string;
primaryGroup: EditorGroupState;
Expand Down Expand Up @@ -1321,8 +1321,44 @@ export function switchAgentCanvasScope(nextScopeId: string | null | undefined):

}

const selectWholeCanvasStore = (state: CanvasStore) => state;
/**
* Snapshot the live agent scope so another window can become its owner.
* `scopeKey` stays out of the payload's own fields; the caller carries it.
*/
export function readAgentCanvasScopeState(): { scopeKey: string; state: CanvasStoreState } {
const live = useAgentCanvasStore.getState() as CanvasStore;
return {
scopeKey: live.scopeKey ?? normalizeAgentScopeKey(null),
state: extractAgentPersistableState(live),
};
}

/**
* Install a scope handed over by another window. The receiver owns the scope
* from here on, so any snapshot it still held for that id is discarded.
*/
export function applyAgentCanvasScopeState(scopeKey: string, state: CanvasStoreState): void {
const clone = structuredClone(state);
clone.scopeKey = scopeKey;
clone.isMissionControlOpen = false;
clone.draggingTabId = null;
clone.draggingFromGroupId = null;
agentScopeSnapshots.delete(scopeKey);
useAgentCanvasStore.setState(clone);
}

/**
* Give up ownership of the live agent scope in place: empty the canvas and
* forget its snapshot, so a later scope swap cannot resurrect content that now
* lives in another window.
*/
export function releaseAgentCanvasScope(): void {
const key = (useAgentCanvasStore.getState() as CanvasStore).scopeKey;
if (key !== undefined) agentScopeSnapshots.delete(key);
applyEmptyAgentCanvas(key);
}

const selectWholeCanvasStore = (state: CanvasStore) => state;
export function useCanvasStore(): CanvasStore;
export function useCanvasStore<T>(selector: (state: CanvasStore) => T): T;
export function useCanvasStore<T>(selector?: (state: CanvasStore) => T): T | CanvasStore {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ export {
useDragging,
switchAgentCanvasScope,
clearAgentCanvasForPeerSwitch,
readAgentCanvasScopeState,
applyAgentCanvasScopeState,
releaseAgentCanvasScope,
} from './canvasStore';
export type { CanvasStoreState } from './canvasStore';
Loading
Loading