package tools
import (
"archive/zip"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"strings"
"testing"
"academy/internal/models/chat"
"academy/internal/sandbox"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// fakeTranslateStore is an in-memory SessionFileSink + dir ensurer.
type fakeTranslateStore struct {
files map[string][]byte
ensured []string
writePath string
}
func (s *fakeTranslateStore) EnsureSessionDir(_ context.Context, _, dir string) error {
s.ensured = append(s.ensured, dir)
return nil
}
func (s *fakeTranslateStore) StatSessionFile(_ context.Context, _, _ string) (*sandbox.RemoteStatEntry, error) {
return nil, fmt.Errorf("not implemented")
}
func (s *fakeTranslateStore) ReadSessionFile(_ context.Context, _, path string) ([]byte, error) {
if data, ok := s.files[path]; ok {
return data, nil
}
return nil, fmt.Errorf("no such file: %s", path)
}
func (s *fakeTranslateStore) WriteSessionWorkspaceFile(_ context.Context, _, path string, content []byte) error {
s.files[path] = content
s.writePath = path
return nil
}
// fakeTranslateTempDoc is an in-memory TemporaryDocumentService covering the
// surface xlsx_translate uses. Unimplemented methods panic via the embedded
// nil interface — the tool must not call them.
type fakeTranslateTempDoc struct {
interfaces.TemporaryDocumentService
docs []*types.TemporaryDocument
created []*types.TemporaryDocument
createdBytes map[string][]byte
openBytes map[string][]byte
}
func (s *fakeTranslateTempDoc) List(_ context.Context, _ uint64, _ string) ([]*types.TemporaryDocument, error) {
return s.docs, nil
}
func (s *fakeTranslateTempDoc) OpenFile(_ context.Context, _ uint64, _ string, documentID string) (io.ReadCloser, string, error) {
if data, ok := s.openBytes[documentID]; ok {
return io.NopCloser(bytes.NewReader(data)), "part.xlsx", nil
}
return nil, "", fmt.Errorf("no such document: %s", documentID)
}
func (s *fakeTranslateTempDoc) Create(_ context.Context, _ uint64, _ string, fileName, _ string, fileSize int64, reader io.Reader, _ types.TemporaryDocumentCreateOptions) (*types.TemporaryDocument, error) {
data, err := io.ReadAll(reader)
if err != nil {
return nil, err
}
if int64(len(data)) != fileSize {
return nil, fmt.Errorf("size mismatch")
}
doc := &types.TemporaryDocument{ID: fmt.Sprintf("doc-%d", len(s.created)+1), FileName: fileName, FileSize: fileSize}
if s.createdBytes == nil {
s.createdBytes = map[string][]byte{}
}
s.createdBytes[doc.ID] = data
s.created = append(s.created, doc)
return doc, nil
}
// fakeTranslateChat answers every batch with the requested array translated
// deterministically: CJK runs become " EN ".
type fakeTranslateChat struct {
prompts []string
}
func (f *fakeTranslateChat) Chat(ctx context.Context, messages []chat.Message, opts *chat.ChatOptions) (*types.ChatResponse, error) {
resp, err := f.ChatStream(ctx, messages, opts)
if err != nil {
return nil, err
}
var content strings.Builder
for chunk := range resp {
content.WriteString(chunk.Content)
}
return &types.ChatResponse{Content: content.String()}, nil
}
func (f *fakeTranslateChat) ChatStream(_ context.Context, messages []chat.Message, _ *chat.ChatOptions) (<-chan types.StreamResponse, error) {
f.prompts = append(f.prompts, messages[len(messages)-1].Content)
content := messages[len(messages)-1].Content
start := strings.IndexByte(content, '[')
end := strings.LastIndexByte(content, ']')
var texts []string
if err := json.Unmarshal([]byte(content[start:end+1]), &texts); err != nil {
return nil, err
}
out := make([]string, 0, len(texts))
for _, t := range texts {
out = append(out, replaceCJKRuns(t))
}
b, _ := json.Marshal(out)
ch := make(chan types.StreamResponse, 2)
ch <- types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Content: string(b)}
ch <- types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Done: true}
close(ch)
return ch, nil
}
func (f *fakeTranslateChat) GetModelName() string { return "fake" }
func (f *fakeTranslateChat) GetModelID() string { return "fake-id" }
// replaceCJKRuns mirrors the engine-test stub: CJK runs become a single space.
func replaceCJKRuns(s string) string {
var b strings.Builder
inCJK := false
for _, r := range s {
if (r >= 0x3400 && r <= 0x9FFF) || (r >= 0xF900 && r <= 0xFAFF) ||
(r >= 0x3000 && r <= 0x303F) || (r >= 0xFF01 && r <= 0xFF5E) {
inCJK = true
continue
}
if inCJK {
b.WriteByte(' ')
inCJK = false
}
b.WriteRune(r)
}
if inCJK {
b.WriteByte(' ')
}
return b.String()
}
func buildToolFixture(t *testing.T) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
for _, f := range []struct{ name, body string }{
{"[Content_Types].xml", ""},
{"xl/sharedStrings.xml", `螺母 M8Assembly Process`},
} {
w, _ := zw.Create(f.name)
w.Write([]byte(f.body))
}
zw.Close()
return buf.Bytes()
}
func toolExecContext(sessionID string) context.Context {
return WithToolExecContext(context.Background(), &ToolExecContext{SessionID: sessionID})
}
func sharedStringsFrom(t *testing.T, data []byte) string {
t.Helper()
r, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("output zip: %v", err)
}
for _, f := range r.File {
if f.Name == "xl/sharedStrings.xml" {
rc, _ := f.Open()
raw, _ := io.ReadAll(rc)
rc.Close()
return string(raw)
}
}
t.Fatalf("no sharedStrings.xml in output")
return ""
}
func TestXlsxTranslateToolEndToEndSandbox(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{
"/workspace/input/part.xlsx": buildToolFixture(t),
}}
tool := NewXlsxTranslateTool(store, store, nil, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
result, err := tool.Execute(toolExecContext("sess-1"), args)
if err != nil {
t.Fatalf("Execute: %v", err)
}
if !result.Success {
t.Fatalf("tool failed: %s", result.Error)
}
if store.writePath != "/workspace/output/part_EN.xlsx" {
t.Fatalf("unexpected output path: %s", store.writePath)
}
if len(result.OutputFiles) != 1 || !strings.Contains(result.OutputFiles[0], "part_EN.xlsx") {
t.Fatalf("missing output link: %v", result.OutputFiles)
}
if !strings.Contains(result.Output, "part_EN.xlsx") {
t.Fatalf("output does not name the deliverable: %s", result.Output)
}
ss := sharedStringsFrom(t, store.files[store.writePath])
if strings.ContainsAny(ss, "螺母") {
t.Fatalf("output still contains Chinese: %s", ss)
}
if !strings.Contains(ss, "Assembly Process") {
t.Fatalf("English string lost: %s", ss)
}
}
// TestXlsxTranslateToolWithoutSandbox covers the 192 deployment failure mode:
// no workspace sandbox anywhere in the session, so input comes from the
// uploaded session attachment and the deliverable is a preview URL.
func TestXlsxTranslateToolWithoutSandbox(t *testing.T) {
tempDoc := &fakeTranslateTempDoc{
openBytes: map[string][]byte{"doc-1": buildToolFixture(t)},
}
tempDoc.docs = append(tempDoc.docs, &types.TemporaryDocument{
ID: "doc-1", FileName: "D4-A08AR12000002-A3-SIP.xlsx", FileType: "xlsx",
})
tool := NewXlsxTranslateTool(nil, nil, tempDoc, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{AttachmentName: "D4-A08AR12000002-A3-SIP.xlsx"})
result, err := tool.Execute(toolExecContext("sess-1"), args)
if err != nil {
t.Fatalf("Execute: %v", err)
}
if !result.Success {
t.Fatalf("tool failed: %s", result.Error)
}
if len(tempDoc.created) != 1 {
t.Fatalf("expected one delivered attachment, got %d", len(tempDoc.created))
}
created := tempDoc.created[0]
if created.FileName != "D4-A08AR12000002-A3-SIP_EN.xlsx" {
t.Fatalf("unexpected deliverable name: %s", created.FileName)
}
wantURL := "/api/v1/sessions/sess-1/attachments/" + created.ID + "/preview"
if !strings.Contains(result.Output, wantURL) {
t.Fatalf("output missing preview URL %s: %s", wantURL, result.Output)
}
ss := sharedStringsFrom(t, tempDoc.createdBytes[created.ID])
if strings.ContainsAny(ss, "螺母") {
t.Fatalf("delivered workbook still contains Chinese: %s", ss)
}
}
// TestXlsxTranslateToolSandboxReadFallsBackToAttachment covers a mixed
// session: a sandbox exists but the named file is not staged there, so the
// upload is read from the attachment service while the deliverable still
// goes to the sandbox output directory.
func TestXlsxTranslateToolSandboxReadFallsBackToAttachment(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{}}
tempDoc := &fakeTranslateTempDoc{
openBytes: map[string][]byte{"doc-1": buildToolFixture(t)},
}
tempDoc.docs = append(tempDoc.docs, &types.TemporaryDocument{
ID: "doc-1", FileName: "part.xlsx", FileType: "xlsx",
})
tool := NewXlsxTranslateTool(store, store, tempDoc, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
result, err := tool.Execute(toolExecContext("sess-1"), args)
if err != nil {
t.Fatalf("Execute: %v", err)
}
if !result.Success {
t.Fatalf("tool failed: %s", result.Error)
}
if store.writePath != "/workspace/output/part_EN.xlsx" {
t.Fatalf("unexpected output path: %s", store.writePath)
}
}
func TestXlsxTranslateToolRejectsNonXlsx(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{
"/workspace/input/part.xls": {0xD0, 0xCF, 0x11, 0xE0},
}}
tool := NewXlsxTranslateTool(store, store, nil, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xls"})
result, _ := tool.Execute(toolExecContext("sess-1"), args)
if result.Success {
t.Fatalf("legacy .xls should be rejected")
}
if !strings.Contains(result.Error, ".xlsx") {
t.Fatalf("unhelpful error: %s", result.Error)
}
}
func TestXlsxTranslateToolMissingFile(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{}}
tempDoc := &fakeTranslateTempDoc{}
tool := NewXlsxTranslateTool(store, store, tempDoc, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/missing.xlsx"})
result, _ := tool.Execute(toolExecContext("sess-1"), args)
if result.Success {
t.Fatalf("missing file should fail")
}
}
// dropItemsChat simulates the deterministic 192 failure: for any batch larger
// than one string the model "merges" two items and returns N-1 translations.
type dropItemsChat struct{}
func (f *dropItemsChat) Chat(ctx context.Context, messages []chat.Message, opts *chat.ChatOptions) (*types.ChatResponse, error) {
resp, err := f.ChatStream(ctx, messages, opts)
if err != nil {
return nil, err
}
var content strings.Builder
for chunk := range resp {
content.WriteString(chunk.Content)
}
return &types.ChatResponse{Content: content.String()}, nil
}
func (f *dropItemsChat) ChatStream(_ context.Context, messages []chat.Message, opts *chat.ChatOptions) (<-chan types.StreamResponse, error) {
content := messages[len(messages)-1].Content
start := strings.IndexByte(content, '[')
end := strings.LastIndexByte(content, ']')
var texts []string
if err := json.Unmarshal([]byte(content[start:end+1]), &texts); err != nil {
return nil, err
}
if len(texts) > 1 {
texts = texts[:len(texts)-1] // drop the last item: 19 of 20
} else if len(texts) == 1 {
texts = nil // single stubborn string: model refuses to translate it
}
out := make([]string, 0, len(texts))
for _, t := range texts {
out = append(out, replaceCJKRuns(t))
}
b, _ := json.Marshal(out)
ch := make(chan types.StreamResponse, 2)
ch <- types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Content: string(b)}
ch <- types.StreamResponse{ResponseType: types.ResponseTypeAnswer, Done: true}
close(ch)
return ch, nil
}
func (f *dropItemsChat) GetModelName() string { return "dropping" }
func (f *dropItemsChat) GetModelID() string { return "dropping-id" }
// TestXlsxTranslateBatchCountMismatchRecovers covers the field failure where
// the model returns N-1 translations for N inputs: bisection must realign
// instead of failing the run.
func TestXlsxTranslateBatchCountMismatchRecovers(t *testing.T) {
texts := make([]string, 20)
for i := range texts {
texts[i] = fmt.Sprintf("检验项目 %d", i+1)
}
tr := &chatBatchTranslator{model: &dropItemsChat{}}
out, err := tr.TranslateBatch(context.Background(), texts)
if err != nil {
t.Fatalf("TranslateBatch: %v", err)
}
if len(out) != len(texts) {
t.Fatalf("recovered %d results for %d inputs", len(out), len(texts))
}
for i := range out {
if strings.TrimSpace(out[i]) == "" {
t.Fatalf("item %d empty after recovery", i)
}
}
}
// TestXlsxTranslateBatchSingleStubbornStringKeepsOriginal covers the terminal
// bisection case: one string the model refuses to translate must degrade to
// the original text, not fail the run.
func TestXlsxTranslateBatchSingleStubbornStringKeepsOriginal(t *testing.T) {
tr := &chatBatchTranslator{model: &dropItemsChat{}}
out, err := tr.TranslateBatch(context.Background(), []string{"顽固文本"})
if err != nil {
t.Fatalf("TranslateBatch: %v", err)
}
if out[0] != "顽固文本" {
t.Fatalf("single item altered: %q", out[0])
}
}