package mcp import ( "context" "crypto/sha256" "encoding/binary" "encoding/hex" "os" "strings" "testing" "time" "unicode/utf8" "github.com/yuanyuanxiang/SimpleRemoter/server/go/connection" "github.com/yuanyuanxiang/SimpleRemoter/server/go/hub" "github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol" ) // shortenTransferTimeouts makes the read_file watchdogs test-sized. The poll // interval stays well under the stall window so the stalled check is reached // deterministically. func shortenTransferTimeouts(t *testing.T, stall, total, poll time.Duration) { t.Helper() oldStall, oldTotal, oldPoll := fileTransferStallTimeout, fileTransferTotalTimeout, fileTransferPollInterval fileTransferStallTimeout, fileTransferTotalTimeout, fileTransferPollInterval = stall, total, poll t.Cleanup(func() { fileTransferStallTimeout, fileTransferTotalTimeout, fileTransferPollInterval = oldStall, oldTotal, oldPoll }) } // ----- wire builders --------------------------------------------------------- func chunkPacket(transferID uint64, fileIndex, totalFiles uint32, fileSize, offset uint64, flags uint16, name string, payload []byte) []byte { nameGBK := protocol.UTF8ToGBK(name) buf := make([]byte, fileChunkHeaderLen+len(nameGBK)+len(payload)) buf[0] = protocol.CommandSendFileV2 binary.LittleEndian.PutUint64(buf[fileChunkOffTransferID:], transferID) binary.LittleEndian.PutUint32(buf[fileChunkOffFileIndex:], fileIndex) binary.LittleEndian.PutUint32(buf[fileChunkOffTotalFiles:], totalFiles) binary.LittleEndian.PutUint64(buf[fileChunkOffFileSize:], fileSize) binary.LittleEndian.PutUint64(buf[fileChunkOffOffset:], offset) binary.LittleEndian.PutUint64(buf[fileChunkOffDataLength:], uint64(len(payload))) binary.LittleEndian.PutUint64(buf[fileChunkOffNameLength:], uint64(len(nameGBK))) binary.LittleEndian.PutUint16(buf[fileChunkOffFlags:], flags) copy(buf[fileChunkHeaderLen:], nameGBK) copy(buf[fileChunkHeaderLen+len(nameGBK):], payload) return buf } func completePacket(transferID uint64, fileIndex uint32, fileSize uint64, sum []byte) []byte { buf := make([]byte, fileCompleteHeaderLen) buf[0] = protocol.CommandFileCompleteV2 binary.LittleEndian.PutUint64(buf[fileCompleteOffTransferID:], transferID) binary.LittleEndian.PutUint32(buf[fileCompleteOffFileIndex:], fileIndex) binary.LittleEndian.PutUint64(buf[fileCompleteOffFileSize:], fileSize) copy(buf[fileCompleteOffSHA256:], sum) return buf } func downloadErrorPacket(win32err uint32) []byte { buf := make([]byte, 5) buf[0] = protocol.TokenDownloadError binary.LittleEndian.PutUint32(buf[1:], win32err) return buf } // ----- harness --------------------------------------------------------------- func (r *fileRig) callRead(args string) <-chan fileCall { ch := make(chan fileCall, 1) go func() { res, rerr := r.s.callReadFile(context.Background(), []byte(args)) if rerr != nil { ch <- fileCall{err: rerr} return } tr, ok := res.(toolResult) if !ok { ch <- fileCall{err: errf(CodeInternal, "unexpected result type %T", res)} return } ch <- fileCall{res: tr} }() return ch } // startReadCall runs one read_file call through the drive-list handshake and // returns the waiting call, the file-manager sub-conn, and the target directory // the server asked the client to write under (which is what real clients echo // back as the packet name prefix). func (r *fileRig) startReadCall(args string, drives ...driveRec) (<-chan fileCall, *connection.Context, string) { r.t.Helper() ch := r.callRead(args) if got := r.next(r.main); len(got) != 1 || got[0] != protocol.CommandListDrive { r.t.Fatalf("drive request wire = %v, want [%d]", got, protocol.CommandListDrive) } sub := r.newSub() if drives == nil { drives = []driveRec{{'C', 3, 500000, 123456, "本地磁盘", "NTFS"}} } if !r.s.OnFilePacket(sub, driveListPacket(drives...)) { r.t.Fatal("drive-list packet was not consumed") } got := r.next(sub) if got[0] != protocol.CmdDownFilesV2 { r.t.Fatalf("download request wire = %v, want token %d first", got, protocol.CmdDownFilesV2) } rest := got[1:] i := strings.IndexByte(string(rest), 0) if i < 0 { r.t.Fatal("download request has no NUL after targetDir") } targetDir := string(rest[:i]) if !strings.HasSuffix(targetDir, string(os.PathSeparator)) { r.t.Fatalf("targetDir %q does not end with a path separator", targetDir) } return ch, sub, targetDir } // readOutput pulls the structured output out of a successful call. func readOutput(t *testing.T, c fileCall) readFileOutput { t.Helper() if c.err != nil { t.Fatalf("read_file failed: %d %s", c.err.Code, c.err.Message) } out, ok := c.res.StructuredContent.(readFileOutput) if !ok { t.Fatalf("structured content type = %T", c.res.StructuredContent) } return out } // ----- name validation ------------------------------------------------------- func TestTransferNameWithinDir(t *testing.T) { const sep = `\` target := "C:" + sep + "Users" + sep + "tmp" + sep + "yama-mcp-read-1" + sep cases := []struct { name string want string // "" means rejected }{ {target + "file.txt", "file.txt"}, {target + `sub\file.txt`, "sub/file.txt"}, {target + "a//b.txt", "a/b.txt"}, {"../x", ""}, {`..\..\x`, ""}, {`C:\Windows\x`, ""}, {"/etc/passwd", ""}, {`\\server\share\x`, ""}, {`a/../../b`, ""}, {target + `sub\..\..\..\x`, ""}, {target, ""}, {"", ""}, {"x\x00y", ""}, {"x\ny", ""}, } for _, c := range cases { got, ok := transferNameWithinDir(target, c.name) if c.want == "" { if ok { t.Errorf("transferNameWithinDir(%q) = %q, want rejection", c.name, got) } continue } if !ok || got != c.want { t.Errorf("transferNameWithinDir(%q) = %q,%v, want %q", c.name, got, ok, c.want) } } } // ----- end-to-end transfers -------------------------------------------------- func TestReadFileWindowsStreamSubConn(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, fm, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\cfg\\app.ini"}`) content := []byte("line1\r\nline2\r\nline3\r\n") split := 8 stream := rig.newSub() // Windows clients open a fresh authenticated sub-conn name := targetDir + "app.ini" rig.s.OnTransferPacket(stream, chunkPacket(42, 0, 1, uint64(len(content)), 0, 0, name, content[:split])) rig.s.OnTransferPacket(stream, chunkPacket(42, 0, 1, uint64(len(content)), uint64(split), ffV2LastChunk, name, content[split:])) sum := sha256.Sum256(content) rig.s.OnTransferPacket(stream, completePacket(42, 0, uint64(len(content)), sum[:])) out := readOutput(t, rig.wait(ch)) if out.Size != len(content) || out.Text != "line1\nline2\nline3" { t.Fatalf("text = %q size=%d", out.Text, out.Size) } if out.Encoding != "utf-8" || out.EOL != "crlf" { t.Fatalf("encoding=%q eol=%q", out.Encoding, out.EOL) } if out.LinesTotal != 3 || out.LinesReturned != 3 || out.Truncated { t.Fatalf("lines_total=%d lines_returned=%d truncated=%v", out.LinesTotal, out.LinesReturned, out.Truncated) } if want := hex.EncodeToString(sum[:]); out.SHA256 != want { t.Fatalf("sha256 = %q, want %q", out.SHA256, want) } if !strings.Contains(out.Path, "app.ini") { t.Fatalf("path = %q", out.Path) } // The file-manager sub-conn is retired once the call returns. waitClosed(t, fm) } func TestReadFilePosixChunksOnFileManagerConn(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, fm, targetDir := rig.startReadCall(`{"id":"1001","path":"/etc/app.conf"}`, driveRec{'/', 4, 100000, 1000, "Linux", "ext4"}) content := []byte("a=1\nb=2\n") name := targetDir + "app.conf" rig.s.OnTransferPacket(fm, chunkPacket(7, 0, 1, uint64(len(content)), 0, ffV2LastChunk, name, content)) sum := sha256.Sum256(content) rig.s.OnTransferPacket(fm, completePacket(7, 0, uint64(len(content)), sum[:])) out := readOutput(t, rig.wait(ch)) if out.Text != "a=1\nb=2" || out.EOL != "lf" { t.Fatalf("text=%q eol=%q", out.Text, out.EOL) } } func TestReadFilePosixRejectsWindowsPath(t *testing.T) { rig := newFileRig(t) ch := rig.callRead(`{"id":"1001","path":"C:\\cfg\\app.ini"}`) if got := rig.next(rig.main); len(got) != 1 || got[0] != protocol.CommandListDrive { t.Fatalf("drive request wire = %v", got) } fm := rig.newSub() if !rig.s.OnFilePacket(fm, driveListPacket(driveRec{'/', 4, 100000, 1000, "Linux", "ext4"})) { t.Fatal("drive-list packet was not consumed") } // The path is checked before anything goes out on the file-manager conn. c := rig.wait(ch) if c.err == nil || c.err.Code != CodeInvalidParams { t.Fatalf("error = %+v, want -32602", c.err) } if !strings.Contains(c.err.Message, "absolute POSIX path") { t.Fatalf("message = %q", c.err.Message) } waitClosed(t, fm) } func TestReadFileSizeGate(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) rig.s.cfg.ReadMax = 4096 ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\big.bin"}`) stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 5000, 0, 0, targetDir+"big.bin", make([]byte, 100))) c := rig.wait(ch) if c.err == nil || c.err.Code != CodeInvalidParams { t.Fatalf("error = %+v, want -32602", c.err) } if !strings.Contains(c.err.Message, "no download_file") || !strings.Contains(c.err.Message, "terminal_exec") { t.Fatalf("message = %q", c.err.Message) } } func TestReadFileDirectoryRejected(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\folder"}`) stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 0, 0, ffV2Directory, targetDir+"folder\\", nil)) c := rig.wait(ch) if c.err == nil || c.err.Code != CodeInvalidParams { t.Fatalf("error = %+v, want -32602", c.err) } if !strings.Contains(c.err.Message, "Not a single regular file") { t.Fatalf("message = %q", c.err.Message) } } // TestReadFileMultiFileBatchRejected pins the expanded-directory case: the // client turns a directory path into a multi-file batch and stamps totalFiles on // every chunk, so the very first chunk must fail the call. Waiting for a second // fileIndex is not enough — file 0's completion packet would end the call and its // content would be returned as if it were the requested path. func TestReadFileMultiFileBatchRejected(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\dir"}`) stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(5, 0, 2, 3, 0, ffV2LastChunk, targetDir+`dir\a.txt`, []byte("aaa"))) sum := sha256.Sum256([]byte("aaa")) // Even a matching completion must not rescue a multi-file batch. rig.s.OnTransferPacket(stream, completePacket(5, 0, 3, sum[:])) c := rig.wait(ch) if c.err == nil || c.err.Code != CodeInvalidParams { t.Fatalf("error = %+v, want -32602", c.err) } if !strings.Contains(c.err.Message, "single regular file") { t.Fatalf("message = %q", c.err.Message) } } func TestReadFileSecondFileIndexRejected(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\dir"}`) stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(9, 0, 2, 3, 0, 0, targetDir+"a.txt", []byte("abc"))) rig.s.OnTransferPacket(stream, chunkPacket(9, 1, 2, 3, 0, 0, targetDir+"b.txt", []byte("xyz"))) c := rig.wait(ch) if c.err == nil || c.err.Code != CodeInvalidParams { t.Fatalf("error = %+v, want -32602", c.err) } } func TestReadFileSHA256Mismatch(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`) content := []byte("hello") stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(3, 0, 1, 5, 0, ffV2LastChunk, targetDir+"a.txt", content)) bad := make([]byte, sha256.Size) rig.s.OnTransferPacket(stream, completePacket(3, 0, 5, bad)) c := rig.wait(ch) if c.err == nil || c.err.Code != CodeInternal { t.Fatalf("error = %+v, want -32000", c.err) } if !strings.Contains(c.err.Message, "SHA-256") { t.Fatalf("message = %q", c.err.Message) } } func TestReadFileEmptyFile(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, _, _ := rig.startReadCall(`{"id":"1001","path":"C:\\empty.txt"}`) // Windows clients send no chunk for an empty file, only the completion. stream := rig.newSub() sum := sha256.Sum256(nil) rig.s.OnTransferPacket(stream, completePacket(5, 0, 0, sum[:])) out := readOutput(t, rig.wait(ch)) if out.Size != 0 || out.Text != "" || out.LinesTotal != 0 || out.LinesReturned != 0 || out.Truncated { t.Fatalf("empty file output = %+v", out) } if out.EOL != "none" { t.Fatalf("eol = %q, want none", out.EOL) } if want := hex.EncodeToString(sum[:]); out.SHA256 != want { t.Fatalf("sha256 = %q, want %q", out.SHA256, want) } } func TestReadFileDropsForeignTransferIDChunks(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`) content := []byte("payload") name := targetDir + "a.txt" stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(100, 0, 1, uint64(len(content)), 0, 0, name, content[:3])) // A late chunk from another (older) transfer must not disturb this one. rig.s.OnTransferPacket(stream, chunkPacket(99, 0, 1, 999, 0, 0, `C:\stale`, []byte("zzz"))) rig.s.OnTransferPacket(stream, chunkPacket(100, 0, 1, uint64(len(content)), 3, ffV2LastChunk, name, content[3:])) sum := sha256.Sum256(content) rig.s.OnTransferPacket(stream, completePacket(100, 0, uint64(len(content)), sum[:])) out := readOutput(t, rig.wait(ch)) if out.Text != string(content) { t.Fatalf("text = %q", out.Text) } } // TestReadFileIgnoresStaleStreamFromEarlierCall covers the live race that // surfaced as "Path traversal detected": once the server rejects a transfer (the // size gate is the usual reason) the client keeps streaming the rest of its // batch on the sub-connection it opened for that earlier call. Those late bytes // must be dropped, not adopted as the new call's stream — adopting them failed // the fresh call with a traversal error, and the stale connection closing would // have failed it as "connection lost" too. func TestReadFileIgnoresStaleStreamFromEarlierCall(t *testing.T) { shortenTransferTimeouts(t, 500*time.Millisecond, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) stale := rig.newSub() // the rejected earlier call's data sub-conn ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\b.txt"}`) content := []byte("good") name := targetDir + "b.txt" rig.s.OnTransferPacket(stale, chunkPacket(7, 0, 1, 3<<20, 0, 0, `C:\Users\tmp\yama-mcp-read-old\big.bin`, []byte("zz"))) empty := sha256.Sum256(nil) rig.s.OnTransferPacket(stale, completePacket(7, 0, 0, empty[:])) stream := rig.newSub() // opened after the download request, as Windows does rig.s.OnTransferPacket(stream, chunkPacket(42, 0, 1, uint64(len(content)), 0, ffV2LastChunk, name, content)) sum := sha256.Sum256(content) rig.s.OnTransferPacket(stream, completePacket(42, 0, uint64(len(content)), sum[:])) out := readOutput(t, rig.wait(ch)) if out.Text != string(content) { t.Fatalf("text = %q, want %q", out.Text, content) } if out.SHA256 != hex.EncodeToString(sum[:]) { t.Fatalf("sha256 = %s, want %s", out.SHA256, hex.EncodeToString(sum[:])) } } // TestReadFileClosesStreamSubConn checks that the call hangs up the client's // data sub-connection when it ends, so a batch the server stopped reading does // not keep streaming in the background. func TestReadFileClosesStreamSubConn(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\c.txt"}`) content := []byte("bye") stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, uint64(len(content)), 0, ffV2LastChunk, targetDir+"c.txt", content)) sum := sha256.Sum256(content) rig.s.OnTransferPacket(stream, completePacket(1, 0, uint64(len(content)), sum[:])) readOutput(t, rig.wait(ch)) if !stream.IsClosed() { t.Fatal("data sub-conn is still open after the call returned") } } func TestReadFileDownloadErrorMapping(t *testing.T) { cases := []struct { win32 int code int frag string }{ {2, CodeNotFound, "does not exist"}, {3, CodeNotFound, "does not exist"}, {5, CodePermission, "Access denied"}, {87, CodeInternal, "could not queue"}, } for _, c := range cases { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, fm, _ := rig.startReadCall(`{"id":"1001","path":"C:\\missing.txt"}`) rig.s.OnTransferPacket(fm, downloadErrorPacket(uint32(c.win32))) got := rig.wait(ch) if got.err == nil || got.err.Code != c.code { t.Fatalf("win32=%d error = %+v, want code %d", c.win32, got.err, c.code) } if !strings.Contains(got.err.Message, c.frag) { t.Fatalf("win32=%d message = %q, want %q", c.win32, got.err.Message, c.frag) } } } func TestReadFileOutOfOrderChunkRejected(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`) stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 10, 4, 0, targetDir+"a.txt", []byte("4567"))) c := rig.wait(ch) if c.err == nil || c.err.Code != CodeInternal { t.Fatalf("error = %+v, want -32000", c.err) } if !strings.Contains(c.err.Message, "offset") { t.Fatalf("message = %q", c.err.Message) } } func TestReadFileTraversalChunkRejected(t *testing.T) { shortenTransferTimeouts(t, time.Second, 5*time.Second, 5*time.Millisecond) rig := newFileRig(t) ch, _, _ := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`) stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 5, 0, ffV2LastChunk, `..\..\evil`, []byte("hello"))) c := rig.wait(ch) if c.err == nil || c.err.Code != CodeInternal { t.Fatalf("error = %+v, want -32000", c.err) } if !strings.Contains(c.err.Message, "Path traversal") { t.Fatalf("message = %q", c.err.Message) } } func TestReadFileStallTimesOut(t *testing.T) { shortenTransferTimeouts(t, 150*time.Millisecond, 5*time.Second, 10*time.Millisecond) rig := newFileRig(t) ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`) stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 10, 0, 0, targetDir+"a.txt", []byte("12345"))) c := rig.wait(ch) if c.err == nil || c.err.Code != CodeTimeout { t.Fatalf("error = %+v, want -32001", c.err) } if !strings.Contains(c.err.Message, "stalled") { t.Fatalf("message = %q", c.err.Message) } } func TestReadFileStreamClosedFailsFast(t *testing.T) { shortenTransferTimeouts(t, 10*time.Second, 20*time.Second, 10*time.Millisecond) rig := newFileRig(t) ch, _, targetDir := rig.startReadCall(`{"id":"1001","path":"C:\\a.txt"}`) stream := rig.newSub() rig.s.OnTransferPacket(stream, chunkPacket(1, 0, 1, 10, 0, 0, targetDir+"a.txt", []byte("12345"))) _ = stream.Close() c := rig.wait(ch) if c.err == nil || c.err.Code != CodeTimeout { t.Fatalf("error = %+v, want -32001", c.err) } if !strings.Contains(c.err.Message, "Connection lost") { t.Fatalf("message = %q", c.err.Message) } } func TestReadFileRequiresV2Capability(t *testing.T) { rig := newFileRig(t) rig.h.Register(&hub.Device{ID: "1001", PeerIP: "10.0.0.1"}, rig.main) // no capability ch := rig.callRead(`{"id":"1001","path":"C:\\a.txt"}`) c := rig.wait(ch) if c.err == nil || c.err.Code != CodeUnsupported { t.Fatalf("error = %+v, want -32005", c.err) } rig.expectNothing() } // ----- text decoding and windowing ------------------------------------------ func TestBuildReadFileResultGBK(t *testing.T) { rawGBK := protocol.UTF8ToGBK("中文\r\nabc") res := buildReadFileResult("/tmp/x.conf", rawGBK, "abc", "auto", 0, 2000, 262144) out := res.StructuredContent.(readFileOutput) if out.Encoding != "gbk" || out.EOL != "crlf" { t.Fatalf("encoding=%q eol=%q", out.Encoding, out.EOL) } if out.Text != "中文\nabc" || out.LinesTotal != 2 { t.Fatalf("text=%q lines_total=%d", out.Text, out.LinesTotal) } if !strings.Contains(res.Content[0].Text, "[read_file] /tmp/x.conf") { t.Fatalf("head line = %q", res.Content[0].Text) } } func TestBuildReadFileResultNegativeOffset(t *testing.T) { res := buildReadFileResult("x", []byte("a\nb\nc\n"), "s", "auto", -2, 2000, 262144) out := res.StructuredContent.(readFileOutput) if out.Offset != 1 || out.Text != "b\nc" || out.LinesReturned != 2 || out.Truncated { t.Fatalf("output = %+v", out) } } func TestBuildReadFileResultLimit(t *testing.T) { res := buildReadFileResult("x", []byte("a\nb\nc\n"), "s", "auto", 0, 1, 262144) out := res.StructuredContent.(readFileOutput) if out.Text != "a" || out.LinesReturned != 1 || !out.Truncated { t.Fatalf("output = %+v", out) } } func TestBuildReadFileResultMaxBytesCutOnCharBoundary(t *testing.T) { line := strings.Repeat("中", 400) // 1200 UTF-8 bytes, one line res := buildReadFileResult("x", []byte(line), "s", "auto", 0, 2000, 1024) out := res.StructuredContent.(readFileOutput) if !out.Truncated || out.LinesReturned != 1 { t.Fatalf("truncated=%v lines_returned=%d", out.Truncated, out.LinesReturned) } if len(out.Text) != 1023 || !utf8.ValidString(out.Text) { t.Fatalf("cut text is %d bytes and valid=%v, want 1023 valid bytes", len(out.Text), utf8.ValidString(out.Text)) } } func TestBuildReadFileResultEncodings(t *testing.T) { // UTF-16LE with BOM. le := []byte{0xFF, 0xFE, 'h', 0, 'i', 0} if out := buildReadFileResult("x", le, "s", "auto", 0, 10, 1024).StructuredContent.(readFileOutput); out.Encoding != "utf-16le" || out.Text != "hi" { t.Fatalf("utf-16le output = %+v", out) } // UTF-8 BOM is stripped. bom := append([]byte{0xEF, 0xBB, 0xBF}, []byte("hi")...) if out := buildReadFileResult("x", bom, "s", "auto", 0, 10, 1024).StructuredContent.(readFileOutput); out.Encoding != "utf-8" || out.Text != "hi" { t.Fatalf("utf-8 bom output = %+v", out) } // Latin-1 is explicit only (byte 0xE9 would otherwise be invalid UTF-8 → GBK). if out := buildReadFileResult("x", []byte{0xE9}, "s", "latin1", 0, 10, 1024).StructuredContent.(readFileOutput); out.Encoding != "latin1" || out.Text != "é" { t.Fatalf("latin1 output = %+v", out) } } func TestDetectEOLVariants(t *testing.T) { cases := map[string]string{ "": "none", "abc": "none", "a\r\nb": "crlf", "a\nb": "lf", "a\rb": "cr", "a\r\nb\n": "mixed", } for in, want := range cases { if got := detectEOL(in); got != want { t.Errorf("detectEOL(%q) = %q, want %q", in, got, want) } } } func TestSplitTextLines(t *testing.T) { if got := splitTextLines(""); got != nil { t.Fatalf("empty text = %v", got) } if got := splitTextLines("a\nb\n"); len(got) != 2 || got[1] != "b" { t.Fatalf("a\\nb\\n = %v", got) } if got := splitTextLines("\n"); len(got) != 1 || got[0] != "" { t.Fatalf("\\n = %v", got) } }