From 7d3b6804af5d8dd53e55cba289ec428624eeb61a Mon Sep 17 00:00:00 2001 From: "DESKTOP-JKIE562\\PC" <1013397054@qq.com> Date: Mon, 30 Nov 2026 23:22:23 +0800 Subject: [PATCH] =?UTF-8?q?fix(=E7=BF=BB=E8=AF=91bug):=E4=BF=AE=E5=A4=8D?= =?UTF-8?q?=E7=BF=BB=E8=AF=91=E8=B6=85=E6=97=B6=E5=A4=B1=E8=B4=A5=EF=BC=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- internal/agent/tools/xlsx_translate.go | 83 +++++++++++++++++++-- internal/agent/tools/xlsx_translate_test.go | 81 ++++++++++++++++++++ internal/xlsxtranslate/classify.go | 7 ++ internal/xlsxtranslate/engine.go | 33 ++++++-- internal/xlsxtranslate/engine_test.go | 31 ++++++++ 5 files changed, 220 insertions(+), 15 deletions(-) diff --git a/internal/agent/tools/xlsx_translate.go b/internal/agent/tools/xlsx_translate.go index 4e3f092..ff69838 100644 --- a/internal/agent/tools/xlsx_translate.go +++ b/internal/agent/tools/xlsx_translate.go @@ -4,6 +4,7 @@ import ( "bytes" "context" "encoding/json" + "errors" "fmt" "io" "path" @@ -284,17 +285,70 @@ Rules: 5. Output ONLY a JSON array of translated strings with the same length and order as the input array. No commentary.` func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string) ([]string, error) { + return c.translateRecover(ctx, texts, bisectDepth(len(texts))) +} + +// bisectDepth bounds the halving steps needed to reach single strings. +func bisectDepth(n int) int { + depth := 0 + for n > 1 { + n /= 2 + depth++ + } + return depth + 1 +} + +// translateRecover aligns model answers with inputs. A positional JSON +// protocol fails in one deterministic way: the model merges or drops an item +// (near-duplicate strings, symbol-only entries) and returns N-1 results, so +// blind retries reproduce the same mismatch forever. On a count mismatch the +// batch is halved and each half retried; a single stubborn string degrades to +// keeping the original text, which the engine's residual scan reports. +func (c *chatBatchTranslator) translateRecover(ctx context.Context, texts []string, depth int) ([]string, error) { + out, err := c.attempt(ctx, texts) + if err == nil && len(out) == len(texts) { + return out, nil + } + if len(texts) == 1 { + if err == nil && len(out) >= 1 && strings.TrimSpace(out[0]) != "" { + return []string{out[0]}, nil + } + // Keep the original untranslated; the residual scan reports it. + return []string{texts[0]}, nil + } + if depth <= 0 { + if err != nil { + return nil, err + } + return nil, fmt.Errorf("model returned %d translations for %d inputs", len(out), len(texts)) + } + mid := len(texts) / 2 + left, err := c.translateRecover(ctx, texts[:mid], depth-1) + if err != nil { + return nil, err + } + right, err := c.translateRecover(ctx, texts[mid:], depth-1) + if err != nil { + return nil, err + } + return append(left, right...), nil +} + +// attempt issues one streaming call. Transport and JSON-shape errors get one +// immediate retry; count mismatches are content-deterministic and returned +// (wrapped) so the caller bisects instead of repeating the same failure. +func (c *chatBatchTranslator) attempt(ctx context.Context, texts []string) ([]string, error) { payload, err := json.Marshal(texts) if err != nil { return nil, err } var lastErr error - for attempt := 0; attempt < 3; attempt++ { - if attempt > 0 { + for a := 0; a < 2; a++ { + if a > 0 { select { case <-ctx.Done(): return nil, ctx.Err() - case <-time.After(time.Duration(attempt) * 2 * time.Second): + case <-time.After(2 * time.Second): } } user := fmt.Sprintf("Translate the following JSON array of strings to English. Return a JSON array with exactly %d items in the same order.\n\n%s", len(texts), payload) @@ -303,9 +357,13 @@ func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string lastErr = err continue } - out, err := parseTranslationArray(content, len(texts)) - if err != nil { - lastErr = err + out, perr := parseTranslationArray(content, len(texts)) + if perr != nil { + var mismatch *countMismatchError + if errors.As(perr, &mismatch) { + return mismatch.items, perr + } + lastErr = perr continue } return out, nil @@ -313,6 +371,17 @@ func (c *chatBatchTranslator) TranslateBatch(ctx context.Context, texts []string return nil, fmt.Errorf("translation call failed after retries: %w", lastErr) } +// countMismatchError carries the model's items so bisection can still use +// them when the counts do not line up. +type countMismatchError struct { + got, want int + items []string +} + +func (e *countMismatchError) Error() string { + return fmt.Sprintf("model returned %d translations for %d inputs", e.got, e.want) +} + // translateOnce issues one streaming batch call and returns the concatenated // answer. Streaming is deliberate: long batches then fall under the chat // client's stall-based timeout instead of a single non-stream HTTP timeout. @@ -354,7 +423,7 @@ func parseTranslationArray(content string, want int) ([]string, error) { return nil, fmt.Errorf("model response is not a valid string array: %w", err) } if len(out) != want { - return nil, fmt.Errorf("model returned %d translations for %d inputs", len(out), want) + return nil, &countMismatchError{got: len(out), want: want, items: out} } return out, nil } diff --git a/internal/agent/tools/xlsx_translate_test.go b/internal/agent/tools/xlsx_translate_test.go index f31d5d9..d6ab15a 100644 --- a/internal/agent/tools/xlsx_translate_test.go +++ b/internal/agent/tools/xlsx_translate_test.go @@ -309,3 +309,84 @@ func TestXlsxTranslateToolMissingFile(t *testing.T) { 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]) + } +} diff --git a/internal/xlsxtranslate/classify.go b/internal/xlsxtranslate/classify.go index d56acc7..1509871 100644 --- a/internal/xlsxtranslate/classify.go +++ b/internal/xlsxtranslate/classify.go @@ -141,6 +141,13 @@ func trimSpaceASCII(s string) string { return strings.Trim(s, " \t\n\r") } +// collapseWhitespace trims and collapses every whitespace run (including +// full-width spaces) to a single ASCII space. Used as the dedupe key so +// layout-padded variants of one term share a single translation unit. +func collapseWhitespace(s string) string { + return strings.Join(strings.Fields(s), " ") +} + // itoa is a tiny helper so this file needs no strconv import noise. func itoa(i int) string { if i == 0 { diff --git a/internal/xlsxtranslate/engine.go b/internal/xlsxtranslate/engine.go index 5508f02..a0ee3df 100644 --- a/internal/xlsxtranslate/engine.go +++ b/internal/xlsxtranslate/engine.go @@ -238,15 +238,24 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([ } } - // Deduplicate across entries, preserving first-seen order. + // Deduplicate across entries, preserving first-seen order. Near + // duplicates that differ only in whitespace collapse to one unit: + // sending both in one batch makes the model answer with a single + // translation for "the same string twice", which desynchronises the + // positional array protocol. unitOrder := []string{} - unitSeen := map[string]struct{}{} + unitSeen := map[string]string{} + unitCanonical := map[string]string{} // raw text -> canonical raw text for _, job := range jobs { for _, u := range job.units { - if _, ok := unitSeen[u]; !ok { - unitSeen[u] = struct{}{} - unitOrder = append(unitOrder, u) + key := collapseWhitespace(u) + if canonical, ok := unitSeen[key]; ok { + unitCanonical[u] = canonical + continue } + unitSeen[key] = u + unitCanonical[u] = u + unitOrder = append(unitOrder, u) } } // Oversized units are skipped rather than risking a broken LLM call. @@ -366,6 +375,12 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([ report.AppliedTranslations = len(translations) // ---- Pass 3: rewrite affected entries, repack in original order ---- + alias := func(raw string) string { + if canonical, ok := unitCanonical[raw]; ok { + return canonical + } + return raw + } type outEntry struct { idx int data []byte @@ -374,7 +389,7 @@ func Translate(ctx context.Context, data []byte, opt *Options, tr Translator) ([ for i := range reader.File { data := entryData[i] if job, ok := jobs[i]; ok { - data = []byte(applyJob(string(data), job, translations)) + data = []byte(applyJob(string(data), job, translations, alias)) } out = append(out, outEntry{idx: i, data: data}) } @@ -518,7 +533,9 @@ func scanDrawing(src string) (*scanJob, int) { // applyJob rewrites one entry with the resolved translations. Bytes outside // the recorded edits — styles, geometry, image references — are untouched. -func applyJob(src string, job *scanJob, translations map[string]string) string { +// alias resolves a raw unit to its canonical unit (whitespace-variant +// near duplicates share one translation). +func applyJob(src string, job *scanJob, translations map[string]string, alias func(string) string) string { type repl struct { start, end int text string @@ -527,7 +544,7 @@ func applyJob(src string, job *scanJob, translations map[string]string) string { for _, e := range job.edits { switch e.kind { case editCarrier: - t, ok := translations[job.units[e.unitIdx]] + t, ok := translations[alias(job.units[e.unitIdx])] if !ok { continue // oversized/skipped unit: keep the original bytes } diff --git a/internal/xlsxtranslate/engine_test.go b/internal/xlsxtranslate/engine_test.go index af7d839..ae2d19a 100644 --- a/internal/xlsxtranslate/engine_test.go +++ b/internal/xlsxtranslate/engine_test.go @@ -440,3 +440,34 @@ func min(a, b int) int { } return b } + +// TestTranslateCollapsesWhitespaceVariants covers the positional-protocol +// desync: whitespace-padded variants of one term must collapse into a single +// translation unit, or a batch containing both loses an answer (19 of 20). +func TestTranslateCollapsesWhitespaceVariants(t *testing.T) { + var buf bytes.Buffer + zw := zip.NewWriter(&buf) + w, _ := zw.Create("xl/sharedStrings.xml") + w.Write([]byte(`` + + `客 戶` + + `客 戶` + + `客户资料清单` + + ``)) + zw.Close() + + tr := &fakeTranslator{} + out, report, err := Translate(context.Background(), buf.Bytes(), nil, tr) + if err != nil { + t.Fatalf("Translate: %v", err) + } + if report.TranslatedUnits != 2 { + t.Fatalf("expected 2 canonical units after whitespace collapse, got %d", report.TranslatedUnits) + } + ss := string(zipEntry(t, out, "xl/sharedStrings.xml")) + if hasCJK(ss) { + t.Fatalf("variants left untranslated:\n%s", ss) + } + if strings.Count(ss, "Customer") != 2 { + t.Fatalf("both whitespace variants should carry the glossary translation:\n%s", ss) + } +}