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
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import { afterAll, afterEach, beforeAll, expect, test } from "bun:test";
import {
emptySnapshot,
formatAttachmentTag,
reduceMany,
} from "@superset/chat/core";
import type { DurableEnvelope, DurableEvent } from "@superset/chat/protocol";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { cleanup, render } from "@testing-library/react";
import type { ContextType } from "react";
import { HostWorkspacesContext } from "renderer/routes/_authenticated/providers/HostWorkspacesProvider";
import { LocalHostServiceContext } from "renderer/routes/_authenticated/providers/LocalHostServiceProvider";
import { SandboxAccessContext } from "renderer/routes/_authenticated/providers/SandboxAccessProvider";
import { StoredChatTranscript } from "./StoredChatTranscript";

// File icons resolve against the page URL, and the test DOM starts on about:blank.
const page = (
window as unknown as { happyDOM: { setURL: (url: string) => void } }
).happyDOM;
beforeAll(() => page.setURL("http://localhost/"));
afterAll(() => page.setURL("about:blank"));
afterEach(cleanup);

function journal(events: DurableEvent[]): DurableEnvelope[] {
return events.map((event, index) => ({
v: 1,
sessionId: "s1",
ts: index,
cursor: { epoch: "e1", seq: index + 1 },
event,
}));
}

const snapshot = reduceMany(
emptySnapshot(),
journal([
{
type: "item",
turnId: "t1",
item: {
id: "u1",
kind: "user_message",
clientId: "c1",
startedAtMs: 1,
content: [
{
type: "text",
text: `fix it\n${formatAttachmentTag({ path: ".superset/attachments/shot.png", type: "image/png" })}`,
},
{
type: "attachment",
attachmentId: "a1",
name: "pasted.png",
mimeType: "image/png",
},
],
},
},
{
type: "item",
turnId: "t1",
item: {
id: "tool-1",
kind: "tool_call",
title: "Edit",
toolKind: "edit",
toolName: "Edit",
status: "completed",
startedAtMs: 2,
content: [
{
type: "diff",
path: "/workspace/src/app.ts",
oldText: "a\n",
newText: "b\n",
},
],
},
},
{
type: "turn",
turn: { id: "t1", status: "completed", startedAtMs: 1, completedAtMs: 3 },
},
]),
);

test("a cloud workspace's stored chat renders while its box wakes, with no workspace host to read from", () => {
const view = render(
<QueryClientProvider client={new QueryClient()}>
<LocalHostServiceContext.Provider
value={
{ machineId: "machine-1", activeHostUrl: null } as NonNullable<
ContextType<typeof LocalHostServiceContext>
>
}
>
<HostWorkspacesContext.Provider
value={
{ workspaces: [], isReady: true } as unknown as NonNullable<
ContextType<typeof HostWorkspacesContext>
>
}
>
<SandboxAccessContext.Provider
value={{
targets: [],
isReady: true,
agentCredentialsChangedWorkspaceId: null,
usageRefusal: null,
}}
>
<StoredChatTranscript
chatId="s1"
pending={[]}
snapshot={snapshot}
/>
</SandboxAccessContext.Provider>
</HostWorkspacesContext.Provider>
</LocalHostServiceContext.Provider>
</QueryClientProvider>,
);

expect(view.getByText("Edited 1 file")).toBeTruthy();
expect(view.getByTitle("shot.png")).toBeTruthy();
expect(view.getByTitle("pasted.png")).toBeTruthy();
});
Original file line number Diff line number Diff line change
@@ -1,14 +1,9 @@
import { useLingui } from "@lingui/react/macro";
import type { AppRouter } from "@superset/host-service/trpc";
import { workspaceTrpc } from "@superset/workspace-client";
import {
keepPreviousData,
QueryClient,
useQuery,
useQueryClient,
} from "@tanstack/react-query";
import { TRPCClientError } from "@trpc/client";
import { observable } from "@trpc/server/observable";
import { type ReactNode, useEffect } from "react";
import { cloudTrpc } from "renderer/lib/cloud-trpc";
import { electronQueryClient } from "renderer/providers/ElectronTRPCProvider";
Expand All @@ -28,21 +23,6 @@ const PREFETCHED_CHATS = 5;
const STALE_MS = 60_000;
const NO_PROMPTS: never[] = [];

