claude: the interactive mode takes an image known by its URL
The interactive mode is pasted files, so an image a client names by its
URL alone made the run fall to the refusal list ("image"), which with
the TUI on means a 502. Now serveSubscription downloads each such image
first (fetchURLImages): from public addresses only (publicClient, the
same fetch the other providers use), checked to be an image by its
bytes, and kept by URL (32 of them) so a conversation that hands the
same URLs over each turn downloads each once. One that can't be had
fails the request with a 400 naming the URL and why; nothing of a
non-image's content is echoed. claudePrint's "image" entry stays as a
backstop, unreachable with the mode on.
The provider editor's tooltip for claude -p no longer lists the image
among what the interactive mode can't take (en, zh, zh-TW, ja, de), and
the bridge's subsystem page says how the image is fetched.
Run (mote, at this tree on 9f17ad4c1): gofmt -l clean; go vet
./internal/gateway, also GOOS=windows; go test -count=1 -timeout 45m
./internal/gateway: ok (760s), with ./internal/claudetui ok; GUI claude-mode, claude-tui-setting and
i18n-keys in chromium and webkit: 44, 16 and 4 pass in each engine, 0 fail.
Rebased on 9d08993c8 (main touched claude_subscription.go's tool names), then
at the pushed tree: go vet ./internal/gateway; go test -run Claude
./internal/gateway ok (68s); i18n-keys and claude-mode 48 pass, 0 fail
in each engine.
Broken by hand: with the fetchURLImages call taken out,
TestClaudeTUIImageByURL is red (502 "an image known by its URL"); green
with it back.
Not tried: a real image by URL through a real interactive Claude Code
(the plan's quota is kept for the long-conversation runs that come
next); the download itself is
FetchImage's, which the other providers' image paths already use.
This commit is contained in:
@@ -266,14 +266,22 @@ the setting (`claudeTUIErr`, `claudeNotTUIWhy`). That is when
|
||||
|
||||
- it is Claude Code in WSL whose home the probe didn't find, or, in
|
||||
the distro user's own folder, one Windows can't read (`wslread`);
|
||||
- the request has a JSON schema, an image
|
||||
known only by its URL (`urlImages`: the helper pastes files, and has no
|
||||
bytes of it), or words over 400KB (`tuiPromptMost`, images not counted),
|
||||
which a paste can't carry;
|
||||
- the request has a JSON schema, or words over 400KB (`tuiPromptMost`,
|
||||
images not counted), which a paste can't carry;
|
||||
- it is a branch of a `-p` run's session (`branch`: see
|
||||
[Tool results another request answers first](#tool-results-another-request-answers-first));
|
||||
a branch of an interactive run's session is interactive too.
|
||||
|
||||
An image known only by its URL is downloaded first
|
||||
(`fetchURLImages`, in `serveClaudeSubscription`): the helper pastes
|
||||
files, where `-p`'s Claude Code had Anthropic fetch the URL. It goes
|
||||
through `publicClient` (public addresses only, as every image fetch), it
|
||||
must read as an image (`http.DetectContentType`), and the last 32 are
|
||||
kept by URL (`urlImageBytes`), since a conversation hands the same URLs
|
||||
over each turn. One that can't be had fails the request, saying which
|
||||
and why; no Claude Code runs it. With the bytes in, the request is an
|
||||
ordinary one with a pasted image (`TestClaudeTUIImageByURL`).
|
||||
|
||||
Safeguards are taken: interactive Claude Code reads
|
||||
`CLAUDE_CODE_EXTRA_BODY` only as it starts (2.1.316: a later
|
||||
`apply_flag_settings` or a rewritten `--settings` file changes nothing it
|
||||
@@ -312,8 +320,7 @@ subscription with Only switch serves nothing through magpie and shows no
|
||||
row.
|
||||
|
||||
A turn the interactive mode can't take ends the run, and the next starts
|
||||
anew: a turn with an image known by its URL (refused, as above), one
|
||||
that takes earlier turns back, an effort change. A run given up on
|
||||
anew: a turn that takes earlier turns back, an effort change. A run given up on
|
||||
(`letGo`) is not taken back, since the interactive mode can't answer a
|
||||
control request to stop a turn.
|
||||
|
||||
@@ -544,8 +551,7 @@ before the run is let go and its file removed (`branchAt`, a cut copy as
|
||||
in [Tool results another request answers first](#tool-results-another-request-answers-first)),
|
||||
and a new interactive run resumes the copy, told only the turn's
|
||||
messages. Before, every turn after a suggestion was told whole to a new
|
||||
run (bbfatx on X). There is no cut with a client's own cache marks, with
|
||||
an image known only by its URL, or for a run with no session or no line;
|
||||
run (bbfatx on X). There is no cut with a client's own cache marks, or for a run with no session or no line;
|
||||
then the turn is told whole, as before.
|
||||
`TestClaudeInteractiveSideQuestionBranchesBeforeIt` holds it.
|
||||
|
||||
|
||||
@@ -3878,6 +3878,71 @@ func urlImages(msgs []Message) int {
|
||||
return n
|
||||
}
|
||||
|
||||
// urlImageBytes keeps the images fetchURLImages downloaded, by URL, for
|
||||
// the turns after: a conversation hands the same URLs over each turn.
|
||||
var urlImageBytes = struct {
|
||||
sync.Mutex
|
||||
got map[string]Part
|
||||
keys []string
|
||||
}{got: map[string]Part{}}
|
||||
|
||||
// urlImagesKept is how many downloaded images urlImageBytes keeps.
|
||||
const urlImagesKept = 32
|
||||
|
||||
// fetchURLImages fills in the bytes of msgs' images known by their URL
|
||||
// alone, in place: from public addresses only (publicClient), and each
|
||||
// must be an image. One that can't be had fails the request, saying which
|
||||
// and why.
|
||||
func fetchURLImages(ctx context.Context, msgs []Message) error {
|
||||
fill := func(p *Part) error {
|
||||
if p.Data != "" || p.URL == "" {
|
||||
return nil
|
||||
}
|
||||
urlImageBytes.Lock()
|
||||
got, ok := urlImageBytes.got[p.URL]
|
||||
urlImageBytes.Unlock()
|
||||
if !ok {
|
||||
b, _, err := FetchImage(ctx, publicClient, p.URL)
|
||||
if err != nil {
|
||||
return fmt.Errorf("couldn't fetch the image at %s for the interactive mode: %v", p.URL, err)
|
||||
}
|
||||
mt := http.DetectContentType(b)
|
||||
if !strings.HasPrefix(mt, "image/") {
|
||||
return fmt.Errorf("couldn't use the image at %s: it isn't an image (it reads as %s)", p.URL, mt)
|
||||
}
|
||||
got = Part{MediaType: mt, Data: base64.StdEncoding.EncodeToString(b)}
|
||||
urlImageBytes.Lock()
|
||||
if _, ok := urlImageBytes.got[p.URL]; !ok {
|
||||
urlImageBytes.keys = append(urlImageBytes.keys, p.URL)
|
||||
if len(urlImageBytes.keys) > urlImagesKept {
|
||||
delete(urlImageBytes.got, urlImageBytes.keys[0])
|
||||
urlImageBytes.keys = urlImageBytes.keys[1:]
|
||||
}
|
||||
}
|
||||
urlImageBytes.got[p.URL] = got
|
||||
urlImageBytes.Unlock()
|
||||
}
|
||||
p.MediaType, p.Data = got.MediaType, got.Data
|
||||
return nil
|
||||
}
|
||||
for i := range msgs {
|
||||
for j := range msgs[i].Parts {
|
||||
part := &msgs[i].Parts[j]
|
||||
if part.Kind == Image {
|
||||
if err := fill(part); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for k := range part.Images {
|
||||
if err := fill(&part.Images[k]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// historyEnd is where the turn to answer begins in msgs: the message after
|
||||
// the last reply that calls no tool. 0 when there is no such reply, or
|
||||
// nothing after it, and the messages are told as one turn.
|
||||
@@ -5443,6 +5508,13 @@ func (s *Server) serveSubscription(w http.ResponseWriter, r *http.Request, from
|
||||
}
|
||||
}
|
||||
}
|
||||
if name == "Claude Code" && claudeTUIOn() && urlImages(req.Messages) > 0 {
|
||||
// the interactive mode is pasted files: an image known by its URL
|
||||
// is downloaded first, as -p's Claude Code had Anthropic fetch it
|
||||
if err := fetchURLImages(r.Context(), req.Messages); err != nil {
|
||||
return writeError(w, from, 400, "Claude Code: "+err.Error()), err.Error()
|
||||
}
|
||||
}
|
||||
// its model searches the web with magpie's tool, which magpie answers
|
||||
var search Tool
|
||||
if req.WebSearch && !searching(r.Context()) {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
package gateway
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/yetone/magpie/internal/claudetui"
|
||||
"github.com/yetone/magpie/internal/provider"
|
||||
"github.com/yetone/magpie/internal/testenv"
|
||||
)
|
||||
|
||||
@@ -102,3 +107,53 @@ func TestClaudeTUIClientCacheKeepsItsOwn(t *testing.T) {
|
||||
t.Fatalf("the next turn started %d runs", n)
|
||||
}
|
||||
}
|
||||
|
||||
// An image known by its URL alone is downloaded for the interactive mode,
|
||||
// which is pasted files: Claude Code is handed its bytes, and the turns
|
||||
// after hand the same URL over without downloading it again. One that
|
||||
// isn't an image, or can't be had, fails the request saying why, and no
|
||||
// Claude Code runs it as -p instead.
|
||||
func TestClaudeTUIImageByURL(t *testing.T) {
|
||||
h := tuiScriptHarness(t, "")
|
||||
srv, hits := secret(t, string(pngBytes))
|
||||
allowPrivate(t, "127.0.0.1")
|
||||
ask := func(url string, said ...string) (int, string) {
|
||||
t.Helper()
|
||||
img := `{"role":"user","content":[{"type":"image","source":{"type":"url","url":"` + url + `"}},{"type":"text","text":"what is it"}]}`
|
||||
msgs := []string{img}
|
||||
for _, m := range said {
|
||||
msgs = append(msgs, `{"role":"assistant","content":"ok"}`, fmt.Sprintf(`{"role":"user","content":%q}`, m))
|
||||
}
|
||||
body := `{"model":"claude-sonnet-5","max_tokens":100,"system":"rules","tools":[{"name":"read","input_schema":{"type":"object"}}],"messages":[` + strings.Join(msgs, ",") + `]}`
|
||||
rec := httptest.NewRecorder()
|
||||
return h.s.serveClaudeSubscription(rec, httptest.NewRequest("POST", "/v1/messages", strings.NewReader(body)), provider.Anthropic, h.p, "claude-sonnet-5", []byte(body), &Usage{})
|
||||
}
|
||||
if code, msg := ask(srv.URL + "/a.png"); code != 200 {
|
||||
t.Fatalf("%d %s", code, msg)
|
||||
}
|
||||
if code, msg := ask(srv.URL+"/a.png", "and now"); code != 200 {
|
||||
t.Fatalf("next turn: %d %s", code, msg)
|
||||
}
|
||||
runs := h.runs()
|
||||
if len(runs) != 1 || hits.Load() != 1 {
|
||||
t.Fatalf("%d runs, the image downloaded %d times", len(runs), hits.Load())
|
||||
}
|
||||
data := base64.StdEncoding.EncodeToString(pngBytes)
|
||||
for _, log := range runs {
|
||||
if !strings.Contains(log, `"data":"`+data+`"`) || !strings.Contains(log, `"media_type":"image/png"`) {
|
||||
t.Fatalf("Claude Code wasn't handed the image's bytes: %s", log)
|
||||
}
|
||||
}
|
||||
notImage, _ := secret(t, `{"admin_token":"s3cret"}`)
|
||||
if code, msg := ask(notImage.URL + "/status"); code != 400 || !strings.Contains(msg, "isn't an image") || strings.Contains(msg, "s3cret") {
|
||||
t.Fatalf("not an image: %d %s", code, msg)
|
||||
}
|
||||
gone := httptest.NewServer(http.NotFoundHandler())
|
||||
defer gone.Close()
|
||||
if code, msg := ask(gone.URL + "/b.png"); code != 400 || !strings.Contains(msg, "404") {
|
||||
t.Fatalf("a missing image: %d %s", code, msg)
|
||||
}
|
||||
if n := len(h.runs()); n != 1 {
|
||||
t.Fatalf("a request whose image couldn't be had ran: %d runs", n)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,7 +38,7 @@ function ccTip(anchor, tui) {
|
||||
t("Your plan counts these requests as Claude Code's own use, at about half of the 5-hour allowance that -p uses for the same work.")),
|
||||
mode(!tui, "claude -p",
|
||||
t("Claude Code's print mode, the one scripts and the Agent SDK use: a request in, its reply out."),
|
||||
t("It starts at once, and takes what the interactive mode can't: a JSON schema, an image by its URL, a first message over 400KB."),
|
||||
t("It starts at once, and takes what the interactive mode can't: a JSON schema, a first message over 400KB."),
|
||||
t("The plan counts a -p request at about twice the interactive mode's.")),
|
||||
el("div", "foot", t("Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why.")));
|
||||
document.body.append(tip);
|
||||
|
||||
@@ -12,7 +12,7 @@ const I18N = {
|
||||
"magpie opens Claude Code as a person does, in a terminal of its own that you don't see, types each request in and reads the reply from its transcript.": "magpie 像人一样打开 Claude Code:在一个你看不到的终端里输入每个请求,再从它的会话记录里读出回复。",
|
||||
"Your plan counts these requests as Claude Code's own use, at about half of the 5-hour allowance that -p uses for the same work.": "套餐把这些请求算作 Claude Code 自身的使用,同样的工作只消耗 -p 约一半的 5 小时额度。",
|
||||
"Claude Code's print mode, the one scripts and the Agent SDK use: a request in, its reply out.": "Claude Code 的打印模式,脚本和 Agent SDK 用的就是它:一个请求进去,一个回复出来。",
|
||||
"It starts at once, and takes what the interactive mode can't: a JSON schema, an image by its URL, a first message over 400KB.": "启动即用,并且支持交互模式做不到的:JSON schema、按 URL 给的图片、超过 400KB 的第一条消息。",
|
||||
"It starts at once, and takes what the interactive mode can't: a JSON schema, a first message over 400KB.": "启动即用,并且支持交互模式做不到的:JSON schema、超过 400KB 的第一条消息。",
|
||||
"The plan counts a -p request at about twice the interactive mode's.": "套餐对 -p 请求的计量约为交互模式的两倍。",
|
||||
"Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why.": "可在这里或 设置 › 模型 › 回复 里切换。开着交互模式时,任何请求都不会走 -p:交互模式接不了或启动失败的请求会报错并说明原因。",
|
||||
"Every request runs as claude -p": "每个请求都以 claude -p 运行",
|
||||
@@ -4366,7 +4366,7 @@ const I18N = {
|
||||
"magpie opens Claude Code as a person does, in a terminal of its own that you don't see, types each request in and reads the reply from its transcript.": "magpie 像人一樣開啟 Claude Code:在一個你看不到的終端機裡輸入每個請求,再從它的對話記錄讀出回覆。",
|
||||
"Your plan counts these requests as Claude Code's own use, at about half of the 5-hour allowance that -p uses for the same work.": "方案把這些請求算作 Claude Code 本身的使用,同樣的工作只消耗 -p 約一半的 5 小時額度。",
|
||||
"Claude Code's print mode, the one scripts and the Agent SDK use: a request in, its reply out.": "Claude Code 的列印模式,腳本和 Agent SDK 用的就是它:一個請求進去,一個回覆出來。",
|
||||
"It starts at once, and takes what the interactive mode can't: a JSON schema, an image by its URL, a first message over 400KB.": "啟動即用,並且支援互動模式做不到的:JSON schema、以 URL 提供的圖片、超過 400KB 的第一則訊息。",
|
||||
"It starts at once, and takes what the interactive mode can't: a JSON schema, a first message over 400KB.": "啟動即用,並且支援互動模式做不到的:JSON schema、超過 400KB 的第一則訊息。",
|
||||
"The plan counts a -p request at about twice the interactive mode's.": "方案對 -p 請求的計量約為互動模式的兩倍。",
|
||||
"Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why.": "可在這裡或 設定 › 模型 › 回覆 裡切換。開著互動模式時,任何請求都不會走 -p:互動模式接不了或啟動失敗的請求會報錯並說明原因。",
|
||||
"Every request runs as claude -p": "每個請求都以 claude -p 執行",
|
||||
@@ -8705,7 +8705,7 @@ const I18N = {
|
||||
"magpie opens Claude Code as a person does, in a terminal of its own that you don't see, types each request in and reads the reply from its transcript.": "magpie は人と同じように Claude Code を開きます。見えない専用のターミナルで各リクエストを入力し、トランスクリプトから応答を読み取ります。",
|
||||
"Your plan counts these requests as Claude Code's own use, at about half of the 5-hour allowance that -p uses for the same work.": "プランはこれらのリクエストを Claude Code 自身の利用として数え、同じ作業で -p の約半分の 5 時間枠しか使いません。",
|
||||
"Claude Code's print mode, the one scripts and the Agent SDK use: a request in, its reply out.": "Claude Code の print モードで、スクリプトや Agent SDK が使うものです。リクエストを渡し、応答を受け取ります。",
|
||||
"It starts at once, and takes what the interactive mode can't: a JSON schema, an image by its URL, a first message over 400KB.": "すぐに起動し、対話モードにできないものも扱えます:JSON schema、URL で指定された画像、400KB を超える最初のメッセージ。",
|
||||
"It starts at once, and takes what the interactive mode can't: a JSON schema, a first message over 400KB.": "すぐに起動し、対話モードにできないものも扱えます:JSON schema、400KB を超える最初のメッセージ。",
|
||||
"The plan counts a -p request at about twice the interactive mode's.": "プランは -p のリクエストを対話モードの約 2 倍として数えます。",
|
||||
"Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why.": "ここか 設定 › モデル › 応答 で切り替えられます。対話モードがオンのときは、何も -p では実行しません。対話モードで扱えないリクエストや起動に失敗したリクエストは理由を添えてエラーになります。",
|
||||
"Every request runs as claude -p": "すべてのリクエストを claude -p で実行します",
|
||||
@@ -13046,7 +13046,7 @@ const I18N = {
|
||||
"magpie opens Claude Code as a person does, in a terminal of its own that you don't see, types each request in and reads the reply from its transcript.": "magpie öffnet Claude Code wie ein Mensch, in einem eigenen Terminal, das du nicht siehst, tippt jede Anfrage ein und liest die Antwort aus dem Transkript.",
|
||||
"Your plan counts these requests as Claude Code's own use, at about half of the 5-hour allowance that -p uses for the same work.": "Dein Plan zählt diese Anfragen als Claude Codes eigene Nutzung, mit etwa der Hälfte des 5-Stunden-Kontingents, das -p für dieselbe Arbeit braucht.",
|
||||
"Claude Code's print mode, the one scripts and the Agent SDK use: a request in, its reply out.": "Der Print-Modus von Claude Code, den Skripte und das Agent SDK nutzen: eine Anfrage hinein, ihre Antwort heraus.",
|
||||
"It starts at once, and takes what the interactive mode can't: a JSON schema, an image by its URL, a first message over 400KB.": "Er startet sofort und kann, was der interaktive Modus nicht kann: ein JSON-Schema, ein Bild per URL, eine erste Nachricht über 400 KB.",
|
||||
"It starts at once, and takes what the interactive mode can't: a JSON schema, a first message over 400KB.": "Er startet sofort und kann, was der interaktive Modus nicht kann: ein JSON-Schema, eine erste Nachricht über 400 KB.",
|
||||
"The plan counts a -p request at about twice the interactive mode's.": "Der Plan zählt eine -p-Anfrage etwa doppelt so hoch wie eine im interaktiven Modus.",
|
||||
"Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why.": "Hier oder unter Einstellungen › Modelle › Antworten umschaltbar. Mit eingeschaltetem interaktivem Modus läuft nie etwas als -p: Eine Anfrage, die er nicht annehmen kann oder für die er nicht startet, schlägt mit dem Grund fehl.",
|
||||
"Every request runs as claude -p": "Jede Anfrage läuft als claude -p",
|
||||
|
||||
@@ -124,7 +124,7 @@ for (const engine of (process.env.BROWSER ? [process.env.BROWSER] : ["chromium",
|
||||
]);
|
||||
// nothing in the card says a request falls back to -p (the owner, 11-01)
|
||||
assert.equal((await tip.locator(".foot").textContent()).trim(), await tr("Switched here or in Settings › Models › Replies. With the interactive mode on, nothing ever runs as -p: a request it can't take, or one it fails to start for, fails saying why."));
|
||||
assert.equal((await tip.locator(".cc-m").nth(1).locator("p.good").textContent()).trim(), await tr("It starts at once, and takes what the interactive mode can't: a JSON schema, an image by its URL, a first message over 400KB."));
|
||||
assert.equal((await tip.locator(".cc-m").nth(1).locator("p.good").textContent()).trim(), await tr("It starts at once, and takes what the interactive mode can't: a JSON schema, a first message over 400KB."));
|
||||
const box = await tip.boundingBox();
|
||||
assert(box.x >= 0 && box.y >= 0 && box.x + box.width <= width && box.y + box.height <= 760, `the card is inside the window: ${JSON.stringify(box)}`);
|
||||
if (lang !== "en") {
|
||||
|
||||
Reference in New Issue
Block a user