fix(翻译):修复(工具与沙箱解耦,双通道自适应)
deploy-hxtesting / build-and-deploy (push) Successful in 1m15s

This commit is contained in:
runny committed 2026-11-30 21:09:02 +08:00
1 parent db8472bf28
commit c6088aeb4b
4 files changed
+307 -99

No files matched your search

@@ -97,8 +97,8 @@ templates:
content: |
You are Academy SIP Translator, specialized in translating Chinese engineering Excel workbooks (SIP standard inspection procedures, SOP standard operating procedures, rack/enclosure manufacturing documents) into English.
Workflow:
- When the user uploads a .xlsx workbook, call xlsx_translate with file_path set to the uploaded file's absolute sandbox path from <sandbox_attachments>. Never ask the user to re-upload or to run any manual steps.
- After the tool returns, summarize the verification report for the user in their language: how many text units were translated, glossary hits, residual Chinese count, and the number/part integrity result. The translated workbook is delivered automatically as a downloadable output artifact named <original>_EN.xlsx — point the user to it.
- When the user uploads a .xlsx workbook, call xlsx_translate: pass file_path set to the uploaded file's absolute sandbox path from <sandbox_attachments> when that section is present, otherwise pass attachment_name set to the uploaded file's name. Never ask the user to re-upload or to run any manual steps.
- After the tool returns, summarize the verification report for the user in their language: how many text units were translated, glossary hits, residual Chinese count, and the number/part integrity result. The translated workbook named <original>_EN.xlsx is delivered automatically — either as a downloadable output artifact or as a direct download link in the tool result; point the user to whichever the result shows.
- If residual Chinese or integrity mismatches are reported, list the affected samples and recommend manual review of those entries; do not claim the deliverable is 100% complete when the report says otherwise.
- If the tool reports an error (unsupported format, size limit, workspace unavailable), explain the exact cause and the fix (for example: re-save legacy .xls as .xlsx, or ask an administrator to enable the session workspace).
- Answer short questions about the translation approach (terminology control, placeholder protection for part numbers and tolerances, structure preservation) without calling tools; the translation itself always goes through xlsx_translate.
+140 -56
View File
@@ -5,6 +5,7 @@ import (
"context"
"encoding/json"
"fmt"
"io"
"path"
"strings"
"time"
@@ -12,6 +13,7 @@ import (
"academy/internal/logger"
"academy/internal/models/chat"
"academy/internal/types"
"academy/internal/types/interfaces"
"academy/internal/utils"
"academy/internal/xlsxtranslate"
)
@@ -28,41 +30,55 @@ var xlsxMagic = []byte{0x50, 0x4B, 0x03, 0x04}
var legacyXLSMagicBytes = []byte{0xD0, 0xCF, 0x11, 0xE0, 0xA1, 0xB1, 0x1A, 0xE1}
const xlsxTranslateDescription = `Translate a Chinese engineering Excel workbook (SIP / SOP / inspection standard,
.xlsx only) into English and deliver the translated workbook as a downloadable output file.
.xlsx only) into English and deliver the translated workbook to the user.
Pass the absolute sandbox path of the uploaded workbook from <sandbox_attachments> as file_path.
Reference the uploaded workbook by its sandbox path (file_path, from <sandbox_attachments>) or by the
uploaded attachment's file name (attachment_name) — pass whichever the conversation shows.
The tool preserves the workbook exactly — merged cells, images, styles, formulas and sheet layout are
copied byte-for-byte; only Chinese text (cell strings, inline strings and drawing text boxes) is
translated. Part numbers, tolerances and dates are protected as placeholders and never altered.
A verification report (residual Chinese, number/part integrity) is returned; the translated workbook
lands in the artifact output directory for the user to download.`
A verification report (residual Chinese, number/part integrity) is returned together with the
translated workbook as a downloadable deliverable.`
// XlsxTranslateInput is the tool argument schema.
// XlsxTranslateInput is the tool argument schema. Exactly one of file_path /
// attachment_name is required; file_path wins when both are given.
type XlsxTranslateInput struct {
FilePath string `json:"file_path" jsonschema:"Absolute sandbox path of the uploaded .xlsx workbook, taken from <sandbox_attachments> (for example /workspace/input/part.xlsx)"`
FilePath string `json:"file_path,omitempty" jsonschema:"Absolute sandbox path of the uploaded workbook when <sandbox_attachments> is present (for example /workspace/input/part.xlsx)"`
AttachmentName string `json:"attachment_name,omitempty" jsonschema:"File name of the uploaded attachment when the conversation shows no sandbox workspace (for example part.xlsx)"`
}
// sessionDirEnsurer is the slice of SessionFileStore that provisions the
// output directory before writing.
type sessionDirEnsurer interface {
// SessionDirEnsurer is the slice of SessionFileStore that provisions the
// output directory before writing. Exported because the agent service wires
// the same store into both the sink and the ensurer slots.
type SessionDirEnsurer interface {
EnsureSessionDir(ctx context.Context, sessionID, dir string) error
}
// XlsxTranslateTool translates an uploaded workbook through the
// xlsxtranslate pipeline, writing the English deliverable into the session
// artifact output directory.
// XlsxTranslateTool translates an uploaded workbook through the xlsxtranslate
// pipeline and delivers the English workbook as a session deliverable.
//
// Delivery adapts to the session's capabilities: with a workspace sandbox the
// output lands in the artifact output directory (collected as a downloadable
// artifact); without one the output is saved as a session attachment through
// the temporary-document service and linked by preview URL. The same
// adaptation applies to reading the upload. This is why registration must NOT
// be gated on the sandbox: a deployment without a workspace sandbox would
// otherwise hide the tool while the agent prompt still instructs the model to
// call it ("tool not found").
type XlsxTranslateTool struct {
BaseTool
store SandboxFileSink
ensure sessionDirEnsurer
ensure SessionDirEnsurer
tempDoc interfaces.TemporaryDocumentService
model chat.Chat
timeout time.Duration
}
// NewXlsxTranslateTool constructs the tool. store and model MUST NOT be nil;
// the tool is only registered when a session sandbox exists, because the
// deliverable is delivered through the artifact output directory.
func NewXlsxTranslateTool(store SandboxFileSink, ensure sessionDirEnsurer, model chat.Chat) *XlsxTranslateTool {
// NewXlsxTranslateTool constructs the tool. store/ensure may be nil when the
// session has no workspace sandbox (the temporary-document channel is used
// instead); tempDoc may be nil only when neither channel can exist. model
// MUST NOT be nil.
func NewXlsxTranslateTool(store SandboxFileSink, ensure SessionDirEnsurer, tempDoc interfaces.TemporaryDocumentService, model chat.Chat) *XlsxTranslateTool {
return &XlsxTranslateTool{
BaseTool: BaseTool{
name: ToolXlsxTranslate,
@@ -71,6 +87,7 @@ func NewXlsxTranslateTool(store SandboxFileSink, ensure sessionDirEnsurer, model
},
store: store,
ensure: ensure,
tempDoc: tempDoc,
model: model,
timeout: 20 * time.Minute,
}
@@ -82,41 +99,21 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
if err := json.Unmarshal(args, &input); err != nil {
return &types.ToolResult{Success: false, Error: fmt.Sprintf("invalid arguments: %v", err)}, nil
}
filePath := strings.TrimSpace(input.FilePath)
if filePath == "" {
return &types.ToolResult{Success: false,
Error: "file_path is required: pass the absolute sandbox path of the uploaded workbook from <sandbox_attachments>"}, nil
}
sessionID := resolveSessionID(ctx)
if sessionID == "" {
return &types.ToolResult{Success: false,
Error: "no session ID in context; xlsx_translate must run inside an agent turn"}, nil
}
layout, layoutErr := executeWorkspaceLayout(ctx, sessionID, t.store)
if layoutErr != nil {
return layoutErr, nil
}
// Same relative-path semantics as the file primitives: a bare filename
// or workspace-relative path resolves against the workspace root.
filePath = resolveIn(layout, filePath)
tenantID, _ := types.TenantIDFromContext(ctx)
lower := strings.ToLower(filePath)
if !strings.HasSuffix(lower, ".xlsx") {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("only .xlsx workbooks are supported, got %q; re-save legacy .xls as .xlsx and upload again", path.Base(filePath))}, nil
}
data, err := t.store.ReadSessionFile(ctx, sessionID, filePath)
if err != nil {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("failed to read %s: %v", filePath, err)}, nil
}
// ---- Resolve the input workbook ----
data, source := t.readInput(ctx, sessionID, tenantID, &input)
if len(data) == 0 {
return &types.ToolResult{Success: false, Error: fmt.Sprintf("%s is empty", filePath)}, nil
return &types.ToolResult{Success: false, Error: source}, nil // source carries the error text
}
if len(data) > maxTranslateBytes {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("%s is %d MB, above the %d MB translation limit", path.Base(filePath), len(data)>>20, maxTranslateBytes>>20)}, nil
Error: fmt.Sprintf("workbook is %d MB, above the %d MB translation limit", len(data)>>20, maxTranslateBytes>>20)}, nil
}
if bytes.HasPrefix(data, legacyXLSMagicBytes) {
return &types.ToolResult{Success: false,
@@ -124,43 +121,67 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
}
if !bytes.HasPrefix(data, xlsxMagic) {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("%s is not a valid .xlsx (ZIP) package", path.Base(filePath))}, nil
Error: fmt.Sprintf("%s is not a valid .xlsx (ZIP) package", path.Base(source))}, nil
}
baseName := path.Base(source)
if !strings.HasSuffix(strings.ToLower(baseName), ".xlsx") {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("only .xlsx workbooks are supported, got %q; re-save legacy .xls as .xlsx and upload again", baseName)}, nil
}
// ---- Translate ----
runCtx, cancel := context.WithTimeout(ctx, t.timeout)
defer cancel()
translated, report, err := xlsxtranslate.Translate(runCtx, data, &xlsxtranslate.Options{
BatchSize: 40,
}, &chatBatchTranslator{model: t.model})
if err != nil {
logger.Warnf(ctx, "[Tool][XlsxTranslate] session=%s file=%s failed: %v", sessionID, filePath, err)
logger.Warnf(ctx, "[Tool][XlsxTranslate] session=%s file=%s failed: %v", sessionID, source, err)
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("translation failed: %v", err)}, nil
}
baseName := path.Base(filePath)
ext := path.Ext(baseName)
outName := strings.TrimSuffix(baseName, ext) + "_EN.xlsx"
outputDir := layoutOutputDir(layout)
if outputDir == "" {
return &types.ToolResult{Success: false,
Error: "session has no artifact output directory; the sandbox workspace is unavailable"}, nil
}
// ---- Deliver: sandbox artifact dir when available, attachment otherwise ----
var deliverable string
var outputLinks []string
if t.store != nil {
if layout, layoutErr := executeWorkspaceLayout(ctx, sessionID, t.store); layoutErr == nil {
if outputDir := layoutOutputDir(layout); outputDir != "" {
outPath := outputDir + "/" + outName
if t.ensure != nil {
if err := t.ensure.EnsureSessionDir(ctx, sessionID, outputDir); err != nil {
logger.Warnf(ctx, "[Tool][XlsxTranslate] ensure output dir failed: %v", err)
}
}
if err := t.store.WriteSessionWorkspaceFile(ctx, sessionID, outPath, translated); err != nil {
if err := t.store.WriteSessionWorkspaceFile(ctx, sessionID, outPath, translated); err == nil {
deliverable = outPath
outputLinks = sandboxOutputLinksIn(outputDir, outPath)
} else {
logger.Warnf(ctx, "[Tool][XlsxTranslate] sandbox write failed, falling back to attachment: %v", err)
}
}
}
}
if deliverable == "" {
url, err := t.saveAsAttachment(ctx, tenantID, sessionID, outName, translated)
if err != nil {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("failed to write translated workbook to %s: %v", outPath, err)}, nil
Error: fmt.Sprintf("translation finished but delivering the workbook failed: %v", err)}, nil
}
deliverable = url
}
logger.Infof(ctx, "[Tool][XlsxTranslate] session=%s file=%s -> %s units=%d residual=%d llm_calls=%d",
sessionID, filePath, outPath, report.TranslatedUnits, report.ResidualCJKCount, report.LLMCalls)
sessionID, source, deliverable, report.TranslatedUnits, report.ResidualCJKCount, report.LLMCalls)
var b strings.Builder
b.WriteString("Translation finished. The English workbook is saved as **" + outName + "** in the output directory (available as a downloadable artifact).\n\n")
if len(outputLinks) > 0 {
b.WriteString("Translation finished. The English workbook **" + outName + "** is saved in the output directory (available as a downloadable artifact).\n\n")
} else {
b.WriteString("Translation finished. Download the English workbook **" + outName + "** here: " + deliverable + "\n\n")
}
b.WriteString(report.Markdown())
if report.ResidualCJKCount > 0 {
b.WriteString("\nNote: residual Chinese remains (see samples above) — usually oversized or untranslatable entries. Review them manually.\n")
@@ -172,9 +193,9 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
return &types.ToolResult{
Success: true,
Output: b.String(),
OutputFiles: sandboxOutputLinksIn(outputDir, outPath),
OutputFiles: outputLinks,
Data: map[string]interface{}{
"output_path": outPath,
"deliverable": deliverable,
"translated_units": report.TranslatedUnits,
"glossary_hits": report.GlossaryHits,
"llm_calls": report.LLMCalls,
@@ -186,6 +207,69 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
}, nil
}
// readInput fetches the workbook bytes: sandbox first (staged attachment),
// temporary-document lookup second. The returned string is the resolved
// source path/name, or the error text when no bytes could be read.
func (t *XlsxTranslateTool) readInput(ctx context.Context, sessionID string, tenantID uint64, input *XlsxTranslateInput) ([]byte, string) {
if t.store != nil && strings.TrimSpace(input.FilePath) != "" {
if layout, layoutErr := executeWorkspaceLayout(ctx, sessionID, t.store); layoutErr == nil {
clean := resolveIn(layout, input.FilePath)
data, err := t.store.ReadSessionFile(ctx, sessionID, clean)
if err == nil && len(data) > 0 {
return data, clean
}
logger.Warnf(ctx, "[Tool][XlsxTranslate] sandbox read of %s failed (%v); trying session attachments", clean, err)
}
}
if t.tempDoc == nil {
return nil, "no input source: pass file_path when a sandbox workspace is present, or attachment_name for the uploaded attachment"
}
name := strings.TrimSpace(input.AttachmentName)
if name == "" {
name = path.Base(strings.TrimSpace(input.FilePath))
}
if name == "" || name == "." {
return nil, "input required: pass file_path (sandbox path) or attachment_name (uploaded file name)"
}
docs, err := t.tempDoc.List(ctx, tenantID, sessionID)
if err != nil {
return nil, fmt.Sprintf("failed to list session attachments: %v", err)
}
var doc *types.TemporaryDocument
for i := range docs { // last match wins: the newest upload with that name
if docs[i] != nil && docs[i].FileName == name {
doc = docs[i]
}
}
if doc == nil {
return nil, fmt.Sprintf("no uploaded attachment named %q found in this session", name)
}
reader, _, err := t.tempDoc.OpenFile(ctx, tenantID, sessionID, doc.ID)
if err != nil {
return nil, fmt.Sprintf("failed to open attachment %q: %v", name, err)
}
defer reader.Close()
data, err := io.ReadAll(reader)
if err != nil {
return nil, fmt.Sprintf("failed to read attachment %q: %v", name, err)
}
return data, doc.FileName
}
// saveAsAttachment stores the translated workbook as a session attachment and
// returns its preview URL, which streams the original bytes.
func (t *XlsxTranslateTool) saveAsAttachment(ctx context.Context, tenantID uint64, sessionID, name string, data []byte) (string, error) {
if t.tempDoc == nil {
return "", fmt.Errorf("no delivery channel: session has neither a workspace sandbox nor the attachment service")
}
const xlsxMime = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
doc, err := t.tempDoc.Create(ctx, tenantID, sessionID, name, xlsxMime, int64(len(data)), bytes.NewReader(data), types.TemporaryDocumentCreateOptions{})
if err != nil {
return "", err
}
return "/api/v1/sessions/" + sessionID + "/attachments/" + doc.ID + "/preview", nil
}
// chatBatchTranslator adapts the session chat model to the engine's
// Translator interface: one call = one JSON array round trip.
type chatBatchTranslator struct {
+139 -24
View File
@@ -13,6 +13,7 @@ import (
"academy/internal/models/chat"
"academy/internal/sandbox"
"academy/internal/types"
"academy/internal/types/interfaces"
)
// fakeTranslateStore is an in-memory SessionFileSink + dir ensurer.
@@ -44,6 +45,45 @@ func (s *fakeTranslateStore) WriteSessionWorkspaceFile(_ context.Context, _, pat
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 {
@@ -52,10 +92,11 @@ type fakeTranslateChat struct {
func (f *fakeTranslateChat) Chat(_ context.Context, messages []chat.Message, _ *chat.ChatOptions) (*types.ChatResponse, error) {
f.prompts = append(f.prompts, messages[len(messages)-1].Content)
start := strings.IndexByte(messages[len(messages)-1].Content, '[')
end := strings.LastIndexByte(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(messages[len(messages)-1].Content[start:end+1]), &texts); err != nil {
if err := json.Unmarshal([]byte(content[start:end+1]), &texts); err != nil {
return nil, err
}
out := make([]string, 0, len(texts))
@@ -110,14 +151,36 @@ func buildToolFixture(t *testing.T) []byte {
return buf.Bytes()
}
func TestXlsxTranslateToolEndToEnd(t *testing.T) {
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, &fakeTranslateChat{})
tool := NewXlsxTranslateTool(store, store, nil, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
result, err := tool.Execute(WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "sess-1"}), args)
result, err := tool.Execute(toolExecContext("sess-1"), args)
if err != nil {
t.Fatalf("Execute: %v", err)
}
@@ -134,20 +197,7 @@ func TestXlsxTranslateToolEndToEnd(t *testing.T) {
t.Fatalf("output does not name the deliverable: %s", result.Output)
}
// The translated workbook must contain no CJK and keep the EN string.
r, err := zip.NewReader(bytes.NewReader(store.files[store.writePath]), int64(len(store.files[store.writePath])))
if err != nil {
t.Fatalf("output zip: %v", err)
}
var ss string
for _, f := range r.File {
if f.Name == "xl/sharedStrings.xml" {
rc, _ := f.Open()
raw, _ := io.ReadAll(rc)
rc.Close()
ss = string(raw)
}
}
ss := sharedStringsFrom(t, store.files[store.writePath])
if strings.ContainsAny(ss, "螺母") {
t.Fatalf("output still contains Chinese: %s", ss)
}
@@ -156,14 +206,78 @@ func TestXlsxTranslateToolEndToEnd(t *testing.T) {
}
}
// 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, &fakeTranslateChat{})
tool := NewXlsxTranslateTool(store, store, nil, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xls"})
result, _ := tool.Execute(WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "sess-1"}), args)
result, _ := tool.Execute(toolExecContext("sess-1"), args)
if result.Success {
t.Fatalf("legacy .xls should be rejected")
}
@@ -174,10 +288,11 @@ func TestXlsxTranslateToolRejectsNonXlsx(t *testing.T) {
func TestXlsxTranslateToolMissingFile(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{}}
tool := NewXlsxTranslateTool(store, store, &fakeTranslateChat{})
tempDoc := &fakeTranslateTempDoc{}
tool := NewXlsxTranslateTool(store, store, tempDoc, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/missing.xlsx"})
result, _ := tool.Execute(WithToolExecContext(context.Background(), &ToolExecContext{SessionID: "sess-1"}), args)
result, _ := tool.Execute(toolExecContext("sess-1"), args)
if result.Success {
t.Fatalf("missing file should fail")
}
+26 -17
View File
@@ -121,6 +121,10 @@ type agentService struct {
storageResolver interfaces.StorageBackendResolver
toolApprovalGate approval.MCPApproval
customAgentService interfaces.CustomAgentService
// temporaryDocuments lets file-producing agent tools deliver outputs as
// session attachments when no workspace sandbox exists (see
// registerXlsxTranslateTool / tools.NewXlsxTranslateTool).
temporaryDocuments interfaces.TemporaryDocumentService
operationDispatcher operations.Dispatcher
collaboration *AgentCollaboration
sandboxMgr sandbox.Manager
@@ -178,10 +182,12 @@ func NewAgentService(
shellJobs *ShellJobService,
operationDispatcher *operations.HandlerDispatcher,
customAgentService interfaces.CustomAgentService,
temporaryDocuments interfaces.TemporaryDocumentService,
collaboration *AgentCollaboration,
) interfaces.AgentService {
svc := &agentService{
customAgentService: customAgentService,
temporaryDocuments: temporaryDocuments,
operationDispatcher: operationDispatcher,
browserSkill: browserSkill,
userRepo: userRepo,
@@ -651,10 +657,13 @@ func (s *agentService) registerSandboxFileTools(
}
// registerXlsxTranslateTool registers the SIP/SOP workbook translation tool
// for agents that allow it. The tool reads the uploaded workbook through the
// session sandbox and delivers the English deliverable through the artifact
// output directory, so it follows the same sandbox capability gate as the
// file primitives: no session workspace, no translation tool.
// for agents that allow it. Registration deliberately does NOT require a
// workspace sandbox: the tool reads the upload and delivers the English
// workbook through the session attachment service when no sandbox exists,
// and through the artifact output directory when one does. Gating on the
// sandbox hid the tool on deployments without a workspace while the agent
// prompt still instructed the model to call it, surfacing as
// "tool not found: xlsx_translate".
func (s *agentService) registerXlsxTranslateTool(
ctx context.Context,
toolRegistry *tools.ToolRegistry,
@@ -676,22 +685,22 @@ func (s *agentService) registerXlsxTranslateTool(
logger.Infof(ctx, "xlsx_translate withheld: session has no chat model to translate with")
return
}
if s.temporaryDocuments == nil {
logger.Infof(ctx, "xlsx_translate withheld: attachment delivery service unavailable")
return
}
var store sandbox.SessionFileStore
sandboxMgr, err := s.resolveWorkspaceSandbox(ctx, sessionID, config)
if err != nil {
logger.Warnf(ctx, "Failed to resolve sandbox for xlsx_translate: %v", err)
return
if err == nil && sandboxMgr != nil {
store = sessionSandboxFileStore(sandboxMgr)
}
if sandboxMgr == nil {
logger.Infof(ctx, "xlsx_translate withheld: session has no workspace sandbox to read attachments and deliver output")
return
// store doubles as the dir ensurer; both are nil without a sandbox.
toolRegistry.RegisterTool(tools.NewXlsxTranslateTool(store, store, s.temporaryDocuments, chatModel))
if store != nil {
logger.Infof(ctx, "Registered xlsx_translate tool for session: %s (sandbox delivery)", sessionID)
} else {
logger.Infof(ctx, "Registered xlsx_translate tool for session: %s (attachment delivery)", sessionID)
}
store := sessionSandboxFileStore(sandboxMgr)
if store == nil {
logger.Infof(ctx, "xlsx_translate withheld: sandbox backend does not advertise session filesystem capability")
return
}
toolRegistry.RegisterTool(tools.NewXlsxTranslateTool(store, store, chatModel))
logger.Infof(ctx, "Registered xlsx_translate tool for session: %s", sessionID)
}
// registerSkillFileTools registers write_skill_file / edit_skill_file for the