diff --git a/packages/dsh-desktop-client-ui/client.js b/packages/dsh-desktop-client-ui/client.js index d9ada137..963a4abc 100644 --- a/packages/dsh-desktop-client-ui/client.js +++ b/packages/dsh-desktop-client-ui/client.js @@ -1508,10 +1508,25 @@ deletion.reset(); renaming.reset(); projects.setScope(undefined); revision++; hi const LANDING_MORPH_EASING = 'cubic-bezier(.25,.65,.35,1)' const CHAT_TEXT_PREPARE_LEAD = 40 const landingMotionAllowed = () => !window.matchMedia?.('(prefers-reduced-motion: reduce)').matches + const hasWorkLanding = state => state.nativeWork && state.workLanding && !state.panelOpen const hasSharedLanding = state => state.connected && state.phase === 'ready' && state.landing === true && - state.conversationId === 'new' && !state.pageId && state.nativeWork && state.workLanding && !state.panelOpen && + state.conversationId === 'new' && !state.pageId && hasWorkLanding(state) && !state.settingsOpen && !state.approvalsOpen && !state.accountDialogOpen + function afterWorkFirstFrame(callback) { + let first, second, timeout, pending = true + const cancel = () => { + pending = false + if (first !== undefined) cancelAnimationFrame(first) + if (second !== undefined) cancelAnimationFrame(second) + clearTimeout(timeout) + } + const finish = () => { if (pending) { cancel(); callback() } } + first = requestAnimationFrame(() => { if (pending) second = requestAnimationFrame(finish) }) + timeout = setTimeout(finish, 120) + return cancel + } + function animateLandingFooter(card, chat, animate, restore) { // The native composer owns the toolbar. Its model slot and add trigger are stable // anchors even though the InputBar's compiled class names are not. @@ -1617,7 +1632,14 @@ deletion.reset(); renaming.reset(); projects.setScope(undefined); revision++; hi } const cases = hero.querySelector('.dso-dock-root') if (cases) animate(cases, { opacity: 0 }, { opacity: 1 }) - return { finished: Promise.all(animations.map(animation => animation.finished)), dispose } + if (fromChat) { + // Lay out frame zero beneath the native Chat view before that view is hidden. + for (const animation of animations) { animation.pause(); animation.currentTime = 0 } + } + return { + finished: Promise.all(animations.map(animation => animation.finished)), dispose, + play() { for (const animation of animations) animation.play() } + } } catch { // A partial setup may be canceled before the combined completion has a consumer. for (const animation of animations) void animation.finished.catch(() => {}) @@ -1650,6 +1672,7 @@ deletion.reset(); renaming.reset(); projects.setScope(undefined); revision++; hi const surfacePresenter = React.useRef(null) const presentSurface = React.useRef(null) const revealMorph = React.useRef(null) + const yieldedWorkMorph = React.useRef(null) const modeIntent = React.useRef(0) const [animateWork, setAnimateWork] = React.useState(false) const tabs = React.useRef({}) @@ -1664,7 +1687,7 @@ deletion.reset(); renaming.reset(); projects.setScope(undefined); revision++; hi } const animation = animateWorkLanding(workPanel.current, morph) const bridge = window.dshEnterpriseChat - let stopped = false, finishing = false, handoffTimeout, prepareTimer, incomingText + let stopped = false, finishing = false, handoffTimeout, prepareTimer, incomingText, animationTimeout, cancelPaint const release = () => { if (!stopped) navigation.finishLandingMorph(morph) } const prepareIncoming = () => { if (!incomingText && !stopped && landingMotionAllowed()) { @@ -1679,7 +1702,7 @@ deletion.reset(); renaming.reset(); projects.setScope(undefined); revision++; hi // Retain the last Work frame until the separate native Chat view is shown. revealMorph.current = morph handoffTimeout = setTimeout(release, 150) - void Promise.resolve(presentSurface.current?.()).then(release, release) + void Promise.resolve(presentSurface.current?.(true)).then(release, release) } const finish = () => { if (stopped || finishing) return @@ -1693,15 +1716,35 @@ deletion.reset(); renaming.reset(); projects.setScope(undefined); revision++; hi // Install the first transparent Chat frame during the tail of Work's motion. prepareTimer = setTimeout(() => { void prepareIncoming() }, LANDING_MORPH_DURATION - CHAT_TEXT_PREPARE_LEAD) } - const timeout = setTimeout(finish, LANDING_MORPH_DURATION + 90) + const startDeadline = () => { animationTimeout = setTimeout(finish, LANDING_MORPH_DURATION + 90) } + if (morph.to === 'work') { + cancelPaint = afterWorkFirstFrame(() => { + if (stopped || finishing) return + yieldedWorkMorph.current = morph + let playing = false + const play = () => { + if (stopped || finishing || playing) return + playing = true + clearTimeout(handoffTimeout) + // Out-of-view geometry skips the morph, but still needs a painted Work surface. + if (!animation) return finish() + animation.play() + startDeadline() + } + handoffTimeout = setTimeout(play, 150) + void Promise.resolve(presentSurface.current?.()).then(play, play) + }) + } else if (animation) startDeadline() if (animation) void animation.finished.then(finish, finish) - else queueMicrotask(finish) + else if (morph.to === 'chat') queueMicrotask(finish) window.addEventListener('resize', finish) return () => { stopped = true - clearTimeout(timeout); clearTimeout(handoffTimeout); clearTimeout(prepareTimer) + cancelPaint?.() + clearTimeout(animationTimeout); clearTimeout(handoffTimeout); clearTimeout(prepareTimer) window.removeEventListener('resize', finish) if (revealMorph.current === morph) revealMorph.current = null + if (yieldedWorkMorph.current === morph) yieldedWorkMorph.current = null animation?.dispose() } }, [morph, state.landingMorph, navigation]) @@ -1716,7 +1759,7 @@ deletion.reset(); renaming.reset(); projects.setScope(undefined); revision++; hi let observedLeading const presenter = surfacePresenter.current || (surfacePresenter.current = createNativeSurfacePresenter(bridge, value => value.settings ? document.querySelector(`[data-dsh-native-surface="${value.settings}"]`) : panel.current)) - const present = () => { + const present = (landingHandoff) => { const rect = (panel.current?.hidden ? workPanel.current : panel.current)?.getBoundingClientRect() if (!rect) return // Native WebContentsView paints above DOM chrome regardless of z-index. @@ -1752,7 +1795,11 @@ const surface = remote ? document.querySelector(`[data-dsh-native-surface="${rem // Project dialogs have an explicit lifecycle; yield the native sibling as they open. const hostModalOpen = projectDialogOpen || cloudDeleteOpen || cloudRenameOpen || overlays.isModal(surface) || appRoot?.inert || document.documentElement.hasAttribute('data-dsh-about-open') const bounds = remote ? remote.bounds : { x, y, width: Math.max(0, rect.right - x), height: Math.max(0, rect.y + rect.height - y) } -return presenter.present({ visible: hostModalOpen ? false : (remote ? state.connected && remote.bounds.width > 0 && remote.bounds.height > 0 : mode === 'chat' && (!morph || revealMorph.current === morph) && !surfaceOpen && !safeModePageOpen), ...(remote ? { settings: remote.section } : {}), ...(palette ? { palette } : {}), bounds, theme: document.body.hasAttribute('data-ds-dark-theme') ? 'dark' : 'light', locale: locale.getSnapshot().active === 'zh' ? 'zh' : 'en' }, overlays.intersects(bounds, surface), () => overlays.defer(bounds, surface)) +const chatHandoff = mode === 'chat' && morph && revealMorph.current === morph +const keepChatUntilWorkPaints = morph?.to === 'work' && yieldedWorkMorph.current !== morph +const chatVisible = ((mode === 'chat' && (!morph || chatHandoff)) || keepChatUntilWorkPaints) && !surfaceOpen && !safeModePageOpen +const visible = !hostModalOpen && (remote ? state.connected && remote.bounds.width > 0 && remote.bounds.height > 0 : chatVisible) +return presenter.present({ visible, ...(visible && chatHandoff && landingHandoff === true ? { landingHandoff: true } : {}), ...(remote ? { settings: remote.section } : {}), ...(palette ? { palette } : {}), bounds, theme: document.body.hasAttribute('data-ds-dark-theme') ? 'dark' : 'light', locale: locale.getSnapshot().active === 'zh' ? 'zh' : 'en' }, overlays.intersects(bounds, surface), () => overlays.defer(bounds, surface)) } // The native view follows the host's modal interaction boundary. // Onboarding makes #root inert while its dialog lives in a body portal. @@ -1790,7 +1837,7 @@ interaction.observe(document.documentElement, { attributes: true, attributeFilte }, []) const showModePicker = !settingsOpen && (mode === 'chat' ? !state.pageId && state.conversationId === 'new' && state.landing !== false - : state.nativeWork && state.workLanding && !state.panelOpen) + : hasWorkLanding(state)) const chooseMode = (next) => { const before = navigation.snapshot() const request = ++modeIntent.current @@ -1835,9 +1882,10 @@ interaction.observe(document.documentElement, { attributes: true, attributeFilte showModePicker && React.createElement('header', { className: 'dshModesHeader' }, React.createElement('div', { role: 'tablist', 'aria-label': t('label'), className: 'dshModesTabs', onKeyDown: keyDown }, ...['chat', 'work'].map((key) => React.createElement('button', { key, id: `dsh-mode-${key}`, type: 'button', role: 'tab', 'aria-selected': mode === key, 'aria-controls': `dsh-panel-${key}`, tabIndex: mode === key ? 0 : -1, ref: (node) => { tabs.current[key] = node }, onClick: () => chooseMode(key) }, t(key))))), - React.createElement('section', { + React.createElement('div', { className: 'dshModeStage' }, React.createElement('section', { ref: workPanel, id: 'dsh-panel-work', role: 'tabpanel', 'aria-label': t('work'), hidden: mode !== 'work' && !morph, - inert: morph ? '' : undefined, 'aria-hidden': mode !== 'work' || undefined, + inert: mode !== 'work' || morph ? '' : undefined, 'aria-hidden': mode !== 'work' || undefined, + 'data-keep-landing-layout': hasWorkLanding(state) ? '' : undefined, className: 'dshModeBody dshWorkContent', 'data-reveal-controls': mode === 'work' && animateWork, onAnimationEnd: event => { if (event.animationName === 'dshWorkControlsRise') setAnimateWork(false) @@ -1847,7 +1895,7 @@ interaction.observe(document.documentElement, { attributes: true, attributeFilte React.createElement('section', { ref: panel, id: 'dsh-panel-chat', 'data-dsh-native-surface': '', role: 'tabpanel', 'aria-label': t('chat'), hidden: mode !== 'chat' || Boolean(morph), className: 'dshModeBody' }, React.createElement('div', { className: 'dshChatStatus', role: 'status' }, React.createElement('p', null, state.phase === 'error' ? t('error') : state.phase === 'ready' ? '' : t('loading')), - state.connected && state.phase === 'error' && React.createElement('button', { type: 'button', onClick: () => { void window.dshEnterpriseChat.retry().catch(() => {}) } }, t('retry'))))) + state.connected && state.phase === 'error' && React.createElement('button', { type: 'button', onClick: () => { void window.dshEnterpriseChat.retry().catch(() => {}) } }, t('retry')))))) } const NAV_ICON_PATHS = { new: 'M12 20H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v7M16 16v6m-3-3h6M7 8h10M7 12h5', @@ -1932,9 +1980,12 @@ interaction.observe(document.documentElement, { attributes: true, attributeFilte .dshModesTabs button{font:inherit;font-size:13px;min-width:96px;height:30px;padding:0 20px;border:0;border-radius:20px;background:transparent;color:var(--dsw-alias-label-secondary);cursor:pointer} .dshModesTabs button[aria-selected=true]{color:var(--dsw-alias-label-primary)} .dshModes button:focus-visible{outline:2px solid var(--dsw-alias-state-business-primary);outline-offset:2px} - .dshModeBody{flex:1;min-height:0;display:flex;flex-direction:column;position:relative}.dshModeBody[hidden]{display:none} + .dshModeStage{flex:1;min-width:0;min-height:0;display:grid;grid-template: minmax(0,1fr) / minmax(0,1fr)} + .dshModeBody{grid-area:1/1;min-width:0;min-height:0;display:flex;flex-direction:column;position:relative}.dshModeBody[hidden]{display:none} #dsh-panel-chat::before{content:'';position:absolute;inset:0 0 auto;height:var(--dsh-square-chrome-height,0px);background:var(--dsh-square-chrome-fill,transparent);pointer-events:none} .dshWorkContent{display:grid;grid-template-rows:minmax(0,1fr);isolation:isolate}.dshWorkContent[hidden]{display:none} + /* Keep Harness's column ResizeObserver at the real width while its landing is behind Chat. */ + .dshWorkContent[hidden][data-keep-landing-layout]{display:grid;visibility:hidden;opacity:0;pointer-events:none} .dshWorkContent [data-dsh-landing-morph-placeholder]{flex:none;anchor-name:--dso-hero-composer} .dshWorkContent [data-composer-card][data-dsh-landing-morph-card]{position:fixed;max-width:none;min-height:0;margin:0;padding-block-end:var(--dsh-morph-footer-clearance,0px);overflow:clip;z-index:2;anchor-name:none!important} .dshWorkContent [data-dsh-landing-morph-card]:has(>[data-dsh-landing-morph-footer]) > :not([data-dsh-landing-morph-footer]){flex-shrink:1;min-block-size:0;overflow:clip} @@ -2024,9 +2075,14 @@ interaction.observe(document.documentElement, { attributes: true, attributeFilte .dshHistoryTitle[data-scrolled]{mask-image:linear-gradient(90deg,transparent,black 12px)} .dshHistoryTitle[data-clipped]{mask-image:linear-gradient(270deg,transparent,black 12px)} .dshHistoryTitle[data-scrolled][data-clipped]{mask-image:linear-gradient(90deg,transparent,black 12px calc(100% - 12px),transparent)} - .dshCloudHistoryPreview{display:grid;gap:4px;overflow-wrap:anywhere;color:var(--dsw-alias-label-primary)} - .dshCloudHistoryPreview time{font-size:12px;color:var(--dsw-alias-label-tertiary)} - .dshCloudHistoryStatus{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--dsw-alias-label-secondary)} + /* Harness's compact hover card uses a dark surface in both themes. */ + .dshCloudHistoryPreview{ + display:grid;gap:4px;overflow-wrap:anywhere;color:var(--dsw-alias-toast-label) + } + .dshCloudHistoryPreview time{ + font-size:12px;color:color-mix(in srgb,var(--dsw-alias-toast-label) 80%,transparent) + } + .dshCloudHistoryStatus{display:flex;align-items:center;gap:6px;font-size:12px;color:inherit} .dshHistoryStatus{position:absolute;inset-block:0;inset-inline-start:8px;width:16px;display:inline-flex;align-items:center;justify-content:center;color:var(--dsw-alias-label-tertiary);pointer-events:none} .dshChatProject .dshHistoryStatus{inset-inline-start:12px} .dshVisuallyHidden{position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap} diff --git a/scripts/verify-cloud-chat-delete.mjs b/scripts/verify-cloud-chat-delete.mjs index b4df6b37..06b6fa05 100644 --- a/scripts/verify-cloud-chat-delete.mjs +++ b/scripts/verify-cloud-chat-delete.mjs @@ -31,7 +31,47 @@ try { import * as primitives from 'fixture-primitives' const dictionaries = new Map(), slots = new Map(), disposers = [] let language = 'zh' - window.fixture = { setLanguage(value) { language = value; render() } } + window.fixture = { + setLanguage(value) { language = value; render() }, + previewContrast() { + const content = document.querySelector('[data-dsh-chat-history-preview]') + const root = document.documentElement + const darkTheme = document.body.getAttribute('data-ds-dark-theme') + const platform = root.getAttribute('data-platform') + const restore = (element, name, value) => value === null ? element.removeAttribute(name) : element.setAttribute(name, value) + const canvas = document.createElement('canvas') + const pixels = canvas.getContext('2d', { willReadFrequently: true }) + const luminance = () => { + const [r, g, b] = Array.from(pixels.getImageData(0, 0, 1, 1).data.slice(0, 3), value => { + const channel = value / 255 + return channel <= .04045 ? channel / 12.92 : ((channel + .055) / 1.055) ** 2.4 + }) + return .2126 * r + .7152 * g + .0722 * b + } + const contrast = text => { + pixels.clearRect(0, 0, 1, 1) + pixels.fillStyle = getComputedStyle(content.parentElement).backgroundColor + pixels.fillRect(0, 0, 1, 1) + const background = luminance() + pixels.fillStyle = getComputedStyle(text).color + pixels.fillRect(0, 0, 1, 1) + const foreground = luminance() + return (Math.max(background, foreground) + .05) / (Math.min(background, foreground) + .05) + } + try { + return [null, 'darwin'].flatMap(marker => { + restore(root, 'data-platform', marker) + return [false, true].map(dark => { + document.body.toggleAttribute('data-ds-dark-theme', dark) + return { marker, dark, title: contrast(content.firstElementChild), time: contrast(content.querySelector('time')) } + }) + }) + } finally { + restore(root, 'data-platform', platform) + restore(document.body, 'data-ds-dark-theme', darkTheme) + } + } + } window.__ModuleLoader__ = {load({factory}) { const plugin = factory(name => name === 'react' ? React : primitives) plugin.apply({ @@ -64,7 +104,8 @@ try { resolveDir: dirname(primitivePath) })) } }] }) - await writeFile(join(dir, 'index.html'), `
`) @@ -114,7 +155,7 @@ try { // Client-generated id: a retried create returns the existing project. if(!projects.some(project=>project.id===action.project_id)) projects.unshift({id:action.project_id,name:action.name}) outcome.project_id=action.project_id - if(action.chat_id) memberships[action.chat_id]=project.id + if(action.chat_id) memberships[action.chat_id]=action.project_id } else if(action.operation==='rename') projects=projects.map(project=>project.id===action.project_id?{...project,name:action.name}:project) else if(action.operation==='delete') { projects=projects.filter(project=>project.id!==action.project_id) @@ -192,6 +233,10 @@ try { const preview='[data-dsh-chat-history-preview]' await wait(()=>shown(preview)) assert.ok((await run('document.querySelector("[data-dsh-chat-history-preview]").textContent')).includes(longTitle)) + const previewContrast=await run('fixture.previewContrast()') + for(const colors of previewContrast) { + assert.ok(colors.title>=4.5&&colors.time>=4.5,'Preview title and time have readable contrast: '+JSON.stringify(colors)) + } const initialView=owner.contentView.children.find(child=>child.webContents?.getURL().includes('/workspace')) assert.equal(initialView.getVisible(),false,'Native Chat yields to the overlapping preview') assert.equal(await run('Boolean(document.querySelector("[data-dsh-native-frame]"))'),true,'The native content remains visible as backing under the preview') @@ -284,7 +329,11 @@ try { assert.equal(await toolVisible(filedTool),true,'Tab exposes the otherwise hidden menu trigger') await key(' ',32,'Space') await wait(()=>shown('[role=menu]')) - if(!await run('document.activeElement.matches(".dshCloudHistoryMenu button[aria-haspopup=menu]")')) await key('Home',36) + if(!await run('document.activeElement.matches(".dshCloudHistoryMenu button[aria-haspopup=menu]")')) { + await key('Home',36) + // The conversation menu now starts with Rename, followed by the project submenu. + await key('ArrowDown',40) + } await wait(()=>run('document.activeElement.matches(".dshCloudHistoryMenu button[aria-haspopup=menu]")')) await wait(()=>shown(projectSubmenu)) assert.deepEqual(await submenuRows(),[ @@ -333,6 +382,7 @@ try { assert.equal(await run('fixture.navigation.projects.snapshot().assignments["project-created"]'),undefined,'Navigation alone cannot create membership') rows.push({chat_id:'project-created',name:'Old project conversation',flow_type:15,flow_id:'',update_time:'2020-01-01'}) await webAction({operation:'assign',chat_id:'project-created',project_id:projectId}) + await focusAgain() await wait(()=>run('Object.keys(fixture.navigation.projects.snapshot().assignments).includes("project-created")')) assert.equal(await run('fixture.navigation.projects.snapshot().assignments["project-created"]'),projectId,'New conversation belongs to its originating project') await wait(()=>run('document.querySelector("[data-chat-project]").textContent.includes("Old project conversation")')) @@ -349,13 +399,17 @@ try { await wait(()=>run('document.querySelector("[data-chat-project]").textContent.includes("Recovered after disconnect")')) await webAction({operation:'assign',chat_id:'project-created',project_id:null}) rows.pop() + await focusAgain() await wait(()=>run('document.querySelectorAll(".dshCloudHistoryActions").length===4')) let cases=0 for(const language of ['zh','en']) for(const dark of [false,true]) { owner.webContents.setZoomFactor(dark ? 1.25 : 1) await run('fixture.setLanguage('+JSON.stringify(language)+');document.body.toggleAttribute("data-ds-dark-theme",'+dark+')') await click('[data-history-kind=chat]') - await wait(()=>host.snapshot().conversationId==='cloud-'+cases) + await wait(()=>{ + const state=host.snapshot() + return state.conversationId==='cloud-'+cases&&state.phase==='ready' + }) const view=owner.contentView.children.find(child=>child.webContents?.getURL().includes('/workspace')) assert.ok(view.getVisible(),'Native chat is visible before confirmation') await click('.dshCloudHistoryActions') @@ -382,13 +436,16 @@ try { await wait(()=>view.getVisible()) cases++ } - const result={cases,projectCases:4,projectPersistence:true,serverMembership:true,bidirectionalSync:true,focusRefresh:true,olderProjectHistory:true,syncLatencyMs,deleted:deleted.size,attempts:[...attempts.values()],platform:process.platform,electron:process.versions.electron,scope:'production UI primitives, project/history controllers, native Chat view and authenticated loopback fixture; no production deployment'} + const result={cases,projectCases:4,previewContrast,projectPersistence:true,serverMembership:true,bidirectionalSync:true,focusRefresh:true,olderProjectHistory:true,syncLatencyMs,deleted:deleted.size,attempts:[...attempts.values()],platform:process.platform,electron:process.versions.electron,scope:'production UI primitives, project/history controllers, native Chat view and authenticated loopback fixture; no production deployment'} if(${JSON.stringify(output || '')}) {await mkdir(${JSON.stringify(output || '')},{recursive:true});await writeFile(${JSON.stringify(join(output || dir,'result.json'))},JSON.stringify(result,null,2));await writeFile(${JSON.stringify(join(output || dir,'completed.png'))},(await owner.webContents.capturePage()).toPNG())} console.log(JSON.stringify(result)) } finally {host.dispose();owner.destroy();server.closeAllConnections();await new Promise(resolve=>server.close(resolve))} app.exit(0) }).catch(error=>{console.error(error);app.exit(1)}) - ` }, bundle: true, platform: 'node', format: 'esm', external: ['electron'], outfile: entry }) + ` }, bundle: true, platform: 'node', format: 'esm', external: ['electron'], outfile: entry, + // The update-card dependency brings in CommonJS packages that require Node builtins. + banner: { js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);" } + }) const env = { ...process.env } if (output) { await mkdir(output, {recursive:true}); await copyFile(entry, join(output,'main-source.mjs')) } delete env.ELECTRON_RUN_AS_NODE diff --git a/src/main/enterprise/chat-view.ts b/src/main/enterprise/chat-view.ts index a6e7e9aa..36a0f879 100644 --- a/src/main/enterprise/chat-view.ts +++ b/src/main/enterprise/chat-view.ts @@ -20,6 +20,7 @@ import { raiseUpdateCardViewIfShown } from '../update/update-card-view' /** Remote Chat gets its own in-memory browser session and a presentation-only preload. */ const DOCUMENT_LOAD_TIMEOUT_MS = 45_000 const LANDING_GEOMETRY_TIMEOUT_MS = 120 +const LANDING_HANDOFF_TIMEOUT_MS = 120 const LANDING_TEXT_MOTION_TIMEOUT_MS = 155 const INITIAL_BACKOFF_MS = [2_000, 5_000, 10_000] const RENEWAL_BACKOFF_MS = [2_000, 5_000, 10_000, 30_000] @@ -179,6 +180,35 @@ export class EnterpriseChatView { return this.snapshot() } + /** The host keeps Work painted until the newly shown Chat renderer has had a frame. */ + async presentWithLandingHandoff(window: BrowserWindow, input: unknown): Promise { + const state = this.present(window, input) + const view = this.view, epoch = this.generation + const ready = () => this.owner === window && !window.isDestroyed() && !window.webContents.isDestroyed() && + view && this.view === view && epoch === this.generation && !view.webContents.isDestroyed() && view.getVisible() && + this.presentation?.visible && this.state.phase === 'ready' && this.landing === true && this.landingPath === '/workspace/c/new' && + !this.modalOpen && !this.settingsSection && !this.presentation.settings + if (!view || this.presentation?.landingHandoff !== true || !ready()) return state + const url = view.webContents.getURL(), page = new URL(url || 'about:blank') + const { width, height } = view.getBounds() + if (page.origin !== this.origin || page.pathname !== '/workspace/c/new' || width <= 0 || height <= 0) return state + const frame = view.webContents.mainFrame + const code = `(() => { + if (location.href !== ${JSON.stringify(url)}) return; + return new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve()))); + })()` + try { + // The first callback runs before paint. A second one lets Chromium commit that frame. + await loadWithin(view.webContents.executeJavaScriptInIsolatedWorld(CHAT_WELCOME_WORLD, [{ code }]), LANDING_HANDOFF_TIMEOUT_MS) + } catch { + // A hidden or replaced renderer can stop scheduling frames. Never hold the outgoing Work frame indefinitely. + if (ready() && frame === view.webContents.mainFrame && url === view.webContents.getURL()) { + this.note('[enterprise-chat] landing_handoff_unavailable') + } + } + return this.snapshot() + } + async capture(window: BrowserWindow): Promise { const view = this.view, epoch = this.generation if (window !== this.owner || window.isDestroyed() || !view?.getVisible() || this.state.phase !== 'ready') return @@ -582,7 +612,7 @@ export class EnterpriseChatView { const surfaceReady = this.presentation.settings ? this.settingsSection === this.presentation.settings && this.isSettingsReady() : !onSettingsPath const shown = visible && this.state.phase === 'ready' && surfaceReady if (!shown || this.presentation.settings) this.discardDialogBacking() - if (this.view.getVisible() !== shown) this.view.setVisible(shown) + if (!shown && this.view.getVisible()) this.view.setVisible(false) this.syncWelcomeCases(shown && !this.presentation.settings) // Settings hides the view while changing locale; its navigation labels still need updates. if (this.state.phase === 'ready') this.applyLocale() @@ -622,6 +652,8 @@ export class EnterpriseChatView { const backing = this.state.phase === 'ready' && !this.presentation.settings ? '#00000000' : background if (this.viewBackground !== backing) { this.view.setBackgroundColor(backing); this.viewBackground = backing } if (this.state.phase === 'ready') this.applyTheme() + // A newly visible native view can otherwise composite with its previous bounds or backing. + if (shown && !this.view.getVisible()) this.view.setVisible(true) } /** Theme reaches the document on every presentation, load and in-page route change. */ diff --git a/src/main/index.ts b/src/main/index.ts index 6d50461a..089c89ae 100644 --- a/src/main/index.ts +++ b/src/main/index.ts @@ -1771,7 +1771,7 @@ function registerHarnessHandlers(): void { }) ipcMain.handle('enterprise-chat:present', (event, presentation: unknown) => { assertTrustedMainWindowEvent(event) - return enterpriseChat?.present(mainWindow!, presentation) ?? { phase: 'idle', connected: false } + return enterpriseChat?.presentWithLandingHandoff(mainWindow!, presentation) ?? { phase: 'idle', connected: false } }) ipcMain.handle('enterprise-chat:state', (event) => { assertTrustedMainWindowEvent(event) diff --git a/src/shared/enterprise-chat-view.ts b/src/shared/enterprise-chat-view.ts index d869c26b..38044022 100644 --- a/src/shared/enterprise-chat-view.ts +++ b/src/shared/enterprise-chat-view.ts @@ -4,6 +4,8 @@ export interface EnterpriseChatPresentation { theme: 'light' | 'dark' locale?: 'zh' | 'en' settings?: EnterpriseSettingsSection + /** Keep the outgoing Work frame while the native landing gets a chance to paint. */ + landingHandoff?: true /** Host surfaces and ink resolved from the active Harness theme; absent when they cannot be sampled. */ palette?: EnterprisePalette } @@ -106,6 +108,9 @@ export function parseChatPresentation(value: unknown): EnterpriseChatPresentatio if (input.locale !== undefined && input.locale !== 'zh' && input.locale !== 'en') { throw new Error('Invalid Chat locale.') } + if (input.landingHandoff !== undefined && input.landingHandoff !== true) { + throw new Error('Invalid Chat landing handoff.') + } const settings = input.settings === undefined ? undefined : parseEnterpriseSettingsSection(input.settings) const palette = parseEnterprisePalette(input.palette) const bounds = input.bounds as Record | undefined @@ -117,6 +122,7 @@ export function parseChatPresentation(value: unknown): EnterpriseChatPresentatio theme: input.theme as 'light' | 'dark', locale: input.locale, settings, + ...(input.landingHandoff ? { landingHandoff: true } : {}), ...(palette ? { palette } : {}), bounds: { x: Number(bounds.x), y: Number(bounds.y), width: Number(bounds.width), height: Number(bounds.height) } } diff --git a/test/desktop-modes-ui.test.mjs b/test/desktop-modes-ui.test.mjs index f76f6c92..b5b7c2f3 100644 --- a/test/desktop-modes-ui.test.mjs +++ b/test/desktop-modes-ui.test.mjs @@ -609,8 +609,9 @@ async function mountLandingMorph({ footer = false, textMotion = false } = {}) { const recordMotion = (name, frames) => { const { promise: finished, resolve, reject } = Promise.withResolvers() const cancel = vi.fn(() => reject(new DOMException('Animation cancelled', 'AbortError'))) - motions.push({ name, frames, resolve, cancel }) - return { finished, cancel } + const pause = vi.fn(), play = vi.fn() + motions.push({ name, frames, resolve, cancel, pause, play }) + return { finished, cancel, pause, play } } for (const [name, element] of Object.entries(elements)) { element.getBoundingClientRect = () => rects[name] @@ -656,6 +657,53 @@ async function mountLandingMorph({ footer = false, textMotion = false } = {}) { return { ui, bridge, workPanel, chatPanel, elements, motions } } +it('keeps the hidden Work landing laid out and paints frame zero before hiding Chat', async () => { + const { ui, bridge, workPanel, chatPanel, motions } = await mountLandingMorph({ footer: true }) + const draft = ui.draft() + expect(workPanel.parentElement).toBe(chatPanel.parentElement) + expect(workPanel.hidden).toBe(true) + expect(workPanel.hasAttribute('inert')).toBe(true) + expect(getComputedStyle(workPanel).display).toBe('grid') + expect(getComputedStyle(workPanel).visibility).toBe('hidden') + + const frames = [] + vi.stubGlobal('requestAnimationFrame', callback => frames.push(callback)) + const hide = Promise.withResolvers() + bridge.present.mockClear().mockImplementation(({ visible }) => visible ? Promise.resolve() : hide.promise) + await ui.click('work') + expect(motions.length).toBeGreaterThan(0) + expect(motions.every(motion => motion.pause.mock.calls.length === 1 && !motion.play.mock.calls.length)).toBe(true) + expect(bridge.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: true })) + await act(async () => frames.shift()(0)) + expect(bridge.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: true })) + await act(async () => frames.shift()(16)) + expect(bridge.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: false })) + expect(motions.every(motion => !motion.play.mock.calls.length)).toBe(true) + await act(async () => hide.resolve()) + expect(motions.every(motion => motion.play.mock.calls.length === 1)).toBe(true) + await act(async () => motions.forEach(motion => motion.resolve())) + expect(workPanel.hasAttribute('inert')).toBe(false) + expect(ui.draft()).toBe(draft) + expect(draft.value).toContain('third line') +}) + +it('paints the Work landing before hiding Chat even when the composer cannot morph', async () => { + const { ui, bridge, elements, workPanel, motions } = await mountLandingMorph() + elements.card.getBoundingClientRect = () => new DOMRect(340, 0, 600, 172) + const frames = [] + vi.stubGlobal('requestAnimationFrame', callback => frames.push(callback)) + bridge.present.mockClear() + + await ui.click('work') + expect(motions).toHaveLength(0) + expect(bridge.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: true })) + await act(async () => frames.shift()(0)) + expect(bridge.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: true })) + await act(async () => frames.shift()(16)) + expect(bridge.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: false })) + expect(workPanel.hasAttribute('inert')).toBe(false) +}) + it('fades the current editor text before the native handoff and introduces the destination text after it starts', async () => { const { ui, bridge, chatPanel, elements, motions } = await mountLandingMorph({ textMotion: true }) const draft = ui.draft() @@ -728,7 +776,7 @@ it('morphs the same Work card and title in both directions while revealing and c expect(workPanel.hidden).toBe(false) expect(chatPanel.hidden).toBe(true) await act(async () => motions.slice(3).forEach(motion => motion.resolve())) - expect(bridge.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: true })) + expect(bridge.present).toHaveBeenLastCalledWith(expect.objectContaining({ visible: true, landingHandoff: true })) expect(placeholder()).not.toBeNull() expect(workPanel.hidden).toBe(false) await act(async () => reveal.resolve()) diff --git a/test/enterprise-chat-view.test.ts b/test/enterprise-chat-view.test.ts index 85700e7f..92b6b8a3 100644 --- a/test/enterprise-chat-view.test.ts +++ b/test/enterprise-chat-view.test.ts @@ -192,6 +192,14 @@ describe('enterprise Chat host boundary', () => { } }) + it('accepts only an explicit true landing handoff flag', () => { + expect(parseChatPresentation(presentation)).not.toHaveProperty('landingHandoff') + expect(parseChatPresentation({ ...presentation, landingHandoff: true }).landingHandoff).toBe(true) + for (const landingHandoff of [false, 'true', null, 1, {}]) { + expect(() => parseChatPresentation({ ...presentation, landingHandoff })).toThrow('landing handoff') + } + }) + it('validates the ingress cookie name and supports the existing server default', () => { const body = { cookie: 'a'.repeat(40), expires_in: 300 } expect(parseWebSession(body, 'https://enterprise.example', 'a').cookieName).toBe('access_token_cookie') @@ -881,6 +889,82 @@ it('measures only a confirmed blank Chat, updating a hidden seat without showing } finally { f.host.dispose() } }) +const LANDING_HANDOFF_FRAME_REQUEST = 'requestAnimationFrame(() => requestAnimationFrame(' + +it('places the native Chat seat before showing it and waits two renderer frames on a landing handoff', async () => { + const f = fixture() + try { + const url = 'https://enterprise.example/workspace/c/new?embed=dsh' + fake.loadLanding = url + f.host.present(f.owner, presentation) + await flush() + const view = fake.views[0], wc = view.webContents + expect(view.setBackgroundColor.mock.invocationCallOrder.at(-1)).toBeLessThan(view.setVisible.mock.invocationCallOrder.at(-1)) + wc.emit('ipc-message', { senderFrame: wc.mainFrame }, 'enterprise-chat:landing', { landing: true, path: '/workspace/c/new' }) + f.host.present(f.owner, { ...presentation, visible: false }) + const frames: Array<() => void> = [] + wc.executeJavaScriptInIsolatedWorld.mockImplementation((_world: number, [script]: Array<{ code: string }>) => { + const code = script?.code + if (!code?.includes(LANDING_HANDOFF_FRAME_REQUEST)) return Promise.resolve() + expect(view.getVisible()).toBe(true) + return Function('location', 'requestAnimationFrame', `return ${code}`)({ href: url }, (callback: () => void) => frames.push(callback)) + }) + const bounds = { x: 80, y: 60, width: 900, height: 600 } + const finish = vi.fn() + const handoff = f.host.presentWithLandingHandoff(f.owner, { ...presentation, bounds, landingHandoff: true }).then(finish) + expect(view.getBounds()).toEqual(bounds) + expect(view.setBounds.mock.invocationCallOrder.at(-1)).toBeLessThan(view.setVisible.mock.invocationCallOrder.at(-1)) + expect(frames).toHaveLength(1) + frames.shift()?.() + await flush() + expect(finish).not.toHaveBeenCalled() + expect(frames).toHaveLength(1) + frames.shift()?.() + await handoff + expect(finish).toHaveBeenCalledWith(expect.objectContaining({ phase: 'ready', landing: true })) + } finally { f.host.dispose() } +}) + +it('skips the landing wait for ordinary, hidden, unconfirmed, or navigated presentations', async () => { + const f = fixture() + try { + fake.loadLanding = 'https://enterprise.example/workspace/c/new?embed=dsh' + f.host.present(f.owner, presentation) + await flush() + const view = fake.views[0], wc = view.webContents + await f.host.presentWithLandingHandoff(f.owner, { ...presentation, landingHandoff: true }) + wc.emit('ipc-message', { senderFrame: wc.mainFrame }, 'enterprise-chat:landing', { landing: true, path: '/workspace/c/new' }) + await f.host.presentWithLandingHandoff(f.owner, presentation) + await f.host.presentWithLandingHandoff(f.owner, { ...presentation, visible: false, landingHandoff: true }) + wc.setURL('https://enterprise.example/workspace/c/another') + await f.host.presentWithLandingHandoff(f.owner, { ...presentation, landingHandoff: true }) + expect(wc.executeJavaScriptInIsolatedWorld).not.toHaveBeenCalledWith(1001, [{ code: expect.stringContaining(LANDING_HANDOFF_FRAME_REQUEST) }]) + } finally { f.host.dispose() } +}) + +it('releases Work if the native landing renderer stops scheduling frames', async () => { + vi.useFakeTimers() + const f = fixture() + try { + fake.loadLanding = 'https://enterprise.example/workspace/c/new?embed=dsh' + f.host.present(f.owner, presentation) + await flush() + const view = fake.views[0], wc = view.webContents + wc.emit('ipc-message', { senderFrame: wc.mainFrame }, 'enterprise-chat:landing', { landing: true, path: '/workspace/c/new' }) + f.host.present(f.owner, { ...presentation, visible: false }) + wc.executeJavaScriptInIsolatedWorld.mockImplementation((_world: number, [script]: Array<{ code: string }>) => + script?.code.includes(LANDING_HANDOFF_FRAME_REQUEST) ? new Promise(() => {}) : Promise.resolve()) + const finish = vi.fn() + const handoff = f.host.presentWithLandingHandoff(f.owner, { ...presentation, landingHandoff: true }).then(finish) + await elapse(119) + expect(finish).not.toHaveBeenCalled() + await elapse(1) + await handoff + expect(finish).toHaveBeenCalledWith(expect.objectContaining({ phase: 'ready', landing: true })) + expect(view.getVisible()).toBe(true) + } finally { f.host.dispose(); vi.useRealTimers() } +}) + it('prepares Chat text only in the owned landing view, without changing native visibility', async () => { const f = fixture() try {