| 1 | package workbench |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "io" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "time" |
| 13 | |
| 14 | "github.com/sylvinus/agent-vm/internal/diagnostics" |
| 15 | "github.com/sylvinus/agent-vm/internal/usererror" |
| 16 | ) |
| 17 | |
| 18 | const browserResponseLimit = 1 << 20 |
| 19 | const browserOrigin = "http://127.0.0.1:18500" |
| 20 | |
| 21 | |
| 22 | |
| 23 | type browserClient struct { |
| 24 | ctx context.Context |
| 25 | cancel context.CancelFunc |
| 26 | http *http.Client |
| 27 | } |
| 28 | |
| 29 | func newBrowserClient(parent context.Context) *browserClient { |
| 30 | ctx, cancel := context.WithCancel(parent) |
| 31 | return &browserClient{ctx: ctx, cancel: cancel, http: &http.Client{ |
| 32 | Transport: &http.Transport{Proxy: nil, IdleConnTimeout: 30 * time.Second, MaxIdleConnsPerHost: 4, DialContext: (&net.Dialer{Timeout: 3 * time.Second}).DialContext}, |
| 33 | CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("redirect refused") }, |
| 34 | }} |
| 35 | } |
| 36 | |
| 37 | func (c *browserClient) close() { |
| 38 | c.cancel() |
| 39 | c.http.CloseIdleConnections() |
| 40 | } |
| 41 | |
| 42 | |
| 43 | |
| 44 | func (c *browserClient) open(parent context.Context, token, method, path, contentType string, body io.Reader, length int64, timeout time.Duration) (*http.Response, error) { |
| 45 | if err := c.ctx.Err(); err != nil { |
| 46 | return nil, err |
| 47 | } |
| 48 | ctx, cancel := context.WithCancel(parent) |
| 49 | stop := context.AfterFunc(c.ctx, cancel) |
| 50 | finish := func() { stop(); cancel() } |
| 51 | if timeout > 0 { |
| 52 | var cancelTimeout context.CancelFunc |
| 53 | ctx, cancelTimeout = context.WithTimeout(ctx, timeout) |
| 54 | finish = func() { stop(); cancelTimeout(); cancel() } |
| 55 | } |
| 56 | req, err := http.NewRequestWithContext(ctx, method, browserOrigin+path, body) |
| 57 | if err != nil { |
| 58 | finish() |
| 59 | return nil, err |
| 60 | } |
| 61 | req.Header.Set("Authorization", "Bearer "+token) |
| 62 | if body != nil { |
| 63 | req.Header.Set("Content-Type", contentType) |
| 64 | req.ContentLength = length |
| 65 | } |
| 66 | response, err := c.http.Do(req) |
| 67 | if err != nil { |
| 68 | finish() |
| 69 | return nil, err |
| 70 | } |
| 71 | response.Body = &browserResponseBody{ReadCloser: response.Body, finish: finish} |
| 72 | return response, nil |
| 73 | } |
| 74 | |
| 75 | type browserResponseBody struct { |
| 76 | io.ReadCloser |
| 77 | finish func() |
| 78 | } |
| 79 | |
| 80 | func (b *browserResponseBody) Close() error { |
| 81 | b.finish() |
| 82 | return b.ReadCloser.Close() |
| 83 | } |
| 84 | |
| 85 | func (c *browserClient) request(ctx context.Context, token, method, path string, body []byte) ([]byte, error) { |
| 86 | timeout := 5 * time.Second |
| 87 | switch path { |
| 88 | case "/audit", "/paste-image", "/tailnet": |
| 89 | timeout = 20 * time.Second |
| 90 | case "/editor-restart": |
| 91 | timeout = 30 * time.Second |
| 92 | case "/extensions": |
| 93 | timeout = 25 * time.Second |
| 94 | } |
| 95 | var reader io.Reader |
| 96 | if body != nil { |
| 97 | reader = bytes.NewReader(body) |
| 98 | } |
| 99 | response, err := c.open(ctx, token, method, path, "application/json", reader, int64(len(body)), timeout) |
| 100 | if err != nil { |
| 101 | diagnostics.Log("warn", "browser", fmt.Sprintf("operation=%s transport=%v", path, err)) |
| 102 | return nil, usererror.Wrap(browserOperation(path), err, "请确认环境仍在运行,并重新连接浏览器;持续失败时在设置中导出诊断包。") |
| 103 | } |
| 104 | defer response.Body.Close() |
| 105 | data, err := io.ReadAll(io.LimitReader(response.Body, browserResponseLimit+1)) |
| 106 | if err != nil { |
| 107 | return nil, usererror.Wrap(browserOperation(path), err, "浏览器结果没有完整返回,请重新连接后核对本次操作是否已生效。") |
| 108 | } |
| 109 | if len(data) > browserResponseLimit { |
| 110 | return nil, errors.New(browserOperation(path) + "失败:浏览器返回的数据超过 1 MiB,已停止读取。请关闭不再使用的标签页或扩展后再试;持续出现时导出诊断包。") |
| 111 | } |
| 112 | if response.StatusCode != http.StatusOK { |
| 113 | diagnostics.Log("warn", "browser", fmt.Sprintf("operation=%s http=%d", path, response.StatusCode)) |
| 114 | var result struct { |
| 115 | Error string `json:"error"` |
| 116 | } |
| 117 | _ = json.Unmarshal(data, &result) |
| 118 | known := map[string]string{ |
| 119 | "Tab no longer exists": "标签页已关闭。请重新打开网页后再操作。", |
| 120 | "Browser is starting": "浏览器仍在启动。请等待启动完成后再操作。", |
| 121 | "Input target changed": "接收内容的页面已切换。请回到原页面并重新点击输入框。", |
| 122 | "Image target changed": "接收图片的页面已切换。请回到原页面并重新点击输入框。", |
| 123 | "Copy target changed": "要复制内容的页面已切换。请回到原页面重新复制。", |
| 124 | "Image too large": "图片超过允许大小。请缩小图片后重新粘贴。", |
| 125 | "Invalid PNG": "图片不是有效的 PNG 文件。请重新复制或导出图片。", |
| 126 | "Only HTTP(S) URLs without credentials are accepted": "网址中包含账号或密码。请使用不带登录凭据的 http 或 https 网址。", |
| 127 | "Only HTTP(S) URLs and supported browser pages are accepted": "不支持这个网址类型。请使用 http 或 https 网址。", |
| 128 | "Unknown browser action": "浏览器组件不支持这次操作。请更新环境组件后再试。", |
| 129 | "Split controller unavailable": "分屏组件没有就绪。请更新环境组件后重新打开分屏。", |
| 130 | "Editor authentication is unavailable": "编辑器的本地登录会话不可用。请从 Cage 重新打开编辑器。", |
| 131 | "文件接收网页已切换,请返回原网页重试": "文件接收网页已切换,请返回原网页重试。", |
| 132 | "浏览器组件未能恢复,请重启环境": "浏览器组件未能恢复,请保存工作后重启环境。", |
| 133 | "不同浏览会话不能分屏": "所选页面属于不同浏览会话,无法放在同一个分屏中。请在同一会话中打开两个网页。", |
| 134 | "无痕标签暂不支持双网页分屏": "无痕标签暂不支持双网页分屏。请使用普通标签页。", |
| 135 | "设置页请在单个浏览器窗格内使用": "设置页请在单个浏览器窗格内使用。请先退出分屏。", |
| 136 | "扩展 ZIP 不能超过 32 MB": "扩展 ZIP 不能超过 32 MB。请缩小扩展包后重新导入。", |
| 137 | } |
| 138 | if reason := known[result.Error]; reason != "" { |
| 139 | return nil, errors.New(browserOperation(path) + "失败:" + reason) |
| 140 | } |
| 141 | return nil, serviceHTTPFailure(browserOperation(path), response.StatusCode) |
| 142 | } |
| 143 | return data, nil |
| 144 | } |
| 145 | |
| 146 | func (c *browserClient) events(ctx context.Context, token string) (io.ReadCloser, error) { |
| 147 | response, err := c.open(ctx, token, http.MethodGet, "/events", "", nil, 0, 0) |
| 148 | if err != nil { |
| 149 | return nil, err |
| 150 | } |
| 151 | if response.StatusCode != http.StatusOK { |
| 152 | response.Body.Close() |
| 153 | return nil, serviceHTTPFailure("接收浏览器状态", response.StatusCode) |
| 154 | } |
| 155 | return response.Body, nil |
| 156 | } |
| 157 | |
| 158 | func (c *browserClient) file(ctx context.Context, token, method, path string, body io.Reader, length int64) (*http.Response, error) { |
| 159 | return c.open(ctx, token, method, path, "application/octet-stream", body, length, 30*time.Minute) |
| 160 | } |