Files
kandev/apps/web/lib/layout/panel-portal-host.tsx
T
José Almeida 45ee2ff48f feat: key terminals + dockview layout to TaskEnvironment (#755)
* feat(backend): key user shells by TaskEnvironmentID

Sessions in the same task share a TaskEnvironment. Re-key the user shell
runner so terminals are scoped per env, not per session — switching between
sessions of the same task now sees the same shell list.

- Add TaskEnvironmentID to AgentExecution / LaunchRequest / ExecutorCreateRequest
  / executor.LaunchAgentRequest, propagated through ToAgentExecution and the
  orchestrator launch path.
- Add Manager.ResolveScopeKey(sessionID) — returns env when execution carries
  it, falls back to sessionID for legacy paths.
- Rename runner param sessionID -> scopeID in interactive_shells.go; map keys
  are now scopeID:terminalID.
- Shell handlers + WS terminal handler resolve sid -> scopeID via
  ResolveScopeKey before calling the runner.

* feat(web): key dockview layout + portals to TaskEnvironmentID

Switching between sessions of the same task no longer rebuilds the dockview
layout — terminals and panels persist because layouts are env-scoped, not
session-scoped. The bottom terminal also reuses a stable sessionId across
same-env switches so it doesn't reconnect to a different shell.

- Rename layout persistence: setSessionLayout/getSessionLayout/*SessionMaximizeState
  -> setEnvLayout/getEnvLayout/*EnvMaximizeState (kandev.dockview.env-layout. prefix).
- Rename dockview-session-switch.ts -> dockview-env-switch.ts; performSessionSwitch
  -> performEnvSwitch with oldEnvId/newEnvId/activeSessionId.
- dockview-store.ts: currentLayoutSessionId -> currentLayoutEnvId; switchSessionLayout
  -> switchEnvLayout(oldEnvId, newEnvId, activeSessionId). Same-env switches no-op.
  Drop _skipLayoutSwitchForSession + consumeSkipFlag — env-keyed action handles it
  structurally.
- panel-portal-manager: PortalEntry.envId; releaseBySession -> releaseByEnv.
  ENV_SCOPED_COMPONENTS in dockview-desktop-layout (renamed from SESSION_SCOPED).
- useEnvSwitchCleanup replaces useSessionSwitchCleanup; tracks env changes only.
- All performLayoutSwitch callers (sidebar, dropdown, header, dialog) resolve
  sid -> envId via environmentIdBySessionId before switching.
- bottom-terminal-panel: drop sessionId prop, use useEnvironmentSessionId().
- cleanupTaskStorage now takes envIds[] alongside sessionIds[] for env-scoped
  layout/maximize cleanup.

* test: add coverage for env-keyed terminals + layout

Playwright e2e (terminal-env-keyed.spec.ts) — switching between sessions of
the same task keeps terminal scrollback intact and asserts both sessions
share one task_environment_id. Update the comment in
sessionless-task-switch.spec.ts to reference performEnvSwitch.

* fix: address env layout PR feedback

* test: fix flaky handshake auth check

* fix: address env scope review findings
2026-05-01 11:00:33 +01:00

116 lines
4.3 KiB
TypeScript

"use client";
import React, { useCallback, useEffect, useRef, useSyncExternalStore, type ReactNode } from "react";
import { createPortal } from "react-dom";
import { panelPortalManager } from "./panel-portal-manager";
import type { IDockviewPanelProps } from "dockview-react";
// ---------------------------------------------------------------------------
// PanelPortalHost — renders all persistent panel content via React portals
// ---------------------------------------------------------------------------
/**
* A render function that receives the panel ID and dockview-compatible props.
* The host calls this to decide *what* to render inside each portal element.
*/
export type PortalRenderer = (
panelId: string,
component: string,
params: Record<string, unknown>,
) => ReactNode;
type PanelPortalHostProps = {
/** Render function called for each registered panel. */
renderPanel: PortalRenderer;
};
/**
* Renders panel content into persistent portal elements that live outside the
* dockview tree. Mount this as a sibling to `<DockviewReact>`.
*/
export function PanelPortalHost({ renderPanel }: PanelPortalHostProps) {
// Re-render when panels are added/removed OR when any panel's params change.
// The version counter bumps on all three — we read ids() at render time
// rather than encoding them in the snapshot so panel ids can contain any
// character (a path like `file:path/with,comma.txt` would break a delimiter).
useSyncExternalStore(
useCallback((cb) => panelPortalManager.subscribe(cb), []),
useCallback(() => panelPortalManager.getVersion(), []),
useCallback(() => panelPortalManager.getVersion(), []),
);
const panelIds = panelPortalManager.ids();
return (
<>
{panelIds.map((panelId) => {
const entry = panelPortalManager.get(panelId);
if (!entry) return null;
return createPortal(
renderPanel(panelId, entry.component, entry.params),
entry.element,
panelId,
);
})}
</>
);
}
// ---------------------------------------------------------------------------
// usePortalSlot — hook for dockview panel wrappers (slot components)
// ---------------------------------------------------------------------------
/**
* Attaches the persistent portal element for `panelId` into the dockview
* panel's container on mount, and detaches it on unmount (without destroying).
*
* Also updates the stored `api` and `params` on every mount, so the portal
* content can read the latest dockview state.
*
* @param envId — when provided, tags the portal as env-scoped so it
* gets cleaned up on env switch via `releaseByEnv()`.
*/
export function usePortalSlot(
props: IDockviewPanelProps,
envId?: string,
): React.RefObject<HTMLDivElement | null> {
const containerRef = useRef<HTMLDivElement | null>(null);
const panelId = props.api.id;
const component = props.api.component;
const params = props.params ?? {};
useEffect(() => {
const container = containerRef.current;
if (!container) return;
const entry = panelPortalManager.acquire(panelId, component, params, props.api, envId);
// Reparent the portal element into this panel's DOM slot.
container.appendChild(entry.element);
return () => {
// Detach only — do NOT release. The element stays in the manager
// and will be re-adopted when the panel remounts after fromJSON().
if (entry.element.parentNode === container) {
container.removeChild(entry.element);
}
};
// envId in deps: when env changes, env-scoped panels re-acquire fresh
// portals (old ones were released by releaseByEnv in the store action).
// Global panels pass envId=undefined so this is a no-op for them.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [panelId, envId]);
// Forward dockview's param updates into the portal manager so preview-tab
// content (file-editor, diff-viewer, commit-detail) re-renders when the
// single preview panel switches to a different file/diff/commit.
useEffect(() => {
const disposable = props.api.onDidParametersChange((next) => {
panelPortalManager.updateParams(panelId, next as Record<string, unknown>);
});
return () => disposable.dispose();
}, [panelId, props.api]);
return containerRef;
}