/** Transcript rows call workspace hooks, which need a client even with no box to reach. */
const noHostClient = workspaceTrpc.createClient({
links: [
() => () =>
observable((observer) =>
observer.error(
new TRPCClientError<AppRouter>("The workspace has no host yet"),
),
),
],
});
const noHostQueryClient = new QueryClient({
defaultOptions: { queries: { retry: false } },
});

/**
* A cloud workspace's newest chat as the database holds it, while the
* workspace waits for its box to answer, else `fallback`. It is cached under
Expand Down Expand Up @@ -106,16 +86,11 @@ export function StoredCloudChat({
})
}
/>
<workspaceTrpc.Provider
client={noHostClient}
queryClient={noHostQueryClient}
>
<StoredChatTranscript
chatId={chatId}
pending={NO_PROMPTS}
snapshot={stored.data}
/>
</workspaceTrpc.Provider>
<StoredChatTranscript
chatId={chatId}
pending={NO_PROMPTS}
snapshot={stored.data}
/>
<div className="h-6" />
</div>
);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -50,25 +50,27 @@ export function DraftChat({
);

return (
<ComposerDropZone
className="flex h-full min-h-0 w-full min-w-0 flex-col"
ref={paneRef}
<ChatPaneActionsProvider
getOpenFilePaths={getOpenFilePaths}
workspaceId={workspaceId}
>
{transcript ??
(prompts.length > 0 ? (
<PendingPromptsView prompts={prompts} />
) : (
<div className="min-h-0 flex-1" />
))}
<WorkDrawer
onExit={(exit) => composerRef.current?.returnFocus(exit === "history")}
paneRef={paneRef}
ref={drawerRef}
/>
<ChatPaneActionsProvider
getOpenFilePaths={getOpenFilePaths}
workspaceId={workspaceId}
<ComposerDropZone
className="flex h-full min-h-0 w-full min-w-0 flex-col"
ref={paneRef}
>
{transcript ??
(prompts.length > 0 ? (
<PendingPromptsView prompts={prompts} />
) : (
<div className="min-h-0 flex-1" />
))}
<WorkDrawer
onExit={(exit) =>
composerRef.current?.returnFocus(exit === "history")
}
paneRef={paneRef}
ref={drawerRef}
/>
<Composer
availableCommands={NO_COMMANDS}
draftKey={draftKey}
Expand All @@ -80,7 +82,7 @@ export function DraftChat({
onSend={(content) => onQueue(content)}
workspaceId={workspaceId}
/>
</ChatPaneActionsProvider>
</ComposerDropZone>
</ComposerDropZone>
</ChatPaneActionsProvider>
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import { MessageScroller } from "@superset/chat-ui/MessageScroller";
import type { ComposerDraft } from "@superset/chat-ui/PromptInput";
import { ChatHistorySidebarScroller } from "@superset/ui/chat-history-sidebar";
import { toast } from "@superset/ui/sonner";
import { workspaceTrpc } from "@superset/workspace-client";
import type { ReactNode } from "react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { env } from "renderer/env.renderer";
Expand Down Expand Up @@ -312,6 +313,9 @@ export function SessionView({
}),
[client, workspaceId],
);
const worktreePath = workspaceTrpc.workspace.get.useQuery({
id: workspaceId,
}).data?.worktreePath;
const sessionUsage = useMemo(
() => latestSessionUsage(session.snapshot.turns),
[session.snapshot.turns],
Expand Down Expand Up @@ -662,6 +666,7 @@ export function SessionView({
openLink={openLink}
getOpenFilePaths={getOpenFilePaths}
workspaceId={workspaceId}
worktreePath={worktreePath}
>
<ComposerDropZone
className="flex h-full min-h-0 w-full min-w-0 flex-col"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,57 +1,18 @@
import { AttachmentFileCard } from "@superset/chat-ui/AttachmentFileCard";
import { useCallback, useState } from "react";
import { useChatImageSource } from "../../hooks/useChatImageSource";
import { useChatImageGallery } from "../../providers/ChatImageGalleryProvider";
import { galleryImageId } from "../../utils/galleryImages";
import { LargeImageTile } from "./components/LargeImageTile";
import { PreviewableImage } from "./components/PreviewableImage";
import type { ComponentProps } from "react";
import { useChatPaneActions } from "../../../../providers/ChatPaneActionsProvider";
import { HostAttachmentImage } from "./components/HostAttachmentImage";

export function AttachmentImage({
alt,
name: attachedName,
owner,
path,
type,
}: {
/** Transcript key of the item showing the image; pairs with `path` in the gallery. */
owner: string;
path: string;
type: string;
alt?: string | undefined;
name?: string | undefined;
}) {
const { open, registerThumbnail } = useChatImageGallery();
const id = galleryImageId(owner, path);
const name = attachedName || (path.split("/").pop() ?? path);
const source = useChatImageSource({ path, mimeType: type }, { full: false });
const [unrenderable, setUnrenderable] = useState(false);
const register = useCallback(
(element: HTMLElement | null) => {
registerThumbnail(id, element);
return () => registerThumbnail(id, null);
},
[id, registerThumbnail],
);
const openPreview = () => open(id);

if (source.status === "error" || unrenderable)
return <AttachmentFileCard name={name} mediaType={type} />;
if (source.status === "loading")
return (
<div className="size-40 animate-pulse rounded-2xl bg-foreground/10" />
);
if (source.status === "too-large")
export function AttachmentImage(
props: ComponentProps<typeof HostAttachmentImage>,
) {
const { workspaceId } = useChatPaneActions();
if (!workspaceId)
return (
<LargeImageTile filename={name} onClick={openPreview} ref={register} />
<AttachmentFileCard
name={props.name || (props.path.split("/").pop() ?? props.path)}
mediaType={props.type}
/>
);
return (
<PreviewableImage
alt={alt}
filename={name}
onClick={openPreview}
onError={() => setUnrenderable(true)}
ref={register}
src={source.src}
/>
);
return <HostAttachmentImage {...props} />;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { AttachmentFileCard } from "@superset/chat-ui/AttachmentFileCard";
import { useCallback, useState } from "react";
import { useChatImageSource } from "../../../../hooks/useChatImageSource";
import { useChatImageGallery } from "../../../../providers/ChatImageGalleryProvider";
import { galleryImageId } from "../../../../utils/galleryImages";
import { LargeImageTile } from "../LargeImageTile";
import { PreviewableImage } from "../PreviewableImage";

export function HostAttachmentImage({
alt,
name: attachedName,
owner,
path,
type,
}: {
/** Transcript key of the item showing the image; pairs with `path` in the gallery. */
owner: string;
path: string;
type: string;
alt?: string | undefined;
name?: string | undefined;
}) {
const { open, registerThumbnail } = useChatImageGallery();
const id = galleryImageId(owner, path);
const name = attachedName || (path.split("/").pop() ?? path);
const source = useChatImageSource({ path, mimeType: type }, { full: false });
const [unrenderable, setUnrenderable] = useState(false);
const register = useCallback(
(element: HTMLElement | null) => {
registerThumbnail(id, element);
return () => registerThumbnail(id, null);
},
[id, registerThumbnail],
);
const openPreview = () => open(id);

if (source.status === "error" || unrenderable)
return <AttachmentFileCard name={name} mediaType={type} />;
if (source.status === "loading")
return (
<div className="size-40 animate-pulse rounded-2xl bg-foreground/10" />
);
if (source.status === "too-large")
return (
<LargeImageTile filename={name} onClick={openPreview} ref={register} />
);
return (
<PreviewableImage
alt={alt}
filename={name}
onClick={openPreview}
onError={() => setUnrenderable(true)}
ref={register}
src={source.src}
/>
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { HostAttachmentImage } from "./HostAttachmentImage";
Loading
Loading