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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions apps/server/src/lazurio/threadTabs.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
});
Expand Down
19 changes: 12 additions & 7 deletions apps/server/src/lazurio/threadTabs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<ThreadTabsAnswer>;
/** 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<ThreadTabsAnswer>;
readonly hold: (threadId: string, tabId: string) => Promise<ThreadTabsSnapshot>;
readonly release: (threadId: string, tabId: string) => Promise<ThreadTabsSnapshot>;
/** An agent's tab joins the thread's strip (preview_open, a new binding); never fails. */
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<ThreadTabsAnswer, ThreadTabsError>;
/** 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<ThreadTabsAnswer, ThreadTabsError>;
readonly hold: (
threadId: ThreadId,
tabId: string,
Expand Down Expand Up @@ -931,8 +936,8 @@ const make = Effect.gen(function* () {
);
const attempt = <A>(work: () => Promise<A>) => 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));
Expand Down
10 changes: 10 additions & 0 deletions apps/server/src/lazurio/threadTabsRoute.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 }),
);
Expand Down
10 changes: 9 additions & 1 deletion apps/server/src/lazurio/threadTabsRoute.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<typeof TabRequest.Type>()),
Expand All @@ -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));
}),
);

Expand Down
8 changes: 1 addition & 7 deletions apps/web/src/components/RightPanelTabs.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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,
},
{
Expand Down Expand Up @@ -568,9 +566,6 @@ function RightPanelEmptyState(props: {
),
)}
</div>
{props.browserNote === null ? null : (
<p className="mt-3 text-center text-muted-foreground text-xs">{props.browserNote}</p>
)}
</div>
</div>
);
Expand Down Expand Up @@ -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
Expand Down
100 changes: 84 additions & 16 deletions apps/web/src/lazurio/LazurioEnvironmentBrowser.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
reloadSurface,
rememberTitle,
resetThreadTabs,
showOwnTab,
syncOf,
tabSurfaceId,
type ThreadTab,
Expand Down Expand Up @@ -105,7 +106,8 @@ const showRoute = (params: Record<string, string>) => {

/**
* 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 = [];
Expand Down Expand Up @@ -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" },
Expand Down Expand Up @@ -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(<Chat threadRef={threadA} draft />);
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(<Chat threadRef={threadA} draft={false} />);
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(<Chat threadRef={threadB} draft />);
expect(useThreadTabsStore.getState().draftInView).toEqual(threadB);
expect(useThreadTabsStore.getState().inView).toEqual(threadB);
await settled(threadB);
await screen.rerender(<p>Elsewhere</p>);
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<Response>(() => undefined) : answer(url, init),
);
await using screen = await renderUi(<Chat threadRef={threadA} draft />);
showOwnTab(threadA, id(1), true);
await screen.rerender(<Chat threadRef={threadA} draft={false} />);
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 () => {
Expand Down Expand Up @@ -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(<Chat threadRef={threadA} draft />);
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(<Chat threadRef={threadA} draft={false} />);
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));
Expand Down
45 changes: 17 additions & 28 deletions apps/web/src/lazurio/LazurioEnvironmentBrowser.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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);
Expand All @@ -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) {
Expand Down Expand Up @@ -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,
Expand All @@ -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
Expand Down Expand Up @@ -316,27 +318,14 @@ export type FrameTitles = ReturnType<typeof useThreadTabsStore.getState>["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<SurfaceAction>) {
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. */
Expand Down
Loading
Loading