The open-source agent harness - the runtime layer that turns an LLM into a working agent.
feat: Add session sharing with configurable permissions (#860)
harshil-2096f4ee3dc065c4
diff --git a/.changeset/share-session-permission-dialog.md b/.changeset/share-session-permission-dialog.mdnew file mode 100644index 000000000..4993ea84d--- /dev/null+++ b/.changeset/share-session-permission-dialog.md@@ -0,0 +1,6 @@+---+"@truefoundry/trueforge-ui": minor+"@truefoundry/trueforge-assistant-ui-runtime": patch+---++Share sessions with tenant members (popover, `shared` PATCH, share routes), toast and redirect on forbidden/missing deep links, and stop the New Chat → named-history max-update-depth loop.diff --git a/packages/assistant-ui-runtime/src/server/types.ts b/packages/assistant-ui-runtime/src/server/types.tsindex da137743f..7a9c04d63 100644--- a/packages/assistant-ui-runtime/src/server/types.ts+++ b/packages/assistant-ui-runtime/src/server/types.ts@@ -179,6 +179,8 @@ export interface Session<TSpec extends AgentSpec = AgentSpec> {agentSpec?: TSpec;/** true → mutable builder + updateSession(spec) allowed. */isMutable: boolean;+ /** When true, any subject in the tenant may read this session and its turns/events by id. */+ shared?: boolean;createdAt: string;updatedAt: string;}@@ -193,6 +195,8 @@ export interface UpdateSessionRequest<TSpec extends AgentSpec = AgentSpec> {sessionId: string;agentSpec?: TSpec;title?: string;+ /** When true, any subject in the tenant may read this session and its turns/events by id. */+ shared?: boolean;}// ---------------------------------------------------------------------------@@ -1179,6 +1183,8 @@ export type AgentUIServerPort<schedules?: TSchedules;metrics?: TMetrics;permissions?: TPermissions;+ /** Authenticated caller identity. Used for tenant-scoped share copy. */+ getMe?: () => Promise<{ tenantId: string }>;};/** Host-facing alias used by trueforge-ui. */diff --git a/packages/assistant-ui-runtime/src/useTrueForgeAgentRuntime.ts b/packages/assistant-ui-runtime/src/useTrueForgeAgentRuntime.tsindex a7b10e71a..23a29b534 100644--- a/packages/assistant-ui-runtime/src/useTrueForgeAgentRuntime.ts+++ b/packages/assistant-ui-runtime/src/useTrueForgeAgentRuntime.ts@@ -35,6 +35,8 @@ import type { UseTrueForgeAgentRuntimeOptions } from './types.js';import { resolveTrueForgeAgentRuntimeOptions } from './types.js';import { useTrueForgeAgentMessages } from './useTrueForgeAgentMessages.js';+const EMPTY_NAMED_DEFAULT_SPEC: AgentSpec = { model: { name: '' } };+/*** Wraps the mode-specific adapter behind a stable object so assistant-ui does* not treat a draft/named mode switch as an adapter change (which would reset@@ -61,6 +63,12 @@ function useTrueForgeAgentRuntimeImpl(const { server, agent, adapters, onError, ...sharedOptions } = options;const draftBridgeRef = useRef(agent.mode === 'draft' ? createDraftSessionBridge(server) : null);+ if (agent.mode === 'draft' && draftBridgeRef.current == null) {+ draftBridgeRef.current = createDraftSessionBridge(server);+ }+ // Named sessions keep the same runtimeKey as New Chat; do not keep the draft+ // bridge armed or a fresh `{ model: { name: '' } }` will retrigger spec sync.+ const draftBridge = agent.mode === 'draft' ? draftBridgeRef.current : null;const draftSessionId = useAuiState(state =>agent.mode === 'draft' ? (state.threadListItem.remoteId ?? undefined) : undefined,@@ -73,8 +81,8 @@ function useTrueForgeAgentRuntimeImpl(const draftSpec = useDraftAgentSpec({draftSessionId,- draftBridge: draftBridgeRef.current,- defaultAgentSpec: agent.mode === 'draft' ? agent.defaultAgentSpec : { model: { name: '' } },+ draftBridge,+ defaultAgentSpec: agent.mode === 'draft' ? agent.defaultAgentSpec : EMPTY_NAMED_DEFAULT_SPEC,onAgentSpecChange: agent.mode === 'draft' ? agent.onAgentSpecChange : undefined,onError,});diff --git a/packages/trueforge-ui/docs/customization.md b/packages/trueforge-ui/docs/customization.mdindex 2bfba623f..d0d16a1f7 100644--- a/packages/trueforge-ui/docs/customization.md+++ b/packages/trueforge-ui/docs/customization.md@@ -65,7 +65,7 @@ Public override surface (primitives stay theme/CSS — not slots):- **Thread list:** `ThreadListShell`, `ThreadListNewButton`, `ThreadListRow`,`ThreadListRowSkeleton`, `ThreadListEmptyState`, `HistoryLoader`,`AgentsLibrary`, `AgentsLibraryButton`, `SessionsBrowserButton`,- `SaveAgentButton`, `SelectAgentEmptyState`, `ClearChatButton`+ `SaveAgentButton`, `SelectAgentEmptyState`, `ClearChatButton`, `ShareChatButton`- **Agent details / sessions:** `AgentDetailsPage`, `AgentDetailsHeader`,`AgentDetailsTabs`, `AgentDetailsUnavailable`, `AgentOverview`,`AgentOverviewCard`, `AgentSessions`, `AgentSessionsFilters`, `SessionsPage`,@@ -100,6 +100,7 @@ Places mirrored to the URL:- `/agents/:agentName` — immutable "Try" of a library agent- `/sessions` — all-user Sessions browser (named agents and drafts)- `/sessions/:sessionId` — a specific chat session+- `/sessions/share/:sessionId` — detail-only session view without the Sessions list or filters- `/settings` — settings overlay (closing navigates to the chat place below it)- `/library` — Agents- `/library/:agentId` — agent details. `?tab=overview|sessions|code|metrics` selects the tab (default Overview);@@ -117,6 +118,7 @@ to keep that place overlay-only with no URL:paths: {buildAgent: '/new-agent',session: '/chats/:sessionId',+ sharedSession: '/sessions/share/:sessionId',libraryAgent: '/library/:agentId',settings: false,},@@ -146,6 +148,9 @@ Notes on behaviour:(`agentId`, `s_tw` for a relative window, or `s_sts`/`s_ets` for an absoluterange). Opening a session pins `s_sts`/`s_ets` around `created_at` (±5 min)so a refresh still finds that row on page 1 without scrolling the list.+- A detail-only shared session is `/sessions/share/:sessionId` when+ `withRouter` is on. Without SDK routing, the same view uses+ `?view=shared-session&sessionId=:sessionId` on the host page.- A `/sessions/:sessionId` link is resolved through `getSession` so the chatopens with its own agent binding and mutability rather than as a new draft.- `/build-agent` is used for a fresh builder; after its draft session persists,diff --git a/packages/trueforge-ui/src/atoms/ClearChatButton.tsx b/packages/trueforge-ui/src/atoms/ClearChatButton.tsxindex 20a09088d..ff5bc5783 100644--- a/packages/trueforge-ui/src/atoms/ClearChatButton.tsx+++ b/packages/trueforge-ui/src/atoms/ClearChatButton.tsx@@ -7,7 +7,7 @@ import { useOptionalShellMode } from '../server/ShellModeContext.js';import { useSlot } from '../theme/SlotsProvider.js';import { auiButtonClass } from './lib/buttonClasses.js';-// Resets the current chat / draft (Try Agent, New Chat, New Agent, Edit).+// Starts a fresh chat / draft (Try Agent, New Chat, New Agent, Edit).// Hidden while idle and on a fresh chat.export function ClearChatButton() {const shell = useOptionalShellMode();@@ -21,14 +21,14 @@ export function ClearChatButton() {<PermissionGuard allowed={canManageSession}><buttontype="button"- title="Clear chat"+ title="New Chat"className={auiButtonClass({ variant: 'ghost', size: 'large' })}onClick={() => {if (canManageSession) shell.clearChat();}}>- <Icon name="broom" size="0.875rem" />- Clear chat+ <Icon name="square-pen" size="0.875rem" />+ New Chat</button></PermissionGuard>);diff --git a/packages/trueforge-ui/src/atoms/PermissionGuard.tsx b/packages/trueforge-ui/src/atoms/PermissionGuard.tsxindex 86a4fa51a..4048cfca3 100644--- a/packages/trueforge-ui/src/atoms/PermissionGuard.tsx+++ b/packages/trueforge-ui/src/atoms/PermissionGuard.tsx@@ -23,8 +23,8 @@ export function PermissionGuard({if (allowed) return guardedChild;return (- <Tooltip content={deniedMessage}>- <span aria-disabled="true" className="inline-flex w-full cursor-not-allowed *:pointer-events-none">+ <Tooltip content={deniedMessage} side="bottom">+ <span aria-disabled="true" className="inline-flex cursor-not-allowed *:pointer-events-none">{guardedChild}</span></Tooltip>diff --git a/packages/trueforge-ui/src/atoms/ShareChatButton.tsx b/packages/trueforge-ui/src/atoms/ShareChatButton.tsxnew file mode 100644index 000000000..4fe9d48cb--- /dev/null+++ b/packages/trueforge-ui/src/atoms/ShareChatButton.tsx@@ -0,0 +1,35 @@+'use client';++import { useAuiState } from '../assistant-ui.js';+import { useActiveSessionCanManage } from '../hooks/useResourcePermissions.js';+import { Icon } from '../icons/Icon.js';+import { useSlot } from '../theme/SlotsProvider.js';+import { Button } from './primitives/Button.js';++export function ShareChatButton() {+ const sessionId = useAuiState(state => state.threadListItem.remoteId);+ const canManageSession = useActiveSessionCanManage();+ const ShareSessionDialog = useSlot('ShareSessionDialog');+ const PermissionGuard = useSlot('PermissionGuard');++ if (sessionId == null) return null;++ const trigger = (+ <Button.Ghost type="button" title="Share">+ <Icon name="share" />+ Share+ </Button.Ghost>+ );++ if (!canManageSession) {+ return <PermissionGuard allowed={false}>{trigger}</PermissionGuard>;+ }++ return <ShareSessionDialog sessionId={sessionId} trigger={trigger} />;+}++declare module '../theme/SlotsProvider.js' {+ interface AtomSlots {+ ShareChatButton: typeof ShareChatButton;+ }+}diff --git a/packages/trueforge-ui/src/atoms/ShareSessionDialog.tsx b/packages/trueforge-ui/src/atoms/ShareSessionDialog.tsxnew file mode 100644index 000000000..9c95e3874--- /dev/null+++ b/packages/trueforge-ui/src/atoms/ShareSessionDialog.tsx@@ -0,0 +1,156 @@+'use client';++import type { ReactNode } from 'react';++import { useShareSessionDialog, type SessionSharePermission } from '../hooks/useShareSessionDialog.js';+import { Icon } from '../icons/Icon.js';+import { auiInputClass } from './lib/inputClasses.js';+import { auiSelectOptionClass, auiSelectTriggerClass } from './lib/selectClasses.js';+import { Button } from './primitives/Button.js';+import { DropdownMenu } from './primitives/DropdownMenu.js';++export type ShareSessionDialogProps = {+ sessionId: string;+ trigger: ReactNode;+};++const SHARE_PERMISSIONS: Record<SessionSharePermission, { title: string; description: string }> = {+ private: { title: 'Only you', description: 'Only you have access' },+ tenant: { title: 'Everyone within this tenant', description: 'Everyone has access' },+};++const SHARE_PERMISSION_VALUES: readonly SessionSharePermission[] = ['private', 'tenant'];++function permissionCopy({+ permission,+ tenantId,+}: {+ permission: SessionSharePermission;+ tenantId: string | undefined;+}): { title: string; description: string } {+ if (permission === 'tenant' && tenantId != null && tenantId.length > 0) {+ return { title: `Everyone within ${tenantId}`, description: SHARE_PERMISSIONS.tenant.description };+ }+ return SHARE_PERMISSIONS[permission];+}++function AccessSelector({+ permission,+ tenantId,+ disabled,+ onChange,+}: {+ permission: SessionSharePermission;+ tenantId: string | undefined;+ disabled: boolean;+ onChange: (next: SessionSharePermission) => void;+}) {+ const selected = permissionCopy({ permission, tenantId });++ return (+ <DropdownMenu+ align="start"+ captureOutsideClick+ containerClassName="w-full"+ className="z-210 w-108 p-1 gap-1"+ trigger={+ <button+ type="button"+ disabled={disabled}+ aria-label="Session sharing"+ className={auiSelectTriggerClass(+ 'h-auto w-full bg-secondary-bg px-4 py-1.75 disabled:cursor-not-allowed disabled:opacity-50',+ )}+ >+ <span className="flex min-w-0 items-center gap-2">+ <Icon name="check" size="1rem" className="text-text-primary shrink-0" />+ <span className="flex min-w-0 items-baseline gap-2 text-sm">+ <span className="text-text-primary font-semibold">{selected.title}</span>+ <span className="text-text-secondary truncate">{selected.description}</span>+ </span>+ </span>+ <Icon name="chevron-down" size="1rem" className="text-text-secondary shrink-0" />+ </button>+ }+ >+ {SHARE_PERMISSION_VALUES.map(value => {+ const copy = permissionCopy({ permission: value, tenantId });+ return (+ <button+ key={value}+ type="button"+ role="option"+ aria-label={copy.title}+ aria-selected={value === permission}+ className={auiSelectOptionClass()}+ onClick={() => onChange(value)}+ >+ <span aria-hidden className="flex min-w-0 flex-1 items-baseline gap-2">+ <span className="font-semibold">{copy.title}</span>+ <span className="text-text-secondary truncate">{copy.description}</span>+ </span>+ <Icon name="check" className={value === permission ? 'opacity-100' : 'opacity-0'} />+ </button>+ );+ })}+ </DropdownMenu>+ );+}++export function ShareSessionDialog({ sessionId, trigger }: ShareSessionDialogProps) {+ const { permission, canManage, loading, shareUrl, copied, tenantId, load, changePermission, copySharedSessionLink } =+ useShareSessionDialog(sessionId);++ return (+ <DropdownMenu+ trigger={trigger}+ align="end"+ closeOnClick={false}+ onOpenChange={open => {+ if (open) void load();+ }}+ className="w-120 gap-5 rounded-[0.75rem] p-6 shadow-xs"+ >+ <div className="flex w-full items-center gap-2">+ <Icon name="user-cog" size="1.25rem" className="text-text-primary shrink-0" />+ <p className="text-text-primary min-w-0 flex-1 text-base font-semibold">Change permissions</p>+ </div>+ <AccessSelector+ permission={permission}+ tenantId={tenantId}+ disabled={!canManage || loading}+ onChange={next => {+ void changePermission(next);+ }}+ />+ <div role="separator" className="bg-border h-px w-full" />+ <div className="flex w-full items-center gap-2">+ <Icon name="link" size="1rem" className="text-text-primary shrink-0" />+ <p className="text-text-primary min-w-0 flex-1 text-sm font-semibold">Share URL</p>+ </div>+ <div className="flex h-8 w-full items-center gap-2">+ <input+ readOnly+ value={shareUrl}+ aria-label="Share URL"+ className={auiInputClass('h-8 min-w-0 flex-1 px-3.5 text-[0.8125rem]')}+ />+ <Button.Primary+ type="button"+ size="large"+ className="h-8 shrink-0 rounded px-2.5 text-xs"+ onClick={() => void copySharedSessionLink()}+ >+ <Icon name={copied ? 'check' : 'copy'} size="0.875rem" />+ {copied ? 'Copied' : 'Copy'}+ </Button.Primary>+ </div>+ </DropdownMenu>+ );+}++declare module '../theme/SlotsProvider.js' {+ interface AtomSlots {+ ShareSessionDialog: typeof ShareSessionDialog;+ }+}diff --git a/packages/trueforge-ui/src/atoms/ThreadShell.tsx b/packages/trueforge-ui/src/atoms/ThreadShell.tsxindex 5dd73a9c0..31d283ff0 100644--- a/packages/trueforge-ui/src/atoms/ThreadShell.tsx+++ b/packages/trueforge-ui/src/atoms/ThreadShell.tsx@@ -2,8 +2,11 @@ import { forwardRef, type ComponentPropsWithRef, type CSSProperties } from 'reacimport { cn } from './lib/cn.js';+const THREAD_MAX_WIDTH = '44rem';+const THREAD_CONTENT_MAX_WIDTH = `var(--thread-max-width, ${THREAD_MAX_WIDTH})`;+const THREAD_CSS_VARS: CSSProperties = {- ['--thread-max-width' as string]: '44rem',+ ['--thread-max-width' as string]: THREAD_MAX_WIDTH,['--composer-padding' as string]: '8px',};@@ -26,24 +29,30 @@ ThreadRootShell.displayName = 'ThreadRootShell';export type ThreadViewportShellProps = ComponentPropsWithRef<'div'> & {isEmpty?: boolean;+ /** Disable the inner scroll root when an ancestor owns the combined surface scroll. */+ scrollable?: boolean;+ /** Override the conversation content width without changing the scroll root width. */+ contentMaxWidth?: string;};export const ThreadViewportShell = forwardRef<HTMLDivElement, ThreadViewportShellProps>(- ({ className, isEmpty, children, ...rest }, ref) => (+ ({ className, isEmpty, scrollable = true, contentMaxWidth, children, ...rest }, ref) => (<divref={ref}data-slot="aui_thread-viewport"className={cn(- 'relative flex min-h-0 min-w-0 flex-1 flex-col overflow-x-hidden overflow-y-auto overscroll-contain',+ 'relative flex min-h-0 min-w-0 flex-col',+ scrollable ? 'flex-1 overflow-x-hidden overflow-y-auto overscroll-contain' : 'shrink-0 overflow-visible',className,)}{...rest}><divclassName={cn(- 'mx-auto flex w-full min-w-0 max-w-(--thread-max-width) flex-col px-3 pt-3',+ 'mx-auto flex w-full min-w-0 flex-col px-3 pt-3',isEmpty ? 'min-h-full justify-center pb-4' : 'pb-32',)}+ style={{ maxWidth: contentMaxWidth ?? THREAD_CONTENT_MAX_WIDTH }}>{children}</div>diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionDetailHeader.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionDetailHeader.tsxindex d470ac83e..b3f75cc16 100644--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionDetailHeader.tsx+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionDetailHeader.tsx@@ -1,65 +1,49 @@'use client';-import { useEffect, useState } from 'react';-import { Icon } from '../../icons/Icon.js';import { useSlot } from '../../theme/SlotsProvider.js';-import { buildAgentSessionShareUrl } from '../../utils/sessionShareUrl.js';import { auiButtonClass } from '../lib/buttonClasses.js';import { cn } from '../lib/cn.js';import { Button } from '../primitives/Button.js';-import { LightTooltip } from '../primitives/Tooltip.js';import type { AgentSessionDetailHeaderProps } from './types.js';export { buildAgentSessionShareUrl } from '../../utils/sessionShareUrl.js';+function SessionsShareTrigger({ disabled }: { disabled?: boolean }) {+ return (+ <button type="button" disabled={disabled} className={auiButtonClass({ variant: 'secondary', size: 'large' })}>+ <Icon name="share" />+ Share+ </button>+ );+}+export function AgentSessionDetailHeader({title,sessionId,- agentId,- createdAt,- view,onClose,resumeHref,onResume,resumeLabel,canResume = true,+ canShare = true,}: AgentSessionDetailHeaderProps) {- const [copied, setCopied] = useState(false);const PermissionGuard = useSlot('PermissionGuard');-- useEffect(() => {- if (!copied) return undefined;- const timer = window.setTimeout(() => setCopied(false), 2000);- return () => window.clearTimeout(timer);- }, [copied]);-- const copySessionLink = async () => {- try {- await navigator.clipboard.writeText(buildAgentSessionShareUrl({ sessionId, agentId, createdAt, view }));- setCopied(true);- } catch {- // Clipboard may be unavailable; ignore.- }- };+ const ShareSessionDialog = useSlot('ShareSessionDialog');return (<div className="flex shrink-0 items-center gap-3 border-b border-border p-3"><div className="flex min-w-0 flex-1 items-center gap-1.5 pb-0.5"><h2 className="min-w-0 truncate text-sm font-semibold leading-none text-text-primary">{title}</h2><code className="min-w-0 truncate font-mono text-xs leading-none text-text-secondary">{sessionId}</code>- <LightTooltip title={copied ? 'Copied' : 'Copy session link'} dismissOnClick={false}>- <Button.Ghost- type="button"- size="icon"- aria-label="Copy session link"- className="size-6"- onClick={() => void copySessionLink()}- >- <Icon name="link" className="size-3.5" />- </Button.Ghost>- </LightTooltip></div>+ {canShare ? (+ <ShareSessionDialog sessionId={sessionId} trigger={<SessionsShareTrigger />} />+ ) : (+ <PermissionGuard allowed={false}>+ <SessionsShareTrigger />+ </PermissionGuard>+ )}{resumeLabel != null && resumeHref != null && canResume ? (<ahref={resumeHref}diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessions.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessions.tsxindex edd02b176..cf753fff3 100644--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessions.tsx+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessions.tsx@@ -14,6 +14,7 @@ import { useOptionalShellMode } from '../../server/ShellModeContext.js';import type { Session, SessionEventItem, SessionListEntry } from '../../server/types.js';import { useSlot } from '../../theme/SlotsProvider.js';import { drainListPages } from '../../utils/drainListPages.js';+import { reportSessionAccessError } from '../../utils/sessionAccessError.js';import { sessionTimeRangeFromCreatedAt } from '../../utils/sessionShareUrl.js';import { EmptyScreen } from '../EmptyScreen.js';import { cn } from '../lib/cn.js';@@ -46,6 +47,9 @@ export function AgentSessions({startTimestamp,endTimestamp,shareView,+ detailOnly = false,+ detailSessionId,+ onCloseDetail,onLoadRecentSessions,}: AgentSessionsProps) {const sessionsServer = useAgentSessionsServer();@@ -53,7 +57,8 @@ export function AgentSessions({const toaster = useToasterOptional();const shell = useOptionalShellMode();const routes = useOptionalResolvedRoutes();- const { sessionId: selectedSessionId, updateShareSearch } = useSessionShareSearch();+ const { sessionId: querySessionId, updateShareSearch } = useSessionShareSearch();+ const selectedSessionId = detailOnly ? (detailSessionId ?? null) : querySessionId;const AgentSessionListRow = useSlot('AgentSessionListRow');const AgentSessionDetailHeader = useSlot('AgentSessionDetailHeader');@@ -103,6 +108,16 @@ export function AgentSessions({let cancelled = false;loadMoreInflightRef.current = false;setNextPageToken(undefined);+ if (detailOnly) {+ setEntries([]);+ setListLoading(false);+ setListLoadingMore(false);+ setListLoadMoreFailed(false);+ setListFailed(false);+ return () => {+ cancelled = true;+ };+ }setListLoading(true);setListLoadingMore(false);setListLoadMoreFailed(false);@@ -127,7 +142,7 @@ export function AgentSessions({return () => {cancelled = true;};- }, [listRequest, sessionsServer]);+ }, [detailOnly, listRequest, sessionsServer]);const loadMore = useCallback(async () => {// A ref, not `listLoadingMore`: the observer can fire twice before a re-render.@@ -189,15 +204,24 @@ export function AgentSessions({...(pageToken == null ? {} : { pageToken }),}),}),- chatServer.getSession({ sessionId: selectedSessionId }).catch(() => undefined),+ chatServer.getSession({ sessionId: selectedSessionId }),]).then(([itemsNewestFirst, session]) => {if (cancelled) return;setDetailEvents([...itemsNewestFirst].reverse());setDetailSession(session);})- .catch(() => {- if (!cancelled) setDetailFailed(true);+ .catch((error: unknown) => {+ if (cancelled) return;+ reportSessionAccessError({+ error,+ ...(toaster != null ? { showError: toaster.showError } : {}),+ });+ if (detailOnly) {+ onCloseDetail?.();+ return;+ }+ setDetailFailed(true);}).finally(() => {if (!cancelled) setDetailLoading(false);@@ -206,7 +230,7 @@ export function AgentSessions({return () => {cancelled = true;};- }, [chatServer, selectedSessionId, sessionsServer]);+ }, [chatServer, detailOnly, onCloseDetail, selectedSessionId, sessionsServer, toaster]);const selectSession = (entry: SessionListEntry) => {const pinned = shareView === 'sessions' ? sessionTimeRangeFromCreatedAt(entry.createdAt) : null;@@ -220,6 +244,10 @@ export function AgentSessions({const clearSelectedSession = () => {if (selectedSessionId == null) return;+ if (detailOnly) {+ onCloseDetail?.();+ return;+ }updateShareSearch({ sessionId: null });};@@ -272,7 +300,47 @@ export function AgentSessions({const resumeProps =resumeHref != null ? { resumeHref, resumeLabel } : shell != null ? { onResume: handleResume, resumeLabel } : {};- const selectedCreatedAt = detailSession?.createdAt ?? selectedEntry?.createdAt;++ const detailPanel = (+ <section className="flex h-full min-w-0 flex-col bg-primary-bg">+ {selectedSessionId == null ? (+ <div className="flex flex-1 items-center justify-center px-6 text-sm text-text-secondary">+ Select a session to view details+ </div>+ ) : detailFailed ? (+ <div className="flex flex-1 items-center justify-center px-6 text-sm text-text-secondary">+ Session details could not be loaded.+ </div>+ ) : (+ <>+ <AgentSessionDetailHeader+ title={selectedTitle}+ sessionId={selectedSessionId}+ onClose={clearSelectedSession}+ canResume={canResume}+ canShare={canResume}+ {...resumeProps}+ />+ {detailLoading || detailEvents === undefined ? (+ <div className="flex flex-1 flex-col p-4" role="status" aria-label="Loading session details">+ <Skeleton className="min-h-64 flex-1 rounded-lg" />+ </div>+ ) : (+ <AgentSessionTimelineContainer+ sessionId={selectedSessionId}+ events={detailEvents}+ listMetrics={selectedEntry?.metrics}+ {...(detailOnly ? { contentMaxWidth: '60rem' } : {})}+ />+ )}+ </>+ )}+ </section>+ );++ if (detailOnly) {+ return <div className="h-full min-h-0 w-full">{detailPanel}</div>;+ }// Full empty only when nothing is selected — keep the detail pane for deep-linked sessionIds// (filters/time range can empty the list while share state still points at a session).@@ -379,41 +447,7 @@ export function AgentSessions({</Separator><Panel id="agent-session-detail" defaultSize="65%" minSize="30%">- <section className="flex h-full min-w-0 flex-col bg-primary-bg">- {selectedSessionId == null ? (- <div className="flex flex-1 items-center justify-center px-6 text-sm text-text-secondary">- Select a session to view details- </div>- ) : detailFailed ? (- <div className="flex flex-1 items-center justify-center px-6 text-sm text-text-secondary">- Session details could not be loaded.- </div>- ) : (- <>- <AgentSessionDetailHeader- title={selectedTitle}- sessionId={selectedSessionId}- agentId={agentId}- createdAt={selectedCreatedAt}- view={shareView}- onClose={clearSelectedSession}- canResume={canResume}- {...resumeProps}- />- {detailLoading || detailEvents === undefined ? (- <div className="flex flex-1 flex-col p-4" role="status" aria-label="Loading session details">- <Skeleton className="min-h-64 flex-1 rounded-lg" />- </div>- ) : (- <AgentSessionTimelineContainer- sessionId={selectedSessionId}- events={detailEvents}- listMetrics={selectedEntry?.metrics}- />- )}- </>- )}- </section>+ {detailPanel}</Panel>{pendingDelete != null ? (diff --git a/packages/trueforge-ui/src/atoms/agent-details/SessionsPage.tsx b/packages/trueforge-ui/src/atoms/agent-details/SessionsPage.tsxindex c2bbf28ea..816966c18 100644--- a/packages/trueforge-ui/src/atoms/agent-details/SessionsPage.tsx+++ b/packages/trueforge-ui/src/atoms/agent-details/SessionsPage.tsx@@ -4,6 +4,7 @@ import { Suspense, useCallback, useEffect, useMemo, useState } from 'react';import { useSessionShareSearch } from '../../hooks/useSessionShareSearch.js';import { useOptionalAgentSessionsServer } from '../../server/ServerContext.js';+import { useShellMode } from '../../server/ShellModeContext.js';import { useSlot } from '../../theme/SlotsProvider.js';import {defaultSessionTimeRange,@@ -17,9 +18,11 @@ import { Skeleton } from '../primitives/Skeleton.js';export function SessionsPage() {const sessionsServer = useOptionalAgentSessionsServer();+ const shell = useShellMode();const { updateShareSearch } = useSessionShareSearch();const AgentSessions = useSlot('AgentSessions');const AgentSessionsFilters = useSlot('AgentSessionsFilters');+ const sharedSessionId = shell.sharedSessionId;const [agentFilter, setAgentFilter] = useState<string | null>(() => readSessionShareSearch(window.location.search).agentId,@@ -29,6 +32,7 @@ export function SessionsPage() {);useEffect(() => {+ if (sharedSessionId != null) return;const share = readSessionShareSearch(window.location.search);updateShareSearch({view: 'sessions',@@ -65,18 +69,20 @@ export function SessionsPage() {<PageHeadertitle="Agent Sessions"end={- <AgentSessionsFilters- agentId={agentFilter}- timeRange={timeRange}- onAgentChange={nextAgentId => {- setAgentFilter(nextAgentId);- updateShareSearch({ agentId: nextAgentId, sessionId: null, view: 'sessions' });- }}- onTimeRangeChange={nextRange => {- setTimeRange(nextRange);- updateShareSearch({ timeRange: nextRange, sessionId: null, view: 'sessions' });- }}- />+ sharedSessionId == null ? (+ <AgentSessionsFilters+ agentId={agentFilter}+ timeRange={timeRange}+ onAgentChange={nextAgentId => {+ setAgentFilter(nextAgentId);+ updateShareSearch({ agentId: nextAgentId, sessionId: null, view: 'sessions' });+ }}+ onTimeRangeChange={nextRange => {+ setTimeRange(nextRange);+ updateShareSearch({ timeRange: nextRange, sessionId: null, view: 'sessions' });+ }}+ />+ ) : null}/><div className="min-h-0 flex-1">@@ -94,8 +100,16 @@ export function SessionsPage() {agentId={agentFilter ?? undefined}startTimestamp={new Date(resolved.startTs).toISOString()}endTimestamp={new Date(resolved.endTs).toISOString()}- shareView="sessions"- {...(showLoadRecentSessions ? { onLoadRecentSessions: loadRecentSessions } : {})}+ {...(sharedSessionId == null+ ? {+ shareView: 'sessions' as const,+ ...(showLoadRecentSessions ? { onLoadRecentSessions: loadRecentSessions } : {}),+ }+ : {+ detailOnly: true,+ detailSessionId: sharedSessionId,+ onCloseDetail: shell.closeSharedSession,+ })}/></Suspense>)}diff --git a/packages/trueforge-ui/src/atoms/agent-details/types.ts b/packages/trueforge-ui/src/atoms/agent-details/types.tsindex 1cc8af7e7..752c98241 100644--- a/packages/trueforge-ui/src/atoms/agent-details/types.ts+++ b/packages/trueforge-ui/src/atoms/agent-details/types.ts@@ -18,6 +18,10 @@ export type AgentSessionsProps = {endTimestamp?: string;/** When `sessions`, selection writes `view=sessions` and pins `s_sts`/`s_ets`. */shareView?: 'sessions' | null;+ /** Render only the selected detail pane for a shared-session URL. */+ detailOnly?: boolean;+ detailSessionId?: string;+ onCloseDetail?: () => void;/** Restores the rolling recent-session window from a URL-loaded session. */onLoadRecentSessions?: () => void;};@@ -43,9 +47,6 @@ export type AgentSessionListRowProps = {export type AgentSessionDetailHeaderProps = {title: string;sessionId: string;- agentId?: string;- createdAt?: string;- view?: 'sessions' | null;onClose: () => void;/*** When set with `resumeLabel`, shows Resume Chat / Resume Agent building as a@@ -58,6 +59,8 @@ export type AgentSessionDetailHeaderProps = {resumeLabel?: string;/** Whether the current user may resume this session. */canResume?: boolean;+ /** Whether the current user may share this session. Defaults to true. */+ canShare?: boolean;};export type AgentSessionTurnHeaderProps = {diff --git a/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsx b/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsxindex 631ad2b5e..6d83da954 100644--- a/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsx+++ b/packages/trueforge-ui/src/atoms/primitives/DropdownMenu.tsx@@ -17,6 +17,8 @@ export type DropdownMenuProps = {onOpenChange?: (open: boolean) => void;closeOnClick?: boolean;lockScroll?: boolean;+ /** Capture-phase outside click. Needed when a parent menu stops mousedown bubbling. */+ captureOutsideClick?: boolean;};// Returns true if the click was on the menu surface, not its contents or scrollbar.@@ -35,6 +37,7 @@ export function DropdownMenu({onOpenChange,closeOnClick = true,lockScroll = false,+ captureOutsideClick = false,}: DropdownMenuProps) {const [internalOpen, setInternalOpen] = useState(false);const open = controlledOpen ?? internalOpen;@@ -85,9 +88,9 @@ export function DropdownMenu({if (menuRef.current?.contains(target)) return;setOpen(false);};- document.addEventListener('mousedown', handler);- return () => document.removeEventListener('mousedown', handler);- }, [open]);+ document.addEventListener('mousedown', handler, captureOutsideClick);+ return () => document.removeEventListener('mousedown', handler, captureOutsideClick);+ }, [captureOutsideClick, open, setOpen]);useEffect(() => {if (!open || !lockScroll) return;diff --git a/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx b/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsxindex 2a968cb0b..a81a91658 100644--- a/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx+++ b/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx@@ -7,6 +7,20 @@ import { cn } from '../lib/cn.js';import { themePortalRoot } from '../lib/themePortalRoot.js';const TOOLTIP_VIEWPORT_PAD = 8;+const TOOLTIP_GAP = 6;++export type TooltipSide = 'top' | 'bottom' | 'left' | 'right';++function isVerticalSide(side: TooltipSide): side is 'top' | 'bottom' {+ return side === 'top' || side === 'bottom';+}++function tooltipTransform(side: TooltipSide): string {+ if (side === 'bottom') return 'translate(-50%, 0)';+ if (side === 'top') return 'translate(-50%, -100%)';+ if (side === 'right') return 'translate(0, -50%)';+ return 'translate(-100%, -50%)';+}/** `left`/`top` are the desired center and top-edge (bottom) or bottom-edge (top). */export function clampCenteredTooltip({@@ -48,6 +62,41 @@ export function clampCenteredTooltip({return { top: nextTop, left: nextLeft };}+/** `left` is the inner edge (right: tooltip start; left: tooltip end). `top` is the vertical center. */+export function clampEdgeTooltip({+ left,+ top,+ width,+ height,+ side,+ viewportWidth,+ viewportHeight,+ pad = TOOLTIP_VIEWPORT_PAD,+}: {+ left: number;+ top: number;+ width: number;+ height: number;+ side: 'left' | 'right';+ viewportWidth: number;+ viewportHeight: number;+ pad?: number;+}): { top: number; left: number } {+ let nextTop = top;+ if (height > 0) {+ const half = height / 2;+ nextTop = Math.min(viewportHeight - pad - half, Math.max(pad + half, top));+ }+ let nextLeft = left;+ if (width > 0) {+ nextLeft =+ side === 'right'+ ? Math.min(viewportWidth - pad - width, Math.max(pad, left))+ : Math.min(viewportWidth - pad, Math.max(pad + width, left));+ }+ return { top: nextTop, left: nextLeft };+}+function hasTooltipContent(content: React.ReactNode): boolean {if (content == null || content === false) return false;if (typeof content === 'string') return content.trim().length > 0;@@ -64,7 +113,7 @@ export type TooltipProps = {children: React.ReactElement;className?: string;triggerClassName?: string;- side?: 'top' | 'bottom';+ side?: TooltipSide;dismissOnClick?: boolean;followCursor?: boolean;/** When set, tooltip is pinned to these viewport coords instead of the trigger. */@@ -99,28 +148,36 @@ export function Tooltip({const trigger = triggerWrapRef.current;let next: { top: number; left: number } | null = null;if (anchor != null) {- next = { top: side === 'bottom' ? anchor.top + 6 : anchor.top - 6, left: anchor.left };- } else if (trigger) {- const rect = trigger.getBoundingClientRect();next = {- top: side === 'bottom' ? rect.bottom + 6 : rect.top - 6,- left: followCursor && cursorXRef.current != null ? cursorXRef.current : rect.left + rect.width / 2,+ top: side === 'bottom' ? anchor.top + TOOLTIP_GAP : anchor.top - TOOLTIP_GAP,+ left: anchor.left,};+ } else if (trigger) {+ const rect = trigger.getBoundingClientRect();+ next = isVerticalSide(side)+ ? {+ top: side === 'bottom' ? rect.bottom + TOOLTIP_GAP : rect.top - TOOLTIP_GAP,+ left: followCursor && cursorXRef.current != null ? cursorXRef.current : rect.left + rect.width / 2,+ }+ : {+ top: rect.top + rect.height / 2,+ left: side === 'right' ? rect.right + TOOLTIP_GAP : rect.left - TOOLTIP_GAP,+ };}if (next == null) return;const tooltipEl = tooltipRef.current;- setPos(- tooltipEl- ? clampCenteredTooltip({- ...next,- width: tooltipEl.offsetWidth,- height: tooltipEl.offsetHeight,- side,- viewportWidth: window.innerWidth,- viewportHeight: window.innerHeight,- })- : next,- );+ if (tooltipEl == null) {+ setPos(next);+ return;+ }+ const size = {+ ...next,+ width: tooltipEl.offsetWidth,+ height: tooltipEl.offsetHeight,+ viewportWidth: window.innerWidth,+ viewportHeight: window.innerHeight,+ };+ setPos(isVerticalSide(side) ? clampCenteredTooltip({ ...size, side }) : clampEdgeTooltip({ ...size, side }));};useLayoutEffect(() => {@@ -184,7 +241,7 @@ export function Tooltip({style={{top: pos?.top ?? 0,left: pos?.left ?? 0,- transform: side === 'bottom' ? 'translate(-50%, 0)' : 'translate(-50%, -100%)',+ transform: tooltipTransform(side),visibility: pos == null ? 'hidden' : undefined,}}className={cn(@@ -213,7 +270,7 @@ export type LightTooltipProps = {className?: string;triggerClassName?: string;size?: string;- side?: 'top' | 'bottom';+ side?: TooltipSide;dismissOnClick?: boolean;followCursor?: boolean;anchor?: TooltipAnchor | null;diff --git a/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx b/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsxindex 433d30fa7..800826663 100644--- a/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx+++ b/packages/trueforge-ui/src/containers/AgentSessionTimelineContainer.tsx@@ -125,6 +125,7 @@ function messagesForTurn(messages: ThreadMessageLike[], turn: SessionTurnView):export type AgentSessionTimelineContainerProps = {sessionId: string;events: SessionEventItem[];+ contentMaxWidth?: string;listMetrics?: {totalTurns: number;totalCostInUsd?: number;@@ -132,7 +133,12 @@ export type AgentSessionTimelineContainerProps = {};};-export function AgentSessionTimelineContainer({ sessionId, events, listMetrics }: AgentSessionTimelineContainerProps) {+export function AgentSessionTimelineContainer({+ sessionId,+ events,+ contentMaxWidth,+ listMetrics,+}: AgentSessionTimelineContainerProps) {const server = useServer();const AgentSessionTurnHeader = useSlot('AgentSessionTurnHeader');const AgentSessionEventTimeline = useSlot('AgentSessionEventTimeline');@@ -207,14 +213,23 @@ export function AgentSessionTimelineContainer({ sessionId, events, listMetrics }}return (- <div className="flex min-h-0 flex-1 flex-col overflow-hidden">- <div className="shrink-0 border-b border-border">+ <div+ className="min-h-0 flex-1 overflow-x-hidden overflow-y-auto overscroll-contain"+ data-slot="agent-session-scroll"+ >+ <div className="sticky top-0 z-20 bg-primary-bg" data-slot="agent-session-metrics-sticky"><AgentSessionMetricsStrip metrics={sessionMetrics} />+ </div>+ <div className="border-b border-border"><Suspense fallback={null}><AgentSessionEventTimeline turns={turnViews} segments={timelineSegments} onSelectTurn={handleSelectTurn} /></Suspense></div>- <ThreadViewportShell className="flex-1 pb-4">+ <ThreadViewportShell+ scrollable={false}+ className="pb-4"+ {...(contentMaxWidth == null ? {} : { contentMaxWidth })}+ ><div className="flex flex-col gap-4">{turnViews.map(turn => (<SessionTurnSectiondiff --git a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsxindex 8c7c74699..0b7043a18 100644--- a/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx+++ b/packages/trueforge-ui/src/containers/TrueForgeUIShell.tsx@@ -29,6 +29,7 @@ import type { AgentUIServer, CreateSessionRequest } from '../server/types.js';import { SlotsProvider, useThemeMode, type SlotOverrides } from '../theme/SlotsProvider.js';import type { LayoutProp, ThemeConfig } from '../theme/types.js';import { getErrorMessage } from '../utils/getErrorMessage.js';+import { ToasterProvider } from './ToasterContainer.js';import { TrueForgeChatProvider, type TrueForgeChatProviderProps } from './TrueForgeChatProvider.js';import { useResolvedServer } from './useResolvedServer.js';@@ -318,27 +319,33 @@ export function TrueForgeUIShell(props: TrueForgeUIShellProps) {const server = resolved.server;const layoutTree = <LayoutChildren layout={layout} className={className} />;+ // Outer toaster so ShellRouteSync (sibling of chat provider) can toast access-denied+ // deep links; nested ToasterProvider inside TrueForgeChatProvider stays for hosts+ // that mount chat alone.const shellTree = (- <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>- <LibrarySessionShareBoot />- {resolvedRoutes != null ? (- <Suspense fallback={null}>- <ShellRouteSync- routes={resolvedRoutes}- activeRemoteId={activeRemoteId}- initialSettingsOpen={initialSettingsOpen}- />- </Suspense>- ) : null}- <ChatProviderFromShell- server={server}- onError={onError}- onRemoteIdChange={resolvedRoutes != null ? handleRemoteIdChange : undefined}- {...providerRest}- >- {layoutTree}- </ChatProviderFromShell>- </ShellModeProvider>+ <ToasterProvider>+ <ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}>+ <LibrarySessionShareBoot />+ {resolvedRoutes != null ? (+ <Suspense fallback={null}>+ <ShellRouteSync+ routes={resolvedRoutes}+ activeRemoteId={activeRemoteId}+ initialSettingsOpen={initialSettingsOpen}+ onError={onError}+ />+ </Suspense>+ ) : null}+ <ChatProviderFromShell+ server={server}+ onError={onError}+ onRemoteIdChange={resolvedRoutes != null ? handleRemoteIdChange : undefined}+ {...providerRest}+ >+ {layoutTree}+ </ChatProviderFromShell>+ </ShellModeProvider>+ </ToasterProvider>);// Widget visibility provider is used to control the visibility of the widget with isolated stateconst visibilityTree =diff --git a/packages/trueforge-ui/src/hooks/useCopySharedSessionLink.ts b/packages/trueforge-ui/src/hooks/useCopySharedSessionLink.tsnew file mode 100644index 000000000..a0adcacf4--- /dev/null+++ b/packages/trueforge-ui/src/hooks/useCopySharedSessionLink.ts@@ -0,0 +1,32 @@+'use client';++import { useCallback, useEffect, useState } from 'react';++import { buildSharedSessionHref } from '../routing/paths.js';+import { useOptionalResolvedRoutes } from '../routing/ResolvedRoutesContext.js';++export function useCopySharedSessionLink(sessionId: string | null | undefined): {+ copied: boolean;+ copySharedSessionLink: () => Promise<void>;+} {+ const routes = useOptionalResolvedRoutes();+ const [copied, setCopied] = useState(false);++ useEffect(() => {+ if (!copied) return undefined;+ const timer = window.setTimeout(() => setCopied(false), 2000);+ return () => window.clearTimeout(timer);+ }, [copied]);++ const copySharedSessionLink = useCallback(async () => {+ if (sessionId == null) return;+ try {+ await navigator.clipboard.writeText(buildSharedSessionHref({ sessionId, routes }));+ setCopied(true);+ } catch {+ // Clipboard access depends on the host browser and document permissions.+ }+ }, [routes, sessionId]);++ return { copied, copySharedSessionLink };+}diff --git a/packages/trueforge-ui/src/hooks/useShareSessionDialog.ts b/packages/trueforge-ui/src/hooks/useShareSessionDialog.tsnew file mode 100644index 000000000..6d2856bbc--- /dev/null+++ b/packages/trueforge-ui/src/hooks/useShareSessionDialog.ts@@ -0,0 +1,86 @@+'use client';++import { useCallback, useState } from 'react';++import { useToasterOptional } from '../containers/ToasterContainer.js';+import { buildSharedSessionHref } from '../routing/paths.js';+import { useOptionalResolvedRoutes } from '../routing/ResolvedRoutesContext.js';+import { useOptionalServer } from '../server/ServerContext.js';+import { useCopySharedSessionLink } from './useCopySharedSessionLink.js';+import { useResourcePermissions } from './useResourcePermissions.js';++export type SessionSharePermission = 'private' | 'tenant';++export function useShareSessionDialog(sessionId: string | null | undefined): {+ permission: SessionSharePermission;+ canManage: boolean;+ loading: boolean;+ shareUrl: string;+ copied: boolean;+ tenantId: string | undefined;+ load: () => Promise<void>;+ changePermission: (next: SessionSharePermission) => Promise<void>;+ copySharedSessionLink: () => Promise<void>;+} {+ const server = useOptionalServer();+ const toaster = useToasterOptional();+ const routes = useOptionalResolvedRoutes();+ const resourceIds = sessionId == null || sessionId.length === 0 ? [] : [sessionId];+ const { allows } = useResourcePermissions({ resourceType: 'session', resourceIds });+ const canManage = allows(sessionId, 'MANAGE');+ const { copied, copySharedSessionLink } = useCopySharedSessionLink(sessionId);+ const [permission, setPermission] = useState<SessionSharePermission>('private');+ const [tenantId, setTenantId] = useState<string | undefined>();+ const [loading, setLoading] = useState(false);++ const shareUrl = sessionId == null || sessionId.length === 0 ? '' : buildSharedSessionHref({ sessionId, routes });++ const load = useCallback(async () => {+ if (sessionId == null || sessionId.length === 0 || server == null) return;+ setLoading(true);+ try {+ const session = await server.getSession({ sessionId });+ setPermission(session.shared === true ? 'tenant' : 'private');+ if (server.getMe != null) {+ try {+ const me = await server.getMe();+ if (me.tenantId.length > 0) setTenantId(me.tenantId);+ } catch {+ // Keep the generic tenant label when identity is unavailable.+ }+ }+ } catch (caught) {+ toaster?.showError(caught);+ } finally {+ setLoading(false);+ }+ }, [server, sessionId, toaster]);++ const changePermission = useCallback(+ async (next: SessionSharePermission) => {+ if (!canManage || next === permission) return;+ const previous = permission;+ setPermission(next);+ if (sessionId == null || sessionId.length === 0 || server == null) return;+ try {+ await server.updateSession({ sessionId, shared: next === 'tenant' });+ } catch (caught) {+ setPermission(previous);+ toaster?.showError(caught);+ }+ },+ [canManage, permission, server, sessionId, toaster],+ );++ return {+ permission,+ canManage,+ loading,+ shareUrl,+ copied,+ tenantId,+ load,+ changePermission,+ copySharedSessionLink,+ };+}diff --git a/packages/trueforge-ui/src/icons/IconRegistry.tsx b/packages/trueforge-ui/src/icons/IconRegistry.tsxindex 0b779ef97..5811ce81b 100644--- a/packages/trueforge-ui/src/icons/IconRegistry.tsx+++ b/packages/trueforge-ui/src/icons/IconRegistry.tsx@@ -59,6 +59,7 @@ import {Save,Search,Settings,+ Share,Shield,ShieldCheck,SlidersHorizontal,@@ -69,6 +70,8 @@ import {Terminal,Trash2,TriangleAlert,+ UserCog,+ Users,Wrench,X,} from 'lucide-react';@@ -162,6 +165,7 @@ const defaults: Record<string, IconEntry> = {sun: Sun,moon: Moon,settings: Settings,+ share: Share,shield: Shield,'shield-check': ShieldCheck,sliders: SlidersHorizontal,@@ -183,6 +187,8 @@ const defaults: Record<string, IconEntry> = {plug: Plug,'list-check': ListChecks,lock: Lock,+ 'user-cog': UserCog,+ users: Users,lightbulb: Lightbulb,link: Link2,wrench: Wrench,diff --git a/packages/trueforge-ui/src/index.ts b/packages/trueforge-ui/src/index.tsindex 2df5d850a..8716faa43 100644--- a/packages/trueforge-ui/src/index.ts+++ b/packages/trueforge-ui/src/index.ts@@ -292,6 +292,9 @@ export {sessionIsCreateAgent,} from './atoms/lib/sessionCreateAgent.js';export { SelectAgentEmptyState } from './atoms/SelectAgentEmptyState.js';+export { ShareChatButton } from './atoms/ShareChatButton.js';+export { ShareSessionDialog } from './atoms/ShareSessionDialog.js';+export type { ShareSessionDialogProps } from './atoms/ShareSessionDialog.js';export { ShellActionsActionSlot } from './atoms/ShellActionsActionSlot.js';export { createTrueForgeServer } from './server/createTrueForgeServer.js';export type { CreateTrueForgeServerOptions, TrueForgeServer } from './server/createTrueForgeServer.js';diff --git a/packages/trueforge-ui/src/layouts/DrawerLayout.tsx b/packages/trueforge-ui/src/layouts/DrawerLayout.tsxindex 0eed6f105..e7be20592 100644--- a/packages/trueforge-ui/src/layouts/DrawerLayout.tsx+++ b/packages/trueforge-ui/src/layouts/DrawerLayout.tsx@@ -12,6 +12,7 @@ import { useIsMobile } from '../atoms/lib/useIsMobile.js';import { Spinner } from '../atoms/primitives/Spinner.js';import { AgentConfigDrawerContainer } from '../containers/AgentConfigDrawerContainer.js';import { Thread } from '../containers/Thread.js';+import { useChatChromeActionsVisible } from '../hooks/useChatChromeActionsVisible.js';import { Icon } from '../icons/Icon.js';import { shellIsCreateAgent, useOptionalShellMode } from '../server/ShellModeContext.js';import { useSlot } from '../theme/SlotsProvider.js';@@ -29,6 +30,7 @@ export function DrawerLayout({ className }: { className?: string }) {const AgentDetailsPage = useSlot('AgentDetailsPage');const AgentsLibrary = useSlot('AgentsLibrary');const SessionsPage = useSlot('SessionsPage');+ const ShareChatButton = useSlot('ShareChatButton');const SaveAgentButton = useSlot('SaveAgentButton');const SelectAgentEmptyState = useSlot('SelectAgentEmptyState');const UserAvatar = useSlot('UserAvatar');@@ -39,6 +41,7 @@ export function DrawerLayout({ className }: { className?: string }) {const sessionsOpen = shell?.sessionsOpen === true;const schedulesOpen = shell?.schedulesOpen === true;const overlayOpen = settingsOpen || libraryOpen || sessionsOpen || schedulesOpen;+ const chatChromeActionsVisible = useChatChromeActionsVisible();const showAgentConfig =shell != null && shellIsCreateAgent(shell.mode) && !overlayOpen && (!isMobile || shell.agentConfigOpen);const showNewActions = shell?.isNewChatEnabled !== false;@@ -100,6 +103,7 @@ export function DrawerLayout({ className }: { className?: string }) {<>{!overlayOpen ? (<>+ <ShareChatButton /><ClearChatButton /><SaveAgentButton /></>@@ -108,7 +112,7 @@ export function DrawerLayout({ className }: { className?: string }) {<UserAvatar />{!overlayOpen ? (<>- {showNewActions ? (+ {showNewActions && !chatChromeActionsVisible ? (<buttontype="button"aria-label="New Chat"diff --git a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx b/packages/trueforge-ui/src/layouts/SidebarLayout.tsxindex b5f5ca86e..a53f1be93 100644--- a/packages/trueforge-ui/src/layouts/SidebarLayout.tsx+++ b/packages/trueforge-ui/src/layouts/SidebarLayout.tsx@@ -177,6 +177,7 @@ export function SidebarLayout({ className }: { className?: string }) {const AgentDetailsPage = useSlot('AgentDetailsPage');const AgentsLibrary = useSlot('AgentsLibrary');const SessionsPage = useSlot('SessionsPage');+ const ShareChatButton = useSlot('ShareChatButton');const ClearChatButton = useSlot('ClearChatButton');const SaveAgentButton = useSlot('SaveAgentButton');const SelectAgentEmptyState = useSlot('SelectAgentEmptyState');@@ -264,6 +265,7 @@ export function SidebarLayout({ className }: { className?: string }) {end={!overlayOpen ? (<>+ <ShareChatButton /><ClearChatButton /><SaveAgentButton /></>diff --git a/packages/trueforge-ui/src/layouts/StackChatPanel.tsx b/packages/trueforge-ui/src/layouts/StackChatPanel.tsxindex 86a4276e5..f9b05d46a 100644--- a/packages/trueforge-ui/src/layouts/StackChatPanel.tsx+++ b/packages/trueforge-ui/src/layouts/StackChatPanel.tsx@@ -11,6 +11,7 @@ import { cn } from '../atoms/lib/cn.js';import { Spinner } from '../atoms/primitives/Spinner.js';import { AgentConfigDrawerContainer } from '../containers/AgentConfigDrawerContainer.js';import { Thread } from '../containers/Thread.js';+import { useChatChromeActionsVisible } from '../hooks/useChatChromeActionsVisible.js';import { Icon } from '../icons/Icon.js';import { useOptionalShellMode } from '../server/ShellModeContext.js';import { useSlot } from '../theme/SlotsProvider.js';@@ -37,6 +38,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelProconst AgentDetailsPage = useSlot('AgentDetailsPage');const AgentsLibrary = useSlot('AgentsLibrary');const SessionsPage = useSlot('SessionsPage');+ const ShareChatButton = useSlot('ShareChatButton');const SaveAgentButton = useSlot('SaveAgentButton');const SelectAgentEmptyState = useSlot('SelectAgentEmptyState');const UserAvatar = useSlot('UserAvatar');@@ -45,6 +47,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelProconst libraryOpen = shell?.libraryOpen === true;const sessionsOpen = shell?.sessionsOpen === true;const schedulesOpen = shell?.schedulesOpen === true;+ const chatChromeActionsVisible = useChatChromeActionsVisible();const showNewActions = shell?.isNewChatEnabled !== false;useEffect(() => {@@ -127,7 +130,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelPro<PageHeaderstart={<>- {showNewActions ? (+ {showNewActions && !chatChromeActionsVisible ? (<buttontype="button"aria-label="New Chat"@@ -154,6 +157,7 @@ export function StackChatPanel({ className, threadHeaderEnd }: StackChatPanelProtitle={<NamedAgentHeaderLabel />}end={<>+ <ShareChatButton /><ClearChatButton /><SaveAgentButton />{threadHeaderEnd}diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/chatServer.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/chatServer.tsindex efae83936..38f21f8b4 100644--- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/chatServer.ts+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/chatServer.ts@@ -88,6 +88,7 @@ function toUiSession(session: TrueForgeApi.Session): HarnessUiSession {id: session.id,isMutable: session.agent.type === 'inline',isCreateAgent: readSessionIsCreateAgent(session.metadata),+ shared: session.shared,createdAt: session.createdAt,updatedAt: session.updatedAt,...(session.title === null ? {} : { title: session.title }),@@ -222,12 +223,14 @@ export function createHarnessChatServer(await client.sessions.update(sessionId, { title });},- async updateSession({ sessionId, agentSpec, title }) {+ async updateSession({ sessionId, agentSpec, title, shared }) {// Named (reference) sessions reject agent updates server-side.- const response = await client.sessions.update(sessionId, {+ const body: TrueForgeApi.UpdateSessionRequest = {...(agentSpec === undefined ? {} : { agent: { spec: toHarnessAgentSpec(agentSpec) } }),...(title === undefined ? {} : { title }),- });+ ...(shared === undefined ? {} : { shared }),+ };+ const response = await client.sessions.update(sessionId, body);return toUiSession(response.data);},diff --git a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.tsindex 80741b256..f1673c1bd 100644--- a/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts+++ b/packages/trueforge-ui/src/plugins/trueforge-agent-server-adapter/index.ts@@ -110,5 +110,9 @@ export function createTrueForgeAgentUIServer(options: CreateTrueForgeAgentUIServmetrics: createHarnessAgentMetricsServer({ ...clientOptions, client }),schedules: createScheduleServer({ client }),permissions: permissions ?? createHarnessPermissionsServer({ client }),+ getMe: async () => {+ const { data } = await client.auth.me();+ return { tenantId: data.tenantId };+ },});}diff --git a/packages/trueforge-ui/src/routing/LibrarySessionShareBoot.tsx b/packages/trueforge-ui/src/routing/LibrarySessionShareBoot.tsxindex 0f2e9ce54..045f0fdf8 100644--- a/packages/trueforge-ui/src/routing/LibrarySessionShareBoot.tsx+++ b/packages/trueforge-ui/src/routing/LibrarySessionShareBoot.tsx@@ -5,24 +5,28 @@ import { useEffect } from 'react';import { useOptionalAgentSessionsServer } from '../server/ServerContext.js';import { useShellMode } from '../server/ShellModeContext.js';import { isSessionsChromeEnabled } from '../server/serverChrome.js';-import { readSessionShareSearch } from '../utils/sessionShareUrl.js';+import { readSessionShareSearch, SHARED_SESSION_VIEW_VALUE } from '../utils/sessionShareUrl.js';/** Open the sessions browser or a library agent from the share query — with or without `withRouter`. */export function LibrarySessionShareBoot() {- const { openLibraryAgent, setSessionsOpen } = useShellMode();+ const { openLibraryAgent, openSharedSession, setSessionsOpen } = useShellMode();const sessions = useOptionalAgentSessionsServer();const sessionsEnabled = isSessionsChromeEnabled({ sessions });useEffect(() => {if (!sessionsEnabled) return;const share = readSessionShareSearch(window.location.search);+ if (share.view === SHARED_SESSION_VIEW_VALUE && share.sessionId != null) {+ openSharedSession(share.sessionId);+ return;+ }if (share.view === 'sessions') {setSessionsOpen(true);return;}if (share.agentId == null) return;openLibraryAgent(share.agentId);- }, [openLibraryAgent, sessionsEnabled, setSessionsOpen]);+ }, [openLibraryAgent, openSharedSession, sessionsEnabled, setSessionsOpen]);return null;}diff --git a/packages/trueforge-ui/src/routing/ShellRouteSync.tsx b/packages/trueforge-ui/src/routing/ShellRouteSync.tsxindex 2f64790a7..3c445fb22 100644--- a/packages/trueforge-ui/src/routing/ShellRouteSync.tsx+++ b/packages/trueforge-ui/src/routing/ShellRouteSync.tsx@@ -5,6 +5,7 @@ import { useLocation, useNavigate } from 'react-router-dom';import { sessionIsCreateAgent } from '../atoms/lib/sessionCreateAgent.js';import { findAgentByName } from '../atoms/lib/useSearchAgentsList.js';+import { useToasterOptional } from '../containers/ToasterContainer.js';import {useOptionalAgentSessionsServer,useOptionalCatalogServer,@@ -20,6 +21,7 @@ import {updateHistoryAgentSearch,type HistoryAgentSearch,} from '../utils/historyAgentSearch.js';+import { reportSessionAccessError } from '../utils/sessionAccessError.js';import { deriveChatPlace, derivePlace } from './derivePlace.js';import { buildPath, matchLocation, placesEqual, sanitizeSearchForPlace } from './paths.js';import type { ResolvedRoutes, RoutePlace, ShellSnapshot } from './types.js';@@ -29,6 +31,10 @@ function placeOwnsHistoryAgentSearch(place: RoutePlace): boolean {return place.type === 'root' || place.type === 'agent' || place.type === 'session';}+function isSessionsPlace(place: RoutePlace): boolean {+ return place.type === 'sessionsBrowser' || place.type === 'sharedSession';+}+/*** Single bidirectional bridge between shell state and the URL. Mounted under* `ShellModeProvider` but outside the keyed chat runtime so boot applies once.@@ -37,10 +43,12 @@ export function ShellRouteSync({routes,activeRemoteId,initialSettingsOpen,+ onError,}: {routes: ResolvedRoutes;activeRemoteId: string | undefined;initialSettingsOpen: boolean;+ onError?: (error: unknown) => void;}) {const shell = useShellMode();const server = useOptionalServer();@@ -49,6 +57,7 @@ export function ShellRouteSync({const schedules = useOptionalScheduleServer();const capabilities = useServerCapabilities();const capabilitiesSettled = useServerCapabilitiesSettled();+ const toaster = useToasterOptional();const navigate = useNavigate();const location = useLocation();// Same gates as sidebar chrome: missing optional ports unregister their paths.@@ -62,6 +71,7 @@ export function ShellRouteSync({const routeGatesKey = [effectiveRoutes.settings,effectiveRoutes.sessionsBrowser,+ effectiveRoutes.sharedSession,effectiveRoutes.libraryAgent,effectiveRoutes.schedules,].join('\0');@@ -70,6 +80,7 @@ export function ShellRouteSync({settingsOpen: shell.settingsOpen,libraryOpen: shell.libraryOpen,sessionsOpen: shell.sessionsOpen,+ sharedSessionId: shell.sharedSessionId,libraryAgentId: shell.libraryAgentId,schedulesOpen: shell.schedulesOpen,pendingSessionId: shell.pendingSessionId,@@ -101,7 +112,26 @@ export function ShellRouteSync({* A URL carries only the id, so ask the server whether it names a mutable* draft or an agent chat; guessing "mutable" opens an agent session as a* blank draft. `requestedSessionRef` drops replies a later place superseded.+ * Access denied / missing session: toast, then New Chat (do not bind the id).*/+ const goToRoot = useCallback(() => {+ shell.setSettingsOpen(false);+ shell.setLibraryOpen(false);+ shell.setSchedulesOpen(false);+ switch (shell.agentConfigMode) {+ case 'AgentLibrary':+ shell.openLibraryHome();+ return;+ case 'AgentComposer':+ case 'AgentLibraryWithComposer':+ shell.openDraft();+ return;+ case 'SingleAgent':+ shell.clearChat();+ return;+ }+ }, [shell]);+const openSession = useCallback((sessionId: string) => {requestedSessionRef.current = sessionId;@@ -120,13 +150,20 @@ export function ShellRouteSync({...(session.agentName != null ? { agentName: session.agentName } : {}),});})- .catch(() => {+ .catch((error: unknown) => {if (requestedSessionRef.current !== sessionId) return;- // Unreachable session: bind by id alone rather than stranding the shell.- shell.openHistorySession({ sessionId });+ requestedSessionRef.current = null;+ // Drop boot's "wait until place matches URL" so shell→URL can leave /sessions/:id.+ bootPlaceRef.current = null;+ reportSessionAccessError({+ error,+ ...(onError != null ? { onError } : {}),+ ...(toaster != null ? { showError: toaster.showError } : {}),+ });+ goToRoot();});},- [server, shell],+ [goToRoot, onError, server, shell, toaster],);const applyHistoryAgentSearch = useCallback(@@ -195,6 +232,9 @@ export function ShellRouteSync({case 'sessionsBrowser':shell.setSessionsOpen(true);return;+ case 'sharedSession':+ shell.openSharedSession(target.sessionId);+ return;case 'libraryAgent':shell.openLibraryAgent(target.agentId);return;@@ -214,24 +254,11 @@ export function ShellRouteSync({openAgent(target.agentName);return;case 'root':- shell.setSettingsOpen(false);- shell.setLibraryOpen(false);- shell.setSchedulesOpen(false);- switch (shell.agentConfigMode) {- case 'AgentLibrary':- shell.openLibraryHome();- return;- case 'AgentComposer':- case 'AgentLibraryWithComposer':- shell.openDraft();- return;- case 'SingleAgent':- shell.clearChat();- return;- }+ goToRoot();+ return;}},- [shell, activeRemoteId, openAgent, openSession],+ [shell, activeRemoteId, goToRoot, openAgent, openSession],);// Boot: URL wins, except an explicit `initialSettingsOpen` overlay. Boot is the@@ -386,7 +413,7 @@ export function ShellRouteSync({if (urlPlace.type !== 'library' && urlPlace.type !== 'libraryAgent' && shell.libraryOpen) {shell.setLibraryOpen(false);}- if (urlPlace.type !== 'sessionsBrowser' && shell.sessionsOpen) {+ if (!isSessionsPlace(urlPlace) && shell.sessionsOpen) {shell.setSessionsOpen(false);}if (urlPlace.type !== 'schedules' && shell.schedulesOpen) {diff --git a/packages/trueforge-ui/src/routing/derivePlace.ts b/packages/trueforge-ui/src/routing/derivePlace.tsindex fb28c7d55..bf2e164e4 100644--- a/packages/trueforge-ui/src/routing/derivePlace.ts+++ b/packages/trueforge-ui/src/routing/derivePlace.ts@@ -28,6 +28,9 @@ export function deriveChatPlace(snapshot: ShellSnapshot): RoutePlace {export function derivePlace(snapshot: ShellSnapshot): RoutePlace {if (snapshot.settingsOpen) return { type: 'settings' };if (snapshot.schedulesOpen) return { type: 'schedules' };+ if (snapshot.sessionsOpen && snapshot.sharedSessionId != null) {+ return { type: 'sharedSession', sessionId: snapshot.sharedSessionId };+ }if (snapshot.sessionsOpen) return { type: 'sessionsBrowser' };if (snapshot.libraryOpen && snapshot.libraryAgentId != null) {return { type: 'libraryAgent', agentId: snapshot.libraryAgentId };diff --git a/packages/trueforge-ui/src/routing/paths.ts b/packages/trueforge-ui/src/routing/paths.tsindex 485aa03e8..32397c291 100644--- a/packages/trueforge-ui/src/routing/paths.ts+++ b/packages/trueforge-ui/src/routing/paths.ts@@ -3,7 +3,11 @@ import {readScheduleShareSearch,writeScheduleShareSearch,} from '../utils/scheduleShareUrl.js';-import { readSessionShareSearch, writeSessionShareSearch } from '../utils/sessionShareUrl.js';+import {+ readSessionShareSearch,+ SHARED_SESSION_VIEW_VALUE,+ writeSessionShareSearch,+} from '../utils/sessionShareUrl.js';import type { ResolvedRoutes, RoutePlace, RoutesConfig } from './types.js';const DEFAULTS = {@@ -15,6 +19,7 @@ const DEFAULTS = {buildAgent: '/build-agent',agent: '/agents/:agentName',session: '/sessions/:sessionId',+ sharedSession: '/sessions/share/:sessionId',sessionsBrowser: '/sessions',} as const;@@ -42,6 +47,7 @@ export function resolveRoutesConfig(routes?: RoutesConfig): ResolvedRoutes {buildAgent: resolveOptional(paths?.buildAgent, DEFAULTS.buildAgent),agent: resolveOptional(paths?.agent, DEFAULTS.agent),session: resolveOptional(paths?.session, DEFAULTS.session),+ sharedSession: resolveOptional(paths?.sharedSession, DEFAULTS.sharedSession),sessionsBrowser: resolveOptional(paths?.sessionsBrowser, DEFAULTS.sessionsBrowser),};}@@ -79,6 +85,8 @@ export function buildPath(place: RoutePlace, routes: ResolvedRoutes): string | nreturn routes.agent == null ? null : fillTemplate(routes.agent, place.agentName);case 'session':return routes.session == null ? null : fillTemplate(routes.session, place.sessionId);+ case 'sharedSession':+ return routes.sharedSession == null ? null : fillTemplate(routes.sharedSession, place.sessionId);case 'sessionsBrowser':return routes.sessionsBrowser;}@@ -107,6 +115,36 @@ export function buildSessionResumeHref({return url.toString();}+/** Absolute detail-only share URL, with a query fallback when SDK routing is unavailable. */+export function buildSharedSessionHref({+ sessionId,+ routes,+ href = typeof window === 'undefined' ? 'http://localhost/' : window.location.href,+}: {+ sessionId: string;+ routes: ResolvedRoutes | null;+ href?: string;+}): string {+ const place: RoutePlace = { type: 'sharedSession', sessionId };+ const sessionPath = routes == null ? null : buildPath(place, routes);+ const url = new URL(href);+ if (routes != null && sessionPath != null) {+ const basename = routes.basename.endsWith('/') ? routes.basename.slice(0, -1) : routes.basename;+ url.pathname = `${basename}${sessionPath}` || '/';+ url.search = sanitizeSearchForPlace(place, url.search);+ url.hash = '';+ return url.toString();+ }+ writeSessionShareSearch(url.searchParams, {+ sessionId,+ agentId: null,+ tab: null,+ view: SHARED_SESSION_VIEW_VALUE,+ timeRange: null,+ });+ return url.toString();+}+/*** Remove query state owned by a different shell place while preserving host* parameters. Settings is an overlay, so it retains the underlying place state.@@ -218,6 +256,10 @@ export function matchPath(pathname: string, routes: ResolvedRoutes): RoutePlaceconst sessionId = matchTemplate(routes.session, segments);if (sessionId != null) return { type: 'session', sessionId };}+ if (routes.sharedSession != null) {+ const sessionId = matchTemplate(routes.sharedSession, segments);+ if (sessionId != null) return { type: 'sharedSession', sessionId };+ }if (normalized === routes.root) {return { type: 'root' };}@@ -236,7 +278,8 @@ export function matchLocation({}): RoutePlace | null {const matched = matchPath(pathname, routes);if (matched == null || matched.type !== 'root') return matched;- const { agentId } = readSessionShareSearch(search);+ const { agentId, sessionId, view } = readSessionShareSearch(search);+ if (view === SHARED_SESSION_VIEW_VALUE && sessionId != null) return { type: 'sharedSession', sessionId };return agentId != null ? { type: 'libraryAgent', agentId } : matched;}@@ -245,5 +288,6 @@ export function placesEqual(a: RoutePlace, b: RoutePlace): boolean {if (a.type === 'agent' && b.type === 'agent') return a.agentName === b.agentName;if (a.type === 'libraryAgent' && b.type === 'libraryAgent') return a.agentId === b.agentId;if (a.type === 'session' && b.type === 'session') return a.sessionId === b.sessionId;+ if (a.type === 'sharedSession' && b.type === 'sharedSession') return a.sessionId === b.sessionId;return true;}diff --git a/packages/trueforge-ui/src/routing/types.ts b/packages/trueforge-ui/src/routing/types.tsindex ea5024005..dba41efa8 100644--- a/packages/trueforge-ui/src/routing/types.ts+++ b/packages/trueforge-ui/src/routing/types.ts@@ -8,6 +8,7 @@ export type RoutePlace =| { type: 'root' }| { type: 'agent'; agentName: string }| { type: 'session'; sessionId: string }+ | { type: 'sharedSession'; sessionId: string }| { type: 'settings' }| { type: 'library' }| { type: 'libraryAgent'; agentId: string }@@ -22,7 +23,7 @@ export type RoutePlace =export type RoutesConfig = {/** Passed to the router; not used for our own match/build (router strips it). */basename?: string;- /** `agent` and `session` templates MUST keep their `:param` segment to stay addressable. */+ /** Parameterized templates MUST keep their `:param` segment to stay addressable. */paths?: {/** New-chat / landing. Default `'/'`. */root?: string;@@ -40,6 +41,8 @@ export type RoutesConfig = {agent?: string | false;/** Session deep link. `false` disables. Default `'/sessions/:sessionId'`. */session?: string | false;+ /** Detail-only session share link. `false` disables. Default `'/sessions/share/:sessionId'`. */+ sharedSession?: string | false;/** All-user sessions browser. `false` disables. Default `'/sessions'`. */sessionsBrowser?: string | false;};@@ -56,6 +59,7 @@ export type ResolvedRoutes = {buildAgent: string | null;agent: string | null;session: string | null;+ sharedSession: string | null;sessionsBrowser: string | null;};@@ -64,6 +68,7 @@ export type ShellSnapshot = {settingsOpen: boolean;libraryOpen: boolean;sessionsOpen: boolean;+ sharedSessionId: string | null;libraryAgentId: string | null;schedulesOpen: boolean;pendingSessionId?: string;diff --git a/packages/trueforge-ui/src/server/ShellModeContext.tsx b/packages/trueforge-ui/src/server/ShellModeContext.tsxindex 95ce0a133..d341efa71 100644--- a/packages/trueforge-ui/src/server/ShellModeContext.tsx+++ b/packages/trueforge-ui/src/server/ShellModeContext.tsx@@ -102,6 +102,10 @@ type ShellModeContextValue = {/** All-user sessions browser (includes drafts). */sessionsOpen: boolean;setSessionsOpen: (open: boolean) => void;+ /** Session shown in the detail-only sharing surface. */+ sharedSessionId: string | null;+ openSharedSession: (sessionId: string) => void;+ closeSharedSession: () => void;openLibraryAgent: (agentId: string) => void;closeLibraryAgent: () => void;schedulesOpen: boolean;@@ -243,6 +247,7 @@ export function ShellModeProvider({const [agentConfigOpenState, setAgentConfigOpenState] = useState(false);const [libraryOpenState, setLibraryOpenState] = useState(false);const [sessionsOpenState, setSessionsOpenState] = useState(false);+ const [sharedSessionId, setSharedSessionId] = useState<string | null>(null);const [libraryAgentId, setLibraryAgentId] = useState<string | null>(null);const [schedulesOpenState, setSchedulesOpenState] = useState(false);const [historyAgentFilter, setHistoryAgentFilter] = useState<HistoryAgentFilter | null>(null);@@ -264,12 +269,33 @@ export function ShellModeProvider({setLibraryAgentId(null);setSchedulesOpenState(false);} else {- replaceSessionShareSearch({ view: null });+ replaceSessionShareSearch({+ view: null,+ ...(sharedSessionId == null ? {} : { sessionId: null }),+ });}+ setSharedSessionId(null);setSessionsOpenState(sessionsEnabled && open);},+ [sessionsEnabled, sharedSessionId],+ );+ const openSharedSession = useCallback(+ (sessionId: string) => {+ if (!sessionsEnabled) return;+ setSettingsOpenState(false);+ setAgentConfigOpenState(false);+ setLibraryOpenState(false);+ setLibraryAgentId(null);+ setSchedulesOpenState(false);+ setSharedSessionId(sessionId);+ setSessionsOpenState(true);+ },[sessionsEnabled],);+ const closeSharedSession = useCallback(() => {+ setSharedSessionId(null);+ replaceSessionShareSearch({ sessionId: null, view: 'sessions' });+ }, []);const setLibraryOpen = useCallback((open: boolean) => {if (!isLibraryEnabled) return;@@ -656,6 +682,9 @@ export function ShellModeProvider({setLibraryOpen,sessionsOpen,setSessionsOpen,+ sharedSessionId,+ openSharedSession,+ closeSharedSession,openLibraryAgent,closeLibraryAgent,schedulesOpen,@@ -694,6 +723,9 @@ export function ShellModeProvider({setLibraryOpen,sessionsOpen,setSessionsOpen,+ sharedSessionId,+ openSharedSession,+ closeSharedSession,openLibraryAgent,closeLibraryAgent,schedulesOpen,diff --git a/packages/trueforge-ui/src/server/createTrueForgeServer.ts b/packages/trueforge-ui/src/server/createTrueForgeServer.tsindex 722562e55..47d53f29c 100644--- a/packages/trueforge-ui/src/server/createTrueForgeServer.ts+++ b/packages/trueforge-ui/src/server/createTrueForgeServer.ts@@ -52,6 +52,8 @@ export type CreateTrueForgeServerOptions<schedules?: TSchedules;/** Per-resource grants. Omit to leave actions enabled. */permissions?: TPermissions;+ /** Authenticated caller identity. Used for tenant-scoped share copy. */+ getMe?: () => Promise<{ tenantId: string }>;};export type TrueForgeServer<@@ -74,6 +76,7 @@ export type TrueForgeServer<metrics?: TMetrics;schedules?: TSchedules;permissions?: TPermissions;+ getMe?: () => Promise<{ tenantId: string }>;};/**@@ -162,6 +165,7 @@ export function createTrueForgeServer<...(opts.metrics != null ? { metrics: opts.metrics } : {}),...(opts.schedules != null ? { schedules: opts.schedules } : {}),...(opts.permissions != null ? { permissions: opts.permissions } : {}),+ ...(opts.getMe != null ? { getMe: opts.getMe } : {}),};return server;}diff --git a/packages/trueforge-ui/src/server/serverChrome.ts b/packages/trueforge-ui/src/server/serverChrome.tsindex 95934a6c7..9246b2638 100644--- a/packages/trueforge-ui/src/server/serverChrome.ts+++ b/packages/trueforge-ui/src/server/serverChrome.ts@@ -52,6 +52,7 @@ export function toEffectiveRoutes({...routes,settings: isSettingsChromeEnabled({ catalog, capabilities }) ? routes.settings : null,sessionsBrowser: sessionsEnabled ? routes.sessionsBrowser : null,+ sharedSession: sessionsEnabled ? routes.sharedSession : null,libraryAgent: sessionsEnabled ? routes.libraryAgent : null,schedules: isSchedulesChromeEnabled({ schedules }) ? routes.schedules : null,};diff --git a/packages/trueforge-ui/src/theme/defaultSlots.ts b/packages/trueforge-ui/src/theme/defaultSlots.tsindex 6f7770d68..2f85523ca 100644--- a/packages/trueforge-ui/src/theme/defaultSlots.ts+++ b/packages/trueforge-ui/src/theme/defaultSlots.ts@@ -80,6 +80,8 @@ import { SchedulesButton } from '../atoms/SchedulesButton.js';import { ScrollToBottomButton } from '../atoms/ScrollToBottomButton.js';import { SelectAgentEmptyState } from '../atoms/SelectAgentEmptyState.js';import { SessionsBrowserButton } from '../atoms/SessionsBrowserButton.js';+import { ShareChatButton } from '../atoms/ShareChatButton.js';+import { ShareSessionDialog } from '../atoms/ShareSessionDialog.js';import { ShellActionsActionSlot } from '../atoms/ShellActionsActionSlot.js';import { MessageListSkeleton } from '../atoms/Skeletons.js';import { SubAgentCard } from '../atoms/SubAgentCard.js';@@ -243,6 +245,8 @@ export const defaultSlots = {SaveAgentForm,SelectAgentEmptyState,ClearChatButton,+ ShareChatButton,+ ShareSessionDialog,ThreadListRowSkeleton,ThreadListEmptyState,ThreadListShell,diff --git a/packages/trueforge-ui/src/utils/sessionAccessError.ts b/packages/trueforge-ui/src/utils/sessionAccessError.tsnew file mode 100644index 000000000..bd7cfa60b--- /dev/null+++ b/packages/trueforge-ui/src/utils/sessionAccessError.ts@@ -0,0 +1,16 @@+/**+ * Report a failed session open. Prefer host `onError` when provided; fall back+ * to toaster `showError`. The backend message is shown as-is.+ */+export function reportSessionAccessError({+ error,+ onError,+ showError,+}: {+ error: unknown;+ onError?: (error: unknown) => void;+ showError?: (error: unknown) => void;+}): void {+ const report = onError ?? showError;+ report?.(error);+}diff --git a/packages/trueforge-ui/src/utils/sessionShareUrl.ts b/packages/trueforge-ui/src/utils/sessionShareUrl.tsindex edf4e212a..bb0bb5be7 100644--- a/packages/trueforge-ui/src/utils/sessionShareUrl.ts+++ b/packages/trueforge-ui/src/utils/sessionShareUrl.ts@@ -3,6 +3,7 @@ export const AGENT_ID_QUERY = 'agentId';export const AGENT_TAB_QUERY = 'tab';export const SESSIONS_VIEW_QUERY = 'view';export const SESSIONS_VIEW_VALUE = 'sessions';+export const SHARED_SESSION_VIEW_VALUE = 'shared-session';export const SESSION_START_TIME_QUERY = 's_sts';export const SESSION_END_TIME_QUERY = 's_ets';export const SESSION_TIME_WINDOW_QUERY = 's_tw';@@ -12,6 +13,7 @@ export const DEFAULT_SESSION_TIME_WINDOW_MS = 30 * 24 * 60 * 60 * 1000;export const DEFAULT_METRICS_TIME_WINDOW_MS = 24 * 60 * 60 * 1000;export type LibraryAgentTab = 'overview' | 'sessions' | 'schedules' | 'code' | 'metrics';+export type SessionShareView = typeof SESSIONS_VIEW_VALUE | typeof SHARED_SESSION_VIEW_VALUE;export type SessionTimeRange = {startTs: number;@@ -23,7 +25,7 @@ export type SessionShareSearch = {sessionId: string | null;agentId: string | null;tab: LibraryAgentTab | null;- view: typeof SESSIONS_VIEW_VALUE | null;+ view: SessionShareView | null;timeRange: SessionTimeRange | null;};@@ -31,7 +33,7 @@ export type SessionShareWrite = {sessionId?: string | null;agentId?: string | null;tab?: LibraryAgentTab | null;- view?: typeof SESSIONS_VIEW_VALUE | null;+ view?: SessionShareView | null;timeRange?: SessionTimeRange | null;};@@ -101,7 +103,7 @@ export function readSessionShareSearch(search: string): SessionShareSearch {sessionId: nonEmpty(params.get(SESSION_ID_QUERY)),agentId: nonEmpty(params.get(AGENT_ID_QUERY)),tab: parseLibraryAgentTab(params.get(AGENT_TAB_QUERY)),- view: view === SESSIONS_VIEW_VALUE ? SESSIONS_VIEW_VALUE : null,+ view: view === SESSIONS_VIEW_VALUE || view === SHARED_SESSION_VIEW_VALUE ? view : null,timeRange:startTs != null && endTs != null? { startTs, endTs }diff --git a/packages/trueforge-ui/test/atoms/AgentSessionDetailHeader.test.tsx b/packages/trueforge-ui/test/atoms/AgentSessionDetailHeader.test.tsxindex 026436b84..197175c55 100644--- a/packages/trueforge-ui/test/atoms/AgentSessionDetailHeader.test.tsx+++ b/packages/trueforge-ui/test/atoms/AgentSessionDetailHeader.test.tsx@@ -1,12 +1,10 @@// @vitest-environment jsdom-import { fireEvent, render, screen, waitFor } from '@testing-library/react';-import { afterEach, describe, expect, it, vi } from 'vitest';+import { fireEvent, render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';import { AgentSessionDetailHeader } from '@/atoms/agent-details/AgentSessionDetailHeader.js';import { buildAgentSessionShareUrl } from '@/utils/sessionShareUrl.js';-const clipboardDescriptor = Object.getOwnPropertyDescriptor(navigator, 'clipboard');-describe('buildAgentSessionShareUrl', () => {it('puts agent id and session id on the current page URL', () => {const href = buildAgentSessionShareUrl({@@ -22,40 +20,26 @@ describe('buildAgentSessionShareUrl', () => {});describe('AgentSessionDetailHeader', () => {- afterEach(() => {- if (clipboardDescriptor === undefined) {- Reflect.deleteProperty(navigator, 'clipboard');- } else {- Object.defineProperty(navigator, 'clipboard', clipboardDescriptor);- }- });+ it('keeps title and session id on one line and shows Share', () => {+ render(<AgentSessionDetailHeader title="Help me find more details" sessionId="sess-1" onClose={() => undefined} />);- it('keeps title and session id on one line and copies the session link', async () => {- const writeText = vi.fn(async () => undefined);- Object.defineProperty(navigator, 'clipboard', { configurable: true, value: { writeText } });+ const heading = screen.getByRole('heading', { name: 'Help me find more details' });+ expect(heading.parentElement).toHaveClass('items-center');+ expect(heading.parentElement).toHaveTextContent('sess-1');+ expect(screen.getByRole('button', { name: 'Share' })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Copy session link' })).not.toBeInTheDocument();+ });+ it('disables Share when canShare is false', () => {render(<AgentSessionDetailHeadertitle="Help me find more details"sessionId="sess-1"- agentId="agent-1"onClose={() => undefined}+ canShare={false}/>,);-- const heading = screen.getByRole('heading', { name: 'Help me find more details' });- expect(heading.parentElement).toHaveClass('items-center');- expect(heading.parentElement).toHaveTextContent('sess-1');-- const copyButton = screen.getByRole('button', { name: 'Copy session link' });- fireEvent.mouseEnter(copyButton);- expect(screen.getByRole('tooltip')).toHaveTextContent('Copy session link');-- fireEvent.click(copyButton);- await waitFor(() => {- expect(writeText).toHaveBeenCalledWith(buildAgentSessionShareUrl({ sessionId: 'sess-1', agentId: 'agent-1' }));- expect(screen.getByRole('tooltip')).toHaveTextContent('Copied');- });+ expect(screen.getByRole('button', { name: 'Share' })).toBeDisabled();});it('shows Resume Chat as a new-tab link with an external icon', () => {@@ -104,4 +88,19 @@ describe('AgentSessionDetailHeader', () => {expect(screen.getByRole('link', { name: /Resume Chat/i })).toBeInTheDocument();expect(screen.queryByRole('button', { name: 'Resume Chat' })).not.toBeInTheDocument();});++ it('disables Resume Chat when the session is read-only', () => {+ render(+ <AgentSessionDetailHeader+ title="Help me find more details"+ sessionId="sess-1"+ onClose={() => undefined}+ resumeHref="https://app.example/sessions/sess-1"+ resumeLabel="Resume Chat"+ canResume={false}+ />,+ );+ expect(screen.getByRole('button', { name: 'Resume Chat' })).toBeDisabled();+ expect(screen.queryByRole('link', { name: /Resume Chat/i })).not.toBeInTheDocument();+ });});diff --git a/packages/trueforge-ui/test/atoms/ClearChatButton.test.tsx b/packages/trueforge-ui/test/atoms/ClearChatButton.test.tsxindex 8bea6b0bc..95b3c6240 100644--- a/packages/trueforge-ui/test/atoms/ClearChatButton.test.tsx+++ b/packages/trueforge-ui/test/atoms/ClearChatButton.test.tsx@@ -37,7 +37,7 @@ describe('ClearChatButton', () => {</ShellModeProvider></SlotsProvider>,);- expect(screen.queryByRole('button', { name: 'Clear chat' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'New Chat' })).not.toBeInTheDocument();});it('is hidden on a fresh chat with no messages', () => {@@ -50,7 +50,7 @@ describe('ClearChatButton', () => {</ShellModeProvider></SlotsProvider>,);- expect(screen.queryByRole('button', { name: 'Clear chat' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'New Chat' })).not.toBeInTheDocument();});it('is hidden on a fresh draft (New Chat / New Agent)', () => {@@ -63,7 +63,7 @@ describe('ClearChatButton', () => {</ShellModeProvider></SlotsProvider>,);- expect(screen.queryByRole('button', { name: 'Clear chat' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'New Chat' })).not.toBeInTheDocument();});it('is visible on mutable sessions', () => {@@ -76,7 +76,7 @@ describe('ClearChatButton', () => {</ShellModeProvider></SlotsProvider>,);- expect(screen.getByRole('button', { name: 'Clear chat' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: 'New Chat' })).toBeInTheDocument();});it('calls clearChat when clicked after a chat has started', () => {@@ -89,8 +89,8 @@ describe('ClearChatButton', () => {</ShellModeProvider></SlotsProvider>,);- expect(screen.getByRole('button', { name: 'Clear chat' })).toBeInTheDocument();- fireEvent.click(screen.getByRole('button', { name: 'Clear chat' }));+ expect(screen.getByRole('button', { name: 'New Chat' })).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'New Chat' }));});});diff --git a/packages/trueforge-ui/test/atoms/PermissionGuard.test.tsx b/packages/trueforge-ui/test/atoms/PermissionGuard.test.tsxindex 7306d814b..30982acf4 100644--- a/packages/trueforge-ui/test/atoms/PermissionGuard.test.tsx+++ b/packages/trueforge-ui/test/atoms/PermissionGuard.test.tsx@@ -27,6 +27,8 @@ describe('PermissionGuard', () => {const button = screen.getByRole('button', { name: 'Update' });expect(button).toBeDisabled();fireEvent.mouseEnter(button.parentElement ?? button);- expect(screen.getByRole('tooltip')).toHaveTextContent('Missing MANAGE permission');+ const tooltip = screen.getByRole('tooltip');+ expect(tooltip).toHaveTextContent('Missing MANAGE permission');+ expect(tooltip).toHaveStyle({ transform: 'translate(-50%, 0)' });});});diff --git a/packages/trueforge-ui/test/atoms/SessionsPage.test.tsx b/packages/trueforge-ui/test/atoms/SessionsPage.test.tsxindex 461b39db2..a0190ec1c 100644--- a/packages/trueforge-ui/test/atoms/SessionsPage.test.tsx+++ b/packages/trueforge-ui/test/atoms/SessionsPage.test.tsx@@ -3,6 +3,7 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { SessionsPage } from '@/atoms/agent-details/SessionsPage.js';+import { ToasterProvider } from '@/containers/ToasterContainer.js';import { ServerProvider } from '@/server/ServerContext.js';import { ShellModeProvider } from '@/server/ShellModeContext.js';import type {@@ -44,8 +45,15 @@ type ListSessionsRequest = {const originalShowModal = Object.getOwnPropertyDescriptor(HTMLDialogElement.prototype, 'showModal');const originalClose = Object.getOwnPropertyDescriptor(HTMLDialogElement.prototype, 'close');+const originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard');+let clipboardWriteText: ReturnType<typeof vi.fn>;beforeEach(() => {+ clipboardWriteText = vi.fn(async () => undefined);+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: { writeText: clipboardWriteText },+ });Object.defineProperty(HTMLDialogElement.prototype, 'showModal', {configurable: true,value: function showModal(this: HTMLDialogElement) {@@ -74,6 +82,11 @@ afterEach(() => {} else {Object.defineProperty(HTMLDialogElement.prototype, 'close', originalClose);}+ if (originalClipboard === undefined) {+ Reflect.deleteProperty(navigator, 'clipboard');+ } else {+ Object.defineProperty(navigator, 'clipboard', originalClipboard);+ }});function renderPage({@@ -106,11 +119,13 @@ function renderPage({});render(<SlotsProvider>- <ServerProvider server={server}>- <ShellModeProvider>- <SessionsPage />- </ShellModeProvider>- </ServerProvider>+ <ToasterProvider>+ <ServerProvider server={server}>+ <ShellModeProvider>+ <SessionsPage />+ </ShellModeProvider>+ </ServerProvider>+ </ToasterProvider></SlotsProvider>,);return { listSessions, listSessionEvents, getSession, deleteSession };@@ -214,6 +229,47 @@ describe('SessionsPage', () => {expect(getSession).toHaveBeenCalledWith({ sessionId: 'sess-1' });});+ it('toasts and keeps the inline failure when a non-share detail load is forbidden', async () => {+ window.history.replaceState(null, '', '/?view=sessions&sessionId=sess-1');+ const forbidden = Object.assign(new Error('Only the session creator can access this session'), {+ statusCode: 403,+ });+ vi.spyOn(console, 'error').mockImplementation(() => {});+ renderPage({+ listSessions: vi.fn(async () => ({ data: [namedRow] })),+ listSessionEvents: vi.fn(async () => {+ throw forbidden;+ }),+ getSession: vi.fn(async () => {+ throw forbidden;+ }),+ });++ expect(await screen.findByText('Session details could not be loaded.')).toBeInTheDocument();+ expect(await screen.findByText('Only the session creator can access this session')).toBeInTheDocument();+ expect(window.location.search).toContain('sessionId=sess-1');+ });++ it('copies the no-router shared-session query URL for the selected session', async () => {+ window.history.replaceState(null, '', '/?view=sessions&sessionId=sess-1&agentId=agent-1&s_tw=30');+ renderPage();++ fireEvent.click(await screen.findByRole('button', { name: 'Share' }));+ expect(await screen.findByText('Change permissions')).toBeInTheDocument();+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Copy' }));++ await waitFor(() => {+ expect(clipboardWriteText).toHaveBeenCalledOnce();+ });+ const copied = new URL(String(clipboardWriteText.mock.calls[0]?.[0]));+ expect(copied.pathname).toBe('/');+ expect(copied.searchParams.get('view')).toBe('shared-session');+ expect(copied.searchParams.get('sessionId')).toBe('sess-1');+ expect(copied.searchParams.get('agentId')).toBeNull();+ expect(copied.searchParams.get('s_tw')).toBeNull();+ });+it('shows the custom range picker only after Custom Time Range is clicked', async () => {renderPage();const timeButton = await screen.findByRole('button', { name: 'Last 30 days' });@@ -346,6 +402,23 @@ describe('SessionsPage', () => {expect(screen.getByText('Draft session')).toBeInTheDocument();});+ it('disables Share without session MANAGE permission', async () => {+ window.history.replaceState(null, '', '/?view=sessions&sessionId=sess-1&s_tw=30');+ renderPage({+ permissions: {+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'session', permissions: { 'sess-1': [], 'sess-draft': ['MANAGE'] } },+ })),+ },+ });++ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Share' })).toBeDisabled();+ });+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));+ expect(screen.queryByText('Change permissions')).not.toBeInTheDocument();+ });+it('disables Delete without session DELETE permission', async () => {const deleteSession = vi.fn(async () => undefined);renderPage({diff --git a/packages/trueforge-ui/test/atoms/ShareChatButton.test.tsx b/packages/trueforge-ui/test/atoms/ShareChatButton.test.tsxnew file mode 100644index 000000000..25c13308a--- /dev/null+++ b/packages/trueforge-ui/test/atoms/ShareChatButton.test.tsx@@ -0,0 +1,99 @@+// @vitest-environment jsdom+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++const activeThread = vi.hoisted(() => ({ remoteId: null as string | null }));++vi.mock('@/assistant-ui.js', () => ({+ useAuiState: (selector: (state: { threadListItem: { remoteId: string | null } }) => unknown) =>+ selector({ threadListItem: { remoteId: activeThread.remoteId } }),+}));++import { ShareChatButton } from '@/atoms/ShareChatButton.js';+import { ActiveSessionPermissionsProvider } from '@/hooks/useResourcePermissions.js';+import { resolveRoutesConfig } from '@/routing/paths.js';+import { ResolvedRoutesProvider } from '@/routing/ResolvedRoutesContext.js';+import { ServerProvider } from '@/server/ServerContext.js';+import type { ListPermissionsResponse } from '@/server/types.js';+import { SlotsProvider } from '@/theme/SlotsProvider.js';+import { createMockAgentUIServer } from '../server/mockServer.js';++const originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard');+let writeText: ReturnType<typeof vi.fn>;++beforeEach(() => {+ activeThread.remoteId = null;+ writeText = vi.fn(async () => undefined);+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: { writeText },+ });+});++afterEach(() => {+ vi.restoreAllMocks();+ if (originalClipboard === undefined) {+ Reflect.deleteProperty(navigator, 'clipboard');+ } else {+ Object.defineProperty(navigator, 'clipboard', originalClipboard);+ }+});++describe('ShareChatButton', () => {+ it('is hidden until the active chat has a persisted session id', () => {+ render(+ <SlotsProvider>+ <ShareChatButton />+ </SlotsProvider>,+ );++ expect(screen.queryByRole('button', { name: 'Share' })).not.toBeInTheDocument();+ });++ it('opens the share popover and copies the routed shared-session URL', async () => {+ activeThread.remoteId = 'session-1';+ render(+ <SlotsProvider>+ <ResolvedRoutesProvider routes={resolveRoutesConfig()}>+ <ShareChatButton />+ </ResolvedRoutesProvider>+ </SlotsProvider>,+ );++ fireEvent.click(screen.getByRole('button', { name: 'Share' }));+ expect(await screen.findByText('Change permissions')).toBeInTheDocument();+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();++ fireEvent.click(screen.getByRole('button', { name: 'Copy' }));+ await waitFor(() => {+ expect(writeText).toHaveBeenCalledOnce();+ });+ expect(new URL(String(writeText.mock.calls[0]?.[0])).pathname).toBe('/sessions/share/session-1');+ });++ it('disables Share without session MANAGE permission', async () => {+ activeThread.remoteId = 'session-1';+ const server = createMockAgentUIServer({+ permissions: {+ listPermissions: vi.fn(async (): Promise<ListPermissionsResponse> => ({+ data: { type: 'session', permissions: { 'session-1': [] } },+ })),+ },+ });+ render(+ <SlotsProvider>+ <ServerProvider server={server}>+ <ActiveSessionPermissionsProvider sessionId="session-1">+ <ShareChatButton />+ </ActiveSessionPermissionsProvider>+ </ServerProvider>+ </SlotsProvider>,+ );++ await waitFor(() => {+ expect(screen.getByRole('button', { name: 'Share' })).toBeDisabled();+ });+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));+ expect(screen.queryByText('Change permissions')).not.toBeInTheDocument();+ });+});diff --git a/packages/trueforge-ui/test/atoms/ShareSessionDialog.test.tsx b/packages/trueforge-ui/test/atoms/ShareSessionDialog.test.tsxnew file mode 100644index 000000000..bb19e21e2--- /dev/null+++ b/packages/trueforge-ui/test/atoms/ShareSessionDialog.test.tsx@@ -0,0 +1,138 @@+// @vitest-environment jsdom+import { fireEvent, render, screen, waitFor } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ShareSessionDialog } from '@/atoms/ShareSessionDialog.js';+import { ToasterProvider } from '@/containers/ToasterContainer.js';+import { resolveRoutesConfig } from '@/routing/paths.js';+import { ResolvedRoutesProvider } from '@/routing/ResolvedRoutesContext.js';+import { ServerProvider } from '@/server/ServerContext.js';+import { SlotsProvider } from '@/theme/SlotsProvider.js';+import { createMockAgentUIServer } from '../server/mockServer.js';++const originalClipboard = Object.getOwnPropertyDescriptor(navigator, 'clipboard');+let writeText: ReturnType<typeof vi.fn>;++beforeEach(() => {+ writeText = vi.fn(async () => undefined);+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: { writeText },+ });+});++afterEach(() => {+ vi.restoreAllMocks();+ if (originalClipboard === undefined) {+ Reflect.deleteProperty(navigator, 'clipboard');+ } else {+ Object.defineProperty(navigator, 'clipboard', originalClipboard);+ }+});++function renderDialog({+ getSession = vi.fn(async () => ({+ id: 'session-1',+ isMutable: true,+ shared: false,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ })),+ updateSession = vi.fn(async (req: { sessionId: string; shared?: boolean }) => ({+ id: req.sessionId,+ isMutable: true,+ shared: req.shared === true,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ })),+ getMe = vi.fn(async () => ({ tenantId: 'acme' })),+}: {+ getSession?: () => Promise<{+ id: string;+ isMutable: boolean;+ shared?: boolean;+ createdAt: string;+ updatedAt: string;+ }>;+ updateSession?: (req: { sessionId: string; shared?: boolean }) => Promise<{+ id: string;+ isMutable: boolean;+ shared?: boolean;+ createdAt: string;+ updatedAt: string;+ }>;+ getMe?: () => Promise<{ tenantId: string }>;+} = {}) {+ const server = createMockAgentUIServer({ getSession, updateSession, getMe });+ render(+ <SlotsProvider>+ <ToasterProvider>+ <ServerProvider server={server}>+ <ResolvedRoutesProvider routes={resolveRoutesConfig()}>+ <ShareSessionDialog sessionId="session-1" trigger={<button type="button">Share</button>} />+ </ResolvedRoutesProvider>+ </ServerProvider>+ </ToasterProvider>+ </SlotsProvider>,+ );+ return { getSession, updateSession, getMe };+}++async function openSharePopover() {+ fireEvent.click(screen.getByRole('button', { name: 'Share' }));+ expect(await screen.findByText('Change permissions')).toBeInTheDocument();+ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+}++describe('ShareSessionDialog', () => {+ it('loads current sharing and copies the share URL', async () => {+ renderDialog();+ await openSharePopover();++ expect(await screen.findByRole('button', { name: 'Session sharing' })).toHaveTextContent('Only you');+ expect((screen.getByLabelText('Share URL') as HTMLInputElement).value).toContain('/sessions/share/session-1');++ fireEvent.click(screen.getByRole('button', { name: 'Copy' }));+ await waitFor(() => {+ expect(writeText).toHaveBeenCalledOnce();+ });+ expect(new URL(String(writeText.mock.calls[0]?.[0])).pathname).toBe('/sessions/share/session-1');+ expect(screen.getByRole('button', { name: 'Copied' })).toBeInTheDocument();+ });++ it('closes permission options on outside click without PATCHing', async () => {+ const { updateSession } = renderDialog();+ await openSharePopover();++ fireEvent.click(await screen.findByRole('button', { name: 'Session sharing' }));+ expect(await screen.findByRole('option', { name: 'Everyone within acme' })).toBeInTheDocument();++ fireEvent.mouseDown(screen.getByText('Change permissions'));++ expect(screen.queryByRole('option', { name: 'Everyone within acme' })).not.toBeInTheDocument();+ expect(updateSession).not.toHaveBeenCalled();+ });++ it('closes the permission menu without PATCHing when the current option is clicked', async () => {+ const { updateSession } = renderDialog();+ await openSharePopover();++ fireEvent.click(await screen.findByRole('button', { name: 'Session sharing' }));+ fireEvent.click(await screen.findByRole('option', { name: 'Only you' }));++ expect(screen.queryByRole('option', { name: 'Only you' })).not.toBeInTheDocument();+ expect(updateSession).not.toHaveBeenCalled();+ });++ it('PATCHes shared when the tenant permission is selected', async () => {+ const { updateSession } = renderDialog();+ await openSharePopover();++ fireEvent.click(await screen.findByRole('button', { name: 'Session sharing' }));+ fireEvent.click(await screen.findByRole('option', { name: 'Everyone within acme' }));++ await waitFor(() => {+ expect(updateSession).toHaveBeenCalledWith({ sessionId: 'session-1', shared: true });+ });+ });+});diff --git a/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx b/packages/trueforge-ui/test/atoms/ThreadShell.test.tsxindex cbac3f538..7f1875ea1 100644--- a/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx+++ b/packages/trueforge-ui/test/atoms/ThreadShell.test.tsx@@ -7,13 +7,13 @@ import { MessageGroup, ThreadComposerAreaShell, ThreadRootShell, ThreadViewportSdescribe('ThreadRootShell', () => {it('merges host styles over defaults and forwards its ref and attributes', () => {const ref = createRef<HTMLDivElement>();- const hostStyle = Object.assign({ color: 'red' }, { '--thread-max-width': '60rem' });+ const hostStyle = Object.assign({ color: 'red' }, { '--thread-max-width': '72rem' });render(<ThreadRootShell ref={ref} data-testid="thread-root" className="host-thread" style={hostStyle} />);const root = screen.getByTestId('thread-root');expect(root).toBe(ref.current);expect(root).toHaveClass('aui-thread-root', 'host-thread');- expect(root.style.getPropertyValue('--thread-max-width')).toBe('60rem');+ expect(root.style.getPropertyValue('--thread-max-width')).toBe('72rem');// Composer surface uses --input-box-bg on the theme root; thread shell must not set --composer-bg.expect(root.style.getPropertyValue('--composer-bg')).toBe('');expect(root.style.color).toBe('red');@@ -33,6 +33,7 @@ describe('ThreadViewportShell', () => {// CSS smooth scroll fights assistant-ui autoScroll and causes bounce on large streams.expect(viewport.className).not.toMatch(/\bscroll-smooth\b/);expect(viewport.firstElementChild).toHaveClass('min-h-full', 'justify-center', 'pb-4');+ expect(viewport.firstElementChild).toHaveStyle({ maxWidth: 'var(--thread-max-width, 44rem)' });expect(viewport).toHaveTextContent('Welcome');rerender(@@ -43,6 +44,19 @@ describe('ThreadViewportShell', () => {expect(viewport.firstElementChild).toHaveClass('pb-32');expect(viewport.firstElementChild).not.toHaveClass('justify-center');});++ it('can leave scrolling to a parent surface', () => {+ render(<ThreadViewportShell scrollable={false} data-testid="viewport" />);++ expect(screen.getByTestId('viewport')).toHaveClass('shrink-0', 'overflow-visible');+ expect(screen.getByTestId('viewport')).not.toHaveClass('overflow-y-auto');+ });++ it('supports a wider content surface without changing the default', () => {+ render(<ThreadViewportShell contentMaxWidth="60rem" data-testid="viewport" />);++ expect(screen.getByTestId('viewport').firstElementChild).toHaveStyle({ maxWidth: '60rem' });+ });});describe('ThreadComposerAreaShell', () => {diff --git a/packages/trueforge-ui/test/atoms/primitives/Tooltip.test.tsx b/packages/trueforge-ui/test/atoms/primitives/Tooltip.test.tsxindex 5eda8814b..50a104afa 100644--- a/packages/trueforge-ui/test/atoms/primitives/Tooltip.test.tsx+++ b/packages/trueforge-ui/test/atoms/primitives/Tooltip.test.tsx@@ -1,7 +1,7 @@import { act, fireEvent, render, screen } from '@testing-library/react';import { describe, expect, it, vi } from 'vitest';-import { clampCenteredTooltip, LightTooltip, Tooltip } from '@/atoms/primitives/Tooltip.js';+import { clampCenteredTooltip, clampEdgeTooltip, LightTooltip, Tooltip } from '@/atoms/primitives/Tooltip.js';describe('Tooltip', () => {it('shows and hides on hover while merging the child callbacks', () => {@@ -179,6 +179,34 @@ describe('Tooltip', () => {).toEqual({ left: 108, top: 40 });});+ it('clamps a right-side tooltip so it stays inside the viewport', () => {+ expect(+ clampEdgeTooltip({+ left: 860,+ top: 40,+ width: 200,+ height: 32,+ side: 'right',+ viewportWidth: 900,+ viewportHeight: 600,+ }),+ ).toEqual({ left: 692, top: 40 });+ });++ it('opens to the right of the trigger when side is right', () => {+ render(+ <Tooltip content="Beside tip" side="right">+ <button>Anchor</button>+ </Tooltip>,+ );++ fireEvent.mouseEnter(screen.getByRole('button', { name: 'Anchor' }));++ const tooltip = screen.getByRole('tooltip');+ expect(tooltip).toHaveTextContent('Beside tip');+ expect(tooltip).toHaveStyle({ transform: 'translate(0, -50%)' });+ });+it('opens below the trigger when side is bottom', () => {render(<Tooltip content="Below tip" side="bottom">diff --git a/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx b/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsxindex 059e8b29f..48332ef80 100644--- a/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx+++ b/packages/trueforge-ui/test/containers/AgentSessionTimelineContainer.test.tsx@@ -158,7 +158,7 @@ describe('AgentSessionTimelineContainer', () => {const scrollIntoView = vi.fn();HTMLElement.prototype.scrollIntoView = scrollIntoView;- render(+ const { container } = render(<SlotsProvideroverrides={{AgentSessionEventTimeline: ({ turns, onSelectTurn }) => (@@ -179,6 +179,13 @@ describe('AgentSessionTimelineContainer', () => {expect(screen.getByText('Turn')).toBeInTheDocument();expect(screen.getByText('Duration')).toBeInTheDocument();expect(await screen.findAllByRole('button', { name: 'Copy' })).not.toHaveLength(0);+ expect(container.querySelector('[data-slot="agent-session-scroll"]')).toHaveClass('overflow-y-auto');+ expect(container.querySelector('[data-slot="agent-session-metrics-sticky"]')).toHaveClass(+ 'sticky',+ 'top-0',+ 'bg-primary-bg',+ );+ expect(container.querySelector('[data-slot="aui_thread-viewport"]')).toHaveClass('overflow-visible');fireEvent.click(screen.getByRole('button', { name: 'timeline turns=1' }));await waitFor(() => {expect(scrollIntoView).toHaveBeenCalled();diff --git a/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx b/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsxindex 777e7b68b..6564a6d5f 100644--- a/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx+++ b/packages/trueforge-ui/test/containers/TrueForgeUI.test.tsx@@ -778,6 +778,10 @@ describe('layout slot overrides', () => {return <button type="button">custom clear</button>;}+ function CustomShareChat() {+ return <button type="button">custom share</button>;+ }+function CustomSaveAgent() {return <button type="button">custom save</button>;}@@ -807,12 +811,17 @@ describe('layout slot overrides', () => {);expect(screen.getByRole('button', { name: 'custom clear' })).toBeInTheDocument();- expect(screen.queryByRole('button', { name: 'Clear chat' })).not.toBeInTheDocument();});- it.each(hosts)('%s places Clear Chat immediately before Save Agent', (_name, Layout) => {+ it.each(hosts)('%s places Share, New Chat, and Save Agent in order', (_name, Layout) => {render(- <SlotsProvider overrides={{ ClearChatButton: CustomClearChat, SaveAgentButton: CustomSaveAgent }}>+ <SlotsProvider+ overrides={{+ ShareChatButton: CustomShareChat,+ ClearChatButton: CustomClearChat,+ SaveAgentButton: CustomSaveAgent,+ }}+ ><ShellModeProvider agentConfig={{ mode: 'SingleAgent', name: 'a' }}><RuntimeHarness messages={[]}><div className="h-96">@@ -823,8 +832,10 @@ describe('layout slot overrides', () => {</SlotsProvider>,);+ const shareChat = screen.getByRole('button', { name: 'custom share' });const clearChat = screen.getByRole('button', { name: 'custom clear' });const saveAgent = screen.getByRole('button', { name: 'custom save' });+ expect(shareChat.nextElementSibling).toBe(clearChat);expect(clearChat.nextElementSibling).toBe(saveAgent);});diff --git a/packages/trueforge-ui/test/publicUiExports.test.ts b/packages/trueforge-ui/test/publicUiExports.test.tsindex 7ed02616a..2fac93335 100644--- a/packages/trueforge-ui/test/publicUiExports.test.ts+++ b/packages/trueforge-ui/test/publicUiExports.test.ts@@ -117,6 +117,8 @@ const expectedRuntimeExports: Array<keyof typeof sdk> = ['ServerProvider','SessionsBrowserButton','SessionsPage',+ 'ShareChatButton',+ 'ShareSessionDialog','ShellActionsActionSlot','ShellModeProvider','SideDrawer',diff --git a/packages/trueforge-ui/test/routing/LibrarySessionShareBoot.test.tsx b/packages/trueforge-ui/test/routing/LibrarySessionShareBoot.test.tsxindex 2e563881d..ce127d5e9 100644--- a/packages/trueforge-ui/test/routing/LibrarySessionShareBoot.test.tsx+++ b/packages/trueforge-ui/test/routing/LibrarySessionShareBoot.test.tsx@@ -17,6 +17,7 @@ function Probe() {<div><span>{shell.libraryAgentId ?? 'none'}</span><span>{shell.sessionsOpen ? 'sessions-open' : 'sessions-closed'}</span>+ <span>{shell.sharedSessionId ?? 'no-shared-session'}</span></div>);}@@ -55,6 +56,13 @@ describe('LibrarySessionShareBoot', () => {expect(getByText('sessions-open')).toBeInTheDocument();});+ it('opens shared-session detail from the query fallback without a router', () => {+ window.history.replaceState(null, '', '/?view=shared-session&sessionId=sess-1');+ const { getByText } = renderBoot();+ expect(getByText('sessions-open')).toBeInTheDocument();+ expect(getByText('sess-1')).toBeInTheDocument();+ });+it('ignores ?view=sessions when sessions port is missing', () => {window.history.replaceState(null, '', '/?view=sessions');const { getByText } = renderBoot({ includeSessions: false });diff --git a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsxindex a17b601ca..c41e16ee2 100644--- a/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx+++ b/packages/trueforge-ui/test/routing/ShellRouteSync.test.tsx@@ -2,7 +2,7 @@import { act, render, waitFor } from '@testing-library/react';import { StrictMode, useEffect, useState, type ReactNode } from 'react';import { MemoryRouter, useLocation } from 'react-router-dom';-import { describe, expect, it } from 'vitest';+import { describe, expect, it, vi } from 'vitest';import { resolveRoutesConfig } from '@/routing/paths.js';import { ShellRouteSync } from '@/routing/ShellRouteSync.js';@@ -47,6 +47,7 @@ function SettingsCatalogProvider({includeCatalog = true,includeSessions = true,includeSchedules = false,+ getSession,}: {children: ReactNode;settingsEnabled?: boolean;@@ -54,6 +55,14 @@ function SettingsCatalogProvider({includeCatalog?: boolean;includeSessions?: boolean;includeSchedules?: boolean;+ getSession?: (req: { sessionId: string }) => Promise<{+ id: string;+ title: string;+ isMutable: boolean;+ createdAt: string;+ updatedAt: string;+ agentName?: string;+ }>;}) {const server = createMockAgentUIServer({...(includeCatalog ? { catalog: createMockCatalog() } : {}),@@ -69,13 +78,15 @@ function SettingsCatalogProvider({},};},- getSession: async ({ sessionId }) => ({- id: sessionId,- title: 'Session',- isMutable: true,- createdAt: '2026-01-01T00:00:00Z',- updatedAt: '2026-01-01T00:00:00Z',- }),+ getSession:+ getSession ??+ (async ({ sessionId }) => ({+ id: sessionId,+ title: 'Session',+ isMutable: true,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ })),// findAgentByName walks unfiltered pages and matches by exact name client-side.searchAgents: async () => [{ name: 'helper', agentId: 'helper-id' }],});@@ -91,6 +102,8 @@ function Harness({includeCatalog = true,includeSessions = true,includeSchedules = false,+ getSession,+ onError,}: {agentConfig?: AgentConfig;initialRemoteId?: string;@@ -100,6 +113,15 @@ function Harness({includeCatalog?: boolean;includeSessions?: boolean;includeSchedules?: boolean;+ getSession?: (req: { sessionId: string }) => Promise<{+ id: string;+ title: string;+ isMutable: boolean;+ createdAt: string;+ updatedAt: string;+ agentName?: string;+ }>;+ onError?: (error: unknown) => void;}) {const [remoteId, setId] = useState<string | undefined>(initialRemoteId);setRemoteId = setId;@@ -110,11 +132,17 @@ function Harness({includeCatalog={includeCatalog}includeSessions={includeSessions}includeSchedules={includeSchedules}+ getSession={getSession}><ShellModeProvider agentConfig={agentConfig} initialSettingsOpen={initialSettingsOpen}><CaptureShell /><CaptureLocation />- <ShellRouteSync routes={routes} activeRemoteId={remoteId} initialSettingsOpen={initialSettingsOpen} />+ <ShellRouteSync+ routes={routes}+ activeRemoteId={remoteId}+ initialSettingsOpen={initialSettingsOpen}+ onError={onError}+ /></ShellModeProvider></SettingsCatalogProvider>);@@ -129,6 +157,15 @@ function renderSync(opts: {includeCatalog?: boolean;includeSessions?: boolean;includeSchedules?: boolean;+ getSession?: (req: { sessionId: string }) => Promise<{+ id: string;+ title: string;+ isMutable: boolean;+ createdAt: string;+ updatedAt: string;+ agentName?: string;+ }>;+ onError?: (error: unknown) => void;strict?: boolean;}) {const tree = (@@ -141,6 +178,8 @@ function renderSync(opts: {includeCatalog={opts.includeCatalog}includeSessions={opts.includeSessions}includeSchedules={opts.includeSchedules}+ getSession={opts.getSession}+ onError={opts.onError}/></MemoryRouter>);@@ -154,6 +193,50 @@ describe('ShellRouteSync', () => {expect(pathname).toBe('/sessions/abc');});+ it('toasts and redirects to New Chat when a session deep link is forbidden', async () => {+ const onError = vi.fn();+ const forbidden = Object.assign(new Error('Only the session creator can access this session'), {+ statusCode: 403,+ });+ renderSync({+ initialEntries: ['/sessions/forbidden'],+ getSession: async () => {+ throw forbidden;+ },+ onError,+ });++ await waitFor(() => {+ expect(onError).toHaveBeenCalledOnce();+ });+ expect(onError).toHaveBeenCalledWith(forbidden);+ await waitFor(() => {+ expect(pathname).toBe('/');+ });+ expect(shell.pendingSessionId).toBeUndefined();+ });++ it('toasts and redirects to New Chat when a session deep link is not found', async () => {+ const onError = vi.fn();+ const notFound = Object.assign(new Error('Session not found: missing'), { statusCode: 404 });+ renderSync({+ initialEntries: ['/sessions/missing'],+ getSession: async () => {+ throw notFound;+ },+ onError,+ });++ await waitFor(() => {+ expect(onError).toHaveBeenCalledOnce();+ });+ expect(onError).toHaveBeenCalledWith(notFound);+ await waitFor(() => {+ expect(pathname).toBe('/');+ });+ expect(shell.pendingSessionId).toBeUndefined();+ });+it('applies an agent deep link on boot and resolves its history filter id', async () => {renderSync({ initialEntries: ['/agents/helper'], agentConfig: { mode: 'AgentLibrary' }, strict: true });expect(shell.mode).toMatchObject({ status: 'active', isMutable: false, agentName: 'helper' });diff --git a/packages/trueforge-ui/test/routing/derivePlace.test.ts b/packages/trueforge-ui/test/routing/derivePlace.test.tsindex 01587c7e2..e8c924652 100644--- a/packages/trueforge-ui/test/routing/derivePlace.test.ts+++ b/packages/trueforge-ui/test/routing/derivePlace.test.ts@@ -8,6 +8,7 @@ function snap(partial: Partial<ShellSnapshot>): ShellSnapshot {settingsOpen: false,libraryOpen: false,sessionsOpen: false,+ sharedSessionId: null,libraryAgentId: null,schedulesOpen: false,mode: { status: 'idle' },@@ -29,6 +30,13 @@ describe('derivePlace', () => {expect(derivePlace(snap({ sessionsOpen: true, pendingSessionId: 'abc' }))).toEqual({ type: 'sessionsBrowser' });});+ it('shared session wins over the sessions browser', () => {+ expect(derivePlace(snap({ sessionsOpen: true, sharedSessionId: 'shared-1' }))).toEqual({+ type: 'sharedSession',+ sessionId: 'shared-1',+ });+ });+it('library agent detail wins over the library list and chat place', () => {expect(derivePlace(snap({ libraryOpen: true, libraryAgentId: 'agent-1', pendingSessionId: 'abc' }))).toEqual({type: 'libraryAgent',diff --git a/packages/trueforge-ui/test/routing/paths.test.ts b/packages/trueforge-ui/test/routing/paths.test.tsindex 9ccd59796..c317bb34d 100644--- a/packages/trueforge-ui/test/routing/paths.test.ts+++ b/packages/trueforge-ui/test/routing/paths.test.ts@@ -3,6 +3,7 @@ import { describe, expect, it } from 'vitest';import {buildPath,buildSessionResumeHref,+ buildSharedSessionHref,matchLocation,matchPath,placesEqual,@@ -22,6 +23,7 @@ describe('resolveRoutesConfig', () => {buildAgent: '/build-agent',agent: '/agents/:agentName',session: '/sessions/:sessionId',+ sharedSession: '/sessions/share/:sessionId',sessionsBrowser: '/sessions',});});@@ -36,6 +38,7 @@ describe('resolveRoutesConfig', () => {expect(resolved.settings).toBeNull();expect(resolved.agent).toBe('/a/:agentName');expect(resolved.session).toBe('/sessions/:sessionId');+ expect(resolved.sharedSession).toBe('/sessions/share/:sessionId');});it('normalizes trailing slashes but keeps root', () => {@@ -57,6 +60,7 @@ describe('buildPath', () => {expect(buildPath({ type: 'buildAgent' }, routes)).toBe('/build-agent');expect(buildPath({ type: 'agent', agentName: 'code-helper' }, routes)).toBe('/agents/code-helper');expect(buildPath({ type: 'session', sessionId: 'abc123' }, routes)).toBe('/sessions/abc123');+ expect(buildPath({ type: 'sharedSession', sessionId: 'abc123' }, routes)).toBe('/sessions/share/abc123');expect(buildPath({ type: 'sessionsBrowser' }, routes)).toBe('/sessions');});@@ -84,6 +88,24 @@ describe('buildPath', () => {}),).toBe('https://app.example/trueforge/sessions/sess-1?theme=dark');});++ it('builds routed and query-fallback shared-session hrefs', () => {+ const withBasename = resolveRoutesConfig({ basename: '/trueforge' });+ expect(+ buildSharedSessionHref({+ sessionId: 'sess/1',+ routes: withBasename,+ href: 'https://app.example/trueforge/sessions?view=sessions&theme=dark',+ }),+ ).toBe('https://app.example/trueforge/sessions/share/sess%2F1?theme=dark');+ expect(+ buildSharedSessionHref({+ sessionId: 'sess-1',+ routes: null,+ href: 'https://app.example/embed?view=sessions&agentId=agent-1&s_tw=30&theme=dark',+ }),+ ).toBe('https://app.example/embed?view=shared-session&theme=dark&sessionId=sess-1');+ });});describe('sanitizeSearchForPlace', () => {@@ -93,6 +115,7 @@ describe('sanitizeSearchForPlace', () => {expect(sanitizeSearchForPlace({ type: 'library' }, sessionSearch)).toBe('?theme=dark');expect(sanitizeSearchForPlace({ type: 'root' }, sessionSearch)).toBe('?theme=dark');expect(sanitizeSearchForPlace({ type: 'session', sessionId: 'sess-2' }, sessionSearch)).toBe('?theme=dark');+ expect(sanitizeSearchForPlace({ type: 'sharedSession', sessionId: 'sess-2' }, sessionSearch)).toBe('?theme=dark');});it('keeps only the query state owned by the destination place', () => {@@ -137,6 +160,7 @@ describe('matchPath', () => {expect(matchPath('/agents/a%2Fb', routes)).toEqual({ type: 'agent', agentName: 'a/b' });expect(matchPath('/sessions', routes)).toEqual({ type: 'sessionsBrowser' });expect(matchPath('/sessions/xyz', routes)).toEqual({ type: 'session', sessionId: 'xyz' });+ expect(matchPath('/sessions/share/xyz', routes)).toEqual({ type: 'sharedSession', sessionId: 'xyz' });});it('returns null for unknown paths', () => {@@ -166,6 +190,7 @@ describe('matchPath', () => {{ type: 'buildAgent' as const },{ type: 'agent' as const, agentName: 'weird name/1' },{ type: 'session' as const, sessionId: 'sess 9' },+ { type: 'sharedSession' as const, sessionId: 'sess 9' },{ type: 'sessionsBrowser' as const },]) {const path = buildPath(place, routes);@@ -194,6 +219,16 @@ describe('matchLocation', () => {type: 'sessionsBrowser',});});++ it('opens a shared session from the no-router query form on the root path', () => {+ expect(+ matchLocation({+ pathname: '/',+ search: '?view=shared-session&sessionId=sess-1',+ routes,+ }),+ ).toEqual({ type: 'sharedSession', sessionId: 'sess-1' });+ });});describe('placesEqual', () => {@@ -203,5 +238,8 @@ describe('placesEqual', () => {expect(placesEqual({ type: 'agent', agentName: 'a' }, { type: 'agent', agentName: 'b' })).toBe(false);expect(placesEqual({ type: 'libraryAgent', agentId: 'a' }, { type: 'libraryAgent', agentId: 'a' })).toBe(true);expect(placesEqual({ type: 'session', sessionId: '1' }, { type: 'root' })).toBe(false);+ expect(placesEqual({ type: 'sharedSession', sessionId: '1' }, { type: 'sharedSession', sessionId: '1' })).toBe(+ true,+ );});});diff --git a/packages/trueforge-ui/test/routing/withRouter.integration.test.tsx b/packages/trueforge-ui/test/routing/withRouter.integration.test.tsxindex 4000f0644..d8f1f4325 100644--- a/packages/trueforge-ui/test/routing/withRouter.integration.test.tsx+++ b/packages/trueforge-ui/test/routing/withRouter.integration.test.tsx@@ -54,6 +54,7 @@ vi.mock('@truefoundry/trueforge-assistant-ui-runtime', () => ({useTrueForgeUpdateAgentSpec: () => vi.fn(),}));+import { SessionsPage } from '@/atoms/agent-details/SessionsPage.js';import { CompactLayoutProvider } from '@/atoms/lib/CompactLayoutContext.js';import { SessionsBrowserButton } from '@/atoms/SessionsBrowserButton.js';import type { ThreadListRowProps } from '@/atoms/ThreadListRow.js';@@ -91,6 +92,7 @@ function ShellProbe() {return (<><div data-testid="pending">{shell.pendingSessionId ?? 'none'}</div>+ <div data-testid="shared-session">{shell.sharedSessionId ?? 'none'}</div><div data-testid="binding">{mode.status === 'idle' ? 'idle' : `${mode.isMutable ? 'mutable' : 'immutable'}:${mode.agentName ?? '-'}`}</div>@@ -106,10 +108,23 @@ function ThreadListHost() {);}+function SessionsSurface() {+ const shell = useShellMode();+ return shell.sessionsOpen ? <SessionsPage /> : <ShellProbe />;+}+function renderApp() {return render(<TrueForgeUI- server={createMockAgentUIServer({})}+ server={createMockAgentUIServer({+ getSession: async ({ sessionId }) => ({+ id: sessionId,+ title: 'Session',+ isMutable: true,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ }),+ })}agentConfig={{ mode: 'AgentLibraryWithComposer' }}withRouterlayout={() => <ShellProbe />}@@ -119,6 +134,100 @@ function renderApp() {}describe('withRouter end to end', () => {+ it('opens /sessions/share/:id as shared-session detail', async () => {+ window.history.replaceState(null, '', '/sessions/share/session-2');+ render(+ <TrueForgeUI+ server={createMockAgentUIServer({ sessions: createMockAgentSessionsServer() })}+ agentConfig={{ mode: 'AgentLibraryWithComposer' }}+ withRouter+ layout={() => <ShellProbe />}+ />,+ );++ await waitFor(() => {+ expect(screen.getByTestId('shared-session')).toHaveTextContent('session-2');+ });+ expect(screen.getByTestId('pending')).toHaveTextContent('none');+ expect(window.location.pathname).toBe('/sessions/share/session-2');+ });++ it('renders shared-session detail without the list, resizer, or filters', async () => {+ window.history.replaceState(null, '', '/sessions/share/session-2');+ const listSessions = vi.fn(async () => ({ data: [] }));+ render(+ <TrueForgeUI+ server={createMockAgentUIServer({+ getSession: async () => ({+ id: 'session-2',+ title: 'Shared session',+ isMutable: false,+ createdAt: '2026-01-01T00:00:00Z',+ updatedAt: '2026-01-01T00:00:00Z',+ }),+ sessions: createMockAgentSessionsServer({+ listSessions,+ listSessionEvents: async () => ({ data: [] }),+ }),+ })}+ agentConfig={{ mode: 'AgentLibraryWithComposer' }}+ withRouter+ layout={() => <SessionsSurface />}+ overrides={{+ AgentSessionTimelineContainer: ({ contentMaxWidth }) => (+ <div data-testid="shared-session-timeline">{contentMaxWidth}</div>+ ),+ }}+ />,+ );++ expect(await screen.findByRole('heading', { name: 'Shared session' })).toBeInTheDocument();+ expect(screen.queryByRole('separator', { name: 'Resize session list' })).not.toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Last 30 days' })).not.toBeInTheDocument();+ expect(screen.getByTestId('shared-session-timeline')).toHaveTextContent('60rem');+ expect(listSessions).not.toHaveBeenCalled();++ fireEvent.click(screen.getByRole('button', { name: 'Close session details' }));+ await waitFor(() => {+ expect(window.location.pathname).toBe('/sessions');+ });+ expect(await screen.findByRole('button', { name: 'Last 30 days' })).toBeInTheDocument();+ expect(listSessions).toHaveBeenCalled();+ });++ it('toasts and redirects to the sessions list when a shared session is forbidden', async () => {+ window.history.replaceState(null, '', '/sessions/share/session-forbidden');+ const forbidden = Object.assign(new Error('Only the session creator can access this session'), {+ statusCode: 403,+ });+ vi.spyOn(console, 'error').mockImplementation(() => {});+ render(+ <TrueForgeUI+ server={createMockAgentUIServer({+ getSession: async () => {+ throw forbidden;+ },+ sessions: createMockAgentSessionsServer({+ listSessions: async () => ({ data: [] }),+ listSessionEvents: async () => {+ throw forbidden;+ },+ }),+ })}+ agentConfig={{ mode: 'AgentLibraryWithComposer' }}+ withRouter+ layout={() => <SessionsSurface />}+ />,+ );++ expect(await screen.findByText('Only the session creator can access this session')).toBeInTheDocument();+ await waitFor(() => {+ expect(window.location.pathname).toBe('/sessions');+ });+ expect(await screen.findByRole('button', { name: 'Last 30 days' })).toBeInTheDocument();+ expect(screen.queryByText('Session details could not be loaded.')).not.toBeInTheDocument();+ });+it('applies a /sessions/:id deep link on boot', async () => {window.history.replaceState(null, '', '/sessions/session-2');renderApp();diff --git a/packages/trueforge-ui/test/server/serverChrome.test.ts b/packages/trueforge-ui/test/server/serverChrome.test.tsindex 428cc1714..195df9b34 100644--- a/packages/trueforge-ui/test/server/serverChrome.test.ts+++ b/packages/trueforge-ui/test/server/serverChrome.test.ts@@ -59,6 +59,7 @@ describe('serverChrome', () => {});expect(disabled.settings).toBeNull();expect(disabled.sessionsBrowser).toBeNull();+ expect(disabled.sharedSession).toBeNull();expect(disabled.libraryAgent).toBeNull();expect(disabled.schedules).toBeNull();expect(disabled.root).toBe('/');@@ -73,6 +74,7 @@ describe('serverChrome', () => {});expect(enabled.settings).toBe('/settings');expect(enabled.sessionsBrowser).toBe('/sessions');+ expect(enabled.sharedSession).toBe('/sessions/share/:sessionId');expect(enabled.libraryAgent).toBe('/library/:agentId');expect(enabled.schedules).toBe('/schedules');});diff --git a/packages/trueforge-ui/test/utils/sessionAccessError.test.ts b/packages/trueforge-ui/test/utils/sessionAccessError.test.tsnew file mode 100644index 000000000..7a231d59f--- /dev/null+++ b/packages/trueforge-ui/test/utils/sessionAccessError.test.ts@@ -0,0 +1,27 @@+import { describe, expect, it, vi } from 'vitest';++import { reportSessionAccessError } from '@/utils/sessionAccessError.js';++describe('sessionAccessError', () => {+ it('reports the backend error as-is', () => {+ const onError = vi.fn();+ const forbidden = Object.assign(new Error('Only the session creator can access this session'), {+ statusCode: 403,+ });+ reportSessionAccessError({ error: forbidden, onError });+ expect(onError).toHaveBeenCalledWith(forbidden);+ });++ it('prefers onError over showError', () => {+ const onError = vi.fn();+ const showError = vi.fn();+ const notFound = Object.assign(new Error('Session not found: x'), { statusCode: 404 });+ reportSessionAccessError({+ error: notFound,+ onError,+ showError,+ });+ expect(onError).toHaveBeenCalledWith(notFound);+ expect(showError).not.toHaveBeenCalled();+ });+});diff --git a/packages/trueforge-ui/test/utils/sessionShareUrl.test.ts b/packages/trueforge-ui/test/utils/sessionShareUrl.test.tsindex cb8b2d10c..f8999c365 100644--- a/packages/trueforge-ui/test/utils/sessionShareUrl.test.ts+++ b/packages/trueforge-ui/test/utils/sessionShareUrl.test.ts@@ -38,6 +38,12 @@ describe('sessionShareUrl', () => {);});+ it('reads the detail-only shared-session view', () => {+ const share = readSessionShareSearch('?view=shared-session&sessionId=sess-1');+ assert.equal(share.view, 'shared-session');+ assert.equal(share.sessionId, 'sess-1');+ });+it('reads an absolute pinned time range', () => {assert.deepEqual(readSessionShareSearch('?s_sts=1000&s_ets=2000'), {sessionId: null,