JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix (tui): Add readdirSync fallback for TUI @ file autocomplete Refs:#1510
haowenzhong1d6bb19faf311
diff --git a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.tsindex 1f42cf3cf2..47a3796a3c 100644--- a/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts+++ b/jiuwenswarm/channels/tui/frontend/src/ui/app-screen.ts@@ -306,10 +306,188 @@ type FileViewerState = {searchTerm: string; // Search term};+const PATH_DELIMITERS = new Set([" ", "\t", '"', "'", "="]);++function findLastPathDelimiter(text: string): number {+ for (let i = text.length - 1; i >= 0; i--) {+ if (PATH_DELIMITERS.has(text[i] ?? "")) return i;+ }+ return -1;+}++function isPathTokenStart(text: string, index: number): boolean {+ return index === 0 || PATH_DELIMITERS.has(text[index - 1] ?? "");+}++function extractQuotedAtPrefix(text: string): string | null {+ let inQuotes = false;+ let quoteStart = -1;+ for (let i = 0; i < text.length; i++) {+ if (text[i] === '"') {+ inQuotes = !inQuotes;+ if (inQuotes) quoteStart = i;+ }+ }+ if (!inQuotes) return null;+ if (quoteStart > 0 && text[quoteStart - 1] === "@") {+ if (!isPathTokenStart(text, quoteStart - 1)) return null;+ return text.slice(quoteStart - 1);+ }+ if (!isPathTokenStart(text, quoteStart)) return null;+ return text.slice(quoteStart);+}++function extractAtPrefix(textBeforeCursor: string): string | null {+ const quotedPrefix = extractQuotedAtPrefix(textBeforeCursor);+ if (quotedPrefix?.startsWith('@"')) return quotedPrefix;+ const lastDelim = findLastPathDelimiter(textBeforeCursor);+ const tokenStart = lastDelim === -1 ? 0 : lastDelim + 1;+ if (textBeforeCursor[tokenStart] === "@") {+ return textBeforeCursor.slice(tokenStart);+ }+ return null;+}++interface ParsedPathPrefix {+ rawPrefix: string;+ isAtPrefix: boolean;+ isQuotedPrefix: boolean;+}++function parseAtPathPrefix(prefix: string): ParsedPathPrefix {+ if (prefix.startsWith('@"')) return { rawPrefix: prefix.slice(2), isAtPrefix: true, isQuotedPrefix: true };+ if (prefix.startsWith('"')) return { rawPrefix: prefix.slice(1), isAtPrefix: false, isQuotedPrefix: true };+ if (prefix.startsWith("@")) return { rawPrefix: prefix.slice(1), isAtPrefix: true, isQuotedPrefix: false };+ return { rawPrefix: prefix, isAtPrefix: false, isQuotedPrefix: false };+}++function expandHomePrefix(filePath: string): string {+ if (filePath.startsWith("~/")) {+ const expanded = path.join(os.homedir(), filePath.slice(2));+ return filePath.endsWith("/") && !expanded.endsWith(path.sep) ? `${expanded}/` : expanded;+ }+ if (filePath === "~") return os.homedir();+ return filePath;+}++function buildAtCompletionValue(filePath: string, opts: { isAtPrefix: boolean; isQuotedPrefix: boolean }): string {+ const needsQuotes = opts.isQuotedPrefix || filePath.includes(" ");+ const at = opts.isAtPrefix ? "@" : "";+ if (!needsQuotes) return `${at}${filePath}`;+ return `${at}"${filePath}"`;+}++function fallbackAtFileSuggestions(+ textBeforeCursor: string,+ cwd: string,+): { items: AutocompleteItem[]; prefix: string } | null {+ const atPrefix = extractAtPrefix(textBeforeCursor);+ if (!atPrefix) return null;++ const { rawPrefix, isAtPrefix, isQuotedPrefix } = parseAtPathPrefix(atPrefix);+ let expandedPrefix = rawPrefix;+ if (expandedPrefix.startsWith("~")) {+ expandedPrefix = expandHomePrefix(expandedPrefix);+ }++ const isRootPrefix =+ rawPrefix === "" ||+ rawPrefix === "./" ||+ rawPrefix === "../" ||+ rawPrefix === "~" ||+ rawPrefix === "~/" ||+ rawPrefix === "/" ||+ (isAtPrefix && rawPrefix === "");++ let searchDir: string;+ let searchPrefix: string;++ if (isRootPrefix) {+ searchDir = rawPrefix.startsWith("~") || expandedPrefix.startsWith("/") ? expandedPrefix : path.join(cwd, expandedPrefix);+ searchPrefix = "";+ } else if (rawPrefix.endsWith("/")) {+ searchDir = rawPrefix.startsWith("~") || expandedPrefix.startsWith("/") ? expandedPrefix : path.join(cwd, expandedPrefix);+ searchPrefix = "";+ } else {+ const dir = path.dirname(expandedPrefix);+ const file = path.basename(expandedPrefix);+ searchDir = rawPrefix.startsWith("~") || expandedPrefix.startsWith("/") ? dir : path.join(cwd, dir);+ searchPrefix = file;+ }++ let entries: fs.Dirent[];+ try {+ entries = fs.readdirSync(searchDir, { withFileTypes: true });+ } catch {+ return null;+ }++ const suggestions: AutocompleteItem[] = [];+ for (const entry of entries) {+ if (!entry.name.toLowerCase().startsWith(searchPrefix.toLowerCase())) continue;++ let isDirectory = entry.isDirectory();+ if (!isDirectory && entry.isSymbolicLink()) {+ try {+ isDirectory = fs.statSync(path.join(searchDir, entry.name)).isDirectory();+ } catch {+ continue;+ }+ }++ const name = entry.name;+ const displayPrefix = rawPrefix;+ let relativePath: string;++ if (displayPrefix.endsWith("/")) {+ relativePath = displayPrefix + name;+ } else if (displayPrefix.includes("/") || displayPrefix.includes("\\")) {+ if (displayPrefix.startsWith("~/")) {+ const homeRelativeDir = displayPrefix.slice(2);+ const parentDir = path.dirname(homeRelativeDir);+ relativePath = `~/${parentDir === "." ? name : path.join(parentDir, name)}`;+ } else if (displayPrefix.startsWith("/")) {+ const parentDir = path.dirname(displayPrefix);+ relativePath = parentDir === "/" ? `/${name}` : `${parentDir}/${name}`;+ } else {+ relativePath = path.join(path.dirname(displayPrefix), name);+ if (displayPrefix.startsWith("./") && !relativePath.startsWith("./")) {+ relativePath = `./${relativePath}`;+ }+ }+ } else {+ relativePath = displayPrefix.startsWith("~") ? `~/${name}` : name;+ }++ relativePath = relativePath.replace(/\\/g, "/");+ const pathValue = isDirectory ? `${relativePath}/` : relativePath;+ const value = buildAtCompletionValue(pathValue, { isAtPrefix, isQuotedPrefix });+ const displayLabel = relativePath + (isDirectory ? "/" : "");+ suggestions.push({+ value,+ label: displayLabel,+ description: isDirectory ? "directory" : undefined,+ });+ }++ suggestions.sort((a, b) => {+ const aIsDir = a.value.endsWith("/");+ const bIsDir = b.value.endsWith("/");+ if (aIsDir && !bIsDir) return -1;+ if (!aIsDir && bIsDir) return 1;+ return a.label.localeCompare(b.label);+ });++ return suggestions.length > 0 ? { items: suggestions, prefix: atPrefix } : null;+}+class ComposerAutocompleteProvider implements AutocompleteProvider {- constructor(private readonly inner: AutocompleteProvider) {}+ constructor(+ private readonly inner: AutocompleteProvider,+ private readonly cwd: string,+ ) {}- getSuggestions(+ async getSuggestions(lines: string[],cursorLine: number,cursorCol: number,@@ -321,10 +499,20 @@ class ComposerAutocompleteProvider implements AutocompleteProvider {textBeforeCursor.startsWith("/") && !textBeforeCursor.includes(" ");if (isCommandNameCompletion && cursorCol !== currentLine.length) {- return Promise.resolve(null);+ return null;+ }++ const innerResult = await this.inner.getSuggestions(lines, cursorLine, cursorCol, options);+ if (innerResult) return innerResult;++ if (options.signal.aborted) return null;++ const atPrefix = extractAtPrefix(textBeforeCursor);+ if (atPrefix) {+ return fallbackAtFileSuggestions(textBeforeCursor, this.cwd);}- return this.inner.getSuggestions(lines, cursorLine, cursorCol, options);+ return null;}applyCompletion(@@ -342,7 +530,16 @@ class ComposerAutocompleteProvider implements AutocompleteProvider {return { lines, cursorLine, cursorCol };}- return this.inner.applyCompletion(lines, cursorLine, cursorCol, item, prefix);+ const result = this.inner.applyCompletion(lines, cursorLine, cursorCol, item, prefix);++ if (prefix.startsWith("@") && !result.lines[result.cursorLine]?.endsWith(" ")) {+ const line = result.lines[result.cursorLine] ?? "";+ const newLines = [...result.lines];+ newLines[result.cursorLine] = line + " ";+ return { lines: newLines, cursorLine: result.cursorLine, cursorCol: result.cursorCol + 1 };+ }++ return result;}}@@ -5013,6 +5210,7 @@ export class AppScreen implements Component, Focusable {getCurrentCwd() || process.cwd(),resolveFdBinary(),),+ getCurrentCwd() || process.cwd(),);}diff --git a/tests/unit_tests/gateway/test_at_file_references.py b/tests/unit_tests/gateway/test_at_file_references.pynew file mode 100644index 0000000000..7d69bce985--- /dev/null+++ b/tests/unit_tests/gateway/test_at_file_references.py@@ -0,0 +1,268 @@+"""Tests for @file reference resolution (resolve_at_file_references, _resolve_structured_attachments)."""++import os+import tempfile++from jiuwenswarm.gateway.message_handler.message_handler import MessageHandler+++class TestResolveAtFileReferences:+ """Test resolve_at_file_references() — @path → <file-content> inlining."""++ @staticmethod+ def test_inlines_file_content():+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".py", delete=False+ ) as f:+ f.write("print('hello')\nprint('world')")+ fname = f.name+ try:+ basename = os.path.basename(fname)+ cwd = os.path.dirname(fname)+ result = MessageHandler.resolve_at_file_references(f"check @{basename}", cwd=cwd)+ assert "<file-content" in result+ assert "print('hello')" in result+ assert "print('world')" in result+ assert f'path="{basename}"' in result+ finally:+ os.unlink(fname)++ @staticmethod+ def test_quoted_path_with_spaces():+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".txt", prefix="my file", delete=False+ ) as f:+ f.write("hello world")+ fname = f.name+ try:+ basename = os.path.basename(fname)+ cwd = os.path.dirname(fname)+ result = MessageHandler.resolve_at_file_references(+ f'check @"{basename}"', cwd=cwd+ )+ assert "<file-content" in result+ assert "hello world" in result+ assert f'path="{basename}"' in result+ finally:+ os.unlink(fname)++ @staticmethod+ def test_absolute_path():+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".py", delete=False+ ) as f:+ f.write("abs content")+ fname = f.name+ try:+ result = MessageHandler.resolve_at_file_references(f"check @{fname}", cwd="/tmp")+ assert "<file-content" in result+ assert "abs content" in result+ assert f'path="{fname}"' in result+ finally:+ os.unlink(fname)++ @staticmethod+ def test_home_directory_expansion():+ home = os.path.expanduser("~")+ rel_path = ".jiuwenswarm_test_at_ref.txt"+ abs_path = os.path.join(home, rel_path)+ try:+ with open(abs_path, "w") as f:+ f.write("home content")+ result = MessageHandler.resolve_at_file_references(+ f"check @~/{rel_path}", cwd="/tmp"+ )+ assert "<file-content" in result+ assert "home content" in result+ finally:+ try:+ os.unlink(abs_path)+ except OSError:+ pass++ @staticmethod+ def test_file_not_found_preserves_original():+ result = MessageHandler.resolve_at_file_references(+ "check @nonexistent_file_12345.txt", cwd="/tmp"+ )+ assert "<file-content" not in result+ assert "@nonexistent_file_12345.txt" in result++ @staticmethod+ def test_max_file_size_truncation():+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".txt", delete=False+ ) as f:+ f.write("A" * 200)+ fname = f.name+ try:+ basename = os.path.basename(fname)+ cwd = os.path.dirname(fname)+ result = MessageHandler.resolve_at_file_references(+ f"check @{basename}", cwd=cwd, max_file_size=100+ )+ assert "<file-content" in result+ assert "truncated" in result+ assert "original_size=200" in result+ assert len("A" * 100) < len(result) < len("A" * 200) + 200+ finally:+ os.unlink(fname)++ @staticmethod+ def test_no_truncation_when_max_size_none():+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".txt", delete=False+ ) as f:+ f.write("B" * 300)+ fname = f.name+ try:+ basename = os.path.basename(fname)+ cwd = os.path.dirname(fname)+ result = MessageHandler.resolve_at_file_references(+ f"check @{basename}", cwd=cwd, max_file_size=None+ )+ assert "<file-content" in result+ assert "B" * 300 in result+ assert "truncated" not in result+ finally:+ os.unlink(fname)++ @staticmethod+ def test_line_range_syntax_ignored_whole_file_read():+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".py", delete=False+ ) as f:+ f.write("line1\nline2\nline3\nline4\nline5")+ fname = f.name+ try:+ basename = os.path.basename(fname)+ cwd = os.path.dirname(fname)+ result = MessageHandler.resolve_at_file_references(+ f"check @{basename}#L2-4", cwd=cwd+ )+ assert "<file-content" in result+ assert "line1" in result+ assert "line5" in result+ finally:+ os.unlink(fname)++ @staticmethod+ def test_multiple_at_references():+ f1 = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False)+ f2 = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False)+ f1.write("first")+ f1.close()+ f2.write("second")+ f2.close()+ try:+ b1 = os.path.basename(f1.name)+ b2 = os.path.basename(f2.name)+ cwd = os.path.dirname(f1.name)+ result = MessageHandler.resolve_at_file_references(+ f"compare @{b1} with @{b2}", cwd=cwd+ )+ assert result.count("<file-content") == 2+ assert "first" in result+ assert "second" in result+ finally:+ os.unlink(f1.name)+ os.unlink(f2.name)++ @staticmethod+ def test_empty_content_returns_empty():+ result = MessageHandler.resolve_at_file_references("", cwd="/tmp")+ assert result == ""++ @staticmethod+ def test_no_at_symbol_returns_unchanged():+ result = MessageHandler.resolve_at_file_references("hello world", cwd="/tmp")+ assert result == "hello world"+++class TestStripAttachedMentions:+ """Test strip_attached_mentions() — remove @path tokens already in attachments list."""++ @staticmethod+ def test_strips_attached_path():+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".py", delete=False+ ) as f:+ f.write("code")+ fname = f.name+ try:+ content = f"check @{fname} for bugs"+ attachments = [{"path": fname, "type": "file"}]+ result = MessageHandler.strip_attached_mentions(content, attachments)+ assert f"@{fname}" not in result+ assert os.path.basename(fname) in result+ finally:+ os.unlink(fname)++ @staticmethod+ def test_no_attachments_returns_unchanged():+ content = "check @somefile.py for bugs"+ result = MessageHandler.strip_attached_mentions(content, [])+ assert result == content++ @staticmethod+ def test_non_matching_path_unchanged():+ content = "check @other.py for bugs"+ attachments = [{"path": "/tmp/different.py", "type": "file"}]+ result = MessageHandler.strip_attached_mentions(content, attachments)+ assert "@other.py" in result+++class TestStructuredAttachmentsIntegration:+ """Test that structured-attachment-style input is correctly resolved via public APIs."""++ @staticmethod+ def test_attachment_content_inlined_by_at_reference():+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".py", delete=False+ ) as f:+ f.write("structured content")+ fname = f.name+ try:+ content = f'@"{fname}" please review this code'+ result = MessageHandler.resolve_at_file_references(content)+ assert "<file-content" in result+ assert "structured content" in result+ assert "please review this code" in result+ finally:+ os.unlink(fname)++ @staticmethod+ def test_no_at_reference_returns_unchanged():+ result = MessageHandler.resolve_at_file_references("hello @test.py")+ assert result == "hello @test.py"++ @staticmethod+ def test_duplicate_at_references_resolve_to_single():+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".py", delete=False+ ) as f:+ f.write("dedup")+ fname = f.name+ try:+ content = f'@"{fname}" review @"{fname}" this'+ result = MessageHandler.resolve_at_file_references(content)+ assert result.count("<file-content") == 2+ assert "dedup" in result+ finally:+ os.unlink(fname)++ @staticmethod+ def test_mixed_at_file_and_plain_text():+ with tempfile.NamedTemporaryFile(+ mode="w", suffix=".py", delete=False+ ) as f:+ f.write("plain text content")+ fname = f.name+ try:+ content = f"plain message with @{fname} embedded"+ result = MessageHandler.resolve_at_file_references(content)+ assert "<file-content" in result+ assert "plain text content" in result+ assert "plain message with" in result+ finally:+ os.unlink(fname)