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
31 changes: 31 additions & 0 deletions apps/server/src/orchestration-v2/ThreadFind.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -463,6 +463,37 @@ describe("V2 thread find", () => {
}).pipe(Effect.provide(layerTest)),
);

it.effect("searches only the picture file chips visible in the viewer's theme", () =>
Effect.gen(function* () {
const projection = yield* setup;
yield* putItems([
item(
"picture",
1,
'<picture><source media="(prefers-color-scheme: dark)" srcset="/workspace/repo/notes.ts#L42-L64"><img src="/workspace/repo/screenshot.png" alt="notes"></picture>',
),
item(
"fallback",
2,
'<picture><source media="(prefers-color-scheme: dark)" srcset="/workspace/repo/dark.png"><img src="/workspace/repo/fallback.ts#L42-L64" alt="notes"></picture>',
),
]);
const dark = { threadId, query: "L42–64", theme: "dark" } as const;
const light = { ...dark, theme: "light" } as const;
const darkResult = yield* projection.searchThread(dark);
assert.equal(darkResult.totalMatches, 1);
assert.equal(darkResult.match?.entryId, "picture");
assert.equal(
(yield* projection.searchThread({ ...light, query: "notes.ts" })).totalMatches,
0,
);
const lightResult = yield* projection.searchThread(light);
assert.equal(lightResult.totalMatches, 1);
assert.equal(lightResult.match?.entryId, "fallback");
assert.equal((yield* projection.searchThread(dark)).match?.entryId, "picture");
}).pipe(Effect.provide(layerTest)),
);

