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
+209 -51

No files matched your search

+104 -26
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.
//
@@ -68,29 +79,46 @@ type SessionDirEnsurer interface {
// call it ("tool not found").
type XlsxTranslateTool struct {
BaseTool
store SandboxFileSink
ensure SessionDirEnsurer
tempDoc interfaces.TemporaryDocumentService
model chat.Chat
timeout time.Duration
store SandboxFileSink
ensure SessionDirEnsurer
tempDoc interfaces.TemporaryDocumentService
files interfaces.FileService
artifacts MessageArtifactSink
model chat.Chat
timeout time.Duration
}
// 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 {
// 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,
description: xlsxTranslateDescription,
schema: utils.GenerateSchema[XlsxTranslateInput](),
},
store: store,
ensure: ensure,
tempDoc: tempDoc,
model: model,
timeout: 20 * time.Minute,
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