mirror of
https://github.com/siteboon/claudecodeui.git
synced 2026-07-09 07:25:43 +08:00
* fix: don't overlap thinking banner over conversation * feat: support message queue and add attention indicator * fix(shell): use c to copy for claude * fix: strip timestamp tags from cursor * fix: select project when loading session from direct URL * feat: support attached images for all providers * feat(opencode): support permission options * fix: resolve source control and chat UX bugs - make staging real in the git panel: new /stage and /unstage endpoints, /status now reports the actual index via porcelain -z (handles renames, conflicts, and paths with spaces), and Stage/Unstage All run real git commands instead of toggling client-side state - add branch search to the header dropdown and Branches tab - persist the chosen permission mode per provider so a brand-new chat keeps it once the session id arrives, instead of reverting to default - replace cmdk's fuzzy model search with strict token matching so "chatgpt" no longer surfaces unrelated models - unit tests for the git status parser * feat(git): commit graph in history view and cross-spawn everywhere - render a VSCode-style commit graph in the source control history: lane-assignment algorithm, SVG strip with colored rails, merge and branch curves, commit dots, and branch/tag badges per commit - /commits returns parents and ref decorations across all branches (--branches --remotes --tags --topo-order) using unit-separator fields so pipes in commit subjects can't break parsing - collect stats via a single --shortstat pass instead of one `git show --stat` call per commit; raise the history limit to 50 - replace child_process spawn with cross-spawn in all runtimes, routes, and services: it resolves .cmd shims and PATHEXT on Windows (fixing taskmaster's npx invocations) and delegates to native spawn elsewhere, removing the per-file win32 ternaries - unit tests for the log parser and lane assignment * fix: remove gemini support since google discontinued it * fix: address code review findings - validate chat image attachments server-side: only files inside the ~/.cloudcli/assets upload store may reach provider file reads - harden asset serving with nosniff and attachment disposition for SVGs to prevent stored XSS - show the timestamp on image-only user messages - serialize git stage/unstage calls and defer the status re-sync so rapid toggles can't interleave or flicker - use a literal hex fallback for commit ref badges (alpha suffix on a var() string produced invalid CSS) - stop binding a URL session to a guening project instead - add the missing attentionRequiredIndicator key to all sidebar locales - clean up dangling conjunctions left the de/ru/tr/ja/zh-CN/zh-TW READMEs * fix: address code scanning findings - enforce a second image trust boundary in the provider builders: buildClaudeUserContent/buildCodexInputItems only accept files inside the upload store or the run's working directory (CodeQL path injection) - drop an always-true selectedProject check in handleSubmit - remove the unused resume option from spawnCursor * fix: use CodeQL-recognized containment check for image reads Replace the path.relative guard in isPathInsideDirectory with the resolve + startsWith(root + sep) idiom so the path-injection barrier is visible to code scanning; behavior is unchanged. * fix(security): canonicalize Claude image attachment reads Resolve image attachment paths with realpath before reading so symlinks inside allowed roots cannot escape to arbitrary files. Preserve support for symlinked project/upload roots and add focused coverage for both cases. * fix: show agent subtask * fix(sessions): title app-created sessions from the first user message App-created sessions (started by sending a message from cloudcli) were titled with placeholder names — "Untitled Codex Session" from the disk indexer and, briefly, "New session" from the empty canonical upsert — before a later sync finally settled on the right text, causing the sidebar title to flicker. - Codex/OpenCode synchronizers now title app-created sessions (distinct app id mapped to a provider id) from the first user message, while sessions found purely by indexing keep their existing setup. Claude keeps its AI-generated titles; Cursor already used the first message. - Decode OpenCode's JSON-string-literal prompts so titles no longer surface wrapped in quotes; hoist unwrapJsonStringLiteral into shared/utils since it's now used by both the reader and synchronizer. - Guard the sidebar upsert merge so an empty summary can never blank out a title that is already set. - Add codex/opencode synchronizer tests for the app-created vs indexed naming paths. * fix(chat): make message queuing reliable across sessions and turn boundaries Queued messages had four related defects: - A queued message flashed and then vanished at flush time: concurrent transcript refreshes (the `complete` handler racing the watcher-triggered update) could resolve out of order, letting a stale response overwrite newer server messages after the optimistic row was pruned. Session slots now carry a monotonic fetch ticket and discard stale fetch/refresh/ fetchMore responses. - Switching sessions flushed the previous session's queued draft into the newly viewed one (sending it with the wrong provider's settings, e.g. a Claude model into a Codex session). The composer flush is now scoped to its session, and a draft restored into an idle session sends after a short grace period so a live-run ack can cancel it. - The thinking banner never appeared for a queued turn: the chat handler's session-keyed completeRun safety net could fire after a queued message had already started the session's next run, emitting a spurious `complete` that killed it. The safety net is now scoped to its own run via completeRunIfCurrent (with a regression test). - Queued messages only sent while their session was being viewed. Drafts now persist their send options (model, effort, permissions) at queue time, and a new app-level useQueuedMessageAutoSend hook dispatches a non-viewed session's queued message as soon as its run completes, using the storage key as the claim ticket to prevent double sends.
342 lines
12 KiB
TypeScript
342 lines
12 KiB
TypeScript
import { promises as fs, realpathSync } from 'node:fs';
|
|
import os from 'node:os';
|
|
import path from 'node:path';
|
|
|
|
/**
|
|
* Shared image-attachment plumbing for every provider runtime.
|
|
*
|
|
* Uploaded chat images are persisted once in the global `~/.cloudcli/assets`
|
|
* folder and referenced by absolute path everywhere else:
|
|
* - Claude: paths are read back into base64 `image` content blocks.
|
|
* - Codex: paths become `local_image` input items.
|
|
* - Cursor/OpenCode: paths are appended to the prompt inside an
|
|
* `<images_input>` tag, which is stripped again when history is read.
|
|
*
|
|
* The chat UI loads them through the dedicated `/api/assets/images/:filename`
|
|
* route, which serves only from this folder.
|
|
*/
|
|
|
|
/** Global storage folder for uploaded chat image attachments. */
|
|
export function getGlobalImageAssetsDir(): string {
|
|
return path.join(os.homedir(), '.cloudcli', 'assets');
|
|
}
|
|
|
|
export type ImageAttachmentDescriptor = {
|
|
/** Project-relative (preferred) or absolute path to the stored image. */
|
|
path: string;
|
|
name?: string;
|
|
mimeType?: string;
|
|
};
|
|
|
|
/** Media types the Claude Messages API accepts for base64 image blocks. */
|
|
const CLAUDE_IMAGE_MEDIA_TYPES = new Set([
|
|
'image/jpeg',
|
|
'image/png',
|
|
'image/gif',
|
|
'image/webp',
|
|
]);
|
|
|
|
const EXTENSION_TO_MEDIA_TYPE: Record<string, string> = {
|
|
'.jpg': 'image/jpeg',
|
|
'.jpeg': 'image/jpeg',
|
|
'.png': 'image/png',
|
|
'.gif': 'image/gif',
|
|
'.webp': 'image/webp',
|
|
'.svg': 'image/svg+xml',
|
|
};
|
|
|
|
/**
|
|
* Accepts the loosely-typed `options.images` payload from chat.send and
|
|
* returns only well-formed descriptors. Plain path strings are supported so
|
|
* callers can also pass bare path arrays.
|
|
*/
|
|
export function normalizeImageDescriptors(images: unknown): ImageAttachmentDescriptor[] {
|
|
if (!Array.isArray(images)) {
|
|
return [];
|
|
}
|
|
|
|
const descriptors: ImageAttachmentDescriptor[] = [];
|
|
for (const entry of images) {
|
|
if (typeof entry === 'string' && entry.trim()) {
|
|
descriptors.push({ path: entry.trim() });
|
|
continue;
|
|
}
|
|
if (entry && typeof entry === 'object') {
|
|
const record = entry as Record<string, unknown>;
|
|
const entryPath = typeof record.path === 'string' ? record.path.trim() : '';
|
|
if (!entryPath) {
|
|
continue;
|
|
}
|
|
descriptors.push({
|
|
path: entryPath,
|
|
name: typeof record.name === 'string' ? record.name : undefined,
|
|
mimeType: typeof record.mimeType === 'string' ? record.mimeType : undefined,
|
|
});
|
|
}
|
|
}
|
|
return descriptors;
|
|
}
|
|
|
|
/** Normalizes Windows separators so stored references stay portable. */
|
|
export function toPosixPath(value: string): string {
|
|
return value.replace(/\\/g, '/');
|
|
}
|
|
|
|
/** Resolves a project-relative image path against the run's working directory. */
|
|
export function resolveImageAbsolutePath(cwd: string | undefined, imagePath: string): string {
|
|
if (path.isAbsolute(imagePath)) {
|
|
return imagePath;
|
|
}
|
|
return path.resolve(cwd || process.cwd(), imagePath);
|
|
}
|
|
|
|
function isPathInsideDirectory(candidate: string, directory: string): boolean {
|
|
// resolve + startsWith(root + separator) is the containment idiom CodeQL
|
|
// recognizes as a path-injection barrier, and matches the check used by
|
|
// resolveImageAssetFile in the assets module. The root itself never
|
|
// matches (no trailing separator after resolve), only entries below it.
|
|
const resolvedRoot = path.resolve(directory) + path.sep;
|
|
return path.resolve(candidate).startsWith(resolvedRoot);
|
|
}
|
|
|
|
function getDirectoryPathVariants(directory: string): string[] {
|
|
const resolvedDirectory = path.resolve(directory);
|
|
try {
|
|
const canonicalDirectory = path.resolve(realpathSync(directory));
|
|
return canonicalDirectory === resolvedDirectory
|
|
? [resolvedDirectory]
|
|
: [resolvedDirectory, canonicalDirectory];
|
|
} catch {
|
|
return [resolvedDirectory];
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Second layer of the image trust boundary (the first is the chat.send filter
|
|
* in the websocket gateway): provider builders only reference files that live
|
|
* in the global upload store or inside the run's working directory — places
|
|
* the agent could already access on its own. Anything else (e.g. `~/.ssh`) is
|
|
* refused, so a caller-supplied descriptor can never leak arbitrary files.
|
|
*/
|
|
export function isAllowedImageSourcePath(resolvedPath: string, cwd?: string): boolean {
|
|
return [getGlobalImageAssetsDir(), cwd || process.cwd()].some((directory) =>
|
|
getDirectoryPathVariants(directory).some((directoryVariant) =>
|
|
isPathInsideDirectory(resolvedPath, directoryVariant)
|
|
)
|
|
);
|
|
}
|
|
|
|
/**
|
|
* Resolves the media type for one image, preferring the uploaded mime type and
|
|
* falling back to the file extension.
|
|
*/
|
|
export function resolveImageMediaType(descriptor: ImageAttachmentDescriptor): string | null {
|
|
if (descriptor.mimeType) {
|
|
return descriptor.mimeType;
|
|
}
|
|
const extension = path.extname(descriptor.path).toLowerCase();
|
|
return EXTENSION_TO_MEDIA_TYPE[extension] || null;
|
|
}
|
|
|
|
const IMAGES_INPUT_TAG_PATTERN = /\s*<images_input>([\s\S]*?)<\/images_input>\s*/g;
|
|
|
|
// One image reference recovered from an <images_input> block: the stored
|
|
// asset path plus the user's original filename when it was recorded.
|
|
export type ParsedImageAttachment = {
|
|
path: string;
|
|
name?: string;
|
|
};
|
|
|
|
// Result of stripping an <images_input> block out of persisted prompt text.
|
|
// `imagePaths` mirrors `attachments` for callers that only need paths.
|
|
export type ParsedImagesInput = {
|
|
text: string;
|
|
imagePaths: string[];
|
|
attachments: ParsedImageAttachment[];
|
|
};
|
|
|
|
/**
|
|
* Appends the `<images_input>` reference block used by the Cursor and
|
|
* OpenCode CLIs. The block carries one numbered line per attachment with
|
|
* the stored file path (quote-free on purpose — Windows .cmd shims mangle
|
|
* quoted text) and the user's original filename, plus an explicit instruction
|
|
* to read the files and keep the block out of the reply. The same block is
|
|
* stripped back out of persisted history by {@link parseImagesInputTag}.
|
|
*/
|
|
export function appendImagesInputTag(prompt: string, images: unknown): string {
|
|
const descriptors = normalizeImageDescriptors(images);
|
|
if (descriptors.length === 0) {
|
|
return prompt;
|
|
}
|
|
|
|
const entryLines = descriptors.map((descriptor, index) => {
|
|
const entryPath = toPosixPath(descriptor.path);
|
|
// Parentheses and newlines would break the "(original name: ...)" suffix
|
|
// the parser looks for, so drop them from the display name.
|
|
const cleanName = descriptor.name?.replace(/[()\r\n]/g, '').trim();
|
|
return cleanName
|
|
? `${index + 1}. ${entryPath} (original name: ${cleanName})`
|
|
: `${index + 1}. ${entryPath}`;
|
|
});
|
|
|
|
return [
|
|
prompt,
|
|
'',
|
|
'<images_input>',
|
|
`The user attached ${descriptors.length} image(s) to this message. Read each file listed below with your file/image reading tool and use what you see to answer the prompt above. Respond as if the images were attached directly. Do not mention this block or the file paths unless the user asks about them.`,
|
|
...entryLines,
|
|
'</images_input>',
|
|
].join('\n');
|
|
}
|
|
|
|
// Matches one numbered attachment entry inside the tag body. Works for both
|
|
// the multi-line block and the Windows-flattened single-line form, where the
|
|
// next ` N. ` marker (or the end of the body) delimits each entry.
|
|
const IMAGES_INPUT_ENTRY_PATTERN = /\d+\.\s+(.+?)(?=\s+\d+\.\s+|\s*$)/g;
|
|
|
|
const ORIGINAL_NAME_SUFFIX_PATTERN = /\(original name: ([^)]*)\)\s*$/;
|
|
|
|
function parseNumberedImageEntries(inner: string): ParsedImageAttachment[] {
|
|
const attachments: ParsedImageAttachment[] = [];
|
|
for (const entryMatch of inner.matchAll(IMAGES_INPUT_ENTRY_PATTERN)) {
|
|
let entryText = entryMatch[1].trim();
|
|
let name: string | undefined;
|
|
|
|
const nameMatch = ORIGINAL_NAME_SUFFIX_PATTERN.exec(entryText);
|
|
if (nameMatch) {
|
|
name = nameMatch[1].trim() || undefined;
|
|
entryText = entryText.slice(0, nameMatch.index).trim();
|
|
}
|
|
|
|
if (entryText) {
|
|
attachments.push(name ? { path: toPosixPath(entryText), name } : { path: toPosixPath(entryText) });
|
|
}
|
|
}
|
|
return attachments;
|
|
}
|
|
|
|
/**
|
|
* Strips one `<images_input>` block from persisted prompt text and returns
|
|
* the clean text plus the referenced attachments (path and original name).
|
|
*
|
|
* Only the LAST block in the text is treated as the attachment carrier — the
|
|
* composer always appends it at the end, so a user who literally typed
|
|
* `<images_input>` earlier in their prompt keeps that text intact.
|
|
*
|
|
* Understands the numbered-line body in both its multi-line and
|
|
* Windows-flattened single-line forms.
|
|
*/
|
|
export function parseImagesInputTag(text: string): ParsedImagesInput {
|
|
if (typeof text !== 'string' || !text.includes('<images_input>')) {
|
|
return { text, imagePaths: [], attachments: [] };
|
|
}
|
|
|
|
let lastMatch: RegExpExecArray | null = null;
|
|
IMAGES_INPUT_TAG_PATTERN.lastIndex = 0;
|
|
for (let match = IMAGES_INPUT_TAG_PATTERN.exec(text); match; match = IMAGES_INPUT_TAG_PATTERN.exec(text)) {
|
|
lastMatch = match;
|
|
}
|
|
if (!lastMatch) {
|
|
return { text, imagePaths: [], attachments: [] };
|
|
}
|
|
|
|
const attachments = parseNumberedImageEntries(lastMatch[1]);
|
|
|
|
const stripped = (
|
|
text.slice(0, lastMatch.index) + '\n' + text.slice(lastMatch.index + lastMatch[0].length)
|
|
).trim();
|
|
|
|
return {
|
|
text: stripped,
|
|
imagePaths: attachments.map((attachment) => attachment.path),
|
|
attachments,
|
|
};
|
|
}
|
|
|
|
/** Maps raw image paths to the attachment shape carried by NormalizedMessage.images. */
|
|
export function toImageAttachments(imagePaths: string[]): Array<{ path: string }> {
|
|
return imagePaths.map((imagePath) => ({ path: toPosixPath(imagePath) }));
|
|
}
|
|
|
|
type ClaudeContentBlock =
|
|
| { type: 'text'; text: string }
|
|
| { type: 'image'; source: { type: 'base64'; media_type: string; data: string } };
|
|
|
|
/**
|
|
* Builds the Claude user-message content list: the prompt text followed by one
|
|
* base64 `image` block per attachment. Images the Claude API cannot accept
|
|
* (e.g. SVG) or that fail to read are skipped with a warning so the prompt
|
|
* itself still goes through.
|
|
*/
|
|
export async function buildClaudeUserContent(
|
|
prompt: string,
|
|
images: unknown,
|
|
cwd?: string,
|
|
): Promise<ClaudeContentBlock[]> {
|
|
const blocks: ClaudeContentBlock[] = [{ type: 'text', text: prompt }];
|
|
|
|
for (const descriptor of normalizeImageDescriptors(images)) {
|
|
const mediaType = resolveImageMediaType(descriptor);
|
|
if (!mediaType || !CLAUDE_IMAGE_MEDIA_TYPES.has(mediaType)) {
|
|
console.warn(`[Images] Skipping unsupported Claude image type for ${descriptor.path}`);
|
|
continue;
|
|
}
|
|
|
|
const resolvedPath = resolveImageAbsolutePath(cwd, descriptor.path);
|
|
if (!isAllowedImageSourcePath(resolvedPath, cwd)) {
|
|
console.warn(`[Images] Refusing to read image outside allowed roots: ${descriptor.path}`);
|
|
continue;
|
|
}
|
|
|
|
try {
|
|
const canonicalPath = await fs.realpath(resolvedPath);
|
|
if (!isAllowedImageSourcePath(canonicalPath, cwd)) {
|
|
console.warn(`[Images] Refusing to read symlinked image outside allowed roots: ${descriptor.path}`);
|
|
continue;
|
|
}
|
|
|
|
const bytes = await fs.readFile(canonicalPath);
|
|
blocks.push({
|
|
type: 'image',
|
|
source: {
|
|
type: 'base64',
|
|
media_type: mediaType,
|
|
data: bytes.toString('base64'),
|
|
},
|
|
});
|
|
} catch (error) {
|
|
const message = error instanceof Error ? error.message : String(error);
|
|
console.warn(`[Images] Failed to read image ${descriptor.path}: ${message}`);
|
|
}
|
|
}
|
|
|
|
return blocks;
|
|
}
|
|
|
|
type CodexInputItem =
|
|
| { type: 'text'; text: string }
|
|
| { type: 'local_image'; path: string };
|
|
|
|
/**
|
|
* Builds the Codex `runStreamed` input list: prompt text plus one
|
|
* `local_image` item per attachment, resolved to absolute paths so the Codex
|
|
* runtime can read them regardless of its own working directory handling.
|
|
*/
|
|
export function buildCodexInputItems(prompt: string, images: unknown, cwd?: string): CodexInputItem[] {
|
|
const items: CodexInputItem[] = [{ type: 'text', text: prompt }];
|
|
for (const descriptor of normalizeImageDescriptors(images)) {
|
|
const resolvedPath = resolveImageAbsolutePath(cwd, descriptor.path);
|
|
if (!isAllowedImageSourcePath(resolvedPath, cwd)) {
|
|
// Same trust boundary as buildClaudeUserContent — the Codex runtime
|
|
// reads this file, so it must stay within the allowed roots.
|
|
console.warn(`[Images] Refusing to attach image outside allowed roots: ${descriptor.path}`);
|
|
continue;
|
|
}
|
|
items.push({
|
|
type: 'local_image',
|
|
path: resolvedPath,
|
|
});
|
|
}
|
|
return items;
|
|
}
|