it.effect("refreshes file labels when the project cwd changes without a thread event", () =>
Effect.gen(function* () {
const projection = yield* setup;
Expand Down
13 changes: 10 additions & 3 deletions apps/server/src/orchestration-v2/ThreadFind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -72,12 +72,14 @@ class TextKey extends Data.Class<{
hasContext: boolean;
cwd: string | undefined;
skills: NonNullable<OrchestrationV2SearchThreadInput["skills"]>;
theme: OrchestrationV2SearchThreadInput["theme"];
}> {}

function textKey(
item: OrchestrationV2TurnItem,
cwd: string | undefined,
skills: TextKey["skills"],
theme: TextKey["theme"],
) {
return new TextKey({
text:
Expand All @@ -92,12 +94,13 @@ function textKey(
hasContext: item.type === "user_message" && item.context !== undefined,
cwd,
skills,
theme,
});
}

function parseText(key: TextKey): readonly string[] {
return key.role === "plan"
? searchablePlanSegments(key.text, key.cwd)
? searchablePlanSegments(key.text, key.cwd, key.theme)
: (searchableMessageSegments(
{
role: key.role,
Expand All @@ -107,6 +110,7 @@ function parseText(key: TextKey): readonly string[] {
},
key.cwd,
key.skills,
key.theme,
) ?? []);
}

Expand Down Expand Up @@ -207,6 +211,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
cwd: Schema.optional(Schema.String),
query: Schema.optional(Schema.String),
skills: OrchestrationV2SearchThreadInput.fields.skills,
theme: OrchestrationV2SearchThreadInput.fields.theme,
}),
),
);
Expand Down Expand Up @@ -309,7 +314,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
scans: CompletedScans,
renderedSnapshot: RenderedSnapshot,
) {
const { threadId } = input;
const { threadId, theme } = input;
const active = yield* sql<{ cwd: string | null }>`
SELECT COALESCE(json_extract(t.payload_json, '$.worktreePath'), p.workspace_root) AS cwd
FROM orchestration_v2_projection_threads t JOIN projection_projects p ON p.project_id = t.project_id
Expand All @@ -322,6 +327,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
cwd,
query: input.query,
skills: input.skills ?? [],
...(theme === undefined ? {} : { theme }),
});
const cached = scans.get(cacheKey);
if (cached && cached.sequence === (yield* readRevision(cached.sourceThreadIds))) {
Expand All @@ -334,6 +340,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
threadId,
cwd,
skills: input.skills ?? [],
...(theme === undefined ? {} : { theme }),
});
const rendered = renderedSnapshot.current;
if (
Expand Down Expand Up @@ -449,7 +456,7 @@ export const makeThreadFind = Effect.fn("makeThreadFind")(function* (
rendered = row;
} else {
const decoded = yield* decode(row);
const key = textKey(decoded.item, cwd, input.skills ?? []);
const key = textKey(decoded.item, cwd, input.skills ?? [], input.theme);
const segments =
decoded.item.type === "assistant_message" &&
decoded.item.text === "" &&
Expand Down
17 changes: 6 additions & 11 deletions apps/web/src/components/ChatMarkdown.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
import { clientHostEnvironmentAtom } from "../state/clientHostEnvironment";
import { buildFileLinkParentSuffixByPath, fileLinkLabel } from "@t3tools/shared/fileLinks";
import {
isMarkdownFileLinkLabel,
isWindowsDrivePathHref,
shouldRenderMarkdownImageAsFileLink,
normalizeMarkdownLinkDestination,
extractInlineCodeSpans,
extractMarkdownLinkHrefs,
Expand All @@ -23,6 +25,7 @@ import {
CHAT_MARKDOWN_REMARK_PLUGINS,
CHAT_MARKDOWN_REMARK_PLUGINS_WITH_BREAKS,
CHAT_MARKDOWN_REHYPE_PLUGINS,
chatMarkdownImageSource,
decodeMarkdownLinkEscapes,
remarkAssistantInsights,
} from "@t3tools/shared/markdownPipeline";
Expand Down Expand Up @@ -156,7 +159,6 @@ import {
markdownFileEditorTarget,
resolveMarkdownFileHostPath,
} from "../markdownFileHostPath";
import { isMarkdownFileLinkLabel } from "@t3tools/shared/markdownLinks";
import { isElectron } from "../env";
import { readLocalApi } from "../localApi";
import { appAtomRegistry } from "../rpc/atomRegistry";
Expand Down Expand Up @@ -1586,18 +1588,11 @@ const CHAT_MARKDOWN_COMPONENTS = {
<span>{label}</span>
);
}
// A `<picture>`'s source for this theme, resolved like any other image.
const themeSrc = node?.properties?.[resolvedTheme === "dark" ? "dataDarkSrc" : "dataLightSrc"];
const localSrc = typeof themeSrc === "string" ? undefined : node?.properties?.dataLocalSrc;
const { authoredSrc: srcString = "", classifiedSrc = "" } =
chatMarkdownImageSource(node?.properties ?? { src }, resolvedTheme) ?? {};
const markdownTitle = node?.properties?.dataMarkdownTitle;
const standalone = node?.properties?.dataStandalone === true;
const authoredSrc =
typeof themeSrc === "string" ? themeSrc : typeof localSrc === "string" ? localSrc : src;
const authoredTitle = typeof markdownTitle === "string" ? markdownTitle : title;
const srcString =
typeof authoredSrc === "string" ? normalizeMarkdownLinkDestination(authoredSrc) : "";
const classifiedSrc =
typeof localSrc === "string" ? srcString.replaceAll("\\", "/") : srcString;
const altText = alt ?? "";
const copyMarkdown = markdownImageCopy(altText, srcString, authoredTitle);
const { className, style: _style, width, height, ...imageProps } = props;
Expand Down Expand Up @@ -1634,7 +1629,7 @@ const CHAT_MARKDOWN_COMPONENTS = {
/>
);
}
if (mediaKind === null && imageSource._tag === "WorkspaceFile") {
if (shouldRenderMarkdownImageAsFileLink(imageSource, mediaKind)) {
const fileLinkMeta = resolveMarkdownFileLinkMeta(srcString, cwd, imageBaseDir ?? cwd);
if (fileLinkMeta) return fileLinkChip(fileLinkMeta, copyMarkdown, srcString);
}
Expand Down
2 changes: 2 additions & 0 deletions apps/web/src/components/chat/threadFindStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,9 +10,11 @@ import {
messageSearchTokens,
} from "@t3tools/shared/paletteSearch";
import { create } from "zustand";
import type { ThemeAppearance } from "~/themePalette";
import type { ThreadFindPositionReader, ThreadFindStart } from "./threadFind";

export interface ThreadFindLocalSelection {
readonly theme: ThemeAppearance;
readonly base: OrchestrationV2SearchThreadResult;
readonly baseNavigationId: number;
readonly activeIndex: number;
Expand Down
26 changes: 22 additions & 4 deletions apps/web/src/components/chat/useThreadFind.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,11 @@ import type { OrchestrationV2SearchThreadResult, ScopedThreadRef } from "@t3tool
import { scopedThreadKey } from "@t3tools/client-runtime/environment";
import { useEffect, useEffectEvent, useRef, useState } from "react";
import { orchestrationEnvironment } from "~/state/orchestration";
import { useRenderedAppearance } from "~/hooks/useTheme";
import { useThreadProjection } from "~/state/entities";
import { useEnvironmentQuery } from "~/state/query";
import { useDebouncedValue } from "~/state/queries";
import type { ThemeAppearance } from "~/themePalette";
import { type ThreadFindMatch, type ThreadFindStart, stepThreadFindIndex } from "./threadFind";
import {
CLOSED_THREAD_FIND,
Expand Down Expand Up @@ -40,6 +42,11 @@ export function useThreadFind({
const isOpen = useThreadFindOpen(thread, enabled);
const stored = useThreadFindStore();
const state = isOpen ? stored : CLOSED_THREAD_FIND;
const theme = useRenderedAppearance();
const requestId =
state.localSelection && state.localSelection.theme !== theme
? state.navigationId
: state.requestId;
const setState = (update: (previous: ThreadFindState) => Partial<ThreadFindState>) =>
useThreadFindStore.setState((previous) =>
previous.threadKey === threadKey ? update(previous) : previous,
Expand All @@ -49,10 +56,11 @@ export function useThreadFind({
isOpen ? thread : null,
state.query,
state.offset,
state.requestId,
requestId,
state.start,
skills,
progressive,
theme,
);
const status: "loading" | "error" | null = remote.error
? "error"
Expand All @@ -63,6 +71,7 @@ export function useThreadFind({
state.localSelection,
remote.data,
remote.navigationId,
theme,
);
const count = remote.data?.totalMatches ?? 0;
const activeIndex = localSelection?.activeIndex ?? remote.data?.activeIndex ?? 0;
Expand Down Expand Up @@ -95,7 +104,12 @@ export function useThreadFind({
const step = (delta: number) => {
if (count === 0 || counting) return;
setState((previous) => {
const local = rebaseLocalSelection(previous.localSelection, remote.data, remote.navigationId);
const local = rebaseLocalSelection(
previous.localSelection,
remote.data,
remote.navigationId,
theme,
);
const pending = previous.navigationId !== (local?.navigationId ?? remote.navigationId);
const selected = local?.match ?? remote.data?.match;
const nextIndex = stepThreadFindIndex(
Expand Down Expand Up @@ -125,6 +139,7 @@ export function useThreadFind({
...previous,
navigationId: nextNavigationId,
localSelection: {
theme,
base: remote.data,
baseNavigationId: remote.navigationId,
activeIndex: nextIndex,
Expand Down Expand Up @@ -258,8 +273,9 @@ function rebaseLocalSelection(
selection: ThreadFindLocalSelection | null,
data: OrchestrationV2SearchThreadResult | null,
navigationId: number,
theme: ThemeAppearance,
) {
if (!selection || !data) return null;
if (!selection || !data || selection.theme !== theme) return null;
if (selection.base === data && selection.baseNavigationId === navigationId) return selection;
if (navigationId >= selection.navigationId) return null;
const entry = data.navigation?.find((entry) => entry.entryId === selection.match.entryId);
Expand All @@ -276,6 +292,7 @@ function useServerResults(
start: ThreadFindStart | undefined,
skills: readonly InlineSkill[],
progressive: boolean,
theme: ThemeAppearance,
) {
const skillLabels = skills.map(({ name, displayName }) => ({ name, displayName }));
const normalizedQuery = query.trim();
Expand All @@ -289,6 +306,7 @@ function useServerResults(
input: {
threadId,
query: debouncedQuery,
theme,
...(start ? { start } : {}),
...(offset !== 0 ? { offset } : {}),
skills: skillLabels,
Expand All @@ -307,7 +325,7 @@ function useServerResults(
}
const result = useEnvironmentQuery(atom);
const key = thread
? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels])
? JSON.stringify([thread.environmentId, thread.threadId, normalizedQuery, skillLabels, theme])
: null;
const [previous, setPrevious] = useState({
key,
Expand Down
37 changes: 15 additions & 22 deletions apps/web/src/markdown-links.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,7 @@ import {
inlineCodeFilePathCandidate,
isRelativeFilePath,
normalizeMarkdownLinkDestination,
parseMarkdownFileLink,
resolveMarkdownFileLinkTarget,
resolveMarkdownFileLink,
} from "@t3tools/shared/markdownLinks";
import { parseFileUrlHref, splitFilePathPosition } from "@t3tools/shared/fileLinks";

Expand Down Expand Up @@ -76,31 +75,25 @@ export function resolveMarkdownFileLinkMeta(
cwd?: string,
baseDir: string | undefined = cwd,
): MarkdownFileLinkMeta | null {
const targetPath = resolveMarkdownFileLinkTarget(href, cwd, baseDir);
if (!targetPath) return null;
const source = href ? parseMarkdownFileLink(href) : null;
return {
...buildFileLinkMetaFromTarget(targetPath, cwd),
...(source?.endLine !== undefined ? { endLine: source.endLine } : {}),
workspaceLookupPath:
source !== null &&
!isAbsolutePath(source.path) &&
baseDir !== undefined &&
workspaceRelativeFilePath(baseDir, cwd) === "."
? source.path
: null,
};
}

function buildFileLinkMetaFromTarget(targetPath: string, cwd?: string) {
const { path, line, column } = splitFilePathPosition(targetPath);
const resolved = resolveMarkdownFileLink(href, cwd, baseDir);
if (!resolved) return null;
const {
sourcePath,
targetPath,
position: { path, ...lines },
} = resolved;
return {
filePath: path,
targetPath,
displayPath: formatWorkspaceRelativePath(targetPath, cwd),
workspaceRelativePath: workspaceRelativeFilePath(path, cwd),
basename: fileBasename(path),
...(line !== undefined ? { line } : {}),
...(column !== undefined ? { column } : {}),
...lines,
workspaceLookupPath:
!isAbsolutePath(sourcePath) &&
baseDir !== undefined &&
workspaceRelativeFilePath(baseDir, cwd) === "."
? sourcePath
: null,
};
}
Loading
Loading