This commit is contained in:
fengxiangdebaozi committed 2026-05-13 18:23:25 +08:00
commit af7e90c87a
555 files changed
+94185 -92322

No files matched your search

+96 -96
View File
@@ -1,96 +1,96 @@
import { getBackendBaseURL } from "@/core/config";
import { apiFetch } from "@/core/api";
import type { Agent, CreateAgentRequest, UpdateAgentRequest } from "./types";
const BACKEND_UNAVAILABLE_STATUSES = new Set([502, 503, 504]);
export class AgentNameCheckError extends Error {
constructor(
message: string,
public readonly reason: "backend_unreachable" | "request_failed",
) {
super(message);
this.name = "AgentNameCheckError";
}
}
export async function listAgents(): Promise<Agent[]> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents`);
if (!res.ok) throw new Error(`Failed to load agents: ${res.statusText}`);
const data = (await res.json()) as { agents: Agent[] };
return data.agents;
}
export async function getAgent(id: string): Promise<Agent> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}`);
if (!res.ok) throw new Error(`Agent '${id}' not found`);
return res.json() as Promise<Agent>;
}
export async function createAgent(request: CreateAgentRequest): Promise<Agent> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to create agent: ${res.statusText}`);
}
return res.json() as Promise<Agent>;
}
export async function updateAgent(
id: string,
request: UpdateAgentRequest,
): Promise<Agent> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to update agent: ${res.statusText}`);
}
return res.json() as Promise<Agent>;
}
export async function deleteAgent(id: string): Promise<void> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error(`Failed to delete agent: ${res.statusText}`);
}
export async function checkAgentName(
name: string,
): Promise<{ available: boolean; name: string }> {
let res: Response;
try {
res = await apiFetch(
`${getBackendBaseURL()}/api/agents/check?name=${encodeURIComponent(name)}`,
);
} catch {
throw new AgentNameCheckError(
"Could not reach the DeerFlow backend.",
"backend_unreachable",
);
}
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
if (BACKEND_UNAVAILABLE_STATUSES.has(res.status)) {
throw new AgentNameCheckError(
"Could not reach the DeerFlow backend.",
"backend_unreachable",
);
}
throw new AgentNameCheckError(
err.detail ?? `Failed to check agent name: ${res.statusText}`,
"request_failed",
);
}
return res.json() as Promise<{ available: boolean; name: string }>;
}
import { getBackendBaseURL } from "@/core/config";
import { apiFetch } from "@/core/api";
import type { Agent, CreateAgentRequest, UpdateAgentRequest } from "./types";
const BACKEND_UNAVAILABLE_STATUSES = new Set([502, 503, 504]);
export class AgentNameCheckError extends Error {
constructor(
message: string,
public readonly reason: "backend_unreachable" | "request_failed",
) {
super(message);
this.name = "AgentNameCheckError";
}
}
export async function listAgents(): Promise<Agent[]> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents`);
if (!res.ok) throw new Error(`Failed to load agents: ${res.statusText}`);
const data = (await res.json()) as { agents: Agent[] };
return data.agents;
}
export async function getAgent(id: string): Promise<Agent> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}`);
if (!res.ok) throw new Error(`Agent '${id}' not found`);
return res.json() as Promise<Agent>;
}
export async function createAgent(request: CreateAgentRequest): Promise<Agent> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to create agent: ${res.statusText}`);
}
return res.json() as Promise<Agent>;
}
export async function updateAgent(
id: string,
request: UpdateAgentRequest,
): Promise<Agent> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(request),
});
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
throw new Error(err.detail ?? `Failed to update agent: ${res.statusText}`);
}
return res.json() as Promise<Agent>;
}
export async function deleteAgent(id: string): Promise<void> {
const res = await apiFetch(`${getBackendBaseURL()}/api/agents/${id}`, {
method: "DELETE",
});
if (!res.ok) throw new Error(`Failed to delete agent: ${res.statusText}`);
}
export async function checkAgentName(
name: string,
): Promise<{ available: boolean; name: string }> {
let res: Response;
try {
res = await apiFetch(
`${getBackendBaseURL()}/api/agents/check?name=${encodeURIComponent(name)}`,
);
} catch {
throw new AgentNameCheckError(
"Could not reach the CM Assistant backend.",
"backend_unreachable",
);
}
if (!res.ok) {
const err = (await res.json().catch(() => ({}))) as { detail?: string };
if (BACKEND_UNAVAILABLE_STATUSES.has(res.status)) {
throw new AgentNameCheckError(
"Could not reach the CM Assistant backend.",
"backend_unreachable",
);
}
throw new AgentNameCheckError(
err.detail ?? `Failed to check agent name: ${res.statusText}`,
"request_failed",
);
}
return res.json() as Promise<{ available: boolean; name: string }>;
}
+64 -64
View File
@@ -1,64 +1,64 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
createAgent,
deleteAgent,
getAgent,
listAgents,
updateAgent,
} from "./api";
import type { CreateAgentRequest, UpdateAgentRequest } from "./types";
export function useAgents() {
const { data, isLoading, error } = useQuery({
queryKey: ["agents"],
queryFn: () => listAgents(),
});
return { agents: data ?? [], isLoading, error };
}
export function useAgent(id: string | null | undefined) {
const { data, isLoading, error } = useQuery({
queryKey: ["agents", id],
queryFn: () => getAgent(id!),
enabled: !!id,
});
return { agent: data ?? null, isLoading, error };
}
export function useCreateAgent() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (request: CreateAgentRequest) => createAgent(request),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["agents"] });
},
});
}
export function useUpdateAgent() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
id,
request,
}: {
id: string;
request: UpdateAgentRequest;
}) => updateAgent(id, request),
onSuccess: (_data, { id }) => {
void queryClient.invalidateQueries({ queryKey: ["agents"] });
void queryClient.invalidateQueries({ queryKey: ["agents", id] });
},
});
}
export function useDeleteAgent() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: string) => deleteAgent(id),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["agents"] });
},
});
}
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
createAgent,
deleteAgent,
getAgent,
listAgents,
updateAgent,
} from "./api";
import type { CreateAgentRequest, UpdateAgentRequest } from "./types";
export function useAgents() {
const { data, isLoading, error } = useQuery({
queryKey: ["agents"],
queryFn: () => listAgents(),
});
return { agents: data ?? [], isLoading, error };
}
export function useAgent(id: string | null | undefined) {
const { data, isLoading, error } = useQuery({
queryKey: ["agents", id],
queryFn: () => getAgent(id!),
enabled: !!id,
});
return { agent: data ?? null, isLoading, error };
}
export function useCreateAgent() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (request: CreateAgentRequest) => createAgent(request),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["agents"] });
},
});
}
export function useUpdateAgent() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
id,
request,
}: {
id: string;
request: UpdateAgentRequest;
}) => updateAgent(id, request),
onSuccess: (_data, { id }) => {
void queryClient.invalidateQueries({ queryKey: ["agents"] });
void queryClient.invalidateQueries({ queryKey: ["agents", id] });
},
});
}
export function useDeleteAgent() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (id: string) => deleteAgent(id),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["agents"] });
},
});
}
+3 -3
View File
@@ -1,3 +1,3 @@
export * from "./api";
export * from "./hooks";
export * from "./types";
export * from "./api";
export * from "./hooks";
export * from "./types";
+34 -34
View File
@@ -1,34 +1,34 @@
export interface Agent {
id: string;
name: string;
description: string;
user_id: string | null;
published: boolean;
builtin: boolean;
created_at?: string | null;
updated_at?: string | null;
soul?: string | null;
model?: string | null;
tool_groups?: string[] | null;
skills?: string[] | null;
}
export interface CreateAgentRequest {
name: string;
description?: string;
soul?: string;
published?: boolean;
skills?: string[] | null;
model?: string | null;
tool_groups?: string[] | null;
}
export interface UpdateAgentRequest {
name?: string | null;
description?: string | null;
soul?: string | null;
published?: boolean | null;
skills?: string[] | null;
model?: string | null;
tool_groups?: string[] | null;
}
export interface Agent {
id: string;
name: string;
description: string;
user_id: string | null;
published: boolean;
builtin: boolean;
created_at?: string | null;
updated_at?: string | null;
soul?: string | null;
model?: string | null;
tool_groups?: string[] | null;
skills?: string[] | null;
}
export interface CreateAgentRequest {
name: string;
description?: string;
soul?: string;
published?: boolean;
skills?: string[] | null;
model?: string | null;
tool_groups?: string[] | null;
}
export interface UpdateAgentRequest {
name?: string | null;
description?: string | null;
soul?: string | null;
published?: boolean | null;
skills?: string[] | null;
model?: string | null;
tool_groups?: string[] | null;
}
+56 -56
View File
@@ -1,56 +1,56 @@
"use client";
import { Client as LangGraphClient } from "@langchain/langgraph-sdk/client";
import { getAuthorizationHeaderValue } from "../auth";
import { getLangGraphBaseURL } from "../config";
import { sanitizeRunStreamOptions } from "./stream-mode";
function createCompatibleClient(isMock?: boolean): LangGraphClient {
const client = new LangGraphClient({
apiUrl: getLangGraphBaseURL(isMock),
onRequest(_url, init) {
const headers = new Headers(init.headers ?? {});
const authHeader = getAuthorizationHeaderValue();
if (authHeader && !headers.has("Authorization")) {
headers.set("Authorization", authHeader);
}
return {
...init,
headers,
};
},
});
const originalRunStream = client.runs.stream.bind(client.runs);
client.runs.stream = ((threadId, assistantId, payload) =>
originalRunStream(
threadId,
assistantId,
sanitizeRunStreamOptions(payload),
)) as typeof client.runs.stream;
const originalJoinStream = client.runs.joinStream.bind(client.runs);
client.runs.joinStream = ((threadId, runId, options) =>
originalJoinStream(
threadId,
runId,
sanitizeRunStreamOptions(options),
)) as typeof client.runs.joinStream;
return client;
}
const _clients = new Map<string, LangGraphClient>();
export function getAPIClient(isMock?: boolean): LangGraphClient {
const cacheKey = isMock ? "mock" : "default";
let client = _clients.get(cacheKey);
if (!client) {
client = createCompatibleClient(isMock);
_clients.set(cacheKey, client);
}
return client;
}
"use client";
import { Client as LangGraphClient } from "@langchain/langgraph-sdk/client";
import { getAuthorizationHeaderValue } from "../auth";
import { getLangGraphBaseURL } from "../config";
import { sanitizeRunStreamOptions } from "./stream-mode";
function createCompatibleClient(isMock?: boolean): LangGraphClient {
const client = new LangGraphClient({
apiUrl: getLangGraphBaseURL(isMock),
onRequest(_url, init) {
const headers = new Headers(init.headers ?? {});
const authHeader = getAuthorizationHeaderValue();
if (authHeader && !headers.has("Authorization")) {
headers.set("Authorization", authHeader);
}
return {
...init,
headers,
};
},
});
const originalRunStream = client.runs.stream.bind(client.runs);
client.runs.stream = ((threadId, assistantId, payload) =>
originalRunStream(
threadId,
assistantId,
sanitizeRunStreamOptions(payload),
)) as typeof client.runs.stream;
const originalJoinStream = client.runs.joinStream.bind(client.runs);
client.runs.joinStream = ((threadId, runId, options) =>
originalJoinStream(
threadId,
runId,
sanitizeRunStreamOptions(options),
)) as typeof client.runs.joinStream;
return client;
}
const _clients = new Map<string, LangGraphClient>();
export function getAPIClient(isMock?: boolean): LangGraphClient {
const cacheKey = isMock ? "mock" : "default";
let client = _clients.get(cacheKey);
if (!client) {
client = createCompatibleClient(isMock);
_clients.set(cacheKey, client);
}
return client;
}
+18 -18
View File
@@ -1,18 +1,18 @@
import { getAuthorizationHeaderValue } from "@/core/auth";
function withAuthHeaders(headers?: HeadersInit): Headers {
const next = new Headers(headers ?? {});
const authHeader = getAuthorizationHeaderValue();
if (authHeader && !next.has("Authorization")) {
next.set("Authorization", authHeader);
}
return next;
}
export function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
return fetch(input, {
...init,
headers: withAuthHeaders(init?.headers),
});
}
import { getAuthorizationHeaderValue } from "@/core/auth";
function withAuthHeaders(headers?: HeadersInit): Headers {
const next = new Headers(headers ?? {});
const authHeader = getAuthorizationHeaderValue();
if (authHeader && !next.has("Authorization")) {
next.set("Authorization", authHeader);
}
return next;
}
export function apiFetch(input: RequestInfo | URL, init?: RequestInit) {
return fetch(input, {
...init,
headers: withAuthHeaders(init?.headers),
});
}
+2 -2
View File
@@ -1,2 +1,2 @@
export * from "./api-client";
export * from "./fetch-client";
export * from "./api-client";
export * from "./fetch-client";
+68 -68
View File
@@ -1,68 +1,68 @@
const SUPPORTED_RUN_STREAM_MODES = new Set([
"values",
"messages",
"messages-tuple",
"updates",
"events",
"debug",
"tasks",
"checkpoints",
"custom",
] as const);
const warnedUnsupportedStreamModes = new Set<string>();
export function warnUnsupportedStreamModes(
modes: string[],
warn: (message: string) => void = console.warn,
) {
const unseenModes = modes.filter((mode) => {
if (warnedUnsupportedStreamModes.has(mode)) {
return false;
}
warnedUnsupportedStreamModes.add(mode);
return true;
});
if (unseenModes.length === 0) {
return;
}
warn(
`[deer-flow] Dropped unsupported LangGraph stream mode(s): ${unseenModes.join(", ")}`,
);
}
export function sanitizeRunStreamOptions<T>(options: T): T {
if (
typeof options !== "object" ||
options === null ||
!("streamMode" in options)
) {
return options;
}
const streamMode = options.streamMode;
if (streamMode == null) {
return options;
}
const requestedModes = Array.isArray(streamMode) ? streamMode : [streamMode];
const sanitizedModes = requestedModes.filter((mode) =>
SUPPORTED_RUN_STREAM_MODES.has(mode),
);
if (sanitizedModes.length === requestedModes.length) {
return options;
}
const droppedModes = requestedModes.filter(
(mode) => !SUPPORTED_RUN_STREAM_MODES.has(mode),
);
warnUnsupportedStreamModes(droppedModes);
return {
...options,
streamMode: Array.isArray(streamMode) ? sanitizedModes : sanitizedModes[0],
};
}
const SUPPORTED_RUN_STREAM_MODES = new Set([
"values",
"messages",
"messages-tuple",
"updates",
"events",
"debug",
"tasks",
"checkpoints",
"custom",
] as const);
const warnedUnsupportedStreamModes = new Set<string>();
export function warnUnsupportedStreamModes(
modes: string[],
warn: (message: string) => void = console.warn,
) {
const unseenModes = modes.filter((mode) => {
if (warnedUnsupportedStreamModes.has(mode)) {
return false;
}
warnedUnsupportedStreamModes.add(mode);
return true;
});
if (unseenModes.length === 0) {
return;
}
warn(
`[deer-flow] Dropped unsupported LangGraph stream mode(s): ${unseenModes.join(", ")}`,
);
}
export function sanitizeRunStreamOptions<T>(options: T): T {
if (
typeof options !== "object" ||
options === null ||
!("streamMode" in options)
) {
return options;
}
const streamMode = options.streamMode;
if (streamMode == null) {
return options;
}
const requestedModes = Array.isArray(streamMode) ? streamMode : [streamMode];
const sanitizedModes = requestedModes.filter((mode) =>
SUPPORTED_RUN_STREAM_MODES.has(mode),
);
if (sanitizedModes.length === requestedModes.length) {
return options;
}
const droppedModes = requestedModes.filter(
(mode) => !SUPPORTED_RUN_STREAM_MODES.has(mode),
);
warnUnsupportedStreamModes(droppedModes);
return {
...options,
streamMode: Array.isArray(streamMode) ? sanitizedModes : sanitizedModes[0],
};
}
+91 -91
View File
@@ -1,91 +1,91 @@
import { apiFetch } from "../api";
import { getFileName } from "../utils/files";
import { urlOfArtifact } from "./utils";
function filenameFromContentDisposition(header: string | null): string | null {
if (!header) return null;
const star = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(header);
if (star) {
const raw = star[1].replace(/["']/g, "").trim();
try {
return decodeURIComponent(raw);
} catch {
return raw;
}
}
const plain = /filename="?([^";\n]+)"?/i.exec(header);
return plain ? plain[1].trim() : null;
}
async function errorMessageFromResponse(res: Response): Promise<string> {
try {
const data: unknown = await res.json();
if (data && typeof data === "object" && "detail" in data) {
const detail = (data as { detail: unknown }).detail;
if (typeof detail === "string") return detail;
if (
detail &&
typeof detail === "object" &&
"message" in detail &&
typeof (detail as { message: unknown }).message === "string"
) {
return (detail as { message: string }).message;
}
}
} catch {
// ignore
}
return res.statusText || "Request failed";
}
export async function downloadArtifactFile({
filepath,
threadId,
isMock,
}: {
filepath: string;
threadId: string;
isMock?: boolean;
}): Promise<void> {
const url = urlOfArtifact({ filepath, threadId, isMock, download: true });
const res = await apiFetch(url);
if (!res.ok) {
throw new Error(await errorMessageFromResponse(res));
}
const cd = res.headers.get("Content-Disposition");
const filename =
filenameFromContentDisposition(cd) ?? getFileName(filepath);
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = objectUrl;
a.download = filename;
a.rel = "noopener";
document.body.appendChild(a);
a.click();
a.remove();
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 30_000);
}
export async function openArtifactInNewTab({
filepath,
threadId,
isMock,
}: {
filepath: string;
threadId: string;
isMock?: boolean;
}): Promise<void> {
const url = urlOfArtifact({ filepath, threadId, isMock, download: false });
const res = await apiFetch(url);
if (!res.ok) {
throw new Error(await errorMessageFromResponse(res));
}
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
const w = window.open(objectUrl, "_blank", "noopener,noreferrer");
if (w) w.opener = null;
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 120_000);
}
import { apiFetch } from "../api";
import { getFileName } from "../utils/files";
import { urlOfArtifact } from "./utils";
function filenameFromContentDisposition(header: string | null): string | null {
if (!header) return null;
const star = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(header);
if (star) {
const raw = star[1].replace(/["']/g, "").trim();
try {
return decodeURIComponent(raw);
} catch {
return raw;
}
}
const plain = /filename="?([^";\n]+)"?/i.exec(header);
return plain ? plain[1].trim() : null;
}
async function errorMessageFromResponse(res: Response): Promise<string> {
try {
const data: unknown = await res.json();
if (data && typeof data === "object" && "detail" in data) {
const detail = (data as { detail: unknown }).detail;
if (typeof detail === "string") return detail;
if (
detail &&
typeof detail === "object" &&
"message" in detail &&
typeof (detail as { message: unknown }).message === "string"
) {
return (detail as { message: string }).message;
}
}
} catch {
// ignore
}
return res.statusText || "Request failed";
}
export async function downloadArtifactFile({
filepath,
threadId,
isMock,
}: {
filepath: string;
threadId: string;
isMock?: boolean;
}): Promise<void> {
const url = urlOfArtifact({ filepath, threadId, isMock, download: true });
const res = await apiFetch(url);
if (!res.ok) {
throw new Error(await errorMessageFromResponse(res));
}
const cd = res.headers.get("Content-Disposition");
const filename =
filenameFromContentDisposition(cd) ?? getFileName(filepath);
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = objectUrl;
a.download = filename;
a.rel = "noopener";
document.body.appendChild(a);
a.click();
a.remove();
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 30_000);
}
export async function openArtifactInNewTab({
filepath,
threadId,
isMock,
}: {
filepath: string;
threadId: string;
isMock?: boolean;
}): Promise<void> {
const url = urlOfArtifact({ filepath, threadId, isMock, download: false });
const res = await apiFetch(url);
if (!res.ok) {
throw new Error(await errorMessageFromResponse(res));
}
const blob = await res.blob();
const objectUrl = URL.createObjectURL(blob);
const w = window.open(objectUrl, "_blank", "noopener,noreferrer");
if (w) w.opener = null;
window.setTimeout(() => URL.revokeObjectURL(objectUrl), 120_000);
}
+43 -43
View File
@@ -1,43 +1,43 @@
import { useQuery } from "@tanstack/react-query";
import { useMemo } from "react";
import { useThread } from "@/components/workspace/messages/context";
import { loadArtifactContent, loadArtifactContentFromToolCall } from "./loader";
export function useArtifactContent({
filepath,
threadId,
enabled,
}: {
filepath: string;
threadId: string;
enabled?: boolean;
}) {
const isWriteFile = useMemo(() => {
return filepath.startsWith("write-file:");
}, [filepath]);
const { thread, isMock } = useThread();
const content = useMemo(() => {
if (isWriteFile) {
return loadArtifactContentFromToolCall({ url: filepath, thread });
}
return null;
}, [filepath, isWriteFile, thread]);
const { data, isLoading, error } = useQuery({
queryKey: ["artifact", filepath, threadId, isMock],
queryFn: () => {
return loadArtifactContent({ filepath, threadId, isMock });
},
enabled,
// Cache artifact content for 5 minutes to avoid repeated fetches (especially for .skill ZIP extraction)
staleTime: 5 * 60 * 1000,
});
return {
content: isWriteFile ? content : data?.content,
url: isWriteFile ? undefined : data?.url,
isLoading,
error,
};
}
import { useQuery } from "@tanstack/react-query";
import { useMemo } from "react";
import { useThread } from "@/components/workspace/messages/context";
import { loadArtifactContent, loadArtifactContentFromToolCall } from "./loader";
export function useArtifactContent({
filepath,
threadId,
enabled,
}: {
filepath: string;
threadId: string;
enabled?: boolean;
}) {
const isWriteFile = useMemo(() => {
return filepath.startsWith("write-file:");
}, [filepath]);
const { thread, isMock } = useThread();
const content = useMemo(() => {
if (isWriteFile) {
return loadArtifactContentFromToolCall({ url: filepath, thread });
}
return null;
}, [filepath, isWriteFile, thread]);
const { data, isLoading, error } = useQuery({
queryKey: ["artifact", filepath, threadId, isMock],
queryFn: () => {
return loadArtifactContent({ filepath, threadId, isMock });
},
enabled,
// Cache artifact content for 5 minutes to avoid repeated fetches (especially for .skill ZIP extraction)
staleTime: 5 * 60 * 1000,
});
return {
content: isWriteFile ? content : data?.content,
url: isWriteFile ? undefined : data?.url,
isLoading,
error,
};
}
+2 -2
View File
@@ -1,2 +1,2 @@
export * from "./download";
export * from "./loader";
export * from "./download";
export * from "./loader";
+48 -48
View File
@@ -1,48 +1,48 @@
import type { BaseStream } from "@langchain/langgraph-sdk/react";
import { apiFetch } from "../api";
import type { AgentThreadState } from "../threads";
import { urlOfArtifact } from "./utils";
export async function loadArtifactContent({
filepath,
threadId,
isMock,
}: {
filepath: string;
threadId: string;
isMock?: boolean;
}) {
let enhancedFilepath = filepath;
if (filepath.endsWith(".skill")) {
enhancedFilepath = filepath + "/SKILL.md";
}
const url = urlOfArtifact({ filepath: enhancedFilepath, threadId, isMock });
const response = await apiFetch(url);
const text = await response.text();
return { content: text, url };
}
export function loadArtifactContentFromToolCall({
url: urlString,
thread,
}: {
url: string;
thread: BaseStream<AgentThreadState>;
}) {
const url = new URL(urlString);
const toolCallId = url.searchParams.get("tool_call_id");
const messageId = url.searchParams.get("message_id");
if (messageId && toolCallId) {
const message = thread.messages.find((message) => message.id === messageId);
if (message?.type === "ai" && message.tool_calls) {
const toolCall = message.tool_calls.find(
(toolCall) => toolCall.id === toolCallId,
);
if (toolCall) {
return toolCall.args.content;
}
}
}
}
import type { BaseStream } from "@langchain/langgraph-sdk/react";
import { apiFetch } from "../api";
import type { AgentThreadState } from "../threads";
import { urlOfArtifact } from "./utils";
export async function loadArtifactContent({
filepath,
threadId,
isMock,
}: {
filepath: string;
threadId: string;
isMock?: boolean;
}) {
let enhancedFilepath = filepath;
if (filepath.endsWith(".skill")) {
enhancedFilepath = filepath + "/SKILL.md";
}
const url = urlOfArtifact({ filepath: enhancedFilepath, threadId, isMock });
const response = await apiFetch(url);
const text = await response.text();
return { content: text, url };
}
export function loadArtifactContentFromToolCall({
url: urlString,
thread,
}: {
url: string;
thread: BaseStream<AgentThreadState>;
}) {
const url = new URL(urlString);
const toolCallId = url.searchParams.get("tool_call_id");
const messageId = url.searchParams.get("message_id");
if (messageId && toolCallId) {
const message = thread.messages.find((message) => message.id === messageId);
if (message?.type === "ai" && message.tool_calls) {
const toolCall = message.tool_calls.find(
(toolCall) => toolCall.id === toolCallId,
);
if (toolCall) {
return toolCall.args.content;
}
}
}
}
+27 -27
View File
@@ -1,27 +1,27 @@
import { getBackendBaseURL } from "../config";
import type { AgentThread } from "../threads";
export function urlOfArtifact({
filepath,
threadId,
download = false,
isMock = false,
}: {
filepath: string;
threadId: string;
download?: boolean;
isMock?: boolean;
}) {
if (isMock) {
return `${getBackendBaseURL()}/mock/api/threads/${threadId}/artifacts${filepath}${download ? "?download=true" : ""}`;
}
return `${getBackendBaseURL()}/api/threads/${threadId}/artifacts${filepath}${download ? "?download=true" : ""}`;
}
export function extractArtifactsFromThread(thread: AgentThread) {
return thread.values.artifacts ?? [];
}
export function resolveArtifactURL(absolutePath: string, threadId: string) {
return `${getBackendBaseURL()}/api/threads/${threadId}/artifacts${absolutePath}`;
}
import { getBackendBaseURL } from "../config";
import type { AgentThread } from "../threads";
export function urlOfArtifact({
filepath,
threadId,
download = false,
isMock = false,
}: {
filepath: string;
threadId: string;
download?: boolean;
isMock?: boolean;
}) {
if (isMock) {
return `${getBackendBaseURL()}/mock/api/threads/${threadId}/artifacts${filepath}${download ? "?download=true" : ""}`;
}
return `${getBackendBaseURL()}/api/threads/${threadId}/artifacts${filepath}${download ? "?download=true" : ""}`;
}
export function extractArtifactsFromThread(thread: AgentThread) {
return thread.values.artifacts ?? [];
}
export function resolveArtifactURL(absolutePath: string, threadId: string) {
return `${getBackendBaseURL()}/api/threads/${threadId}/artifacts${absolutePath}`;
}
+27 -27
View File
@@ -1,27 +1,27 @@
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import type { LoginByUsernameResponse } from "./index";
export async function loginByUsername(
username: string,
): Promise<LoginByUsernameResponse> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/v1/auth/login/username`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username }),
},
);
if (!response.ok) {
const error = await response
.json()
.catch(() => ({ detail: "Login failed." }));
throw new Error(error.detail ?? "Login failed.");
}
return response.json() as Promise<LoginByUsernameResponse>;
}
import { apiFetch } from "@/core/api/fetch-client";
import { getBackendBaseURL } from "@/core/config";
import type { LoginByUsernameResponse } from "./index";
export async function loginByUsername(
username: string,
): Promise<LoginByUsernameResponse> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/v1/auth/login/username`,
{
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ username }),
},
);
if (!response.ok) {
const error = await response
.json()
.catch(() => ({ detail: "Login failed." }));
throw new Error(error.detail ?? "Login failed.");
}
return response.json() as Promise<LoginByUsernameResponse>;
}
+63 -63
View File
@@ -1,63 +1,63 @@
export interface LoginByUsernameResponse {
access_token: string;
token_type: string;
expires_in: number;
user_id: string;
email: string;
system_role: string;
needs_setup: boolean;
created: boolean;
}
const AUTH_STORAGE_KEY = "deerflow.auth";
function isBrowser(): boolean {
return typeof window !== "undefined";
}
export function getStoredAuth(): LoginByUsernameResponse | null {
if (!isBrowser()) {
return null;
}
const raw = window.localStorage.getItem(AUTH_STORAGE_KEY);
if (!raw) {
return null;
}
try {
return JSON.parse(raw) as LoginByUsernameResponse;
} catch {
return null;
}
}
export function setStoredAuth(auth: LoginByUsernameResponse) {
if (!isBrowser()) {
return;
}
window.localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(auth));
}
export function clearStoredAuth() {
if (!isBrowser()) {
return;
}
window.localStorage.removeItem(AUTH_STORAGE_KEY);
}
export function getAccessToken(): string | undefined {
const auth = getStoredAuth();
const token = auth?.access_token?.trim();
return token ? token : undefined;
}
export function getAuthorizationHeaderValue(): string | undefined {
const auth = getStoredAuth();
const token = auth?.access_token?.trim();
if (!token) {
return undefined;
}
const rawType = auth?.token_type?.trim();
const tokenType = rawType ? rawType : "Bearer";
return `${tokenType} ${token}`;
}
export interface LoginByUsernameResponse {
access_token: string;
token_type: string;
expires_in: number;
user_id: string;
email: string;
system_role: string;
needs_setup: boolean;
created: boolean;
}
const AUTH_STORAGE_KEY = "deerflow.auth";
function isBrowser(): boolean {
return typeof window !== "undefined";
}
export function getStoredAuth(): LoginByUsernameResponse | null {
if (!isBrowser()) {
return null;
}
const raw = window.localStorage.getItem(AUTH_STORAGE_KEY);
if (!raw) {
return null;
}
try {
return JSON.parse(raw) as LoginByUsernameResponse;
} catch {
return null;
}
}
export function setStoredAuth(auth: LoginByUsernameResponse) {
if (!isBrowser()) {
return;
}
window.localStorage.setItem(AUTH_STORAGE_KEY, JSON.stringify(auth));
}
export function clearStoredAuth() {
if (!isBrowser()) {
return;
}
window.localStorage.removeItem(AUTH_STORAGE_KEY);
}
export function getAccessToken(): string | undefined {
const auth = getStoredAuth();
const token = auth?.access_token?.trim();
return token ? token : undefined;
}
export function getAuthorizationHeaderValue(): string | undefined {
const auth = getStoredAuth();
const token = auth?.access_token?.trim();
if (!token) {
return undefined;
}
const rawType = auth?.token_type?.trim();
const tokenType = rawType ? rawType : "Bearer";
return `${tokenType} ${token}`;
}
+357 -357
View File
@@ -1,357 +1,357 @@
import type { Folder, MdxFile, PageMapItem } from "nextra";
import { getPageMap } from "nextra/page-map";
import { cache } from "react";
import { getLangByLocale, type Locale } from "@/core/i18n/locale";
export const BLOG_LANGS = ["zh", "en"] as const;
const RECENT_POST_LIMIT = 5;
export type BlogLang = (typeof BLOG_LANGS)[number];
export type BlogMetadata = {
date?: string;
description?: string;
item: MdxFile;
tags: string[];
title: string;
};
type BlogMdxFile = MdxFile & {
frontMatter?: {
date?: string;
description?: string;
tags?: unknown;
title?: string;
};
title?: string;
};
export type BlogPost = {
lang: BlogLang;
languages: BlogLang[];
metadata: BlogMetadata;
slug: string[];
title: string;
};
type LocalizedBlogPost = {
lang: BlogLang;
metadata: BlogMetadata;
slug: string[];
title: string;
};
export type BlogIndexData = {
pageMap: PageMapItem[];
posts: BlogPost[];
recentPosts: BlogPost[];
tags: Array<{ name: string; count: number; posts: BlogPost[] }>;
};
function isFolder(item: PageMapItem): item is Folder {
return "children" in item && Array.isArray(item.children);
}
function isMdxFile(item: PageMapItem): item is BlogMdxFile {
return "name" in item && "route" in item && !isFolder(item);
}
function normalizeBlogRoute(route: string): string {
// Posts are sourced from locale-specific content trees but exposed
// under the single public /blog route.
return route.replace(/^\/(en|zh)\/(?:posts|blog)(?=\/|$)/, "/blog");
}
export function getBlogRoute(slug: string[]): string {
return slug.length === 0 ? "/blog" : `/blog/${slug.join("/")}`;
}
function getSlugFromRoute(route: string): string[] {
return route
.replace(/^\/blog\/?/, "")
.split("/")
.filter(Boolean);
}
function getSlugKey(slug: string[]): string {
return slug.join("/");
}
function parseTags(tags: unknown): string[] {
if (!Array.isArray(tags)) {
return [];
}
return tags.filter(
(tag): tag is string => typeof tag === "string" && tag.length > 0,
);
}
function parseDate(value: string | undefined): number {
if (!value) {
return 0;
}
const time = new Date(value).getTime();
return Number.isNaN(time) ? 0 : time;
}
function selectPreferredLanguage(
languages: BlogLang[],
preferredLang?: BlogLang,
): BlogLang | null {
if (preferredLang && languages.includes(preferredLang)) {
return preferredLang;
}
// Keep fallback order stable so merged posts resolve predictably
// when the preferred locale is unavailable.
for (const lang of BLOG_LANGS) {
if (languages.includes(lang)) {
return lang;
}
}
return null;
}
function collectLocalizedBlogPosts(
items: PageMapItem[],
lang: BlogLang,
): LocalizedBlogPost[] {
const posts: LocalizedBlogPost[] = [];
for (const item of items) {
if (isFolder(item)) {
posts.push(...collectLocalizedBlogPosts(item.children, lang));
continue;
}
if (!isMdxFile(item)) {
continue;
}
const route = normalizeBlogRoute(item.route);
const slug = getSlugFromRoute(route);
if (slug.length === 0) {
continue;
}
const title = item.frontMatter?.title ?? item.title ?? item.name;
posts.push({
lang,
metadata: {
date: item.frontMatter?.date,
description:
typeof item.frontMatter?.description === "string"
? item.frontMatter.description
: undefined,
item: {
...item,
route,
},
tags: parseTags(item.frontMatter?.tags),
title,
},
slug,
title,
});
}
return posts;
}
function mergePostsBySlug(
posts: LocalizedBlogPost[],
preferredLang?: BlogLang,
): BlogPost[] {
const postsBySlug = new Map<string, LocalizedBlogPost[]>();
for (const post of posts) {
const key = getSlugKey(post.slug);
const group = postsBySlug.get(key) ?? [];
group.push(post);
postsBySlug.set(key, group);
}
return [...postsBySlug.values()]
.flatMap((group): BlogPost[] => {
const languages = group.map((post) => post.lang);
const selectedLang = selectPreferredLanguage(languages, preferredLang);
const primary =
group.find((post) => post.lang === selectedLang) ?? group[0];
if (!primary) {
return [];
}
const mergedTags = new Set<string>();
for (const post of group) {
for (const tag of post.metadata.tags) {
mergedTags.add(tag);
}
}
return [
{
...primary,
languages,
metadata: {
...primary.metadata,
tags: [...mergedTags],
},
},
];
})
.sort((a, b) => parseDate(b.metadata.date) - parseDate(a.metadata.date));
}
function createFolder(
name: string,
route: string,
title: string,
children: PageMapItem[],
): Folder {
return {
children,
name,
route,
title,
} as Folder;
}
function createPostItem(post: BlogPost): MdxFile {
return {
...post.metadata.item,
name: post.title,
route: getBlogRoute(post.slug),
};
}
export function normalizeTagSlug(tag: string): string {
return tag.toLowerCase().replace(/\s+/g, "-");
}
export function formatTagName(tag: string): string {
return tag
.split("-")
.filter(Boolean)
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
.join(" ");
}
export function getPreferredBlogLang(locale: Locale): BlogLang | undefined {
const lang = getLangByLocale(locale);
return BLOG_LANGS.find((value) => value === lang);
}
function matchTags(tags: string[], slug: string): boolean {
for (const tag of tags) {
if (normalizeTagSlug(tag) === slug) {
return true;
}
}
return false;
}
export const getAllPosts = cache(async function getAllPosts(
preferredLang?: BlogLang,
): Promise<BlogPost[]> {
const localizedPageMaps = await Promise.all(
BLOG_LANGS.map(async (lang) => ({
items: await getPageMap(`/${lang}/posts`),
lang,
})),
);
const localizedPosts = localizedPageMaps.flatMap(({ items, lang }) =>
collectLocalizedBlogPosts(items, lang),
);
return mergePostsBySlug(localizedPosts, preferredLang);
});
export async function getBlogIndexData(
preferredLang?: BlogLang,
filters?: {
tag?: string;
},
): Promise<BlogIndexData> {
const posts = await getAllPosts(preferredLang);
const tagFilter = filters?.tag;
const filteredPosts = tagFilter
? posts.filter((post) => matchTags(post.metadata.tags, tagFilter))
: posts;
const recentPosts = posts.slice(0, RECENT_POST_LIMIT);
const postsByTag = new Map<string, BlogPost[]>();
for (const post of posts) {
for (const tag of post.metadata.tags) {
const group = postsByTag.get(tag) ?? [];
group.push(post);
postsByTag.set(tag, group);
}
}
const tags = [...postsByTag.entries()]
.sort(([left], [right]) => left.localeCompare(right))
.map(([name, tagPosts]) => ({
count: tagPosts.length,
name,
posts: [...tagPosts].sort(
(a, b) => parseDate(b.metadata.date) - parseDate(a.metadata.date),
),
}));
const pageMap: PageMapItem[] = [
{
data: {
posts: { title: "All Posts", type: "Page" },
recent_posts: { title: "Recent Posts" },
tags: { title: "Tags" },
},
},
{
name: "All Posts",
route: "/blog/posts",
title: "All Posts",
frontMatter: {
title: "All Posts",
filePath: "blog/index.mdx",
},
} as MdxFile,
createFolder(
"recent_posts",
"/blog/recent-posts",
"Recent Posts",
recentPosts.map(createPostItem),
),
];
if (tags.length > 0) {
pageMap.push(
createFolder(
"tags",
"/blog/tags",
"Tags",
tags.map((tag) => {
return {
name: tag.name,
title: `${tag.name} (${tag.count})`,
route: `/blog/tags/${normalizeTagSlug(tag.name)}`,
};
}),
),
);
}
return {
pageMap,
posts: filteredPosts,
recentPosts,
tags,
};
}
import type { Folder, MdxFile, PageMapItem } from "nextra";
import { getPageMap } from "nextra/page-map";
import { cache } from "react";
import { getLangByLocale, type Locale } from "@/core/i18n/locale";
export const BLOG_LANGS = ["zh", "en"] as const;
const RECENT_POST_LIMIT = 5;
export type BlogLang = (typeof BLOG_LANGS)[number];
export type BlogMetadata = {
date?: string;
description?: string;
item: MdxFile;
tags: string[];
title: string;
};
type BlogMdxFile = MdxFile & {
frontMatter?: {
date?: string;
description?: string;
tags?: unknown;
title?: string;
};
title?: string;
};
export type BlogPost = {
lang: BlogLang;
languages: BlogLang[];
metadata: BlogMetadata;
slug: string[];
title: string;
};
type LocalizedBlogPost = {
lang: BlogLang;
metadata: BlogMetadata;
slug: string[];
title: string;
};
export type BlogIndexData = {
pageMap: PageMapItem[];
posts: BlogPost[];
recentPosts: BlogPost[];
tags: Array<{ name: string; count: number; posts: BlogPost[] }>;
};
function isFolder(item: PageMapItem): item is Folder {
return "children" in item && Array.isArray(item.children);
}
function isMdxFile(item: PageMapItem): item is BlogMdxFile {
return "name" in item && "route" in item && !isFolder(item);
}
function normalizeBlogRoute(route: string): string {
// Posts are sourced from locale-specific content trees but exposed
// under the single public /blog route.
return route.replace(/^\/(en|zh)\/(?:posts|blog)(?=\/|$)/, "/blog");
}
export function getBlogRoute(slug: string[]): string {
return slug.length === 0 ? "/blog" : `/blog/${slug.join("/")}`;
}
function getSlugFromRoute(route: string): string[] {
return route
.replace(/^\/blog\/?/, "")
.split("/")
.filter(Boolean);
}
function getSlugKey(slug: string[]): string {
return slug.join("/");
}
function parseTags(tags: unknown): string[] {
if (!Array.isArray(tags)) {
return [];
}
return tags.filter(
(tag): tag is string => typeof tag === "string" && tag.length > 0,
);
}
function parseDate(value: string | undefined): number {
if (!value) {
return 0;
}
const time = new Date(value).getTime();
return Number.isNaN(time) ? 0 : time;
}
function selectPreferredLanguage(
languages: BlogLang[],
preferredLang?: BlogLang,
): BlogLang | null {
if (preferredLang && languages.includes(preferredLang)) {
return preferredLang;
}
// Keep fallback order stable so merged posts resolve predictably
// when the preferred locale is unavailable.
for (const lang of BLOG_LANGS) {
if (languages.includes(lang)) {
return lang;
}
}
return null;
}
function collectLocalizedBlogPosts(
items: PageMapItem[],
lang: BlogLang,
): LocalizedBlogPost[] {
const posts: LocalizedBlogPost[] = [];
for (const item of items) {
if (isFolder(item)) {
posts.push(...collectLocalizedBlogPosts(item.children, lang));
continue;
}
if (!isMdxFile(item)) {
continue;
}
const route = normalizeBlogRoute(item.route);
const slug = getSlugFromRoute(route);
if (slug.length === 0) {
continue;
}
const title = item.frontMatter?.title ?? item.title ?? item.name;
posts.push({
lang,
metadata: {
date: item.frontMatter?.date,
description:
typeof item.frontMatter?.description === "string"
? item.frontMatter.description
: undefined,
item: {
...item,
route,
},
tags: parseTags(item.frontMatter?.tags),
title,
},
slug,
title,
});
}
return posts;
}
function mergePostsBySlug(
posts: LocalizedBlogPost[],
preferredLang?: BlogLang,
): BlogPost[] {
const postsBySlug = new Map<string, LocalizedBlogPost[]>();
for (const post of posts) {
const key = getSlugKey(post.slug);
const group = postsBySlug.get(key) ?? [];
group.push(post);
postsBySlug.set(key, group);
}
return [...postsBySlug.values()]
.flatMap((group): BlogPost[] => {
const languages = group.map((post) => post.lang);
const selectedLang = selectPreferredLanguage(languages, preferredLang);
const primary =
group.find((post) => post.lang === selectedLang) ?? group[0];
if (!primary) {
return [];
}
const mergedTags = new Set<string>();
for (const post of group) {
for (const tag of post.metadata.tags) {
mergedTags.add(tag);
}
}
return [
{
...primary,
languages,
metadata: {
...primary.metadata,
tags: [...mergedTags],
},
},
];
})
.sort((a, b) => parseDate(b.metadata.date) - parseDate(a.metadata.date));
}
function createFolder(
name: string,
route: string,
title: string,
children: PageMapItem[],
): Folder {
return {
children,
name,
route,
title,
} as Folder;
}
function createPostItem(post: BlogPost): MdxFile {
return {
...post.metadata.item,
name: post.title,
route: getBlogRoute(post.slug),
};
}
export function normalizeTagSlug(tag: string): string {
return tag.toLowerCase().replace(/\s+/g, "-");
}
export function formatTagName(tag: string): string {
return tag
.split("-")
.filter(Boolean)
.map((segment) => segment.charAt(0).toUpperCase() + segment.slice(1))
.join(" ");
}
export function getPreferredBlogLang(locale: Locale): BlogLang | undefined {
const lang = getLangByLocale(locale);
return BLOG_LANGS.find((value) => value === lang);
}
function matchTags(tags: string[], slug: string): boolean {
for (const tag of tags) {
if (normalizeTagSlug(tag) === slug) {
return true;
}
}
return false;
}
export const getAllPosts = cache(async function getAllPosts(
preferredLang?: BlogLang,
): Promise<BlogPost[]> {
const localizedPageMaps = await Promise.all(
BLOG_LANGS.map(async (lang) => ({
items: await getPageMap(`/${lang}/posts`),
lang,
})),
);
const localizedPosts = localizedPageMaps.flatMap(({ items, lang }) =>
collectLocalizedBlogPosts(items, lang),
);
return mergePostsBySlug(localizedPosts, preferredLang);
});
export async function getBlogIndexData(
preferredLang?: BlogLang,
filters?: {
tag?: string;
},
): Promise<BlogIndexData> {
const posts = await getAllPosts(preferredLang);
const tagFilter = filters?.tag;
const filteredPosts = tagFilter
? posts.filter((post) => matchTags(post.metadata.tags, tagFilter))
: posts;
const recentPosts = posts.slice(0, RECENT_POST_LIMIT);
const postsByTag = new Map<string, BlogPost[]>();
for (const post of posts) {
for (const tag of post.metadata.tags) {
const group = postsByTag.get(tag) ?? [];
group.push(post);
postsByTag.set(tag, group);
}
}
const tags = [...postsByTag.entries()]
.sort(([left], [right]) => left.localeCompare(right))
.map(([name, tagPosts]) => ({
count: tagPosts.length,
name,
posts: [...tagPosts].sort(
(a, b) => parseDate(b.metadata.date) - parseDate(a.metadata.date),
),
}));
const pageMap: PageMapItem[] = [
{
data: {
posts: { title: "All Posts", type: "Page" },
recent_posts: { title: "Recent Posts" },
tags: { title: "Tags" },
},
},
{
name: "All Posts",
route: "/blog/posts",
title: "All Posts",
frontMatter: {
title: "All Posts",
filePath: "blog/index.mdx",
},
} as MdxFile,
createFolder(
"recent_posts",
"/blog/recent-posts",
"Recent Posts",
recentPosts.map(createPostItem),
),
];
if (tags.length > 0) {
pageMap.push(
createFolder(
"tags",
"/blog/tags",
"Tags",
tags.map((tag) => {
return {
name: tag.name,
title: `${tag.name} (${tag.count})`,
route: `/blog/tags/${normalizeTagSlug(tag.name)}`,
};
}),
),
);
}
return {
pageMap,
posts: filteredPosts,
recentPosts,
tags,
};
}
+40 -40
View File
@@ -1,40 +1,40 @@
import { env } from "@/env";
function getBaseOrigin() {
if (typeof window !== "undefined") {
return window.location.origin;
}
// Fallback for SSR
return "http://localhost:2026";
}
export function getBackendBaseURL() {
if (env.NEXT_PUBLIC_BACKEND_BASE_URL) {
return new URL(env.NEXT_PUBLIC_BACKEND_BASE_URL, getBaseOrigin())
.toString()
.replace(/\/+$/, "");
} else {
return "";
}
}
export function getLangGraphBaseURL(isMock?: boolean) {
if (env.NEXT_PUBLIC_LANGGRAPH_BASE_URL) {
return new URL(
env.NEXT_PUBLIC_LANGGRAPH_BASE_URL,
getBaseOrigin(),
).toString();
} else if (isMock) {
if (typeof window !== "undefined") {
return `${window.location.origin}/mock/api`;
}
return "http://localhost:3000/mock/api";
} else {
// LangGraph SDK requires a full URL, construct it from current origin
if (typeof window !== "undefined") {
return `${window.location.origin}/api/langgraph`;
}
// Fallback for SSR
return "http://localhost:2026/api/langgraph";
}
}
import { env } from "@/env";
function getBaseOrigin() {
if (typeof window !== "undefined") {
return window.location.origin;
}
// Fallback for SSR
return "http://localhost:2026";
}
export function getBackendBaseURL() {
if (env.NEXT_PUBLIC_BACKEND_BASE_URL) {
return new URL(env.NEXT_PUBLIC_BACKEND_BASE_URL, getBaseOrigin())
.toString()
.replace(/\/+$/, "");
} else {
return "";
}
}
export function getLangGraphBaseURL(isMock?: boolean) {
if (env.NEXT_PUBLIC_LANGGRAPH_BASE_URL) {
return new URL(
env.NEXT_PUBLIC_LANGGRAPH_BASE_URL,
getBaseOrigin(),
).toString();
} else if (isMock) {
if (typeof window !== "undefined") {
return `${window.location.origin}/mock/api`;
}
return "http://localhost:3000/mock/api";
} else {
// LangGraph SDK requires a full URL, construct it from current origin
if (typeof window !== "undefined") {
return `${window.location.origin}/api/langgraph`;
}
// Fallback for SSR
return "http://localhost:2026/api/langgraph";
}
}
+41 -41
View File
@@ -1,41 +1,41 @@
"use client";
import { createContext, useContext, useState, type ReactNode } from "react";
import type { Locale } from "@/core/i18n";
export interface I18nContextType {
locale: Locale;
setLocale: (locale: Locale) => void;
}
export const I18nContext = createContext<I18nContextType | null>(null);
export function I18nProvider({
children,
initialLocale,
}: {
children: ReactNode;
initialLocale: Locale;
}) {
const [locale, setLocale] = useState<Locale>(initialLocale);
const handleSetLocale = (newLocale: Locale) => {
setLocale(newLocale);
document.cookie = `locale=${newLocale}; path=/; max-age=31536000`;
};
return (
<I18nContext.Provider value={{ locale, setLocale: handleSetLocale }}>
{children}
</I18nContext.Provider>
);
}
export function useI18nContext() {
const context = useContext(I18nContext);
if (!context) {
throw new Error("useI18n must be used within I18nProvider");
}
return context;
}
"use client";
import { createContext, useContext, useState, type ReactNode } from "react";
import type { Locale } from "@/core/i18n";
export interface I18nContextType {
locale: Locale;
setLocale: (locale: Locale) => void;
}
export const I18nContext = createContext<I18nContextType | null>(null);
export function I18nProvider({
children,
initialLocale,
}: {
children: ReactNode;
initialLocale: Locale;
}) {
const [locale, setLocale] = useState<Locale>(initialLocale);
const handleSetLocale = (newLocale: Locale) => {
setLocale(newLocale);
document.cookie = `locale=${newLocale}; path=/; max-age=31536000`;
};
return (
<I18nContext.Provider value={{ locale, setLocale: handleSetLocale }}>
{children}
</I18nContext.Provider>
);
}
export function useI18nContext() {
const context = useContext(I18nContext);
if (!context) {
throw new Error("useI18n must be used within I18nProvider");
}
return context;
}
+41 -41
View File
@@ -1,41 +1,41 @@
/**
* Cookie utilities for locale management
* Works on both client and server side
*/
const LOCALE_COOKIE_NAME = "locale";
/**
* Get locale from cookie (client-side)
*/
export function getLocaleFromCookie(): string | null {
if (typeof document === "undefined") {
return null;
}
const cookies = document.cookie.split(";");
for (const cookie of cookies) {
const [name, value] = cookie.trim().split("=");
if (name === LOCALE_COOKIE_NAME) {
return decodeURIComponent(value ?? "");
}
}
return null;
}
/**
* Set locale in cookie (client-side)
*/
export function setLocaleInCookie(locale: string): void {
if (typeof document === "undefined") {
return;
}
// Set cookie with 1 year expiration
const maxAge = 365 * 24 * 60 * 60; // 1 year in seconds
document.cookie = `${LOCALE_COOKIE_NAME}=${encodeURIComponent(locale)}; max-age=${maxAge}; path=/; SameSite=Lax`;
}
export async function getLocaleFromCookieServer(): Promise<string | null> {
return getLocaleFromCookie();
}
/**
* Cookie utilities for locale management
* Works on both client and server side
*/
const LOCALE_COOKIE_NAME = "locale";
/**
* Get locale from cookie (client-side)
*/
export function getLocaleFromCookie(): string | null {
if (typeof document === "undefined") {
return null;
}
const cookies = document.cookie.split(";");
for (const cookie of cookies) {
const [name, value] = cookie.trim().split("=");
if (name === LOCALE_COOKIE_NAME) {
return decodeURIComponent(value ?? "");
}
}
return null;
}
/**
* Set locale in cookie (client-side)
*/
export function setLocaleInCookie(locale: string): void {
if (typeof document === "undefined") {
return;
}
// Set cookie with 1 year expiration
const maxAge = 365 * 24 * 60 * 60; // 1 year in seconds
document.cookie = `${LOCALE_COOKIE_NAME}=${encodeURIComponent(locale)}; max-age=${maxAge}; path=/; SameSite=Lax`;
}
export async function getLocaleFromCookieServer(): Promise<string | null> {
return getLocaleFromCookie();
}
+48 -48
View File
@@ -1,48 +1,48 @@
"use client";
import { useEffect } from "react";
import { useI18nContext } from "./context";
import { getLocaleFromCookie, setLocaleInCookie } from "./cookies";
import { translations } from "./translations";
import {
DEFAULT_LOCALE,
detectLocale,
normalizeLocale,
type Locale,
} from "./index";
export function useI18n() {
const { locale, setLocale } = useI18nContext();
const t = translations[locale] ?? translations[DEFAULT_LOCALE];
const changeLocale = (newLocale: Locale) => {
setLocale(newLocale);
setLocaleInCookie(newLocale);
};
// Initialize locale on mount
useEffect(() => {
const saved = getLocaleFromCookie();
if (saved) {
const normalizedSaved = normalizeLocale(saved);
setLocale(normalizedSaved);
if (saved !== normalizedSaved) {
setLocaleInCookie(normalizedSaved);
}
return;
}
const detected = detectLocale();
setLocale(detected);
setLocaleInCookie(detected);
}, [setLocale]);
return {
locale,
t,
changeLocale,
};
}
"use client";
import { useEffect } from "react";
import { useI18nContext } from "./context";
import { getLocaleFromCookie, setLocaleInCookie } from "./cookies";
import { translations } from "./translations";
import {
DEFAULT_LOCALE,
detectLocale,
normalizeLocale,
type Locale,
} from "./index";
export function useI18n() {
const { locale, setLocale } = useI18nContext();
const t = translations[locale] ?? translations[DEFAULT_LOCALE];
const changeLocale = (newLocale: Locale) => {
setLocale(newLocale);
setLocaleInCookie(newLocale);
};
// Initialize locale on mount
useEffect(() => {
const saved = getLocaleFromCookie();
if (saved) {
const normalizedSaved = normalizeLocale(saved);
setLocale(normalizedSaved);
if (saved !== normalizedSaved) {
setLocaleInCookie(normalizedSaved);
}
return;
}
const detected = detectLocale();
setLocale(detected);
setLocaleInCookie(detected);
}, [setLocale]);
return {
locale,
t,
changeLocale,
};
}
+11 -11
View File
@@ -1,11 +1,11 @@
export { enUS } from "./locales/en-US";
export { zhCN } from "./locales/zh-CN";
export type { Translations } from "./locales/types";
export {
DEFAULT_LOCALE,
SUPPORTED_LOCALES,
detectLocale,
isLocale,
normalizeLocale,
} from "./locale";
export type { Locale } from "./locale";
export { enUS } from "./locales/en-US";
export { zhCN } from "./locales/zh-CN";
export type { Translations } from "./locales/types";
export {
DEFAULT_LOCALE,
SUPPORTED_LOCALES,
detectLocale,
isLocale,
normalizeLocale,
} from "./locale";
export type { Locale } from "./locale";
+54 -54
View File
@@ -1,54 +1,54 @@
export const SUPPORTED_LOCALES = ["en-US", "zh-CN"] as const;
export type Locale = (typeof SUPPORTED_LOCALES)[number];
export const DEFAULT_LOCALE: Locale = "en-US";
export function isLocale(value: string): value is Locale {
return (SUPPORTED_LOCALES as readonly string[]).includes(value);
}
export function getLocaleByLang(lang: string): Locale {
const normalizedLang = lang.toLowerCase();
for (const locale of SUPPORTED_LOCALES) {
if (locale.startsWith(normalizedLang)) {
return locale;
}
}
return DEFAULT_LOCALE;
}
export function getLangByLocale(locale: Locale): string {
const parts = locale.split("-");
if (parts.length > 0 && typeof parts[0] === "string") {
return parts[0];
}
return locale;
}
export function normalizeLocale(locale: string | null | undefined): Locale {
if (!locale) {
return DEFAULT_LOCALE;
}
if (isLocale(locale)) {
return locale;
}
if (locale.toLowerCase().startsWith("zh")) {
return "zh-CN";
}
return DEFAULT_LOCALE;
}
// Helper function to detect browser locale
export function detectLocale(): Locale {
if (typeof window === "undefined") {
return DEFAULT_LOCALE;
}
const browserLang =
navigator.language ||
(navigator as unknown as { userLanguage: string }).userLanguage;
return normalizeLocale(browserLang);
}
export const SUPPORTED_LOCALES = ["en-US", "zh-CN"] as const;
export type Locale = (typeof SUPPORTED_LOCALES)[number];
export const DEFAULT_LOCALE: Locale = "en-US";
export function isLocale(value: string): value is Locale {
return (SUPPORTED_LOCALES as readonly string[]).includes(value);
}
export function getLocaleByLang(lang: string): Locale {
const normalizedLang = lang.toLowerCase();
for (const locale of SUPPORTED_LOCALES) {
if (locale.startsWith(normalizedLang)) {
return locale;
}
}
return DEFAULT_LOCALE;
}
export function getLangByLocale(locale: Locale): string {
const parts = locale.split("-");
if (parts.length > 0 && typeof parts[0] === "string") {
return parts[0];
}
return locale;
}
export function normalizeLocale(locale: string | null | undefined): Locale {
if (!locale) {
return DEFAULT_LOCALE;
}
if (isLocale(locale)) {
return locale;
}
if (locale.toLowerCase().startsWith("zh")) {
return "zh-CN";
}
return DEFAULT_LOCALE;
}
// Helper function to detect browser locale
export function detectLocale(): Locale {
if (typeof window === "undefined") {
return DEFAULT_LOCALE;
}
const browserLang =
navigator.language ||
(navigator as unknown as { userLanguage: string }).userLanguage;
return normalizeLocale(browserLang);
}
+482 -459
View File
@@ -1,459 +1,482 @@
import {
CompassIcon,
GraduationCapIcon,
ImageIcon,
MicroscopeIcon,
PenLineIcon,
ShapesIcon,
SparklesIcon,
VideoIcon,
} from "lucide-react";
import type { Translations } from "./types";
export const enUS: Translations = {
// Locale meta
locale: {
localName: "English",
},
// Common
common: {
home: "Home",
settings: "Settings",
delete: "Delete",
edit: "Edit",
rename: "Rename",
share: "Share",
openInNewWindow: "Open in new window",
close: "Close",
more: "More",
search: "Search",
download: "Download",
thinking: "Thinking",
artifacts: "Artifacts",
public: "Public",
custom: "Custom",
notAvailableInDemoMode: "Not available in demo mode",
loading: "Loading...",
version: "Version",
lastUpdated: "Last updated",
code: "Code",
preview: "Preview",
cancel: "Cancel",
save: "Save",
install: "Install",
create: "Create",
import: "Import",
export: "Export",
exportAsMarkdown: "Export as Markdown",
exportAsJSON: "Export as JSON",
exportSuccess: "Conversation exported",
},
// Home
home: {
docs: "Docs",
blog: "Blog",
},
// Welcome
welcome: {
greeting: "Hello, again!",
description:
"Welcome to 🦌 DeerFlow, an open source super agent. With built-in and custom skills, DeerFlow helps you search on the web, analyze data, and generate artifacts like slides, web pages and do almost anything.",
createYourOwnSkill: "Create Your Own Skill",
createYourOwnSkillDescription:
"Create your own skill to release the power of DeerFlow. With customized skills,\nDeerFlow can help you search on the web, analyze data, and generate\n artifacts like slides, web pages and do almost anything.",
},
// Clipboard
clipboard: {
copyToClipboard: "Copy to clipboard",
copiedToClipboard: "Copied to clipboard",
failedToCopyToClipboard: "Failed to copy to clipboard",
linkCopied: "Link copied to clipboard",
},
// Input Box
inputBox: {
placeholder: "How can I assist you today?",
createSkillPrompt:
"We're going to build a new skill step by step with `skill-creator`. To start, what do you want this skill to do?",
addAttachments: "Add attachments",
mode: "Mode",
flashMode: "Flash",
flashModeDescription: "Fast and efficient, but may not be accurate",
reasoningMode: "Reasoning",
reasoningModeDescription:
"Reasoning before action, balance between time and accuracy",
proMode: "Pro",
proModeDescription:
"Reasoning, planning and executing, get more accurate results, may take more time",
ultraMode: "Ultra",
ultraModeDescription:
"Pro mode with subagents to divide work; best for complex multi-step tasks",
reasoningEffort: "Reasoning Effort",
reasoningEffortMinimal: "Minimal",
reasoningEffortMinimalDescription: "Retrieval + Direct Output",
reasoningEffortLow: "Low",
reasoningEffortLowDescription: "Simple Logic Check + Shallow Deduction",
reasoningEffortMedium: "Medium",
reasoningEffortMediumDescription:
"Multi-layer Logic Analysis + Basic Verification",
reasoningEffortHigh: "High",
reasoningEffortHighDescription:
"Full-dimensional Logic Deduction + Multi-path Verification + Backward Check",
searchModels: "Search models...",
surpriseMe: "Surprise",
surpriseMePrompt: "Surprise me",
followupLoading: "Generating follow-up questions...",
followupConfirmTitle: "Send suggestion?",
followupConfirmDescription:
"You already have text in the input. Choose how to send it.",
followupConfirmAppend: "Append & send",
followupConfirmReplace: "Replace & send",
suggestions: [
{
suggestion: "Write",
prompt: "Write a blog post about the latest trends on [topic]",
icon: PenLineIcon,
},
{
suggestion: "Research",
prompt:
"Conduct a deep dive research on [topic], and summarize the findings.",
icon: MicroscopeIcon,
},
{
suggestion: "Collect",
prompt: "Collect data from [source] and create a report.",
icon: ShapesIcon,
},
{
suggestion: "Learn",
prompt: "Learn about [topic] and create a tutorial.",
icon: GraduationCapIcon,
},
],
suggestionsCreate: [
{
suggestion: "Webpage",
prompt: "Create a webpage about [topic]",
icon: CompassIcon,
},
{
suggestion: "Image",
prompt: "Create an image about [topic]",
icon: ImageIcon,
},
{
suggestion: "Video",
prompt: "Create a video about [topic]",
icon: VideoIcon,
},
{
type: "separator",
},
{
suggestion: "Skill",
prompt:
"We're going to build a new skill step by step with `skill-creator`. To start, what do you want this skill to do?",
icon: SparklesIcon,
},
],
},
// Sidebar
sidebar: {
newChat: "New chat",
chats: "Chats",
recentChats: "Recent chats",
demoChats: "Demo chats",
agents: "Agents",
},
// Agents
agents: {
title: "Agents",
description:
"Create and manage custom agents with specialized prompts and capabilities.",
newAgent: "New Agent",
emptyTitle: "No custom agents yet",
emptyDescription:
"Create your first custom agent with a specialized system prompt.",
chat: "Chat",
delete: "Delete",
deleteConfirm:
"Are you sure you want to delete this agent? This action cannot be undone.",
deleteSuccess: "Agent deleted",
newChat: "New chat",
createPageTitle: "Design your Agent",
createPageSubtitle:
"Describe the agent you want — I'll help you create it through conversation.",
nameStepTitle: "Name your new Agent",
nameStepHint:
"Letters, digits, and hyphens only — stored lowercase (e.g. code-reviewer)",
nameStepPlaceholder: "e.g. code-reviewer",
nameStepContinue: "Continue",
nameStepInvalidError:
"Invalid name — use only letters, digits, and hyphens",
nameStepAlreadyExistsError: "An agent with this name already exists",
nameStepNetworkError:
"Network request failed — check your network or backend connection",
nameStepCheckError: "Could not verify name availability — please try again",
nameStepBootstrapMessage:
"The new custom agent name is {name}. Let's bootstrap it's **SOUL**.",
save: "Save agent",
saving: "Saving agent...",
saveRequested:
"Save requested. DeerFlow is generating and saving an initial version now.",
saveHint:
"You can save this agent at any time from the top-right menu, even if this is only a first draft.",
saveCommandMessage:
"Please save this custom agent now based on everything we have discussed so far. Treat this as my explicit confirmation to save. If some details are still missing, make reasonable assumptions, generate a concise first SOUL.md in English, and call setup_agent immediately without asking me for more confirmation.",
agentCreatedPendingRefresh:
"The agent was created, but DeerFlow could not load it yet. Please refresh this page in a moment.",
more: "More actions",
agentCreated: "Agent created!",
startChatting: "Start chatting",
backToGallery: "Back to Gallery",
},
// Breadcrumb
breadcrumb: {
workspace: "Workspace",
chats: "Chats",
},
// Workspace
workspace: {
officialWebsite: "DeerFlow's official website",
githubTooltip: "DeerFlow on Github",
settingsAndMore: "Settings and more",
visitGithub: "DeerFlow on GitHub",
reportIssue: "Report a issue",
contactUs: "Contact us",
about: "About DeerFlow",
},
// Conversation
conversation: {
noMessages: "No messages yet",
startConversation: "Start a conversation to see messages here",
},
// Chats
chats: {
searchChats: "Search chats",
},
// Page titles (document title)
pages: {
appName: "DeerFlow",
brandSubtitle: "Smart CM Platform",
chats: "Chats",
newChat: "New chat",
untitled: "Untitled",
},
// Tool calls
toolCalls: {
moreSteps: (count: number) => `${count} more step${count === 1 ? "" : "s"}`,
lessSteps: "Less steps",
executeCommand: "Execute command",
presentFiles: "Present files",
needYourHelp: "Need your help",
useTool: (toolName: string) => `Use "${toolName}" tool`,
searchFor: (query: string) => `Search for "${query}"`,
searchForRelatedInfo: "Search for related information",
searchForRelatedImages: "Search for related images",
searchForRelatedImagesFor: (query: string) =>
`Search for related images for "${query}"`,
searchOnWebFor: (query: string) => `Search on the web for "${query}"`,
viewWebPage: "View web page",
listFolder: "List folder",
readFile: "Read file",
writeFile: "Write file",
clickToViewContent: "Click to view file content",
writeTodos: "Update to-do list",
skillInstallTooltip: "Install skill and make it available to DeerFlow",
},
// Subtasks
uploads: {
uploading: "Uploading...",
uploadingFiles: "Uploading files, please wait...",
},
subtasks: {
subtask: "Subtask",
executing: (count: number) =>
`Executing ${count === 1 ? "" : count + " "}subtask${count === 1 ? "" : "s in parallel"}`,
in_progress: "Running subtask",
completed: "Subtask completed",
failed: "Subtask failed",
},
// Token Usage
tokenUsage: {
title: "Token Usage",
label: "Tokens",
input: "Input",
output: "Output",
total: "Total",
unavailable:
"No token usage yet. Usage appears only after a successful model response when the provider returns usage_metadata.",
unavailableShort: "No usage returned",
},
// Shortcuts
shortcuts: {
searchActions: "Search actions...",
noResults: "No results found.",
actions: "Actions",
keyboardShortcuts: "Keyboard Shortcuts",
keyboardShortcutsDescription:
"Navigate DeerFlow faster with keyboard shortcuts.",
openCommandPalette: "Open Command Palette",
toggleSidebar: "Toggle Sidebar",
},
// Settings
settings: {
title: "Settings",
description: "Adjust how DeerFlow looks and behaves for you.",
sections: {
appearance: "Appearance",
memory: "Memory",
tools: "Tools",
skills: "Skills",
notification: "Notification",
about: "About",
},
memory: {
title: "Memory",
description:
"DeerFlow automatically learns from your conversations in the background. These memories help DeerFlow understand you better and deliver a more personalized experience.",
empty: "No memory data to display.",
rawJson: "Raw JSON",
exportButton: "Export memory",
exportSuccess: "Memory exported",
importButton: "Import memory",
importConfirmTitle: "Import memory?",
importConfirmDescription:
"This will overwrite your current memory with the selected JSON backup.",
importFileLabel: "Selected file",
importInvalidFile:
"Failed to read the selected memory file. Please choose a valid JSON export.",
importSuccess: "Memory imported",
manualFactSource: "Manual",
addFact: "Add fact",
addFactTitle: "Add memory fact",
editFactTitle: "Edit memory fact",
addFactSuccess: "Fact created",
editFactSuccess: "Fact updated",
clearAll: "Clear all memory",
clearAllConfirmTitle: "Clear all memory?",
clearAllConfirmDescription:
"This will remove all saved summaries and facts. This action cannot be undone.",
clearAllSuccess: "All memory cleared",
factDeleteConfirmTitle: "Delete this fact?",
factDeleteConfirmDescription:
"This fact will be removed from memory immediately. This action cannot be undone.",
factDeleteSuccess: "Fact deleted",
factContentLabel: "Content",
factCategoryLabel: "Category",
factConfidenceLabel: "Confidence",
factContentPlaceholder: "Describe the memory fact you want to save",
factCategoryPlaceholder: "context",
factConfidenceHint: "Use a number between 0 and 1.",
factSave: "Save fact",
factValidationContent: "Fact content cannot be empty.",
factValidationConfidence: "Confidence must be a number between 0 and 1.",
noFacts: "No saved facts yet.",
summaryReadOnly:
"Summary sections are read-only for now. You can currently add, edit, or delete individual facts, or clear all memory.",
memoryFullyEmpty: "No memory saved yet.",
factPreviewLabel: "Fact to delete",
searchPlaceholder: "Search memory",
filterAll: "All",
filterFacts: "Facts",
filterSummaries: "Summaries",
noMatches: "No matching memory found.",
markdown: {
overview: "Overview",
userContext: "User context",
work: "Work",
personal: "Personal",
topOfMind: "Top of mind",
historyBackground: "History",
recentMonths: "Recent months",
earlierContext: "Earlier context",
longTermBackground: "Long-term background",
updatedAt: "Updated at",
facts: "Facts",
empty: "(empty)",
table: {
category: "Category",
confidence: "Confidence",
confidenceLevel: {
veryHigh: "Very high",
high: "High",
normal: "Normal",
unknown: "Unknown",
},
content: "Content",
source: "Source",
createdAt: "CreatedAt",
view: "View",
},
},
},
appearance: {
themeTitle: "Theme",
themeDescription:
"Choose how the interface follows your device or stays fixed.",
system: "System",
light: "Light",
dark: "Dark",
systemDescription: "Match the operating system preference automatically.",
lightDescription: "Bright palette with higher contrast for daytime.",
darkDescription: "Dim palette that reduces glare for focus.",
languageTitle: "Language",
languageDescription: "Switch between languages.",
},
tools: {
title: "Tools",
description: "Manage the configuration and enabled status of MCP tools.",
},
skills: {
title: "Agent Skills",
description:
"Manage the configuration and enabled status of the agent skills.",
createSkill: "Create skill",
emptyTitle: "No agent skill yet",
emptyDescription:
"Put your agent skill folders under the `/skills/custom` folder under the root folder of DeerFlow.",
emptyButton: "Create Your First Skill",
},
notification: {
title: "Notification",
description:
"DeerFlow only sends a completion notification when the window is not active. This is especially useful for long-running tasks so you can switch to other work and get notified when done.",
requestPermission: "Request notification permission",
deniedHint:
"Notification permission was denied. You can enable it in your browser's site settings to receive completion alerts.",
testButton: "Send test notification",
testTitle: "DeerFlow",
testBody: "This is a test notification.",
notSupported: "Your browser does not support notifications.",
disableNotification: "Disable notification",
},
acknowledge: {
emptyTitle: "Acknowledgements",
emptyDescription: "Credits and acknowledgements will show here.",
},
},
};
import {
CompassIcon,
GraduationCapIcon,
ImageIcon,
MicroscopeIcon,
PenLineIcon,
ShapesIcon,
SparklesIcon,
VideoIcon,
} from "lucide-react";
import type { Translations } from "./types";
export const enUS: Translations = {
// Locale meta
locale: {
localName: "English",
},
// Common
common: {
home: "Home",
settings: "Settings",
delete: "Delete",
edit: "Edit",
rename: "Rename",
share: "Share",
openInNewWindow: "Open in new window",
close: "Close",
more: "More",
search: "Search",
download: "Download",
thinking: "Thinking",
artifacts: "Artifacts",
public: "Public",
custom: "Custom",
notAvailableInDemoMode: "Not available in demo mode",
loading: "Loading...",
version: "Version",
lastUpdated: "Last updated",
code: "Code",
preview: "Preview",
cancel: "Cancel",
save: "Save",
install: "Install",
create: "Create",
import: "Import",
export: "Export",
exportAsMarkdown: "Export as Markdown",
exportAsJSON: "Export as JSON",
exportSuccess: "Conversation exported",
},
// Home
home: {
docs: "Docs",
blog: "Blog",
},
// Welcome
welcome: {
greeting: "Hello, again!",
description:
"Welcome to CM Assistant. With built-in and custom skills, CM Assistant helps you search on the web, analyze data, and generate artifacts like slides, web pages and do almost anything.",
createYourOwnSkill: "Create Your Own Skill",
createYourOwnSkillDescription:
"Create your own skill to release the power of CM Assistant. With customized skills,\nCM Assistant can help you search on the web, analyze data, and generate\n artifacts like slides, web pages and do almost anything.",
},
// Clipboard
clipboard: {
copyToClipboard: "Copy to clipboard",
copiedToClipboard: "Copied to clipboard",
failedToCopyToClipboard: "Failed to copy to clipboard",
linkCopied: "Link copied to clipboard",
},
// Input Box
inputBox: {
placeholder: "How can I assist you today?",
createSkillPrompt:
"We're going to build a new skill step by step with `skill-creator`. To start, what do you want this skill to do?",
addAttachments: "Add attachments",
mode: "Mode",
flashMode: "Flash",
flashModeDescription: "Fast and efficient, but may not be accurate",
reasoningMode: "Reasoning",
reasoningModeDescription:
"Reasoning before action, balance between time and accuracy",
proMode: "Pro",
proModeDescription:
"Reasoning, planning and executing, get more accurate results, may take more time",
ultraMode: "Ultra",
ultraModeDescription:
"Pro mode with subagents to divide work; best for complex multi-step tasks",
reasoningEffort: "Reasoning Effort",
reasoningEffortMinimal: "Minimal",
reasoningEffortMinimalDescription: "Retrieval + Direct Output",
reasoningEffortLow: "Low",
reasoningEffortLowDescription: "Simple Logic Check + Shallow Deduction",
reasoningEffortMedium: "Medium",
reasoningEffortMediumDescription:
"Multi-layer Logic Analysis + Basic Verification",
reasoningEffortHigh: "High",
reasoningEffortHighDescription:
"Full-dimensional Logic Deduction + Multi-path Verification + Backward Check",
searchModels: "Search models...",
surpriseMe: "Surprise",
surpriseMePrompt: "Surprise me",
followupLoading: "Generating follow-up questions...",
followupConfirmTitle: "Send suggestion?",
followupConfirmDescription:
"You already have text in the input. Choose how to send it.",
followupConfirmAppend: "Append & send",
followupConfirmReplace: "Replace & send",
suggestions: [
{
suggestion: "Write",
prompt: "Write a blog post about the latest trends on [topic]",
icon: PenLineIcon,
},
{
suggestion: "Research",
prompt:
"Conduct a deep dive research on [topic], and summarize the findings.",
icon: MicroscopeIcon,
},
{
suggestion: "Collect",
prompt: "Collect data from [source] and create a report.",
icon: ShapesIcon,
},
{
suggestion: "Learn",
prompt: "Learn about [topic] and create a tutorial.",
icon: GraduationCapIcon,
},
],
suggestionsCreate: [
{
suggestion: "Webpage",
prompt: "Create a webpage about [topic]",
icon: CompassIcon,
},
{
suggestion: "Image",
prompt: "Create an image about [topic]",
icon: ImageIcon,
},
{
suggestion: "Video",
prompt: "Create a video about [topic]",
icon: VideoIcon,
},
{
type: "separator",
},
{
suggestion: "Skill",
prompt:
"We're going to build a new skill step by step with `skill-creator`. To start, what do you want this skill to do?",
icon: SparklesIcon,
},
],
},
// Sidebar
sidebar: {
newChat: "New chat",
chats: "Chats",
recentChats: "Recent chats",
demoChats: "Demo chats",
agents: "Agents",
},
// Agents
agents: {
title: "Agents",
description:
"Create and manage custom agents with specialized prompts and capabilities.",
newAgent: "New Agent",
emptyTitle: "No custom agents yet",
emptyDescription:
"Create your first custom agent with a specialized system prompt.",
chat: "Chat",
delete: "Delete",
deleteConfirm:
"Are you sure you want to delete this agent? This action cannot be undone.",
deleteSuccess: "Agent deleted",
newChat: "New chat",
createPageTitle: "Design your Agent",
createPageSubtitle:
"Describe the agent you want — I'll help you create it through conversation.",
nameStepTitle: "Name your new Agent",
nameStepHint:
"Letters, digits, and hyphens only — stored lowercase (e.g. code-reviewer)",
nameStepPlaceholder: "e.g. code-reviewer",
nameStepContinue: "Continue",
nameStepInvalidError:
"Invalid name — use only letters, digits, and hyphens",
nameStepAlreadyExistsError: "An agent with this name already exists",
nameStepNetworkError:
"Network request failed — check your network or backend connection",
nameStepCheckError: "Could not verify name availability — please try again",
nameStepBootstrapMessage:
"The new custom agent name is {name}. Let's bootstrap it's **SOUL**.",
save: "Save agent",
saving: "Saving agent...",
saveRequested:
"Save requested. CM Assistant is generating and saving an initial version now.",
saveHint:
"You can save this agent at any time from the top-right menu, even if this is only a first draft.",
saveCommandMessage:
"Please save this custom agent now based on everything we have discussed so far. Treat this as my explicit confirmation to save. If some details are still missing, make reasonable assumptions, generate a concise first SOUL.md in English, and call setup_agent immediately without asking me for more confirmation.",
agentCreatedPendingRefresh:
"The agent was created, but CM Assistant could not load it yet. Please refresh this page in a moment.",
more: "More actions",
agentCreated: "Agent created!",
startChatting: "Start chatting",
backToGallery: "Back to Gallery",
},
// Breadcrumb
breadcrumb: {
workspace: "Workspace",
chats: "Chats",
},
// Workspace
workspace: {
officialWebsite: "CM Assistant's official website",
githubTooltip: "CM Assistant on Github",
settingsAndMore: "Settings and more",
visitGithub: "CM Assistant on GitHub",
reportIssue: "Report a issue",
contactUs: "Contact us",
about: "About CM Assistant",
},
// Conversation
conversation: {
noMessages: "No messages yet",
startConversation: "Start a conversation to see messages here",
},
// Chats
chats: {
searchChats: "Search chats",
},
// Page titles (document title)
pages: {
appName: "CM Assistant",
brandSubtitle: "Smart CM Platform",
chats: "Chats",
newChat: "New chat",
untitled: "Untitled",
},
// Tool calls
toolCalls: {
moreSteps: (count: number) => `${count} more step${count === 1 ? "" : "s"}`,
lessSteps: "Less steps",
executeCommand: "Execute command",
presentFiles: "Present files",
needYourHelp: "Need your help",
useTool: (toolName: string) => `Use "${toolName}" tool`,
searchFor: (query: string) => `Search for "${query}"`,
searchForRelatedInfo: "Search for related information",
searchForRelatedImages: "Search for related images",
searchForRelatedImagesFor: (query: string) =>
`Search for related images for "${query}"`,
searchOnWebFor: (query: string) => `Search on the web for "${query}"`,
viewWebPage: "View web page",
listFolder: "List folder",
readFile: "Read file",
writeFile: "Write file",
clickToViewContent: "Click to view file content",
writeTodos: "Update to-do list",
skillInstallTooltip: "Install skill and make it available to CM Assistant",
},
// Subtasks
uploads: {
uploading: "Uploading...",
uploadingFiles: "Uploading files, please wait...",
},
subtasks: {
subtask: "Subtask",
executing: (count: number) =>
`Executing ${count === 1 ? "" : count + " "}subtask${count === 1 ? "" : "s in parallel"}`,
in_progress: "Running subtask",
completed: "Subtask completed",
failed: "Subtask failed",
},
// Token Usage
tokenUsage: {
title: "Token Usage",
label: "Tokens",
input: "Input",
output: "Output",
total: "Total",
unavailable:
"No token usage yet. Usage appears only after a successful model response when the provider returns usage_metadata.",
unavailableShort: "No usage returned",
},
// Shortcuts
shortcuts: {
searchActions: "Search actions...",
noResults: "No results found.",
actions: "Actions",
keyboardShortcuts: "Keyboard Shortcuts",
keyboardShortcutsDescription:
"Navigate CM Assistant faster with keyboard shortcuts.",
openCommandPalette: "Open Command Palette",
toggleSidebar: "Toggle Sidebar",
},
// Settings
settings: {
title: "Settings",
description: "Adjust how CM Assistant looks and behaves for you.",
sections: {
appearance: "Appearance",
memory: "Memory",
tools: "Tools",
skills: "Skills",
notification: "Notification",
about: "About",
},
memory: {
title: "Memory",
description:
"CM Assistant automatically learns from your conversations in the background. These memories help CM Assistant understand you better and deliver a more personalized experience.",
empty: "No memory data to display.",
rawJson: "Raw JSON",
exportButton: "Export memory",
exportSuccess: "Memory exported",
importButton: "Import memory",
importConfirmTitle: "Import memory?",
importConfirmDescription:
"This will overwrite your current memory with the selected JSON backup.",
importFileLabel: "Selected file",
importInvalidFile:
"Failed to read the selected memory file. Please choose a valid JSON export.",
importSuccess: "Memory imported",
manualFactSource: "Manual",
addFact: "Add fact",
addFactTitle: "Add memory fact",
editFactTitle: "Edit memory fact",
addFactSuccess: "Fact created",
editFactSuccess: "Fact updated",
clearAll: "Clear all memory",
clearAllConfirmTitle: "Clear all memory?",
clearAllConfirmDescription:
"This will remove all saved summaries and facts. This action cannot be undone.",
clearAllSuccess: "All memory cleared",
factDeleteConfirmTitle: "Delete this fact?",
factDeleteConfirmDescription:
"This fact will be removed from memory immediately. This action cannot be undone.",
factDeleteSuccess: "Fact deleted",
factContentLabel: "Content",
factCategoryLabel: "Category",
factConfidenceLabel: "Confidence",
factContentPlaceholder: "Describe the memory fact you want to save",
factCategoryPlaceholder: "context",
factConfidenceHint: "Use a number between 0 and 1.",
factSave: "Save fact",
factValidationContent: "Fact content cannot be empty.",
factValidationConfidence: "Confidence must be a number between 0 and 1.",
noFacts: "No saved facts yet.",
summaryReadOnly:
"Summary sections are read-only for now. You can currently add, edit, or delete individual facts, or clear all memory.",
memoryFullyEmpty: "No memory saved yet.",
factPreviewLabel: "Fact to delete",
searchPlaceholder: "Search memory",
filterAll: "All",
filterFacts: "Facts",
filterSummaries: "Summaries",
noMatches: "No matching memory found.",
markdown: {
overview: "Overview",
userContext: "User context",
work: "Work",
personal: "Personal",
topOfMind: "Top of mind",
historyBackground: "History",
recentMonths: "Recent months",
earlierContext: "Earlier context",
longTermBackground: "Long-term background",
updatedAt: "Updated at",
facts: "Facts",
empty: "(empty)",
table: {
category: "Category",
confidence: "Confidence",
confidenceLevel: {
veryHigh: "Very high",
high: "High",
normal: "Normal",
unknown: "Unknown",
},
content: "Content",
source: "Source",
createdAt: "CreatedAt",
view: "View",
},
},
},
appearance: {
themeTitle: "Theme",
themeDescription:
"Choose how the interface follows your device or stays fixed.",
system: "System",
light: "Light",
dark: "Dark",
systemDescription: "Match the operating system preference automatically.",
lightDescription: "Bright palette with higher contrast for daytime.",
darkDescription: "Dim palette that reduces glare for focus.",
languageTitle: "Language",
languageDescription: "Switch between languages.",
},
tools: {
title: "Tools",
description: "Manage the configuration and enabled status of MCP tools.",
},
skills: {
title: "Agent Skills",
description:
"Manage the configuration and enabled status of the agent skills.",
createSkill: "Create skill",
installSkill: "Install skill",
emptyTitle: "No agent skill yet",
emptyDescription:
"Put your agent skill folders under the `/skills/custom` folder under the root folder of CM Assistant.",
emptyButton: "Create Your First Skill",
installDialog: {
title: "Install skill",
dropHint: "Drop a .zip or .skill archive here, or",
chooseFile: "Choose file",
validating: "Validating archive…",
installing: "Installing…",
replace: "Replace existing",
install: "Install",
cancel: "Cancel",
nameLabel: "Name",
descriptionLabel: "Description",
licenseLabel: "License",
toolsLabel: "Allowed tools",
warningsLabel: "Warnings",
conflictCustom:
"A custom skill named '{name}' is already installed. Use 'Replace existing' to overwrite (its enabled state will be kept).",
conflictPublic:
"A built-in public skill named '{name}' already exists and cannot be overwritten.",
installSuccess: "Skill '{name}' installed.",
installSuccessReplaced: "Skill '{name}' replaced.",
rejectInvalidExt: "Only .zip or .skill files are accepted.",
},
},
notification: {
title: "Notification",
description:
"CM Assistant only sends a completion notification when the window is not active. This is especially useful for long-running tasks so you can switch to other work and get notified when done.",
requestPermission: "Request notification permission",
deniedHint:
"Notification permission was denied. You can enable it in your browser's site settings to receive completion alerts.",
testButton: "Send test notification",
testTitle: "CM Assistant",
testBody: "This is a test notification.",
notSupported: "Your browser does not support notifications.",
disableNotification: "Disable notification",
},
acknowledge: {
emptyTitle: "Acknowledgements",
emptyDescription: "Credits and acknowledgements will show here.",
},
},
};
+3 -3
View File
@@ -1,3 +1,3 @@
export { enUS } from "./en-US";
export { zhCN } from "./zh-CN";
export type { Translations } from "./types";
export { enUS } from "./en-US";
export { zhCN } from "./zh-CN";
export type { Translations } from "./types";
+398 -377
View File
@@ -1,377 +1,398 @@
import type { LucideIcon } from "lucide-react";
export interface Translations {
// Locale meta
locale: {
localName: string;
};
// Common
common: {
home: string;
settings: string;
delete: string;
edit: string;
rename: string;
share: string;
openInNewWindow: string;
close: string;
more: string;
search: string;
download: string;
thinking: string;
artifacts: string;
public: string;
custom: string;
notAvailableInDemoMode: string;
loading: string;
version: string;
lastUpdated: string;
code: string;
preview: string;
cancel: string;
save: string;
install: string;
create: string;
import: string;
export: string;
exportAsMarkdown: string;
exportAsJSON: string;
exportSuccess: string;
};
home: {
docs: string;
blog: string;
};
// Welcome
welcome: {
greeting: string;
description: string;
createYourOwnSkill: string;
createYourOwnSkillDescription: string;
};
// Clipboard
clipboard: {
copyToClipboard: string;
copiedToClipboard: string;
failedToCopyToClipboard: string;
linkCopied: string;
};
// Input Box
inputBox: {
placeholder: string;
createSkillPrompt: string;
addAttachments: string;
mode: string;
flashMode: string;
flashModeDescription: string;
reasoningMode: string;
reasoningModeDescription: string;
proMode: string;
proModeDescription: string;
ultraMode: string;
ultraModeDescription: string;
reasoningEffort: string;
reasoningEffortMinimal: string;
reasoningEffortMinimalDescription: string;
reasoningEffortLow: string;
reasoningEffortLowDescription: string;
reasoningEffortMedium: string;
reasoningEffortMediumDescription: string;
reasoningEffortHigh: string;
reasoningEffortHighDescription: string;
searchModels: string;
surpriseMe: string;
surpriseMePrompt: string;
followupLoading: string;
followupConfirmTitle: string;
followupConfirmDescription: string;
followupConfirmAppend: string;
followupConfirmReplace: string;
suggestions: {
suggestion: string;
prompt: string;
icon: LucideIcon;
}[];
suggestionsCreate: (
| {
suggestion: string;
prompt: string;
icon: LucideIcon;
}
| {
type: "separator";
}
)[];
};
// Sidebar
sidebar: {
recentChats: string;
newChat: string;
chats: string;
demoChats: string;
agents: string;
};
// Agents
agents: {
title: string;
description: string;
newAgent: string;
emptyTitle: string;
emptyDescription: string;
chat: string;
delete: string;
deleteConfirm: string;
deleteSuccess: string;
newChat: string;
createPageTitle: string;
createPageSubtitle: string;
nameStepTitle: string;
nameStepHint: string;
nameStepPlaceholder: string;
nameStepContinue: string;
nameStepInvalidError: string;
nameStepAlreadyExistsError: string;
nameStepNetworkError: string;
nameStepCheckError: string;
nameStepBootstrapMessage: string;
save: string;
saving: string;
saveRequested: string;
saveHint: string;
saveCommandMessage: string;
agentCreatedPendingRefresh: string;
more: string;
agentCreated: string;
startChatting: string;
backToGallery: string;
};
// Breadcrumb
breadcrumb: {
workspace: string;
chats: string;
};
// Workspace
workspace: {
officialWebsite: string;
githubTooltip: string;
settingsAndMore: string;
visitGithub: string;
reportIssue: string;
contactUs: string;
about: string;
};
// Conversation
conversation: {
noMessages: string;
startConversation: string;
};
// Chats
chats: {
searchChats: string;
};
// Page titles (document title)
pages: {
appName: string;
brandSubtitle: string;
chats: string;
newChat: string;
untitled: string;
};
// Tool calls
toolCalls: {
moreSteps: (count: number) => string;
lessSteps: string;
executeCommand: string;
presentFiles: string;
needYourHelp: string;
useTool: (toolName: string) => string;
searchForRelatedInfo: string;
searchForRelatedImages: string;
searchFor: (query: string) => string;
searchForRelatedImagesFor: (query: string) => string;
searchOnWebFor: (query: string) => string;
viewWebPage: string;
listFolder: string;
readFile: string;
writeFile: string;
clickToViewContent: string;
writeTodos: string;
skillInstallTooltip: string;
};
// Uploads
uploads: {
uploading: string;
uploadingFiles: string;
};
// Subtasks
subtasks: {
subtask: string;
executing: (count: number) => string;
in_progress: string;
completed: string;
failed: string;
};
// Token Usage
tokenUsage: {
title: string;
label: string;
input: string;
output: string;
total: string;
unavailable: string;
unavailableShort: string;
};
// Shortcuts
shortcuts: {
searchActions: string;
noResults: string;
actions: string;
keyboardShortcuts: string;
keyboardShortcutsDescription: string;
openCommandPalette: string;
toggleSidebar: string;
};
// Settings
settings: {
title: string;
description: string;
sections: {
appearance: string;
memory: string;
tools: string;
skills: string;
notification: string;
about: string;
};
memory: {
title: string;
description: string;
empty: string;
rawJson: string;
exportButton: string;
exportSuccess: string;
importButton: string;
importConfirmTitle: string;
importConfirmDescription: string;
importFileLabel: string;
importInvalidFile: string;
importSuccess: string;
manualFactSource: string;
addFact: string;
addFactTitle: string;
editFactTitle: string;
addFactSuccess: string;
editFactSuccess: string;
clearAll: string;
clearAllConfirmTitle: string;
clearAllConfirmDescription: string;
clearAllSuccess: string;
factDeleteConfirmTitle: string;
factDeleteConfirmDescription: string;
factDeleteSuccess: string;
factContentLabel: string;
factCategoryLabel: string;
factConfidenceLabel: string;
factContentPlaceholder: string;
factCategoryPlaceholder: string;
factConfidenceHint: string;
factSave: string;
factValidationContent: string;
factValidationConfidence: string;
noFacts: string;
summaryReadOnly: string;
memoryFullyEmpty: string;
factPreviewLabel: string;
searchPlaceholder: string;
filterAll: string;
filterFacts: string;
filterSummaries: string;
noMatches: string;
markdown: {
overview: string;
userContext: string;
work: string;
personal: string;
topOfMind: string;
historyBackground: string;
recentMonths: string;
earlierContext: string;
longTermBackground: string;
updatedAt: string;
facts: string;
empty: string;
table: {
category: string;
confidence: string;
confidenceLevel: {
veryHigh: string;
high: string;
normal: string;
unknown: string;
};
content: string;
source: string;
createdAt: string;
view: string;
};
};
};
appearance: {
themeTitle: string;
themeDescription: string;
system: string;
light: string;
dark: string;
systemDescription: string;
lightDescription: string;
darkDescription: string;
languageTitle: string;
languageDescription: string;
};
tools: {
title: string;
description: string;
};
skills: {
title: string;
description: string;
createSkill: string;
emptyTitle: string;
emptyDescription: string;
emptyButton: string;
};
notification: {
title: string;
description: string;
requestPermission: string;
deniedHint: string;
testButton: string;
testTitle: string;
testBody: string;
notSupported: string;
disableNotification: string;
};
acknowledge: {
emptyTitle: string;
emptyDescription: string;
};
};
}
import type { LucideIcon } from "lucide-react";
export interface Translations {
// Locale meta
locale: {
localName: string;
};
// Common
common: {
home: string;
settings: string;
delete: string;
edit: string;
rename: string;
share: string;
openInNewWindow: string;
close: string;
more: string;
search: string;
download: string;
thinking: string;
artifacts: string;
public: string;
custom: string;
notAvailableInDemoMode: string;
loading: string;
version: string;
lastUpdated: string;
code: string;
preview: string;
cancel: string;
save: string;
install: string;
create: string;
import: string;
export: string;
exportAsMarkdown: string;
exportAsJSON: string;
exportSuccess: string;
};
home: {
docs: string;
blog: string;
};
// Welcome
welcome: {
greeting: string;
description: string;
createYourOwnSkill: string;
createYourOwnSkillDescription: string;
};
// Clipboard
clipboard: {
copyToClipboard: string;
copiedToClipboard: string;
failedToCopyToClipboard: string;
linkCopied: string;
};
// Input Box
inputBox: {
placeholder: string;
createSkillPrompt: string;
addAttachments: string;
mode: string;
flashMode: string;
flashModeDescription: string;
reasoningMode: string;
reasoningModeDescription: string;
proMode: string;
proModeDescription: string;
ultraMode: string;
ultraModeDescription: string;
reasoningEffort: string;
reasoningEffortMinimal: string;
reasoningEffortMinimalDescription: string;
reasoningEffortLow: string;
reasoningEffortLowDescription: string;
reasoningEffortMedium: string;
reasoningEffortMediumDescription: string;
reasoningEffortHigh: string;
reasoningEffortHighDescription: string;
searchModels: string;
surpriseMe: string;
surpriseMePrompt: string;
followupLoading: string;
followupConfirmTitle: string;
followupConfirmDescription: string;
followupConfirmAppend: string;
followupConfirmReplace: string;
suggestions: {
suggestion: string;
prompt: string;
icon: LucideIcon;
}[];
suggestionsCreate: (
| {
suggestion: string;
prompt: string;
icon: LucideIcon;
}
| {
type: "separator";
}
)[];
};
// Sidebar
sidebar: {
recentChats: string;
newChat: string;
chats: string;
demoChats: string;
agents: string;
};
// Agents
agents: {
title: string;
description: string;
newAgent: string;
emptyTitle: string;
emptyDescription: string;
chat: string;
delete: string;
deleteConfirm: string;
deleteSuccess: string;
newChat: string;
createPageTitle: string;
createPageSubtitle: string;
nameStepTitle: string;
nameStepHint: string;
nameStepPlaceholder: string;
nameStepContinue: string;
nameStepInvalidError: string;
nameStepAlreadyExistsError: string;
nameStepNetworkError: string;
nameStepCheckError: string;
nameStepBootstrapMessage: string;
save: string;
saving: string;
saveRequested: string;
saveHint: string;
saveCommandMessage: string;
agentCreatedPendingRefresh: string;
more: string;
agentCreated: string;
startChatting: string;
backToGallery: string;
};
// Breadcrumb
breadcrumb: {
workspace: string;
chats: string;
};
// Workspace
workspace: {
officialWebsite: string;
githubTooltip: string;
settingsAndMore: string;
visitGithub: string;
reportIssue: string;
contactUs: string;
about: string;
};
// Conversation
conversation: {
noMessages: string;
startConversation: string;
};
// Chats
chats: {
searchChats: string;
};
// Page titles (document title)
pages: {
appName: string;
brandSubtitle: string;
chats: string;
newChat: string;
untitled: string;
};
// Tool calls
toolCalls: {
moreSteps: (count: number) => string;
lessSteps: string;
executeCommand: string;
presentFiles: string;
needYourHelp: string;
useTool: (toolName: string) => string;
searchForRelatedInfo: string;
searchForRelatedImages: string;
searchFor: (query: string) => string;
searchForRelatedImagesFor: (query: string) => string;
searchOnWebFor: (query: string) => string;
viewWebPage: string;
listFolder: string;
readFile: string;
writeFile: string;
clickToViewContent: string;
writeTodos: string;
skillInstallTooltip: string;
};
// Uploads
uploads: {
uploading: string;
uploadingFiles: string;
};
// Subtasks
subtasks: {
subtask: string;
executing: (count: number) => string;
in_progress: string;
completed: string;
failed: string;
};
// Token Usage
tokenUsage: {
title: string;
label: string;
input: string;
output: string;
total: string;
unavailable: string;
unavailableShort: string;
};
// Shortcuts
shortcuts: {
searchActions: string;
noResults: string;
actions: string;
keyboardShortcuts: string;
keyboardShortcutsDescription: string;
openCommandPalette: string;
toggleSidebar: string;
};
// Settings
settings: {
title: string;
description: string;
sections: {
appearance: string;
memory: string;
tools: string;
skills: string;
notification: string;
about: string;
};
memory: {
title: string;
description: string;
empty: string;
rawJson: string;
exportButton: string;
exportSuccess: string;
importButton: string;
importConfirmTitle: string;
importConfirmDescription: string;
importFileLabel: string;
importInvalidFile: string;
importSuccess: string;
manualFactSource: string;
addFact: string;
addFactTitle: string;
editFactTitle: string;
addFactSuccess: string;
editFactSuccess: string;
clearAll: string;
clearAllConfirmTitle: string;
clearAllConfirmDescription: string;
clearAllSuccess: string;
factDeleteConfirmTitle: string;
factDeleteConfirmDescription: string;
factDeleteSuccess: string;
factContentLabel: string;
factCategoryLabel: string;
factConfidenceLabel: string;
factContentPlaceholder: string;
factCategoryPlaceholder: string;
factConfidenceHint: string;
factSave: string;
factValidationContent: string;
factValidationConfidence: string;
noFacts: string;
summaryReadOnly: string;
memoryFullyEmpty: string;
factPreviewLabel: string;
searchPlaceholder: string;
filterAll: string;
filterFacts: string;
filterSummaries: string;
noMatches: string;
markdown: {
overview: string;
userContext: string;
work: string;
personal: string;
topOfMind: string;
historyBackground: string;
recentMonths: string;
earlierContext: string;
longTermBackground: string;
updatedAt: string;
facts: string;
empty: string;
table: {
category: string;
confidence: string;
confidenceLevel: {
veryHigh: string;
high: string;
normal: string;
unknown: string;
};
content: string;
source: string;
createdAt: string;
view: string;
};
};
};
appearance: {
themeTitle: string;
themeDescription: string;
system: string;
light: string;
dark: string;
systemDescription: string;
lightDescription: string;
darkDescription: string;
languageTitle: string;
languageDescription: string;
};
tools: {
title: string;
description: string;
};
skills: {
title: string;
description: string;
createSkill: string;
installSkill: string;
emptyTitle: string;
emptyDescription: string;
emptyButton: string;
installDialog: {
title: string;
dropHint: string;
chooseFile: string;
validating: string;
installing: string;
replace: string;
install: string;
cancel: string;
nameLabel: string;
descriptionLabel: string;
licenseLabel: string;
toolsLabel: string;
warningsLabel: string;
conflictCustom: string;
conflictPublic: string;
installSuccess: string;
installSuccessReplaced: string;
rejectInvalidExt: string;
};
};
notification: {
title: string;
description: string;
requestPermission: string;
deniedHint: string;
testButton: string;
testTitle: string;
testBody: string;
notSupported: string;
disableNotification: string;
};
acknowledge: {
emptyTitle: string;
emptyDescription: string;
};
};
}
+462 -440
View File
@@ -1,440 +1,462 @@
import {
CompassIcon,
GraduationCapIcon,
ImageIcon,
MicroscopeIcon,
PenLineIcon,
ShapesIcon,
SparklesIcon,
VideoIcon,
} from "lucide-react";
import type { Translations } from "./types";
export const zhCN: Translations = {
// Locale meta
locale: {
localName: "中文",
},
// Common
common: {
home: "首页",
settings: "设置",
delete: "删除",
edit: "编辑",
rename: "重命名",
share: "分享",
openInNewWindow: "在新窗口打开",
close: "关闭",
more: "更多",
search: "搜索",
download: "下载",
thinking: "思考",
artifacts: "文件",
public: "公共",
custom: "自定义",
notAvailableInDemoMode: "在演示模式下不可用",
loading: "加载中...",
version: "版本",
lastUpdated: "最后更新",
code: "代码",
preview: "预览",
cancel: "取消",
save: "保存",
install: "安装",
create: "创建",
import: "导入",
export: "导出",
exportAsMarkdown: "导出为 Markdown",
exportAsJSON: "导出为 JSON",
exportSuccess: "对话已导出",
},
// Home
home: {
docs: "文档",
blog: "博客",
},
// Welcome
welcome: {
greeting: "你好,欢迎回来!",
description:
"欢迎使用 CM业务中心-问答管理",
createYourOwnSkill: "创建你自己的 Agent SKill",
createYourOwnSkillDescription:
"创建你的 Agent Skill 来释放 CM业务中心-问答管理的潜力。通过自定义技能,CM业务中心-问答管理\n可以帮你搜索网络、分析数据,还能为你生成幻灯片、\n网页等作品,几乎可以做任何事情。",
},
// Clipboard
clipboard: {
copyToClipboard: "复制到剪贴板",
copiedToClipboard: "已复制到剪贴板",
failedToCopyToClipboard: "复制到剪贴板失败",
linkCopied: "链接已复制到剪贴板",
},
// Input Box
inputBox: {
placeholder: "今天我能为你做些什么?",
createSkillPrompt:
"我们一起用 skill-creator 技能来创建一个技能吧。先问问我希望这个技能能做什么。",
addAttachments: "添加附件",
mode: "模式",
flashMode: "快速",
flashModeDescription: "快速且高效的完成任务,但可能不够精准",
reasoningMode: "思考",
reasoningModeDescription: "思考后再行动,在时间与准确性之间取得平衡",
proMode: "专业问答",
proModeDescription: "思考、计划再执行,获得更精准的结果,可能需要更多时间",
ultraMode: "多智能体问答",
ultraModeDescription:
"继承自专业问答模式,可调用子代理分工协作,适合复杂多步骤任务,能力最强",
reasoningEffort: "推理深度",
reasoningEffortMinimal: "最低",
reasoningEffortMinimalDescription: "检索 + 直接输出",
reasoningEffortLow: "低",
reasoningEffortLowDescription: "简单逻辑校验 + 浅层推演",
reasoningEffortMedium: "中",
reasoningEffortMediumDescription: "多层逻辑分析 + 基础验证",
reasoningEffortHigh: "高",
reasoningEffortHighDescription: "全维度逻辑推演 + 多路径验证 + 反推校验",
searchModels: "搜索模型...",
surpriseMe: "小惊喜",
surpriseMePrompt: "给我一个小惊喜吧",
followupLoading: "正在生成可能的后续问题...",
followupConfirmTitle: "发送建议问题?",
followupConfirmDescription: "当前输入框已有内容,选择发送方式。",
followupConfirmAppend: "追加并发送",
followupConfirmReplace: "替换并发送",
suggestions: [
{
suggestion: "写作",
prompt: "撰写一篇关于[主题]的博客文章",
icon: PenLineIcon,
},
{
suggestion: "研究",
prompt: "深入浅出的研究一下[主题],并总结发现。",
icon: MicroscopeIcon,
},
{
suggestion: "收集",
prompt: "从[来源]收集数据并创建报告。",
icon: ShapesIcon,
},
{
suggestion: "学习",
prompt: "学习关于[主题]并创建教程。",
icon: GraduationCapIcon,
},
],
suggestionsCreate: [
{
suggestion: "网页",
prompt: "生成一个关于[主题]的网页",
icon: CompassIcon,
},
{
suggestion: "图片",
prompt: "生成一个关于[主题]的图片",
icon: ImageIcon,
},
{
suggestion: "视频",
prompt: "生成一个关于[主题]的视频",
icon: VideoIcon,
},
{
type: "separator",
},
{
suggestion: "技能",
prompt:
"我们一起用 skill-creator 技能来创建一个技能吧。先问问我希望这个技能能做什么。",
icon: SparklesIcon,
},
],
},
// Sidebar
sidebar: {
newChat: "新对话",
chats: "对话",
recentChats: "最近的对话",
demoChats: "演示对话",
agents: "智能体",
},
// Agents
agents: {
title: "智能体",
description: "创建和管理具有专属 Prompt 与能力的自定义智能体。",
newAgent: "新建智能体",
emptyTitle: "还没有自定义智能体",
emptyDescription: "创建你的第一个自定义智能体,设置专属系统提示词。",
chat: "对话",
delete: "删除",
deleteConfirm: "确定要删除该智能体吗?此操作不可撤销。",
deleteSuccess: "智能体已删除",
newChat: "新对话",
createPageTitle: "设计你的智能体",
createPageSubtitle: "描述你想要的智能体,我来帮你通过对话创建。",
nameStepTitle: "给新智能体起个名字",
nameStepHint:
"只允许字母、数字和连字符,存储时自动转为小写(例如 code-reviewer)",
nameStepPlaceholder: "例如 code-reviewer",
nameStepContinue: "继续",
nameStepInvalidError: "名称无效,只允许字母、数字和连字符",
nameStepAlreadyExistsError: "已存在同名智能体",
nameStepNetworkError: "网络请求失败,请检查网络或后端连接",
nameStepCheckError: "无法验证名称可用性,请稍后重试",
nameStepBootstrapMessage:
"新智能体的名称是 {name},现在开始为它生成 **SOUL**。",
save: "保存智能体",
saving: "正在保存智能体...",
saveRequested:
"已提交保存请求,CM业务中心-问答管理 正在根据当前对话生成并保存初版智能体。",
saveHint:
"你可以在右上角的菜单里随时保存这个智能体,就算目前还只是初稿也可以。",
saveCommandMessage:
"请现在根据我们目前已经讨论的全部内容保存这个自定义智能体。这就是我明确的保存确认。如果仍有少量细节缺失,请根据上下文做出合理假设,生成一份简洁的英文初始 SOUL.md,并直接调用 setup_agent,不要再向我索要额外确认。",
agentCreatedPendingRefresh:
"智能体已创建,但 CM业务中心-问答管理 暂时还无法读取到它。请稍后刷新当前页面。",
more: "更多操作",
agentCreated: "智能体已创建!",
startChatting: "开始对话",
backToGallery: "返回 Gallery",
},
// Breadcrumb
breadcrumb: {
workspace: "工作区",
chats: "对话",
},
// Workspace
workspace: {
officialWebsite: "访问 CM业务中心-问答管理 官方网站",
githubTooltip: "访问 CM业务中心-问答管理 的 Github 仓库",
settingsAndMore: "设置和更多",
visitGithub: "在 Github 上查看 CM业务中心-问答管理",
reportIssue: "报告问题",
contactUs: "联系我们",
about: "关于 CM业务中心-问答管理",
},
// Conversation
conversation: {
noMessages: "还没有消息",
startConversation: "开始新的对话以查看消息",
},
// Chats
chats: {
searchChats: "搜索对话",
},
// Page titles (document title)
pages: {
appName: "CM业务中心-问答管理",
brandSubtitle: "Smart CM Platform",
chats: "对话",
newChat: "新对话",
untitled: "未命名",
},
// Tool calls
toolCalls: {
moreSteps: (count: number) => `查看其他 ${count} 个步骤`,
lessSteps: "隐藏步骤",
executeCommand: "执行命令",
presentFiles: "展示文件",
needYourHelp: "需要你的协助",
useTool: (toolName: string) => `使用 “${toolName}” 工具`,
searchFor: (query: string) => `搜索 “${query}”`,
searchForRelatedInfo: "搜索相关信息",
searchForRelatedImages: "搜索相关图片",
searchForRelatedImagesFor: (query: string) => `搜索相关图片 “${query}”`,
searchOnWebFor: (query: string) => `在网络上搜索 “${query}”`,
viewWebPage: "查看网页",
listFolder: "列出文件夹",
readFile: "读取文件",
writeFile: "写入文件",
clickToViewContent: "点击查看文件内容",
writeTodos: "更新 To-do 列表",
skillInstallTooltip: "安装技能并使其可在 CM业务中心-问答管理 中使用",
},
uploads: {
uploading: "上传中...",
uploadingFiles: "文件上传中,请稍候...",
},
subtasks: {
subtask: "子任务",
executing: (count: number) =>
`${count > 1 ? "并行" : ""}执行 ${count} 个子任务`,
in_progress: "子任务运行中",
completed: "子任务已完成",
failed: "子任务失败",
},
// Token Usage
tokenUsage: {
title: "Token 用量",
label: "Tokens",
input: "输入",
output: "输出",
total: "总计",
unavailable:
"暂无 Token 用量。只有模型成功返回且供应商提供 usage_metadata 时才会显示。",
unavailableShort: "未返回用量",
},
// Shortcuts
shortcuts: {
searchActions: "搜索操作...",
noResults: "未找到结果。",
actions: "操作",
keyboardShortcuts: "键盘快捷键",
keyboardShortcutsDescription: "使用键盘快捷键更快地操作 CM业务中心-问答管理。",
openCommandPalette: "打开命令面板",
toggleSidebar: "切换侧边栏",
},
// Settings
settings: {
title: "设置",
description: "根据你的偏好调整 CM业务中心-问答管理 的界面和行为。",
sections: {
appearance: "外观",
memory: "记忆",
tools: "工具",
skills: "技能",
notification: "通知",
about: "关于",
},
memory: {
title: "记忆",
description:
"CM业务中心-问答管理 会在后台不断从你的对话中自动学习。这些记忆能帮助 CM业务中心-问答管理 更好地理解你,并提供更个性化的体验。",
empty: "暂无可展示的记忆数据。",
rawJson: "原始 JSON",
exportButton: "导出记忆",
exportSuccess: "记忆已导出",
importButton: "导入记忆",
importConfirmTitle: "导入记忆?",
importConfirmDescription: "这会用选中的 JSON 备份覆盖当前记忆。",
importFileLabel: "已选择文件",
importInvalidFile: "读取记忆文件失败,请选择有效的 JSON 导出文件。",
importSuccess: "记忆已导入",
manualFactSource: "手动添加",
addFact: "添加事实",
addFactTitle: "添加记忆事实",
editFactTitle: "编辑记忆事实",
addFactSuccess: "事实已创建",
editFactSuccess: "事实已更新",
clearAll: "清空全部记忆",
clearAllConfirmTitle: "要清空全部记忆吗?",
clearAllConfirmDescription:
"这会删除所有已保存的摘要和事实。此操作无法撤销。",
clearAllSuccess: "已清空全部记忆",
factDeleteConfirmTitle: "要删除这条事实吗?",
factDeleteConfirmDescription:
"这条事实会立即从记忆中删除。此操作无法撤销。",
factDeleteSuccess: "事实已删除",
factContentLabel: "内容",
factCategoryLabel: "类别",
factConfidenceLabel: "置信度",
factContentPlaceholder: "描述你想保存的记忆事实",
factCategoryPlaceholder: "context",
factConfidenceHint: "请输入 0 到 1 之间的数字。",
factSave: "保存事实",
factValidationContent: "事实内容不能为空。",
factValidationConfidence: "置信度必须是 0 到 1 之间的数字。",
noFacts: "还没有保存的事实。",
summaryReadOnly:
"摘要分区当前仍为只读。现在你可以清空全部记忆或删除单条事实。",
memoryFullyEmpty: "还没有保存任何记忆。",
factPreviewLabel: "即将删除的事实",
searchPlaceholder: "搜索记忆",
filterAll: "全部",
filterFacts: "事实",
filterSummaries: "摘要",
noMatches: "没有找到匹配的记忆。",
markdown: {
overview: "概览",
userContext: "用户上下文",
work: "工作",
personal: "个人",
topOfMind: "近期关注(Top of mind)",
historyBackground: "历史背景",
recentMonths: "近几个月",
earlierContext: "更早上下文",
longTermBackground: "长期背景",
updatedAt: "更新于",
facts: "事实",
empty: "(空)",
table: {
category: "类别",
confidence: "置信度",
confidenceLevel: {
veryHigh: "极高",
high: "较高",
normal: "一般",
unknown: "未知",
},
content: "内容",
source: "来源",
createdAt: "创建时间",
view: "查看",
},
},
},
appearance: {
themeTitle: "主题",
themeDescription: "跟随系统或选择固定的界面模式。",
system: "系统",
light: "浅色",
dark: "深色",
systemDescription: "自动跟随系统主题。",
lightDescription: "更明亮的配色,适合日间使用。",
darkDescription: "更暗的配色,减少眩光方便专注。",
languageTitle: "语言",
languageDescription: "在不同语言之间切换。",
},
tools: {
title: "工具",
description: "管理 MCP 工具的配置和启用状态。",
},
skills: {
title: "技能",
description: "管理 Agent Skill 配置和启用状态。",
createSkill: "新建技能",
emptyTitle: "还没有技能",
emptyDescription:
"将你的 Agent Skill 文件夹放在 CM业务中心-问答管理 根目录下的 `/skills/custom` 文件夹中。",
emptyButton: "创建你的第一个技能",
},
notification: {
title: "通知",
description:
"CM业务中心-问答管理 只会在窗口不活跃时发送完成通知,特别适合长时间任务:你可以先去做别的事,完成后会收到提醒。",
requestPermission: "请求通知权限",
deniedHint:
"通知权限已被拒绝。可在浏览器的网站设置中重新开启,以接收完成提醒。",
testButton: "发送测试通知",
testTitle: "CM业务中心-问答管理",
testBody: "这是一条测试通知。",
notSupported: "当前浏览器不支持通知功能。",
disableNotification: "关闭通知",
},
acknowledge: {
emptyTitle: "致谢",
emptyDescription: "相关的致谢信息会展示在这里。",
},
},
};
import {
CompassIcon,
GraduationCapIcon,
ImageIcon,
MicroscopeIcon,
PenLineIcon,
ShapesIcon,
SparklesIcon,
VideoIcon,
} from "lucide-react";
import type { Translations } from "./types";
export const zhCN: Translations = {
// Locale meta
locale: {
localName: "中文",
},
// Common
common: {
home: "首页",
settings: "设置",
delete: "删除",
edit: "编辑",
rename: "重命名",
share: "分享",
openInNewWindow: "在新窗口打开",
close: "关闭",
more: "更多",
search: "搜索",
download: "下载",
thinking: "思考",
artifacts: "文件",
public: "公共",
custom: "自定义",
notAvailableInDemoMode: "在演示模式下不可用",
loading: "加载中...",
version: "版本",
lastUpdated: "最后更新",
code: "代码",
preview: "预览",
cancel: "取消",
save: "保存",
install: "安装",
create: "创建",
import: "导入",
export: "导出",
exportAsMarkdown: "导出为 Markdown",
exportAsJSON: "导出为 JSON",
exportSuccess: "对话已导出",
},
// Home
home: {
docs: "文档",
blog: "博客",
},
// Welcome
welcome: {
greeting: "你好,欢迎回来!",
description:
"欢迎使用 CM 助手",
createYourOwnSkill: "创建你自己的 Agent SKill",
createYourOwnSkillDescription:
"创建你的 Agent Skill 来释放 CM 助手的潜力。通过自定义技能,CM 助手\n可以帮你搜索网络、分析数据,还能为你生成幻灯片、\n网页等作品,几乎可以做任何事情。",
},
// Clipboard
clipboard: {
copyToClipboard: "复制到剪贴板",
copiedToClipboard: "已复制到剪贴板",
failedToCopyToClipboard: "复制到剪贴板失败",
linkCopied: "链接已复制到剪贴板",
},
// Input Box
inputBox: {
placeholder: "今天我能为你做些什么?",
createSkillPrompt:
"我们一起用 skill-creator 技能来创建一个技能吧。先问问我希望这个技能能做什么。",
addAttachments: "添加附件",
mode: "模式",
flashMode: "快速",
flashModeDescription: "快速且高效的完成任务,但可能不够精准",
reasoningMode: "思考",
reasoningModeDescription: "思考后再行动,在时间与准确性之间取得平衡",
proMode: "专业问答",
proModeDescription: "思考、计划再执行,获得更精准的结果,可能需要更多时间",
ultraMode: "多智能体问答",
ultraModeDescription:
"继承自专业问答模式,可调用子代理分工协作,适合复杂多步骤任务,能力最强",
reasoningEffort: "推理深度",
reasoningEffortMinimal: "最低",
reasoningEffortMinimalDescription: "检索 + 直接输出",
reasoningEffortLow: "低",
reasoningEffortLowDescription: "简单逻辑校验 + 浅层推演",
reasoningEffortMedium: "中",
reasoningEffortMediumDescription: "多层逻辑分析 + 基础验证",
reasoningEffortHigh: "高",
reasoningEffortHighDescription: "全维度逻辑推演 + 多路径验证 + 反推校验",
searchModels: "搜索模型...",
surpriseMe: "小惊喜",
surpriseMePrompt: "给我一个小惊喜吧",
followupLoading: "正在生成可能的后续问题...",
followupConfirmTitle: "发送建议问题?",
followupConfirmDescription: "当前输入框已有内容,选择发送方式。",
followupConfirmAppend: "追加并发送",
followupConfirmReplace: "替换并发送",
suggestions: [
{
suggestion: "写作",
prompt: "撰写一篇关于[主题]的博客文章",
icon: PenLineIcon,
},
{
suggestion: "研究",
prompt: "深入浅出的研究一下[主题],并总结发现。",
icon: MicroscopeIcon,
},
{
suggestion: "收集",
prompt: "从[来源]收集数据并创建报告。",
icon: ShapesIcon,
},
{
suggestion: "学习",
prompt: "学习关于[主题]并创建教程。",
icon: GraduationCapIcon,
},
],
suggestionsCreate: [
{
suggestion: "网页",
prompt: "生成一个关于[主题]的网页",
icon: CompassIcon,
},
{
suggestion: "图片",
prompt: "生成一个关于[主题]的图片",
icon: ImageIcon,
},
{
suggestion: "视频",
prompt: "生成一个关于[主题]的视频",
icon: VideoIcon,
},
{
type: "separator",
},
{
suggestion: "技能",
prompt:
"我们一起用 skill-creator 技能来创建一个技能吧。先问问我希望这个技能能做什么。",
icon: SparklesIcon,
},
],
},
// Sidebar
sidebar: {
newChat: "新对话",
chats: "对话",
recentChats: "最近的对话",
demoChats: "演示对话",
agents: "智能体",
},
// Agents
agents: {
title: "智能体",
description: "创建和管理具有专属 Prompt 与能力的自定义智能体。",
newAgent: "新建智能体",
emptyTitle: "还没有自定义智能体",
emptyDescription: "创建你的第一个自定义智能体,设置专属系统提示词。",
chat: "对话",
delete: "删除",
deleteConfirm: "确定要删除该智能体吗?此操作不可撤销。",
deleteSuccess: "智能体已删除",
newChat: "新对话",
createPageTitle: "设计你的智能体",
createPageSubtitle: "描述你想要的智能体,我来帮你通过对话创建。",
nameStepTitle: "给新智能体起个名字",
nameStepHint:
"只允许字母、数字和连字符,存储时自动转为小写(例如 code-reviewer)",
nameStepPlaceholder: "例如 code-reviewer",
nameStepContinue: "继续",
nameStepInvalidError: "名称无效,只允许字母、数字和连字符",
nameStepAlreadyExistsError: "已存在同名智能体",
nameStepNetworkError: "网络请求失败,请检查网络或后端连接",
nameStepCheckError: "无法验证名称可用性,请稍后重试",
nameStepBootstrapMessage:
"新智能体的名称是 {name},现在开始为它生成 **SOUL**。",
save: "保存智能体",
saving: "正在保存智能体...",
saveRequested:
"已提交保存请求,CM 助手 正在根据当前对话生成并保存初版智能体。",
saveHint:
"你可以在右上角的菜单里随时保存这个智能体,就算目前还只是初稿也可以。",
saveCommandMessage:
"请现在根据我们目前已经讨论的全部内容保存这个自定义智能体。这就是我明确的保存确认。如果仍有少量细节缺失,请根据上下文做出合理假设,生成一份简洁的英文初始 SOUL.md,并直接调用 setup_agent,不要再向我索要额外确认。",
agentCreatedPendingRefresh:
"智能体已创建,但 CM 助手 暂时还无法读取到它。请稍后刷新当前页面。",
more: "更多操作",
agentCreated: "智能体已创建!",
startChatting: "开始对话",
backToGallery: "返回 Gallery",
},
// Breadcrumb
breadcrumb: {
workspace: "工作区",
chats: "对话",
},
// Workspace
workspace: {
officialWebsite: "访问 CM 助手 官方网站",
githubTooltip: "访问 CM 助手 的 Github 仓库",
settingsAndMore: "设置和更多",
visitGithub: "在 Github 上查看 CM 助手",
reportIssue: "报告问题",
contactUs: "联系我们",
about: "关于 CM 助手",
},
// Conversation
conversation: {
noMessages: "还没有消息",
startConversation: "开始新的对话以查看消息",
},
// Chats
chats: {
searchChats: "搜索对话",
},
// Page titles (document title)
pages: {
appName: "CM 助手",
brandSubtitle: "Smart CM Platform",
chats: "对话",
newChat: "新对话",
untitled: "未命名",
},
// Tool calls
toolCalls: {
moreSteps: (count: number) => `查看其他 ${count} 个步骤`,
lessSteps: "隐藏步骤",
executeCommand: "执行命令",
presentFiles: "展示文件",
needYourHelp: "需要你的协助",
useTool: (toolName: string) => `使用 “${toolName}” 工具`,
searchFor: (query: string) => `搜索 “${query}”`,
searchForRelatedInfo: "搜索相关信息",
searchForRelatedImages: "搜索相关图片",
searchForRelatedImagesFor: (query: string) => `搜索相关图片 “${query}”`,
searchOnWebFor: (query: string) => `在网络上搜索 “${query}”`,
viewWebPage: "查看网页",
listFolder: "列出文件夹",
readFile: "读取文件",
writeFile: "写入文件",
clickToViewContent: "点击查看文件内容",
writeTodos: "更新 To-do 列表",
skillInstallTooltip: "安装技能并使其可在 CM 助手 中使用",
},
uploads: {
uploading: "上传中...",
uploadingFiles: "文件上传中,请稍候...",
},
subtasks: {
subtask: "子任务",
executing: (count: number) =>
`${count > 1 ? "并行" : ""}执行 ${count} 个子任务`,
in_progress: "子任务运行中",
completed: "子任务已完成",
failed: "子任务失败",
},
// Token Usage
tokenUsage: {
title: "Token 用量",
label: "Tokens",
input: "输入",
output: "输出",
total: "总计",
unavailable:
"暂无 Token 用量。只有模型成功返回且供应商提供 usage_metadata 时才会显示。",
unavailableShort: "未返回用量",
},
// Shortcuts
shortcuts: {
searchActions: "搜索操作...",
noResults: "未找到结果。",
actions: "操作",
keyboardShortcuts: "键盘快捷键",
keyboardShortcutsDescription: "使用键盘快捷键更快地操作 CM 助手。",
openCommandPalette: "打开命令面板",
toggleSidebar: "切换侧边栏",
},
// Settings
settings: {
title: "设置",
description: "根据你的偏好调整 CM 助手 的界面和行为。",
sections: {
appearance: "外观",
memory: "记忆",
tools: "工具",
skills: "技能",
notification: "通知",
about: "关于",
},
memory: {
title: "记忆",
description:
"CM 助手 会在后台不断从你的对话中自动学习。这些记忆能帮助 CM 助手 更好地理解你,并提供更个性化的体验。",
empty: "暂无可展示的记忆数据。",
rawJson: "原始 JSON",
exportButton: "导出记忆",
exportSuccess: "记忆已导出",
importButton: "导入记忆",
importConfirmTitle: "导入记忆?",
importConfirmDescription: "这会用选中的 JSON 备份覆盖当前记忆。",
importFileLabel: "已选择文件",
importInvalidFile: "读取记忆文件失败,请选择有效的 JSON 导出文件。",
importSuccess: "记忆已导入",
manualFactSource: "手动添加",
addFact: "添加事实",
addFactTitle: "添加记忆事实",
editFactTitle: "编辑记忆事实",
addFactSuccess: "事实已创建",
editFactSuccess: "事实已更新",
clearAll: "清空全部记忆",
clearAllConfirmTitle: "要清空全部记忆吗?",
clearAllConfirmDescription:
"这会删除所有已保存的摘要和事实。此操作无法撤销。",
clearAllSuccess: "已清空全部记忆",
factDeleteConfirmTitle: "要删除这条事实吗?",
factDeleteConfirmDescription:
"这条事实会立即从记忆中删除。此操作无法撤销。",
factDeleteSuccess: "事实已删除",
factContentLabel: "内容",
factCategoryLabel: "类别",
factConfidenceLabel: "置信度",
factContentPlaceholder: "描述你想保存的记忆事实",
factCategoryPlaceholder: "context",
factConfidenceHint: "请输入 0 到 1 之间的数字。",
factSave: "保存事实",
factValidationContent: "事实内容不能为空。",
factValidationConfidence: "置信度必须是 0 到 1 之间的数字。",
noFacts: "还没有保存的事实。",
summaryReadOnly:
"摘要分区当前仍为只读。现在你可以清空全部记忆或删除单条事实。",
memoryFullyEmpty: "还没有保存任何记忆。",
factPreviewLabel: "即将删除的事实",
searchPlaceholder: "搜索记忆",
filterAll: "全部",
filterFacts: "事实",
filterSummaries: "摘要",
noMatches: "没有找到匹配的记忆。",
markdown: {
overview: "概览",
userContext: "用户上下文",
work: "工作",
personal: "个人",
topOfMind: "近期关注(Top of mind)",
historyBackground: "历史背景",
recentMonths: "近几个月",
earlierContext: "更早上下文",
longTermBackground: "长期背景",
updatedAt: "更新于",
facts: "事实",
empty: "(空)",
table: {
category: "类别",
confidence: "置信度",
confidenceLevel: {
veryHigh: "极高",
high: "较高",
normal: "一般",
unknown: "未知",
},
content: "内容",
source: "来源",
createdAt: "创建时间",
view: "查看",
},
},
},
appearance: {
themeTitle: "主题",
themeDescription: "跟随系统或选择固定的界面模式。",
system: "系统",
light: "浅色",
dark: "深色",
systemDescription: "自动跟随系统主题。",
lightDescription: "更明亮的配色,适合日间使用。",
darkDescription: "更暗的配色,减少眩光方便专注。",
languageTitle: "语言",
languageDescription: "在不同语言之间切换。",
},
tools: {
title: "工具",
description: "管理 MCP 工具的配置和启用状态。",
},
skills: {
title: "技能",
description: "管理 Agent Skill 配置和启用状态。",
createSkill: "新建技能",
installSkill: "安装技能",
emptyTitle: "还没有技能",
emptyDescription:
"将你的 Agent Skill 文件夹放在 CM 助手 根目录下的 `/skills/custom` 文件夹中。",
emptyButton: "创建你的第一个技能",
installDialog: {
title: "安装技能",
dropHint: "拖拽 .zip 或 .skill 文件到此处,或者",
chooseFile: "选择文件",
validating: "正在校验文件…",
installing: "安装中…",
replace: "覆盖已有",
install: "安装",
cancel: "取消",
nameLabel: "名称",
descriptionLabel: "描述",
licenseLabel: "许可证",
toolsLabel: "允许的工具",
warningsLabel: "警告",
conflictCustom:
"已存在同名自定义技能 “{name}”。点击「覆盖已有」可替换(原启用状态保留)。",
conflictPublic: "存在同名内置技能 “{name}”,无法覆盖。",
installSuccess: "技能 “{name}” 已安装。",
installSuccessReplaced: "技能 “{name}” 已替换。",
rejectInvalidExt: "只接受 .zip 或 .skill 文件。",
},
},
notification: {
title: "通知",
description:
"CM 助手 只会在窗口不活跃时发送完成通知,特别适合长时间任务:你可以先去做别的事,完成后会收到提醒。",
requestPermission: "请求通知权限",
deniedHint:
"通知权限已被拒绝。可在浏览器的网站设置中重新开启,以接收完成提醒。",
testButton: "发送测试通知",
testTitle: "CM 助手",
testBody: "这是一条测试通知。",
notSupported: "当前浏览器不支持通知功能。",
disableNotification: "关闭通知",
},
acknowledge: {
emptyTitle: "致谢",
emptyDescription: "相关的致谢信息会展示在这里。",
},
},
};
+24 -24
View File
@@ -1,24 +1,24 @@
import { DEFAULT_LOCALE, normalizeLocale, type Locale } from "./locale";
import { getLocaleFromCookie, setLocaleInCookie } from "./cookies";
import { translations } from "./translations";
export async function detectLocaleServer(): Promise<Locale> {
return normalizeLocale(getLocaleFromCookie());
}
export async function setLocale(locale: string | Locale): Promise<Locale> {
const normalizedLocale = normalizeLocale(locale);
setLocaleInCookie(normalizedLocale);
return normalizedLocale;
}
export async function getI18n(localeOverride?: string | Locale) {
const locale = localeOverride
? normalizeLocale(localeOverride)
: await detectLocaleServer();
const t = translations[locale] ?? translations[DEFAULT_LOCALE];
return {
locale,
t,
};
}
import { DEFAULT_LOCALE, normalizeLocale, type Locale } from "./locale";
import { getLocaleFromCookie, setLocaleInCookie } from "./cookies";
import { translations } from "./translations";
export async function detectLocaleServer(): Promise<Locale> {
return normalizeLocale(getLocaleFromCookie());
}
export async function setLocale(locale: string | Locale): Promise<Locale> {
const normalizedLocale = normalizeLocale(locale);
setLocaleInCookie(normalizedLocale);
return normalizedLocale;
}
export async function getI18n(localeOverride?: string | Locale) {
const locale = localeOverride
? normalizeLocale(localeOverride)
: await detectLocaleServer();
const t = translations[locale] ?? translations[DEFAULT_LOCALE];
return {
locale,
t,
};
}
+7 -7
View File
@@ -1,7 +1,7 @@
import type { Locale } from "./locale";
import { enUS, zhCN, type Translations } from "./locales";
export const translations: Record<Locale, Translations> = {
"en-US": enUS,
"zh-CN": zhCN,
};
import type { Locale } from "./locale";
import { enUS, zhCN, type Translations } from "./locales";
export const translations: Record<Locale, Translations> = {
"en-US": enUS,
"zh-CN": zhCN,
};
+20 -20
View File
@@ -1,20 +1,20 @@
import { getBackendBaseURL } from "@/core/config";
import { apiFetch } from "@/core/api";
import type { MCPConfig } from "./types";
export async function loadMCPConfig() {
const response = await apiFetch(`${getBackendBaseURL()}/api/mcp/config`);
return response.json() as Promise<MCPConfig>;
}
export async function updateMCPConfig(config: MCPConfig) {
const response = await apiFetch(`${getBackendBaseURL()}/api/mcp/config`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(config),
});
return response.json();
}
import { getBackendBaseURL } from "@/core/config";
import { apiFetch } from "@/core/api";
import type { MCPConfig } from "./types";
export async function loadMCPConfig() {
const response = await apiFetch(`${getBackendBaseURL()}/api/mcp/config`);
return response.json() as Promise<MCPConfig>;
}
export async function updateMCPConfig(config: MCPConfig) {
const response = await apiFetch(`${getBackendBaseURL()}/api/mcp/config`, {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(config),
});
return response.json();
}
+44 -44
View File
@@ -1,44 +1,44 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { loadMCPConfig, updateMCPConfig } from "./api";
export function useMCPConfig() {
const { data, isLoading, error } = useQuery({
queryKey: ["mcpConfig"],
queryFn: () => loadMCPConfig(),
});
return { config: data, isLoading, error };
}
export function useEnableMCPServer() {
const queryClient = useQueryClient();
const { config } = useMCPConfig();
return useMutation({
mutationFn: async ({
serverName,
enabled,
}: {
serverName: string;
enabled: boolean;
}) => {
if (!config) {
throw new Error("MCP config not found");
}
if (!config.mcp_servers[serverName]) {
throw new Error(`MCP server ${serverName} not found`);
}
await updateMCPConfig({
mcp_servers: {
...config.mcp_servers,
[serverName]: {
...config.mcp_servers[serverName],
enabled,
},
},
});
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["mcpConfig"] });
},
});
}
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { loadMCPConfig, updateMCPConfig } from "./api";
export function useMCPConfig() {
const { data, isLoading, error } = useQuery({
queryKey: ["mcpConfig"],
queryFn: () => loadMCPConfig(),
});
return { config: data, isLoading, error };
}
export function useEnableMCPServer() {
const queryClient = useQueryClient();
const { config } = useMCPConfig();
return useMutation({
mutationFn: async ({
serverName,
enabled,
}: {
serverName: string;
enabled: boolean;
}) => {
if (!config) {
throw new Error("MCP config not found");
}
if (!config.mcp_servers[serverName]) {
throw new Error(`MCP server ${serverName} not found`);
}
await updateMCPConfig({
mcp_servers: {
...config.mcp_servers,
[serverName]: {
...config.mcp_servers[serverName],
enabled,
},
},
});
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["mcpConfig"] });
},
});
}
+2 -2
View File
@@ -1,2 +1,2 @@
export * from "./api";
export * from "./types";
export * from "./api";
export * from "./types";
+8 -8
View File
@@ -1,8 +1,8 @@
export interface MCPServerConfig extends Record<string, unknown> {
enabled: boolean;
description: string;
}
export interface MCPConfig {
mcp_servers: Record<string, MCPServerConfig>;
}
export interface MCPServerConfig extends Record<string, unknown> {
enabled: boolean;
description: string;
}
export interface MCPConfig {
mcp_servers: Record<string, MCPServerConfig>;
}
+149 -149
View File
@@ -1,149 +1,149 @@
import { getBackendBaseURL } from "../config";
import { apiFetch } from "../api";
import type {
MemoryFactInput,
MemoryFactPatchInput,
UserMemory,
} from "./types";
async function readMemoryResponse(
response: Response,
fallbackMessage: string,
): Promise<UserMemory> {
function formatErrorDetail(detail: unknown): string | null {
if (typeof detail === "string") {
return detail;
}
if (Array.isArray(detail)) {
const parts = detail
.map((item) => {
if (typeof item === "string") {
return item;
}
if (item && typeof item === "object") {
const record = item as Record<string, unknown>;
if (typeof record.msg === "string") {
return record.msg;
}
try {
return JSON.stringify(record);
} catch {
return null;
}
}
return String(item);
})
.filter(Boolean);
return parts.length > 0 ? parts.join("; ") : null;
}
if (detail && typeof detail === "object") {
try {
return JSON.stringify(detail);
} catch {
return null;
}
}
if (
typeof detail === "string" ||
typeof detail === "number" ||
typeof detail === "boolean" ||
typeof detail === "bigint"
) {
return String(detail);
}
if (typeof detail === "symbol") {
return detail.description ?? null;
}
return null;
}
if (!response.ok) {
const errorData = (await response.json().catch(() => ({}))) as {
detail?: unknown;
};
const detailMessage = formatErrorDetail(errorData.detail);
throw new Error(
detailMessage ?? `${fallbackMessage}: ${response.statusText}`,
);
}
return response.json() as Promise<UserMemory>;
}
export async function loadMemory(): Promise<UserMemory> {
const response = await apiFetch(`${getBackendBaseURL()}/api/memory`);
return readMemoryResponse(response, "Failed to fetch memory");
}
export async function clearMemory(): Promise<UserMemory> {
const response = await apiFetch(`${getBackendBaseURL()}/api/memory`, {
method: "DELETE",
});
return readMemoryResponse(response, "Failed to clear memory");
}
export async function deleteMemoryFact(factId: string): Promise<UserMemory> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/memory/facts/${encodeURIComponent(factId)}`,
{
method: "DELETE",
},
);
return readMemoryResponse(response, "Failed to delete memory fact");
}
export async function exportMemory(): Promise<UserMemory> {
const response = await apiFetch(`${getBackendBaseURL()}/api/memory/export`);
return readMemoryResponse(response, "Failed to export memory");
}
export async function importMemory(memory: UserMemory): Promise<UserMemory> {
const response = await apiFetch(`${getBackendBaseURL()}/api/memory/import`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(memory),
});
return readMemoryResponse(response, "Failed to import memory");
}
export async function createMemoryFact(
input: MemoryFactInput,
): Promise<UserMemory> {
const response = await apiFetch(`${getBackendBaseURL()}/api/memory/facts`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(input),
});
return readMemoryResponse(response, "Failed to create memory fact");
}
export async function updateMemoryFact(
factId: string,
input: MemoryFactPatchInput,
): Promise<UserMemory> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/memory/facts/${encodeURIComponent(factId)}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(input),
},
);
return readMemoryResponse(response, "Failed to update memory fact");
}
import { getBackendBaseURL } from "../config";
import { apiFetch } from "../api";
import type {
MemoryFactInput,
MemoryFactPatchInput,
UserMemory,
} from "./types";
async function readMemoryResponse(
response: Response,
fallbackMessage: string,
): Promise<UserMemory> {
function formatErrorDetail(detail: unknown): string | null {
if (typeof detail === "string") {
return detail;
}
if (Array.isArray(detail)) {
const parts = detail
.map((item) => {
if (typeof item === "string") {
return item;
}
if (item && typeof item === "object") {
const record = item as Record<string, unknown>;
if (typeof record.msg === "string") {
return record.msg;
}
try {
return JSON.stringify(record);
} catch {
return null;
}
}
return String(item);
})
.filter(Boolean);
return parts.length > 0 ? parts.join("; ") : null;
}
if (detail && typeof detail === "object") {
try {
return JSON.stringify(detail);
} catch {
return null;
}
}
if (
typeof detail === "string" ||
typeof detail === "number" ||
typeof detail === "boolean" ||
typeof detail === "bigint"
) {
return String(detail);
}
if (typeof detail === "symbol") {
return detail.description ?? null;
}
return null;
}
if (!response.ok) {
const errorData = (await response.json().catch(() => ({}))) as {
detail?: unknown;
};
const detailMessage = formatErrorDetail(errorData.detail);
throw new Error(
detailMessage ?? `${fallbackMessage}: ${response.statusText}`,
);
}
return response.json() as Promise<UserMemory>;
}
export async function loadMemory(): Promise<UserMemory> {
const response = await apiFetch(`${getBackendBaseURL()}/api/memory`);
return readMemoryResponse(response, "Failed to fetch memory");
}
export async function clearMemory(): Promise<UserMemory> {
const response = await apiFetch(`${getBackendBaseURL()}/api/memory`, {
method: "DELETE",
});
return readMemoryResponse(response, "Failed to clear memory");
}
export async function deleteMemoryFact(factId: string): Promise<UserMemory> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/memory/facts/${encodeURIComponent(factId)}`,
{
method: "DELETE",
},
);
return readMemoryResponse(response, "Failed to delete memory fact");
}
export async function exportMemory(): Promise<UserMemory> {
const response = await apiFetch(`${getBackendBaseURL()}/api/memory/export`);
return readMemoryResponse(response, "Failed to export memory");
}
export async function importMemory(memory: UserMemory): Promise<UserMemory> {
const response = await apiFetch(`${getBackendBaseURL()}/api/memory/import`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(memory),
});
return readMemoryResponse(response, "Failed to import memory");
}
export async function createMemoryFact(
input: MemoryFactInput,
): Promise<UserMemory> {
const response = await apiFetch(`${getBackendBaseURL()}/api/memory/facts`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(input),
});
return readMemoryResponse(response, "Failed to create memory fact");
}
export async function updateMemoryFact(
factId: string,
input: MemoryFactPatchInput,
): Promise<UserMemory> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/memory/facts/${encodeURIComponent(factId)}`,
{
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(input),
},
);
return readMemoryResponse(response, "Failed to update memory fact");
}
+84 -84
View File
@@ -1,84 +1,84 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
clearMemory,
createMemoryFact,
deleteMemoryFact,
importMemory,
loadMemory,
updateMemoryFact,
} from "./api";
import type {
MemoryFactInput,
MemoryFactPatchInput,
UserMemory,
} from "./types";
export function useMemory() {
const { data, isLoading, error } = useQuery({
queryKey: ["memory"],
queryFn: () => loadMemory(),
});
return { memory: data ?? null, isLoading, error };
}
export function useClearMemory() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: () => clearMemory(),
onSuccess: (memory) => {
queryClient.setQueryData<UserMemory>(["memory"], memory);
},
});
}
export function useDeleteMemoryFact() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (factId: string) => deleteMemoryFact(factId),
onSuccess: (memory) => {
queryClient.setQueryData<UserMemory>(["memory"], memory);
},
});
}
export function useImportMemory() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (memory: UserMemory) => importMemory(memory),
onSuccess: (memory) => {
queryClient.setQueryData<UserMemory>(["memory"], memory);
},
});
}
export function useCreateMemoryFact() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (input: MemoryFactInput) => createMemoryFact(input),
onSuccess: (memory) => {
queryClient.setQueryData<UserMemory>(["memory"], memory);
},
});
}
export function useUpdateMemoryFact() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
factId,
input,
}: {
factId: string;
input: MemoryFactPatchInput;
}) => updateMemoryFact(factId, input),
onSuccess: (memory) => {
queryClient.setQueryData<UserMemory>(["memory"], memory);
},
});
}
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import {
clearMemory,
createMemoryFact,
deleteMemoryFact,
importMemory,
loadMemory,
updateMemoryFact,
} from "./api";
import type {
MemoryFactInput,
MemoryFactPatchInput,
UserMemory,
} from "./types";
export function useMemory() {
const { data, isLoading, error } = useQuery({
queryKey: ["memory"],
queryFn: () => loadMemory(),
});
return { memory: data ?? null, isLoading, error };
}
export function useClearMemory() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: () => clearMemory(),
onSuccess: (memory) => {
queryClient.setQueryData<UserMemory>(["memory"], memory);
},
});
}
export function useDeleteMemoryFact() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (factId: string) => deleteMemoryFact(factId),
onSuccess: (memory) => {
queryClient.setQueryData<UserMemory>(["memory"], memory);
},
});
}
export function useImportMemory() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (memory: UserMemory) => importMemory(memory),
onSuccess: (memory) => {
queryClient.setQueryData<UserMemory>(["memory"], memory);
},
});
}
export function useCreateMemoryFact() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (input: MemoryFactInput) => createMemoryFact(input),
onSuccess: (memory) => {
queryClient.setQueryData<UserMemory>(["memory"], memory);
},
});
}
export function useUpdateMemoryFact() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({
factId,
input,
}: {
factId: string;
input: MemoryFactPatchInput;
}) => updateMemoryFact(factId, input),
onSuccess: (memory) => {
queryClient.setQueryData<UserMemory>(["memory"], memory);
},
});
}
+2 -2
View File
@@ -1,2 +1,2 @@
export * from "./api";
export * from "./types";
export * from "./api";
export * from "./types";
+54 -54
View File
@@ -1,54 +1,54 @@
export interface MemoryFact {
id: string;
content: string;
category: string;
confidence: number;
createdAt: string;
source: string;
}
export interface MemoryFactInput {
content: string;
category: string;
confidence: number;
}
export interface MemoryFactPatchInput {
content?: string;
category?: string;
confidence?: number;
}
export interface UserMemory {
version: string;
lastUpdated: string;
user: {
workContext: {
summary: string;
updatedAt: string;
};
personalContext: {
summary: string;
updatedAt: string;
};
topOfMind: {
summary: string;
updatedAt: string;
};
};
history: {
recentMonths: {
summary: string;
updatedAt: string;
};
earlierContext: {
summary: string;
updatedAt: string;
};
longTermBackground: {
summary: string;
updatedAt: string;
};
};
facts: MemoryFact[];
}
export interface MemoryFact {
id: string;
content: string;
category: string;
confidence: number;
createdAt: string;
source: string;
}
export interface MemoryFactInput {
content: string;
category: string;
confidence: number;
}
export interface MemoryFactPatchInput {
content?: string;
category?: string;
confidence?: number;
}
export interface UserMemory {
version: string;
lastUpdated: string;
user: {
workContext: {
summary: string;
updatedAt: string;
};
personalContext: {
summary: string;
updatedAt: string;
};
topOfMind: {
summary: string;
updatedAt: string;
};
};
history: {
recentMonths: {
summary: string;
updatedAt: string;
};
earlierContext: {
summary: string;
updatedAt: string;
};
longTermBackground: {
summary: string;
updatedAt: string;
};
};
facts: MemoryFact[];
}
+60 -60
View File
@@ -1,60 +1,60 @@
import type { Message } from "@langchain/langgraph-sdk";
export interface TokenUsage {
inputTokens: number;
outputTokens: number;
totalTokens: number;
}
/**
* Extract usage_metadata from an AI message if present.
* The field is added by the backend (PR #1218) but not typed in the SDK.
*/
export function getUsageMetadata(message: Message): TokenUsage | null {
if (message.type !== "ai") {
return null;
}
const usage = (message as Record<string, unknown>).usage_metadata as
| { input_tokens?: number; output_tokens?: number; total_tokens?: number }
| undefined;
if (!usage) {
return null;
}
return {
inputTokens: usage.input_tokens ?? 0,
outputTokens: usage.output_tokens ?? 0,
totalTokens: usage.total_tokens ?? 0,
};
}
/**
* Accumulate token usage across all AI messages in a thread.
*/
export function accumulateUsage(messages: Message[]): TokenUsage | null {
const cumulative: TokenUsage = {
inputTokens: 0,
outputTokens: 0,
totalTokens: 0,
};
let hasUsage = false;
for (const message of messages) {
const usage = getUsageMetadata(message);
if (usage) {
hasUsage = true;
cumulative.inputTokens += usage.inputTokens;
cumulative.outputTokens += usage.outputTokens;
cumulative.totalTokens += usage.totalTokens;
}
}
return hasUsage ? cumulative : null;
}
/**
* Format a token count for display: 1234 -> "1,234", 12345 -> "12.3K"
*/
export function formatTokenCount(count: number): string {
if (count < 10_000) {
return count.toLocaleString();
}
return `${(count / 1000).toFixed(1)}K`;
}
import type { Message } from "@langchain/langgraph-sdk";
export interface TokenUsage {
inputTokens: number;
outputTokens: number;
totalTokens: number;
}
/**
* Extract usage_metadata from an AI message if present.
* The field is added by the backend (PR #1218) but not typed in the SDK.
*/
export function getUsageMetadata(message: Message): TokenUsage | null {
if (message.type !== "ai") {
return null;
}
const usage = (message as Record<string, unknown>).usage_metadata as
| { input_tokens?: number; output_tokens?: number; total_tokens?: number }
| undefined;
if (!usage) {
return null;
}
return {
inputTokens: usage.input_tokens ?? 0,
outputTokens: usage.output_tokens ?? 0,
totalTokens: usage.total_tokens ?? 0,
};
}
/**
* Accumulate token usage across all AI messages in a thread.
*/
export function accumulateUsage(messages: Message[]): TokenUsage | null {
const cumulative: TokenUsage = {
inputTokens: 0,
outputTokens: 0,
totalTokens: 0,
};
let hasUsage = false;
for (const message of messages) {
const usage = getUsageMetadata(message);
if (usage) {
hasUsage = true;
cumulative.inputTokens += usage.inputTokens;
cumulative.outputTokens += usage.outputTokens;
cumulative.totalTokens += usage.totalTokens;
}
}
return hasUsage ? cumulative : null;
}
/**
* Format a token count for display: 1234 -> "1,234", 12345 -> "12.3K"
*/
export function formatTokenCount(count: number): string {
if (count < 10_000) {
return count.toLocaleString();
}
return `${(count / 1000).toFixed(1)}K`;
}
+392 -392
View File
@@ -1,392 +1,392 @@
import type { AIMessage, Message } from "@langchain/langgraph-sdk";
interface GenericMessageGroup<T = string> {
type: T;
id: string | undefined;
messages: Message[];
}
interface HumanMessageGroup extends GenericMessageGroup<"human"> {}
interface AssistantProcessingGroup extends GenericMessageGroup<"assistant:processing"> {}
interface AssistantMessageGroup extends GenericMessageGroup<"assistant"> {}
interface AssistantPresentFilesGroup extends GenericMessageGroup<"assistant:present-files"> {}
interface AssistantClarificationGroup extends GenericMessageGroup<"assistant:clarification"> {}
interface AssistantSubagentGroup extends GenericMessageGroup<"assistant:subagent"> {}
type MessageGroup =
| HumanMessageGroup
| AssistantProcessingGroup
| AssistantMessageGroup
| AssistantPresentFilesGroup
| AssistantClarificationGroup
| AssistantSubagentGroup;
export function groupMessages<T>(
messages: Message[],
mapper: (group: MessageGroup) => T,
): T[] {
if (messages.length === 0) {
return [];
}
const groups: MessageGroup[] = [];
// Returns the last group if it can still accept tool messages
// (i.e. it's an in-flight processing group, not a terminal human/assistant group).
function lastOpenGroup() {
const last = groups[groups.length - 1];
if (
last &&
last.type !== "human" &&
last.type !== "assistant" &&
last.type !== "assistant:clarification"
) {
return last;
}
return null;
}
for (const message of messages) {
if (isHiddenFromUIMessage(message)) {
continue;
}
if (message.name === "todo_reminder") {
continue;
}
if (message.type === "human") {
groups.push({ id: message.id, type: "human", messages: [message] });
continue;
}
if (message.type === "tool") {
if (isClarificationToolMessage(message)) {
// Add to the preceding processing group to preserve tool-call association,
// then also open a standalone clarification group for prominent display.
lastOpenGroup()?.messages.push(message);
groups.push({
id: message.id,
type: "assistant:clarification",
messages: [message],
});
} else {
const open = lastOpenGroup();
if (open) {
open.messages.push(message);
} else {
console.error(
"Unexpected tool message outside a processing group",
message,
);
}
}
continue;
}
if (message.type === "ai") {
if (hasPresentFiles(message)) {
groups.push({
id: message.id,
type: "assistant:present-files",
messages: [message],
});
} else if (hasSubagent(message)) {
groups.push({
id: message.id,
type: "assistant:subagent",
messages: [message],
});
} else if (hasReasoning(message) || hasToolCalls(message)) {
const lastGroup = groups[groups.length - 1];
// Accumulate consecutive intermediate AI messages into one processing group.
if (lastGroup?.type !== "assistant:processing") {
groups.push({
id: message.id,
type: "assistant:processing",
messages: [message],
});
} else {
lastGroup.messages.push(message);
}
}
// Not an else-if: a message with reasoning + content (but no tool calls) goes
// into the processing group above AND gets its own assistant bubble here.
if (hasContent(message) && !hasToolCalls(message)) {
groups.push({ id: message.id, type: "assistant", messages: [message] });
}
}
}
return groups
.map(mapper)
.filter((result) => result !== undefined && result !== null) as T[];
}
export function extractTextFromMessage(message: Message) {
if (typeof message.content === "string") {
return (
splitInlineReasoningFromAIMessage(message)?.content ??
message.content.trim()
);
}
if (Array.isArray(message.content)) {
return message.content
.map((content) => (content.type === "text" ? content.text : ""))
.join("\n")
.trim();
}
return "";
}
const THINK_TAG_RE = /<think>\s*([\s\S]*?)\s*<\/think>/g;
function splitInlineReasoning(content: string) {
const reasoningParts: string[] = [];
const cleaned = content
.replace(THINK_TAG_RE, (_, reasoning: string) => {
const normalized = reasoning.trim();
if (normalized) {
reasoningParts.push(normalized);
}
return "";
})
.trim();
return {
content: cleaned,
reasoning: reasoningParts.length > 0 ? reasoningParts.join("\n\n") : null,
};
}
function splitInlineReasoningFromAIMessage(message: Message) {
if (message.type !== "ai" || typeof message.content !== "string") {
return null;
}
return splitInlineReasoning(message.content);
}
export function extractContentFromMessage(message: Message) {
if (typeof message.content === "string") {
return (
splitInlineReasoningFromAIMessage(message)?.content ??
message.content.trim()
);
}
if (Array.isArray(message.content)) {
return message.content
.map((content) => {
switch (content.type) {
case "text":
return content.text;
case "image_url":
const imageURL = extractURLFromImageURLContent(content.image_url);
return `![image](${imageURL})`;
default:
return "";
}
})
.join("\n")
.trim();
}
return "";
}
export function extractReasoningContentFromMessage(message: Message) {
if (message.type !== "ai") {
return null;
}
if (
message.additional_kwargs &&
"reasoning_content" in message.additional_kwargs
) {
return message.additional_kwargs.reasoning_content as string | null;
}
if (Array.isArray(message.content)) {
const part = message.content[0];
if (part && "thinking" in part) {
return part.thinking as string;
}
}
if (typeof message.content === "string") {
return splitInlineReasoning(message.content).reasoning;
}
return null;
}
export function removeReasoningContentFromMessage(message: Message) {
if (message.type !== "ai" || !message.additional_kwargs) {
return;
}
delete message.additional_kwargs.reasoning_content;
}
export function extractURLFromImageURLContent(
content:
| string
| {
url: string;
},
) {
if (typeof content === "string") {
return content;
}
return content.url;
}
export function hasContent(message: Message) {
if (typeof message.content === "string") {
return (
(
splitInlineReasoningFromAIMessage(message)?.content ??
message.content.trim()
).length > 0
);
}
if (Array.isArray(message.content)) {
return message.content.length > 0;
}
return false;
}
export function hasReasoning(message: Message) {
if (message.type !== "ai") {
return false;
}
if (typeof message.additional_kwargs?.reasoning_content === "string") {
return true;
}
if (Array.isArray(message.content)) {
const part = message.content[0];
// Compatible with the Anthropic gateway
return (part as unknown as { type: "thinking" })?.type === "thinking";
}
if (typeof message.content === "string") {
return splitInlineReasoning(message.content).reasoning !== null;
}
return false;
}
export function hasToolCalls(message: Message) {
return (
message.type === "ai" && message.tool_calls && message.tool_calls.length > 0
);
}
export function hasPresentFiles(message: Message) {
return (
message.type === "ai" &&
message.tool_calls?.some((toolCall) => toolCall.name === "present_files")
);
}
export function isClarificationToolMessage(message: Message) {
return message.type === "tool" && message.name === "ask_clarification";
}
export function extractPresentFilesFromMessage(message: Message) {
if (message.type !== "ai" || !hasPresentFiles(message)) {
return [];
}
const files: string[] = [];
for (const toolCall of message.tool_calls ?? []) {
if (
toolCall.name === "present_files" &&
Array.isArray(toolCall.args.filepaths)
) {
files.push(...(toolCall.args.filepaths as string[]));
}
}
return files;
}
export function hasSubagent(message: AIMessage) {
for (const toolCall of message.tool_calls ?? []) {
if (toolCall.name === "task") {
return true;
}
}
return false;
}
export function findToolCallResult(toolCallId: string, messages: Message[]) {
for (const message of messages) {
if (message.type === "tool" && message.tool_call_id === toolCallId) {
const content = extractTextFromMessage(message);
if (content) {
return content;
}
}
}
return undefined;
}
export function isHiddenFromUIMessage(message: Message) {
return message.additional_kwargs?.hide_from_ui === true;
}
/**
* Represents a file stored in message additional_kwargs.files.
* Used for optimistic UI (uploading state) and structured file metadata.
*/
export interface FileInMessage {
filename: string;
size: number; // bytes
path?: string; // virtual path, may not be set during upload
status?: "uploading" | "uploaded";
}
/**
* Strip <uploaded_files> tag from message content.
* Returns the content with the tag removed.
*/
export function stripUploadedFilesTag(content: string): string {
return content
.replace(/<uploaded_files>[\s\S]*?<\/uploaded_files>/g, "")
.trim();
}
export function parseUploadedFiles(content: string): FileInMessage[] {
// Match <uploaded_files>...</uploaded_files> tag
const uploadedFilesRegex = /<uploaded_files>([\s\S]*?)<\/uploaded_files>/;
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const match = content.match(uploadedFilesRegex);
if (!match) {
return [];
}
const uploadedFilesContent = match[1];
// Check if it's "No files have been uploaded yet."
if (uploadedFilesContent?.includes("No files have been uploaded yet.")) {
return [];
}
// Check if the backend reported no new files were uploaded in this message
if (uploadedFilesContent?.includes("(empty)")) {
return [];
}
// Parse file list
// Format: - filename (size)\n Path: /path/to/file
const fileRegex = /- ([^\n(]+)\s*\(([^)]+)\)\s*\n\s*Path:\s*([^\n]+)/g;
const files: FileInMessage[] = [];
let fileMatch;
while ((fileMatch = fileRegex.exec(uploadedFilesContent ?? "")) !== null) {
files.push({
filename: fileMatch[1].trim(),
size: parseInt(fileMatch[2].trim(), 10) ?? 0,
path: fileMatch[3].trim(),
});
}
return files;
}
import type { AIMessage, Message } from "@langchain/langgraph-sdk";
interface GenericMessageGroup<T = string> {
type: T;
id: string | undefined;
messages: Message[];
}
interface HumanMessageGroup extends GenericMessageGroup<"human"> {}
interface AssistantProcessingGroup extends GenericMessageGroup<"assistant:processing"> {}
interface AssistantMessageGroup extends GenericMessageGroup<"assistant"> {}
interface AssistantPresentFilesGroup extends GenericMessageGroup<"assistant:present-files"> {}
interface AssistantClarificationGroup extends GenericMessageGroup<"assistant:clarification"> {}
interface AssistantSubagentGroup extends GenericMessageGroup<"assistant:subagent"> {}
type MessageGroup =
| HumanMessageGroup
| AssistantProcessingGroup
| AssistantMessageGroup
| AssistantPresentFilesGroup
| AssistantClarificationGroup
| AssistantSubagentGroup;
export function groupMessages<T>(
messages: Message[],
mapper: (group: MessageGroup) => T,
): T[] {
if (messages.length === 0) {
return [];
}
const groups: MessageGroup[] = [];
// Returns the last group if it can still accept tool messages
// (i.e. it's an in-flight processing group, not a terminal human/assistant group).
function lastOpenGroup() {
const last = groups[groups.length - 1];
if (
last &&
last.type !== "human" &&
last.type !== "assistant" &&
last.type !== "assistant:clarification"
) {
return last;
}
return null;
}
for (const message of messages) {
if (isHiddenFromUIMessage(message)) {
continue;
}
if (message.name === "todo_reminder") {
continue;
}
if (message.type === "human") {
groups.push({ id: message.id, type: "human", messages: [message] });
continue;
}
if (message.type === "tool") {
if (isClarificationToolMessage(message)) {
// Add to the preceding processing group to preserve tool-call association,
// then also open a standalone clarification group for prominent display.
lastOpenGroup()?.messages.push(message);
groups.push({
id: message.id,
type: "assistant:clarification",
messages: [message],
});
} else {
const open = lastOpenGroup();
if (open) {
open.messages.push(message);
} else {
console.error(
"Unexpected tool message outside a processing group",
message,
);
}
}
continue;
}
if (message.type === "ai") {
if (hasPresentFiles(message)) {
groups.push({
id: message.id,
type: "assistant:present-files",
messages: [message],
});
} else if (hasSubagent(message)) {
groups.push({
id: message.id,
type: "assistant:subagent",
messages: [message],
});
} else if (hasReasoning(message) || hasToolCalls(message)) {
const lastGroup = groups[groups.length - 1];
// Accumulate consecutive intermediate AI messages into one processing group.
if (lastGroup?.type !== "assistant:processing") {
groups.push({
id: message.id,
type: "assistant:processing",
messages: [message],
});
} else {
lastGroup.messages.push(message);
}
}
// Not an else-if: a message with reasoning + content (but no tool calls) goes
// into the processing group above AND gets its own assistant bubble here.
if (hasContent(message) && !hasToolCalls(message)) {
groups.push({ id: message.id, type: "assistant", messages: [message] });
}
}
}
return groups
.map(mapper)
.filter((result) => result !== undefined && result !== null) as T[];
}
export function extractTextFromMessage(message: Message) {
if (typeof message.content === "string") {
return (
splitInlineReasoningFromAIMessage(message)?.content ??
message.content.trim()
);
}
if (Array.isArray(message.content)) {
return message.content
.map((content) => (content.type === "text" ? content.text : ""))
.join("\n")
.trim();
}
return "";
}
const THINK_TAG_RE = /<think>\s*([\s\S]*?)\s*<\/think>/g;
function splitInlineReasoning(content: string) {
const reasoningParts: string[] = [];
const cleaned = content
.replace(THINK_TAG_RE, (_, reasoning: string) => {
const normalized = reasoning.trim();
if (normalized) {
reasoningParts.push(normalized);
}
return "";
})
.trim();
return {
content: cleaned,
reasoning: reasoningParts.length > 0 ? reasoningParts.join("\n\n") : null,
};
}
function splitInlineReasoningFromAIMessage(message: Message) {
if (message.type !== "ai" || typeof message.content !== "string") {
return null;
}
return splitInlineReasoning(message.content);
}
export function extractContentFromMessage(message: Message) {
if (typeof message.content === "string") {
return (
splitInlineReasoningFromAIMessage(message)?.content ??
message.content.trim()
);
}
if (Array.isArray(message.content)) {
return message.content
.map((content) => {
switch (content.type) {
case "text":
return content.text;
case "image_url":
const imageURL = extractURLFromImageURLContent(content.image_url);
return `![image](${imageURL})`;
default:
return "";
}
})
.join("\n")
.trim();
}
return "";
}
export function extractReasoningContentFromMessage(message: Message) {
if (message.type !== "ai") {
return null;
}
if (
message.additional_kwargs &&
"reasoning_content" in message.additional_kwargs
) {
return message.additional_kwargs.reasoning_content as string | null;
}
if (Array.isArray(message.content)) {
const part = message.content[0];
if (part && "thinking" in part) {
return part.thinking as string;
}
}
if (typeof message.content === "string") {
return splitInlineReasoning(message.content).reasoning;
}
return null;
}
export function removeReasoningContentFromMessage(message: Message) {
if (message.type !== "ai" || !message.additional_kwargs) {
return;
}
delete message.additional_kwargs.reasoning_content;
}
export function extractURLFromImageURLContent(
content:
| string
| {
url: string;
},
) {
if (typeof content === "string") {
return content;
}
return content.url;
}
export function hasContent(message: Message) {
if (typeof message.content === "string") {
return (
(
splitInlineReasoningFromAIMessage(message)?.content ??
message.content.trim()
).length > 0
);
}
if (Array.isArray(message.content)) {
return message.content.length > 0;
}
return false;
}
export function hasReasoning(message: Message) {
if (message.type !== "ai") {
return false;
}
if (typeof message.additional_kwargs?.reasoning_content === "string") {
return true;
}
if (Array.isArray(message.content)) {
const part = message.content[0];
// Compatible with the Anthropic gateway
return (part as unknown as { type: "thinking" })?.type === "thinking";
}
if (typeof message.content === "string") {
return splitInlineReasoning(message.content).reasoning !== null;
}
return false;
}
export function hasToolCalls(message: Message) {
return (
message.type === "ai" && message.tool_calls && message.tool_calls.length > 0
);
}
export function hasPresentFiles(message: Message) {
return (
message.type === "ai" &&
message.tool_calls?.some((toolCall) => toolCall.name === "present_files")
);
}
export function isClarificationToolMessage(message: Message) {
return message.type === "tool" && message.name === "ask_clarification";
}
export function extractPresentFilesFromMessage(message: Message) {
if (message.type !== "ai" || !hasPresentFiles(message)) {
return [];
}
const files: string[] = [];
for (const toolCall of message.tool_calls ?? []) {
if (
toolCall.name === "present_files" &&
Array.isArray(toolCall.args.filepaths)
) {
files.push(...(toolCall.args.filepaths as string[]));
}
}
return files;
}
export function hasSubagent(message: AIMessage) {
for (const toolCall of message.tool_calls ?? []) {
if (toolCall.name === "task") {
return true;
}
}
return false;
}
export function findToolCallResult(toolCallId: string, messages: Message[]) {
for (const message of messages) {
if (message.type === "tool" && message.tool_call_id === toolCallId) {
const content = extractTextFromMessage(message);
if (content) {
return content;
}
}
}
return undefined;
}
export function isHiddenFromUIMessage(message: Message) {
return message.additional_kwargs?.hide_from_ui === true;
}
/**
* Represents a file stored in message additional_kwargs.files.
* Used for optimistic UI (uploading state) and structured file metadata.
*/
export interface FileInMessage {
filename: string;
size: number; // bytes
path?: string; // virtual path, may not be set during upload
status?: "uploading" | "uploaded";
}
/**
* Strip <uploaded_files> tag from message content.
* Returns the content with the tag removed.
*/
export function stripUploadedFilesTag(content: string): string {
return content
.replace(/<uploaded_files>[\s\S]*?<\/uploaded_files>/g, "")
.trim();
}
export function parseUploadedFiles(content: string): FileInMessage[] {
// Match <uploaded_files>...</uploaded_files> tag
const uploadedFilesRegex = /<uploaded_files>([\s\S]*?)<\/uploaded_files>/;
// eslint-disable-next-line @typescript-eslint/prefer-regexp-exec
const match = content.match(uploadedFilesRegex);
if (!match) {
return [];
}
const uploadedFilesContent = match[1];
// Check if it's "No files have been uploaded yet."
if (uploadedFilesContent?.includes("No files have been uploaded yet.")) {
return [];
}
// Check if the backend reported no new files were uploaded in this message
if (uploadedFilesContent?.includes("(empty)")) {
return [];
}
// Parse file list
// Format: - filename (size)\n Path: /path/to/file
const fileRegex = /- ([^\n(]+)\s*\(([^)]+)\)\s*\n\s*Path:\s*([^\n]+)/g;
const files: FileInMessage[] = [];
let fileMatch;
while ((fileMatch = fileRegex.exec(uploadedFilesContent ?? "")) !== null) {
files.push({
filename: fileMatch[1].trim(),
size: parseInt(fileMatch[2].trim(), 10) ?? 0,
path: fileMatch[3].trim(),
});
}
return files;
}
+13 -13
View File
@@ -1,13 +1,13 @@
import { getBackendBaseURL } from "../config";
import { apiFetch } from "../api";
import type { ModelsResponse } from "./types";
export async function loadModels(): Promise<ModelsResponse> {
const res = await apiFetch(`${getBackendBaseURL()}/api/models`);
const data = (await res.json()) as Partial<ModelsResponse>;
return {
models: data.models ?? [],
token_usage: data.token_usage ?? { enabled: false },
};
}
import { getBackendBaseURL } from "../config";
import { apiFetch } from "../api";
import type { ModelsResponse } from "./types";
export async function loadModels(): Promise<ModelsResponse> {
const res = await apiFetch(`${getBackendBaseURL()}/api/models`);
const data = (await res.json()) as Partial<ModelsResponse>;
return {
models: data.models ?? [],
token_usage: data.token_usage ?? { enabled: false },
};
}
+18 -18
View File
@@ -1,18 +1,18 @@
import { useQuery } from "@tanstack/react-query";
import { loadModels } from "./api";
export function useModels({ enabled = true }: { enabled?: boolean } = {}) {
const { data, isLoading, error } = useQuery({
queryKey: ["models"],
queryFn: () => loadModels(),
enabled,
refetchOnWindowFocus: false,
});
return {
models: data?.models ?? [],
tokenUsageEnabled: data?.token_usage.enabled ?? false,
isLoading,
error,
};
}
import { useQuery } from "@tanstack/react-query";
import { loadModels } from "./api";
export function useModels({ enabled = true }: { enabled?: boolean } = {}) {
const { data, isLoading, error } = useQuery({
queryKey: ["models"],
queryFn: () => loadModels(),
enabled,
refetchOnWindowFocus: false,
});
return {
models: data?.models ?? [],
tokenUsageEnabled: data?.token_usage.enabled ?? false,
isLoading,
error,
};
}
+2 -2
View File
@@ -1,2 +1,2 @@
export * from "./api";
export * from "./types";
export * from "./api";
export * from "./types";
+18 -18
View File
@@ -1,18 +1,18 @@
export interface Model {
id: string;
name: string;
model: string;
display_name: string;
description?: string | null;
supports_thinking?: boolean;
supports_reasoning_effort?: boolean;
}
export interface TokenUsageSettings {
enabled: boolean;
}
export interface ModelsResponse {
models: Model[];
token_usage: TokenUsageSettings;
}
export interface Model {
id: string;
name: string;
model: string;
display_name: string;
description?: string | null;
supports_thinking?: boolean;
supports_reasoning_effort?: boolean;
}
export interface TokenUsageSettings {
enabled: boolean;
}
export interface ModelsResponse {
models: Model[];
token_usage: TokenUsageSettings;
}
+98 -98
View File
@@ -1,98 +1,98 @@
import { useState, useEffect, useCallback, useRef } from "react";
import { useLocalSettings } from "../settings";
interface NotificationOptions {
body?: string;
icon?: string;
badge?: string;
tag?: string;
data?: unknown;
requireInteraction?: boolean;
silent?: boolean;
}
interface UseNotificationReturn {
permission: NotificationPermission;
isSupported: boolean;
requestPermission: () => Promise<NotificationPermission>;
showNotification: (title: string, options?: NotificationOptions) => void;
}
export function useNotification(): UseNotificationReturn {
const [permission, setPermission] =
useState<NotificationPermission>("default");
const [isSupported, setIsSupported] = useState(false);
const lastNotificationTime = useRef<Date>(new Date());
useEffect(() => {
// Check if browser supports Notification API
if ("Notification" in window) {
setIsSupported(true);
setPermission(Notification.permission);
}
}, []);
const requestPermission =
useCallback(async (): Promise<NotificationPermission> => {
if (!isSupported) {
console.warn("Notification API is not supported in this browser");
return "denied";
}
const result = await Notification.requestPermission();
setPermission(result);
return result;
}, [isSupported]);
const [settings] = useLocalSettings();
const showNotification = useCallback(
(title: string, options?: NotificationOptions) => {
if (!isSupported) {
console.warn("Notification API is not supported");
return;
}
if (!settings.notification.enabled) {
console.warn("Notification is disabled");
return;
}
if (
new Date().getTime() - lastNotificationTime.current.getTime() <
1000
) {
console.warn("Notification sent too soon");
return;
}
lastNotificationTime.current = new Date();
if (permission !== "granted") {
console.warn("Notification permission not granted");
return;
}
const notification = new Notification(title, options);
// Optional: Add event listeners
notification.onclick = () => {
window.focus();
notification.close();
};
notification.onerror = (error) => {
console.error("Notification error:", error);
};
},
[isSupported, settings.notification.enabled, permission],
);
return {
permission,
isSupported,
requestPermission,
showNotification,
};
}
import { useState, useEffect, useCallback, useRef } from "react";
import { useLocalSettings } from "../settings";
interface NotificationOptions {
body?: string;
icon?: string;
badge?: string;
tag?: string;
data?: unknown;
requireInteraction?: boolean;
silent?: boolean;
}
interface UseNotificationReturn {
permission: NotificationPermission;
isSupported: boolean;
requestPermission: () => Promise<NotificationPermission>;
showNotification: (title: string, options?: NotificationOptions) => void;
}
export function useNotification(): UseNotificationReturn {
const [permission, setPermission] =
useState<NotificationPermission>("default");
const [isSupported, setIsSupported] = useState(false);
const lastNotificationTime = useRef<Date>(new Date());
useEffect(() => {
// Check if browser supports Notification API
if ("Notification" in window) {
setIsSupported(true);
setPermission(Notification.permission);
}
}, []);
const requestPermission =
useCallback(async (): Promise<NotificationPermission> => {
if (!isSupported) {
console.warn("Notification API is not supported in this browser");
return "denied";
}
const result = await Notification.requestPermission();
setPermission(result);
return result;
}, [isSupported]);
const [settings] = useLocalSettings();
const showNotification = useCallback(
(title: string, options?: NotificationOptions) => {
if (!isSupported) {
console.warn("Notification API is not supported");
return;
}
if (!settings.notification.enabled) {
console.warn("Notification is disabled");
return;
}
if (
new Date().getTime() - lastNotificationTime.current.getTime() <
1000
) {
console.warn("Notification sent too soon");
return;
}
lastNotificationTime.current = new Date();
if (permission !== "granted") {
console.warn("Notification permission not granted");
return;
}
const notification = new Notification(title, options);
// Optional: Add event listeners
notification.onclick = () => {
window.focus();
notification.close();
};
notification.onerror = (error) => {
console.error("Notification error:", error);
};
},
[isSupported, settings.notification.enabled, permission],
);
return {
permission,
isSupported,
requestPermission,
showNotification,
};
}
+56 -56
View File
@@ -1,56 +1,56 @@
import type { Element, Root, ElementContent } from "hast";
import { useMemo } from "react";
import { visit } from "unist-util-visit";
import type { BuildVisitor } from "unist-util-visit";
const CJK_TEXT_RE =
/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
export function rehypeSplitWordsIntoSpans() {
return (tree: Root) => {
visit(tree, "element", ((node: Element) => {
if (
["p", "h1", "h2", "h3", "h4", "h5", "h6", "li", "strong"].includes(
node.tagName,
) &&
node.children
) {
const newChildren: Array<ElementContent> = [];
node.children.forEach((child) => {
if (child.type === "text") {
if (CJK_TEXT_RE.test(child.value)) {
newChildren.push(child);
return;
}
const segmenter = new Intl.Segmenter("zh", { granularity: "word" });
const segments = segmenter.segment(child.value);
const words = Array.from(segments)
.map((segment) => segment.segment)
.filter(Boolean);
words.forEach((word: string) => {
newChildren.push({
type: "element",
tagName: "span",
properties: {
className: "animate-fade-in",
},
children: [{ type: "text", value: word }],
});
});
} else {
newChildren.push(child);
}
});
node.children = newChildren;
}
}) as BuildVisitor<Root, "element">);
};
}
export function useRehypeSplitWordsIntoSpans(enabled = true) {
const rehypePlugins = useMemo(
() => (enabled ? [rehypeSplitWordsIntoSpans] : []),
[enabled],
);
return rehypePlugins;
}
import type { Element, Root, ElementContent } from "hast";
import { useMemo } from "react";
import { visit } from "unist-util-visit";
import type { BuildVisitor } from "unist-util-visit";
const CJK_TEXT_RE =
/[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
export function rehypeSplitWordsIntoSpans() {
return (tree: Root) => {
visit(tree, "element", ((node: Element) => {
if (
["p", "h1", "h2", "h3", "h4", "h5", "h6", "li", "strong"].includes(
node.tagName,
) &&
node.children
) {
const newChildren: Array<ElementContent> = [];
node.children.forEach((child) => {
if (child.type === "text") {
if (CJK_TEXT_RE.test(child.value)) {
newChildren.push(child);
return;
}
const segmenter = new Intl.Segmenter("zh", { granularity: "word" });
const segments = segmenter.segment(child.value);
const words = Array.from(segments)
.map((segment) => segment.segment)
.filter(Boolean);
words.forEach((word: string) => {
newChildren.push({
type: "element",
tagName: "span",
properties: {
className: "animate-fade-in",
},
children: [{ type: "text", value: word }],
});
});
} else {
newChildren.push(child);
}
});
node.children = newChildren;
}
}) as BuildVisitor<Root, "element">);
};
}
export function useRehypeSplitWordsIntoSpans(enabled = true) {
const rehypePlugins = useMemo(
() => (enabled ? [rehypeSplitWordsIntoSpans] : []),
[enabled],
);
return rehypePlugins;
}
@@ -7,6 +7,7 @@ import type {
ScheduledTaskDeliveryProfile,
ScheduledTaskResultFileContent,
ScheduledTaskRun,
ScheduledTaskRunFileUpdateResponse,
ScheduledTaskSubscription,
SchedulerThread,
} from "./types";
@@ -81,6 +82,20 @@ export async function getScheduledTaskRunFileContent(runId: string, fileIndex: n
);
}
export async function updateScheduledTaskRunFile(
runId: string,
fileIndex: number,
content: string,
) {
return parseResponse<ScheduledTaskRunFileUpdateResponse>(
await apiFetch(`${baseUrl()}/runs/${encodeURIComponent(runId)}/files/${fileIndex}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ content }),
}),
);
}
function filenameFromContentDisposition(header: string | null): string | null {
if (!header) return null;
const star = /filename\*=(?:UTF-8'')?([^;]+)/i.exec(header);
@@ -1,3 +1,3 @@
export * from "./api";
export * from "./hooks";
export * from "./types";
export * from "./api";
export * from "./hooks";
export * from "./types";
@@ -0,0 +1,274 @@
/**
* Convert markdown text to a Word (.docx) Blob in the browser.
*
* Implementation notes:
* - Uses the `docx` npm package to construct an OOXML document client-side.
* - Parser is intentionally lightweight: it covers the markdown features that
* scheduled-task agent reports actually emit — ATX headings, paragraphs,
* ordered/unordered lists, fenced code blocks, blockquotes, horizontal
* rules, and inline `**bold**` / `*italic*` / `` `code` `` runs.
* - We deliberately do NOT reach for a full markdown AST library (remark/
* unified) to keep the bundle small. Edge cases (tables, footnotes, html)
* degrade to plain text rather than failing loudly.
*/
import {
AlignmentType,
Document,
HeadingLevel,
Packer,
Paragraph,
TextRun,
type IRunOptions,
} from "docx";
const HEADING_LEVELS = [
HeadingLevel.HEADING_1,
HeadingLevel.HEADING_2,
HeadingLevel.HEADING_3,
HeadingLevel.HEADING_4,
HeadingLevel.HEADING_5,
HeadingLevel.HEADING_6,
];
type InlineSegment = { text: string; bold?: boolean; italic?: boolean; code?: boolean };
/**
* Tokenise a single line of markdown into formatted segments.
*
* Recognised inline syntax:
* `code`, **bold**, __bold__, *italic*, _italic_
* Order matters: code spans win over emphasis so backticks don't get parsed
* as italic delimiters.
*/
function parseInlineSegments(text: string): InlineSegment[] {
const tokens: InlineSegment[] = [];
const pattern = /(`+)([^`]+)\1|\*\*([^*]+)\*\*|__([^_]+)__|\*([^*]+)\*|_([^_]+)_/g;
let cursor = 0;
let match: RegExpExecArray | null;
while ((match = pattern.exec(text)) !== null) {
if (match.index > cursor) {
tokens.push({ text: text.slice(cursor, match.index) });
}
if (match[2] !== undefined) {
tokens.push({ text: match[2], code: true });
} else if (match[3] !== undefined) {
tokens.push({ text: match[3], bold: true });
} else if (match[4] !== undefined) {
tokens.push({ text: match[4], bold: true });
} else if (match[5] !== undefined) {
tokens.push({ text: match[5], italic: true });
} else if (match[6] !== undefined) {
tokens.push({ text: match[6], italic: true });
}
cursor = pattern.lastIndex;
}
if (cursor < text.length) {
tokens.push({ text: text.slice(cursor) });
}
return tokens.length > 0 ? tokens : [{ text }];
}
function segmentsToRuns(segments: InlineSegment[], extra?: Partial<IRunOptions>): TextRun[] {
return segments.map((seg) => {
const opts: IRunOptions = {
text: seg.text,
bold: seg.bold,
italics: seg.italic,
...extra,
};
if (seg.code) {
opts.font = { name: "Consolas" };
}
return new TextRun(opts);
});
}
function makeParagraphFromInline(text: string): Paragraph {
return new Paragraph({
children: segmentsToRuns(parseInlineSegments(text)),
});
}
function makeHeadingParagraph(level: number, text: string): Paragraph {
return new Paragraph({
heading: HEADING_LEVELS[Math.min(level, HEADING_LEVELS.length) - 1],
children: segmentsToRuns(parseInlineSegments(text)),
});
}
function makeListItem(text: string, ordered: boolean, level: number): Paragraph {
return new Paragraph({
children: segmentsToRuns(parseInlineSegments(text)),
numbering: ordered
? { reference: "ordered-list", level: Math.min(level, 8) }
: undefined,
bullet: ordered ? undefined : { level: Math.min(level, 8) },
});
}
function makeCodeParagraph(line: string): Paragraph {
return new Paragraph({
children: [
new TextRun({
text: line || " ",
font: { name: "Consolas" },
}),
],
});
}
function makeQuoteParagraph(text: string): Paragraph {
return new Paragraph({
children: segmentsToRuns(parseInlineSegments(text), { italics: true }),
indent: { left: 720 },
});
}
function makeHorizontalRule(): Paragraph {
return new Paragraph({
alignment: AlignmentType.CENTER,
children: [new TextRun({ text: "────────" })],
});
}
/**
* Convert markdown text into an array of docx Paragraph objects.
*
* Block grammar handled (line-by-line):
* - ATX heading: `^(#{1,6})\s+(.*)$`
* - Fenced code: lines between ``` ``` are emitted verbatim
* - Blockquote: `^>\s?(.*)$`
* - Ordered list: `^\s*(\d+)\.\s+(.*)$`
* - Unordered list: `^\s*[-*+]\s+(.*)$`
* - Horizontal rule: `^(---|\*\*\*|___)\s*$`
* - Blank line: paragraph break
* - Anything else: paragraph (with inline formatting)
*/
function markdownToParagraphs(markdown: string): Paragraph[] {
const lines = markdown.replace(/\r\n/g, "\n").split("\n");
const paragraphs: Paragraph[] = [];
let inFence = false;
let paragraphBuffer: string[] = [];
const flushParagraph = () => {
if (paragraphBuffer.length === 0) return;
paragraphs.push(makeParagraphFromInline(paragraphBuffer.join(" ")));
paragraphBuffer = [];
};
for (const rawLine of lines) {
const line = rawLine.replace(/\t/g, " ");
if (line.trim().startsWith("```")) {
flushParagraph();
inFence = !inFence;
continue;
}
if (inFence) {
paragraphs.push(makeCodeParagraph(line));
continue;
}
if (!line.trim()) {
flushParagraph();
continue;
}
const heading = /^(#{1,6})\s+(.*)$/.exec(line);
if (heading) {
flushParagraph();
paragraphs.push(makeHeadingParagraph(heading[1].length, heading[2].trim()));
continue;
}
if (/^(?:---|\*\*\*|___)\s*$/.test(line)) {
flushParagraph();
paragraphs.push(makeHorizontalRule());
continue;
}
const blockquote = /^>\s?(.*)$/.exec(line);
if (blockquote) {
flushParagraph();
paragraphs.push(makeQuoteParagraph(blockquote[1]));
continue;
}
const orderedItem = /^(\s*)(\d+)\.\s+(.*)$/.exec(line);
if (orderedItem) {
flushParagraph();
const indent = Math.floor(orderedItem[1].length / 2);
paragraphs.push(makeListItem(orderedItem[3], true, indent));
continue;
}
const unorderedItem = /^(\s*)[-*+]\s+(.*)$/.exec(line);
if (unorderedItem) {
flushParagraph();
const indent = Math.floor(unorderedItem[1].length / 2);
paragraphs.push(makeListItem(unorderedItem[2], false, indent));
continue;
}
paragraphBuffer.push(line.trim());
}
flushParagraph();
return paragraphs;
}
/**
* Convert a markdown string into a .docx Blob suitable for download.
*/
export async function markdownToDocxBlob(markdown: string, title?: string): Promise<Blob> {
const children: Paragraph[] = [];
if (title?.trim()) {
children.push(
new Paragraph({
heading: HeadingLevel.TITLE,
children: [new TextRun({ text: title.trim(), bold: true })],
}),
);
}
children.push(...markdownToParagraphs(markdown));
const doc = new Document({
numbering: {
config: [
{
reference: "ordered-list",
levels: [
{ level: 0, format: "decimal", text: "%1.", alignment: AlignmentType.START },
{ level: 1, format: "decimal", text: "%2.", alignment: AlignmentType.START },
{ level: 2, format: "decimal", text: "%3.", alignment: AlignmentType.START },
],
},
],
},
sections: [{ children }],
});
return Packer.toBlob(doc);
}
/**
* Trigger a browser download of the markdown source converted to .docx.
*/
export async function downloadMarkdownAsDocx(
markdown: string,
fileName: string,
title?: string,
): Promise<void> {
const blob = await markdownToDocxBlob(markdown, title);
const safeName = fileName.replace(/\.(md|markdown)$/i, "") || "document";
const url = URL.createObjectURL(blob);
const anchor = document.createElement("a");
anchor.href = url;
anchor.download = `${safeName}.docx`;
anchor.rel = "noopener";
document.body.appendChild(anchor);
anchor.click();
anchor.remove();
window.setTimeout(() => URL.revokeObjectURL(url), 30_000);
}
@@ -89,4 +89,13 @@ export type ScheduledTaskRun = {
result?: ScheduledTaskRunResult | null;
created_at?: string | null;
updated_at?: string | null;
can_edit?: boolean;
};
export type ScheduledTaskRunFileUpdateResponse = {
index: number;
name: string;
size: number;
mime_type?: string | null;
kind?: string | null;
};
+59 -59
View File
@@ -1,59 +1,59 @@
import { useCallback, useMemo, useSyncExternalStore } from "react";
import {
DEFAULT_LOCAL_SETTINGS,
applyThreadModelOverride,
type LocalSettings,
} from "./local";
import {
getBaseSettingsSnapshot,
getThreadModelSnapshot,
subscribe,
updateLocalSettings,
updateThreadSettings,
type LocalSettingsSetter,
} from "./store";
export function useLocalSettings(): [LocalSettings, LocalSettingsSetter] {
const settings = useSyncExternalStore(
subscribe,
getBaseSettingsSnapshot,
() => DEFAULT_LOCAL_SETTINGS,
);
const setSettings = useCallback<LocalSettingsSetter>((key, value) => {
updateLocalSettings(key, value);
}, []);
return [settings, setSettings];
}
export function useThreadSettings(
threadId: string,
): [LocalSettings, LocalSettingsSetter] {
const baseSettings = useSyncExternalStore(
subscribe,
getBaseSettingsSnapshot,
() => DEFAULT_LOCAL_SETTINGS,
);
const threadModelName = useSyncExternalStore(
subscribe,
() => getThreadModelSnapshot(threadId),
() => undefined,
);
const settings = useMemo(
() => applyThreadModelOverride(baseSettings, threadModelName),
[baseSettings, threadModelName],
);
const setSettings = useCallback<LocalSettingsSetter>(
(key, value) => {
updateThreadSettings(threadId, key, value);
},
[threadId],
);
return [settings, setSettings];
}
import { useCallback, useMemo, useSyncExternalStore } from "react";
import {
DEFAULT_LOCAL_SETTINGS,
applyThreadModelOverride,
type LocalSettings,
} from "./local";
import {
getBaseSettingsSnapshot,
getThreadModelSnapshot,
subscribe,
updateLocalSettings,
updateThreadSettings,
type LocalSettingsSetter,
} from "./store";
export function useLocalSettings(): [LocalSettings, LocalSettingsSetter] {
const settings = useSyncExternalStore(
subscribe,
getBaseSettingsSnapshot,
() => DEFAULT_LOCAL_SETTINGS,
);
const setSettings = useCallback<LocalSettingsSetter>((key, value) => {
updateLocalSettings(key, value);
}, []);
return [settings, setSettings];
}
export function useThreadSettings(
threadId: string,
): [LocalSettings, LocalSettingsSetter] {
const baseSettings = useSyncExternalStore(
subscribe,
getBaseSettingsSnapshot,
() => DEFAULT_LOCAL_SETTINGS,
);
const threadModelName = useSyncExternalStore(
subscribe,
() => getThreadModelSnapshot(threadId),
() => undefined,
);
const settings = useMemo(
() => applyThreadModelOverride(baseSettings, threadModelName),
[baseSettings, threadModelName],
);
const setSettings = useCallback<LocalSettingsSetter>(
(key, value) => {
updateThreadSettings(threadId, key, value);
},
[threadId],
);
return [settings, setSettings];
}
+2 -2
View File
@@ -1,2 +1,2 @@
export { useLocalSettings, useThreadSettings } from "./hooks";
export type { LocalSettings } from "./local";
export { useLocalSettings, useThreadSettings } from "./hooks";
export type { LocalSettings } from "./local";
+115 -115
View File
@@ -1,115 +1,115 @@
import type { AgentThreadContext } from "../threads";
export const DEFAULT_LOCAL_SETTINGS: LocalSettings = {
notification: {
enabled: true,
},
context: {
model_name: undefined,
mode: undefined,
reasoning_effort: undefined,
},
};
export const LOCAL_SETTINGS_KEY = "deerflow.local-settings";
export const THREAD_MODEL_KEY_PREFIX = "deerflow.thread-model.";
function isBrowser(): boolean {
return typeof window !== "undefined";
}
export interface LocalSettings {
notification: {
enabled: boolean;
};
context: Omit<
AgentThreadContext,
| "thread_id"
| "is_plan_mode"
| "thinking_enabled"
| "subagent_enabled"
| "model_name"
| "reasoning_effort"
> & {
model_name?: string | undefined;
mode: "flash" | "thinking" | "pro" | "ultra" | undefined;
reasoning_effort?: "minimal" | "low" | "medium" | "high";
};
}
function mergeLocalSettings(settings?: Partial<LocalSettings>): LocalSettings {
return {
...DEFAULT_LOCAL_SETTINGS,
context: {
...DEFAULT_LOCAL_SETTINGS.context,
...settings?.context,
},
notification: {
...DEFAULT_LOCAL_SETTINGS.notification,
...settings?.notification,
},
};
}
function getThreadModelStorageKey(threadId: string): string {
return `${THREAD_MODEL_KEY_PREFIX}${threadId}`;
}
export function getThreadModelName(threadId: string): string | undefined {
if (!isBrowser()) {
return undefined;
}
return localStorage.getItem(getThreadModelStorageKey(threadId)) ?? undefined;
}
export function saveThreadModelName(
threadId: string,
modelName: string | undefined,
) {
if (!isBrowser()) {
return;
}
const key = getThreadModelStorageKey(threadId);
if (!modelName) {
localStorage.removeItem(key);
return;
}
localStorage.setItem(key, modelName);
}
export function applyThreadModelOverride(
settings: LocalSettings,
threadModelName: string | undefined,
): LocalSettings {
if (!threadModelName) {
return settings;
}
return {
...settings,
context: {
...settings.context,
model_name: threadModelName,
},
};
}
export function getLocalSettings(): LocalSettings {
if (!isBrowser()) {
return DEFAULT_LOCAL_SETTINGS;
}
const json = localStorage.getItem(LOCAL_SETTINGS_KEY);
try {
if (json) {
const settings = JSON.parse(json) as Partial<LocalSettings>;
return mergeLocalSettings(settings);
}
} catch {}
return DEFAULT_LOCAL_SETTINGS;
}
export function saveLocalSettings(settings: LocalSettings) {
if (!isBrowser()) {
return;
}
localStorage.setItem(LOCAL_SETTINGS_KEY, JSON.stringify(settings));
}
import type { AgentThreadContext } from "../threads";
export const DEFAULT_LOCAL_SETTINGS: LocalSettings = {
notification: {
enabled: true,
},
context: {
model_name: undefined,
mode: undefined,
reasoning_effort: undefined,
},
};
export const LOCAL_SETTINGS_KEY = "deerflow.local-settings";
export const THREAD_MODEL_KEY_PREFIX = "deerflow.thread-model.";
function isBrowser(): boolean {
return typeof window !== "undefined";
}
export interface LocalSettings {
notification: {
enabled: boolean;
};
context: Omit<
AgentThreadContext,
| "thread_id"
| "is_plan_mode"
| "thinking_enabled"
| "subagent_enabled"
| "model_name"
| "reasoning_effort"
> & {
model_name?: string | undefined;
mode: "flash" | "thinking" | "pro" | "ultra" | undefined;
reasoning_effort?: "minimal" | "low" | "medium" | "high";
};
}
function mergeLocalSettings(settings?: Partial<LocalSettings>): LocalSettings {
return {
...DEFAULT_LOCAL_SETTINGS,
context: {
...DEFAULT_LOCAL_SETTINGS.context,
...settings?.context,
},
notification: {
...DEFAULT_LOCAL_SETTINGS.notification,
...settings?.notification,
},
};
}
function getThreadModelStorageKey(threadId: string): string {
return `${THREAD_MODEL_KEY_PREFIX}${threadId}`;
}
export function getThreadModelName(threadId: string): string | undefined {
if (!isBrowser()) {
return undefined;
}
return localStorage.getItem(getThreadModelStorageKey(threadId)) ?? undefined;
}
export function saveThreadModelName(
threadId: string,
modelName: string | undefined,
) {
if (!isBrowser()) {
return;
}
const key = getThreadModelStorageKey(threadId);
if (!modelName) {
localStorage.removeItem(key);
return;
}
localStorage.setItem(key, modelName);
}
export function applyThreadModelOverride(
settings: LocalSettings,
threadModelName: string | undefined,
): LocalSettings {
if (!threadModelName) {
return settings;
}
return {
...settings,
context: {
...settings.context,
model_name: threadModelName,
},
};
}
export function getLocalSettings(): LocalSettings {
if (!isBrowser()) {
return DEFAULT_LOCAL_SETTINGS;
}
const json = localStorage.getItem(LOCAL_SETTINGS_KEY);
try {
if (json) {
const settings = JSON.parse(json) as Partial<LocalSettings>;
return mergeLocalSettings(settings);
}
} catch {}
return DEFAULT_LOCAL_SETTINGS;
}
export function saveLocalSettings(settings: LocalSettings) {
if (!isBrowser()) {
return;
}
localStorage.setItem(LOCAL_SETTINGS_KEY, JSON.stringify(settings));
}
+150 -150
View File
@@ -1,150 +1,150 @@
import {
DEFAULT_LOCAL_SETTINGS,
LOCAL_SETTINGS_KEY,
THREAD_MODEL_KEY_PREFIX,
getLocalSettings,
getThreadModelName,
saveLocalSettings,
saveThreadModelName,
type LocalSettings,
} from "./local";
type Listener = () => void;
export type LocalSettingsSetter = <K extends keyof LocalSettings>(
key: K,
value: Partial<LocalSettings[K]>,
) => void;
const listeners = new Set<Listener>();
const threadModelNames = new Map<string, string | undefined>();
let baseSettings: LocalSettings = DEFAULT_LOCAL_SETTINGS;
let baseSettingsLoaded = false;
let storageListenerRegistered = false;
function emitChange() {
for (const listener of listeners) {
listener();
}
}
function ensureBaseSettingsLoaded() {
if (baseSettingsLoaded || typeof window === "undefined") {
return;
}
baseSettings = getLocalSettings();
baseSettingsLoaded = true;
}
function ensureStorageListenerRegistered() {
if (storageListenerRegistered || typeof window === "undefined") {
return;
}
window.addEventListener("storage", handleStorage);
storageListenerRegistered = true;
}
function mergeSettingsSection<K extends keyof LocalSettings>(
settings: LocalSettings,
key: K,
value: Partial<LocalSettings[K]>,
): LocalSettings {
return {
...settings,
[key]: {
...settings[key],
...value,
},
} as LocalSettings;
}
function handleStorage(event: StorageEvent) {
if (event.storageArea && event.storageArea !== localStorage) {
return;
}
ensureBaseSettingsLoaded();
if (event.key === null) {
baseSettings = getLocalSettings();
threadModelNames.clear();
emitChange();
return;
}
if (event.key === LOCAL_SETTINGS_KEY) {
baseSettings = getLocalSettings();
emitChange();
return;
}
if (!event.key.startsWith(THREAD_MODEL_KEY_PREFIX)) {
return;
}
const threadId = event.key.slice(THREAD_MODEL_KEY_PREFIX.length);
threadModelNames.set(threadId, getThreadModelName(threadId));
emitChange();
}
export function subscribe(listener: Listener): () => void {
ensureBaseSettingsLoaded();
ensureStorageListenerRegistered();
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
export function getBaseSettingsSnapshot(): LocalSettings {
ensureBaseSettingsLoaded();
return baseSettings;
}
export function getThreadModelSnapshot(threadId: string): string | undefined {
ensureBaseSettingsLoaded();
if (!threadModelNames.has(threadId)) {
threadModelNames.set(threadId, getThreadModelName(threadId));
}
return threadModelNames.get(threadId);
}
export const updateLocalSettings: LocalSettingsSetter = (key, value) => {
ensureBaseSettingsLoaded();
ensureStorageListenerRegistered();
baseSettings = mergeSettingsSection(baseSettings, key, value);
saveLocalSettings(baseSettings);
emitChange();
};
export function updateThreadSettings<K extends keyof LocalSettings>(
threadId: string,
key: K,
value: Partial<LocalSettings[K]>,
) {
ensureBaseSettingsLoaded();
ensureStorageListenerRegistered();
const nextBaseSettings = mergeSettingsSection(baseSettings, key, value);
baseSettings = nextBaseSettings;
saveLocalSettings(baseSettings);
if (
key === "context" &&
Object.prototype.hasOwnProperty.call(value, "model_name")
) {
const contextValue = value as Partial<LocalSettings["context"]>;
const threadModelName = contextValue.model_name;
threadModelNames.set(threadId, threadModelName);
saveThreadModelName(threadId, threadModelName);
}
emitChange();
}
import {
DEFAULT_LOCAL_SETTINGS,
LOCAL_SETTINGS_KEY,
THREAD_MODEL_KEY_PREFIX,
getLocalSettings,
getThreadModelName,
saveLocalSettings,
saveThreadModelName,
type LocalSettings,
} from "./local";
type Listener = () => void;
export type LocalSettingsSetter = <K extends keyof LocalSettings>(
key: K,
value: Partial<LocalSettings[K]>,
) => void;
const listeners = new Set<Listener>();
const threadModelNames = new Map<string, string | undefined>();
let baseSettings: LocalSettings = DEFAULT_LOCAL_SETTINGS;
let baseSettingsLoaded = false;
let storageListenerRegistered = false;
function emitChange() {
for (const listener of listeners) {
listener();
}
}
function ensureBaseSettingsLoaded() {
if (baseSettingsLoaded || typeof window === "undefined") {
return;
}
baseSettings = getLocalSettings();
baseSettingsLoaded = true;
}
function ensureStorageListenerRegistered() {
if (storageListenerRegistered || typeof window === "undefined") {
return;
}
window.addEventListener("storage", handleStorage);
storageListenerRegistered = true;
}
function mergeSettingsSection<K extends keyof LocalSettings>(
settings: LocalSettings,
key: K,
value: Partial<LocalSettings[K]>,
): LocalSettings {
return {
...settings,
[key]: {
...settings[key],
...value,
},
} as LocalSettings;
}
function handleStorage(event: StorageEvent) {
if (event.storageArea && event.storageArea !== localStorage) {
return;
}
ensureBaseSettingsLoaded();
if (event.key === null) {
baseSettings = getLocalSettings();
threadModelNames.clear();
emitChange();
return;
}
if (event.key === LOCAL_SETTINGS_KEY) {
baseSettings = getLocalSettings();
emitChange();
return;
}
if (!event.key.startsWith(THREAD_MODEL_KEY_PREFIX)) {
return;
}
const threadId = event.key.slice(THREAD_MODEL_KEY_PREFIX.length);
threadModelNames.set(threadId, getThreadModelName(threadId));
emitChange();
}
export function subscribe(listener: Listener): () => void {
ensureBaseSettingsLoaded();
ensureStorageListenerRegistered();
listeners.add(listener);
return () => {
listeners.delete(listener);
};
}
export function getBaseSettingsSnapshot(): LocalSettings {
ensureBaseSettingsLoaded();
return baseSettings;
}
export function getThreadModelSnapshot(threadId: string): string | undefined {
ensureBaseSettingsLoaded();
if (!threadModelNames.has(threadId)) {
threadModelNames.set(threadId, getThreadModelName(threadId));
}
return threadModelNames.get(threadId);
}
export const updateLocalSettings: LocalSettingsSetter = (key, value) => {
ensureBaseSettingsLoaded();
ensureStorageListenerRegistered();
baseSettings = mergeSettingsSection(baseSettings, key, value);
saveLocalSettings(baseSettings);
emitChange();
};
export function updateThreadSettings<K extends keyof LocalSettings>(
threadId: string,
key: K,
value: Partial<LocalSettings[K]>,
) {
ensureBaseSettingsLoaded();
ensureStorageListenerRegistered();
const nextBaseSettings = mergeSettingsSection(baseSettings, key, value);
baseSettings = nextBaseSettings;
saveLocalSettings(baseSettings);
if (
key === "context" &&
Object.prototype.hasOwnProperty.call(value, "model_name")
) {
const contextValue = value as Partial<LocalSettings["context"]>;
const threadModelName = contextValue.model_name;
threadModelNames.set(threadId, threadModelName);
saveThreadModelName(threadId, threadModelName);
}
emitChange();
}
+112 -63
View File
@@ -1,63 +1,112 @@
import { getBackendBaseURL } from "@/core/config";
import { apiFetch } from "@/core/api";
import type { Skill } from "./type";
export async function loadSkills() {
const skills = await apiFetch(`${getBackendBaseURL()}/api/skills`);
const json = await skills.json();
return json.skills as Skill[];
}
export async function enableSkill(skillName: string, enabled: boolean) {
const response = await apiFetch(
`${getBackendBaseURL()}/api/skills/${skillName}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
enabled,
}),
},
);
return response.json();
}
export interface InstallSkillRequest {
thread_id: string;
path: string;
}
export interface InstallSkillResponse {
success: boolean;
skill_name: string;
message: string;
}
export async function installSkill(
request: InstallSkillRequest,
): Promise<InstallSkillResponse> {
const response = await apiFetch(`${getBackendBaseURL()}/api/skills/install`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(request),
});
if (!response.ok) {
// Handle HTTP error responses (4xx, 5xx)
const errorData = await response.json().catch(() => ({}));
const errorMessage =
errorData.detail ?? `HTTP ${response.status}: ${response.statusText}`;
return {
success: false,
skill_name: "",
message: errorMessage,
};
}
return response.json();
}
import { getBackendBaseURL } from "@/core/config";
import { apiFetch } from "@/core/api";
import type { Skill } from "./type";
export async function loadSkills() {
const skills = await apiFetch(`${getBackendBaseURL()}/api/skills`);
const json = await skills.json();
return json.skills as Skill[];
}
export async function enableSkill(skillName: string, enabled: boolean) {
const response = await apiFetch(
`${getBackendBaseURL()}/api/skills/${skillName}`,
{
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
enabled,
}),
},
);
return response.json();
}
export interface InstallSkillRequest {
thread_id: string;
path: string;
}
export interface InstallSkillResponse {
success: boolean;
skill_name: string;
message: string;
overwritten?: boolean;
}
export interface ValidateSkillUploadResponse {
ok: boolean;
skill_name: string;
description: string;
license: string | null;
allowed_tools: string[];
conflict: boolean;
conflict_kind: "public" | "custom" | null;
warnings: string[];
}
export async function installSkill(
request: InstallSkillRequest,
): Promise<InstallSkillResponse> {
const response = await apiFetch(`${getBackendBaseURL()}/api/skills/install`, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(request),
});
if (!response.ok) {
// Handle HTTP error responses (4xx, 5xx)
const errorData = await response.json().catch(() => ({}));
const errorMessage =
errorData.detail ?? `HTTP ${response.status}: ${response.statusText}`;
return {
success: false,
skill_name: "",
message: errorMessage,
};
}
return response.json();
}
async function parseDetailedError(response: Response, fallback: string): Promise<Error> {
const data = await response.json().catch(() => ({}));
const detail = (data as { detail?: unknown }).detail;
const message = typeof detail === "string" && detail ? detail : `${fallback} (HTTP ${response.status})`;
return new Error(message);
}
export async function validateSkillUpload(file: File): Promise<ValidateSkillUploadResponse> {
const form = new FormData();
form.append("file", file, file.name);
const response = await apiFetch(`${getBackendBaseURL()}/api/skills/validate`, {
method: "POST",
body: form,
});
if (!response.ok) {
throw await parseDetailedError(response, "Validation failed");
}
return response.json() as Promise<ValidateSkillUploadResponse>;
}
export async function installSkillUpload(
file: File,
options: { overwrite?: boolean } = {},
): Promise<InstallSkillResponse> {
const form = new FormData();
form.append("file", file, file.name);
const query = options.overwrite ? "?overwrite=true" : "";
const response = await apiFetch(
`${getBackendBaseURL()}/api/skills/install-upload${query}`,
{ method: "POST", body: form },
);
if (!response.ok) {
throw await parseDetailedError(response, "Install failed");
}
return response.json() as Promise<InstallSkillResponse>;
}
+48 -31
View File
@@ -1,31 +1,48 @@
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { enableSkill } from "./api";
import { loadSkills } from ".";
export function useSkills() {
const { data, isLoading, error } = useQuery({
queryKey: ["skills"],
queryFn: () => loadSkills(),
});
return { skills: data ?? [], isLoading, error };
}
export function useEnableSkill() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
skillName,
enabled,
}: {
skillName: string;
enabled: boolean;
}) => {
await enableSkill(skillName, enabled);
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
},
});
}
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { enableSkill, installSkillUpload, validateSkillUpload } from "./api";
import { loadSkills } from ".";
export function useSkills() {
const { data, isLoading, error } = useQuery({
queryKey: ["skills"],
queryFn: () => loadSkills(),
});
return { skills: data ?? [], isLoading, error };
}
export function useEnableSkill() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({
skillName,
enabled,
}: {
skillName: string;
enabled: boolean;
}) => {
await enableSkill(skillName, enabled);
},
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
},
});
}
export function useValidateSkillUpload() {
return useMutation({
mutationFn: (file: File) => validateSkillUpload(file),
});
}
export function useInstallSkillUpload() {
const queryClient = useQueryClient();
return useMutation({
mutationFn: ({ file, overwrite }: { file: File; overwrite?: boolean }) =>
installSkillUpload(file, { overwrite }),
onSuccess: () => {
void queryClient.invalidateQueries({ queryKey: ["skills"] });
},
});
}
+2 -2
View File
@@ -1,2 +1,2 @@
export * from "./api";
export * from "./type";
export * from "./api";
export * from "./type";
+7 -7
View File
@@ -1,7 +1,7 @@
export interface Skill {
name: string;
description: string;
category: string;
license: string;
enabled: boolean;
}
export interface Skill {
name: string;
description: string;
category: string;
license: string;
enabled: boolean;
}
+1 -1
View File
@@ -1 +1 @@
export * from "./plugins";
export * from "./plugins";
+50 -50
View File
@@ -1,50 +1,50 @@
import rehypeKatex from "rehype-katex";
import rehypeRaw from "rehype-raw";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import type { StreamdownProps } from "streamdown";
import { rehypeSplitWordsIntoSpans } from "../rehype";
export const streamdownPlugins = {
remarkPlugins: [
remarkGfm,
[remarkMath, { singleDollarTextMath: true }],
] as StreamdownProps["remarkPlugins"],
rehypePlugins: [
rehypeRaw,
[rehypeKatex, { output: "html" }],
] as StreamdownProps["rehypePlugins"],
};
export const streamdownPluginsWithWordAnimation = {
remarkPlugins: [
remarkGfm,
[remarkMath, { singleDollarTextMath: true }],
] as StreamdownProps["remarkPlugins"],
rehypePlugins: [
[rehypeKatex, { output: "html" }],
rehypeSplitWordsIntoSpans,
] as StreamdownProps["rehypePlugins"],
};
// Plugins for reasoning/thinking content — derived from streamdownPlugins but without rehypeRaw,
// to prevent LLM-hallucinated HTML tags (e.g. <simd>) from being rendered as DOM elements.
export const reasoningPlugins = {
remarkPlugins: streamdownPlugins.remarkPlugins,
rehypePlugins: streamdownPlugins.rehypePlugins?.filter(
(p) => p !== rehypeRaw,
) as StreamdownProps["rehypePlugins"],
};
// Plugins for human messages - no autolink to prevent URL bleeding into adjacent text
export const humanMessagePlugins = {
remarkPlugins: [
// Use remark-gfm without autolink literals by not including it
// Only include math support for human messages
[remarkMath, { singleDollarTextMath: true }],
] as StreamdownProps["remarkPlugins"],
rehypePlugins: [
[rehypeKatex, { output: "html" }],
] as StreamdownProps["rehypePlugins"],
};
import rehypeKatex from "rehype-katex";
import rehypeRaw from "rehype-raw";
import remarkGfm from "remark-gfm";
import remarkMath from "remark-math";
import type { StreamdownProps } from "streamdown";
import { rehypeSplitWordsIntoSpans } from "../rehype";
export const streamdownPlugins = {
remarkPlugins: [
remarkGfm,
[remarkMath, { singleDollarTextMath: true }],
] as StreamdownProps["remarkPlugins"],
rehypePlugins: [
rehypeRaw,
[rehypeKatex, { output: "html" }],
] as StreamdownProps["rehypePlugins"],
};
export const streamdownPluginsWithWordAnimation = {
remarkPlugins: [
remarkGfm,
[remarkMath, { singleDollarTextMath: true }],
] as StreamdownProps["remarkPlugins"],
rehypePlugins: [
[rehypeKatex, { output: "html" }],
rehypeSplitWordsIntoSpans,
] as StreamdownProps["rehypePlugins"],
};
// Plugins for reasoning/thinking content — derived from streamdownPlugins but without rehypeRaw,
// to prevent LLM-hallucinated HTML tags (e.g. <simd>) from being rendered as DOM elements.
export const reasoningPlugins = {
remarkPlugins: streamdownPlugins.remarkPlugins,
rehypePlugins: streamdownPlugins.rehypePlugins?.filter(
(p) => p !== rehypeRaw,
) as StreamdownProps["rehypePlugins"],
};
// Plugins for human messages - no autolink to prevent URL bleeding into adjacent text
export const humanMessagePlugins = {
remarkPlugins: [
// Use remark-gfm without autolink literals by not including it
// Only include math support for human messages
[remarkMath, { singleDollarTextMath: true }],
] as StreamdownProps["remarkPlugins"],
rehypePlugins: [
[rehypeKatex, { output: "html" }],
] as StreamdownProps["rehypePlugins"],
};
+53 -53
View File
@@ -1,53 +1,53 @@
import { createContext, useCallback, useContext, useState } from "react";
import type { Subtask } from "./types";
export interface SubtaskContextValue {
tasks: Record<string, Subtask>;
setTasks: (tasks: Record<string, Subtask>) => void;
}
export const SubtaskContext = createContext<SubtaskContextValue>({
tasks: {},
setTasks: () => {
/* noop */
},
});
export function SubtasksProvider({ children }: { children: React.ReactNode }) {
const [tasks, setTasks] = useState<Record<string, Subtask>>({});
return (
<SubtaskContext.Provider value={{ tasks, setTasks }}>
{children}
</SubtaskContext.Provider>
);
}
export function useSubtaskContext() {
const context = useContext(SubtaskContext);
if (context === undefined) {
throw new Error(
"useSubtaskContext must be used within a SubtaskContext.Provider",
);
}
return context;
}
export function useSubtask(id: string) {
const { tasks } = useSubtaskContext();
return tasks[id];
}
export function useUpdateSubtask() {
const { tasks, setTasks } = useSubtaskContext();
const updateSubtask = useCallback(
(task: Partial<Subtask> & { id: string }) => {
tasks[task.id] = { ...tasks[task.id], ...task } as Subtask;
if (task.latestMessage) {
setTasks({ ...tasks });
}
},
[tasks, setTasks],
);
return updateSubtask;
}
import { createContext, useCallback, useContext, useState } from "react";
import type { Subtask } from "./types";
export interface SubtaskContextValue {
tasks: Record<string, Subtask>;
setTasks: (tasks: Record<string, Subtask>) => void;
}
export const SubtaskContext = createContext<SubtaskContextValue>({
tasks: {},
setTasks: () => {
/* noop */
},
});
export function SubtasksProvider({ children }: { children: React.ReactNode }) {
const [tasks, setTasks] = useState<Record<string, Subtask>>({});
return (
<SubtaskContext.Provider value={{ tasks, setTasks }}>
{children}
</SubtaskContext.Provider>
);
}
export function useSubtaskContext() {
const context = useContext(SubtaskContext);
if (context === undefined) {
throw new Error(
"useSubtaskContext must be used within a SubtaskContext.Provider",
);
}
return context;
}
export function useSubtask(id: string) {
const { tasks } = useSubtaskContext();
return tasks[id];
}
export function useUpdateSubtask() {
const { tasks, setTasks } = useSubtaskContext();
const updateSubtask = useCallback(
(task: Partial<Subtask> & { id: string }) => {
tasks[task.id] = { ...tasks[task.id], ...task } as Subtask;
if (task.latestMessage) {
setTasks({ ...tasks });
}
},
[tasks, setTasks],
);
return updateSubtask;
}
+1 -1
View File
@@ -1 +1 @@
export * from "./types";
export * from "./types";
+12 -12
View File
@@ -1,12 +1,12 @@
import type { AIMessage } from "@langchain/langgraph-sdk";
export interface Subtask {
id: string;
status: "in_progress" | "completed" | "failed";
subagent_type: string;
description: string;
latestMessage?: AIMessage;
prompt: string;
result?: string;
error?: string;
}
import type { AIMessage } from "@langchain/langgraph-sdk";
export interface Subtask {
id: string;
status: "in_progress" | "completed" | "failed";
subagent_type: string;
description: string;
latestMessage?: AIMessage;
prompt: string;
result?: string;
error?: string;
}
+140 -140
View File
@@ -1,140 +1,140 @@
import type { Message } from "@langchain/langgraph-sdk";
import {
extractContentFromMessage,
extractReasoningContentFromMessage,
hasContent,
hasToolCalls,
stripUploadedFilesTag,
} from "../messages/utils";
import type { AgentThread } from "./types";
import { titleOfThread } from "./utils";
function formatMessageContent(message: Message): string {
const text = extractContentFromMessage(message);
if (!text) return "";
return stripUploadedFilesTag(text);
}
function formatToolCalls(message: Message): string {
if (message.type !== "ai" || !hasToolCalls(message)) return "";
const calls = message.tool_calls ?? [];
return calls.map((call) => `- **Tool:** \`${call.name}\``).join("\n");
}
export function formatThreadAsMarkdown(
thread: AgentThread,
messages: Message[],
): string {
const title = titleOfThread(thread);
const createdAt = thread.created_at
? new Date(thread.created_at).toLocaleString()
: "Unknown";
const lines: string[] = [
`# ${title}`,
"",
`*Exported on ${new Date().toLocaleString()} · Created ${createdAt}*`,
"",
"---",
"",
];
for (const message of messages) {
if (message.type === "human") {
const content = formatMessageContent(message);
if (content) {
lines.push(`## 🧑 User`, "", content, "", "---", "");
}
} else if (message.type === "ai") {
const reasoning = extractReasoningContentFromMessage(message);
const content = formatMessageContent(message);
const toolCalls = formatToolCalls(message);
if (!content && !toolCalls && !reasoning) continue;
lines.push(`## 🤖 Assistant`);
if (reasoning) {
lines.push(
"",
"<details>",
"<summary>Thinking</summary>",
"",
reasoning,
"",
"</details>",
);
}
if (toolCalls) {
lines.push("", toolCalls);
}
if (content && hasContent(message)) {
lines.push("", content);
}
lines.push("", "---", "");
}
}
return lines.join("\n").trimEnd() + "\n";
}
export function formatThreadAsJSON(
thread: AgentThread,
messages: Message[],
): string {
const exportData = {
title: titleOfThread(thread),
thread_id: thread.thread_id,
created_at: thread.created_at,
exported_at: new Date().toISOString(),
messages: messages.map((msg) => ({
type: msg.type,
id: msg.id,
content: typeof msg.content === "string" ? msg.content : msg.content,
...(msg.type === "ai" && msg.tool_calls?.length
? { tool_calls: msg.tool_calls }
: {}),
})),
};
return JSON.stringify(exportData, null, 2);
}
function sanitizeFilename(name: string): string {
return name.replace(/[^\p{L}\p{N}_\- ]/gu, "").trim() || "conversation";
}
export function downloadAsFile(
content: string,
filename: string,
mimeType: string,
) {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
export function exportThreadAsMarkdown(
thread: AgentThread,
messages: Message[],
) {
const markdown = formatThreadAsMarkdown(thread, messages);
const filename = `${sanitizeFilename(titleOfThread(thread))}.md`;
downloadAsFile(markdown, filename, "text/markdown;charset=utf-8");
}
export function exportThreadAsJSON(thread: AgentThread, messages: Message[]) {
const json = formatThreadAsJSON(thread, messages);
const filename = `${sanitizeFilename(titleOfThread(thread))}.json`;
downloadAsFile(json, filename, "application/json;charset=utf-8");
}
import type { Message } from "@langchain/langgraph-sdk";
import {
extractContentFromMessage,
extractReasoningContentFromMessage,
hasContent,
hasToolCalls,
stripUploadedFilesTag,
} from "../messages/utils";
import type { AgentThread } from "./types";
import { titleOfThread } from "./utils";
function formatMessageContent(message: Message): string {
const text = extractContentFromMessage(message);
if (!text) return "";
return stripUploadedFilesTag(text);
}
function formatToolCalls(message: Message): string {
if (message.type !== "ai" || !hasToolCalls(message)) return "";
const calls = message.tool_calls ?? [];
return calls.map((call) => `- **Tool:** \`${call.name}\``).join("\n");
}
export function formatThreadAsMarkdown(
thread: AgentThread,
messages: Message[],
): string {
const title = titleOfThread(thread);
const createdAt = thread.created_at
? new Date(thread.created_at).toLocaleString()
: "Unknown";
const lines: string[] = [
`# ${title}`,
"",
`*Exported on ${new Date().toLocaleString()} · Created ${createdAt}*`,
"",
"---",
"",
];
for (const message of messages) {
if (message.type === "human") {
const content = formatMessageContent(message);
if (content) {
lines.push(`## 🧑 User`, "", content, "", "---", "");
}
} else if (message.type === "ai") {
const reasoning = extractReasoningContentFromMessage(message);
const content = formatMessageContent(message);
const toolCalls = formatToolCalls(message);
if (!content && !toolCalls && !reasoning) continue;
lines.push(`## 🤖 Assistant`);
if (reasoning) {
lines.push(
"",
"<details>",
"<summary>Thinking</summary>",
"",
reasoning,
"",
"</details>",
);
}
if (toolCalls) {
lines.push("", toolCalls);
}
if (content && hasContent(message)) {
lines.push("", content);
}
lines.push("", "---", "");
}
}
return lines.join("\n").trimEnd() + "\n";
}
export function formatThreadAsJSON(
thread: AgentThread,
messages: Message[],
): string {
const exportData = {
title: titleOfThread(thread),
thread_id: thread.thread_id,
created_at: thread.created_at,
exported_at: new Date().toISOString(),
messages: messages.map((msg) => ({
type: msg.type,
id: msg.id,
content: typeof msg.content === "string" ? msg.content : msg.content,
...(msg.type === "ai" && msg.tool_calls?.length
? { tool_calls: msg.tool_calls }
: {}),
})),
};
return JSON.stringify(exportData, null, 2);
}
function sanitizeFilename(name: string): string {
return name.replace(/[^\p{L}\p{N}_\- ]/gu, "").trim() || "conversation";
}
export function downloadAsFile(
content: string,
filename: string,
mimeType: string,
) {
const blob = new Blob([content], { type: mimeType });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
export function exportThreadAsMarkdown(
thread: AgentThread,
messages: Message[],
) {
const markdown = formatThreadAsMarkdown(thread, messages);
const filename = `${sanitizeFilename(titleOfThread(thread))}.md`;
downloadAsFile(markdown, filename, "text/markdown;charset=utf-8");
}
export function exportThreadAsJSON(thread: AgentThread, messages: Message[]) {
const json = formatThreadAsJSON(thread, messages);
const filename = `${sanitizeFilename(titleOfThread(thread))}.json`;
downloadAsFile(json, filename, "application/json;charset=utf-8");
}
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -1 +1 @@
export * from "./types";
export * from "./types";
+26 -26
View File
@@ -1,26 +1,26 @@
import type { Message, Thread } from "@langchain/langgraph-sdk";
import type { Todo } from "../todos";
export interface AgentThreadState extends Record<string, unknown> {
title: string;
messages: Message[];
artifacts: string[];
todos?: Todo[];
}
export interface AgentThreadContext extends Record<string, unknown> {
thread_id: string;
model_name: string | undefined;
thinking_enabled: boolean;
is_plan_mode: boolean;
subagent_enabled: boolean;
reasoning_effort?: "minimal" | "low" | "medium" | "high";
agent_id?: string;
/** @deprecated kept for reading legacy thread metadata; prefer agent_id */
agent_name?: string;
}
export interface AgentThread extends Thread<AgentThreadState> {
context?: AgentThreadContext;
}
import type { Message, Thread } from "@langchain/langgraph-sdk";
import type { Todo } from "../todos";
export interface AgentThreadState extends Record<string, unknown> {
title: string;
messages: Message[];
artifacts: string[];
todos?: Todo[];
}
export interface AgentThreadContext extends Record<string, unknown> {
thread_id: string;
model_name: string | undefined;
thinking_enabled: boolean;
is_plan_mode: boolean;
subagent_enabled: boolean;
reasoning_effort?: "minimal" | "low" | "medium" | "high";
agent_id?: string;
/** @deprecated kept for reading legacy thread metadata; prefer agent_id */
agent_name?: string;
}
export interface AgentThread extends Thread<AgentThreadState> {
context?: AgentThreadContext;
}
+1 -1
View File
@@ -1 +1 @@
export * from "./types";
export * from "./types";
+4 -4
View File
@@ -1,4 +1,4 @@
export interface Todo {
content?: string;
status?: "pending" | "in_progress" | "completed";
}
export interface Todo {
content?: string;
status?: "pending" | "in_progress" | "completed";
}
+29 -29
View File
@@ -1,29 +1,29 @@
import type { ToolCall } from "@langchain/core/messages";
import type { AIMessage } from "@langchain/langgraph-sdk";
import type { Translations } from "../i18n";
import { hasToolCalls } from "../messages/utils";
export function explainLastToolCall(message: AIMessage, t: Translations) {
if (hasToolCalls(message)) {
const lastToolCall = message.tool_calls![message.tool_calls!.length - 1]!;
return explainToolCall(lastToolCall, t);
}
return t.common.thinking;
}
export function explainToolCall(toolCall: ToolCall, t: Translations) {
if (toolCall.name === "web_search" || toolCall.name === "image_search") {
return t.toolCalls.searchFor(toolCall.args.query);
} else if (toolCall.name === "web_fetch") {
return t.toolCalls.viewWebPage;
} else if (toolCall.name === "present_files") {
return t.toolCalls.presentFiles;
} else if (toolCall.name === "write_todos") {
return t.toolCalls.writeTodos;
} else if (toolCall.args.description) {
return toolCall.args.description;
} else {
return t.toolCalls.useTool(toolCall.name);
}
}
import type { ToolCall } from "@langchain/core/messages";
import type { AIMessage } from "@langchain/langgraph-sdk";
import type { Translations } from "../i18n";
import { hasToolCalls } from "../messages/utils";
export function explainLastToolCall(message: AIMessage, t: Translations) {
if (hasToolCalls(message)) {
const lastToolCall = message.tool_calls![message.tool_calls!.length - 1]!;
return explainToolCall(lastToolCall, t);
}
return t.common.thinking;
}
export function explainToolCall(toolCall: ToolCall, t: Translations) {
if (toolCall.name === "web_search" || toolCall.name === "image_search") {
return t.toolCalls.searchFor(toolCall.args.query);
} else if (toolCall.name === "web_fetch") {
return t.toolCalls.viewWebPage;
} else if (toolCall.name === "present_files") {
return t.toolCalls.presentFiles;
} else if (toolCall.name === "write_todos") {
return t.toolCalls.writeTodos;
} else if (toolCall.args.description) {
return toolCall.args.description;
} else {
return t.toolCalls.useTool(toolCall.name);
}
}
+107 -107
View File
@@ -1,107 +1,107 @@
/**
* API functions for file uploads
*/
import { getBackendBaseURL } from "../config";
import { apiFetch } from "../api";
export interface UploadedFileInfo {
filename: string;
size: number;
path: string;
virtual_path: string;
artifact_url: string;
extension?: string;
modified?: number;
markdown_file?: string;
markdown_path?: string;
markdown_virtual_path?: string;
markdown_artifact_url?: string;
}
export interface UploadResponse {
success: boolean;
files: UploadedFileInfo[];
message: string;
}
export interface ListFilesResponse {
files: UploadedFileInfo[];
count: number;
}
async function readErrorDetail(
response: Response,
fallback: string,
): Promise<string> {
const error = await response.json().catch(() => ({ detail: fallback }));
return error.detail ?? fallback;
}
/**
* Upload files to a thread
*/
export async function uploadFiles(
threadId: string,
files: File[],
): Promise<UploadResponse> {
const formData = new FormData();
files.forEach((file) => {
formData.append("files", file);
});
const response = await apiFetch(
`${getBackendBaseURL()}/api/threads/${threadId}/uploads`,
{
method: "POST",
body: formData,
},
);
if (!response.ok) {
throw new Error(await readErrorDetail(response, "Upload failed"));
}
return response.json();
}
/**
* List all uploaded files for a thread
*/
export async function listUploadedFiles(
threadId: string,
): Promise<ListFilesResponse> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/threads/${threadId}/uploads/list`,
);
if (!response.ok) {
throw new Error(
await readErrorDetail(response, "Failed to list uploaded files"),
);
}
return response.json();
}
/**
* Delete an uploaded file
*/
export async function deleteUploadedFile(
threadId: string,
filename: string,
): Promise<{ success: boolean; message: string }> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/threads/${threadId}/uploads/${filename}`,
{
method: "DELETE",
},
);
if (!response.ok) {
throw new Error(await readErrorDetail(response, "Failed to delete file"));
}
return response.json();
}
/**
* API functions for file uploads
*/
import { getBackendBaseURL } from "../config";
import { apiFetch } from "../api";
export interface UploadedFileInfo {
filename: string;
size: number;
path: string;
virtual_path: string;
artifact_url: string;
extension?: string;
modified?: number;
markdown_file?: string;
markdown_path?: string;
markdown_virtual_path?: string;
markdown_artifact_url?: string;
}
export interface UploadResponse {
success: boolean;
files: UploadedFileInfo[];
message: string;
}
export interface ListFilesResponse {
files: UploadedFileInfo[];
count: number;
}
async function readErrorDetail(
response: Response,
fallback: string,
): Promise<string> {
const error = await response.json().catch(() => ({ detail: fallback }));
return error.detail ?? fallback;
}
/**
* Upload files to a thread
*/
export async function uploadFiles(
threadId: string,
files: File[],
): Promise<UploadResponse> {
const formData = new FormData();
files.forEach((file) => {
formData.append("files", file);
});
const response = await apiFetch(
`${getBackendBaseURL()}/api/threads/${threadId}/uploads`,
{
method: "POST",
body: formData,
},
);
if (!response.ok) {
throw new Error(await readErrorDetail(response, "Upload failed"));
}
return response.json();
}
/**
* List all uploaded files for a thread
*/
export async function listUploadedFiles(
threadId: string,
): Promise<ListFilesResponse> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/threads/${threadId}/uploads/list`,
);
if (!response.ok) {
throw new Error(
await readErrorDetail(response, "Failed to list uploaded files"),
);
}
return response.json();
}
/**
* Delete an uploaded file
*/
export async function deleteUploadedFile(
threadId: string,
filename: string,
): Promise<{ success: boolean; message: string }> {
const response = await apiFetch(
`${getBackendBaseURL()}/api/threads/${threadId}/uploads/${filename}`,
{
method: "DELETE",
},
);
if (!response.ok) {
throw new Error(await readErrorDetail(response, "Failed to delete file"));
}
return response.json();
}
@@ -1,34 +1,34 @@
const MACOS_APP_BUNDLE_CONTENT_TYPES = new Set([
"",
"application/octet-stream",
]);
export const MACOS_APP_BUNDLE_UPLOAD_MESSAGE =
"macOS .app bundles can't be uploaded directly from the browser. Compress the app as a .zip or upload the .dmg instead.";
export function isLikelyMacOSAppBundle(file: Pick<File, "name" | "type">) {
return (
file.name.toLowerCase().endsWith(".app") &&
MACOS_APP_BUNDLE_CONTENT_TYPES.has(file.type)
);
}
export function splitUnsupportedUploadFiles(fileList: File[] | FileList) {
const incoming = Array.from(fileList);
const accepted: File[] = [];
const rejected: File[] = [];
for (const file of incoming) {
if (isLikelyMacOSAppBundle(file)) {
rejected.push(file);
continue;
}
accepted.push(file);
}
return {
accepted,
rejected,
message: rejected.length > 0 ? MACOS_APP_BUNDLE_UPLOAD_MESSAGE : undefined,
};
}
const MACOS_APP_BUNDLE_CONTENT_TYPES = new Set([
"",
"application/octet-stream",
]);
export const MACOS_APP_BUNDLE_UPLOAD_MESSAGE =
"macOS .app bundles can't be uploaded directly from the browser. Compress the app as a .zip or upload the .dmg instead.";
export function isLikelyMacOSAppBundle(file: Pick<File, "name" | "type">) {
return (
file.name.toLowerCase().endsWith(".app") &&
MACOS_APP_BUNDLE_CONTENT_TYPES.has(file.type)
);
}
export function splitUnsupportedUploadFiles(fileList: File[] | FileList) {
const incoming = Array.from(fileList);
const accepted: File[] = [];
const rejected: File[] = [];
for (const file of incoming) {
if (isLikelyMacOSAppBundle(file)) {
rejected.push(file);
continue;
}
accepted.push(file);
}
return {
accepted,
rejected,
message: rejected.length > 0 ? MACOS_APP_BUNDLE_UPLOAD_MESSAGE : undefined,
};
}
+79 -79
View File
@@ -1,79 +1,79 @@
/**
* React hooks for file uploads
*/
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback } from "react";
import {
deleteUploadedFile,
listUploadedFiles,
uploadFiles,
type UploadedFileInfo,
type UploadResponse,
} from "./api";
/**
* Hook to upload files
*/
export function useUploadFiles(threadId: string) {
const queryClient = useQueryClient();
return useMutation<UploadResponse, Error, File[]>({
mutationFn: (files: File[]) => uploadFiles(threadId, files),
onSuccess: () => {
// Invalidate the uploaded files list
void queryClient.invalidateQueries({
queryKey: ["uploads", "list", threadId],
});
},
});
}
/**
* Hook to list uploaded files
*/
export function useUploadedFiles(threadId: string) {
return useQuery({
queryKey: ["uploads", "list", threadId],
queryFn: () => listUploadedFiles(threadId),
enabled: !!threadId,
});
}
/**
* Hook to delete an uploaded file
*/
export function useDeleteUploadedFile(threadId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (filename: string) => deleteUploadedFile(threadId, filename),
onSuccess: () => {
// Invalidate the uploaded files list
void queryClient.invalidateQueries({
queryKey: ["uploads", "list", threadId],
});
},
});
}
/**
* Hook to handle file uploads in submit flow
* Returns a function that uploads files and returns their info
*/
export function useUploadFilesOnSubmit(threadId: string) {
const uploadMutation = useUploadFiles(threadId);
return useCallback(
async (files: File[]): Promise<UploadedFileInfo[]> => {
if (files.length === 0) {
return [];
}
const result = await uploadMutation.mutateAsync(files);
return result.files;
},
[uploadMutation],
);
}
/**
* React hooks for file uploads
*/
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useCallback } from "react";
import {
deleteUploadedFile,
listUploadedFiles,
uploadFiles,
type UploadedFileInfo,
type UploadResponse,
} from "./api";
/**
* Hook to upload files
*/
export function useUploadFiles(threadId: string) {
const queryClient = useQueryClient();
return useMutation<UploadResponse, Error, File[]>({
mutationFn: (files: File[]) => uploadFiles(threadId, files),
onSuccess: () => {
// Invalidate the uploaded files list
void queryClient.invalidateQueries({
queryKey: ["uploads", "list", threadId],
});
},
});
}
/**
* Hook to list uploaded files
*/
export function useUploadedFiles(threadId: string) {
return useQuery({
queryKey: ["uploads", "list", threadId],
queryFn: () => listUploadedFiles(threadId),
enabled: !!threadId,
});
}
/**
* Hook to delete an uploaded file
*/
export function useDeleteUploadedFile(threadId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (filename: string) => deleteUploadedFile(threadId, filename),
onSuccess: () => {
// Invalidate the uploaded files list
void queryClient.invalidateQueries({
queryKey: ["uploads", "list", threadId],
});
},
});
}
/**
* Hook to handle file uploads in submit flow
* Returns a function that uploads files and returns their info
*/
export function useUploadFilesOnSubmit(threadId: string) {
const uploadMutation = useUploadFiles(threadId);
return useCallback(
async (files: File[]): Promise<UploadedFileInfo[]> => {
if (files.length === 0) {
return [];
}
const result = await uploadMutation.mutateAsync(files);
return result.files;
},
[uploadMutation],
);
}
+8 -8
View File
@@ -1,8 +1,8 @@
/**
* File uploads module
*/
export * from "./api";
export * from "./file-validation";
export * from "./hooks";
export * from "./prompt-input-files";
/**
* File uploads module
*/
export * from "./api";
export * from "./file-validation";
export * from "./hooks";
export * from "./prompt-input-files";
@@ -1,52 +1,52 @@
import type { FileUIPart } from "ai";
export type PromptInputFilePart = FileUIPart & {
// Transient submit-time handle to the original browser File; not serializable.
file?: File;
};
export async function promptInputFilePartToFile(
filePart: PromptInputFilePart,
): Promise<File | null> {
if (filePart.file instanceof File) {
const filename =
typeof filePart.filename === "string" && filePart.filename.length > 0
? filePart.filename
: filePart.file.name;
const mediaType =
typeof filePart.mediaType === "string" && filePart.mediaType.length > 0
? filePart.mediaType
: filePart.file.type;
if (filePart.file.name === filename && filePart.file.type === mediaType) {
return filePart.file;
}
return new File([filePart.file], filename, { type: mediaType });
}
if (!filePart.url || !filePart.filename) {
return null;
}
try {
const response = await fetch(filePart.url);
if (!response.ok) {
throw new Error(
`HTTP ${response.status} while fetching fallback file URL`,
);
}
const blob = await response.blob();
return new File([blob], filePart.filename, {
type: filePart.mediaType || blob.type,
});
} catch (error) {
console.warn("promptInputFilePartToFile: fetch fallback failed", {
error,
url: filePart.url,
filename: filePart.filename,
});
return null;
}
}
import type { FileUIPart } from "ai";
export type PromptInputFilePart = FileUIPart & {
// Transient submit-time handle to the original browser File; not serializable.
file?: File;
};
export async function promptInputFilePartToFile(
filePart: PromptInputFilePart,
): Promise<File | null> {
if (filePart.file instanceof File) {
const filename =
typeof filePart.filename === "string" && filePart.filename.length > 0
? filePart.filename
: filePart.file.name;
const mediaType =
typeof filePart.mediaType === "string" && filePart.mediaType.length > 0
? filePart.mediaType
: filePart.file.type;
if (filePart.file.name === filename && filePart.file.type === mediaType) {
return filePart.file;
}
return new File([filePart.file], filename, { type: mediaType });
}
if (!filePart.url || !filePart.filename) {
return null;
}
try {
const response = await fetch(filePart.url);
if (!response.ok) {
throw new Error(
`HTTP ${response.status} while fetching fallback file URL`,
);
}
const blob = await response.blob();
return new File([blob], filePart.filename, {
type: filePart.mediaType || blob.type,
});
} catch (error) {
console.warn("promptInputFilePartToFile: fetch fallback failed", {
error,
url: filePart.url,
filename: filePart.filename,
});
return null;
}
}
+27 -27
View File
@@ -1,27 +1,27 @@
import { formatDistanceToNow } from "date-fns";
import { enUS as dateFnsEnUS, zhCN as dateFnsZhCN } from "date-fns/locale";
import { detectLocale, type Locale } from "@/core/i18n";
import { getLocaleFromCookie } from "@/core/i18n/cookies";
function getDateFnsLocale(locale: Locale) {
switch (locale) {
case "zh-CN":
return dateFnsZhCN;
case "en-US":
default:
return dateFnsEnUS;
}
}
export function formatTimeAgo(date: Date | string | number, locale?: Locale) {
const effectiveLocale =
locale ??
(getLocaleFromCookie() as Locale | null) ??
// Fallback when cookie is missing (or on first render)
detectLocale();
return formatDistanceToNow(date, {
addSuffix: true,
locale: getDateFnsLocale(effectiveLocale),
});
}
import { formatDistanceToNow } from "date-fns";
import { enUS as dateFnsEnUS, zhCN as dateFnsZhCN } from "date-fns/locale";
import { detectLocale, type Locale } from "@/core/i18n";
import { getLocaleFromCookie } from "@/core/i18n/cookies";
function getDateFnsLocale(locale: Locale) {
switch (locale) {
case "zh-CN":
return dateFnsZhCN;
case "en-US":
default:
return dateFnsEnUS;
}
}
export function formatTimeAgo(date: Date | string | number, locale?: Locale) {
const effectiveLocale =
locale ??
(getLocaleFromCookie() as Locale | null) ??
// Fallback when cookie is missing (or on first render)
detectLocale();
return formatDistanceToNow(date, {
addSuffix: true,
locale: getDateFnsLocale(effectiveLocale),
});
}
+236 -236
View File
@@ -1,236 +1,236 @@
import {
BookOpenTextIcon,
CompassIcon,
FileCodeIcon,
FileCogIcon,
FilePlayIcon,
FileTextIcon,
ImageIcon,
} from "lucide-react";
const extensionMap: Record<string, string> = {
// Text
txt: "text",
csv: "csv",
log: "text",
conf: "text",
config: "text",
properties: "text",
props: "text",
// JavaScript/TypeScript ecosystem
js: "javascript",
jsx: "jsx",
ts: "typescript",
tsx: "tsx",
mjs: "javascript",
cjs: "javascript",
mts: "typescript",
cts: "typescript",
// Web
html: "html",
htm: "html",
css: "css",
scss: "scss",
sass: "sass",
less: "less",
vue: "vue",
svelte: "svelte",
astro: "astro",
// Python
py: "python",
pyi: "python",
pyw: "python",
// Java/JVM
java: "java",
kt: "kotlin",
kts: "kotlin",
scala: "scala",
groovy: "groovy",
// C/C++
c: "c",
h: "c",
cpp: "cpp",
cc: "cpp",
cxx: "cpp",
hpp: "cpp",
hxx: "cpp",
hh: "cpp",
// C#
cs: "csharp",
// Go
go: "go",
// Rust
rs: "rust",
// Ruby
rb: "ruby",
rake: "ruby",
// PHP
php: "php",
// Shell/Bash
sh: "bash",
bash: "bash",
zsh: "zsh",
fish: "fish",
// Config & Data
json: "json",
jsonc: "jsonc",
json5: "json5",
yaml: "yaml",
yml: "yaml",
toml: "toml",
xml: "xml",
ini: "ini",
env: "dotenv",
// Markdown & Docs
md: "markdown",
mdx: "mdx",
rst: "rst",
// SQL
sql: "sql",
// Other languages
swift: "swift",
dart: "dart",
lua: "lua",
r: "r",
matlab: "matlab",
julia: "jl",
elm: "elm",
haskell: "haskell",
hs: "haskell",
elixir: "elixir",
ex: "elixir",
clj: "clojure",
cljs: "clojure",
// Infrastructure
dockerfile: "dockerfile",
docker: "docker",
tf: "terraform",
tfvars: "terraform",
hcl: "hcl",
// Build & Config
makefile: "makefile",
cmake: "cmake",
gradle: "groovy",
// Git
gitignore: "git-commit",
gitattributes: "git-commit",
// Misc
graphql: "graphql",
gql: "graphql",
proto: "protobuf",
prisma: "prisma",
wasm: "wasm",
zig: "zig",
v: "v",
};
export function getFileName(filepath: string) {
return filepath.split("/").pop()!;
}
export function getFileExtension(filepath: string) {
return filepath.split(".").pop()!.toLocaleLowerCase();
}
export function checkCodeFile(
filepath: string,
):
| { isCodeFile: true; language: string }
| { isCodeFile: false; language: null } {
const extension = getFileExtension(filepath);
const isCodeFile = extension in extensionMap;
if (isCodeFile) {
return {
isCodeFile: true,
language: extensionMap[extension] ?? "text",
};
}
return {
isCodeFile: false,
language: null,
};
}
export function getFileExtensionDisplayName(filepath: string) {
const fileName = getFileName(filepath);
const extension = fileName.split(".").pop()!.toLocaleLowerCase();
switch (extension) {
case "doc":
case "docx":
return "Word";
case "md":
return "Markdown";
case "txt":
return "Text";
case "ppt":
case "pptx":
return "PowerPoint";
case "xls":
case "xlsx":
return "Excel";
default:
return extension.toUpperCase();
}
}
export function getFileIcon(filepath: string, className?: string) {
const extension = getFileExtension(filepath);
const { isCodeFile } = checkCodeFile(filepath);
switch (extension) {
case "skill":
return <FileCogIcon className={className} />;
case "html":
return <CompassIcon className={className} />;
case "txt":
case "md":
return <BookOpenTextIcon className={className} />;
case "jpg":
case "jpeg":
case "png":
case "gif":
case "bmp":
case "tiff":
case "ico":
case "webp":
case "svg":
case "heic":
return <ImageIcon className={className} />;
case "mp3":
case "wav":
case "ogg":
case "aac":
case "m4a":
case "flac":
case "wma":
case "aiff":
case "ape":
case "mp4":
case "mov":
case "m4v":
return <FilePlayIcon className={className} />;
default:
if (isCodeFile) {
return <FileCodeIcon className={className} />;
}
return <FileTextIcon className={className} />;
}
}
import {
BookOpenTextIcon,
CompassIcon,
FileCodeIcon,
FileCogIcon,
FilePlayIcon,
FileTextIcon,
ImageIcon,
} from "lucide-react";
const extensionMap: Record<string, string> = {
// Text
txt: "text",
csv: "csv",
log: "text",
conf: "text",
config: "text",
properties: "text",
props: "text",
// JavaScript/TypeScript ecosystem
js: "javascript",
jsx: "jsx",
ts: "typescript",
tsx: "tsx",
mjs: "javascript",
cjs: "javascript",
mts: "typescript",
cts: "typescript",
// Web
html: "html",
htm: "html",
css: "css",
scss: "scss",
sass: "sass",
less: "less",
vue: "vue",
svelte: "svelte",
astro: "astro",
// Python
py: "python",
pyi: "python",
pyw: "python",
// Java/JVM
java: "java",
kt: "kotlin",
kts: "kotlin",
scala: "scala",
groovy: "groovy",
// C/C++
c: "c",
h: "c",
cpp: "cpp",
cc: "cpp",
cxx: "cpp",
hpp: "cpp",
hxx: "cpp",
hh: "cpp",
// C#
cs: "csharp",
// Go
go: "go",
// Rust
rs: "rust",
// Ruby
rb: "ruby",
rake: "ruby",
// PHP
php: "php",
// Shell/Bash
sh: "bash",
bash: "bash",
zsh: "zsh",
fish: "fish",
// Config & Data
json: "json",
jsonc: "jsonc",
json5: "json5",
yaml: "yaml",
yml: "yaml",
toml: "toml",
xml: "xml",
ini: "ini",
env: "dotenv",
// Markdown & Docs
md: "markdown",
mdx: "mdx",
rst: "rst",
// SQL
sql: "sql",
// Other languages
swift: "swift",
dart: "dart",
lua: "lua",
r: "r",
matlab: "matlab",
julia: "jl",
elm: "elm",
haskell: "haskell",
hs: "haskell",
elixir: "elixir",
ex: "elixir",
clj: "clojure",
cljs: "clojure",
// Infrastructure
dockerfile: "dockerfile",
docker: "docker",
tf: "terraform",
tfvars: "terraform",
hcl: "hcl",
// Build & Config
makefile: "makefile",
cmake: "cmake",
gradle: "groovy",
// Git
gitignore: "git-commit",
gitattributes: "git-commit",
// Misc
graphql: "graphql",
gql: "graphql",
proto: "protobuf",
prisma: "prisma",
wasm: "wasm",
zig: "zig",
v: "v",
};
export function getFileName(filepath: string) {
return filepath.split("/").pop()!;
}
export function getFileExtension(filepath: string) {
return filepath.split(".").pop()!.toLocaleLowerCase();
}
export function checkCodeFile(
filepath: string,
):
| { isCodeFile: true; language: string }
| { isCodeFile: false; language: null } {
const extension = getFileExtension(filepath);
const isCodeFile = extension in extensionMap;
if (isCodeFile) {
return {
isCodeFile: true,
language: extensionMap[extension] ?? "text",
};
}
return {
isCodeFile: false,
language: null,
};
}
export function getFileExtensionDisplayName(filepath: string) {
const fileName = getFileName(filepath);
const extension = fileName.split(".").pop()!.toLocaleLowerCase();
switch (extension) {
case "doc":
case "docx":
return "Word";
case "md":
return "Markdown";
case "txt":
return "Text";
case "ppt":
case "pptx":
return "PowerPoint";
case "xls":
case "xlsx":
return "Excel";
default:
return extension.toUpperCase();
}
}
export function getFileIcon(filepath: string, className?: string) {
const extension = getFileExtension(filepath);
const { isCodeFile } = checkCodeFile(filepath);
switch (extension) {
case "skill":
return <FileCogIcon className={className} />;
case "html":
return <CompassIcon className={className} />;
case "txt":
case "md":
return <BookOpenTextIcon className={className} />;
case "jpg":
case "jpeg":
case "png":
case "gif":
case "bmp":
case "tiff":
case "ico":
case "webp":
case "svg":
case "heic":
return <ImageIcon className={className} />;
case "mp3":
case "wav":
case "ogg":
case "aac":
case "m4a":
case "flac":
case "wma":
case "aiff":
case "ape":
case "mp4":
case "mov":
case "m4v":
return <FilePlayIcon className={className} />;
default:
if (isCodeFile) {
return <FileCodeIcon className={className} />;
}
return <FileTextIcon className={className} />;
}
}
+10 -10
View File
@@ -1,10 +1,10 @@
import { parse } from "best-effort-json-parser";
export function tryParseJSON(json: string) {
try {
const object = parse(json);
return object;
} catch {
return undefined;
}
}
import { parse } from "best-effort-json-parser";
export function tryParseJSON(json: string) {
try {
const object = parse(json);
return object;
} catch {
return undefined;
}
}
+10 -10
View File
@@ -1,10 +1,10 @@
export function extractTitleFromMarkdown(markdown: string) {
if (markdown.startsWith("# ")) {
let title = markdown.split("\n")[0]!.trim();
if (title.startsWith("# ")) {
title = title.slice(2).trim();
}
return title;
}
return undefined;
}
export function extractTitleFromMarkdown(markdown: string) {
if (markdown.startsWith("# ")) {
let title = markdown.split("\n")[0]!.trim();
if (title.startsWith("# ")) {
title = title.slice(2).trim();
}
return title;
}
return undefined;
}
+1 -1
View File
@@ -1 +1 @@
export { v4 as uuid } from "uuid";
export { v4 as uuid } from "uuid";