feat(翻译):优化翻译保存地址!
deploy-hxtesting / build-and-deploy (push) Successful in 1m14s

This commit is contained in:
runny committed 2026-11-30 23:48:07 +08:00
1 parent 7d3b6804af
commit 2048251eff
6 files changed
+199 -41

No files matched your search

@@ -98,7 +98,7 @@ templates:
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: 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.
- 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 <original>_EN.xlsx is delivered automatically as a file card on this reply (and filed in the conversation artifact library) — tell the user to click that card to view details and download it. NEVER print raw API paths or URLs; always refer to the file by its name and the card on the reply.
- 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.
+94 -16
View File
@@ -17,6 +17,8 @@ import (
"academy/internal/types/interfaces"
"academy/internal/utils"
"academy/internal/xlsxtranslate"
"github.com/google/uuid"
)
// maxTranslateBytes caps one translation run. The largest known real file is
@@ -55,6 +57,15 @@ type SessionDirEnsurer interface {
EnsureSessionDir(ctx context.Context, sessionID, dir string) error
}
// MessageArtifactSink persists deliverables onto the assistant message so
// they surface as clickable artifact cards in the chat, the conversation
// artifact library, and the standard artifact download route (which serves
// Content-Disposition: attachment) — all without a workspace sandbox.
type MessageArtifactSink interface {
GetMessage(ctx context.Context, sessionID string, id string) (*types.Message, error)
UpdateMessage(ctx context.Context, message *types.Message) error
}
// XlsxTranslateTool translates an uploaded workbook through the xlsxtranslate
// pipeline and delivers the English workbook as a session deliverable.
//
@@ -71,6 +82,8 @@ type XlsxTranslateTool struct {
store SandboxFileSink
ensure SessionDirEnsurer
tempDoc interfaces.TemporaryDocumentService
files interfaces.FileService
artifacts MessageArtifactSink
model chat.Chat
timeout time.Duration
}
@@ -79,7 +92,20 @@ type XlsxTranslateTool struct {
// 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 {
// NewXlsxTranslateTool constructs the tool. Delivery adapts to session
// capabilities: a workspace sandbox delivers through the artifact output
// directory; otherwise the workbook is saved through the file service and
// attached to the assistant message as a chat artifact. tempDoc is the
// fallback input reader for the uploaded attachment; files + artifacts carry
// the no-sandbox delivery and MUST NOT both be nil.
func NewXlsxTranslateTool(
store SandboxFileSink,
ensure SessionDirEnsurer,
tempDoc interfaces.TemporaryDocumentService,
files interfaces.FileService,
artifacts MessageArtifactSink,
model chat.Chat,
) *XlsxTranslateTool {
return &XlsxTranslateTool{
BaseTool: BaseTool{
name: ToolXlsxTranslate,
@@ -89,6 +115,8 @@ func NewXlsxTranslateTool(store SandboxFileSink, ensure SessionDirEnsurer, tempD
store: store,
ensure: ensure,
tempDoc: tempDoc,
files: files,
artifacts: artifacts,
model: model,
timeout: 20 * time.Minute,
}
@@ -164,21 +192,27 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
}
}
}
attached := false
if deliverable == "" {
url, err := t.saveAsAttachment(ctx, tenantID, sessionID, outName, translated)
if err != nil {
assistantMessageID := assistantMessageIDFromContext(ctx)
var derr error
attached, derr = t.saveAsMessageArtifact(ctx, tenantID, sessionID, assistantMessageID, outName, translated)
if derr != nil {
return &types.ToolResult{Success: false,
Error: fmt.Sprintf("translation finished but delivering the workbook failed: %v", err)}, nil
Error: fmt.Sprintf("translation finished but delivering the workbook failed: %v", derr)}, nil
}
deliverable = url
deliverable = outName
}
logger.Infof(ctx, "[Tool][XlsxTranslate] session=%s file=%s -> %s units=%d residual=%d llm_calls=%d",
sessionID, source, deliverable, report.TranslatedUnits, report.ResidualCJKCount, report.LLMCalls)
var b strings.Builder
if len(outputLinks) > 0 {
switch {
case 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 {
case attached:
b.WriteString("Translation finished. The English workbook **" + outName + "** is attached to this reply as a file card — open it to see details and download.\n\n")
default:
b.WriteString("Translation finished. Download the English workbook **" + outName + "** here: " + deliverable + "\n\n")
}
b.WriteString(report.Markdown())
@@ -195,6 +229,7 @@ func (t *XlsxTranslateTool) Execute(ctx context.Context, args json.RawMessage) (
OutputFiles: outputLinks,
Data: map[string]interface{}{
"deliverable": deliverable,
"artifact_attached": attached,
"translated_units": report.TranslatedUnits,
"glossary_hits": report.GlossaryHits,
"llm_calls": report.LLMCalls,
@@ -255,18 +290,61 @@ func (t *XlsxTranslateTool) readInput(ctx context.Context, sessionID string, ten
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")
// assistantMessageIDFromContext reads the assistant message the current tool
// call belongs to; empty outside agent turns.
func assistantMessageIDFromContext(ctx context.Context) string {
if meta, ok := ToolExecFromContext(ctx); ok && meta != nil {
return meta.AssistantMessageID
}
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{})
return ""
}
// saveAsMessageArtifact persists the translated workbook through the file
// service and records it on the assistant message. The stream handler's
// post-run merge matches the file name in the answer against session
// artifacts, so the record surfaces as a clickable artifact card on this
// reply, in the conversation artifact library, and through the artifact
// download route (Content-Disposition: attachment — the browser saves it to
// the download location, e.g. Desktop, under the translated file name).
// Returns attached=false when the assistant message is not known yet.
func (t *XlsxTranslateTool) saveAsMessageArtifact(
ctx context.Context, tenantID uint64, sessionID, assistantMessageID, name string, data []byte,
) (bool, error) {
if t.files == nil || t.artifacts == nil {
return false, fmt.Errorf("no delivery channel: session has neither a workspace sandbox nor the artifact service")
}
if assistantMessageID == "" {
return false, fmt.Errorf("assistant message is not known yet; resend the translation request in this conversation")
}
storageName := "artifact_" + uuid.NewString() + "_" + name
storagePath, err := t.files.SaveBytes(ctx, data, tenantID, storageName, false)
if err != nil {
return "", err
return false, fmt.Errorf("save workbook: %w", err)
}
return "/api/v1/sessions/" + sessionID + "/attachments/" + doc.ID + "/preview", nil
msg, err := t.artifacts.GetMessage(ctx, sessionID, assistantMessageID)
if err != nil || msg == nil {
return false, fmt.Errorf("assistant message %s not found: %v", assistantMessageID, err)
}
for _, a := range msg.Artifacts {
if a.FileName == name && !a.Deleted() {
return true, nil // idempotent: this turn already delivered the file
}
}
msg.Artifacts = append(msg.Artifacts, types.MessageArtifact{
URL: storagePath,
FileName: name,
FileType: ".xlsx",
FileSize: int64(len(data)),
SourcePath: name, // no sandbox path; the name keeps the known-set stable
ModTime: time.Now().UTC(),
CreatedAt: time.Now().UTC(),
})
if err := t.artifacts.UpdateMessage(ctx, msg); err != nil {
return false, fmt.Errorf("attach artifact to message: %w", err)
}
logger.Infof(ctx, "[Tool][XlsxTranslate] artifact attached: session=%s message=%s file=%s bytes=%d",
sessionID, assistantMessageID, name, len(data))
return true, nil
}
// chatBatchTranslator adapts the session chat model to the engine's
+100 -22
View File
@@ -45,6 +45,40 @@ func (s *fakeTranslateStore) WriteSessionWorkspaceFile(_ context.Context, _, pat
return nil
}
// fakeArtifactSink records artifacts appended to the assistant message.
type fakeArtifactSink struct {
interfaces.MessageService
messages map[string]*types.Message
updated int
}
func (s *fakeArtifactSink) GetMessage(_ context.Context, _ string, id string) (*types.Message, error) {
if msg, ok := s.messages[id]; ok {
return msg, nil
}
return nil, fmt.Errorf("message %s not found", id)
}
func (s *fakeArtifactSink) UpdateMessage(_ context.Context, msg *types.Message) error {
s.messages[msg.ID] = msg
s.updated++
return nil
}
// fakeTranslateFileService captures SaveBytes calls.
type fakeTranslateFileService struct {
interfaces.FileService
saved map[string][]byte
}
func (s *fakeTranslateFileService) SaveBytes(_ context.Context, data []byte, _ uint64, name string, _ bool) (string, error) {
if s.saved == nil {
s.saved = map[string][]byte{}
}
s.saved[name] = data
return "local://" + name, 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.
@@ -163,8 +197,11 @@ func buildToolFixture(t *testing.T) []byte {
return buf.Bytes()
}
func toolExecContext(sessionID string) context.Context {
return WithToolExecContext(context.Background(), &ToolExecContext{SessionID: sessionID})
func toolExecContext(sessionID, assistantMessageID string) context.Context {
return WithToolExecContext(context.Background(), &ToolExecContext{
SessionID: sessionID,
AssistantMessageID: assistantMessageID,
})
}
func sharedStringsFrom(t *testing.T, data []byte) string {
@@ -189,10 +226,10 @@ func TestXlsxTranslateToolEndToEndSandbox(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{
"/workspace/input/part.xlsx": buildToolFixture(t),
}}
tool := NewXlsxTranslateTool(store, store, nil, &fakeTranslateChat{})
tool := NewXlsxTranslateTool(store, store, nil, nil, nil, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
result, err := tool.Execute(toolExecContext("sess-1"), args)
result, err := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
if err != nil {
t.Fatalf("Execute: %v", err)
}
@@ -220,7 +257,8 @@ func TestXlsxTranslateToolEndToEndSandbox(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.
// uploaded session attachment and the deliverable attaches to the assistant
// message as a chat artifact (artifact library + clickable card + download).
func TestXlsxTranslateToolWithoutSandbox(t *testing.T) {
tempDoc := &fakeTranslateTempDoc{
openBytes: map[string][]byte{"doc-1": buildToolFixture(t)},
@@ -228,31 +266,71 @@ func TestXlsxTranslateToolWithoutSandbox(t *testing.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{})
sink := &fakeArtifactSink{messages: map[string]*types.Message{
"assistant-1": {ID: "assistant-1", SessionID: "sess-1"},
}}
files := &fakeTranslateFileService{}
tool := NewXlsxTranslateTool(nil, nil, tempDoc, files, sink, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{AttachmentName: "D4-A08AR12000002-A3-SIP.xlsx"})
result, err := tool.Execute(toolExecContext("sess-1"), args)
result, err := tool.Execute(toolExecContext("sess-1", "assistant-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))
if !strings.Contains(result.Output, "file card") {
t.Fatalf("output should point at the artifact card: %s", result.Output)
}
created := tempDoc.created[0]
if created.FileName != "D4-A08AR12000002-A3-SIP_EN.xlsx" {
t.Fatalf("unexpected deliverable name: %s", created.FileName)
msg := sink.messages["assistant-1"]
if msg == nil || len(msg.Artifacts) != 1 {
t.Fatalf("expected one artifact on the assistant message, got %+v", msg)
}
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)
art := msg.Artifacts[0]
want := "D4-A08AR12000002-A3-SIP_EN.xlsx"
if art.FileName != want || art.FileType != ".xlsx" || art.Deleted() {
t.Fatalf("unexpected artifact: %+v", art)
}
ss := sharedStringsFrom(t, tempDoc.createdBytes[created.ID])
data, ok := files.saved[strings.TrimPrefix(art.URL, "local://")]
if !ok {
t.Fatalf("artifact bytes not saved: %s", art.URL)
}
ss := sharedStringsFrom(t, data)
if strings.ContainsAny(ss, "螺母") {
t.Fatalf("delivered workbook still contains Chinese: %s", ss)
}
if !strings.Contains(ss, "Assembly Process") {
t.Fatalf("English string lost: %s", ss)
}
}
// TestXlsxTranslateArtifactDeliveryIsIdempotent: a retried tool call must not
// duplicate the artifact on the assistant message.
func TestXlsxTranslateArtifactDeliveryIsIdempotent(t *testing.T) {
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",
})
sink := &fakeArtifactSink{messages: map[string]*types.Message{
"assistant-1": {ID: "assistant-1", SessionID: "sess-1"},
}}
files := &fakeTranslateFileService{}
tool := NewXlsxTranslateTool(nil, nil, tempDoc, files, sink, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{AttachmentName: "part.xlsx"})
for i := 0; i < 2; i++ {
result, err := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
if err != nil || !result.Success {
t.Fatalf("Execute run %d failed: %v / %s", i+1, err, result.Error)
}
}
if got := len(sink.messages["assistant-1"].Artifacts); got != 1 {
t.Fatalf("artifact duplicated on retry: %d", got)
}
}
// TestXlsxTranslateToolSandboxReadFallsBackToAttachment covers a mixed
@@ -267,10 +345,10 @@ func TestXlsxTranslateToolSandboxReadFallsBackToAttachment(t *testing.T) {
tempDoc.docs = append(tempDoc.docs, &types.TemporaryDocument{
ID: "doc-1", FileName: "part.xlsx", FileType: "xlsx",
})
tool := NewXlsxTranslateTool(store, store, tempDoc, &fakeTranslateChat{})
tool := NewXlsxTranslateTool(store, store, tempDoc, nil, nil, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xlsx"})
result, err := tool.Execute(toolExecContext("sess-1"), args)
result, err := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
if err != nil {
t.Fatalf("Execute: %v", err)
}
@@ -286,10 +364,10 @@ 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{})
tool := NewXlsxTranslateTool(store, store, nil, nil, nil, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/part.xls"})
result, _ := tool.Execute(toolExecContext("sess-1"), args)
result, _ := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
if result.Success {
t.Fatalf("legacy .xls should be rejected")
}
@@ -301,10 +379,10 @@ func TestXlsxTranslateToolRejectsNonXlsx(t *testing.T) {
func TestXlsxTranslateToolMissingFile(t *testing.T) {
store := &fakeTranslateStore{files: map[string][]byte{}}
tempDoc := &fakeTranslateTempDoc{}
tool := NewXlsxTranslateTool(store, store, tempDoc, &fakeTranslateChat{})
tool := NewXlsxTranslateTool(store, store, tempDoc, nil, nil, &fakeTranslateChat{})
args, _ := json.Marshal(XlsxTranslateInput{FilePath: "/workspace/input/missing.xlsx"})
result, _ := tool.Execute(toolExecContext("sess-1"), args)
result, _ := tool.Execute(toolExecContext("sess-1", "assistant-1"), args)
if result.Success {
t.Fatalf("missing file should fail")
}
@@ -694,8 +694,10 @@ func (s *agentService) registerXlsxTranslateTool(
if err == nil && sandboxMgr != nil {
store = sessionSandboxFileStore(sandboxMgr)
}
// store doubles as the dir ensurer; both are nil without a sandbox.
toolRegistry.RegisterTool(tools.NewXlsxTranslateTool(store, store, s.temporaryDocuments, chatModel))
// store doubles as the dir ensurer; both are nil without a sandbox. The
// message service is the no-sandbox artifact sink: deliverables attach to
// the assistant message and surface as chat artifact cards.
toolRegistry.RegisterTool(tools.NewXlsxTranslateTool(store, store, s.temporaryDocuments, s.fileService, s.messageService, chatModel))
if store != nil {
logger.Infof(ctx, "Registered xlsx_translate tool for session: %s (sandbox delivery)", sessionID)
} else {