From e4cc7f6186edf74238b915ede8ebced2a1debe18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mat=C4=9Bj=20Such=C3=A1nek?= <16311043+immakermatty@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:38:21 +0000 Subject: [PATCH] feat(lazurio): a draft thread offers the Environment browser, and its first message hands its tabs to the thread MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A draft's right panel said the Environment browser comes with the first message (variant 2 of #53). Now a draft offers Nová karta like a thread: one read (`?draft=1`, outside the holds' queue) gives its empty strip, tabs opened there are the device's own with nothing held, × offers Vrátit without a release, and when the first message makes the draft a thread its open tabs are held for that thread before its stream opens. A draft left without a message holds nothing. Ported onto the rebuilt main as one commit; it was reviewed as 66e088eb83 to efa77718f8 (branch backup/LZD-0025-B10-koncept-efa7771). Plan LZD-0025 B10 (LazurioDevelopment/mission-control-data#191), decided by Matěj 2026-11-17. Co-Authored-By: Claude Opus 5.5 --- apps/server/src/lazurio/threadTabs.test.ts | 6 ++ apps/server/src/lazurio/threadTabs.ts | 19 ++-- .../src/lazurio/threadTabsRoute.test.ts | 10 ++ apps/server/src/lazurio/threadTabsRoute.ts | 10 +- apps/web/src/components/RightPanelTabs.tsx | 8 +- ...LazurioEnvironmentBrowser.browser.test.tsx | 100 +++++++++++++++--- .../src/lazurio/LazurioEnvironmentBrowser.tsx | 45 +++----- .../lazurio/LazurioNewTab.browser.test.tsx | 44 ++++---- apps/web/src/lazurio/LazurioNewTab.tsx | 5 +- ...urioNewTab.withoutElement.browser.test.tsx | 11 -- .../src/lazurio/threadTabs.browser.test.ts | 75 ++++++++++--- apps/web/src/lazurio/threadTabs.ts | 90 +++++++++++----- docs/operations/lazurio-fork-release.md | 2 +- docs/operations/lazurio-overlay.md | 28 ++--- scripts/lazurio-release-contract.test.mjs | 17 ++- 15 files changed, 309 insertions(+), 161 deletions(-) diff --git a/apps/server/src/lazurio/threadTabs.test.ts b/apps/server/src/lazurio/threadTabs.test.ts index 098bd02cf1492..8eb838024b275 100644 --- a/apps/server/src/lazurio/threadTabs.test.ts +++ b/apps/server/src/lazurio/threadTabs.test.ts @@ -493,9 +493,15 @@ describe("holds and releases", () => { await expect(w.core.hold("5c4b3a29-1807-4f6e-9d5c-4b3a2918f7e6", id(1))).rejects.toMatchObject({ reason: "thread-not-found", }); + // A draft's read: an unknown thread's strip, which holds nothing. + expect(await w.core.read("5c4b3a29-1807-4f6e-9d5c-4b3a2918f7e6", true)).toMatchObject({ + strip: "t3-5c4b3a29-1807-4f6e-9d5c-4b3a2918f7e6", + tabs: [], + }); await w.core.lifecycle({ type: "retired", threadId: threadA }); await expect(w.core.hold(threadA, id(1))).rejects.toMatchObject({ reason: "thread-not-found" }); await expect(w.core.read(threadA)).rejects.toMatchObject({ reason: "thread-not-found" }); + await expect(w.core.read(threadA, true)).rejects.toMatchObject({ reason: "thread-not-found" }); await w.core.record(threadA, id(2), true); expect(await w.stored()).toBeNull(); }); diff --git a/apps/server/src/lazurio/threadTabs.ts b/apps/server/src/lazurio/threadTabs.ts index 77c8e90d00209..3efb84022a9ab 100644 --- a/apps/server/src/lazurio/threadTabs.ts +++ b/apps/server/src/lazurio/threadTabs.ts @@ -144,7 +144,8 @@ export interface ThreadTabsCoreSeams { export interface ThreadTabsCore { /** The Environment's declaration of its browser: the origin of its view, or undefined. */ readonly declare: (viewOrigin: string | undefined) => void; - readonly read: (threadId: string) => Promise; + /** With `draft`, a thread not live yet is a draft's: its strip, which holds nothing so far. */ + readonly read: (threadId: string, draft?: boolean) => Promise; readonly hold: (threadId: string, tabId: string) => Promise; readonly release: (threadId: string, tabId: string) => Promise; /** An agent's tab joins the thread's strip (preview_open, a new binding); never fails. */ @@ -748,11 +749,11 @@ export function createThreadTabs(seams: ThreadTabsCoreSeams): ThreadTabsCore { } publish(); }, - async read(threadId) { + async read(threadId, draft = false) { if (!available()) return { available: false }; await loaded(); const strip = stripOf(threadId); - if (retired.has(strip) || (await liveThreadOf(threadId)) === null) { + if (retired.has(strip) || (!draft && (await liveThreadOf(threadId)) === null)) { throw refusal("thread-not-found"); } return snapshotFor(strip, threadId); @@ -831,8 +832,12 @@ export function createThreadTabs(seams: ThreadTabsCoreSeams): ThreadTabsCore { export class ThreadTabs extends Context.Service< ThreadTabs, { - /** The thread's snapshot, or `{available: false}` while the service is off. */ - readonly read: (threadId: ThreadId) => Effect.Effect; + /** The thread's snapshot, or `{available: false}` while the service is off; with `draft`, + * also of a thread that is not live yet (a draft of a client). */ + readonly read: ( + threadId: ThreadId, + draft?: boolean, + ) => Effect.Effect; readonly hold: ( threadId: ThreadId, tabId: string, @@ -931,8 +936,8 @@ const make = Effect.gen(function* () { ); const attempt = (work: () => Promise) => Effect.tryPromise({ try: work, catch: asError }); return ThreadTabs.of({ - read: Effect.fn("ThreadTabs.read")(function (threadId) { - return attempt(() => core.read(threadId)); + read: Effect.fn("ThreadTabs.read")(function (threadId, draft) { + return attempt(() => core.read(threadId, draft)); }), hold: Effect.fn("ThreadTabs.hold")(function (threadId, tabId) { return attempt(() => core.hold(threadId, tabId)); diff --git a/apps/server/src/lazurio/threadTabsRoute.test.ts b/apps/server/src/lazurio/threadTabsRoute.test.ts index 25ffb5b23c476..5a824b2dae6a8 100644 --- a/apps/server/src/lazurio/threadTabsRoute.test.ts +++ b/apps/server/src/lazurio/threadTabsRoute.test.ts @@ -221,6 +221,16 @@ it.layer(authLayer.pipe(Layer.provide(platformLayer)), { excludeTestServices: tr expect(missing.status).toBe(404); expect(await missing.json()).toEqual({ error: "thread-not-found" }); } + // A draft's read: the strip of a thread not live yet. + const draft = await on.handler( + new Request(route("?threadId=5c4b3a29-1807-4f6e-9d5c-4b3a2918f7e6&draft=1"), { + headers: { cookie }, + }), + ); + expect(await draft.json()).toMatchObject({ + strip: "t3-5c4b3a29-1807-4f6e-9d5c-4b3a2918f7e6", + tabs: [], + }); const released = await on.handler( post("/release", { threadId: threadA, tabId: tab }, { cookie, ...sameOrigin }), ); diff --git a/apps/server/src/lazurio/threadTabsRoute.ts b/apps/server/src/lazurio/threadTabsRoute.ts index 36023253bde6e..97e70b6b2dc2c 100644 --- a/apps/server/src/lazurio/threadTabsRoute.ts +++ b/apps/server/src/lazurio/threadTabsRoute.ts @@ -69,6 +69,14 @@ export const layer = HttpRouter.use((router) => ), ); + // `&draft=1`: a client's draft, a thread not live yet; only the plain read takes it. + const draftOfQuery = Effect.map(HttpServerRequest.HttpServerRequest, (request) => + Option.exists( + HttpServerRequest.toURL(request), + (url) => url.searchParams.get("draft") === "1", + ), + ); + const tabRequest = HttpServerRequest.schemaBodyJson(TabRequest).pipe( Effect.asSome, Effect.orElseSucceed(() => Option.none()), @@ -85,7 +93,7 @@ export const layer = HttpRouter.use((router) => yield* authenticate(threadTabsScopes.read); const threadId = yield* threadIdOfQuery; if (Option.isNone(threadId)) return refused("invalid-request"); - return yield* answered(threadTabs.read(threadId.value)); + return yield* answered(threadTabs.read(threadId.value, yield* draftOfQuery)); }), ); diff --git a/apps/web/src/components/RightPanelTabs.tsx b/apps/web/src/components/RightPanelTabs.tsx index b999bf60247e1..fae8933d3188e 100644 --- a/apps/web/src/components/RightPanelTabs.tsx +++ b/apps/web/src/components/RightPanelTabs.tsx @@ -337,8 +337,6 @@ function RightPanelEmptyState(props: { deviceAvailable: boolean; sideChatAvailable: boolean; sideChatDisabledReason: string | null; - /** Lazurio overlay: why the Environment browser is not here yet, instead of upstream's line. */ - browserNote: string | null; }) { const [highlight, setHighlight] = useState(-1); @@ -348,7 +346,7 @@ function RightPanelEmptyState(props: { icon: Globe2, shortcut: "B", available: props.browserAvailable, - disabledReason: props.browserNote ?? SURFACE_UNAVAILABLE_HINTS.browser, + disabledReason: SURFACE_UNAVAILABLE_HINTS.browser, onClick: props.onAddBrowser, }, { @@ -568,9 +566,6 @@ function RightPanelEmptyState(props: { ), )} - {props.browserNote === null ? null : ( -

{props.browserNote}

- )} ); @@ -1581,7 +1576,6 @@ export function RightPanelTabs(props: RightPanelTabsProps) { deviceAvailable={props.deviceAvailable} sideChatAvailable={props.sideChatAvailable === true} sideChatDisabledReason={props.sideChatDisabledReason ?? null} - browserNote={lazurio.browserNote} /> ) : ( props.children diff --git a/apps/web/src/lazurio/LazurioEnvironmentBrowser.browser.test.tsx b/apps/web/src/lazurio/LazurioEnvironmentBrowser.browser.test.tsx index b8e3aec6be98c..b9395f610be95 100644 --- a/apps/web/src/lazurio/LazurioEnvironmentBrowser.browser.test.tsx +++ b/apps/web/src/lazurio/LazurioEnvironmentBrowser.browser.test.tsx @@ -25,6 +25,7 @@ import { reloadSurface, rememberTitle, resetThreadTabs, + showOwnTab, syncOf, tabSurfaceId, type ThreadTab, @@ -105,7 +106,8 @@ const showRoute = (params: Record) => { /** * One test's page, from nothing: the stores start empty, the route shows no thread, the server's - * streams are fakes the test emits on, and its POSTs answer with thread A's holder file. + * streams are fakes the test emits on, and its POSTs and a draft's read (recorded by its address, + * with no body) answer with thread A's holder file. */ function setup() { route.state.matches = []; @@ -139,14 +141,17 @@ function setup() { stubs.use( stubGlobal("fetch", async (url: string, init: RequestInit) => { const action = url.split("/").at(-1) ?? ""; - const body = JSON.parse(String(init.body)) as { readonly tabId: string }; + const body = + init.body === undefined ? null : (JSON.parse(String(init.body)) as { tabId: string }); posted.push({ action, body }); - held = - action === "hold" - ? held.some((entry) => entry.tabId === body.tabId) - ? held - : [...held, { tabId: body.tabId, view: "", agent: false, alsoHeldBy: [] }] - : held.filter((entry) => entry.tabId !== body.tabId); + if (body !== null) { + held = + action === "hold" + ? held.some((entry) => entry.tabId === body.tabId) + ? held + : [...held, { tabId: body.tabId, view: "", agent: false, alsoHeldBy: [] }] + : held.filter((entry) => entry.tabId !== body.tabId); + } return new Response(JSON.stringify(snapshot(held)), { status: 200, headers: { "content-type": "application/json" }, @@ -706,19 +711,47 @@ describe("the chat's hook", () => { // The draft keeps its ref when it becomes a thread (ChatView's promotion is data-driven). await using screen = await renderUi(); expect(page.opened).toHaveLength(0); - expect(useThreadTabsStore.getState().draftInView).toEqual(threadA); - expect(useThreadTabsStore.getState().inView).toBeNull(); + expect(useThreadTabsStore.getState().inView).toEqual(threadA); + // A tab opened in the draft is the device's own until the first message. + showOwnTab(threadA, id(1), true); + await settled(); + expect(page.posted).toEqual([{ action: "thread-tabs?threadId=thread-A&draft=1", body: null }]); await screen.rerender(); expect(page.stream().url).toBe("/api/lazurio/thread-tabs/events?threadId=thread-A"); - expect(useThreadTabsStore.getState().draftInView).toBeNull(); expect(useThreadTabsStore.getState().inView).toEqual(threadA); - await page.stream().emit("snapshot", snapshot([{ tabId: id(1) }])); - expect(panel().surfaces).toEqual([tab(1)]); - // Another draft in view takes the line; leaving it clears it. + await settled(); + expect(page.posted.at(-1)).toEqual({ + action: "hold", + body: { threadId: "thread-A", tabId: id(1) }, + }); + await page.stream().emit("snapshot", snapshot([{ tabId: id(1) }, { tabId: id(2) }])); + expect(panel().surfaces).toEqual([tab(1), tab(2)]); + // Another draft in view, and then none. await screen.rerender(); - expect(useThreadTabsStore.getState().draftInView).toEqual(threadB); + expect(useThreadTabsStore.getState().inView).toEqual(threadB); + await settled(threadB); await screen.rerender(

Elsewhere

); - expect(useThreadTabsStore.getState().draftInView).toBeNull(); + expect(useThreadTabsStore.getState().inView).toBeNull(); + }); + + it("holds a draft's tabs for its thread and opens the stream while the draft's read still stalls", async () => { + using page = setup(); + const answer = window.fetch; + using _stalled = stubGlobal("fetch", (url: string, init: RequestInit) => + init.body === undefined ? new Promise(() => undefined) : answer(url, init), + ); + await using screen = await renderUi(); + showOwnTab(threadA, id(1), true); + await screen.rerender(); + expect(page.stream().url).toBe("/api/lazurio/thread-tabs/events?threadId=thread-A"); + await vi.waitFor(() => + expect(page.posted.at(-1)).toEqual({ + action: "hold", + body: { threadId: "thread-A", tabId: id(1) }, + }), + ); + await settled(); + expect(panel().surfaces).toEqual([tab(1)]); }); it("asks nothing for a thread of another environment, or in the desktop app", async () => { @@ -855,6 +888,41 @@ describe("the chat's hook", () => { expect(page.posted).toEqual([]); }); + it("offers Vrátit for a tab closed in a draft without a release, and the thread holds it once restored", async () => { + using page = setup(); + await using screen = await renderUi(); + using toasts = vi.spyOn(toastManager, "add"); + showOwnTab(threadA, id(1), true); + showOwnTab(threadA, id(2), false); + await settled(); + await act(() => useRightPanelStore.getState().closeSurface(threadA, tab(1).id)); + await settled(); + expect(panel().surfaces).toEqual([tab(2)]); + expect(toasts).toHaveBeenCalledTimes(1); + expect(toasts.mock.calls[0]?.[0]).toMatchObject({ + title: "The tab left this thread.", + description: "It closes in the Environment.", + actionProps: { children: "Undo" }, + }); + const undo = toasts.mock.calls[0]?.[0].actionProps as { onClick: () => void } | undefined; + await act(() => undo?.onClick()); + expect(panel()).toMatchObject({ activeSurfaceId: tab(1).id, surfaces: [tab(1), tab(2)] }); + await settled(); + // Nothing is held or released while it is a draft; the thread its first message makes holds both. + expect(page.posted).toEqual([{ action: "thread-tabs?threadId=thread-A&draft=1", body: null }]); + await screen.rerender(); + await settled(); + expect( + page.posted + .slice(1) + .map((entry) => [entry.action, (entry.body as { tabId: string }).tabId]) + .sort(), + ).toEqual([ + ["hold", id(1)], + ["hold", id(2)], + ]); + }); + it("opens a link to one remote tab in the panel on a plain click, held, and leaves other clicks alone", async () => { using page = setup(); await using screen = await renderUi(chatOn(threadA)); diff --git a/apps/web/src/lazurio/LazurioEnvironmentBrowser.tsx b/apps/web/src/lazurio/LazurioEnvironmentBrowser.tsx index 40882f755475f..ee7cd11f81883 100644 --- a/apps/web/src/lazurio/LazurioEnvironmentBrowser.tsx +++ b/apps/web/src/lazurio/LazurioEnvironmentBrowser.tsx @@ -26,15 +26,13 @@ import { readEnvironmentBrowserMessage, viewEnvironmentId, } from "./environmentBrowser"; -import { NewTabSurface, type SurfaceAction, useNewTab, useNewTabDefined } from "./LazurioNewTab"; +import { NewTabSurface, type SurfaceAction, useNewTab } from "./LazurioNewTab"; import { type ClosedTabs, - draftBrowserNote, type EnvironmentBrowserSurface, enterDraft, enterThreadTabs, isNewTabSurface, - leaveDraft, leaveThreadTabs, letGoOfTabs, openLinkInPanel, @@ -97,8 +95,8 @@ const parseData = (data: unknown) => { /** * A tab of this Environment that the person closed in the strip, by any close action, while the - * list still has it or its hold is pending: the thread lets go of it. Store changes in one task - * (upstream's Close all closes one at a time) make one batch and one toast. + * list still has it, its hold is pending or a draft keeps it: the thread lets go of it. Store + * changes in one task (upstream's Close all closes one at a time) make one batch and one toast. */ function watchClosedTabs(threadRef: ScopedThreadRef): () => void { const key = scopedThreadKey(threadRef); @@ -120,7 +118,7 @@ function watchClosedTabs(threadRef: ScopedThreadRef): () => void { if (remaining.has(surface.id)) return false; const tab = tabIdOfSurface(surface); if (tab === null || sync.ended.has(tab) || sync.released.has(tab)) return false; - return listed.has(tab) || sync.pending.has(tab); + return listed.has(tab) || sync.pending.has(tab) || (sync.draft && sync.local.has(tab)); }); if (closed.length === 0) return; if (batch === null) { @@ -151,8 +149,8 @@ function watchClosedTabs(threadRef: ScopedThreadRef): () => void { /** * Lazurio overlay: ChatView's one hook. The strip follows the server's list of the thread's tabs, * a new reveal opens the inline panel (never the sheet), and a plain click on a remote-tab link in - * the chat opens it in the panel. A draft opens no stream: the server would answer 404, which an - * EventSource never retries, so the stream starts once the draft is a thread (Lazurio/t3code#53). + * the chat opens it in the panel. A draft opens no stream and holds nothing (`enterDraft`); the + * stream starts once its first message makes it a thread, which then holds the draft's tabs. */ export function useLazurioThreadTabs( input: ScopedThreadRef | null, @@ -168,11 +166,15 @@ export function useLazurioThreadTabs( if (threadRef !== null) syncOf(threadRef).inlinePanel = inlinePanel; }, [threadRef, inlinePanel]); - // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a draft's presence in view is a mount lifecycle the module tracks + // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- a draft in view: one read of its strip on the server, and its presence the module tracks useEffect(() => { if (threadRef === null || !draft) return; - enterDraft(threadRef); - return () => leaveDraft(threadRef, stillShown(router, threadRef)); + void enterDraft(threadRef); + const stopWatching = watchClosedTabs(threadRef); + return () => { + stopWatching(); + leaveThreadTabs(threadRef, stillShown(router, threadRef)); + }; }, [threadRef, draft, router]); // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to the server's EventSource of the thread's tabs @@ -316,27 +318,14 @@ export type FrameTitles = ReturnType["titles /** * RightPanelTabs's one hook: whether "+" and the empty panel open Nová karta (`newTab`, - * LazurioNewTab.tsx), the empty panel's line on a draft, and the titles the frames report. The - * strip is compiled and memoizes its tabs by their inputs, so a tab's title follows its frame only - * because the titles reach `surfaceTitle` through here, never read from the store while it renders. + * LazurioNewTab.tsx), and the titles the frames report. The strip is compiled and memoizes its tabs + * by their inputs, so a tab's title follows its frame only because the titles reach `surfaceTitle` + * through here, never read from the store while it renders. */ export function useRightPanel(actions: ReadonlyArray) { const newTab = useNewTab(actions); const titles = useThreadTabsStore((state) => state.titles); - // A draft on an Environment whose shell offers Nová karta, unless the server already said that - // this Environment has no browser for another thread. - const draftNote = useThreadTabsStore( - (state) => - state.draftInView !== null && - !Object.values(state.snapshots).some((answer) => answer === null), - ); - const defined = useNewTabDefined(); - return { - newTab, - /** The empty panel's line about the Environment browser, or null for upstream's. */ - browserNote: draftNote && defined ? draftBrowserNote(prefersCzech()) : null, - titles, - }; + return { newTab, titles }; } /** The strip's title of an Environment browser tab: what its frame reported, or Nová karta. */ diff --git a/apps/web/src/lazurio/LazurioNewTab.browser.test.tsx b/apps/web/src/lazurio/LazurioNewTab.browser.test.tsx index f5ee28a18fdef..995a627ce239c 100644 --- a/apps/web/src/lazurio/LazurioNewTab.browser.test.tsx +++ b/apps/web/src/lazurio/LazurioNewTab.browser.test.tsx @@ -15,6 +15,7 @@ import { import { LazurioRightPanelSurfaces } from "./LazurioEnvironmentBrowser"; import { NEW_TAB_ELEMENT } from "./LazurioNewTab"; import { + enterDraft, isNewTabSurface, newTabSurface, resetThreadTabs, @@ -48,8 +49,6 @@ const snapshot: ThreadTabsSnapshot = { viewOrigin, tabs: [], }; -/** The draft's line in English, the test browser's language. */ -const DRAFT_LINE = "The Environment browser comes with the first message."; const files: RightPanelSurface = { id: "files", kind: "files" }; const panel = () => selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadA); const setPanel = (state: ThreadRightPanelState) => @@ -58,7 +57,8 @@ const noop = () => undefined; /** * One test's page with the shell's element, from nothing: the stores start empty, and the server's - * POSTs answer with thread A's holder file. + * POSTs and a draft's read (recorded by its address, with no body) answer with thread A's holder + * file. */ async function setup() { resetThreadTabs(); @@ -71,12 +71,15 @@ async function setup() { let held: string[] = []; const fetch = stubGlobal("fetch", async (url: string, init: RequestInit) => { const action = url.split("/").at(-1) ?? ""; - const body = JSON.parse(String(init.body)) as { readonly tabId: string }; + const body = + init.body === undefined ? null : (JSON.parse(String(init.body)) as { tabId: string }); posted.push({ action, body }); - held = - action === "hold" - ? [...new Set([...held, body.tabId])] - : held.filter((entry) => entry !== body.tabId); + if (body !== null) { + held = + action === "hold" + ? [...new Set([...held, body.tabId])] + : held.filter((entry) => entry !== body.tabId); + } const tabs = held.map((tab) => ({ tabId: tab, agent: false, alsoHeldBy: [] })); return new Response(JSON.stringify({ ...snapshot, tabs }), { status: 200, @@ -199,25 +202,18 @@ describe("with the shell's element", () => { expect(panel().surfaces).toEqual([]); }); - it("says on a draft's empty panel that the Environment browser comes with its first message", async () => { - using _page = await setup(); - useThreadTabsStore.setState({ draftInView: threadA }); + it("shows Nová karta on a draft's empty panel, where a chosen page is the device's own", async () => { + using page = await setup(); setPanel({ isOpen: true, activeSurfaceId: null, surfaces: [] }); + await enterDraft(threadA); await using screen = await render(strip()); - expect(screen.container.textContent).toContain("Open a surface"); - expect(screen.container.textContent).toContain(DRAFT_LINE); - expect(screen.container.querySelector(NEW_TAB_ELEMENT)).toBeNull(); - // Where the server said of another thread that this Environment has no browser, upstream's - // line stays. - await act(() => - useThreadTabsStore.setState({ - snapshots: { - [scopedThreadKey(scopeThreadRef("env-1" as EnvironmentId, ThreadId.make("thread-B")))]: - null, - }, - }), + expect(screen.container.querySelector(NEW_TAB_ELEMENT)?.getAttribute("strip")).toBe( + "t3-thread-A", ); - expect(screen.container.textContent).not.toContain(DRAFT_LINE); + await choose(screen.container, { kind: "page", tab: tabId, view: `${viewOrigin}/t/${tabId}` }); + expect(panel().surfaces).toEqual([{ id: tabSurfaceId(tabId), kind: "environment-browser" }]); + await syncOf(threadA).queue; + expect(page.posted).toEqual([{ action: "thread-tabs?threadId=thread-A&draft=1", body: null }]); }); it("shows Nová karta as the empty panel, with the thread's strip and upstream's tools", async () => { diff --git a/apps/web/src/lazurio/LazurioNewTab.tsx b/apps/web/src/lazurio/LazurioNewTab.tsx index 43050ca685750..accb62b7f379b 100644 --- a/apps/web/src/lazurio/LazurioNewTab.tsx +++ b/apps/web/src/lazurio/LazurioNewTab.tsx @@ -117,9 +117,6 @@ if (typeof customElements !== "undefined") { .then(() => useNewTabStore.setState({ defined: true })); } -/** Whether this page's shell defines Nová karta: the page is a Lazurio Environment's. */ -export const useNewTabDefined = () => useNewTabStore((state) => state.defined); - /** Upstream's actions as RightPanelTabs last rendered them: each runs in Nová karta's place. */ let publishedActions: ReadonlyArray = []; @@ -190,7 +187,7 @@ const sameTools = (left: readonly NewTabTool[], right: readonly NewTabTool[]) => return other !== undefined && other.id === tool.id && other.key === tool.key; }); -/** The thread in view while the server keeps its tabs, else null. */ +/** The thread or draft in view while the server keeps its tabs, else null. */ const threadWithTabs = (state: ReturnType) => state.inView !== null && (state.snapshots[scopedThreadKey(state.inView)] ?? null) !== null ? state.inView diff --git a/apps/web/src/lazurio/LazurioNewTab.withoutElement.browser.test.tsx b/apps/web/src/lazurio/LazurioNewTab.withoutElement.browser.test.tsx index 186c409b40e90..4e608af551d3d 100644 --- a/apps/web/src/lazurio/LazurioNewTab.withoutElement.browser.test.tsx +++ b/apps/web/src/lazurio/LazurioNewTab.withoutElement.browser.test.tsx @@ -37,8 +37,6 @@ const snapshot: ThreadTabsSnapshot = { viewOrigin: "https://browser.vm-01.example.lazurio.io", tabs: [], }; -/** The draft's line in English, the test browser's language. */ -const DRAFT_LINE = "The Environment browser comes with the first message."; const files: RightPanelSurface = { id: "files", kind: "files" }; const panel = () => selectThreadRightPanelState(useRightPanelStore.getState().byThreadKey, threadA); const setPanel = (state: ThreadRightPanelState) => @@ -153,13 +151,4 @@ describe("without the shell's element", () => { ); expect(panel().surfaces).toEqual([files]); }); - - it("keeps upstream's empty panel on a draft, without the Environment browser's line", async () => { - setup(); - useThreadTabsStore.setState({ draftInView: threadA }); - setPanel({ isOpen: true, activeSurfaceId: null, surfaces: [] }); - await using screen = await render(strip()); - expect(screen.container.textContent).toContain("Open a surface"); - expect(screen.container.textContent).not.toContain(DRAFT_LINE); - }); }); diff --git a/apps/web/src/lazurio/threadTabs.browser.test.ts b/apps/web/src/lazurio/threadTabs.browser.test.ts index b9c142b859bf6..e550d0a04585c 100644 --- a/apps/web/src/lazurio/threadTabs.browser.test.ts +++ b/apps/web/src/lazurio/threadTabs.browser.test.ts @@ -19,7 +19,6 @@ import { enterThreadTabs, holdTab, isNewTabSurface, - leaveDraft, leaveThreadTabs, letGoOfTabs, newTabSurface, @@ -76,8 +75,9 @@ const answerWith = new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json" } }); /** - * The page's own server for one test, from nothing: the stores start empty, and every POST is - * recorded and gets the next queued answer, or an empty list. + * The page's own server for one test, from nothing: the stores start empty, and every request is + * recorded (a draft's read by its address, with no body) and gets the next queued answer, or an + * empty list. */ function setup() { resetThreadTabs(); @@ -86,7 +86,8 @@ function setup() { const posted: Array<{ readonly action: string; readonly body: unknown }> = []; const answers: Array<() => Response | Promise> = []; const fetch = stubGlobal("fetch", async (url: string, init: RequestInit) => { - posted.push({ action: url.split("/").at(-1) ?? "", body: JSON.parse(String(init.body)) }); + const body = init.body === undefined ? null : JSON.parse(String(init.body)); + posted.push({ action: url.split("/").at(-1) ?? "", body }); const next = answers.shift(); return next === undefined ? answerWith(snapshot([]))() : next(); }); @@ -113,9 +114,9 @@ function setup() { }; } -/** Waits for the thread's POSTs queued so far, and those they queue. */ -async function settled() { - const sync = syncOf(threadA); +/** Waits for the thread's requests queued so far, and those they queue. */ +async function settled(threadRef = threadA) { + const sync = syncOf(threadRef); let queue: Promise; do { queue = sync.queue; @@ -190,13 +191,13 @@ describe("reveals", () => { }); }); - it("keep what the device saw while the route shows the thread, and start again once the person left it", () => { + it("keep what the device saw while the route shows the thread, and start again once the person left it", async () => { using _server = setup(); syncOf(threadA).inlinePanel = true; // The person sends the first message of a draft: the route still shows the draft as its thread's // stream opens. - enterDraft(threadA); - leaveDraft(threadA, true); + await enterDraft(threadA); + leaveThreadTabs(threadA, true); enterThreadTabs(threadA); receiveSnapshot(threadA, snapshot([])); // The thread's view closes and opens again while the route still shows it (ChatView mounting @@ -215,8 +216,8 @@ describe("reveals", () => { expect(panel().isOpen).toBe(false); // The same after another thread's draft. leaveThreadTabs(threadA, false); - enterDraft(threadB); - leaveDraft(threadB, false); + await enterDraft(threadB); + leaveThreadTabs(threadB, false); enterThreadTabs(threadA); receiveSnapshot(threadA, snapshot([{ tabId: id(1), revealRequest: { id: "epoch-1:3" } }])); expect(panel().isOpen).toBe(false); @@ -361,6 +362,56 @@ describe("holds", () => { expect(panel().surfaces).toEqual([]); expect(syncOf(threadA).pending.size).toBe(0); }); + it("keep a draft's tabs the device's own, and hold them for the thread its first message makes before any snapshot of its stream", async () => { + using server = setup(); + const read = enterDraft(threadA); + // Tabs opened in the draft, before its read answers: shown, and nothing holds them on the server. + chooseTab(threadA, null, id(1)); + showOwnTab(threadA, id(2), false); + await read; + expect(panel()).toEqual({ + isOpen: true, + activeSurfaceId: tab(1).id, + surfaces: [tab(1), tab(2)], + }); + expect(server.posted).toEqual([ + { action: "thread-tabs?threadId=thread-A&draft=1", body: null }, + ]); + // The person closes one; the first message makes the draft the thread, whose stream opens. + useRightPanelStore.getState().closeSurface(threadA, tab(2).id); + const hold = server.heldAnswer(); + leaveThreadTabs(threadA, true); + enterThreadTabs(threadA); + expect([...syncOf(threadA).pending]).toEqual([id(1)]); + // The stream's first snapshot, from before the hold landed, keeps the tab. + receiveSnapshot(threadA, snapshot([], { revision: 2 })); + expect(panel().surfaces).toEqual([tab(1)]); + await hold.wasSent; + hold.answer(answerWith(snapshot([{ tabId: id(1) }], { revision: 3 }))()); + await settled(); + expect(server.posted.slice(1)).toEqual([ + { action: "hold", body: { threadId: "thread-A", tabId: id(1) } }, + ]); + expect(syncOf(threadA).pending.size).toBe(0); + expect(panel().surfaces).toEqual([tab(1)]); + }); + + it("hold nothing of a draft left without a message, also not for the next thread in view", async () => { + using server = setup(); + const read = enterDraft(threadA); + showOwnTab(threadA, id(1), true); + await read; + // Its view ends while the draft shows it: nothing to let go of on the server. + tabEnded(threadA, tab(1).id); + showOwnTab(threadA, id(2), true); + leaveThreadTabs(threadA, false); + enterThreadTabs(threadB); + await settled(); + await settled(threadB); + expect(server.posted).toEqual([ + { action: "thread-tabs?threadId=thread-A&draft=1", body: null }, + ]); + }); }); describe("closing in the strip and Vrátit", () => { diff --git a/apps/web/src/lazurio/threadTabs.ts b/apps/web/src/lazurio/threadTabs.ts index 0542d866dfd48..49df851e68c0f 100644 --- a/apps/web/src/lazurio/threadTabs.ts +++ b/apps/web/src/lazurio/threadTabs.ts @@ -297,11 +297,8 @@ interface ThreadTabsState { /** How often each tab's frame was reloaded, by surface id: part of its frame's key, so a reload * is a fresh frame, also of a tab behind the one in front. */ readonly reloads: Readonly>; - /** The thread the chat shows, whose panel may show Nová karta. */ + /** The thread or draft the chat shows, whose panel may show Nová karta. */ readonly inView: ScopedThreadRef | null; - /** The draft the chat shows: no thread of the server yet, so it has no tabs until its first - * message (Lazurio/t3code#53). */ - readonly draftInView: ScopedThreadRef | null; } export const useThreadTabsStore = create(() => ({ @@ -309,7 +306,6 @@ export const useThreadTabsStore = create(() => ({ titles: {}, reloads: {}, inView: null, - draftInView: null, })); export function rememberTitle(surfaceId: string, title: string | null): void { @@ -356,6 +352,8 @@ export interface ThreadTabsSync { accepted: { readonly epoch: string; readonly revision: number } | null; /** Runs of the server the device saw replaced: their snapshots never come back. */ readonly leftEpochs: Set; + /** A draft on this device: its tabs are the device's own (`local`) until its stream opens. */ + draft: boolean; } const syncs = new Map(); @@ -375,6 +373,7 @@ export function syncOf(threadRef: ScopedThreadRef): ThreadTabsSync { intentCount: 0, accepted: null, leftEpochs: new Set(), + draft: false, }; syncs.set(key, sync); } @@ -389,7 +388,6 @@ export function resetThreadTabs(): void { titles: {}, reloads: {}, inView: null, - draftInView: null, }); } @@ -567,11 +565,22 @@ function leftThread(threadRef: ScopedThreadRef, stillShown: boolean): void { if (!stillShown) syncOf(threadRef).baseline = null; } -/** The thread's stream opens. */ +/** + * The thread's stream opens. Where the first message made this device's draft the thread, the + * thread holds the draft's tabs still in the strip, pending from here on: before any snapshot of + * the stream can reconcile them away. + */ export function enterThreadTabs(threadRef: ScopedThreadRef): void { useThreadTabsStore.setState({ inView: threadRef }); + const sync = syncOf(threadRef); + if (!sync.draft) return; + sync.draft = false; + const tabs = [...sync.local]; + sync.local.clear(); + for (const tab of tabs) if (hasSurface(threadRef, tabSurfaceId(tab))) holdTab(threadRef, tab); } +/** The thread's or the draft's view closes. */ export function leaveThreadTabs(threadRef: ScopedThreadRef, stillShown: boolean): void { leftThread(threadRef, stillShown); const inView = useThreadTabsStore.getState().inView; @@ -580,25 +589,38 @@ export function leaveThreadTabs(threadRef: ScopedThreadRef, stillShown: boolean) } } -/** A draft comes into view: the panel says that the Environment browser comes with the first - * message, instead of upstream's desktop-only line. */ -export function enterDraft(threadRef: ScopedThreadRef): void { - useThreadTabsStore.setState({ draftInView: threadRef }); -} - -export function leaveDraft(threadRef: ScopedThreadRef, stillShown: boolean): void { - leftThread(threadRef, stillShown); - const draft = useThreadTabsStore.getState().draftInView; - if (draft !== null && scopedThreadKey(draft) === scopedThreadKey(threadRef)) { - useThreadTabsStore.setState({ draftInView: null }); +/** One read of a draft's strip on this page's own origin; null where the server gave none. */ +async function readDraft(threadId: string): Promise { + try { + const response = await window.fetch( + `${THREAD_TABS_ROUTE}?threadId=${encodeURIComponent(threadId)}&draft=1`, + { + credentials: "same-origin", + redirect: "error", + cache: "no-store", + headers: { accept: "application/json" }, + }, + ); + return response.status === 200 ? parseThreadTabsAnswer(await response.json()) : null; + } catch { + return null; } } -/** The empty panel's line on a draft (Lazurio/t3code#53; the Admin chose it on 2026-10-12). */ -export const draftBrowserNote = (czech: boolean) => - czech - ? "Prohlížeč Prostředí bude k dispozici po první zprávě." - : "The Environment browser comes with the first message."; +/** + * A draft comes into view (Lazurio/t3code#53): no stream, whose 404 an EventSource never retries, + * and its tabs stay the device's own (`holdTab`). One read of its empty strip gives Nová karta the + * strip and the frames the view origin. + */ +export function enterDraft(threadRef: ScopedThreadRef): Promise { + syncOf(threadRef).draft = true; + useThreadTabsStore.setState({ inView: threadRef }); + // Outside the holds' queue: a stalled read never holds back the first message's holds. Once the + // draft is a thread, its stream is newer than any answer of the read. + return readDraft(threadRef.threadId).then((answer) => { + if (answer !== null && syncOf(threadRef).draft) receiveSnapshot(threadRef, answer); + }); +} const RETRY_DELAYS_MS = [1_000, 2_000, 4_000, 8_000, 16_000, 30_000]; @@ -612,16 +634,20 @@ function intend(sync: ThreadTabsSync, tab: string): () => boolean { /** * Pending until the POST answers. Network failures and 5xx retry with backoff for about a minute - * while the tab is in the strip; a refusal or an outlasting failure leaves it the device's own, - * which ends 30 s after its last viewer (F39). A later × replaces the hold, even mid-flight. + * while the tab is in the strip; a refusal, an outlasting failure or a draft leaves it the + * device's own, which ends 30 s after its last viewer (F39). A later × replaces the hold. */ export function holdTab(threadRef: ScopedThreadRef, tabId: string): void { const sync = syncOf(threadRef); const tab = tabId.toUpperCase(); const current = intend(sync, tab); - sync.pending.add(tab); sync.released.delete(tab); sync.ended.delete(tab); + if (sync.draft) { + sync.local.add(tab); + return; + } + sync.pending.add(tab); sync.local.delete(tab); const attempt = (tries: number) => enqueue(sync, async () => { @@ -672,6 +698,8 @@ function releaseTab(threadRef: ScopedThreadRef, tabId: string): void { const sync = syncOf(threadRef); const current = intend(sync, tabId); sync.pending.delete(tabId); + // A draft holds nothing to let go of. + if (sync.draft) return; const attempt = (tries: number) => enqueue(sync, async () => { if (!current()) return; @@ -700,7 +728,8 @@ export interface ClosedTabs { /** * The person closed tabs of the thread in the strip (×, middle click, Close others, Close all): * the thread lets go of them, and one toast says what becomes of them, with Vrátit for 7 s, within - * the hub's 8 s grace. The remote tab stays while anything still needs it. + * the hub's 8 s grace. The remote tab stays while anything still needs it. A draft holds nothing, + * so it only forgets them. */ export function letGoOfTabs(threadRef: ScopedThreadRef, closed: ClosedTabs): void { const sync = syncOf(threadRef); @@ -710,6 +739,10 @@ export function letGoOfTabs(threadRef: ScopedThreadRef, closed: ClosedTabs): voi const tab = tabIdOfSurface(surface); if (tab === null) continue; tabs.push(tab); + if (sync.draft) { + sync.local.delete(tab); + continue; + } sync.released.add(tab); releaseTab(threadRef, tab); } @@ -737,7 +770,8 @@ export function letGoOfTabs(threadRef: ScopedThreadRef, closed: ClosedTabs): voi ); } -/** Vrátit: the tabs go back where they were and the thread holds them again (a new record). */ +/** Vrátit: the tabs go back where they were and the thread holds them again (a new record), or a + * draft keeps them as the device's own (`holdTab`). */ function restoreTabs(threadRef: ScopedThreadRef, closed: ClosedTabs): void { useRightPanelStore.getState().lazurio(threadRef, false, (current) => { const surfaces = [...current.surfaces]; diff --git a/docs/operations/lazurio-fork-release.md b/docs/operations/lazurio-fork-release.md index b3e952d764224..ffc555fd5a846 100644 --- a/docs/operations/lazurio-fork-release.md +++ b/docs/operations/lazurio-fork-release.md @@ -292,7 +292,7 @@ Commity v pořadí na `main`: `apps/server/src/lazurio/agentBrowserSession.ts` a jeho test. - **9.** `6c83822f37`. `apps/web/src/components/ChatView.tsx`\* (volání háčku, obal rámů), `RightPanelTabs.tsx`\* (název s titulky rámů jako vstupem, ikona, - tooltip v `RightPanelTab`, menu záložky, volání háčku, řádek konceptu), + tooltip v `RightPanelTab`, menu záložky, volání háčku), `apps/web/src/rightPanelStore.ts`\* (druh povrchu, jeho člen, `openProactive`, akce `lazurio`, přeskočení v paměti zavřených záložek); `apps/web/src/lazurio/`: `LazurioEnvironmentBrowser.tsx`\* a jeho test v prohlížeči, `environmentBrowser.ts` diff --git a/docs/operations/lazurio-overlay.md b/docs/operations/lazurio-overlay.md index 3e861ce4162cd..dec9398172b61 100644 --- a/docs/operations/lazurio-overlay.md +++ b/docs/operations/lazurio-overlay.md @@ -188,7 +188,8 @@ k přestavbě na v0.1.0, Lazurio/t3code#70), a tak overlay dělá tohle: sleduje spolu s ostatními, a když ho nejde vypsat, nepřevezme žádnou novou vazbu. - **Cesta pro web.** `GET /api/lazurio/thread-tabs?threadId=` vrátí snímek - nebo `{"available": false}`, `GET …/events?threadId=` je SSE se snímkem + nebo `{"available": false}` (s `&draft=1` i pro vlákno, které ještě není živé, + tedy pás konceptu), `GET …/events?threadId=` je SSE se snímkem hned a při každé změně (a s událostmi `foreign`), `POST …/hold` a `POST …/release` s `{threadId, tabId}`. Cesta se ověřuje jako ostatní HTTP cesty T3 (cookie, bearer nebo DPoP; požadavek s cookie z cizího originu @@ -261,16 +262,19 @@ k přestavbě na v0.1.0, Lazurio/t3code#70), a tak overlay dělá tohle: Bez elementu (starší Platforma) zůstává upstream nabídka, Mod+T i prázdný stav a Browser je ve webu nedostupný, protože server serverový prohlížeč neinzeruje. -- **Rozepsané vlákno** (Lazurio/t3code#53, varianta, kterou Admin zvolil - 2026-10-12). Koncept ještě není vlákno serveru: proud záložek by odpověděl +- **Rozepsané vlákno** (Lazurio/t3code#53, varianta 1, kterou uživatel zvolil + 2026-11-17). Koncept ještě není vlákno serveru: proud záložek by odpověděl 404, který EventSource znovu nezkouší, a koncept si po první zprávě nechá - stejný ref vlákna. Proto koncept proud neotevře a jeho prázdný panel zůstane - upstream, jen místo „Only available in the desktop app.“ řekne pod seznamem - i jako důvod u řádku Browser „Prohlížeč Prostředí bude k dispozici po - první zprávě.“ Jakmile ho ChatView přestane označovat za koncept, proud se - otevře a panel ukáže Novou kartu. Kde server o jiném vlákně řekl, že - Environment prohlížeč nemá, zůstane upstream řádek. Menu „+“ při jiných - otevřených površích konceptu nechává u Browser upstream důvod. + stejný ref vlákna. Proto koncept proud neotevře; jednou přečte svůj pás + (`&draft=1`), takže Nová karta dostane `strip` a rámy origin pohledu, a „+“ + i prázdný panel otevřou Novou kartu jako ve vlákně. Záložky, které se + v konceptu otevřou, patří jen zařízení (`local`): server je nedrží, takže + skončí 30 s po posledním divákovi (F39 bod 9). × nabídne Vrátit jako ve + vlákně, ale × ani konec záložky nic neposílá. Jakmile ho ChatView přestane označovat za koncept, vlákno podrží + záložky konceptu, které pás ještě má, dřív, než se otevře proud: čekající + podržení první snímek nezahodí. Odmítnuté podržení nechá záložku jen + zařízení jako jindy. Koncept opuštěný bez zprávy nedrží nic. Kde Environment + prohlížeč nemá, zůstane upstream prázdný stav. - **× pustí záložku jen pro toto vlákno.** ×, prostřední tlačítko i Zavřít, Zavřít ostatní, Zavřít vpravo a Zavřít vše pošlou release. Jeden toast (i pro Zavřít vše) řekne podle snímku, co se stane: pracuje-li v záložce agent, @@ -402,8 +406,8 @@ Upstream soubory overlay mění jen ve švech: `rightPanelStore.ts` (druh povrchu, jeden člen povrchu, Nová karta jako jeho singleton, druh v `openProactive`, jedna obecná akce `lazurio` a přeskočení těchto povrchů v paměti zavřených záložek), `RightPanelTabs.tsx` (jedno volání háčku, „+“ -a prázdný stav za podmínkou Nové karty, jeden řádek pro Mod+T, řádek prázdného -stavu na konceptu, název záložky s titulky rámů jako vstupem `surfaceTitle`, +a prázdný stav za podmínkou Nové karty, jeden řádek pro Mod+T, název záložky +s titulky rámů jako vstupem `surfaceTitle`, ikona, tooltip jako komponenta overlaye v `RightPanelTab` a menu záložky), `ChatView.tsx` (jedno volání háčku s příznakem konceptu a obal kolem `RightPanelSurfaceContent`, který drží rámy vedle povrchu v popředí; od v0.1.2 diff --git a/scripts/lazurio-release-contract.test.mjs b/scripts/lazurio-release-contract.test.mjs index f705c92e64ff1..897c71eabc86c 100644 --- a/scripts/lazurio-release-contract.test.mjs +++ b/scripts/lazurio-release-contract.test.mjs @@ -1977,13 +1977,9 @@ NodeTest.test( /case "environment-browser":\n\s+return ;/, ); NodeAssert.match(tabs, /\n {2}const lazurio = Lazurio\.useRightPanel\(addSurfaceActions\);\n/); - // The empty panel's line on a draft: the Browser row's reason and one line under the list. - NodeAssert.match(tabs, /browserNote=\{lazurio\.browserNote\}/); - NodeAssert.match( - tabs, - /disabledReason: props\.browserNote \?\? SURFACE_UNAVAILABLE_HINTS\.browser,/, - ); - NodeAssert.equal(tabs.match(/props\.browserNote/g)?.length, 3); + // A draft offers Nová karta as a thread does (Lazurio/t3code#53): upstream's empty panel + // carries no line of the overlay's. + NodeAssert.doesNotMatch(tabs, /browserNote/); // Each strip tab is upstream's compiled RightPanelTab: the overlay's tooltip is a component in // place of the title, so the tab's props stay upstream's. NodeAssert.match( @@ -1993,9 +1989,10 @@ NodeTest.test( NodeAssert.doesNotMatch(tabs, /environmentBrowserTitles|previewBridge \? browserDefaults/); // ChatView: one hook call, and upstream's surface in view wrapped once beside the frames. NodeAssert.equal(chatView.match(/useLazurioThreadTabs\(/g)?.length, 1); - // A draft opens no stream until its first message makes it a thread (Lazurio/t3code#53), and - // Buddy's surface, which has no right panel, follows no thread's tabs (row 28), and neither - // does a side chat, which renders ChatView embedded (pingdotgg/t3code#26901). + // A draft opens no stream until its first message makes it a thread, which then holds the + // draft's tabs (Lazurio/t3code#53), and Buddy's surface, which has no right panel, follows no + // thread's tabs (row 28), and neither does a side chat, which renders ChatView embedded + // (pingdotgg/t3code#26901). NodeAssert.match( chatView, /useLazurioThreadTabs\(buddySurface \|\| embedded \? null : activeThreadRef, \{\n\s+inlinePanel: !shouldUsePlanSidebarSheet,\n\s+draft: !isServerThread,\n\s+\}\);/,