Compare commits

...
Author SHA1 Message Date
leokun 2e265d415e feat(forwarder): make checkpoint recovery idempotent
Preserve interrupted provider output, keep checkpoint projections deterministic, and enforce proto snapshot synchronization.
2026-08-06 21:08:43 +08:00
leokun 0d1cedda5b Merge remote-tracking branch 'origin/hotfix/chat-checkpoint' 2026-08-06 16:34:10 +08:00
leokun c7fe198110 Merge branch 'main' of github.com:leookun/cursor-byok 2026-08-06 14:10:18 +08:00
leokunandGitHub 8c4baf7ade Merge pull request #262 from k23223/feat/model-adapter-model-selection
feat(model-adapter): add remote model selection
2026-08-06 14:10:08 +08:00
leokun 4e0d2ee703 Merge branch 'main' of github.com:leookun/cursor-byok 2026-08-06 14:05:58 +08:00
leokunandGitHub e1dacab268 Merge pull request #260 from leookun/hotfix/fork-chat 2026-08-06 12:12:46 +08:00
xiaopuandCursor 320b9fb7b9 feat(model-adapter): add remote model selection
- Fetch and normalize OpenAI and Anthropic model lists through the proxy service.
- Add searchable multi-model selection with localized UI and persisted adapter mappings.
- Cover endpoint resolution, authentication, pagination, and response parsing.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-05 15:23:51 +08:00
leokunandGitHub c55c575a58 Merge pull request #255 from Phoeky/patch-1 2026-08-05 11:58:23 +08:00
leookun d3adfffbd8 Implement checkpoint blob handling in forwarder service
- Added support for checkpointing phases and blob management in the forwarder.
- Introduced new types and methods for handling checkpoint blobs, including queuing and publishing checkpoints.
- Enhanced the projector to build checkpoint projections with content-addressed blobs.
- Implemented tests to ensure proper checkpoint blob synchronization and handling of cancellation scenarios.
2026-08-05 02:09:45 +08:00
leookun 4e9335d82f Implement tests for ProjectLegacyCheckpoint to ensure proper handling of conversation state and message imports. This includes verifying that no dangling inline blobs are present and that the correct user and assistant messages are imported. 2026-08-05 01:46:47 +08:00
leokunandGitHub 374ff9c217 Merge pull request #259 from leookun/release/0.0.45
Release/0.0.45
2026-08-05 01:26:22 +08:00
leookun 06ab0d8dae chore(release): update version to 0.0.45 and fix conversation disappearance issue
- Updated version number to 0.0.45 across all relevant files.
- Fixed an issue that could cause conversations to disappear.
2026-08-05 01:25:39 +08:00
leookun 2f47f02497 chore(cursor-proxy-debugger): enhance traffic capture for Fork Chat and update README
- Added support for capturing and decoding Fork Chat traffic, including `ForkBackgroundComposer`, `NotifyConversationClone`, and `UploadConversationBlobs`.
- Updated the README to reflect new features and usage instructions for Fork Chat traffic.
- Modified `.gitignore` to include `proto/extensions-cursor-app/`.
- Refactored `Taskfile.yml` to improve error messages related to Cursor extensions.
- Introduced new tests for decoding functionality in `cursor-proxy-debugger`.
2026-08-05 01:17:01 +08:00
leookun 058aaa532e remote: cursor source code from git 2026-08-05 00:34:30 +08:00
leookun 622a57fed7 Revert "Merge pull request #239 from DedSecer/fix/cursor-fork-context"
This reverts commit 697fa99245, reversing
changes made to 5742073be5.
2026-08-04 23:49:49 +08:00
leookun f5a7347f44 fix: gate WebView sandbox opt-out behind environment variable 2026-08-04 21:49:26 +08:00
PhoekyandGitHub a9b406ec30 解决 VDI 环境(如 VMware Horizon)导致主窗口白屏。 2026-08-04 17:39:14 +08:00
leokunandGitHub 639c452a00 Merge pull request #252 from leookun/release/0.0.44
chore(release): update version to 0.0.44 and enhance release notes
2026-08-03 23:18:11 +08:00
leookun 0c9a07e018 chore(release): update version to 0.0.44 and enhance release notes
- Updated version number to 0.0.44 across all relevant files.
- Added support for cursor-cli in release notes.
2026-08-03 23:17:44 +08:00
68 changed files with 35618 additions and 12380 deletions
+12
View File
@@ -342,3 +342,15 @@ go run ./cmd/cursor-proxy-debugger
- `PendingInteraction`
- 同一 backend 进程内的 `RunSSE` 重连,要优先看 checkpoint / `pending_tool_calls` 里的 live pending
- backend 重启后,不要把 checkpoint 当持久恢复点;跨轮承接与持久恢复只看 `history/<conversationId>/state.json` + `history/<conversationId>/context.json`
### 5.1 checkpoint 投影必须幂等且只有一个事实源
- 把 checkpoint 当作 `state.json + context.json` 的纯投影,不要把它写成第二套语义历史。
- 不要创建或维护 `checkpoint.json`、checkpoint history、独立 checkpoint entry 序列等持久化事实源。
- 允许在当前 stream 内存中保留 latest checkpoint 供 retry/resume 使用;进程重启后必须能从唯一事实源重新投影。
- 对同一份 semantic history 重复投影时,要求 state、turn 顺序、blob ID 和 blob 内容在语义上完全一致;投影函数不得修改输入 history。
- 把重复发送视为同一快照的幂等覆盖,不要追加一条新的会话历史;内容寻址 blob 的重复写入必须可安全忽略。
-`turns` 投影为 UI 可恢复的完整结构,保留所有需要展示的 `ThinkingMessage``ToolCall` 和工具结果;不要为了模型 prompt 过滤而删除 UI step。
-`root_prompt_messages_json` 单独投影为模型 replay;只在这条投影上应用 provider/context 过滤,不能反向改变 `turns`
- 将工具完成结果合并回同一 `ToolCall`,保留开始态的 `args`、调用 ID 和开始时间,再补齐 `result` 与完成时间;不要制造协议不存在的独立 `ToolResult` step。
- 用 TDD 覆盖至少这些性质:重复投影相等、投影不修改 history、开始态字段在结果合并后仍存在、UI turns 保留思考/工具内容而模型 replay 仍遵守独立过滤规则。
+1
View File
@@ -15,6 +15,7 @@ server-go/log/
.cursor-local-assistant
.cursor-local-assistant-v2
.cursor-app-formatted/
proto/extensions-cursor-app/
ads-server-linux-amd64.tar
cmd/ads-server/*.db
cmd/ads-server/*.db-*
+9 -2
View File
@@ -13,8 +13,8 @@ tasks:
preconditions:
- sh: 'test -z "{{.PROTO_INPUT}}" || test -f "{{.PROTO_INPUT}}"'
msg: "PROTO_INPUT 指向的 Cursor 扩展 bundle 不存在。"
- sh: 'test -n "{{.PROTO_INPUT}}" || test -f ./proto/extensions-cursor-app/cursor-always-local/dist/main.js || test -f /Applications/Cursor.app/Contents/Resources/app/extensions/cursor-always-local/dist/main.js'
msg: "未找到 Cursor 扩展 bundle;请传入 PROTO_INPUT=/path/to/cursor-always-local/dist/main.js。"
- sh: 'test -n "{{.PROTO_INPUT}}" || test -f /Applications/Cursor.app/Contents/Resources/app/extensions/cursor-always-local/dist/main.js'
msg: "未找到已安装 Cursor 扩展 bundle;请传入 PROTO_INPUT=/path/to/cursor-always-local/dist/main.js。"
cmds:
- chmod +x ./proto/extract_extensions_proto.sh
- '{{if .PROTO_INPUT}}./proto/extract_extensions_proto.sh "{{.PROTO_INPUT}}"{{else}}./proto/extract_extensions_proto.sh{{end}}'
@@ -29,9 +29,16 @@ tasks:
- cp ./proto/from_extensions/aiserver_v1.proto ./proto/aiserver_v1.proto
- perl -0pi -e 's|option go_package = "react-admin/cursor-server/gen/agent/v1;agentv1";|option go_package = "cursor/gen/agentv1;agentv1";|' ./proto/agent_v1.proto
- perl -0pi -e 's|option go_package = "react-admin/cursor-server/gen/aiserver/v1;aiserverv1";|option go_package = "cursor/gen/aiserverv1;aiserverv1";|' ./proto/aiserver_v1.proto
- ./proto/check_proto_sync.sh
- rm -rf ./gen/agentv1 ./gen/aiserverv1
- task: generate:proto
check:proto:
summary: 检查根 proto 与扩展提取快照是否一致
dir: '{{.ROOT_DIR}}'
cmds:
- ./proto/check_proto_sync.sh
generate:proto:
summary: 生成 proto Go/Connect 代码
dir: '{{.ROOT_DIR}}'
+1 -1
View File
@@ -8,7 +8,7 @@ info:
description: "Cursor助手"
copyright: "© 2026, Cursor助手"
comments: "Cursor助手"
version: "0.0.43"
version: "0.0.45"
dev_mode:
root_path: .
+2 -2
View File
@@ -17,9 +17,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.0.43</string>
<string>0.0.45</string>
<key>CFBundleVersion</key>
<string>0.0.43</string>
<string>0.0.45</string>
<key>LSMinimumSystemVersion</key>
<string>12.0.0</string>
<key>LSUIElement</key>
+2 -2
View File
@@ -17,9 +17,9 @@
<key>CFBundlePackageType</key>
<string>APPL</string>
<key>CFBundleShortVersionString</key>
<string>0.0.43</string>
<string>0.0.45</string>
<key>CFBundleVersion</key>
<string>0.0.43</string>
<string>0.0.45</string>
<key>LSMinimumSystemVersion</key>
<string>12.0.0</string>
<key>LSUIElement</key>
+1 -1
View File
@@ -6,7 +6,7 @@
name: "Cursor助手"
arch: ${GOARCH}
platform: "linux"
version: "0.0.43"
version: "0.0.45"
section: "default"
priority: "extra"
maintainer: ${GIT_COMMITTER_NAME} <${GIT_COMMITTER_EMAIL}>
+2 -2
View File
@@ -1,10 +1,10 @@
{
"fixed": {
"file_version": "0.0.43"
"file_version": "0.0.45"
},
"info": {
"0000": {
"ProductVersion": "0.0.43",
"ProductVersion": "0.0.45",
"CompanyName": "Cursor助手",
"FileDescription": "Cursor助手",
"LegalCopyright": "© 2026, Cursor助手",
+1 -1
View File
@@ -14,7 +14,7 @@
!define INFO_PRODUCTNAME "Cursor助手"
!endif
!ifndef INFO_PRODUCTVERSION
!define INFO_PRODUCTVERSION "0.0.43"
!define INFO_PRODUCTVERSION "0.0.45"
!endif
!ifndef INFO_COPYRIGHT
!define INFO_COPYRIGHT "© 2026, Cursor助手"
+1 -1
View File
@@ -1,6 +1,6 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1" xmlns:asmv3="urn:schemas-microsoft-com:asm.v3">
<assemblyIdentity type="win32" name="com.cursor.wuxianxubei" version="0.0.43" processorArchitecture="*"/>
<assemblyIdentity type="win32" name="com.cursor.wuxianxubei" version="0.0.45" processorArchitecture="*"/>
<dependency>
<dependentAssembly>
<assemblyIdentity type="win32" name="Microsoft.Windows.Common-Controls" version="6.0.0.0" processorArchitecture="*" publicKeyToken="6595b64144ccf1df" language="*"/>
+3 -1
View File
@@ -2,7 +2,7 @@
[中文](README.md) | [English](README.en.md)
This standalone local HTTPS debugging proxy captures Cursor's `BidiAppend` and `RunSSE` traffic. It does not modify Cursor, the system proxy, or the installed client.
This standalone local HTTPS debugging proxy captures Cursor's `BidiAppend`, `RunSSE`, and Fork Chat traffic. It does not modify Cursor, the system proxy, or the installed client.
## Start
@@ -51,6 +51,8 @@ go build -o bin/cursor-proxy-debugger ./cmd/cursor-proxy-debugger
- HTTPS MITM is applied only to `target-host`; other CONNECT traffic passes through unchanged.
- `RunSSE` is decoded incrementally using the 5-byte Connect frame header and supports per-frame gzip decompression.
- `BidiAppendRequest.data` is further decoded as `agent.v1.AgentClientMessage`.
- Fork Chat's `ForkBackgroundComposer`, `NotifyConversationClone`, and `UploadConversationBlobs` traffic is decoded bidirectionally as protobuf JSON.
- Local Fork Chat is primarily client-side and only emits `NotifyConversationClone` and `UploadConversationBlobs` when clone blob synchronization is enabled and privacy settings allow it.
- Requests can be sorted chronologically or in reverse chronological order and filtered by protocol `request_id`.
- The UI supports Simplified Chinese and English, follows the browser language, and remembers a manual selection.
- Captured traffic is stored only in process memory and is discarded when the process exits.
+3 -1
View File
@@ -2,7 +2,7 @@
[中文](README.md) | [English](README.en.md)
这是一个独立运行的本地 HTTPS 调试代理,用于观察 Cursor 的 `BidiAppend``RunSSE` 通信。它不会修改 Cursor、系统代理或已安装客户端。
这是一个独立运行的本地 HTTPS 调试代理,用于观察 Cursor 的 `BidiAppend``RunSSE` 和 Fork Chat 相关通信。它不会修改 Cursor、系统代理或已安装客户端。
## 启动
@@ -51,6 +51,8 @@ go build -o bin/cursor-proxy-debugger ./cmd/cursor-proxy-debugger
- 仅对 `target-host` 执行 HTTPS MITM,其他 CONNECT 流量直接透传。
- `RunSSE` 按 5 字节 Connect 帧头增量拆帧,支持逐帧 gzip 解压。
- `BidiAppendRequest.data` 会继续解码为 `agent.v1.AgentClientMessage`
- Fork Chat 相关的 `ForkBackgroundComposer``NotifyConversationClone``UploadConversationBlobs` 会双向解码为 protobuf JSON。
- 本地 Fork Chat 主要在客户端完成,只有启用克隆 blob 同步且隐私设置允许时才会产生 `NotifyConversationClone``UploadConversationBlobs` 流量。
- 请求列表支持按抓包时间正序/倒序排列,并可按协议中的 `request_id` 过滤。
- 调试界面支持简体中文和英文,可跟随浏览器语言并记住手动选择。
- 抓包只保留在当前进程内存中;关闭进程后消失。
+64 -6
View File
@@ -20,6 +20,13 @@ import (
const maxConnectFrameBytes = 64 << 20
const (
bidiAppendPath = "/aiserver.v1.BidiService/BidiAppend"
forkBackgroundComposerPath = "/aiserver.v1.BackgroundComposerService/ForkBackgroundComposer"
notifyConversationClonePath = "/agent.v1.AgentService/NotifyConversationClone"
uploadConversationBlobsPath = "/agent.v1.AgentService/UploadConversationBlobs"
)
type connectFrameDecoder struct {
buffer []byte
messageType string
@@ -140,10 +147,9 @@ func decompressPayload(payload []byte, codec string) ([]byte, error) {
return decoded, nil
}
func decodeUnary(path string, payload []byte) (decodedJSON string, kind string, requestID string, err error) {
var message proto.Message
func decodeUnaryRequest(path string, payload []byte) (decodedJSON string, kind string, requestID string, err error) {
switch path {
case "/aiserver.v1.BidiService/BidiAppend":
case bidiAppendPath:
request := &aiserverv1.BidiAppendRequest{}
if err := proto.Unmarshal(payload, request); err != nil {
return "", "", "", err
@@ -165,13 +171,65 @@ func decodeUnary(path string, payload []byte) (decodedJSON string, kind string,
}
formatted, marshalErr := json.MarshalIndent(combined, "", " ")
return string(formatted), clientKind, requestID, marshalErr
default:
message = nil
}
message, kind := unaryRequestMessage(path)
if message == nil {
return "", "", "", nil
}
return marshalProtoJSON(message), activeOneofName(message), "", nil
if err := proto.Unmarshal(payload, message); err != nil {
return "", "", "", err
}
return marshalProtoJSON(message), kind, "", nil
}
func decodeUnaryResponse(path string, payload []byte) (decodedJSON string, kind string, err error) {
message, kind := unaryResponseMessage(path)
if message == nil {
return "", "", nil
}
if err := proto.Unmarshal(payload, message); err != nil {
return "", "", err
}
return marshalProtoJSON(message), kind, nil
}
func unaryRequestMessage(path string) (proto.Message, string) {
switch path {
case forkBackgroundComposerPath:
return &aiserverv1.ForkBackgroundComposerRequest{}, "fork_background_composer_request"
case notifyConversationClonePath:
return &agentv1.NotifyConversationCloneRequest{}, "notify_conversation_clone_request"
case uploadConversationBlobsPath:
return &agentv1.UploadConversationBlobsRequest{}, "upload_conversation_blobs_request"
default:
return nil, ""
}
}
func unaryResponseMessage(path string) (proto.Message, string) {
switch path {
case forkBackgroundComposerPath:
return &aiserverv1.ForkBackgroundComposerResponse{}, "fork_background_composer_response"
case notifyConversationClonePath:
return &agentv1.NotifyConversationCloneResponse{}, "notify_conversation_clone_response"
case uploadConversationBlobsPath:
return &agentv1.UploadConversationBlobsResponse{}, "upload_conversation_blobs_response"
default:
return nil, ""
}
}
func decodesUnaryRequest(path string) bool {
if path == bidiAppendPath {
return true
}
message, _ := unaryRequestMessage(path)
return message != nil
}
func decodesUnaryResponse(path string) bool {
message, _ := unaryResponseMessage(path)
return message != nil
}
func newMessage(messageType string) proto.Message {
+242
View File
@@ -0,0 +1,242 @@
package proxydebugger
import (
"bytes"
"compress/gzip"
"encoding/json"
"strings"
"testing"
"time"
"cursor/gen/agentv1"
"cursor/gen/aiserverv1"
"google.golang.org/protobuf/proto"
)
func TestDecodeForkTrafficRequests(t *testing.T) {
t.Parallel()
tests := []struct {
name string
path string
message proto.Message
kind string
contains []string
}{
{
name: "fork background composer",
path: forkBackgroundComposerPath,
message: &aiserverv1.ForkBackgroundComposerRequest{
SourceBcId: "bc-source",
Mode: aiserverv1.ForkBackgroundComposerMode_FORK_BACKGROUND_COMPOSER_MODE_CONVERSATION,
Name: proto.String("forked chat"),
TurnCount: proto.Uint32(4),
},
kind: "fork_background_composer_request",
contains: []string{`"source_bc_id":"bc-source"`, `"turn_count":4`},
},
{
name: "notify conversation clone",
path: notifyConversationClonePath,
message: &agentv1.NotifyConversationCloneRequest{
ConversationId: "new-conversation",
SourceConversationId: "source-conversation",
SourceRequestId: "source-request",
},
kind: "notify_conversation_clone_request",
contains: []string{`"conversation_id":"new-conversation"`, `"source_conversation_id":"source-conversation"`},
},
{
name: "upload conversation blobs",
path: uploadConversationBlobsPath,
message: &agentv1.UploadConversationBlobsRequest{
ConversationId: "new-conversation",
Blobs: []*agentv1.BlobEntry{{
Id: []byte{1, 2},
Value: []byte("blob-value"),
}},
ChunkIndex: 1,
TotalChunks: 2,
},
kind: "upload_conversation_blobs_request",
contains: []string{`"conversation_id":"new-conversation"`, `"total_chunks":2`, `"value":"YmxvYi12YWx1ZQ=="`},
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
payload, err := proto.Marshal(test.message)
if err != nil {
t.Fatal(err)
}
decoded, kind, requestID, err := decodeUnaryRequest(test.path, payload)
if err != nil {
t.Fatalf("decode request: %v", err)
}
if kind != test.kind {
t.Fatalf("kind = %q, want %q", kind, test.kind)
}
if requestID != "" {
t.Fatalf("request ID = %q, want empty", requestID)
}
compact := compactJSON(t, decoded)
for _, expected := range test.contains {
if !strings.Contains(compact, expected) {
t.Errorf("decoded JSON does not contain %q:\n%s", expected, decoded)
}
}
})
}
}
func TestDecodeForkTrafficResponses(t *testing.T) {
t.Parallel()
tests := []struct {
name string
path string
message proto.Message
kind string
contains string
}{
{
name: "fork background composer",
path: forkBackgroundComposerPath,
message: &aiserverv1.ForkBackgroundComposerResponse{
BcId: "bc-fork",
SourceBcId: "bc-source",
Mode: aiserverv1.ForkBackgroundComposerMode_FORK_BACKGROUND_COMPOSER_MODE_CONVERSATION,
},
kind: "fork_background_composer_response",
contains: `"bc_id":"bc-fork"`,
},
{
name: "notify conversation clone",
path: notifyConversationClonePath,
message: &agentv1.NotifyConversationCloneResponse{},
kind: "notify_conversation_clone_response",
contains: `{}`,
},
{
name: "upload conversation blobs",
path: uploadConversationBlobsPath,
message: &agentv1.UploadConversationBlobsResponse{},
kind: "upload_conversation_blobs_response",
contains: `{}`,
},
}
for _, test := range tests {
test := test
t.Run(test.name, func(t *testing.T) {
t.Parallel()
payload, err := proto.Marshal(test.message)
if err != nil {
t.Fatal(err)
}
decoded, kind, err := decodeUnaryResponse(test.path, payload)
if err != nil {
t.Fatalf("decode response: %v", err)
}
if kind != test.kind {
t.Fatalf("kind = %q, want %q", kind, test.kind)
}
if !strings.Contains(compactJSON(t, decoded), test.contains) {
t.Errorf("decoded JSON does not contain %q:\n%s", test.contains, decoded)
}
})
}
}
func TestFinishResponseBodyDecodesCompressedForkResponse(t *testing.T) {
t.Parallel()
payload, err := proto.Marshal(&aiserverv1.ForkBackgroundComposerResponse{
BcId: "bc-fork",
SourceBcId: "bc-source",
})
if err != nil {
t.Fatal(err)
}
var compressed bytes.Buffer
writer := gzip.NewWriter(&compressed)
if _, err := writer.Write(payload); err != nil {
t.Fatal(err)
}
if err := writer.Close(); err != nil {
t.Fatal(err)
}
server := &Server{store: newExchangeStore(1)}
server.store.create(&Exchange{
ExchangeSummary: ExchangeSummary{ID: "1", StartedAt: time.Now()},
})
server.finishResponseBody("1", forkBackgroundComposerPath, "gzip", compressed.Bytes(), int64(compressed.Len()), false, nil)
exchange, ok := server.store.get("1")
if !ok {
t.Fatal("exchange was not stored")
}
if exchange.ResponseKind != "fork_background_composer_response" {
t.Fatalf("response kind = %q", exchange.ResponseKind)
}
if !strings.Contains(compactJSON(t, exchange.Response.DecodedJSON), `"bc_id":"bc-fork"`) {
t.Fatalf("unexpected decoded response:\n%s", exchange.Response.DecodedJSON)
}
if exchange.Response.DecodeError != "" {
t.Fatalf("decode error = %q", exchange.Response.DecodeError)
}
}
func TestFinishRequestBodyDecodesCompressedCloneRequest(t *testing.T) {
t.Parallel()
payload, err := proto.Marshal(&agentv1.NotifyConversationCloneRequest{
ConversationId: "new-conversation",
SourceConversationId: "source-conversation",
SourceRequestId: "source-request",
})
if err != nil {
t.Fatal(err)
}
var compressed bytes.Buffer
writer := gzip.NewWriter(&compressed)
if _, err := writer.Write(payload); err != nil {
t.Fatal(err)
}
if err := writer.Close(); err != nil {
t.Fatal(err)
}
server := &Server{store: newExchangeStore(1)}
server.store.create(&Exchange{
ExchangeSummary: ExchangeSummary{ID: "1", StartedAt: time.Now()},
})
server.finishRequestBody("1", notifyConversationClonePath, "gzip", compressed.Bytes(), int64(compressed.Len()), false, nil)
exchange, ok := server.store.get("1")
if !ok {
t.Fatal("exchange was not stored")
}
if exchange.RequestKind != "notify_conversation_clone_request" {
t.Fatalf("request kind = %q", exchange.RequestKind)
}
if !strings.Contains(compactJSON(t, exchange.Request.DecodedJSON), `"source_conversation_id":"source-conversation"`) {
t.Fatalf("unexpected decoded request:\n%s", exchange.Request.DecodedJSON)
}
if exchange.Request.DecodeError != "" {
t.Fatalf("decode error = %q", exchange.Request.DecodeError)
}
}
func compactJSON(t *testing.T, value string) string {
t.Helper()
var compact bytes.Buffer
if err := json.Compact(&compact, []byte(value)); err != nil {
t.Fatalf("compact JSON: %v\n%s", err, value)
}
return compact.String()
}
+39 -13
View File
@@ -226,28 +226,29 @@ func (server *Server) captureResponse(response *http.Response, context *goproxy.
if id == "" || response == nil {
return response
}
path := ""
if response.Request != nil && response.Request.URL != nil {
path = response.Request.URL.Path
}
responseCodec := responseContentCodec(path, response.Header)
server.store.update(id, func(exchange *Exchange) {
exchange.Status = response.StatusCode
exchange.State = "streaming"
exchange.DurationMS = elapsedMS(exchange.StartedAt)
exchange.Response.Headers = sortedHeaders(response.Header)
exchange.Response.ContentType = response.Header.Get("Content-Type")
exchange.Response.ContentCodec = responseContentCodec(response.Header)
exchange.Response.ContentCodec = responseCodec
})
if response.Body == nil {
server.finishResponseBody(id, nil, 0, false, nil)
server.finishResponseBody(id, path, responseCodec, nil, 0, false, nil)
return response
}
path := ""
if response.Request != nil && response.Request.URL != nil {
path = response.Request.URL.Path
}
var frameDecoder *connectFrameDecoder
if path == "/agent.v1.AgentService/RunSSE" {
frameDecoder = newConnectFrameDecoder(
"agent.v1.AgentServerMessage",
response.Header.Get("Connect-Content-Encoding"),
responseCodec,
server.config.MaxFrames,
func(frame FrameView) { server.appendResponseFrame(id, frame) },
)
@@ -264,7 +265,7 @@ func (server *Server) captureResponse(response *http.Response, context *goproxy.
if frameDecoder != nil {
frameDecoder.Close()
}
server.finishResponseBody(id, captured, size, truncated, readErr)
server.finishResponseBody(id, path, responseCodec, captured, size, truncated, readErr)
},
)
return response
@@ -273,14 +274,14 @@ func (server *Server) captureResponse(response *http.Response, context *goproxy.
func (server *Server) finishRequestBody(id, path string, codec string, captured []byte, size int64, truncated bool, readErr error) {
decodePayload := captured
var contentDecodeErr error
if path == "/aiserver.v1.BidiService/BidiAppend" && truncated {
if decodesUnaryRequest(path) && truncated {
contentDecodeErr = errors.New("请求正文超过抓取上限,无法完整解码")
} else if path == "/aiserver.v1.BidiService/BidiAppend" && codec != "" && !strings.EqualFold(codec, "identity") {
} else if decodesUnaryRequest(path) && codec != "" && !strings.EqualFold(codec, "identity") {
decodePayload, contentDecodeErr = decompressPayload(captured, codec)
}
decodedJSON, kind, requestID, decodeErr := "", "", "", contentDecodeErr
if decodeErr == nil {
decodedJSON, kind, requestID, decodeErr = decodeUnary(path, decodePayload)
decodedJSON, kind, requestID, decodeErr = decodeUnaryRequest(path, decodePayload)
}
server.store.update(id, func(exchange *Exchange) {
exchange.RequestBytes = size
@@ -312,19 +313,44 @@ func requestContentCodec(path string, headers http.Header) string {
return strings.TrimSpace(headers.Get("Content-Encoding"))
}
func responseContentCodec(headers http.Header) string {
func responseContentCodec(path string, headers http.Header) string {
if path == "/agent.v1.AgentService/RunSSE" {
return strings.TrimSpace(headers.Get("Connect-Content-Encoding"))
}
if !decodesUnaryResponse(path) {
if codec := strings.TrimSpace(headers.Get("Connect-Content-Encoding")); codec != "" {
return codec
}
}
return strings.TrimSpace(headers.Get("Content-Encoding"))
}
func (server *Server) finishResponseBody(id string, captured []byte, size int64, truncated bool, readErr error) {
func (server *Server) finishResponseBody(id, path, codec string, captured []byte, size int64, truncated bool, readErr error) {
decodePayload := captured
var contentDecodeErr error
if decodesUnaryResponse(path) && truncated {
contentDecodeErr = errors.New("响应正文超过抓取上限,无法完整解码")
} else if decodesUnaryResponse(path) && codec != "" && !strings.EqualFold(codec, "identity") {
decodePayload, contentDecodeErr = decompressPayload(captured, codec)
}
decodedJSON, kind, decodeErr := "", "", contentDecodeErr
if decodeErr == nil {
decodedJSON, kind, decodeErr = decodeUnaryResponse(path, decodePayload)
}
server.store.update(id, func(exchange *Exchange) {
exchange.ResponseBytes = size
exchange.Response.Size = size
exchange.Response.RawHex = rawHex(captured)
exchange.Response.RawTruncated = truncated
if decodedJSON != "" {
exchange.Response.DecodedJSON = decodedJSON
}
if kind != "" {
exchange.ResponseKind = kind
}
if decodeErr != nil {
exchange.Response.DecodeError = decodeErr.Error()
}
exchange.DurationMS = elapsedMS(exchange.StartedAt)
exchange.State = "completed"
if readErr != nil && !errors.Is(readErr, io.EOF) {
+8
View File
@@ -138,6 +138,7 @@ function filteredExchanges() {
.filter((item) => {
if (state.endpoint === "runsse" && !item.path.toLowerCase().includes("runsse")) return false;
if (state.endpoint === "bidiappend" && !item.path.toLowerCase().includes("bidiappend")) return false;
if (state.endpoint === "fork" && !isForkTrafficPath(item.path)) return false;
if (requestId && !String(item.requestId || "").toLowerCase().includes(requestId)) return false;
if (!query) return true;
return [item.url, item.requestId, item.requestKind, item.responseKind, item.state, String(item.status)]
@@ -151,6 +152,13 @@ function filteredExchanges() {
});
}
function isForkTrafficPath(path) {
const normalized = String(path || "").toLowerCase();
return ["forkbackgroundcomposer", "notifyconversationclone", "uploadconversationblobs"].some((endpoint) =>
normalized.includes(endpoint),
);
}
function renderList() {
const exchanges = filteredExchanges();
elements.requestCount.textContent = t("count.requests", { count: exchanges.length });
+2
View File
@@ -22,6 +22,7 @@ const messages = {
"filters.requestIdPlaceholder": "按 Request ID 过滤",
"filters.endpoint": "接口过滤",
"filters.all": "全部",
"filters.fork": "Fork",
"filters.sort": "排序方向",
"filters.ascending": "正序",
"filters.descending": "倒序",
@@ -81,6 +82,7 @@ const messages = {
"filters.requestIdPlaceholder": "Filter by Request ID",
"filters.endpoint": "Endpoint filter",
"filters.all": "All",
"filters.fork": "Fork",
"filters.sort": "Sort order",
"filters.ascending": "Oldest first",
"filters.descending": "Newest first",
+1
View File
@@ -46,6 +46,7 @@
<button class="active" type="button" data-value="all" data-i18n="filters.all">全部</button>
<button type="button" data-value="runsse">RunSSE</button>
<button type="button" data-value="bidiappend">BidiAppend</button>
<button type="button" data-value="fork" data-i18n="filters.fork">Fork</button>
</div>
<div id="sort-order" class="segmented-control sort-control" role="group" aria-label="排序方向" data-i18n-aria-label="filters.sort">
<button type="button" data-value="asc" data-i18n="filters.ascending">正序</button>
+362
View File
@@ -0,0 +1,362 @@
<script setup>
import { autoUpdate, computePosition, flip, offset, shift, size } from "@floating-ui/dom";
import { computed, onBeforeUnmount, nextTick, ref, watch, watchPostEffect } from "vue";
const props = defineProps({
modelValue: {
type: Array,
default: () => [],
},
options: {
type: Array,
default: () => [],
},
placeholder: { type: String, default: "请选择" },
disabled: { type: Boolean, default: false },
ariaLabel: { type: String, default: "" },
summaryFormatter: { type: Function, default: null },
});
const emit = defineEmits(["update:modelValue", "change"]);
const rootRef = ref(null);
const buttonRef = ref(null);
const menuRef = ref(null);
const selectAllRef = ref(null);
const optionRefs = ref([]);
const isOpen = ref(false);
const menuStyle = ref({});
// -1 表示"全选"按钮,0..n-1 表示选项,共同组成一个可循环的键盘焦点环
const activeIndex = ref(-1);
const normalizedOptions = computed(() => props.options.map((option) => {
if (typeof option === "string") {
return { label: option, value: option };
}
return {
label: option?.label ?? option?.value ?? "",
value: option?.value ?? "",
icon: option?.icon ?? "",
};
}));
const selectedValues = computed(() => new Set(props.modelValue ?? []));
const allSelected = computed(() =>
normalizedOptions.value.length > 0
&& normalizedOptions.value.every((option) => selectedValues.value.has(option.value)),
);
const summaryLabel = computed(() => {
const count = selectedValues.value.size;
if (count === 0) {
return props.placeholder;
}
if (props.summaryFormatter) {
return props.summaryFormatter(count, normalizedOptions.value.length);
}
return `已选择 ${count}`;
});
function emitSelection(values) {
emit("update:modelValue", values);
emit("change", values);
}
function toggleOption(option) {
const next = normalizedOptions.value
.filter((item) => (item.value === option.value
? !selectedValues.value.has(item.value)
: selectedValues.value.has(item.value)))
.map((item) => item.value);
emitSelection(next);
}
function toggleSelectAll() {
if (allSelected.value) {
emitSelection([]);
return;
}
emitSelection(normalizedOptions.value.map((option) => option.value));
}
function setOptionRef(el, index) {
if (el) {
optionRefs.value[index] = el;
return;
}
delete optionRefs.value[index];
}
function focusActiveOption() {
nextTick(() => {
if (activeIndex.value < 0) {
selectAllRef.value?.focus();
return;
}
optionRefs.value[activeIndex.value]?.focus();
});
}
function moveActiveIndex(step) {
if (!isOpen.value) {
openMenu();
return;
}
const total = normalizedOptions.value.length;
if (total === 0) {
return;
}
// 焦点环长度为 total + 1(含全选),内部用 0..total 表示,再映射回 -1..total-1
const ringSize = total + 1;
const current = activeIndex.value + 1;
activeIndex.value = ((current + step + ringSize) % ringSize) - 1;
focusActiveOption();
}
function openMenu() {
if (props.disabled || isOpen.value) {
return;
}
isOpen.value = true;
const firstSelected = normalizedOptions.value.findIndex((option) => selectedValues.value.has(option.value));
activeIndex.value = firstSelected;
nextTick(() => {
updatePosition();
focusActiveOption();
});
}
function closeMenu({ restoreFocus = false } = {}) {
if (!isOpen.value) {
return;
}
isOpen.value = false;
activeIndex.value = -1;
optionRefs.value = [];
menuStyle.value = {};
if (restoreFocus) {
nextTick(() => buttonRef.value?.focus());
}
}
function toggleMenu() {
if (isOpen.value) {
closeMenu();
return;
}
openMenu();
}
function handleButtonKeydown(event) {
if (props.disabled) {
return;
}
switch (event.key) {
case "ArrowDown":
event.preventDefault();
moveActiveIndex(1);
break;
case "ArrowUp":
event.preventDefault();
moveActiveIndex(-1);
break;
case "Enter":
case " ":
event.preventDefault();
toggleMenu();
break;
case "Escape":
if (isOpen.value) {
event.preventDefault();
closeMenu();
}
break;
default:
break;
}
}
function handleOptionKeydown(event, option, index) {
switch (event.key) {
case "ArrowDown":
event.preventDefault();
activeIndex.value = index;
moveActiveIndex(1);
break;
case "ArrowUp":
event.preventDefault();
activeIndex.value = index;
moveActiveIndex(-1);
break;
case "Enter":
case " ":
event.preventDefault();
if (option) {
toggleOption(option);
break;
}
toggleSelectAll();
break;
case "Escape":
event.preventDefault();
closeMenu({ restoreFocus: true });
break;
case "Tab":
closeMenu();
break;
default:
break;
}
}
function handlePointerDown(event) {
if (rootRef.value?.contains(event.target) || menuRef.value?.contains(event.target)) {
return;
}
closeMenu();
}
function updatePosition() {
if (!buttonRef.value || !menuRef.value) {
return;
}
computePosition(buttonRef.value, menuRef.value, {
placement: "bottom-start",
middleware: [
offset(6),
flip({ padding: 12 }),
shift({ padding: 12 }),
size({
apply({ rects, elements, availableHeight }) {
Object.assign(elements.floating.style, {
minWidth: `${rects.reference.width}px`,
maxHeight: `${Math.max(availableHeight, 200)}px`,
});
},
padding: 12,
}),
],
}).then(({ x, y }) => {
menuStyle.value = {
left: `${x}px`,
top: `${y}px`,
};
});
}
watchPostEffect((cleanup) => {
if (!isOpen.value || !buttonRef.value || !menuRef.value) {
return;
}
const stopAutoUpdate = autoUpdate(buttonRef.value, menuRef.value, updatePosition);
cleanup(() => {
stopAutoUpdate();
});
});
watch(isOpen, (open) => {
if (open) {
document.addEventListener("pointerdown", handlePointerDown);
return;
}
document.removeEventListener("pointerdown", handlePointerDown);
});
watch(() => props.disabled, (disabled) => {
if (disabled) {
closeMenu();
}
});
onBeforeUnmount(() => {
document.removeEventListener("pointerdown", handlePointerDown);
});
</script>
<template>
<div ref="rootRef" class="relative">
<button
ref="buttonRef"
type="button"
:disabled="disabled"
class="flex h-9 w-full items-center justify-between gap-2 rounded-[6px] border border-[#3f3f3f] bg-[#232323] px-3 text-left text-sm text-[#e5e5e5] outline-none transition-colors focus:border-[#10AD5D] disabled:cursor-not-allowed disabled:opacity-60"
:aria-expanded="isOpen"
:aria-label="ariaLabel || undefined"
aria-haspopup="listbox"
@click="toggleMenu"
@keydown="handleButtonKeydown"
>
<span class="flex min-w-0 flex-1 items-center gap-2" :class="selectedValues.size ? 'text-[#e5e5e5]' : 'text-[#7b7b7b]'">
<span class="truncate">{{ summaryLabel }}</span>
</span>
<span
class="pointer-events-none center-row text-[#8f8f8f] transition-transform duration-200"
:class="isOpen ? 'rotate-180' : ''"
>
<span class="icon-[mdi--chevron-down] text-[18px]"></span>
</span>
</button>
</div>
<Teleport to="body">
<Transition
enter-active-class="transition duration-150 ease-out"
enter-from-class="translate-y-1 opacity-0"
enter-to-class="translate-y-0 opacity-100"
leave-active-class="transition duration-100 ease-in"
leave-from-class="translate-y-0 opacity-100"
leave-to-class="translate-y-1 opacity-0"
>
<div
v-if="isOpen"
ref="menuRef"
class="fixed z-[999] flex flex-col overflow-hidden rounded-[8px] border border-[#3f3f3f] bg-[#232323] p-1 shadow-[0_16px_30px_-12px_rgba(0,0,0,0.7)]"
:style="menuStyle"
>
<button
ref="selectAllRef"
type="button"
class="flex w-full items-center gap-2 rounded-[6px] px-3 py-2 text-left text-sm text-[#d4d4d4] outline-none transition-colors hover:bg-[#303030]"
:class="activeIndex === -1 ? 'bg-[#303030]' : ''"
@click="toggleSelectAll"
@mouseenter="activeIndex = -1"
@keydown="handleOptionKeydown($event, null, -1)"
>
<span :class="[allSelected ? 'icon-[mdi--checkbox-marked]' : 'icon-[mdi--checkbox-blank-outline]', 'text-[16px] shrink-0']"></span>
<span class="truncate">{{ allSelected ? "取消全选" : "全选" }}</span>
</button>
<ul role="listbox" aria-multiselectable="true" class="overflow-y-auto py-1">
<li v-for="(option, index) in normalizedOptions" :key="option.value">
<button
:ref="(el) => setOptionRef(el, index)"
type="button"
role="option"
class="flex w-full items-center gap-2 rounded-[6px] px-3 py-2 text-left text-sm outline-none transition-colors"
:class="[
selectedValues.has(option.value)
? 'bg-[#10AD5D]/15 text-[#10d06f]'
: 'text-[#e5e5e5] hover:bg-[#303030]',
activeIndex === index ? 'bg-[#303030]' : '',
]"
:aria-selected="selectedValues.has(option.value)"
tabindex="0"
@click="toggleOption(option)"
@mouseenter="activeIndex = index"
@keydown="handleOptionKeydown($event, option, index)"
>
<span
:class="[
selectedValues.has(option.value) ? 'icon-[mdi--checkbox-marked]' : 'icon-[mdi--checkbox-blank-outline]',
'text-[16px] shrink-0',
]"
></span>
<span v-if="option.icon" :class="[option.icon, 'text-[16px] shrink-0']" aria-hidden="true"></span>
<span class="truncate">{{ option.label }}</span>
</button>
</li>
</ul>
</div>
</Transition>
</Teleport>
</template>
File diff suppressed because it is too large Load Diff
+13 -1
View File
@@ -18,6 +18,7 @@
"15d124b200ddabed": "Maximum number of context tokens the model can accept in a single request. Leave blank to use the default.",
"185aebe19c77425d": "{0} must be a JSON object",
"18b7312022cd1840": "Start Service",
"1afed6a81a2512d2": "Select model",
"1baddde657dd2720": "Current outbound requests use system proxy",
"1bc77f5ab979f4c1": "Add Model Settings",
"1c631615c1d85c9e": "Log in to Cursor",
@@ -29,6 +30,7 @@
"281eb6d08c9960d0": "{0} thinking budget token must be a positive integer",
"28aeffc70ceb4267": "Change the display language for this interface. The setting takes effect immediately and is saved on this device.",
"2a24519398684ed5": "Visit Homepage",
"2c18d5e2d70b45db": "Model prefix",
"2cd0f3be8738a86c": "Cancel",
"2d706f7981b45a7b": "Local settings saved",
"2f9daa828907b93f": "Delete",
@@ -44,8 +46,10 @@
"37d23612f78a2e63": "Restart Now to Update",
"392d0dceb45998d3": "Extreme",
"393df9bb13ea4900": "Hit",
"3a5040b68abf75f9": "Select all",
"3ab8cc15939f3b5c": "Log out",
"3af7e5489e61ea51": "Refreshing",
"3b2e5f2fba1bcbc7": "Enter the API address and access key",
"3c2a9f9901109e75": "{0} type only supports OpenAI or Anthropic",
"3d13868593ae4eeb": "Interface Language",
"3d52574ce1500561": "Not connected",
@@ -69,6 +73,7 @@
"58c6b0935a7216da": "Failed to open contributor profile",
"593a972852ba0004": "Cursor Assistant | Permanently Free | Custom API",
"59a2195a01a8b35b": "{0} must be a valid JSON object",
"5a5c8318ef649672": "{0} selected",
"5aa8f5590c940829": "Non-cache Input: {0}",
"5beb1206c532729f": "Maximum number of tokens allowed in a single response. Leave blank to use the default.",
"5d1687a4a41883fd": "Stopping...",
@@ -95,8 +100,10 @@
"737225e2904673fc": "Estimated output tokens: {0}",
"7520bd50a5ee5471": "Stop testing {0}/{1}",
"753d8bb0da9913ce": "Duplication failed",
"75b5f4c68c79322c": "Select at least one model to save",
"774d6e1b7cb89751": "Default Definition",
"77c9e582e85583af": "Test failed",
"7923d007483ae04c": "No models to save",
"7a26bf794e9fb6bf": "Used only for display in the UI, so you can distinguish different models.",
"7b6187c41e88b70c": "Testing...",
"7bf8e2c07e084d09": "Model Editor",
@@ -106,15 +113,16 @@
"80296f4aa3f4543b": "Cache Read/Write",
"81123c56d5d880d0": "API Key",
"8139cb3dd11f5a67": "When enabled, the JSON object will override the final request headers. Duplicate headers are determined by this field, and values must be strings.",
"826c0e5a4407befa": "You can select multiple models. Only selected models will be saved, with one configuration generated for each model.",
"83be9cac28873059": "Cursor Control Plane Account",
"8672864e90417138": "Max",
"86df7ec743047234": "Service running",
"891bfee3bbe52d3c": "Enter a model ID",
"899add6275682210": "Uses 200000 by default when left blank",
"8a4ef3e48e4e8a5a": "Enabled",
"8c1935935600e336": "Model Test",
"8cbcf741e727dbf7": "Model Settings",
"8d1de152be6360ce": "Valid ratio: {0}",
"8e2dc7b0d2e8f6f8": "e.g. OpenAI - GPT-4.1",
"8f6f8d979c981ced": "Copied",
"8f8baf5d18dd0492": "When enabled, the JSON object will override the OpenAI request body. Duplicate fields are determined by this field. OpenAI service_tier supports auto, default, flex, scale, priority; priority can be used for high-priority/Fast scenarios.",
"8faa670b512b6b9b": "Open Model Settings",
@@ -160,6 +168,7 @@
"b571037dc396a00c": "Total request tokens include both prompt and model output.",
"b765005f69fa971f": "e.g. gpt-4.1",
"b76a22622020f849": "Select interface protocol endpoint. When selecting 'Custom Path', please enter the complete request URL in the API address bar (including the /chat/completions or /responses suffix). The system will automatically detect the protocol type based on the trailing segment.",
"b7ceef2fbfeb4a85": "e.g. GPT-5",
"b870928f8f9a24c4": "API Endpoint",
"b90a8ac9c488ce46": "Select language",
"ba3c66f90fd11725": "System proxy identified",
@@ -173,6 +182,7 @@
"c3d46b387eeadb23": "This only logs the Cursor account out of cursor-byok; it does not log out of the Cursor client. Continue?",
"c5af02060847d167": "Thinking effort for Anthropic adaptive thinking. Requests will consistently use the new thinking.type=adaptive.",
"c69f5bce63b9f14c": "Settings Folder",
"c72d5dc20cd27118": "{0} / {1} models selected",
"c8a52b66651d294c": "Failed to log out",
"c8c14507b2d37395": "Reasoning Effort",
"c98e118e0a43f078": "Model",
@@ -206,6 +216,7 @@
"e4c0daa3c4bea691": "Thanks to @aike0210 for contributing the Cursor control-plane account feature.",
"e53580f8031f13c0": "Complete login in the browser, then return to Cursor and reopen the plugin marketplace",
"e552c2accdbf5178": "Add Model",
"e6943d5cbfb863e0": "Fetching models...",
"e6faccfddce722e8": "Cache read tokens: {0}",
"e8a0a6053998ebfa": "Logged in",
"eaffd48cd2ea9f1a": "e.g. https://api.anthropic.com",
@@ -218,6 +229,7 @@
"f3a76d896853c1df": "Miss",
"f3fae6cccb9004b1": "Custom header name cannot be empty",
"f474a4108aba4c4c": "Stop Service",
"f4d4bae588c4c0ff": "Deselect all",
"f4f0ead1116b5b62": "Enable",
"f56c6c82203b33f6": "Notice",
"f61e03f047b786d5": "{0} max output tokens must be a positive integer",
+16 -4
View File
@@ -18,6 +18,7 @@
"15d124b200ddabed": "モデルが1回のリクエストで受け取れる最大コンテキスト Token 数。空欄の場合はデフォルト値を使用します。",
"185aebe19c77425d": "{0}はJSONオブジェクトである必要があります",
"18b7312022cd1840": "サービスを開始",
"1afed6a81a2512d2": "モデルを選択",
"1baddde657dd2720": "現在のアウトバウンドリクエストはシステムプロキシを使用しています",
"1bc77f5ab979f4c1": "モデル設定を追加",
"1c631615c1d85c9e": "Cursor にログイン",
@@ -29,6 +30,7 @@
"281eb6d08c9960d0": "{0} の思考予算 Token は正の整数である必要があります",
"28aeffc70ceb4267": "この画面の表示言語を切り替えます。設定はすぐに反映され、この端末に保存されます",
"2a24519398684ed5": "ホームページへ",
"2c18d5e2d70b45db": "モデルのプレフィックス",
"2cd0f3be8738a86c": "キャンセル",
"2d706f7981b45a7b": "ローカル設定を保存しました",
"2f9daa828907b93f": "削除",
@@ -44,8 +46,10 @@
"37d23612f78a2e63": "今すぐ再起動して更新",
"392d0dceb45998d3": "最高",
"393df9bb13ea4900": "ヒット",
"3a5040b68abf75f9": "すべて選択",
"3ab8cc15939f3b5c": "ログアウト",
"3af7e5489e61ea51": "更新中",
"3b2e5f2fba1bcbc7": "インターフェースのアドレスとアクセスキーを入力してください",
"3c2a9f9901109e75": "{0} のタイプは OpenAI または Anthropic のみサポートします",
"3d13868593ae4eeb": "表示言語",
"3d52574ce1500561": "未接続",
@@ -69,6 +73,7 @@
"58c6b0935a7216da": "コントリビューターのプロフィールを開けませんでした",
"593a972852ba0004": "Cursor アシスタント | 永久無料 | カスタム API",
"59a2195a01a8b35b": "{0}は有効なJSONオブジェクトである必要があります",
"5a5c8318ef649672": "{0}件を選択中",
"5aa8f5590c940829": "非キャッシュ入力:{0}",
"5beb1206c532729f": "1回の応答で生成できる最大 Token 数。空欄の場合はデフォルト値を使用します。",
"5d1687a4a41883fd": "停止中...",
@@ -95,9 +100,11 @@
"737225e2904673fc": "推定出力 Token: {0}",
"7520bd50a5ee5471": "テスト停止 {0}/{1}",
"753d8bb0da9913ce": "複製に失敗しました",
"75b5f4c68c79322c": "保存するモデルを1つ以上選択してください",
"774d6e1b7cb89751": "デフォルト定義",
"77c9e582e85583af": "テスト失敗",
"7a26bf794e9fb6bf": "UI 上の表示専用で、異なるモデルを見分けやすくします。",
"7923d007483ae04c": "保存できるモデルがありません",
"7a26bf794e9fb6bf": "UIでモデルを区別するための表示専用です。",
"7b6187c41e88b70c": "テスト中...",
"7bf8e2c07e084d09": "モデル編集",
"7df7641e5e741346": "キャッシュ読み取り / (キャッシュ読み取り + キャッシュ作成 + 非キャッシュ入力)",
@@ -106,15 +113,16 @@
"80296f4aa3f4543b": "キャッシュ読み書き",
"81123c56d5d880d0": "API キー",
"8139cb3dd11f5a67": "有効にすると、JSONオブジェクトが最終的なリクエストヘッダーを上書きします。同名のヘッダーはこの設定が優先され、値は文字列である必要があります。",
"826c0e5a4407befa": "複数のモデルを選択できます。保存されるのは選択したモデルだけで、モデルごとに1つの設定が作成されます。",
"83be9cac28873059": "Cursor コントロールプレーンアカウント",
"8672864e90417138": "最大",
"86df7ec743047234": "サービス稼働中",
"891bfee3bbe52d3c": "モデルIDを入力してください",
"899add6275682210": "空欄で 200000",
"8a4ef3e48e4e8a5a": "有効",
"8c1935935600e336": "モデルテスト",
"8cbcf741e727dbf7": "モデル設定",
"8d1de152be6360ce": "有効率: {0}",
"8e2dc7b0d2e8f6f8": "例: OpenAI - GPT-4.1",
"8f6f8d979c981ced": "コピーしました",
"8f8baf5d18dd0492": "有効にすると、JSONオブジェクトがOpenAIのリクエストボディを上書きします。同名のフィールドはこの設定が優先されます。OpenAIのservice_tierはauto、default、flex、scale、priorityをサポートしており、priorityは高優先度/Fastのシナリオで使用できます。",
"8faa670b512b6b9b": "モデル設定を開く",
@@ -122,8 +130,8 @@
"917b1c1f18d0276b": "保存中...",
"9196835e388d2550": "すべてテスト",
"91cba5c107a51892": "/ 異常",
"92059fe6cd713db4": "実際にサーバー送信されるモデル名です。例: gpt-4.1 または claude-sonnet。",
"93e08803675e378b": "モデル ID",
"92059fe6cd713db4": "サーバーに実際に送信されるモデル名。例: gpt-4.1claude-sonnet。",
"93e08803675e378b": "モデルID",
"93faf55cd25c8319": "このソフトウェアは完全に無料です。もし料金を請求された場合は、詐欺の可能性が高いです。\n著者のホームページ https://space.bilibili.com/311706663/upload/video にアクセスして、更新情報や利用方法などを確認してください。",
"942ff2d88baca0c6": "アップデートを確認中...",
"970388573a3c88c9": "キャッシュ読み取り:{0} × ${1}/1M = {2}",
@@ -160,6 +168,7 @@
"b571037dc396a00c": "総リクエスト Token には Prompt とモデル出力の両方が含まれます。",
"b765005f69fa971f": "例: gpt-4.1",
"b76a22622020f849": "インターフェースプロトコルのエンドポイントを選択します。「カスタムパス」を選択する場合は、APIアドレスバーに完全なリクエストURL/chat/completions または /responses のサフィックスを含む)を入力してください。システムは末尾 of セグメントに基づいてプロトコルタイプを自動的に判断します。",
"b7ceef2fbfeb4a85": "例: GPT-5",
"b870928f8f9a24c4": "APIエンドポイント",
"b90a8ac9c488ce46": "言語を選択",
"ba3c66f90fd11725": "システムプロキシを認識しました",
@@ -173,6 +182,7 @@
"c3d46b387eeadb23": "cursor-byok 内の Cursor アカウントからのみログアウトします。Cursor クライアントからはログアウトしません。続行しますか?",
"c5af02060847d167": "Anthropic adaptive thinkingの思考強度。リクエストは一貫して新しいthinking.type=adaptiveを使用します。",
"c69f5bce63b9f14c": "設定フォルダー",
"c72d5dc20cd27118": "{0} / {1} モデルを選択中",
"c8a52b66651d294c": "ログアウトに失敗しました",
"c8c14507b2d37395": "推論強度",
"c98e118e0a43f078": "モデル",
@@ -206,6 +216,7 @@
"e4c0daa3c4bea691": "Cursor コントロールプレーンアカウント機能への @aike0210 の貢献に感謝します。",
"e53580f8031f13c0": "ブラウザでログインを完了し、Cursor に戻ってプラグインマーケットを開き直してください",
"e552c2accdbf5178": "モデルを追加",
"e6943d5cbfb863e0": "モデルを取得中...",
"e6faccfddce722e8": "キャッシュ読込 Token: {0}",
"e8a0a6053998ebfa": "ログイン済み",
"eaffd48cd2ea9f1a": "例: https://api.anthropic.com",
@@ -218,6 +229,7 @@
"f3a76d896853c1df": "ミス",
"f3fae6cccb9004b1": "カスタムヘッダー名は空にできません",
"f474a4108aba4c4c": "サービスを停止",
"f4d4bae588c4c0ff": "すべて選択解除",
"f4f0ead1116b5b62": "有効化",
"f56c6c82203b33f6": "お知らせ",
"f61e03f047b786d5": "{0} の最大出力 Token は正の整数である必要があります",
+15 -3
View File
@@ -18,6 +18,7 @@
"15d124b200ddabed": "Максимальное число токенов контекста, которое модель может принять за один запрос. Оставьте поле пустым для значения по умолчанию.",
"185aebe19c77425d": "{0} должен быть объектом JSON",
"18b7312022cd1840": "Запустить сервис",
"1afed6a81a2512d2": "Выберите модель",
"1baddde657dd2720": "Исходящие запросы используют системный прокси",
"1bc77f5ab979f4c1": "Добавить настройки модели",
"1c631615c1d85c9e": "Войти в Cursor",
@@ -29,6 +30,7 @@
"281eb6d08c9960d0": "Бюджет токенов рассуждения {0} должен быть положительным целым числом",
"28aeffc70ceb4267": "Измените язык интерфейса. Настройка применяется сразу и сохраняется на этом устройстве.",
"2a24519398684ed5": "Перейти на домашнюю страницу",
"2c18d5e2d70b45db": "Префикс модели",
"2cd0f3be8738a86c": "Отмена",
"2d706f7981b45a7b": "Локальные настройки сохранены",
"2f9daa828907b93f": "Удалить",
@@ -44,8 +46,10 @@
"37d23612f78a2e63": "Перезапустить и обновить",
"392d0dceb45998d3": "Очень высокая",
"393df9bb13ea4900": "Попадание",
"3a5040b68abf75f9": "Выбрать все",
"3ab8cc15939f3b5c": "Выйти",
"3af7e5489e61ea51": "Обновление",
"3b2e5f2fba1bcbc7": "Введите адрес интерфейса и ключ доступа",
"3c2a9f9901109e75": "Тип {0} поддерживает только OpenAI или Anthropic",
"3d13868593ae4eeb": "Язык интерфейса",
"3d52574ce1500561": "Не подключено",
@@ -69,6 +73,7 @@
"58c6b0935a7216da": "Не удалось открыть профиль участника",
"593a972852ba0004": "Cursor Assistant | Всегда бесплатно | Пользовательский API",
"59a2195a01a8b35b": "{0} должен быть допустимым объектом JSON",
"5a5c8318ef649672": "Выбрано: {0}",
"5aa8f5590c940829": "Ввод без кеша: {0}",
"5beb1206c532729f": "Максимальное число токенов в одном ответе. Оставьте поле пустым для значения по умолчанию.",
"5d1687a4a41883fd": "Остановка...",
@@ -95,9 +100,11 @@
"737225e2904673fc": "Расчетные выходные токены: {0}",
"7520bd50a5ee5471": "Остановить проверку {0}/{1}",
"753d8bb0da9913ce": "Не удалось дублировать",
"75b5f4c68c79322c": "Выберите хотя бы одну модель для сохранения",
"774d6e1b7cb89751": "Стандартный расчет",
"77c9e582e85583af": "Проверка не пройдена",
"7a26bf794e9fb6bf": "Используется только для отображения в интерфейсе и помогает различать модели.",
"7923d007483ae04c": "Нет моделей для сохранения",
"7a26bf794e9fb6bf": "Используется только для отображения в интерфейсе, чтобы различать модели.",
"7b6187c41e88b70c": "Проверка...",
"7bf8e2c07e084d09": "Редактор модели",
"7df7641e5e741346": "Чтение кеша / (Чтение кеша + Создание кеша + Ввод без кеша)",
@@ -106,15 +113,16 @@
"80296f4aa3f4543b": "Чтение/запись кеша",
"81123c56d5d880d0": "Ключ API",
"8139cb3dd11f5a67": "Если включено, объект JSON переопределит итоговые заголовки запроса. При совпадении имен используются значения отсюда; все значения должны быть строками.",
"826c0e5a4407befa": "Можно выбрать несколько моделей. Будут сохранены только выбранные модели, для каждой будет создана отдельная конфигурация.",
"83be9cac28873059": "Аккаунт управляющего уровня Cursor",
"8672864e90417138": "Максимальная",
"86df7ec743047234": "Сервис запущен",
"891bfee3bbe52d3c": "Введите идентификатор модели",
"899add6275682210": "Если оставить пустым, используется 200000",
"8a4ef3e48e4e8a5a": "Включено",
"8c1935935600e336": "Проверка модели",
"8cbcf741e727dbf7": "Настройки модели",
"8d1de152be6360ce": "Доля успешных: {0}",
"8e2dc7b0d2e8f6f8": "например, OpenAI - GPT-4.1",
"8f6f8d979c981ced": "Скопировано",
"8f8baf5d18dd0492": "Если включено, объект JSON переопределит тело запроса OpenAI. При совпадении полей используются значения отсюда. OpenAI service_tier поддерживает auto, default, flex, scale и priority; priority можно использовать для сценариев с высоким приоритетом/Fast.",
"8faa670b512b6b9b": "Открыть настройки модели",
@@ -122,7 +130,7 @@
"917b1c1f18d0276b": "Сохранение...",
"9196835e388d2550": "Проверить все",
"91cba5c107a51892": "/ Ошибочные",
"92059fe6cd713db4": "Имя модели, которое фактически отправляется серверу, например gpt-4.1 или claude-sonnet.",
"92059fe6cd713db4": "Имя модели, фактически отправляемое серверу, например gpt-4.1 или claude-sonnet.",
"93e08803675e378b": "Идентификатор модели",
"93faf55cd25c8319": "Это программное обеспечение полностью бесплатно. Если с вас взяли плату, скорее всего, вас обманули.\\nПосетите страницу автора: https://space.bilibili.com/311706663/upload/video\\nТам публикуются обновления, руководства и другие материалы.",
"942ff2d88baca0c6": "Проверка обновлений...",
@@ -160,6 +168,7 @@
"b571037dc396a00c": "Общее число токенов запроса включает Prompt и вывод модели.",
"b765005f69fa971f": "например, gpt-4.1",
"b76a22622020f849": "Выберите конечную точку протокола. Для варианта «Пользовательский путь» укажите полный URL запроса в поле адреса API, включая суффикс /chat/completions или /responses. Тип протокола будет определен автоматически по последнему сегменту.",
"b7ceef2fbfeb4a85": "например, GPT-5",
"b870928f8f9a24c4": "Конечная точка API",
"b90a8ac9c488ce46": "Выберите язык",
"ba3c66f90fd11725": "Обнаружен системный прокси",
@@ -173,6 +182,7 @@
"c3d46b387eeadb23": "Будет выполнен выход только из аккаунта Cursor в cursor-byok. В клиенте Cursor вы останетесь в системе. Продолжить?",
"c5af02060847d167": "Интенсивность для адаптивных рассуждений Anthropic. В запросах всегда используется новый режим thinking.type=adaptive.",
"c69f5bce63b9f14c": "Папка настроек",
"c72d5dc20cd27118": "Выбрано моделей: {0} / {1}",
"c8a52b66651d294c": "Не удалось выйти",
"c8c14507b2d37395": "Интенсивность рассуждений",
"c98e118e0a43f078": "Модель",
@@ -206,6 +216,7 @@
"e4c0daa3c4bea691": "Спасибо @aike0210 за вклад в функцию аккаунта панели управления Cursor.",
"e53580f8031f13c0": "Завершите вход в браузере, затем вернитесь в Cursor и снова откройте магазин плагинов",
"e552c2accdbf5178": "Добавить модель",
"e6943d5cbfb863e0": "Получение моделей...",
"e6faccfddce722e8": "Токены чтения из кеша: {0}",
"e8a0a6053998ebfa": "Выполнен вход",
"eaffd48cd2ea9f1a": "например, https://api.anthropic.com",
@@ -218,6 +229,7 @@
"f3a76d896853c1df": "Промах",
"f3fae6cccb9004b1": "Имя пользовательского заголовка не может быть пустым",
"f474a4108aba4c4c": "Остановить сервис",
"f4d4bae588c4c0ff": "Снять выделение со всех",
"f4f0ead1116b5b62": "Включить",
"f56c6c82203b33f6": "Уведомление",
"f61e03f047b786d5": "Максимальное число выходных токенов {0} должно быть положительным целым числом",
+13 -1
View File
@@ -18,6 +18,7 @@
"15d124b200ddabed": "模型单次可接受的最大上下文 Token 数。留空时使用默认值。",
"185aebe19c77425d": "{0}必须是 JSON 对象",
"18b7312022cd1840": "启动服务",
"1afed6a81a2512d2": "选择模型",
"1baddde657dd2720": "当前出站请求使用系统代理",
"1bc77f5ab979f4c1": "新增模型配置",
"1c631615c1d85c9e": "登录 Cursor",
@@ -29,6 +30,7 @@
"281eb6d08c9960d0": "{0} 的思考预算 Token 必须为正整数",
"28aeffc70ceb4267": "切换当前界面显示语言,设置会立即生效并保存在本机",
"2a24519398684ed5": "访问主页",
"2c18d5e2d70b45db": "模型前缀",
"2cd0f3be8738a86c": "取消",
"2d706f7981b45a7b": "本地配置已保存",
"2f9daa828907b93f": "删除",
@@ -44,8 +46,10 @@
"37d23612f78a2e63": "立即重启更新",
"392d0dceb45998d3": "极高",
"393df9bb13ea4900": "命中",
"3a5040b68abf75f9": "全选",
"3ab8cc15939f3b5c": "退出登录",
"3af7e5489e61ea51": "刷新中",
"3b2e5f2fba1bcbc7": "请输入接口地址和访问密钥",
"3c2a9f9901109e75": "{0} 的类型仅支持 OpenAI 或 Anthropic",
"3d13868593ae4eeb": "界面语言",
"3d52574ce1500561": "未连接",
@@ -69,6 +73,7 @@
"58c6b0935a7216da": "打开贡献者主页失败",
"593a972852ba0004": "Cursor助手|永久免费|自定义API",
"59a2195a01a8b35b": "{0}必须是合法 JSON 对象",
"5a5c8318ef649672": "已选择 {0} 项",
"5aa8f5590c940829": "非缓存输入:{0}",
"5beb1206c532729f": "单次回复允许生成的最大 Token 数。留空时使用默认值。",
"5d1687a4a41883fd": "停止中...",
@@ -95,8 +100,10 @@
"737225e2904673fc": "输出推算:{0}",
"7520bd50a5ee5471": "停止测试 {0}/{1}",
"753d8bb0da9913ce": "复制失败",
"75b5f4c68c79322c": "请先选择要保存的模型",
"774d6e1b7cb89751": "默认口径",
"77c9e582e85583af": "测试失败",
"7923d007483ae04c": "没有可保存的模型",
"7a26bf794e9fb6bf": "仅用于界面展示,便于你区分不同模型。",
"7b6187c41e88b70c": "测试中...",
"7bf8e2c07e084d09": "模型编辑",
@@ -106,15 +113,16 @@
"80296f4aa3f4543b": "缓存读写",
"81123c56d5d880d0": "访问密钥",
"8139cb3dd11f5a67": "开启后会把 JSON 对象覆盖到最终请求头。同名请求头以这里为准,值必须是字符串。",
"826c0e5a4407befa": "可多选。保存时只会写入选中的模型,每个模型生成一条配置。",
"83be9cac28873059": "Cursor 控制面账号",
"8672864e90417138": "最高",
"86df7ec743047234": "服务运行中",
"891bfee3bbe52d3c": "请填写模型标识",
"899add6275682210": "留空时默认 200000",
"8a4ef3e48e4e8a5a": "已开启",
"8c1935935600e336": "模型测试",
"8cbcf741e727dbf7": "模型配置",
"8d1de152be6360ce": "有效占比:{0}",
"8e2dc7b0d2e8f6f8": "例如:OpenAI - GPT-4.1",
"8f6f8d979c981ced": "已复制",
"8f8baf5d18dd0492": "开启后会把 JSON 对象覆盖到 OpenAI 请求体。同名字段以这里为准。OpenAI service_tier 支持 auto、default、flex、scale、prioritypriority 可用于高优先级/Fast 类场景。",
"8faa670b512b6b9b": "打开模型配置",
@@ -160,6 +168,7 @@
"b571037dc396a00c": "总请求 Token 包含 Prompt 和模型输出。",
"b765005f69fa971f": "例如:gpt-4.1",
"b76a22622020f849": "选择接口协议端点。选“自定义路径”时,请在接口地址栏填写完整请求地址(含 /chat/completions 或 /responses 路径后缀),系统会根据末段自动判断协议形态。",
"b7ceef2fbfeb4a85": "例如:GPT-5",
"b870928f8f9a24c4": "接口端点",
"b90a8ac9c488ce46": "选择语言",
"ba3c66f90fd11725": "已识别系统代理",
@@ -173,6 +182,7 @@
"c3d46b387eeadb23": "只会退出 cursor-byok 中的 Cursor 账号,不会退出 Cursor 客户端。是否继续?",
"c5af02060847d167": "Anthropic adaptive thinking 的思考强度。请求会固定使用新版 thinking.type=adaptive。",
"c69f5bce63b9f14c": "设置文件夹",
"c72d5dc20cd27118": "已选择 {0} / {1} 个模型",
"c8a52b66651d294c": "退出登录失败",
"c8c14507b2d37395": "推理强度",
"c98e118e0a43f078": "模型",
@@ -206,6 +216,7 @@
"e4c0daa3c4bea691": "感谢 @aike0210 对 Cursor 控制面账号功能的贡献。",
"e53580f8031f13c0": "请在浏览器完成登录,完成后返回 Cursor 重新打开插件市场",
"e552c2accdbf5178": "新增模型",
"e6943d5cbfb863e0": "正在获取模型...",
"e6faccfddce722e8": "缓存读取:{0}",
"e8a0a6053998ebfa": "已经登录",
"eaffd48cd2ea9f1a": "例如:https://api.anthropic.com",
@@ -218,6 +229,7 @@
"f3a76d896853c1df": "未命中",
"f3fae6cccb9004b1": "自定义请求头名称不能为空",
"f474a4108aba4c4c": "关闭服务",
"f4d4bae588c4c0ff": "取消全选",
"f4f0ead1116b5b62": "启用",
"f56c6c82203b33f6": "提示",
"f61e03f047b786d5": "{0} 的最大输出 Token 必须为正整数",
+6
View File
@@ -161,3 +161,9 @@ export function getModelAdapterTestResults() {
Call.ByName(`${PROXY_SERVICE_NAME}.GetModelAdapterTestResults`),
);
}
export function fetchModelAdapterModels(payload) {
return withApiLogging("FetchModelAdapterModels", payload, () =>
Call.ByName(`${PROXY_SERVICE_NAME}.FetchModelAdapterModels`, payload),
);
}
+95
View File
@@ -17,6 +17,7 @@ import {
startProxyService,
stopProxyService,
testModelAdapter,
fetchModelAdapterModels,
} from "@/services/clientApi";
const APP_STATE_STORAGE_KEY = "cursor-client:runtime-state:v2";
@@ -1143,6 +1144,100 @@ export async function saveModelAdapterAt(index, adapter) {
};
}
export async function fetchAvailableModelIDs(payload) {
const result = await fetchModelAdapterModels(payload);
return asArray(result?.models)
.map((item) => asString(item))
.filter(Boolean);
}
function buildPrefixedModelDisplayName(prefix, modelID) {
const normalizedPrefix = asString(prefix) || "模型";
return `${normalizedPrefix}-${asString(modelID)}`;
}
export function buildModelAdaptersFromModelIDs(source, modelIDs, prefix) {
const base = normalizeModelAdapter(source);
const seen = new Set();
return asArray(modelIDs)
.map((item) => asString(item))
.filter((modelID) => {
if (!modelID || seen.has(modelID)) {
return false;
}
seen.add(modelID);
return true;
})
.map((modelID) => normalizeModelAdapter({
...base,
id: "",
modelID,
displayName: buildPrefixedModelDisplayName(prefix, modelID),
tooltipData: base.tooltipData || "备注",
}));
}
function findModelAdapterUpsertIndex(adapters, target) {
return adapters.findIndex((adapter) => {
const current = normalizeModelAdapter(adapter);
return current.type === target.type
&& normalizeBaseURL(current.baseURL) === normalizeBaseURL(target.baseURL)
&& current.apiKey === target.apiKey
&& current.modelID === target.modelID
&& current.displayName === target.displayName
&& (current.type !== "openai" || current.openAIEndpoint === target.openAIEndpoint);
});
}
export async function saveModelAdaptersFromModelIDs(source, modelIDs, prefix, selectedModelID = "") {
const generatedAdapters = buildModelAdaptersFromModelIDs(source, modelIDs, prefix);
if (generatedAdapters.length === 0) {
return { ok: false, error: "没有可保存的模型" };
}
const generatedError = validateModelAdapters(generatedAdapters);
if (generatedError) {
return { ok: false, error: generatedError };
}
const currentConfig = await loadPersistedUserConfig();
const nextAdapters = normalizeModelAdapters(currentConfig.modelAdapters);
const targetModelID = asString(selectedModelID) || generatedAdapters[0]?.modelID || "";
let selectedIndex = -1;
for (const adapter of generatedAdapters) {
const index = findModelAdapterUpsertIndex(nextAdapters, adapter);
if (index >= 0) {
nextAdapters.splice(index, 1, adapter);
if (selectedIndex < 0 && adapter.modelID === targetModelID) {
selectedIndex = index;
}
continue;
}
nextAdapters.push(adapter);
if (selectedIndex < 0 && adapter.modelID === targetModelID) {
selectedIndex = nextAdapters.length - 1;
}
}
const result = await persistConfigPayload(
{
...currentConfig,
modelAdapters: nextAdapters,
},
{ modelAdaptersOnly: true },
);
if (!result.ok) {
return result;
}
return {
...result,
index: selectedIndex,
adapter: selectedIndex >= 0 ? appState.modelAdapters[selectedIndex] ?? null : null,
count: generatedAdapters.length,
};
}
export async function deleteModelAdapterAt(index) {
const currentConfig = await loadPersistedUserConfig();
const nextAdapters = normalizeModelAdapters(currentConfig.modelAdapters);
+192 -29
View File
@@ -2,6 +2,7 @@
import Button from "@/components/ui/Button.vue";
import Input from "@/components/ui/Input.vue";
import ModelAdapterTestCard from "@/components/ModelAdapterTestCard.vue";
import MultiSelect from "@/components/ui/MultiSelect.vue";
import Select from "@/components/ui/Select.vue";
import Tooltip from "@/components/ui/Tooltip.vue";
import { getModelEditorContext } from "@/services/clientApi";
@@ -9,9 +10,11 @@ import {
ANTHROPIC_THINKING_EFFORT_DEFAULT,
appState,
buildModelAdapterTestRequestHash,
buildModelAdaptersFromModelIDs,
createEmptyModelAdapter,
CUSTOM_HEADERS_DEFAULT_JSON,
EXTRA_PARAMS_DEFAULT_JSON,
fetchAvailableModelIDs,
getModelAdapterTestResult,
getModelAdapterTestResultByID,
isModelAdapterTestResultStale,
@@ -22,11 +25,12 @@ import {
OPENAI_EXTRA_PARAMS_DEFAULT_JSON,
runModelAdapterTest,
saveModelAdapterAt,
saveModelAdaptersFromModelIDs,
toUserError,
validateModelAdapters,
} from "@/state/appState";
import { Window } from "@wailsio/runtime";
import { computed, onMounted, reactive, ref, watch } from "vue";
import { computed, onBeforeUnmount, onMounted, reactive, ref, watch } from "vue";
const modelTypeTabs = [
{ label: "OpenAI", value: "openai", icon: "icon-[bxl--openai]" },
@@ -61,6 +65,14 @@ const errorMessage = ref("");
const loading = ref(true);
const lastTestAdapterID = ref("");
const localTestFailure = ref("");
const modelPrefix = ref("");
const existingModelPrefixCleared = ref(false);
const availableModelIDs = ref([]);
const selectedModelIDs = ref([]);
const modelSelectionMode = ref("auto");
const modelListLoading = ref(false);
const modelListRequestSeq = ref(0);
let modelListDebounceTimer = 0;
function createOptionalPositiveIntegerModel(key) {
return computed({
@@ -80,14 +92,44 @@ const contextWindowTokensInput = createOptionalPositiveIntegerModel("contextWind
const interfacePlaceholder = computed(() =>
draft.type === "anthropic" ? "例如:https://api.anthropic.com" : "例如:https://api.openai.com/v1",
);
const currentRequestHash = computed(() => buildModelAdapterTestRequestHash(draft));
const directModelTestResult = computed(() => getModelAdapterTestResult(draft));
const modelOptions = computed(() => availableModelIDs.value.map((modelID) => ({
label: modelID,
value: modelID,
icon: "icon-[mdi--cube-outline]",
})));
const isManualModelInput = computed(() => modelSelectionMode.value === "manual");
const activeModelIDs = computed(() => (
isManualModelInput.value
? [String(draft.modelID || "").trim()].filter(Boolean)
: selectedModelIDs.value
));
const primaryModelID = computed(() => (
isManualModelInput.value
? String(draft.modelID || "").trim()
: selectedModelIDs.value.includes(draft.modelID) ? draft.modelID : selectedModelIDs.value[0] || ""
));
const selectedTestAdapter = computed(() => {
if (isManualModelInput.value) {
const modelID = primaryModelID.value;
return normalizeModelAdapter({
...draft,
modelID,
displayName: modelID,
});
}
const adapters = buildModelAdaptersFromModelIDs(draft, selectedModelIDs.value, modelPrefix.value);
return adapters.find((adapter) => adapter.modelID === primaryModelID.value)
?? adapters[0]
?? normalizeModelAdapter(draft);
});
const currentRequestHash = computed(() => buildModelAdapterTestRequestHash(selectedTestAdapter.value));
const directModelTestResult = computed(() => getModelAdapterTestResult(selectedTestAdapter.value));
const rememberedModelTestResult = computed(() =>
lastTestAdapterID.value ? getModelAdapterTestResultByID(lastTestAdapterID.value) : null,
);
const activeModelTestResult = computed(() => directModelTestResult.value || rememberedModelTestResult.value);
const modelTestResultStale = computed(() =>
isModelAdapterTestResultStale(draft, activeModelTestResult.value),
isModelAdapterTestResultStale(selectedTestAdapter.value, activeModelTestResult.value),
);
const isCurrentConfigTesting = computed(() => directModelTestResult.value?.status === "running");
const modelTestSummary = computed(() => {
@@ -125,7 +167,8 @@ function ensureAnthropicThinkingEffort() {
const fieldTips = {
displayName: "仅用于界面展示,便于你区分不同模型。",
modelID: "请求实际发送给服务端的模型名称,例如 gpt-4.1 或 claude-sonnet。",
modelID: "可多选。保存时只会写入选中的模型,每个模型生成一条配置。",
manualModelID: "请求实际发送给服务端的模型名称,例如 gpt-4.1 或 claude-sonnet。",
baseURL: "模型服务的 API 根地址,通常为兼容 OpenAI 或 Anthropic 的接口入口。",
apiKey: "调用该模型服务需要使用的访问密钥。",
contextWindowTokens: "模型单次可接受的最大上下文 Token 数。留空时使用默认值。",
@@ -146,6 +189,11 @@ async function loadContext() {
editorIndex.value = typeof ctx.index === "number" ? ctx.index : -1;
const parsed = JSON.parse(ctx.adapterJSON || "{}");
Object.assign(draft, normalizeModelAdapter(parsed));
if (draft.modelID) {
availableModelIDs.value = [draft.modelID];
selectedModelIDs.value = [draft.modelID];
}
modelPrefix.value = draft.displayName || "";
if (!draft.type) {
draft.type = "openai";
}
@@ -157,8 +205,81 @@ async function loadContext() {
}
}
function syncSelectionWithAvailable() {
const available = availableModelIDs.value;
const kept = selectedModelIDs.value.filter((modelID) => available.includes(modelID));
selectedModelIDs.value = kept;
draft.modelID = kept.includes(draft.modelID) ? draft.modelID : kept[0] || "";
}
function handleModelSelectionChange(values) {
selectedModelIDs.value = values;
draft.modelID = values.includes(draft.modelID) ? draft.modelID : values[0] || "";
}
async function refreshModelList() {
const baseURL = String(draft.baseURL || "").trim();
const apiKey = String(draft.apiKey || "").trim();
if (!baseURL || !apiKey || !draft.type) {
modelSelectionMode.value = "auto";
availableModelIDs.value = draft.modelID ? [draft.modelID] : [];
syncSelectionWithAvailable();
return [];
}
const requestSeq = modelListRequestSeq.value + 1;
modelListRequestSeq.value = requestSeq;
modelSelectionMode.value = "auto";
modelListLoading.value = true;
try {
const models = await fetchAvailableModelIDs({
type: draft.type,
baseURL,
apiKey,
customHeadersEnabled: draft.customHeadersEnabled,
customHeadersJSON: draft.customHeadersJSON,
});
if (requestSeq !== modelListRequestSeq.value) {
return availableModelIDs.value;
}
if (editorIndex.value >= 0 && !existingModelPrefixCleared.value) {
modelPrefix.value = "";
existingModelPrefixCleared.value = true;
}
modelSelectionMode.value = "auto";
availableModelIDs.value = models;
syncSelectionWithAvailable();
return models;
} catch (_error) {
if (requestSeq === modelListRequestSeq.value) {
modelSelectionMode.value = "manual";
availableModelIDs.value = [];
selectedModelIDs.value = [];
}
return availableModelIDs.value;
} finally {
if (requestSeq === modelListRequestSeq.value) {
modelListLoading.value = false;
}
}
}
async function persistDraft() {
const adapter = normalizeModelAdapter(draft);
const models = activeModelIDs.value;
if (models.length === 0) {
const error = isManualModelInput.value ? "请填写模型标识" : "请先选择要保存的模型";
errorMessage.value = error;
return { ok: false, error, adapter: null };
}
const selectedModelID = primaryModelID.value || models[0];
const adapter = normalizeModelAdapter({
...draft,
modelID: selectedModelID,
displayName: isManualModelInput.value
? String(modelPrefix.value || selectedModelID).trim()
: `${String(modelPrefix.value || "模型").trim()}-${selectedModelID}`,
});
const singleCheck = validateModelAdapters([adapter]);
if (singleCheck) {
@@ -166,7 +287,9 @@ async function persistDraft() {
return { ok: false, error: singleCheck, adapter: null };
}
const result = await saveModelAdapterAt(editorIndex.value, adapter);
const result = isManualModelInput.value
? await saveModelAdapterAt(editorIndex.value, adapter)
: await saveModelAdaptersFromModelIDs(adapter, models, modelPrefix.value, selectedModelID);
if (!result.ok) {
errorMessage.value = result.error;
return { ok: false, error: result.error, adapter: null };
@@ -177,12 +300,14 @@ async function persistDraft() {
}
if (result.adapter) {
Object.assign(draft, normalizeModelAdapter(result.adapter));
} else {
Object.assign(draft, adapter);
}
errorMessage.value = "";
return {
ok: true,
error: "",
adapter: result.adapter ? normalizeModelAdapter(result.adapter) : normalizeModelAdapter(draft),
adapter: result.adapter ? normalizeModelAdapter(result.adapter) : normalizeModelAdapter(adapter),
};
}
@@ -200,6 +325,10 @@ async function handleCancel() {
function handleModelTypeChange(type) {
draft.type = type;
modelSelectionMode.value = "auto";
availableModelIDs.value = [];
selectedModelIDs.value = [];
draft.modelID = "";
if (type === "openai" && !draft.openAIEndpoint) {
draft.openAIEndpoint = OPENAI_ENDPOINT_RESPONSES;
} else if (type === "anthropic") {
@@ -273,9 +402,32 @@ watch(
},
);
watch(
() => [draft.type, draft.baseURL, draft.apiKey, draft.customHeadersEnabled, draft.customHeadersJSON],
() => {
window.clearTimeout(modelListDebounceTimer);
const baseURL = String(draft.baseURL || "").trim();
const apiKey = String(draft.apiKey || "").trim();
if (!baseURL || !apiKey) {
modelSelectionMode.value = "auto";
modelListLoading.value = false;
availableModelIDs.value = draft.modelID ? [draft.modelID] : [];
syncSelectionWithAvailable();
return;
}
modelListDebounceTimer = window.setTimeout(() => {
void refreshModelList();
}, 600);
},
);
onMounted(async () => {
await loadContext();
});
onBeforeUnmount(() => {
window.clearTimeout(modelListDebounceTimer);
});
</script>
<template>
@@ -318,26 +470,13 @@ onMounted(async () => {
<div class="grid grid-cols-1 gap-3 md:grid-cols-2">
<label class="flex flex-col gap-1">
<span class="center-row justify-start gap-1.5 text-sm text-[#d4d4d4]">
<Tooltip :content="fieldTips.displayName" />
<span>显示名称</span>
<Tooltip :content="fieldTips.baseURL" />
<span>接口地址</span>
</span>
<input
v-model="draft.displayName"
v-model="draft.baseURL"
type="text"
placeholder="例如:OpenAI - GPT-4.1"
class="h-9 rounded-[6px] border border-[#3f3f3f] bg-[#232323] px-3 text-sm text-[#e5e5e5] outline-none focus:border-[#10AD5D]"
/>
</label>
<label class="flex flex-col gap-1">
<span class="center-row justify-start gap-1.5 text-sm text-[#d4d4d4]">
<Tooltip :content="fieldTips.modelID" />
<span>模型标识</span>
</span>
<input
v-model="draft.modelID"
type="text"
placeholder="例如:gpt-4.1"
:placeholder="interfacePlaceholder"
class="h-9 rounded-[6px] border border-[#3f3f3f] bg-[#232323] px-3 text-sm text-[#e5e5e5] outline-none focus:border-[#10AD5D]"
/>
</label>
@@ -358,17 +497,41 @@ onMounted(async () => {
<label class="flex flex-col gap-1">
<span class="center-row justify-start gap-1.5 text-sm text-[#d4d4d4]">
<Tooltip :content="fieldTips.baseURL" />
<span>接口地址</span>
<Tooltip :content="isManualModelInput ? fieldTips.displayName : fieldTips.modelID" />
<span>{{ isManualModelInput ? "显示名称" : "模型前缀" }}</span>
</span>
<input
v-model="draft.baseURL"
v-model="modelPrefix"
type="text"
:placeholder="interfacePlaceholder"
placeholder="例如:GPT-5"
class="h-9 rounded-[6px] border border-[#3f3f3f] bg-[#232323] px-3 text-sm text-[#e5e5e5] outline-none focus:border-[#10AD5D]"
/>
</label>
<div class="flex flex-col gap-1">
<span class="center-row justify-start gap-1.5 text-sm text-[#d4d4d4]">
<Tooltip :content="isManualModelInput ? fieldTips.manualModelID : fieldTips.modelID" />
<span>{{ isManualModelInput ? "模型标识" : "选择模型" }}</span>
</span>
<input
v-if="isManualModelInput"
v-model="draft.modelID"
type="text"
placeholder="例如:gpt-4.1"
class="h-9 rounded-[6px] border border-[#3f3f3f] bg-[#232323] px-3 text-sm text-[#e5e5e5] outline-none focus:border-[#10AD5D]"
/>
<MultiSelect
v-else
:model-value="selectedModelIDs"
:options="modelOptions"
:disabled="modelListLoading || modelOptions.length === 0"
:placeholder="modelListLoading ? '正在获取模型...' : '请输入接口地址和访问密钥'"
:summary-formatter="(count, total) => `已选择 ${count} / ${total} 个模型`"
aria-label="选择模型"
@update:model-value="handleModelSelectionChange"
/>
</div>
<label class="flex flex-col gap-1">
<span class="center-row justify-start gap-1.5 text-sm text-[#d4d4d4]">
<Tooltip :content="fieldTips.contextWindowTokens" />
+15
View File
@@ -8,7 +8,9 @@ import (
"encoding/pem"
"io/fs"
"net"
"os"
goruntime "runtime"
"strconv"
"strings"
"time"
@@ -37,6 +39,8 @@ const (
appName = "Cursor助手"
// adRefreshInterval 表示后台广告拉取间隔。
adRefreshInterval = 3 * time.Minute
// disableWebViewSandboxEnv allows affected VDI users to opt out of the WebView2 sandbox.
disableWebViewSandboxEnv = "CURSOR_BYOK_DISABLE_WEBVIEW_SANDBOX"
)
// EmbeddedResources 定义了当前模块中的 EmbeddedResources 类型。
@@ -134,6 +138,9 @@ func Run(resources EmbeddedResources) error {
Assets: application.AssetOptions{
Handler: application.AssetFileServerFS(resources.Assets),
},
Windows: application.WindowsOptions{
AdditionalBrowserArgs: windowsAdditionalBrowserArgs(),
},
Mac: application.MacOptions{
ActivationPolicy: application.ActivationPolicyAccessory,
ApplicationShouldTerminateAfterLastWindowClosed: false,
@@ -415,6 +422,14 @@ func Run(resources EmbeddedResources) error {
return app.Run()
}
func windowsAdditionalBrowserArgs() []string {
disableSandbox, err := strconv.ParseBool(strings.TrimSpace(os.Getenv(disableWebViewSandboxEnv)))
if err != nil || !disableSandbox {
return nil
}
return []string{"--no-sandbox"}
}
func browserReachableLoopbackBaseURL(listenAddr string) string {
host, port, err := net.SplitHostPort(strings.TrimSpace(listenAddr))
if err != nil || strings.TrimSpace(port) == "" {
+29
View File
@@ -0,0 +1,29 @@
package app
import (
"reflect"
"testing"
)
func TestWindowsAdditionalBrowserArgs(t *testing.T) {
tests := []struct {
name string
env string
want []string
}{
{name: "unset"},
{name: "enabled with one", env: "1", want: []string{"--no-sandbox"}},
{name: "enabled with true", env: " true ", want: []string{"--no-sandbox"}},
{name: "disabled", env: "false"},
{name: "invalid", env: "yes"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Setenv(disableWebViewSandboxEnv, tt.env)
if got := windowsAdditionalBrowserArgs(); !reflect.DeepEqual(got, tt.want) {
t.Fatalf("windowsAdditionalBrowserArgs() = %v, want %v", got, tt.want)
}
})
}
}
-383
View File
@@ -1,383 +0,0 @@
package forwarder
import (
"encoding/hex"
"fmt"
"log"
"strings"
"time"
"google.golang.org/protobuf/proto"
"cursor/gen/agentv1"
)
const (
checkpointBlobWriteTimeout = 10 * time.Second
checkpointBlobCacheIdleTTL = 6 * time.Hour
checkpointBlobCacheMaxConversations = 256
)
type checkpointBlobCacheEntry struct {
Confirmed map[string]struct{}
LastAccess time.Time
}
func checkpointBlobKey(id []byte) string {
return string(id)
}
func checkpointBlobHex(key string) string {
return hex.EncodeToString([]byte(key))
}
func (service *Service) confirmedCheckpointBlob(conversationID string, key string) bool {
if service == nil || key == "" {
return false
}
service.checkpointBlobMu.Lock()
defer service.checkpointBlobMu.Unlock()
conversationID = strings.TrimSpace(conversationID)
entry := service.checkpointBlobs[conversationID]
if entry == nil {
return false
}
entry.LastAccess = time.Now().UTC()
_, ok := entry.Confirmed[key]
return ok
}
func (service *Service) confirmCheckpointBlob(conversationID string, key string) {
if service == nil || key == "" {
return
}
service.checkpointBlobMu.Lock()
defer service.checkpointBlobMu.Unlock()
if service.checkpointBlobs == nil {
service.checkpointBlobs = make(map[string]*checkpointBlobCacheEntry)
}
conversationID = strings.TrimSpace(conversationID)
now := time.Now().UTC()
entry := service.checkpointBlobs[conversationID]
if entry == nil {
entry = &checkpointBlobCacheEntry{Confirmed: make(map[string]struct{})}
service.checkpointBlobs[conversationID] = entry
}
entry.Confirmed[key] = struct{}{}
entry.LastAccess = now
service.pruneCheckpointBlobCacheLocked(now)
}
func (service *Service) pruneCheckpointBlobCacheLocked(now time.Time) {
if service == nil || len(service.checkpointBlobs) == 0 {
return
}
cutoff := now.Add(-checkpointBlobCacheIdleTTL)
for conversationID, entry := range service.checkpointBlobs {
if entry == nil || entry.LastAccess.Before(cutoff) {
delete(service.checkpointBlobs, conversationID)
}
}
for len(service.checkpointBlobs) > checkpointBlobCacheMaxConversations {
oldestConversationID := ""
oldestAccess := now
for conversationID, entry := range service.checkpointBlobs {
if entry == nil || oldestConversationID == "" || entry.LastAccess.Before(oldestAccess) {
oldestConversationID = conversationID
if entry != nil {
oldestAccess = entry.LastAccess
}
}
}
if oldestConversationID == "" {
return
}
delete(service.checkpointBlobs, oldestConversationID)
}
}
func checkpointCompletionAction(completion *pendingTurnCompletion) checkpointTerminalAction {
if completion == nil {
return checkpointTerminalAction{kind: checkpointTerminalActionNone}
}
return checkpointTerminalAction{
kind: checkpointTerminalActionComplete,
completion: *clonePendingTurnCompletion(completion),
}
}
func checkpointCancellationAction(message string) checkpointTerminalAction {
return checkpointTerminalAction{
kind: checkpointTerminalActionCancel,
cancelMessage: firstNonEmpty(strings.TrimSpace(message), "[canceled] User aborted request"),
}
}
func mergeCheckpointTerminalAction(current checkpointTerminalAction, incoming checkpointTerminalAction) checkpointTerminalAction {
switch {
case incoming.kind == checkpointTerminalActionCancel:
return incoming
case current.kind == checkpointTerminalActionCancel:
return current
case incoming.kind == checkpointTerminalActionComplete:
return incoming
default:
return current
}
}
func (action checkpointTerminalAction) completionValue() *pendingTurnCompletion {
if action.kind != checkpointTerminalActionComplete {
return nil
}
return clonePendingTurnCompletion(&action.completion)
}
func (service *Service) queueCheckpointProjection(stream *ActiveStream, projection *CheckpointProjection, terminalAction checkpointTerminalAction) error {
if service == nil || stream == nil || projection == nil || projection.State == nil {
return nil
}
state, ok := proto.Clone(projection.State).(*agentv1.ConversationStateStructure)
if !ok || state == nil {
return fmt.Errorf("clone checkpoint state")
}
stream.mu.Lock()
if stream.PendingCheckpointBlobWrites == nil {
stream.PendingCheckpointBlobWrites = make(map[uint32]pendingCheckpointBlobWrite)
}
if stream.PendingCheckpointBlobRequests == nil {
stream.PendingCheckpointBlobRequests = make(map[string]uint32)
}
stream.NextCheckpointRevision++
if stream.NextCheckpointRevision == 0 {
stream.NextCheckpointRevision++
}
revision := stream.NextCheckpointRevision
if stream.PendingCheckpoint != nil {
terminalAction = mergeCheckpointTerminalAction(stream.PendingCheckpoint.TerminalAction, terminalAction)
}
required := make(map[string]struct{}, len(projection.Blobs))
toWrite := make([]struct {
requestID uint32
blob CheckpointBlob
}, 0, len(projection.Blobs))
for _, blob := range projection.Blobs {
key := checkpointBlobKey(blob.ID)
if key == "" {
continue
}
required[key] = struct{}{}
if service.confirmedCheckpointBlob(stream.ConversationID, key) {
continue
}
if _, pending := stream.PendingCheckpointBlobRequests[key]; pending {
continue
}
stream.NextCheckpointBlobRequestID++
if stream.NextCheckpointBlobRequestID == 0 {
stream.NextCheckpointBlobRequestID++
}
requestID := stream.NextCheckpointBlobRequestID
stream.PendingCheckpointBlobWrites[requestID] = pendingCheckpointBlobWrite{
Key: key,
Revision: revision,
}
stream.PendingCheckpointBlobRequests[key] = requestID
toWrite = append(toWrite, struct {
requestID uint32
blob CheckpointBlob
}{requestID: requestID, blob: blob})
}
stream.PendingCheckpoint = &pendingCheckpointPublish{
Revision: revision,
State: state,
Required: required,
TerminalAction: terminalAction,
}
if terminalAction.kind != checkpointTerminalActionNone {
stream.Phase = TurnPhaseCheckpointing
}
for requestID, write := range stream.PendingCheckpointBlobWrites {
if _, stillRequired := required[write.Key]; stillRequired {
continue
}
delete(stream.PendingCheckpointBlobWrites, requestID)
delete(stream.PendingCheckpointBlobRequests, write.Key)
}
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
for _, item := range toWrite {
if err := service.broker.Publish(stream.RequestID, StreamEvent{
Message: buildSetCheckpointBlobMessage(item.requestID, item.blob),
}); err != nil {
service.discardPendingCheckpoint(stream, fmt.Errorf("publish checkpoint blob write: %w", err))
return err
}
}
if len(toWrite) > 0 {
service.scheduleStreamTimer(
stream,
providerTimerKey(streamTimerCheckpointBlobs, ""),
checkpointBlobWriteTimeout,
streamTimerCheckpointBlobs,
"",
0,
"checkpoint blob write timeout",
)
}
return service.publishReadyCheckpoint(stream)
}
func clonePendingTurnCompletion(completion *pendingTurnCompletion) *pendingTurnCompletion {
if completion == nil {
return nil
}
cloned := *completion
return &cloned
}
func (service *Service) handleCheckpointBlobResult(stream *ActiveStream, message *agentv1.KvClientMessage) error {
if service == nil || stream == nil || message == nil {
return nil
}
result := message.GetSetBlobResult()
if result == nil {
return nil
}
stream.mu.Lock()
write, ok := stream.PendingCheckpointBlobWrites[message.GetId()]
pendingRequiresBlob := false
if ok {
delete(stream.PendingCheckpointBlobWrites, message.GetId())
delete(stream.PendingCheckpointBlobRequests, write.Key)
if stream.PendingCheckpoint != nil {
_, pendingRequiresBlob = stream.PendingCheckpoint.Required[write.Key]
}
}
conversationID := stream.ConversationID
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
if !ok {
return nil
}
if result.GetError() != nil {
if !pendingRequiresBlob {
return service.publishReadyCheckpoint(stream)
}
return service.abandonPendingCheckpoint(stream, fmt.Errorf(
"write checkpoint blob %s: %s",
checkpointBlobHex(write.Key),
firstNonEmpty(result.GetError().GetMessage(), "client blob store rejected write"),
))
}
service.confirmCheckpointBlob(conversationID, write.Key)
return service.publishReadyCheckpoint(stream)
}
func (service *Service) publishReadyCheckpoint(stream *ActiveStream) error {
if service == nil || stream == nil {
return nil
}
stream.mu.Lock()
pending := stream.PendingCheckpoint
if pending == nil {
stream.mu.Unlock()
return nil
}
for key := range pending.Required {
if !service.confirmedCheckpointBlob(stream.ConversationID, key) {
stream.mu.Unlock()
return nil
}
}
stream.PendingCheckpoint = nil
state := pending.State
terminalAction := pending.TerminalAction
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
clearStreamTimer(stream, providerTimerKey(streamTimerCheckpointBlobs, ""))
if err := service.broker.Publish(stream.RequestID, StreamEvent{Message: buildCheckpointMessage(state)}); err != nil {
return err
}
switch terminalAction.kind {
case checkpointTerminalActionComplete:
if completion := terminalAction.completionValue(); completion != nil {
return service.finishSuccessfulTurnAfterCheckpoint(stream, *completion)
}
case checkpointTerminalActionCancel:
return service.finishCanceledTurnAfterCheckpoint(stream, terminalAction.cancelMessage)
}
return nil
}
func (service *Service) discardPendingCheckpoint(stream *ActiveStream, cause error) {
if service == nil || stream == nil {
return
}
stream.mu.Lock()
stream.PendingCheckpoint = nil
stream.PendingCheckpointBlobWrites = make(map[uint32]pendingCheckpointBlobWrite)
stream.PendingCheckpointBlobRequests = make(map[string]uint32)
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
clearStreamTimer(stream, providerTimerKey(streamTimerCheckpointBlobs, ""))
if cause != nil {
log.Printf("forwarder pending checkpoint discarded request_id=%s conversation_id=%s err=%v", stream.RequestID, stream.ConversationID, cause)
}
}
func (service *Service) abandonPendingCheckpoint(stream *ActiveStream, cause error) error {
if service == nil || stream == nil {
return nil
}
stream.mu.Lock()
pending := stream.PendingCheckpoint
stream.PendingCheckpoint = nil
stream.PendingCheckpointBlobWrites = make(map[uint32]pendingCheckpointBlobWrite)
stream.PendingCheckpointBlobRequests = make(map[string]uint32)
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
clearStreamTimer(stream, providerTimerKey(streamTimerCheckpointBlobs, ""))
if cause != nil {
log.Printf("forwarder checkpoint blob sync abandoned request_id=%s conversation_id=%s err=%v", stream.RequestID, stream.ConversationID, cause)
}
if pending != nil {
return service.failTerminalCheckpointSync(stream, cause)
}
return nil
}
func (service *Service) finishCanceledTurnAfterCheckpoint(stream *ActiveStream, message string) error {
if stream == nil {
return nil
}
service.setTurnPhase(stream, TurnPhaseCanceled)
return service.broker.Cancel(stream.RequestID, firstNonEmpty(strings.TrimSpace(message), "[canceled] User aborted request"))
}
func (service *Service) failTerminalCheckpointSync(stream *ActiveStream, cause error) error {
if stream == nil {
return nil
}
message := "checkpoint synchronization failed"
if cause != nil && strings.TrimSpace(cause.Error()) != "" {
message = strings.TrimSpace(cause.Error())
}
service.setTurnPhase(stream, TurnPhaseFailed)
return service.broker.Fail(stream.RequestID, "checkpoint_sync_error", message)
}
func (service *Service) handleCheckpointBlobTimeout(stream *ActiveStream) error {
if stream == nil {
return nil
}
stream.mu.Lock()
pendingCount := len(stream.PendingCheckpointBlobWrites)
stream.mu.Unlock()
if pendingCount == 0 {
return service.publishReadyCheckpoint(stream)
}
return service.abandonPendingCheckpoint(stream, fmt.Errorf("%d checkpoint blob writes timed out", pendingCount))
}
@@ -1,546 +0,0 @@
package forwarder
import (
"os"
"path/filepath"
"testing"
"cursor/gen/agentv1"
)
func TestCheckpointBlobSyncPublishesCheckpointAfterAllWrites(t *testing.T) {
service, stream := testCheckpointBlobService(t)
projection, err := service.projector.ProjectCheckpointProjection(testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "hello"),
newAssistantTextEntry(1, "request-1", "hi", "", ""),
}))
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
if err := service.queueCheckpointProjection(stream, projection, checkpointTerminalAction{kind: checkpointTerminalActionNone}); err != nil {
t.Fatalf("queueCheckpointProjection() error = %v", err)
}
events, err := service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil {
t.Fatalf("ReadFromCursor() error = %v", err)
}
if len(events) != len(projection.Blobs) {
t.Fatalf("events before ACK = %d, want %d blob writes", len(events), len(projection.Blobs))
}
for _, event := range events {
if event.Message.GetKvServerMessage().GetSetBlobArgs() == nil {
t.Fatalf("event before ACK = %#v, want set_blob_args", event.Message)
}
}
for index, event := range events {
requestID := event.Message.GetKvServerMessage().GetId()
if err := service.handleCheckpointBlobResult(stream, &agentv1.KvClientMessage{
Id: requestID,
Message: &agentv1.KvClientMessage_SetBlobResult{
SetBlobResult: &agentv1.SetBlobResult{},
},
}); err != nil {
t.Fatalf("handleCheckpointBlobResult(%d) error = %v", index, err)
}
}
events, err = service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil {
t.Fatalf("ReadFromCursor() after ACK error = %v", err)
}
if len(events) != len(projection.Blobs)+1 {
t.Fatalf("events after ACK = %d, want %d", len(events), len(projection.Blobs)+1)
}
checkpoint := events[len(events)-1].Message.GetConversationCheckpointUpdate()
if checkpoint == nil || len(checkpoint.GetTurns()) != 1 {
t.Fatalf("last event checkpoint = %#v, want one Blob-backed turn", checkpoint)
}
}
func TestCheckpointBlobSyncRejectDoesNotPublishDanglingCheckpoint(t *testing.T) {
service, stream := testCheckpointBlobService(t)
projection, err := service.projector.ProjectCheckpointProjection(testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "hello"),
}))
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
if err := service.queueCheckpointProjection(stream, projection, checkpointTerminalAction{kind: checkpointTerminalActionNone}); err != nil {
t.Fatalf("queueCheckpointProjection() error = %v", err)
}
events, err := service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil || len(events) == 0 {
t.Fatalf("blob write events = %d, err = %v", len(events), err)
}
requestID := events[0].Message.GetKvServerMessage().GetId()
if err := service.handleCheckpointBlobResult(stream, &agentv1.KvClientMessage{
Id: requestID,
Message: &agentv1.KvClientMessage_SetBlobResult{
SetBlobResult: &agentv1.SetBlobResult{Error: &agentv1.Error{Message: "disk full"}},
},
}); err != nil {
t.Fatalf("handleCheckpointBlobResult() error = %v", err)
}
events, err = service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil {
t.Fatalf("ReadFromCursor() after rejection error = %v", err)
}
for _, event := range events {
if event.Message.GetConversationCheckpointUpdate() != nil {
t.Fatal("rejected Blob write published a dangling checkpoint")
}
}
}
func TestTerminalCheckpointRejectionFailsInsteadOfCompleting(t *testing.T) {
service, stream := testCheckpointBlobService(t)
projection, err := service.projector.ProjectCheckpointProjection(testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, stream.RequestID, "hello"),
}))
if err != nil {
t.Fatalf("projection: %v", err)
}
completion := &pendingTurnCompletion{RequestID: stream.RequestID}
if err := service.queueCheckpointProjection(stream, projection, checkpointCompletionAction(completion)); err != nil {
t.Fatalf("queue checkpoint: %v", err)
}
stream.mu.Lock()
var requestID uint32
for pendingID := range stream.PendingCheckpointBlobWrites {
requestID = pendingID
break
}
stream.mu.Unlock()
if requestID == 0 {
t.Fatal("test did not queue a Blob write")
}
if err := rejectCheckpointBlob(service, stream, requestID, "disk full"); err != nil {
t.Fatalf("reject terminal checkpoint: %v", err)
}
events, err := service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil {
t.Fatalf("ReadFromCursor() error = %v", err)
}
var failed, completed bool
for _, event := range events {
if event.End && event.TerminalErrorCode == "checkpoint_sync_error" {
failed = true
}
if event.Message.GetInteractionUpdate().GetTurnEnded() != nil {
completed = true
}
}
if !failed || completed {
t.Fatalf("terminal checkpoint events failed=%v completed=%v", failed, completed)
}
}
func TestCheckpointBlobSyncMergesRevisionsWithoutObsoleteFailure(t *testing.T) {
service, stream := testCheckpointBlobService(t)
first, err := service.projector.ProjectCheckpointProjection(testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "hello"),
}))
if err != nil {
t.Fatalf("first ProjectCheckpointProjection() error = %v", err)
}
latest, err := service.projector.ProjectCheckpointProjection(testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "hello"),
newAssistantTextEntry(1, "request-1", "latest answer", "", ""),
}))
if err != nil {
t.Fatalf("latest ProjectCheckpointProjection() error = %v", err)
}
if err := service.queueCheckpointProjection(stream, first, checkpointTerminalAction{kind: checkpointTerminalActionNone}); err != nil {
t.Fatalf("queue first projection: %v", err)
}
firstEvents, err := service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil {
t.Fatalf("read first events: %v", err)
}
if err := service.queueCheckpointProjection(stream, latest, checkpointTerminalAction{kind: checkpointTerminalActionNone}); err != nil {
t.Fatalf("queue latest projection: %v", err)
}
latestRequired := make(map[string]struct{}, len(latest.Blobs))
for _, blob := range latest.Blobs {
latestRequired[string(blob.ID)] = struct{}{}
}
var obsoleteRequestID uint32
for _, event := range firstEvents {
message := event.Message.GetKvServerMessage()
if message == nil || message.GetSetBlobArgs() == nil {
continue
}
if _, required := latestRequired[string(message.GetSetBlobArgs().GetBlobId())]; !required {
obsoleteRequestID = message.GetId()
break
}
}
if obsoleteRequestID == 0 {
t.Fatal("test did not find an obsolete first-revision Blob write")
}
if err := rejectCheckpointBlob(service, stream, obsoleteRequestID, "obsolete write rejected"); err != nil {
t.Fatalf("reject obsolete Blob: %v", err)
}
if err := acknowledgePendingCheckpointBlobs(service, stream); err != nil {
t.Fatalf("acknowledge latest Blob writes: %v", err)
}
events, err := service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil {
t.Fatalf("read merged events: %v", err)
}
checkpoints := 0
for _, event := range events {
if checkpoint := event.Message.GetConversationCheckpointUpdate(); checkpoint != nil {
checkpoints++
if len(checkpoint.GetTurns()) != len(latest.State.GetTurns()) || string(checkpoint.GetTurns()[0]) != string(latest.State.GetTurns()[0]) {
t.Fatalf("published checkpoint is not the latest revision: %#v", checkpoint)
}
}
}
if checkpoints != 1 {
t.Fatalf("published checkpoints = %d, want exactly latest revision", checkpoints)
}
}
func TestCheckpointBlobSyncCarriesCompletionIntoLatestRevision(t *testing.T) {
service, stream := testCheckpointBlobService(t)
first, err := service.projector.ProjectCheckpointProjection(testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "hello"),
}))
if err != nil {
t.Fatalf("first projection: %v", err)
}
latest, err := service.projector.ProjectCheckpointProjection(testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "hello"),
newAssistantTextEntry(1, "request-1", "done", "", ""),
}))
if err != nil {
t.Fatalf("latest projection: %v", err)
}
completion := &pendingTurnCompletion{
RequestID: stream.RequestID,
Usage: turnUsageSnapshot{InputTokens: 11, OutputTokens: 7},
}
if err := service.queueCheckpointProjection(stream, first, checkpointCompletionAction(completion)); err != nil {
t.Fatalf("queue completion projection: %v", err)
}
if err := service.queueCheckpointProjection(stream, latest, checkpointTerminalAction{kind: checkpointTerminalActionNone}); err != nil {
t.Fatalf("queue latest projection: %v", err)
}
if err := acknowledgePendingCheckpointBlobs(service, stream); err != nil {
t.Fatalf("acknowledge latest Blob writes: %v", err)
}
events, err := service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil {
t.Fatalf("read completion events: %v", err)
}
checkpointIndex, turnEndedIndex, endIndex := -1, -1, -1
for index, event := range events {
switch {
case event.Message.GetConversationCheckpointUpdate() != nil:
checkpointIndex = index
case event.Message.GetInteractionUpdate().GetTurnEnded() != nil:
turnEndedIndex = index
case event.End:
endIndex = index
}
}
if checkpointIndex < 0 || turnEndedIndex <= checkpointIndex || endIndex <= turnEndedIndex {
t.Fatalf("terminal order checkpoint=%d turn_ended=%d end=%d", checkpointIndex, turnEndedIndex, endIndex)
}
}
func TestCheckpointBlobSyncTimeoutFailsStreamWithoutPublishingDanglingCheckpoint(t *testing.T) {
service, stream := testCheckpointBlobService(t)
projection, err := service.projector.ProjectCheckpointProjection(testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "hello"),
}))
if err != nil {
t.Fatalf("projection: %v", err)
}
if err := service.queueCheckpointProjection(stream, projection, checkpointTerminalAction{kind: checkpointTerminalActionNone}); err != nil {
t.Fatalf("queue checkpoint: %v", err)
}
if err := service.handleCheckpointBlobTimeout(stream); err != nil {
t.Fatalf("timeout checkpoint: %v", err)
}
events, err := service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil {
t.Fatalf("read timeout events: %v", err)
}
var failed bool
for _, event := range events {
if event.Message.GetConversationCheckpointUpdate() != nil {
t.Fatal("timed-out Blob dependency published a dangling checkpoint")
}
if event.End && event.TerminalErrorCode == "checkpoint_sync_error" {
failed = true
}
}
if !failed {
t.Fatal("timed-out checkpoint did not fail the stream explicitly")
}
}
func TestCheckpointBlobSyncReusesConversationCacheAcrossRequests(t *testing.T) {
service, firstStream := testCheckpointBlobService(t)
projection, err := service.projector.ProjectCheckpointProjection(testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "hello"),
}))
if err != nil {
t.Fatalf("projection: %v", err)
}
if err := service.queueCheckpointProjection(firstStream, projection, checkpointTerminalAction{kind: checkpointTerminalActionNone}); err != nil {
t.Fatalf("queue first request: %v", err)
}
if err := acknowledgePendingCheckpointBlobs(service, firstStream); err != nil {
t.Fatalf("acknowledge first request: %v", err)
}
secondStream, err := service.broker.OpenStream(
"request-2", firstStream.ConversationID, 2, "default", "default",
agentv1.AgentMode_AGENT_MODE_AGENT, "continue",
)
if err != nil {
t.Fatalf("OpenStream() second request error = %v", err)
}
if err := service.queueCheckpointProjection(secondStream, projection, checkpointTerminalAction{kind: checkpointTerminalActionNone}); err != nil {
t.Fatalf("queue second request: %v", err)
}
events, err := service.broker.ReadFromCursor(secondStream.RequestID, 0)
if err != nil {
t.Fatalf("read second request events: %v", err)
}
if len(events) != 1 || events[0].Message.GetConversationCheckpointUpdate() == nil {
t.Fatalf("second request events = %#v, want cached immediate checkpoint", events)
}
}
func TestCancellationReplacesUnconfirmedCheckpointBeforeEnding(t *testing.T) {
service, stream := testCheckpointBlobService(t)
conversation := testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, stream.RequestID, "hello"),
})
if err := service.replaceCheckpointConversation(stream, conversation); err != nil {
t.Fatalf("replaceCheckpointConversation() error = %v", err)
}
projection, err := service.projector.ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
if err := service.queueCheckpointProjection(stream, projection, checkpointTerminalAction{kind: checkpointTerminalActionNone}); err != nil {
t.Fatalf("queueCheckpointProjection() error = %v", err)
}
stream.mu.Lock()
var staleRequestID uint32
for requestID := range stream.PendingCheckpointBlobWrites {
staleRequestID = requestID
break
}
stream.mu.Unlock()
if staleRequestID == 0 {
t.Fatal("test did not queue an unconfirmed Blob write")
}
if err := service.handleCancelIntent(InboundIntent{
Kind: "cancel",
RequestID: stream.RequestID,
CancelReason: "user stopped",
}); err != nil {
t.Fatalf("handleCancelIntent() error = %v", err)
}
stream.mu.Lock()
phase := stream.Phase
status := stream.Status
pendingCheckpoint := stream.PendingCheckpoint
pendingWrites := len(stream.PendingCheckpointBlobWrites)
stream.mu.Unlock()
if phase != TurnPhaseCheckpointing || status != StreamStatusCreated {
t.Fatalf("before checkpoint ACK phase=%s status=%s, want checkpointing/created", phase, status)
}
if pendingCheckpoint == nil || pendingWrites == 0 {
t.Fatalf("before checkpoint ACK pending_checkpoint=%v pending_writes=%d", pendingCheckpoint != nil, pendingWrites)
}
if err := service.handleCheckpointBlobResult(stream, &agentv1.KvClientMessage{
Id: staleRequestID,
Message: &agentv1.KvClientMessage_SetBlobResult{
SetBlobResult: &agentv1.SetBlobResult{},
},
}); err != nil {
t.Fatalf("stale Blob ACK error = %v", err)
}
if err := acknowledgePendingCheckpointBlobs(service, stream); err != nil {
t.Fatalf("acknowledge cancellation checkpoint: %v", err)
}
stream.mu.Lock()
phase = stream.Phase
status = stream.Status
stream.mu.Unlock()
if phase != TurnPhaseCanceled || status != StreamStatusCanceled {
t.Fatalf("after checkpoint ACK phase=%s status=%s, want canceled", phase, status)
}
assertCanceledEndEvent(t, service, stream)
}
func TestCancellationMetadataFailureStillEndsStream(t *testing.T) {
service, stream := testCheckpointBlobService(t)
blockingPath := filepath.Join(t.TempDir(), "not-a-directory")
if err := os.WriteFile(blockingPath, []byte("block child creation"), 0o600); err != nil {
t.Fatalf("WriteFile() error = %v", err)
}
service.store = NewConversationFileStore(blockingPath)
if err := service.replaceCheckpointConversation(stream, testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, stream.RequestID, "hello"),
})); err != nil {
t.Fatalf("replaceCheckpointConversation() error = %v", err)
}
if err := service.handleCancelIntent(InboundIntent{Kind: "cancel", RequestID: stream.RequestID}); err != nil {
t.Fatalf("handleCancelIntent() error = %v", err)
}
if err := acknowledgePendingCheckpointBlobs(service, stream); err != nil {
t.Fatalf("acknowledge cancellation checkpoint: %v", err)
}
assertCanceledEndEvent(t, service, stream)
}
func TestCheckpointTerminalActionMergePriority(t *testing.T) {
complete := checkpointCompletionAction(&pendingTurnCompletion{RequestID: "complete"})
cancel := checkpointCancellationAction("user canceled")
none := checkpointTerminalAction{kind: checkpointTerminalActionNone}
tests := []struct {
name string
current checkpointTerminalAction
incoming checkpointTerminalAction
wantKind checkpointTerminalActionKind
wantID string
}{
{name: "none then complete", current: none, incoming: complete, wantKind: checkpointTerminalActionComplete, wantID: "complete"},
{name: "complete then none", current: complete, incoming: none, wantKind: checkpointTerminalActionComplete, wantID: "complete"},
{name: "complete then cancel", current: complete, incoming: cancel, wantKind: checkpointTerminalActionCancel},
{name: "cancel then complete", current: cancel, incoming: complete, wantKind: checkpointTerminalActionCancel},
{name: "cancel then none", current: cancel, incoming: none, wantKind: checkpointTerminalActionCancel},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
merged := mergeCheckpointTerminalAction(test.current, test.incoming)
if merged.kind != test.wantKind {
t.Fatalf("merged kind = %d, want %d", merged.kind, test.wantKind)
}
if test.wantID != "" {
completion := merged.completionValue()
if completion == nil || completion.RequestID != test.wantID {
t.Fatalf("merged completion = %#v, want request_id=%s", completion, test.wantID)
}
}
})
}
}
func TestCheckpointTerminalActionIsMutuallyExclusive(t *testing.T) {
completion := &pendingTurnCompletion{RequestID: "request-1"}
action := checkpointCompletionAction(completion)
if action.kind != checkpointTerminalActionComplete || action.completionValue() == nil {
t.Fatalf("completion action = %#v", action)
}
empty := checkpointCompletionAction(nil)
if empty.kind != checkpointTerminalActionNone || empty.completionValue() != nil {
t.Fatalf("empty action = %#v", empty)
}
}
func assertCanceledEndEvent(t *testing.T, service *Service, stream *ActiveStream) {
t.Helper()
events, err := service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil {
t.Fatalf("ReadFromCursor() error = %v", err)
}
for _, event := range events {
if event.End && event.TerminalErrorCode == "canceled" {
return
}
}
t.Fatal("cancellation did not publish canceled end event")
}
func acknowledgePendingCheckpointBlobs(service *Service, stream *ActiveStream) error {
for {
stream.mu.Lock()
requestIDs := make([]uint32, 0, len(stream.PendingCheckpointBlobWrites))
for requestID := range stream.PendingCheckpointBlobWrites {
requestIDs = append(requestIDs, requestID)
}
stream.mu.Unlock()
if len(requestIDs) == 0 {
return nil
}
for _, requestID := range requestIDs {
if err := service.handleCheckpointBlobResult(stream, &agentv1.KvClientMessage{
Id: requestID,
Message: &agentv1.KvClientMessage_SetBlobResult{
SetBlobResult: &agentv1.SetBlobResult{},
},
}); err != nil {
return err
}
}
}
}
func rejectCheckpointBlob(service *Service, stream *ActiveStream, requestID uint32, message string) error {
return service.handleCheckpointBlobResult(stream, &agentv1.KvClientMessage{
Id: requestID,
Message: &agentv1.KvClientMessage_SetBlobResult{
SetBlobResult: &agentv1.SetBlobResult{Error: &agentv1.Error{Message: message}},
},
})
}
func TestImportedTurnIDsRemainCheckpointPrefix(t *testing.T) {
importedID := make([]byte, 32)
for index := range importedID {
importedID[index] = byte(index + 1)
}
conversation := testConversation([]HistoryEntry{
testUserMessageEntry(t, 2, "request-2", "continued question"),
})
conversation.ImportedTurnIDs = [][]byte{importedID}
projection, err := NewHistoryProjector().ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
if len(projection.State.GetTurns()) != 2 {
t.Fatalf("turns = %d, want imported prefix plus projected turn", len(projection.State.GetTurns()))
}
if string(projection.State.GetTurns()[0]) != string(importedID) {
t.Fatal("imported turn ID was not preserved as the checkpoint prefix")
}
}
func testCheckpointBlobService(t *testing.T) (*Service, *ActiveStream) {
t.Helper()
broker := NewStreamBroker()
service := &Service{
projector: NewHistoryProjector(),
broker: broker,
checkpointBlobs: make(map[string]*checkpointBlobCacheEntry),
}
stream, err := broker.OpenStream(
"request-1",
"conversation-1",
1,
"default",
"default",
agentv1.AgentMode_AGENT_MODE_AGENT,
"hello",
)
if err != nil {
t.Fatalf("OpenStream() error = %v", err)
}
return service, stream
}
+8 -2
View File
@@ -76,6 +76,12 @@ func (broker *StreamBroker) OpenStream(requestID string, conversationID string,
if existing.BackgroundShellActions == nil {
existing.BackgroundShellActions = make(map[string]time.Time)
}
if existing.PendingCheckpointBlobWrites == nil {
existing.PendingCheckpointBlobWrites = make(map[uint32]string)
}
if existing.ConfirmedCheckpointBlobs == nil {
existing.ConfirmedCheckpointBlobs = make(map[string]struct{})
}
existing.UpdatedAt = time.Now().UTC()
existing.mu.Unlock()
return existing, nil
@@ -102,8 +108,8 @@ func (broker *StreamBroker) OpenStream(requestID string, conversationID string,
BackgroundShellsByMessageID: make(map[uint32]string),
BackgroundShellsByExecID: make(map[string]string),
BackgroundShellActions: make(map[string]time.Time),
PendingCheckpointBlobWrites: make(map[uint32]pendingCheckpointBlobWrite),
PendingCheckpointBlobRequests: make(map[string]uint32),
PendingCheckpointBlobWrites: make(map[uint32]string),
ConfirmedCheckpointBlobs: make(map[string]struct{}),
CreatedAt: now,
UpdatedAt: now,
}
@@ -0,0 +1,238 @@
package forwarder
import (
"encoding/hex"
"fmt"
"log"
"strings"
"time"
"google.golang.org/protobuf/proto"
"cursor/gen/agentv1"
)
const checkpointBlobWriteTimeout = 5 * time.Second
type pendingCheckpointBlobWrite struct {
requestID uint32
blob CheckpointBlob
}
func clonePendingTurnCompletion(completion *pendingTurnCompletion) *pendingTurnCompletion {
if completion == nil {
return nil
}
cloned := *completion
return &cloned
}
func (service *Service) queueCheckpointProjection(stream *ActiveStream, projection *CheckpointProjection, completion *pendingTurnCompletion) error {
if service == nil || stream == nil || projection == nil || projection.State == nil {
return nil
}
state, ok := proto.Clone(projection.State).(*agentv1.ConversationStateStructure)
if !ok || state == nil {
return fmt.Errorf("clone checkpoint state")
}
stream.mu.Lock()
if stream.PendingCheckpointBlobWrites == nil {
stream.PendingCheckpointBlobWrites = make(map[uint32]string)
}
if stream.ConfirmedCheckpointBlobs == nil {
stream.ConfirmedCheckpointBlobs = make(map[string]struct{})
}
if completion == nil && stream.PendingCheckpoint != nil {
completion = stream.PendingCheckpoint.Completion
}
required := make(map[string]struct{}, len(projection.Blobs))
pendingKeys := make(map[string]struct{}, len(stream.PendingCheckpointBlobWrites))
for _, key := range stream.PendingCheckpointBlobWrites {
pendingKeys[key] = struct{}{}
}
toWrite := make([]pendingCheckpointBlobWrite, 0, len(projection.Blobs))
for _, blob := range projection.Blobs {
key := string(blob.ID)
if key == "" {
continue
}
required[key] = struct{}{}
if _, confirmed := stream.ConfirmedCheckpointBlobs[key]; confirmed {
continue
}
if _, pending := pendingKeys[key]; pending {
continue
}
stream.NextCheckpointBlobRequestID++
if stream.NextCheckpointBlobRequestID == 0 {
stream.NextCheckpointBlobRequestID++
}
requestID := stream.NextCheckpointBlobRequestID
stream.PendingCheckpointBlobWrites[requestID] = key
pendingKeys[key] = struct{}{}
toWrite = append(toWrite, pendingCheckpointBlobWrite{requestID: requestID, blob: blob})
}
stream.PendingCheckpoint = &pendingCheckpointPublish{
State: state,
Required: required,
Completion: clonePendingTurnCompletion(completion),
}
if completion != nil {
stream.Phase = TurnPhaseCheckpointing
}
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
for _, write := range toWrite {
if err := service.broker.Publish(stream.RequestID, StreamEvent{
Message: buildSetCheckpointBlobMessage(write.requestID, write.blob),
}); err != nil {
return service.finishAfterCheckpointSyncFailure(stream, fmt.Errorf("publish checkpoint blob: %w", err))
}
}
if service.checkpointProjectionReady(stream) {
return service.publishReadyCheckpoint(stream)
}
service.scheduleStreamTimer(
stream,
providerTimerKey(streamTimerCheckpointBlobs, ""),
checkpointBlobWriteTimeout,
streamTimerCheckpointBlobs,
"",
0,
"checkpoint blob write timeout",
)
return nil
}
func (service *Service) checkpointProjectionReady(stream *ActiveStream) bool {
if stream == nil {
return false
}
stream.mu.Lock()
defer stream.mu.Unlock()
if stream.PendingCheckpoint == nil {
return false
}
for key := range stream.PendingCheckpoint.Required {
if _, confirmed := stream.ConfirmedCheckpointBlobs[key]; !confirmed {
return false
}
}
return true
}
func (service *Service) handleCheckpointBlobResult(stream *ActiveStream, message *agentv1.KvClientMessage) error {
if service == nil || stream == nil || message == nil || message.GetSetBlobResult() == nil {
return nil
}
stream.mu.Lock()
key, ok := stream.PendingCheckpointBlobWrites[message.GetId()]
if ok {
delete(stream.PendingCheckpointBlobWrites, message.GetId())
}
required := false
if ok && stream.PendingCheckpoint != nil {
_, required = stream.PendingCheckpoint.Required[key]
}
if ok && message.GetSetBlobResult().GetError() == nil {
stream.ConfirmedCheckpointBlobs[key] = struct{}{}
}
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
if !ok {
return nil
}
if blobErr := message.GetSetBlobResult().GetError(); blobErr != nil && required {
return service.finishAfterCheckpointSyncFailure(stream, fmt.Errorf(
"client rejected checkpoint blob %s: %s",
hex.EncodeToString([]byte(key)),
firstNonEmpty(strings.TrimSpace(blobErr.GetMessage()), "unknown error"),
))
}
if service.checkpointProjectionReady(stream) {
return service.publishReadyCheckpoint(stream)
}
return nil
}
func (service *Service) publishReadyCheckpoint(stream *ActiveStream) error {
if service == nil || stream == nil {
return nil
}
stream.mu.Lock()
pending := stream.PendingCheckpoint
if pending == nil {
stream.mu.Unlock()
return nil
}
for key := range pending.Required {
if _, confirmed := stream.ConfirmedCheckpointBlobs[key]; !confirmed {
stream.mu.Unlock()
return nil
}
}
stream.PendingCheckpoint = nil
state := pending.State
completion := clonePendingTurnCompletion(pending.Completion)
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
clearStreamTimer(stream, providerTimerKey(streamTimerCheckpointBlobs, ""))
if err := service.broker.Publish(stream.RequestID, StreamEvent{Message: buildCheckpointMessage(state)}); err != nil {
if completion != nil {
log.Printf("forwarder checkpoint publish skipped before successful terminal request_id=%s err=%v", stream.RequestID, err)
return service.finishSuccessfulTurnAfterCheckpoint(stream, *completion)
}
return err
}
if completion != nil {
return service.finishSuccessfulTurnAfterCheckpoint(stream, *completion)
}
return nil
}
func (service *Service) handleCheckpointBlobTimeout(stream *ActiveStream) error {
if stream == nil {
return nil
}
stream.mu.Lock()
pendingCount := len(stream.PendingCheckpointBlobWrites)
stream.mu.Unlock()
return service.finishAfterCheckpointSyncFailure(stream, fmt.Errorf("%d checkpoint blob writes timed out", pendingCount))
}
func (service *Service) finishAfterCheckpointSyncFailure(stream *ActiveStream, cause error) error {
if stream == nil {
return nil
}
stream.mu.Lock()
pending := stream.PendingCheckpoint
stream.PendingCheckpoint = nil
stream.PendingCheckpointBlobWrites = make(map[uint32]string)
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
clearStreamTimer(stream, providerTimerKey(streamTimerCheckpointBlobs, ""))
if cause != nil {
log.Printf("forwarder checkpoint blob sync skipped request_id=%s conversation_id=%s err=%v", stream.RequestID, stream.ConversationID, cause)
}
if pending != nil && pending.Completion != nil {
return service.finishSuccessfulTurnAfterCheckpoint(stream, *pending.Completion)
}
return nil
}
func (service *Service) discardPendingCheckpoint(stream *ActiveStream, reason string) {
if stream == nil {
return
}
stream.mu.Lock()
stream.PendingCheckpoint = nil
stream.PendingCheckpointBlobWrites = make(map[uint32]string)
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
clearStreamTimer(stream, providerTimerKey(streamTimerCheckpointBlobs, ""))
if strings.TrimSpace(reason) != "" {
log.Printf("forwarder pending checkpoint discarded request_id=%s conversation_id=%s reason=%s", stream.RequestID, stream.ConversationID, strings.TrimSpace(reason))
}
}
@@ -0,0 +1,208 @@
package forwarder
import (
"testing"
"google.golang.org/protobuf/encoding/protojson"
"cursor/gen/agentv1"
)
func TestCheckpointBlobSyncPublishesCheckpointAfterAcknowledgements(t *testing.T) {
service, stream, projection := testCheckpointBlobProjection(t)
if err := service.queueCheckpointProjection(stream, projection, nil); err != nil {
t.Fatalf("queueCheckpointProjection() error = %v", err)
}
events := readCheckpointTestEvents(t, service, stream)
if len(events) != len(projection.Blobs) {
t.Fatalf("events before ACK = %d, want %d Blob writes", len(events), len(projection.Blobs))
}
for _, event := range events {
if event.Message.GetKvServerMessage().GetSetBlobArgs() == nil {
t.Fatalf("event before ACK = %#v, want set_blob_args", event.Message)
}
}
acknowledgeCheckpointBlobs(t, service, stream)
events = readCheckpointTestEvents(t, service, stream)
checkpoint := events[len(events)-1].Message.GetConversationCheckpointUpdate()
if checkpoint == nil || len(checkpoint.GetTurns()) != 1 {
t.Fatalf("last event checkpoint = %#v, want one Blob-backed turn", checkpoint)
}
}
func TestCheckpointBlobSyncPublishesCheckpointBeforeSuccessfulTerminal(t *testing.T) {
service, stream, projection := testCheckpointBlobProjection(t)
completion := &pendingTurnCompletion{
RequestID: stream.RequestID,
Usage: turnUsageSnapshot{InputTokens: 11, OutputTokens: 7},
}
if err := service.queueCheckpointProjection(stream, projection, completion); err != nil {
t.Fatalf("queueCheckpointProjection() error = %v", err)
}
acknowledgeCheckpointBlobs(t, service, stream)
events := readCheckpointTestEvents(t, service, stream)
checkpointIndex, turnEndedIndex, endIndex := -1, -1, -1
for index, event := range events {
switch {
case event.Message.GetConversationCheckpointUpdate() != nil:
checkpointIndex = index
case event.Message.GetInteractionUpdate().GetTurnEnded() != nil:
turnEndedIndex = index
case event.End:
endIndex = index
}
}
if checkpointIndex < 0 || turnEndedIndex <= checkpointIndex || endIndex <= turnEndedIndex {
t.Fatalf("terminal order checkpoint=%d turn_ended=%d end=%d", checkpointIndex, turnEndedIndex, endIndex)
}
}
func TestCheckpointBlobTimeoutDoesNotFailSuccessfulTurn(t *testing.T) {
service, stream, projection := testCheckpointBlobProjection(t)
completion := &pendingTurnCompletion{
RequestID: stream.RequestID,
Usage: turnUsageSnapshot{InputTokens: 11, OutputTokens: 7},
}
if err := service.queueCheckpointProjection(stream, projection, completion); err != nil {
t.Fatalf("queueCheckpointProjection() error = %v", err)
}
if err := service.handleCheckpointBlobTimeout(stream); err != nil {
t.Fatalf("handleCheckpointBlobTimeout() error = %v", err)
}
events := readCheckpointTestEvents(t, service, stream)
var checkpoint, turnEnded, successfulEnd bool
for _, event := range events {
checkpoint = checkpoint || event.Message.GetConversationCheckpointUpdate() != nil
turnEnded = turnEnded || event.Message.GetInteractionUpdate().GetTurnEnded() != nil
successfulEnd = successfulEnd || event.End && event.TerminalErrorCode == ""
}
if checkpoint || !turnEnded || !successfulEnd {
t.Fatalf("timeout events checkpoint=%v turn_ended=%v successful_end=%v", checkpoint, turnEnded, successfulEnd)
}
}
func TestCancellationDiscardsPendingCheckpointAndIgnoresLateAcknowledgements(t *testing.T) {
service, stream, projection := testCheckpointBlobProjection(t)
if err := service.queueCheckpointProjection(stream, projection, nil); err != nil {
t.Fatalf("queueCheckpointProjection() error = %v", err)
}
stream.mu.Lock()
requestIDs := make([]uint32, 0, len(stream.PendingCheckpointBlobWrites))
for requestID := range stream.PendingCheckpointBlobWrites {
requestIDs = append(requestIDs, requestID)
}
stream.mu.Unlock()
if err := service.handleCancelIntent(InboundIntent{
Kind: "cancel",
RequestID: stream.RequestID,
CancelReason: "user stopped",
}); err != nil {
t.Fatalf("handleCancelIntent() error = %v", err)
}
for _, requestID := range requestIDs {
if err := service.handleCheckpointBlobResult(stream, &agentv1.KvClientMessage{
Id: requestID,
Message: &agentv1.KvClientMessage_SetBlobResult{
SetBlobResult: &agentv1.SetBlobResult{},
},
}); err != nil {
t.Fatalf("late ACK %d error = %v", requestID, err)
}
}
events := readCheckpointTestEvents(t, service, stream)
var checkpoint, canceledEnd bool
for _, event := range events {
checkpoint = checkpoint || event.Message.GetConversationCheckpointUpdate() != nil
canceledEnd = canceledEnd || event.End && event.TerminalErrorCode == "canceled"
}
stream.mu.Lock()
pending := stream.PendingCheckpoint
stream.mu.Unlock()
if checkpoint || !canceledEnd || pending != nil {
t.Fatalf("cancel events checkpoint=%v canceled_end=%v pending=%v", checkpoint, canceledEnd, pending != nil)
}
}
func testCheckpointBlobProjection(t *testing.T) (*Service, *ActiveStream, *CheckpointProjection) {
t.Helper()
broker := NewStreamBroker()
service := &Service{
store: NewConversationFileStore(t.TempDir()),
projector: NewHistoryProjector(),
broker: broker,
}
stream, err := broker.OpenStream(
"request-1", "conversation-1", 1, "default", "default",
agentv1.AgentMode_AGENT_MODE_AGENT, "hello",
)
if err != nil {
t.Fatalf("OpenStream() error = %v", err)
}
conversation := &ConversationFile{
ConversationID: "conversation-1",
RootConversationID: "conversation-1",
Mode: "agent",
NextTurnSeq: 2,
NextEntrySeq: 3,
TokenDetailsMaxTokens: projectedConversationMaxTokens,
Entries: []HistoryEntry{
testCheckpointUserEntry(t),
newAssistantTextEntry(1, "request-1", "hi", "", ""),
},
}
projection, err := service.projector.ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
if err := service.replaceCheckpointConversation(stream, conversation); err != nil {
t.Fatalf("replaceCheckpointConversation() error = %v", err)
}
return service, stream, projection
}
func testCheckpointUserEntry(t *testing.T) HistoryEntry {
t.Helper()
payload, err := protojson.Marshal(&agentv1.UserMessage{Text: "hello", MessageId: "message-1"})
if err != nil {
t.Fatalf("marshal user message: %v", err)
}
return HistoryEntry{Seq: 1, TurnSeq: 1, RequestID: "request-1", Role: "user", Kind: "user_message", Payload: payload}
}
func acknowledgeCheckpointBlobs(t *testing.T, service *Service, stream *ActiveStream) {
t.Helper()
for {
stream.mu.Lock()
requestIDs := make([]uint32, 0, len(stream.PendingCheckpointBlobWrites))
for requestID := range stream.PendingCheckpointBlobWrites {
requestIDs = append(requestIDs, requestID)
}
stream.mu.Unlock()
if len(requestIDs) == 0 {
return
}
for _, requestID := range requestIDs {
if err := service.handleCheckpointBlobResult(stream, &agentv1.KvClientMessage{
Id: requestID,
Message: &agentv1.KvClientMessage_SetBlobResult{
SetBlobResult: &agentv1.SetBlobResult{},
},
}); err != nil {
t.Fatalf("handleCheckpointBlobResult(%d) error = %v", requestID, err)
}
}
}
}
func readCheckpointTestEvents(t *testing.T, service *Service, stream *ActiveStream) []StreamEvent {
t.Helper()
events, err := service.broker.ReadFromCursor(stream.RequestID, 0)
if err != nil {
t.Fatalf("ReadFromCursor() error = %v", err)
}
return events
}
+12 -2
View File
@@ -690,9 +690,21 @@ func appendEntriesInPlace(conversation *ConversationFile, entries []HistoryEntry
}
now := time.Now().UTC()
assigned := make([]HistoryEntry, 0, len(entries))
existingIdempotencyKeys := make(map[string]struct{})
for _, existing := range conversation.Entries {
if key := strings.TrimSpace(existing.IdempotencyKey); key != "" {
existingIdempotencyKeys[key] = struct{}{}
}
}
maxTurnSeq := conversation.NextTurnSeq - 1
for _, entry := range entries {
next := entry
if key := strings.TrimSpace(next.IdempotencyKey); key != "" {
if _, exists := existingIdempotencyKeys[key]; exists {
continue
}
existingIdempotencyKeys[key] = struct{}{}
}
if next.CreatedAt.IsZero() {
next.CreatedAt = now
}
@@ -750,7 +762,6 @@ func mergeConversationMetadata(target *ConversationFile, source *ConversationFil
target.CurrentPlanText = source.CurrentPlanText
target.CurrentPlans = clonePlanRegistryEntries(source.CurrentPlans)
target.CurrentTodos = cloneTodoItems(source.CurrentTodos)
target.ImportedTurnIDs = cloneByteSlices(source.ImportedTurnIDs)
target.LatestRequestPrefix = cloneConversationRequestPrefix(source.LatestRequestPrefix)
target.LastProviderCall = cloneConversationProviderCall(source.LastProviderCall)
if !source.CreatedAt.IsZero() && (target.CreatedAt.IsZero() || source.CreatedAt.Before(target.CreatedAt)) {
@@ -883,7 +894,6 @@ func cloneConversationFile(conversation *ConversationFile) *ConversationFile {
cloned := *conversation
cloned.CurrentPlans = clonePlanRegistryEntries(conversation.CurrentPlans)
cloned.CurrentTodos = cloneTodoItems(conversation.CurrentTodos)
cloned.ImportedTurnIDs = cloneByteSlices(conversation.ImportedTurnIDs)
cloned.LatestRequestPrefix = cloneConversationRequestPrefix(conversation.LatestRequestPrefix)
cloned.LastProviderCall = cloneConversationProviderCall(conversation.LastProviderCall)
cloned.Entries = append([]HistoryEntry(nil), conversation.Entries...)
@@ -1,167 +0,0 @@
package forwarder
import (
"crypto/sha256"
"fmt"
"google.golang.org/protobuf/proto"
"cursor/gen/agentv1"
modeladapter "cursor/internal/backend/agent/model"
promptengine "cursor/internal/backend/agent/prompt"
)
type importedBlobStore map[string][]byte
func newImportedBlobStore(items []*agentv1.PreFetchedBlob) (importedBlobStore, error) {
if len(items) == 0 {
return nil, nil
}
store := make(importedBlobStore, len(items))
for _, item := range items {
if item == nil || len(item.GetId()) == 0 {
continue
}
if len(item.GetId()) != sha256.Size {
return nil, fmt.Errorf("prefetched blob id length %d, want %d", len(item.GetId()), sha256.Size)
}
digest := sha256.Sum256(item.GetValue())
if string(digest[:]) != string(item.GetId()) {
return nil, fmt.Errorf("prefetched blob %x failed SHA-256 validation", item.GetId())
}
store[string(item.GetId())] = append([]byte(nil), item.GetValue()...)
}
return store, nil
}
func (store importedBlobStore) resolve(id []byte) ([]byte, bool) {
if len(id) == 0 || len(store) == 0 {
return nil, false
}
value, ok := store[string(id)]
return append([]byte(nil), value...), ok
}
func decodeImportedTurn(raw []byte, blobs importedBlobStore) (*agentv1.ConversationTurnStructure, []byte, error) {
if data, ok := blobs.resolve(raw); ok {
turn := &agentv1.ConversationTurnStructure{}
if err := proto.Unmarshal(data, turn); err != nil || turn.GetTurn() == nil {
return nil, nil, fmt.Errorf("decode imported turn blob %x: %w", raw, firstNonNilError(err, fmt.Errorf("turn payload is empty")))
}
return turn, append([]byte(nil), raw...), nil
}
turn := &agentv1.ConversationTurnStructure{}
if err := proto.Unmarshal(raw, turn); err == nil && turn.GetTurn() != nil {
return turn, nil, nil
}
if len(raw) == sha256.Size {
return nil, append([]byte(nil), raw...), nil
}
return nil, nil, fmt.Errorf("decode imported inline turn")
}
func decodeImportedUserMessage(raw []byte, blobs importedBlobStore) (*agentv1.UserMessage, error) {
data := raw
if resolved, ok := blobs.resolve(raw); ok {
data = resolved
} else if len(raw) == sha256.Size {
candidate := &agentv1.UserMessage{}
if err := proto.Unmarshal(raw, candidate); err != nil || !hasKnownUserMessageContent(candidate) {
return nil, fmt.Errorf("missing prefetched user message blob %x", raw)
}
return candidate, nil
}
message := &agentv1.UserMessage{}
if err := proto.Unmarshal(data, message); err != nil {
return nil, fmt.Errorf("decode imported turn user_message: %w", err)
}
return message, nil
}
func decodeImportedStep(raw []byte, blobs importedBlobStore) (*agentv1.ConversationStep, error) {
data := raw
if resolved, ok := blobs.resolve(raw); ok {
data = resolved
} else if len(raw) == sha256.Size {
candidate := &agentv1.ConversationStep{}
if err := proto.Unmarshal(raw, candidate); err != nil || candidate.GetMessage() == nil {
return nil, fmt.Errorf("missing prefetched conversation step blob %x", raw)
}
return candidate, nil
}
step := &agentv1.ConversationStep{}
if err := proto.Unmarshal(data, step); err != nil {
return nil, fmt.Errorf("decode imported turn step: %w", err)
}
if step.GetMessage() == nil {
return nil, fmt.Errorf("decode imported turn step: payload is empty")
}
return step, nil
}
func importedBlobTurnMessages(turn *agentv1.ConversationTurnStructure, blobs importedBlobStore) ([]modeladapter.Message, error) {
if turn == nil || turn.GetAgentConversationTurn() == nil {
return nil, nil
}
agentTurn := turn.GetAgentConversationTurn()
messages := make([]modeladapter.Message, 0, 1+len(agentTurn.GetSteps()))
if len(agentTurn.GetUserMessage()) > 0 {
userMessage, err := decodeImportedUserMessage(agentTurn.GetUserMessage(), blobs)
if err != nil {
return nil, err
}
if replay, ok := promptengine.BuildUserMessageReplayMessage(userMessage); ok {
messages = append(messages, toModelMessage(replay))
}
}
for _, rawStep := range agentTurn.GetSteps() {
if len(rawStep) == 0 {
continue
}
step, err := decodeImportedStep(rawStep, blobs)
if err != nil {
return nil, err
}
for _, replay := range promptengine.BuildLegacyMessagesFromConversationStep(step) {
messages = append(messages, toModelMessage(replay))
}
}
return messages, nil
}
func importedTurnIDs(turns [][]byte, blobs importedBlobStore) ([][]byte, error) {
ids := make([][]byte, 0, len(turns))
for _, raw := range turns {
if len(raw) == 0 {
continue
}
_, id, err := decodeImportedTurn(raw, blobs)
if err != nil {
return nil, err
}
if len(id) > 0 {
ids = append(ids, id)
}
}
return ids, nil
}
func hasKnownUserMessageContent(message *agentv1.UserMessage) bool {
if message == nil {
return false
}
return message.GetText() != "" ||
message.GetMessageId() != "" ||
message.GetSelectedContext() != nil ||
message.GetRichText() != "" ||
len(message.GetConversationStateBlobId()) > 0 ||
len(message.GetTextBlobId()) > 0 ||
len(message.GetRichTextBlobId()) > 0
}
func firstNonNilError(err error, fallback error) error {
if err != nil {
return err
}
return fallback
}
@@ -0,0 +1,187 @@
package forwarder
import (
"encoding/json"
"strings"
"testing"
)
func TestAppendEntriesDeduplicatesIdempotencyKey(t *testing.T) {
store := NewConversationFileStore(t.TempDir())
entry := HistoryEntry{
TurnSeq: 1,
RequestID: "request-1",
IdempotencyKey: "provider-interrupted-output:test",
Role: "assistant",
Kind: "assistant_text",
Payload: json.RawMessage(`{"text":"partial"}`),
}
if _, assigned, err := store.AppendEntries("conversation-1", []HistoryEntry{entry}); err != nil {
t.Fatalf("first AppendEntries() error = %v", err)
} else if len(assigned) != 1 {
t.Fatalf("first AppendEntries() assigned = %d, want 1", len(assigned))
}
if _, assigned, err := store.AppendEntries("conversation-1", []HistoryEntry{entry}); err != nil {
t.Fatalf("duplicate AppendEntries() error = %v", err)
} else if len(assigned) != 0 {
t.Fatalf("duplicate AppendEntries() assigned = %d, want 0", len(assigned))
}
conversation, err := store.LoadConversation("conversation-1")
if err != nil {
t.Fatalf("LoadConversation() error = %v", err)
}
if len(conversation.Entries) != 1 {
t.Fatalf("persisted entries = %d, want 1", len(conversation.Entries))
}
}
func TestCancelPersistsInterruptedProviderOutputIdempotently(t *testing.T) {
service, stream, _ := testCheckpointBlobProjection(t)
conversation, _, _, err := service.snapshotCheckpointConversation(stream)
if err != nil {
t.Fatalf("snapshotCheckpointConversation() error = %v", err)
}
if _, err := service.store.SaveConversationWithEntries(stream.ConversationID, conversation, conversation.Entries); err != nil {
t.Fatalf("SaveConversationWithEntries() error = %v", err)
}
stream.mu.Lock()
stream.CurrentModelCallID = "model-call-1"
stream.ProviderAccumulatedText = "partial answer"
stream.ProviderAccumulatedReasoning = "partial reasoning"
stream.mu.Unlock()
cancel := InboundIntent{
Kind: "cancel",
RequestID: stream.RequestID,
CancelReason: "[canceled] Superseded by newer request",
}
if err := service.handleCancelIntent(cancel); err != nil {
t.Fatalf("first handleCancelIntent() error = %v", err)
}
stream.mu.Lock()
stream.ProviderAccumulatedText = "late duplicate fragment"
stream.mu.Unlock()
if err := service.handleCancelIntent(cancel); err != nil {
t.Fatalf("duplicate handleCancelIntent() error = %v", err)
}
persisted, err := service.store.LoadConversation(stream.ConversationID)
if err != nil {
t.Fatalf("LoadConversation() error = %v", err)
}
assistantEntries := 0
cancelEntries := 0
for _, entry := range persisted.Entries {
if entry.Kind == "metadata" {
var payload metadataPayload
if err := json.Unmarshal(entry.Payload, &payload); err != nil {
t.Fatalf("decode metadata entry: %v", err)
}
if payload.Type == "control" && readStringValue(payload.Value["status"]) == "canceled" {
cancelEntries++
}
}
if entry.Kind != "assistant_text" {
continue
}
var payload assistantTextPayload
if err := json.Unmarshal(entry.Payload, &payload); err != nil {
t.Fatalf("decode assistant entry: %v", err)
}
if payload.Text == "partial answer" {
assistantEntries++
}
}
if assistantEntries != 1 {
t.Fatalf("persisted interrupted assistant entries = %d, want 1", assistantEntries)
}
if cancelEntries != 1 {
t.Fatalf("persisted cancel metadata entries = %d, want 1", cancelEntries)
}
replay, err := service.projector.ProjectPromptReplay(persisted)
if err != nil {
t.Fatalf("ProjectPromptReplay() error = %v", err)
}
found := false
for _, message := range replay {
if message.Role == "assistant" && strings.TrimSpace(message.Content) == "partial answer" && strings.TrimSpace(message.ReasoningContent) == "partial reasoning" {
found = true
break
}
}
if !found {
t.Fatalf("replay = %#v, want interrupted assistant output", replay)
}
checkpoint, err := service.projector.ProjectCheckpointProjection(persisted)
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
if checkpoint == nil || checkpoint.State == nil || len(checkpoint.State.GetTurns()) != 1 {
t.Fatalf("checkpoint state = %#v, want interrupted turn", checkpoint)
}
}
func TestCancelPreservesPersistedTurnActivityWithoutLiveAccumulator(t *testing.T) {
service, stream, _ := testCheckpointBlobProjection(t)
conversation, _, _, err := service.snapshotCheckpointConversation(stream)
if err != nil {
t.Fatalf("snapshotCheckpointConversation() error = %v", err)
}
if _, err := service.store.SaveConversationWithEntries(stream.ConversationID, conversation, conversation.Entries); err != nil {
t.Fatalf("SaveConversationWithEntries() error = %v", err)
}
if err := service.handleCancelIntent(InboundIntent{
Kind: "cancel",
RequestID: stream.RequestID,
CancelReason: "new_message_submitted",
}); err != nil {
t.Fatalf("handleCancelIntent() error = %v", err)
}
persisted, err := service.store.LoadConversation(stream.ConversationID)
if err != nil {
t.Fatalf("LoadConversation() error = %v", err)
}
replay, err := service.projector.ProjectPromptReplay(persisted)
if err != nil {
t.Fatalf("ProjectPromptReplay() error = %v", err)
}
for _, message := range replay {
if message.Role == "assistant" && strings.TrimSpace(message.Content) == "hi" {
return
}
}
t.Fatalf("replay = %#v, want persisted assistant activity", replay)
}
func TestProjectPromptReplayPreservesLegacyCanceledTurnActivity(t *testing.T) {
cancelEntry := newMetadataEntry(1, "request-1", "control", map[string]any{
"status": "canceled",
"reason": "new_message_submitted",
"replay_policy": cancelReplayPolicyKeepStableInput,
})
conversation := &ConversationFile{
ConversationID: "conversation-1",
NextTurnSeq: 2,
Entries: []HistoryEntry{
newAssistantTextEntry(1, "request-1", "persisted activity", "", ""),
cancelEntry,
},
}
replay, err := NewHistoryProjector().ProjectPromptReplay(conversation)
if err != nil {
t.Fatalf("ProjectPromptReplay() error = %v", err)
}
for _, message := range replay {
if message.Role == "assistant" && strings.TrimSpace(message.Content) == "persisted activity" {
return
}
}
t.Fatalf("replay = %#v, want legacy canceled activity", replay)
}
+72 -55
View File
@@ -355,6 +355,7 @@ const (
cancelReplayPolicyDropTurn = "drop_turn"
cancelReplayPolicyDropUnstarted = "drop_unstarted_turn"
cancelReplayPolicyKeepStableInput = "keep_stable_input"
cancelReplayPolicyKeepInterrupted = "keep_interrupted_output"
)
func sanitizeCanceledReplayEntries(entries []HistoryEntry) []HistoryEntry {
@@ -370,12 +371,18 @@ func sanitizeCanceledReplayEntries(entries []HistoryEntry) []HistoryEntry {
for _, entry := range entries {
if entry.TurnSeq > 0 {
if policy, canceled := canceledTurns[entry.TurnSeq]; canceled {
if policy == cancelReplayPolicyDropUnstarted {
if _, active := activeCanceledTurns[entry.TurnSeq]; active {
policy = cancelReplayPolicyKeepStableInput
} else {
policy = cancelReplayPolicyDropTurn
if policy == cancelReplayPolicyKeepInterrupted {
filtered = append(filtered, entry)
continue
}
if policy != cancelReplayPolicyDropTurn {
if _, active := activeCanceledTurns[entry.TurnSeq]; active {
filtered = append(filtered, entry)
continue
}
}
if policy == cancelReplayPolicyDropUnstarted {
policy = cancelReplayPolicyDropTurn
}
if policy == cancelReplayPolicyDropTurn || !isStableCanceledTurnInputEntry(entry) {
continue
@@ -450,6 +457,8 @@ func normalizeCancelReplayPolicy(policy string, reason string) string {
return cancelReplayPolicyDropUnstarted
case cancelReplayPolicyKeepStableInput:
return cancelReplayPolicyKeepStableInput
case cancelReplayPolicyKeepInterrupted:
return cancelReplayPolicyKeepInterrupted
default:
return cancelReplayPolicyForReason(reason)
}
@@ -566,7 +575,7 @@ func (projector *HistoryProjector) ProjectCheckpointProjection(conversation *Con
if err != nil {
return nil, err
}
state.Turns = append(cloneByteSlices(conversation.ImportedTurnIDs), turnIDs...)
state.Turns = turnIDs
replayMessages, err := projector.ProjectPromptReplay(conversation)
if err != nil {
return nil, err
@@ -616,9 +625,13 @@ func projectCheckpointTurnBlobs(conversation *ConversationFile, blobs *checkpoin
turnIDs := make([][]byte, 0, len(order))
for _, turnSeq := range order {
entries := grouped[turnSeq]
completedToolCalls, err := collectCheckpointCompletedToolCalls(entries)
if err != nil {
return nil, err
}
var userMessageID []byte
var turnRequestID string
stepIDs := make([][]byte, 0, len(entries))
steps := make([]*agentv1.ConversationStep, 0, len(entries))
seenToolCalls := make(map[string]struct{})
openToolCalls := make(map[string]struct{})
for _, entry := range entries {
@@ -645,59 +658,48 @@ func projectCheckpointTurnBlobs(conversation *ConversationFile, blobs *checkpoin
continue
}
if strings.TrimSpace(payload.ReasoningContent) != "" {
stepID, err := addCheckpointStepBlob(blobs, &agentv1.ConversationStep{
steps = append(steps, &agentv1.ConversationStep{
Message: &agentv1.ConversationStep_ThinkingMessage{
ThinkingMessage: &agentv1.ThinkingMessage{Text: payload.ReasoningContent},
},
})
if err != nil {
return nil, err
}
stepIDs = append(stepIDs, stepID)
}
if strings.TrimSpace(payload.Text) == "" {
continue
}
stepID, err := addCheckpointStepBlob(blobs, &agentv1.ConversationStep{
steps = append(steps, &agentv1.ConversationStep{
Message: &agentv1.ConversationStep_AssistantMessage{
AssistantMessage: &agentv1.AssistantMessage{Text: strings.TrimSpace(payload.Text)},
},
})
if err != nil {
return nil, err
}
stepIDs = append(stepIDs, stepID)
case "tool_call":
var payload toolCallEntryPayload
if err := json.Unmarshal(entry.Payload, &payload); err != nil {
return nil, err
}
if strings.TrimSpace(payload.ReasoningContent) != "" {
stepID, err := addCheckpointStepBlob(blobs, &agentv1.ConversationStep{
steps = append(steps, &agentv1.ConversationStep{
Message: &agentv1.ConversationStep_ThinkingMessage{
ThinkingMessage: &agentv1.ThinkingMessage{Text: payload.ReasoningContent},
},
})
if err != nil {
return nil, err
}
stepIDs = append(stepIDs, stepID)
}
toolCall := &agentv1.ToolCall{}
toolCallID := strings.TrimSpace(payload.ToolCallID)
if err := protojson.Unmarshal(payload.ToolCall, toolCall); err != nil {
return nil, err
}
if !shouldPersistToolResultName(firstNonEmpty(strings.TrimSpace(payload.ToolName), inferToolName(toolCall))) {
continue
}
stepID, err := addCheckpointStepBlob(blobs, &agentv1.ConversationStep{
Message: &agentv1.ConversationStep_ToolCall{ToolCall: toolCall},
})
if err != nil {
if completedPayload := completedToolCalls[toolCallID]; len(completedPayload) > 0 {
completedToolCall := &agentv1.ToolCall{}
if err := protojson.Unmarshal(completedPayload, completedToolCall); err != nil {
return nil, err
}
stepIDs = append(stepIDs, stepID)
if toolCallID := strings.TrimSpace(payload.ToolCallID); toolCallID != "" {
proto.Merge(toolCall, completedToolCall)
}
steps = append(steps, &agentv1.ConversationStep{
Message: &agentv1.ConversationStep_ToolCall{ToolCall: toolCall},
})
if toolCallID != "" {
seenToolCalls[toolCallID] = struct{}{}
openToolCalls[toolCallID] = struct{}{}
}
@@ -706,22 +708,19 @@ func projectCheckpointTurnBlobs(conversation *ConversationFile, blobs *checkpoin
if err := json.Unmarshal(entry.Payload, &payload); err != nil {
return nil, err
}
if toolCallID := strings.TrimSpace(payload.ToolCallID); toolCallID != "" {
if _, ok := seenToolCalls[toolCallID]; ok {
toolCallID := strings.TrimSpace(payload.ToolCallID)
if toolCallID != "" {
delete(openToolCalls, toolCallID)
}
if _, ok := seenToolCalls[toolCallID]; ok {
continue
}
}
if strings.TrimSpace(payload.ReasoningContent) != "" {
stepID, err := addCheckpointStepBlob(blobs, &agentv1.ConversationStep{
steps = append(steps, &agentv1.ConversationStep{
Message: &agentv1.ConversationStep_ThinkingMessage{
ThinkingMessage: &agentv1.ThinkingMessage{Text: payload.ReasoningContent},
},
})
if err != nil {
return nil, err
}
stepIDs = append(stepIDs, stepID)
}
if len(payload.ToolCall) == 0 {
continue
@@ -730,21 +729,22 @@ func projectCheckpointTurnBlobs(conversation *ConversationFile, blobs *checkpoin
if err := protojson.Unmarshal(payload.ToolCall, toolCall); err != nil {
return nil, err
}
if !shouldPersistToolResultName(firstNonEmpty(strings.TrimSpace(payload.ToolName), inferToolName(toolCall))) {
continue
}
stepID, err := addCheckpointStepBlob(blobs, &agentv1.ConversationStep{
steps = append(steps, &agentv1.ConversationStep{
Message: &agentv1.ConversationStep_ToolCall{ToolCall: toolCall},
})
}
}
if len(userMessageID) == 0 && len(steps) == 0 {
continue
}
stepIDs := make([][]byte, 0, len(steps))
for _, step := range steps {
stepID, err := addCheckpointStepBlob(blobs, step)
if err != nil {
return nil, err
}
stepIDs = append(stepIDs, stepID)
}
}
if len(userMessageID) == 0 && len(stepIDs) == 0 {
continue
}
agentTurn := &agentv1.AgentConversationTurnStructure{
UserMessage: userMessageID,
Steps: stepIDs,
@@ -765,6 +765,23 @@ func projectCheckpointTurnBlobs(conversation *ConversationFile, blobs *checkpoin
return turnIDs, nil
}
func collectCheckpointCompletedToolCalls(entries []HistoryEntry) (map[string]json.RawMessage, error) {
completed := make(map[string]json.RawMessage)
for _, entry := range entries {
if strings.TrimSpace(entry.Kind) != "tool_result" {
continue
}
var payload toolResultEntryPayload
if err := json.Unmarshal(entry.Payload, &payload); err != nil {
return nil, err
}
if toolCallID := strings.TrimSpace(payload.ToolCallID); toolCallID != "" && len(payload.ToolCall) > 0 {
completed[toolCallID] = payload.ToolCall
}
}
return completed, nil
}
func addCheckpointStepBlob(blobs *checkpointBlobGraph, step *agentv1.ConversationStep) ([]byte, error) {
payload, err := proto.Marshal(step)
if err != nil {
@@ -1209,7 +1226,7 @@ func trimReplayDanglingAssistantToolCalls(messages []modeladapter.Message) []mod
return trimmed
}
func shouldPersistToolResultName(toolName string) bool {
func shouldPersistCheckpointReplayToolResultName(toolName string) bool {
switch strings.TrimSpace(toolName) {
case "PatchEdit", "PatchEditLines", "PatchEditSpan", "Edit", "Write", "GenerateImage":
return true
@@ -1228,7 +1245,7 @@ func filterCheckpointPersistentToolReplay(messages []promptengine.Message) []pro
if strings.TrimSpace(message.Role) == "assistant" && len(message.ToolCalls) > 0 {
nextToolCalls := make([]promptengine.ToolCallDescriptor, 0, len(message.ToolCalls))
for _, toolCall := range message.ToolCalls {
if !shouldPersistToolResultName(toolCall.Function.Name) {
if !shouldPersistCheckpointReplayToolResultName(toolCall.Function.Name) {
skippedToolCallIDs[strings.TrimSpace(toolCall.ID)] = struct{}{}
continue
}
@@ -1245,7 +1262,7 @@ func filterCheckpointPersistentToolReplay(messages []promptengine.Message) []pro
if _, ok := skippedToolCallIDs[strings.TrimSpace(message.ToolCallID)]; ok {
continue
}
if !shouldPersistToolResultName(message.Name) {
if !shouldPersistCheckpointReplayToolResultName(message.Name) {
continue
}
}
@@ -1254,7 +1271,7 @@ func filterCheckpointPersistentToolReplay(messages []promptengine.Message) []pro
return filtered
}
func restoreImportedReplayUserMessages(messages []promptengine.Message, importedTurns [][]byte, blobs importedBlobStore) []promptengine.Message {
func restoreImportedReplayUserMessages(messages []promptengine.Message, importedTurns [][]byte) []promptengine.Message {
if len(messages) == 0 || len(importedTurns) == 0 {
return messages
}
@@ -1263,16 +1280,16 @@ func restoreImportedReplayUserMessages(messages []promptengine.Message, imported
if len(rawTurn) == 0 {
continue
}
turn, _, err := decodeImportedTurn(rawTurn, blobs)
if err != nil || turn == nil {
turn := &agentv1.ConversationTurnStructure{}
if err := proto.Unmarshal(rawTurn, turn); err != nil {
continue
}
agentTurn := turn.GetAgentConversationTurn()
if agentTurn == nil || len(agentTurn.GetUserMessage()) == 0 {
continue
}
userMessage, err := decodeImportedUserMessage(agentTurn.GetUserMessage(), blobs)
if err != nil {
userMessage := &agentv1.UserMessage{}
if err := proto.Unmarshal(agentTurn.GetUserMessage(), userMessage); err != nil {
continue
}
replay, ok := promptengine.BuildUserMessageReplayMessage(userMessage)
@@ -0,0 +1,380 @@
package forwarder
import (
"bytes"
"crypto/sha256"
"encoding/json"
"strings"
"testing"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"cursor/gen/agentv1"
promptengine "cursor/internal/backend/agent/prompt"
)
func TestProjectCheckpointProjectionBuildsResolvableForkState(t *testing.T) {
userPayload, err := protojson.Marshal(&agentv1.UserMessage{
Text: "parent question",
MessageId: "message-1",
})
if err != nil {
t.Fatalf("marshal user message: %v", err)
}
conversation := &ConversationFile{
ConversationID: "conversation-1",
RootConversationID: "conversation-1",
Mode: "agent",
NextTurnSeq: 2,
NextEntrySeq: 3,
TokenDetailsMaxTokens: projectedConversationMaxTokens,
Entries: []HistoryEntry{
{Seq: 1, TurnSeq: 1, RequestID: "request-1", Role: "user", Kind: "user_message", Payload: userPayload},
newAssistantTextEntry(1, "request-1", "parent answer", "", ""),
},
}
projection, err := NewHistoryProjector().ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
state := projection.State
if len(state.GetTurns()) != 1 {
t.Fatalf("ProjectCheckpointProjection() turns = %d, want 1 Blob-backed turn", len(state.GetTurns()))
}
blobs := make(map[string][]byte, len(projection.Blobs))
for _, blob := range projection.Blobs {
digest := sha256.Sum256(blob.Data)
if len(blob.ID) != sha256.Size || string(blob.ID) != string(digest[:]) {
t.Fatalf("invalid content-addressed Blob id=%x", blob.ID)
}
blobs[string(blob.ID)] = blob.Data
}
turnPayload, ok := blobs[string(state.GetTurns()[0])]
if !ok {
t.Fatal("turn references a missing Blob")
}
turn := &agentv1.ConversationTurnStructure{}
if err := proto.Unmarshal(turnPayload, turn); err != nil {
t.Fatalf("decode turn Blob: %v", err)
}
agentTurn := turn.GetAgentConversationTurn()
if agentTurn == nil {
t.Fatal("turn Blob does not contain an agent turn")
}
if _, ok := blobs[string(agentTurn.GetUserMessage())]; !ok {
t.Fatal("turn references a missing user message Blob")
}
for _, stepID := range agentTurn.GetSteps() {
if _, ok := blobs[string(stepID)]; !ok {
t.Fatal("turn references a missing step Blob")
}
}
messages, err := importedConversationStateModelMessages(state)
if err != nil {
t.Fatalf("importedConversationStateModelMessages() error = %v", err)
}
if len(messages) != 2 {
t.Fatalf("imported messages = %d, want parent user and assistant context", len(messages))
}
if messages[0].Role != "user" || !strings.Contains(messages[0].Content, "parent question") {
t.Fatalf("first imported message = %#v", messages[0])
}
if messages[1].Role != "assistant" || messages[1].Content != "parent answer" {
t.Fatalf("second imported message = %#v", messages[1])
}
}
func TestProjectCheckpointProjectionKeepsForkPointIsolatedFromLaterHistory(t *testing.T) {
firstUser, err := protojson.Marshal(&agentv1.UserMessage{Text: "first question", MessageId: "message-1"})
if err != nil {
t.Fatalf("marshal first user message: %v", err)
}
conversation := &ConversationFile{
ConversationID: "conversation-1",
RootConversationID: "conversation-1",
Mode: "agent",
NextTurnSeq: 2,
NextEntrySeq: 3,
TokenDetailsMaxTokens: projectedConversationMaxTokens,
Entries: []HistoryEntry{
{Seq: 1, TurnSeq: 1, RequestID: "request-1", Role: "user", Kind: "user_message", Payload: firstUser},
newAssistantTextEntry(1, "request-1", "first answer", "", ""),
},
}
projector := NewHistoryProjector()
midpoint, err := projector.ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("midpoint projection: %v", err)
}
secondUser, err := protojson.Marshal(&agentv1.UserMessage{Text: "second question", MessageId: "message-2"})
if err != nil {
t.Fatalf("marshal second user message: %v", err)
}
appendEntriesInPlace(conversation, []HistoryEntry{
{TurnSeq: 2, RequestID: "request-2", Role: "user", Kind: "user_message", Payload: secondUser},
newAssistantTextEntry(2, "request-2", "second answer", "", ""),
})
latest, err := projector.ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("latest projection: %v", err)
}
midpointMessages, err := importedConversationStateModelMessages(midpoint.State)
if err != nil {
t.Fatalf("import midpoint messages: %v", err)
}
latestMessages, err := importedConversationStateModelMessages(latest.State)
if err != nil {
t.Fatalf("import latest messages: %v", err)
}
if len(midpoint.State.GetTurns()) != 1 || len(midpointMessages) != 2 {
t.Fatalf("midpoint turns=%d messages=%d, want 1 turn and 2 messages", len(midpoint.State.GetTurns()), len(midpointMessages))
}
if len(latest.State.GetTurns()) != 2 || len(latestMessages) != 4 {
t.Fatalf("latest turns=%d messages=%d, want 2 turns and 4 messages", len(latest.State.GetTurns()), len(latestMessages))
}
if midpointMessages[1].Content != "first answer" || latestMessages[3].Content != "second answer" {
t.Fatalf("fork snapshots are not isolated: midpoint=%#v latest=%#v", midpointMessages, latestMessages)
}
}
func TestProjectCheckpointProjectionMergesToolCallWithCompletedResult(t *testing.T) {
userPayload, err := protojson.Marshal(&agentv1.UserMessage{Text: "inspect file", MessageId: "message-1"})
if err != nil {
t.Fatalf("marshal user message: %v", err)
}
startedAt := uint64(100)
toolCallID := "call-1"
startedToolCall := checkpointTestToolCallPayload(t, &agentv1.ToolCall{
ToolCallId: &toolCallID,
StartedAtMs: &startedAt,
Tool: &agentv1.ToolCall_ReadToolCall{
ReadToolCall: &agentv1.ReadToolCall{
Args: &agentv1.ReadToolArgs{Path: "/tmp/example.txt"},
},
},
})
completedAt := uint64(200)
completedToolCall := checkpointTestToolCallPayload(t, &agentv1.ToolCall{
CompletedAtMs: &completedAt,
Tool: &agentv1.ToolCall_ReadToolCall{
ReadToolCall: &agentv1.ReadToolCall{
Result: &agentv1.ReadToolResult{
Result: &agentv1.ReadToolResult_Success{
Success: &agentv1.ReadToolSuccess{
Path: "/tmp/example.txt",
TotalLines: 1,
Output: &agentv1.ReadToolSuccess_Content{Content: "file contents"},
},
},
},
},
},
})
conversation := &ConversationFile{
ConversationID: "conversation-1",
Mode: "agent",
NextTurnSeq: 2,
Entries: []HistoryEntry{
{Seq: 1, TurnSeq: 1, RequestID: "request-1", Role: "user", Kind: "user_message", Payload: userPayload},
newAssistantTextEntry(1, "request-1", "before", "", ""),
newToolCallEntry(1, "request-1", "call-1", "Read", "", "", startedToolCall),
newToolResultEntry(1, "request-1", "call-1", "Read", `{"path":"/tmp/example.txt"}`, "file contents", "", completedToolCall),
newAssistantTextEntry(1, "request-1", "after", "", ""),
},
}
projection, err := NewHistoryProjector().ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
if len(projection.Blobs) != 5 {
t.Fatalf("checkpoint blobs = %d, want user, three final steps, and turn", len(projection.Blobs))
}
steps := checkpointProjectionSteps(t, projection)
if len(steps) != 3 {
t.Fatalf("checkpoint steps = %d, want assistant, completed Read, assistant", len(steps))
}
if steps[0].GetAssistantMessage().GetText() != "before" || steps[2].GetAssistantMessage().GetText() != "after" {
t.Fatalf("checkpoint step ordering changed: %#v", steps)
}
mergedToolCall := steps[1].GetToolCall()
readCall := mergedToolCall.GetReadToolCall()
if readCall == nil || readCall.GetResult().GetSuccess().GetContent() != "file contents" {
t.Fatalf("checkpoint Read step does not contain completed result: %#v", steps[1].GetToolCall())
}
if readCall.GetArgs().GetPath() != "/tmp/example.txt" || mergedToolCall.GetToolCallId() != toolCallID || mergedToolCall.GetStartedAtMs() != startedAt || mergedToolCall.GetCompletedAtMs() != completedAt {
t.Fatalf("checkpoint Read step lost started-call fields: %#v", mergedToolCall)
}
replay, err := promptengine.DecodeReplayMessages(projection.State.GetRootPromptMessagesJson())
if err != nil {
t.Fatalf("decode root prompt replay: %v", err)
}
for _, message := range replay {
if message.Name == "Read" || len(message.ToolCalls) > 0 {
t.Fatalf("UI-only Read result leaked into root prompt replay: %#v", replay)
}
}
}
func TestProjectCheckpointProjectionIsIdempotentAndDoesNotMutateHistory(t *testing.T) {
userPayload, err := protojson.Marshal(&agentv1.UserMessage{Text: "inspect file", MessageId: "message-1"})
if err != nil {
t.Fatalf("marshal user message: %v", err)
}
completedToolCall := checkpointTestReadToolCall(t, &agentv1.ReadToolResult{
Result: &agentv1.ReadToolResult_Success{
Success: &agentv1.ReadToolSuccess{
Path: "/tmp/example.txt",
TotalLines: 1,
Output: &agentv1.ReadToolSuccess_Content{Content: "file contents"},
},
},
})
conversation := &ConversationFile{
ConversationID: "conversation-1",
Mode: "agent",
NextTurnSeq: 2,
Entries: []HistoryEntry{
{Seq: 1, TurnSeq: 1, RequestID: "request-1", Role: "user", Kind: "user_message", Payload: userPayload},
newToolCallEntry(1, "request-1", "call-1", "Read", "", "", checkpointTestReadToolCall(t, nil)),
newToolResultEntry(1, "request-1", "call-1", "Read", `{"path":"/tmp/example.txt"}`, "file contents", "", completedToolCall),
},
}
before, err := json.Marshal(conversation)
if err != nil {
t.Fatalf("marshal conversation before projection: %v", err)
}
projector := NewHistoryProjector()
first, err := projector.ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("first projection: %v", err)
}
second, err := projector.ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("second projection: %v", err)
}
if !proto.Equal(first.State, second.State) {
t.Fatalf("repeated projection changed checkpoint state: first=%#v second=%#v", first.State, second.State)
}
if len(first.Blobs) != len(second.Blobs) {
t.Fatalf("repeated projection changed blob count: first=%d second=%d", len(first.Blobs), len(second.Blobs))
}
for index := range first.Blobs {
if !bytes.Equal(first.Blobs[index].ID, second.Blobs[index].ID) || !bytes.Equal(first.Blobs[index].Data, second.Blobs[index].Data) {
t.Fatalf("repeated projection changed blob %d", index)
}
}
after, err := json.Marshal(conversation)
if err != nil {
t.Fatalf("marshal conversation after projection: %v", err)
}
if !bytes.Equal(before, after) {
t.Fatalf("checkpoint projection mutated semantic history:\nbefore=%s\nafter=%s", before, after)
}
}
func TestProjectCheckpointProjectionKeepsStartedToolCallWhenResultPayloadIsMissing(t *testing.T) {
startedToolCall := checkpointTestReadToolCall(t, nil)
conversation := &ConversationFile{
ConversationID: "conversation-1",
Mode: "agent",
NextTurnSeq: 2,
Entries: []HistoryEntry{
newToolCallEntry(1, "request-1", "call-1", "Read", "", "", startedToolCall),
newToolResultEntry(1, "request-1", "call-1", "Read", `{"path":"/tmp/example.txt"}`, "read failed", "", nil),
},
}
projection, err := NewHistoryProjector().ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
steps := checkpointProjectionSteps(t, projection)
if len(steps) != 1 {
t.Fatalf("checkpoint steps = %d, want the original Read step", len(steps))
}
readCall := steps[0].GetToolCall().GetReadToolCall()
if readCall == nil || readCall.GetArgs().GetPath() != "/tmp/example.txt" || readCall.GetResult() != nil {
t.Fatalf("checkpoint did not preserve the original Read call: %#v", steps[0].GetToolCall())
}
}
func TestProjectCheckpointProjectionAppendsLegacyResultWithoutToolCallEntry(t *testing.T) {
completedToolCall := checkpointTestReadToolCall(t, &agentv1.ReadToolResult{
Result: &agentv1.ReadToolResult_Error{Error: &agentv1.ReadToolError{ErrorMessage: "not readable"}},
})
conversation := &ConversationFile{
ConversationID: "conversation-1",
Mode: "agent",
NextTurnSeq: 2,
Entries: []HistoryEntry{
newToolResultEntry(1, "request-1", "call-1", "Read", `{"path":"/tmp/example.txt"}`, "not readable", "", completedToolCall),
},
}
projection, err := NewHistoryProjector().ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
steps := checkpointProjectionSteps(t, projection)
if len(steps) != 1 || steps[0].GetToolCall().GetReadToolCall().GetResult().GetError().GetErrorMessage() != "not readable" {
t.Fatalf("legacy result-only Read step was not preserved: %#v", steps)
}
}
func checkpointTestReadToolCall(t *testing.T, result *agentv1.ReadToolResult) []byte {
t.Helper()
return checkpointTestToolCallPayload(t, &agentv1.ToolCall{
Tool: &agentv1.ToolCall_ReadToolCall{
ReadToolCall: &agentv1.ReadToolCall{
Args: &agentv1.ReadToolArgs{Path: "/tmp/example.txt"},
Result: result,
},
},
})
}
func checkpointTestToolCallPayload(t *testing.T, toolCall *agentv1.ToolCall) []byte {
t.Helper()
payload, err := protojson.Marshal(toolCall)
if err != nil {
t.Fatalf("marshal Read tool call: %v", err)
}
return payload
}
func checkpointProjectionSteps(t *testing.T, projection *CheckpointProjection) []*agentv1.ConversationStep {
t.Helper()
if projection == nil || projection.State == nil || len(projection.State.GetTurns()) != 1 {
t.Fatalf("checkpoint turns = %#v, want exactly one turn", projection)
}
blobs := make(map[string][]byte, len(projection.Blobs))
for _, blob := range projection.Blobs {
blobs[string(blob.ID)] = blob.Data
}
turn := &agentv1.ConversationTurnStructure{}
if err := proto.Unmarshal(blobs[string(projection.State.GetTurns()[0])], turn); err != nil {
t.Fatalf("decode checkpoint turn: %v", err)
}
agentTurn := turn.GetAgentConversationTurn()
if agentTurn == nil {
t.Fatal("checkpoint turn does not contain an agent turn")
}
steps := make([]*agentv1.ConversationStep, 0, len(agentTurn.GetSteps()))
for _, stepID := range agentTurn.GetSteps() {
step := &agentv1.ConversationStep{}
if err := proto.Unmarshal(blobs[string(stepID)], step); err != nil {
t.Fatalf("decode checkpoint step: %v", err)
}
steps = append(steps, step)
}
return steps
}
@@ -1,433 +0,0 @@
package forwarder
import (
"crypto/sha256"
"encoding/json"
"fmt"
"strings"
"testing"
"google.golang.org/protobuf/encoding/protojson"
"google.golang.org/protobuf/proto"
"cursor/gen/agentv1"
modeladapter "cursor/internal/backend/agent/model"
promptengine "cursor/internal/backend/agent/prompt"
)
func TestProjectCheckpointProjectionBuildsBlobBackedTurns(t *testing.T) {
toolCall := testEditToolCall(t, "file.txt")
tests := []struct {
name string
entries []HistoryEntry
}{
{
name: "no tools",
entries: []HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "hello"),
newAssistantTextEntry(1, "request-1", "hi", "", ""),
},
},
{
name: "completed tool call",
entries: []HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "edit the file"),
newToolCallEntry(1, "request-1", "call-1", "Edit", "", "", toolCall),
newToolResultEntry(1, "request-1", "call-1", "Edit", `{"path":"file.txt"}`, "edited", "", toolCall),
newAssistantTextEntry(1, "request-1", "done", "", ""),
},
},
{
name: "unfinished tool call",
entries: []HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "edit the file"),
newToolCallEntry(1, "request-1", "call-1", "Edit", "", "", toolCall),
},
},
{
name: "orphan tool result",
entries: []HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "edit the file"),
newToolResultEntry(1, "request-1", "call-1", "Edit", `{"path":"file.txt"}`, "edited", "", toolCall),
},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
conversation := testConversation(test.entries)
projection, err := NewHistoryProjector().ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
if len(projection.State.GetTurns()) != 1 {
t.Fatalf("ProjectCheckpointProjection() turns = %d, want 1 Blob ID", len(projection.State.GetTurns()))
}
assertCheckpointBlobGraph(t, projection)
messages, err := promptengine.DecodeReplayMessages(projection.State.GetRootPromptMessagesJson())
if err != nil {
t.Fatalf("DecodeReplayMessages() error = %v", err)
}
if len(messages) == 0 {
t.Fatal("ProjectCheckpointProjection() removed all root prompt replay history")
}
if messages[0].Role != "user" || messages[0].Content == "" {
t.Fatalf("first replay message = %#v, want retained user history", messages[0])
}
})
}
}
func TestProjectLegacyCheckpointLargeModelHistoryUsesRootReplay(t *testing.T) {
entries := make([]HistoryEntry, 0, 400)
for turn := int64(1); turn <= 200; turn++ {
requestID := fmt.Sprintf("request-%d", turn)
entries = append(entries,
testModelMessageEntry(t, turn, requestID, modeladapter.Message{Role: "user", Content: fmt.Sprintf("question %d", turn)}),
testModelMessageEntry(t, turn, requestID, modeladapter.Message{Role: "assistant", Content: fmt.Sprintf("answer %d", turn)}),
)
}
state, err := NewHistoryProjector().ProjectLegacyCheckpoint(testConversation(entries))
if err != nil {
t.Fatalf("ProjectLegacyCheckpoint() error = %v", err)
}
if len(state.GetTurns()) != 0 {
t.Fatalf("ProjectLegacyCheckpoint() model-only turns = %d, want 0", len(state.GetTurns()))
}
messages, err := promptengine.DecodeReplayMessages(state.GetRootPromptMessagesJson())
if err != nil {
t.Fatalf("DecodeReplayMessages() error = %v", err)
}
if len(messages) != 400 {
t.Fatalf("decoded replay messages = %d, want 400", len(messages))
}
}
func TestProjectLegacyCheckpointSnapshotIsIsolatedFromLaterHistory(t *testing.T) {
conversation := testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "first question"),
newAssistantTextEntry(1, "request-1", "first answer", "", ""),
})
projector := NewHistoryProjector()
midpointProjection, err := projector.ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("midpoint ProjectCheckpointProjection() error = %v", err)
}
midpoint := midpointProjection.State
appendEntriesInPlace(conversation, []HistoryEntry{
testUserMessageEntry(t, 2, "request-2", "second question"),
newAssistantTextEntry(2, "request-2", "second answer", "", ""),
})
latestProjection, err := projector.ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("latest ProjectCheckpointProjection() error = %v", err)
}
latest := latestProjection.State
midpointMessages, err := promptengine.DecodeReplayMessages(midpoint.GetRootPromptMessagesJson())
if err != nil {
t.Fatalf("decode midpoint replay: %v", err)
}
latestMessages, err := promptengine.DecodeReplayMessages(latest.GetRootPromptMessagesJson())
if err != nil {
t.Fatalf("decode latest replay: %v", err)
}
if len(midpointMessages) != 2 {
t.Fatalf("midpoint replay messages = %d, want 2", len(midpointMessages))
}
if len(latestMessages) != 4 {
t.Fatalf("latest replay messages = %d, want 4", len(latestMessages))
}
if len(midpoint.GetTurns()) != 1 || len(latest.GetTurns()) != 2 {
t.Fatalf("checkpoint turn counts = (%d, %d), want (1, 2)", len(midpoint.GetTurns()), len(latest.GetTurns()))
}
assertCheckpointBlobGraph(t, midpointProjection)
assertCheckpointBlobGraph(t, latestProjection)
}
func TestProjectCheckpointProjectionKeepsVisibleTurnsAcrossCompaction(t *testing.T) {
summaryPayload, err := json.Marshal(compactionSummaryEntryPayload{Summary: "first turn summarized"})
if err != nil {
t.Fatalf("marshal compaction summary: %v", err)
}
conversation := testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "first question"),
newAssistantTextEntry(1, "request-1", "first answer", "", ""),
{TurnSeq: 0, Role: "system", Kind: "compaction_summary", Payload: summaryPayload},
testUserMessageEntry(t, 2, "request-2", "second question"),
newAssistantTextEntry(2, "request-2", "second answer", "", ""),
})
projection, err := NewHistoryProjector().ProjectCheckpointProjection(conversation)
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
if len(projection.State.GetTurns()) != 2 {
t.Fatalf("visible turns after compaction = %d, want 2", len(projection.State.GetTurns()))
}
assertCheckpointBlobGraph(t, projection)
messages, err := promptengine.DecodeReplayMessages(projection.State.GetRootPromptMessagesJson())
if err != nil {
t.Fatalf("DecodeReplayMessages() error = %v", err)
}
if len(messages) != 3 {
t.Fatalf("compacted root replay messages = %d, want summary plus latest turn", len(messages))
}
if messages[0].Role != "user" || messages[0].Content != "<conversation_summary>\nfirst turn summarized\n</conversation_summary>" {
t.Fatalf("first compacted replay message = %#v", messages[0])
}
}
func TestImportedConversationStateRejectsBlobTurnIDsWithoutPrefetchedData(t *testing.T) {
turnID := sha256.Sum256([]byte("imported turn"))
state := &agentv1.ConversationStateStructure{Turns: [][]byte{turnID[:]}}
if _, err := importedConversationStateModelMessages(state, nil); err == nil {
t.Fatal("importedConversationStateModelMessages() accepted unresolved Blob turn")
}
conversation := testConversation(nil)
service := &Service{}
if _, err := service.importConversationState(conversation, state, nil); err == nil {
t.Fatal("importConversationState() accepted unresolved Blob turn")
}
}
func TestImportedConversationStateRestoresBlobOnlyForkFromPrefetchedBlobs(t *testing.T) {
projection, err := NewHistoryProjector().ProjectCheckpointProjection(testConversation([]HistoryEntry{
testUserMessageEntry(t, 1, "request-1", "parent question"),
newAssistantTextEntry(1, "request-1", "parent answer", "", ""),
}))
if err != nil {
t.Fatalf("ProjectCheckpointProjection() error = %v", err)
}
prefetched := make([]*agentv1.PreFetchedBlob, 0, len(projection.Blobs))
for _, blob := range projection.Blobs {
prefetched = append(prefetched, &agentv1.PreFetchedBlob{Id: blob.ID, Value: blob.Data})
}
state := proto.Clone(projection.State).(*agentv1.ConversationStateStructure)
state.RootPromptMessagesJson = nil
conversation := testConversation(nil)
entries, err := (&Service{}).importConversationState(conversation, state, prefetched)
if err != nil {
t.Fatalf("importConversationState() error = %v", err)
}
if len(conversation.ImportedTurnIDs) != 1 {
t.Fatalf("ImportedTurnIDs = %d, want 1", len(conversation.ImportedTurnIDs))
}
if len(entries) != 2 {
t.Fatalf("imported model entries = %d, want user and assistant", len(entries))
}
}
func TestImportedInlineTurnWithSHA256LengthIsNotMisclassified(t *testing.T) {
var rawTurn []byte
for size := 1; size <= 128; size++ {
rawUser, err := proto.Marshal(&agentv1.UserMessage{Text: strings.Repeat("x", size), MessageId: "inline"})
if err != nil {
t.Fatalf("marshal user message: %v", err)
}
rawTurn, err = proto.Marshal(&agentv1.ConversationTurnStructure{
Turn: &agentv1.ConversationTurnStructure_AgentConversationTurn{
AgentConversationTurn: &agentv1.AgentConversationTurnStructure{UserMessage: rawUser},
},
})
if err != nil {
t.Fatalf("marshal turn: %v", err)
}
if len(rawTurn) == sha256.Size {
break
}
}
if len(rawTurn) != sha256.Size {
t.Fatal("test could not construct a 32-byte inline turn")
}
ids, err := importedTurnIDs([][]byte{rawTurn}, nil)
if err != nil {
t.Fatalf("importedTurnIDs() error = %v", err)
}
if len(ids) != 0 {
t.Fatal("32-byte inline turn was misclassified as a Blob ID")
}
messages, err := importedConversationStateModelMessages(&agentv1.ConversationStateStructure{Turns: [][]byte{rawTurn}}, nil)
if err != nil {
t.Fatalf("importedConversationStateModelMessages() error = %v", err)
}
if len(messages) != 1 || messages[0].Role != "user" {
t.Fatalf("inline turn messages = %#v, want one user message", messages)
}
}
func TestImportedTurnIDsPersistThroughConversationStore(t *testing.T) {
store := NewConversationFileStore(t.TempDir())
turnID := sha256.Sum256([]byte("parent turn"))
conversation := testConversation(nil)
conversation.ImportedTurnIDs = [][]byte{turnID[:]}
persisted, err := store.SaveConversationWithEntries(conversation.ConversationID, conversation, []HistoryEntry{
testUserMessageEntry(t, 2, "request-2", "fork question"),
})
if err != nil {
t.Fatalf("SaveConversationWithEntries() error = %v", err)
}
if len(persisted.ImportedTurnIDs) != 1 || string(persisted.ImportedTurnIDs[0]) != string(turnID[:]) {
t.Fatalf("persisted ImportedTurnIDs = %x, want %x", persisted.ImportedTurnIDs, turnID)
}
loaded, err := store.LoadConversation(conversation.ConversationID)
if err != nil {
t.Fatalf("LoadConversation() error = %v", err)
}
if len(loaded.ImportedTurnIDs) != 1 || string(loaded.ImportedTurnIDs[0]) != string(turnID[:]) {
t.Fatalf("loaded ImportedTurnIDs = %x, want %x", loaded.ImportedTurnIDs, turnID)
}
}
func TestRewindImportedTurnPrefixUsesClientForkPoint(t *testing.T) {
ids := make([][]byte, 4)
for index := range ids {
digest := sha256.Sum256([]byte(fmt.Sprintf("turn-%d", index+1)))
ids[index] = digest[:]
}
trimmed := rewindImportedTurnPrefix(ids, runRewindDecision{
TargetTurnSeq: 4,
HasClientTurnCount: true,
ClientTurnCount: 2,
})
if len(trimmed) != 2 || string(trimmed[0]) != string(ids[0]) || string(trimmed[1]) != string(ids[1]) {
t.Fatalf("rewindImportedTurnPrefix() = %x, want first two IDs", trimmed)
}
}
func TestRewindImportedTurnPrefixClearsAllIDsAtClientTurnZero(t *testing.T) {
ids := make([][]byte, 2)
for index := range ids {
digest := sha256.Sum256([]byte(fmt.Sprintf("turn-%d", index+1)))
ids[index] = digest[:]
}
trimmed := rewindImportedTurnPrefix(ids, runRewindDecision{
TargetTurnSeq: 3,
HasClientTurnCount: true,
ClientTurnCount: 0,
})
if trimmed != nil {
t.Fatalf("rewindImportedTurnPrefix() = %x, want nil at client turn zero", trimmed)
}
}
func TestRewindImportedTurnPrefixUsesTargetWithoutClientCount(t *testing.T) {
ids := make([][]byte, 4)
for index := range ids {
digest := sha256.Sum256([]byte(fmt.Sprintf("turn-%d", index+1)))
ids[index] = digest[:]
}
trimmed := rewindImportedTurnPrefix(ids, runRewindDecision{TargetTurnSeq: 3})
if len(trimmed) != 2 || string(trimmed[0]) != string(ids[0]) || string(trimmed[1]) != string(ids[1]) {
t.Fatalf("rewindImportedTurnPrefix() = %x, want target-derived first two IDs", trimmed)
}
}
func assertCheckpointBlobGraph(t *testing.T, projection *CheckpointProjection) {
t.Helper()
if projection == nil || projection.State == nil {
t.Fatal("checkpoint projection is nil")
}
blobByID := make(map[string][]byte, len(projection.Blobs))
for _, blob := range projection.Blobs {
if len(blob.ID) != sha256.Size {
t.Fatalf("blob id length = %d, want %d", len(blob.ID), sha256.Size)
}
digest := sha256.Sum256(blob.Data)
if string(blob.ID) != string(digest[:]) {
t.Fatal("blob id does not match SHA-256(data)")
}
blobByID[string(blob.ID)] = blob.Data
}
for _, turnID := range projection.State.GetTurns() {
turnData, ok := blobByID[string(turnID)]
if !ok {
t.Fatal("turn references missing blob")
}
turn := &agentv1.ConversationTurnStructure{}
if err := proto.Unmarshal(turnData, turn); err != nil {
t.Fatalf("decode turn blob: %v", err)
}
agentTurn := turn.GetAgentConversationTurn()
if agentTurn == nil {
continue
}
if userID := agentTurn.GetUserMessage(); len(userID) > 0 {
userData, exists := blobByID[string(userID)]
if !exists {
t.Fatal("turn references missing user message blob")
}
if err := proto.Unmarshal(userData, &agentv1.UserMessage{}); err != nil {
t.Fatalf("decode user message blob: %v", err)
}
}
for _, stepID := range agentTurn.GetSteps() {
stepData, exists := blobByID[string(stepID)]
if !exists {
t.Fatal("turn references missing step blob")
}
if err := proto.Unmarshal(stepData, &agentv1.ConversationStep{}); err != nil {
t.Fatalf("decode conversation step blob: %v", err)
}
}
}
}
func testConversation(entries []HistoryEntry) *ConversationFile {
conversation := &ConversationFile{
ConversationID: "conversation-1",
RootConversationID: "conversation-1",
Mode: "agent",
NextTurnSeq: 1,
NextEntrySeq: 1,
Entries: make([]HistoryEntry, 0, len(entries)),
}
appendEntriesInPlace(conversation, entries)
return conversation
}
func testUserMessageEntry(t *testing.T, turnSeq int64, requestID string, text string) HistoryEntry {
t.Helper()
payload, err := protojson.Marshal(&agentv1.UserMessage{Text: text, MessageId: fmt.Sprintf("message-%d", turnSeq)})
if err != nil {
t.Fatalf("marshal user message: %v", err)
}
return HistoryEntry{
TurnSeq: turnSeq,
RequestID: requestID,
Role: "user",
Kind: "user_message",
Payload: payload,
}
}
func testModelMessageEntry(t *testing.T, turnSeq int64, requestID string, message modeladapter.Message) HistoryEntry {
t.Helper()
entry, ok, err := newModelMessageEntry(turnSeq, requestID, message)
if err != nil {
t.Fatalf("newModelMessageEntry() error = %v", err)
}
if !ok {
t.Fatal("newModelMessageEntry() rejected test message")
}
return entry
}
func testEditToolCall(t *testing.T, path string) []byte {
t.Helper()
payload, err := protojson.Marshal(&agentv1.ToolCall{
Tool: &agentv1.ToolCall_EditToolCall{
EditToolCall: &agentv1.EditToolCall{
Args: &agentv1.EditArgs{Path: path},
},
},
})
if err != nil {
t.Fatalf("marshal edit tool call: %v", err)
}
return payload
}
+2 -23
View File
@@ -36,7 +36,7 @@ type runRewindMatch struct {
}
func (service *Service) decideRunRewind(intent InboundIntent, conversation *ConversationFile) runRewindDecision {
decision := runRewindDecision{}
decision := runRewindDecision{ClientTurnCount: -1}
if !shouldEvaluateRunRewind(intent) {
return decision
}
@@ -121,7 +121,7 @@ func selectRunRewindMatch(matches []runRewindMatch, clientTurnCount int, hasClie
if len(matches) == 0 {
return runRewindMatch{}, "no_match"
}
if hasClientTurnCount {
if hasClientTurnCount && clientTurnCount >= 0 {
targetTurnSeq := int64(clientTurnCount) + 1
for _, match := range matches {
if match.Entry.TurnSeq == targetTurnSeq {
@@ -224,7 +224,6 @@ func (service *Service) applyRunRewindToConversation(conversation *ConversationF
conversation.Entries = nil
conversation.NextEntrySeq = 1
conversation.NextTurnSeq = 1
conversation.ImportedTurnIDs = rewindImportedTurnPrefix(conversation.ImportedTurnIDs, decision)
appendEntriesInPlace(conversation, appendReplacementRunEntries(decision.PrefixEntries, entries))
applyRunRewindConversationState(conversation, intent, turnSeq)
deriveConversationLoopState(conversation)
@@ -270,30 +269,10 @@ func applyRunRewindMetadata(conversation *ConversationFile, source *Conversation
if source.TokenDetailsMaxTokens > 0 {
conversation.TokenDetailsMaxTokens = source.TokenDetailsMaxTokens
}
decision := runRewindDecision{TargetTurnSeq: turnSeq}
if intent.ConversationState != nil {
decision.HasClientTurnCount = true
decision.ClientTurnCount = len(intent.ConversationState.GetTurns())
}
conversation.ImportedTurnIDs = rewindImportedTurnPrefix(source.ImportedTurnIDs, decision)
}
applyRunRewindConversationState(conversation, intent, turnSeq)
}
func rewindImportedTurnPrefix(importedTurnIDs [][]byte, decision runRewindDecision) [][]byte {
keep := decision.TargetTurnSeq - 1
if decision.HasClientTurnCount {
keep = int64(decision.ClientTurnCount)
}
if keep <= 0 || len(importedTurnIDs) == 0 {
return nil
}
if keep > int64(len(importedTurnIDs)) {
keep = int64(len(importedTurnIDs))
}
return cloneByteSlices(importedTurnIDs[:keep])
}
func (service *Service) logRunRewindDecision(requestID string, conversationID string, eventName string, decision runRewindDecision) {
if service == nil || !decision.Evaluated {
return
@@ -50,7 +50,7 @@ func (service *Service) bootstrapRuntimeConversation(intent InboundIntent) (*Con
}
importedEntries := []HistoryEntry(nil)
if len(conversation.Entries) == 0 && intent.ConversationState != nil {
importedEntries, err = service.importConversationState(conversation, intent.ConversationState, intent.PreFetchedBlobs)
importedEntries, err = service.importConversationState(conversation, intent.ConversationState)
if err != nil {
return nil, agentv1.AgentMode_AGENT_MODE_AGENT, 0, nil, err
}
@@ -138,7 +138,6 @@ func (service *Service) syncConversationRecord(conversationID string, conversati
item.AutoCompactionReserveTokens = conversation.AutoCompactionReserveTokens
item.AutoCompactionTriggeredAt = conversation.AutoCompactionTriggeredAt
item.AutoCompactionSourceModelCallID = conversation.AutoCompactionSourceModelCallID
item.ImportedTurnIDs = cloneByteSlices(conversation.ImportedTurnIDs)
item.LatestRequestPrefix = cloneConversationRequestPrefix(conversation.LatestRequestPrefix)
item.LastProviderCall = cloneConversationProviderCall(conversation.LastProviderCall)
item.CreatedAt = conversation.CreatedAt
+126 -66
View File
@@ -3,13 +3,14 @@ package forwarder
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"log"
"sort"
"strings"
"sync"
"time"
"connectrpc.com/connect"
@@ -262,8 +263,6 @@ type Service struct {
execBridge execbridge.ExecBridge
interactionBridge interactionbridge.InteractionBridge
appendSeq *appendSequenceTracker
checkpointBlobMu sync.Mutex
checkpointBlobs map[string]*checkpointBlobCacheEntry
}
type agentModelMemory interface {
@@ -303,7 +302,6 @@ func NewService(historyRoot string, resolver modeladapter.ChannelResolver) *Serv
execBridge: execbridge.NewBridge(),
interactionBridge: interactionbridge.NewBridge(),
appendSeq: newAppendSequenceTracker(),
checkpointBlobs: make(map[string]*checkpointBlobCacheEntry),
}
service.startHistoryMaintenance()
store.SyncAllCursorTranscriptsBestEffort()
@@ -332,7 +330,6 @@ func newServiceWithDependencies(store *ConversationFileStore, projector *History
execBridge: execbridge.NewBridge(),
interactionBridge: interactionbridge.NewBridge(),
appendSeq: newAppendSequenceTracker(),
checkpointBlobs: make(map[string]*checkpointBlobCacheEntry),
}
}
@@ -562,7 +559,6 @@ func (service *Service) decodeInboundIntent(requestID string, message *agentv1.A
}
intent.ConversationID = conversationID
intent.ConversationState = runRequest.GetConversationState()
intent.PreFetchedBlobs = runRequest.GetPreFetchedBlobs()
intent.UserMessage = extractUserMessage(message)
intent.RequestContext = extractRequestContext(message)
if service.shouldIgnoreEmptyResumeRunRequest(requestID, runRequest, intent.UserMessage, intent.RequestContext) {
@@ -610,7 +606,6 @@ func (service *Service) decodeInboundIntent(requestID string, message *agentv1.A
intent.ConversationID = conversationID
intent.SubagentTypeName = strings.TrimSpace(prewarmRequest.GetSubagentTypeName())
intent.ConversationState = prewarmRequest.GetConversationState()
intent.PreFetchedBlobs = prewarmRequest.GetPreFetchedBlobs()
intent.Mode, intent.ModeSource, intent.HasExplicitMode, err = extractPrewarmMode(prewarmRequest)
if err != nil {
return InboundIntent{}, err
@@ -826,14 +821,11 @@ func (service *Service) snapshotVisibleTurns(conversation *ConversationFile) ([]
if service == nil || service.projector == nil || conversation == nil {
return nil, nil
}
projection, err := service.projector.ProjectCheckpointProjection(conversation)
state, err := service.projector.ProjectLegacyCheckpoint(conversation)
if err != nil {
return nil, err
}
if projection == nil || projection.State == nil {
return nil, fmt.Errorf("checkpoint projection is empty")
}
return cloneByteSlices(projection.State.GetTurns()), nil
return cloneByteSlices(state.GetTurns()), nil
}
// handleCancelIntent 处理取消请求,并向客户端发送执行桥 abort。
@@ -843,60 +835,131 @@ func (service *Service) handleCancelIntent(intent InboundIntent) error {
return fmt.Errorf("request is not active: %s", intent.RequestID)
}
hasCheckpoint := checkpointConversationInitialized(stream)
if hasCheckpoint {
preservedInterruptedOutput, err := service.persistInterruptedProviderOutput(stream)
if err != nil {
return err
}
cancelReason := firstNonEmpty(intent.CancelReason, "user aborted")
replayPolicy := cancelReplayPolicyForReason(cancelReason)
if preservedInterruptedOutput || checkpointTurnHasReplayActivity(stream) {
replayPolicy = cancelReplayPolicyKeepInterrupted
}
cancelEntry := newMetadataEntry(stream.TurnSeq, intent.RequestID, "control", map[string]any{
"status": "canceled",
"reason": cancelReason,
"replay_policy": replayPolicy,
})
cancelEntry.IdempotencyKey = cancelMetadataIdempotencyKey(stream.TurnSeq, intent.RequestID)
_, err = service.appendConversationEntries(stream, stream.ConversationID, []HistoryEntry{cancelEntry})
if err != nil {
return err
}
}
stream.mu.Lock()
pendingExecs := make([]runtimecore.PendingExec, 0, len(stream.PendingExecs))
for _, pending := range stream.PendingExecs {
pendingExecs = append(pendingExecs, pending)
}
if stream.ProviderCancel != nil {
stream.ProviderCancel()
stream.ProviderCancel = nil
}
stream.ProviderActive = false
stream.CurrentProviderToken++
stream.CurrentCompactionToken++
stream.PendingProviderAction = providerActionNone
stream.PendingCompaction = nil
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
if hasCheckpoint {
cancelReason := firstNonEmpty(intent.CancelReason, "user aborted")
cancelEntry := newMetadataEntry(stream.TurnSeq, intent.RequestID, "control", map[string]any{
"status": "canceled",
"reason": cancelReason,
"replay_policy": cancelReplayPolicyForReason(cancelReason),
})
if _, err := service.appendConversationEntries(stream, stream.ConversationID, []HistoryEntry{cancelEntry}); err != nil {
log.Printf("forwarder cancellation metadata persistence failed request_id=%s conversation_id=%s err=%v", stream.RequestID, stream.ConversationID, err)
if memoryErr := service.appendCheckpointEntries(stream, []HistoryEntry{cancelEntry}); memoryErr != nil {
return memoryErr
}
}
}
for _, pending := range pendingExecs {
_ = service.broker.Publish(intent.RequestID, StreamEvent{
Message: buildExecAbortMessage(pending),
})
}
if hasCheckpoint {
service.discardPendingCheckpoint(stream, "checkpoint superseded by cancellation")
}
clearPendingProviderCompletion(stream)
terminalMessage := firstNonEmpty(intent.CancelReason, "[canceled] User aborted request")
stream.mu.Lock()
stream.PendingExecs = make(map[string]runtimecore.PendingExec)
stream.PendingInteractions = make(map[string]runtimecore.PendingInteraction)
stream.PendingProviderAction = providerActionNone
stream.UpdatedAt = time.Now().UTC()
stream.mu.Unlock()
service.discardPendingCheckpoint(stream, fmt.Errorf("checkpoint superseded by cancellation"))
if hasCheckpoint {
if err := service.publishCheckpointWithTerminalAction(
stream.RequestID,
stream.ConversationID,
checkpointCancellationAction(terminalMessage),
); err != nil {
return service.failTerminalCheckpointSync(stream, err)
service.setTurnPhase(stream, TurnPhaseCanceled)
return service.broker.Cancel(intent.RequestID, firstNonEmpty(intent.CancelReason, "[canceled] User aborted request"))
}
func checkpointTurnHasReplayActivity(stream *ActiveStream) bool {
if stream == nil {
return false
}
return nil
stream.mu.Lock()
defer stream.mu.Unlock()
if stream.CheckpointConversation == nil {
return false
}
return service.finishCanceledTurnAfterCheckpoint(stream, terminalMessage)
for _, entry := range stream.CheckpointConversation.Entries {
if entry.TurnSeq == stream.TurnSeq && isCanceledTurnActivityEntry(entry) {
return true
}
}
return false
}
// persistInterruptedProviderOutput commits the current provider pass before cancellation.
// The entry key is stable for this provider pass, so repeated cancellation handling is a no-op.
func (service *Service) persistInterruptedProviderOutput(stream *ActiveStream) (bool, error) {
if stream == nil {
return false, nil
}
stream.mu.Lock()
turnSeq := stream.TurnSeq
requestID := strings.TrimSpace(stream.RequestID)
modelCallID := strings.TrimSpace(stream.CurrentModelCallID)
providerPass := stream.ProviderPassCount
text := stream.ProviderAccumulatedText
reasoning := stream.ProviderAccumulatedReasoning
reasoningSignature := stream.ProviderAccumulatedReasoningSignature
reasoningSignatureSource := stream.ProviderAccumulatedReasoningSignatureSource
reasoningItemID := stream.ProviderAccumulatedReasoningItemID
reasoningStatus := stream.ProviderAccumulatedReasoningStatus
reasoningSummary := append([]byte(nil), stream.ProviderAccumulatedReasoningSummary...)
stream.mu.Unlock()
if strings.TrimSpace(text) == "" && !hasReplayableReasoningPayload(reasoning, reasoningSignature, reasoningSignatureSource) {
return false, nil
}
key := interruptedProviderOutputIdempotencyKey(turnSeq, requestID, modelCallID, providerPass)
_, err := service.appendConversationEntries(stream, stream.ConversationID, []HistoryEntry{
{
TurnSeq: turnSeq,
RequestID: requestID,
IdempotencyKey: key,
Role: "assistant",
Kind: "assistant_text",
Payload: newAssistantTextPayload(
text,
reasoning,
reasoningSignature,
reasoningSignatureSource,
reasoningItemID,
reasoningStatus,
reasoningSummary,
),
},
})
return true, err
}
func interruptedProviderOutputIdempotencyKey(turnSeq int64, requestID string, modelCallID string, providerPass int) string {
payload := strings.Join([]string{
"provider_interrupted_output",
fmt.Sprintf("%d", turnSeq),
strings.TrimSpace(requestID),
strings.TrimSpace(modelCallID),
fmt.Sprintf("%d", providerPass),
}, "\x00")
digest := sha256.Sum256([]byte(payload))
return "provider-interrupted-output:" + hex.EncodeToString(digest[:])
}
func cancelMetadataIdempotencyKey(turnSeq int64, requestID string) string {
payload := strings.Join([]string{
"cancel",
fmt.Sprintf("%d", turnSeq),
strings.TrimSpace(requestID),
}, "\x00")
digest := sha256.Sum256([]byte(payload))
return "cancel:" + hex.EncodeToString(digest[:])
}
// handleExecResult 处理客户端返回的执行桥结果,并在终态时把 tool_result 写回 history。
@@ -2150,10 +2213,7 @@ func (service *Service) completeSuccessfulTurn(stream *ActiveStream, completion
err,
)
}
if err := service.publishCheckpointWithCompletion(requestID, conversationID, &completion); err != nil {
return err
}
return nil
return service.publishCheckpointWithCompletion(requestID, conversationID, &completion)
}
func (service *Service) finishSuccessfulTurnAfterCheckpoint(stream *ActiveStream, completion pendingTurnCompletion) error {
@@ -2192,11 +2252,7 @@ func (service *Service) publishCheckpoint(requestID string, conversationID strin
return service.publishCheckpointWithCompletion(requestID, conversationID, nil)
}
func (service *Service) publishCheckpointWithCompletion(requestID string, conversationID string, completion *pendingTurnCompletion) error {
return service.publishCheckpointWithTerminalAction(requestID, conversationID, checkpointCompletionAction(completion))
}
func (service *Service) publishCheckpointWithTerminalAction(requestID string, conversationID string, terminalAction checkpointTerminalAction) error {
func (service *Service) publishCheckpointWithCompletion(requestID string, _ string, completion *pendingTurnCompletion) error {
stream, ok := service.broker.Get(requestID)
if !ok || stream == nil {
return fmt.Errorf("request is not active: %s", requestID)
@@ -2214,7 +2270,7 @@ func (service *Service) publishCheckpointWithTerminalAction(requestID string, co
}
projection.State.PendingToolCalls = buildPendingToolCalls(pendingExecs, pendingInteractions)
service.rewriteCheckpointTokenDetailsForClient(stream, conversation, projection.State)
return service.queueCheckpointProjection(stream, projection, terminalAction)
return service.queueCheckpointProjection(stream, projection, completion)
}
func (service *Service) rewriteCheckpointTokenDetailsForClient(stream *ActiveStream, conversation *ConversationFile, state *agentv1.ConversationStateStructure) {
@@ -2468,6 +2524,16 @@ func newAssistantTextEntry(turnSeq int64, requestID string, text string, reasoni
}
func newAssistantTextEntryWithProviderMetadata(turnSeq int64, requestID string, text string, reasoningContent string, reasoningSignature string, reasoningSignatureSource string, reasoningItemID string, reasoningStatus string, reasoningSummary json.RawMessage) HistoryEntry {
return HistoryEntry{
TurnSeq: turnSeq,
RequestID: strings.TrimSpace(requestID),
Role: "assistant",
Kind: "assistant_text",
Payload: newAssistantTextPayload(text, reasoningContent, reasoningSignature, reasoningSignatureSource, reasoningItemID, reasoningStatus, reasoningSummary),
}
}
func newAssistantTextPayload(text string, reasoningContent string, reasoningSignature string, reasoningSignatureSource string, reasoningItemID string, reasoningStatus string, reasoningSummary json.RawMessage) json.RawMessage {
payload, _ := json.Marshal(assistantTextPayload{
Text: text,
ReasoningContent: reasoningContent,
@@ -2477,13 +2543,7 @@ func newAssistantTextEntryWithProviderMetadata(turnSeq int64, requestID string,
ReasoningStatus: strings.TrimSpace(reasoningStatus),
ReasoningSummary: append(json.RawMessage(nil), reasoningSummary...),
})
return HistoryEntry{
TurnSeq: turnSeq,
RequestID: strings.TrimSpace(requestID),
Role: "assistant",
Kind: "assistant_text",
Payload: payload,
}
return payload
}
// newToolCallEntry 构造 tool_call entry。
+30 -25
View File
@@ -45,25 +45,13 @@ func (snapshot turnUsageSnapshot) requestTokensTotal() int64 {
return snapshot.promptTokensTotal() + nonNegativeInt64(snapshot.OutputTokens)
}
func (service *Service) importConversationState(item *ConversationFile, state *agentv1.ConversationStateStructure, prefetchedBlobs []*agentv1.PreFetchedBlob) ([]HistoryEntry, error) {
func (service *Service) importConversationState(item *ConversationFile, state *agentv1.ConversationStateStructure) ([]HistoryEntry, error) {
if item == nil || state == nil {
return nil, nil
}
blobs, err := newImportedBlobStore(prefetchedBlobs)
if err != nil {
return nil, err
}
importedIDs, err := importedTurnIDs(state.GetTurns(), blobs)
if err != nil {
return nil, err
}
item.TokenDetailsUsedTokens = state.GetTokenDetails().GetUsedTokens()
item.ImportedTurnIDs = importedIDs
if minimumNextTurnSeq := int64(len(item.ImportedTurnIDs)) + 1; item.NextTurnSeq < minimumNextTurnSeq {
item.NextTurnSeq = minimumNextTurnSeq
}
entries := make([]HistoryEntry, 0, 2)
if messages, err := importedConversationStateModelMessages(state, blobs); err != nil {
if messages, err := importedConversationStateModelMessages(state); err != nil {
return nil, err
} else {
for _, message := range messages {
@@ -116,7 +104,7 @@ func (service *Service) importConversationState(item *ConversationFile, state *a
return entries, nil
}
func importedConversationStateModelMessages(state *agentv1.ConversationStateStructure, blobs importedBlobStore) ([]modeladapter.Message, error) {
func importedConversationStateModelMessages(state *agentv1.ConversationStateStructure) ([]modeladapter.Message, error) {
if state == nil {
return nil, nil
}
@@ -125,7 +113,7 @@ func importedConversationStateModelMessages(state *agentv1.ConversationStateStru
if err != nil {
return nil, fmt.Errorf("decode imported replay messages: %w", err)
}
decoded = restoreImportedReplayUserMessages(decoded, state.GetTurns(), blobs)
decoded = restoreImportedReplayUserMessages(decoded, state.GetTurns())
decoded = filterLegacyPlainWriteReplay(decoded)
decoded = filterInternalPromptContextReplay(decoded)
messages := make([]modeladapter.Message, 0, len(decoded))
@@ -145,18 +133,35 @@ func importedConversationStateModelMessages(state *agentv1.ConversationStateStru
if len(rawTurn) == 0 {
continue
}
turn, turnID, err := decodeImportedTurn(rawTurn, blobs)
if err != nil {
return nil, err
turn := &agentv1.ConversationTurnStructure{}
if err := proto.Unmarshal(rawTurn, turn); err != nil {
return nil, fmt.Errorf("decode imported turn: %w", err)
}
if turn == nil && len(turnID) > 0 {
return nil, fmt.Errorf("missing prefetched turn blob %x", turnID)
agentTurn := turn.GetAgentConversationTurn()
if agentTurn == nil {
continue
}
if rawUser := agentTurn.GetUserMessage(); len(rawUser) > 0 {
userMessage := &agentv1.UserMessage{}
if err := proto.Unmarshal(rawUser, userMessage); err != nil {
return nil, fmt.Errorf("decode imported turn user_message: %w", err)
}
if replay, ok := promptengine.BuildUserMessageReplayMessage(userMessage); ok {
messages = append(messages, toModelMessage(replay))
}
}
for _, rawStep := range agentTurn.GetSteps() {
if len(rawStep) == 0 {
continue
}
step := &agentv1.ConversationStep{}
if err := proto.Unmarshal(rawStep, step); err != nil {
return nil, fmt.Errorf("decode imported turn step: %w", err)
}
for _, replay := range promptengine.BuildLegacyMessagesFromConversationStep(step) {
messages = append(messages, toModelMessage(replay))
}
turnMessages, err := importedBlobTurnMessages(turn, blobs)
if err != nil {
return nil, err
}
messages = append(messages, turnMessages...)
}
return normalizeReplayMessageSequence(messages), nil
}
+4 -26
View File
@@ -39,7 +39,6 @@ type ConversationFile struct {
CurrentPlanText string `json:"current_plan_text,omitempty"`
CurrentPlans map[string]*agentv1.PlanRegistryEntry `json:"current_plans,omitempty"`
CurrentTodos []*agentv1.TodoItem `json:"current_todos,omitempty"`
ImportedTurnIDs [][]byte `json:"imported_turn_ids,omitempty"`
LatestRequestPrefix *ConversationRequestPrefix `json:"latest_request_prefix,omitempty"`
LastProviderCall *ConversationProviderCall `json:"last_provider_call,omitempty"`
CreatedAt time.Time `json:"created_at"`
@@ -80,6 +79,7 @@ type HistoryEntry struct {
Seq int64 `json:"seq"`
TurnSeq int64 `json:"turn_seq"`
RequestID string `json:"request_id,omitempty"`
IdempotencyKey string `json:"idempotency_key,omitempty"`
Role string `json:"role"`
Kind string `json:"kind"`
ToolCallID string `json:"tool_call_id,omitempty"`
@@ -164,10 +164,9 @@ type ActiveStream struct {
ProviderUsage turnUsageSnapshot
ProviderTerminalToolInvocation bool
PendingCompaction *PendingCompaction
PendingCheckpointBlobWrites map[uint32]pendingCheckpointBlobWrite
PendingCheckpointBlobRequests map[string]uint32
PendingCheckpointBlobWrites map[uint32]string
ConfirmedCheckpointBlobs map[string]struct{}
NextCheckpointBlobRequestID uint32
NextCheckpointRevision uint64
PendingCheckpoint *pendingCheckpointPublish
Backlog []StreamEvent
@@ -225,30 +224,10 @@ type pendingTurnCompletion struct {
Disposition pendingCompletionDisposition
}
type pendingCheckpointBlobWrite struct {
Key string
Revision uint64
}
type checkpointTerminalActionKind uint8
const (
checkpointTerminalActionNone checkpointTerminalActionKind = iota
checkpointTerminalActionComplete
checkpointTerminalActionCancel
)
type checkpointTerminalAction struct {
kind checkpointTerminalActionKind
completion pendingTurnCompletion
cancelMessage string
}
type pendingCheckpointPublish struct {
Revision uint64
State *agentv1.ConversationStateStructure
Required map[string]struct{}
TerminalAction checkpointTerminalAction
Completion *pendingTurnCompletion
}
type PendingCompaction struct {
@@ -450,7 +429,6 @@ type InboundIntent struct {
SubagentTypeName string
SubagentModelOverrides map[string]runtimecore.SubagentModelOverrideSelection
ConversationState *agentv1.ConversationStateStructure
PreFetchedBlobs []*agentv1.PreFetchedBlob
UserMessage *agentv1.UserMessage
RequestContext *agentv1.RequestContext
ClientMessage *agentv1.AgentClientMessage
+11
View File
@@ -24,6 +24,12 @@ type ModelAdapterTestResult = client.ModelAdapterTestResult
// ModelAdapterTestResultsPayload 定义测速结果事件载荷。
type ModelAdapterTestResultsPayload = client.ModelAdapterTestResultsPayload
// ModelAdapterModelsRequest 定义模型列表查询请求。
type ModelAdapterModelsRequest = client.ModelAdapterModelsRequest
// ModelAdapterModelsResult 定义模型列表查询结果。
type ModelAdapterModelsResult = client.ModelAdapterModelsResult
// CursorAccountStatus 是可安全展示给桌面前端的独立 Cursor 账号状态。
type CursorAccountStatus = client.CursorAccountStatus
@@ -119,6 +125,11 @@ func (s *ProxyService) GetModelAdapterTestResults() []ModelAdapterTestResult {
return s.core.GetModelAdapterTestResults()
}
// FetchModelAdapterModels 用于从模型服务读取可用模型列表。
func (s *ProxyService) FetchModelAdapterModels(input ModelAdapterModelsRequest) (ModelAdapterModelsResult, error) {
return s.core.FetchModelAdapterModels(input)
}
// GetDeviceID 用于处理与 GetDeviceID 相关的逻辑。
func (s *ProxyService) GetDeviceID() (string, error) {
return s.core.GetDeviceID()
+303
View File
@@ -10,6 +10,7 @@ import (
"io"
"math"
"net/http"
"net/url"
"sort"
"strconv"
"strings"
@@ -31,8 +32,48 @@ const (
modelAdapterTestDefaultMaxTokens = 65_536
modelAdapterTestEmptyTextError = "未收到文本输出,无法计算测速结果"
modelAdapterTestMaxErrorBodyBytes = 8192
modelAdapterListTimeout = 20 * time.Second
modelAdapterListMaxBodyBytes = 8 << 20
modelAdapterListPageSize = 1000
modelAdapterListMaxPages = 50
)
// modelListProviderRule 收敛各家模型列表接口的协议差异,避免判断散落到多个函数。
type modelListProviderRule struct {
// paths 按优先级排列,逐个尝试直到某个返回可用模型
paths []string
authHeader string
authPrefix string
extraHeader map[string]string
// paginated 为真时按 limit + after_id 游标翻页,直到 has_more 为 false
paginated bool
}
var modelListProviderRules = map[string]modelListProviderRule{
"openai": {
paths: []string{"/models"},
authHeader: "Authorization",
authPrefix: "Bearer ",
},
"anthropic": {
paths: []string{"/models"},
authHeader: "x-api-key",
extraHeader: map[string]string{"anthropic-version": "2023-06-01"},
paginated: true,
},
}
// modelListVersionSegments 用于判断 base url 是否已带版本前缀,带了就不再补 /v1。
var modelListVersionSegments = map[string]bool{
"v1": true,
"v1beta": true,
"v2": true,
"beta": true,
"openai": true,
"compat": true,
"compatible": true,
}
type ModelAdapterTestStatus string
const (
@@ -58,6 +99,20 @@ type ModelAdapterTestResult struct {
TestedAt string `json:"testedAt"`
}
// ModelAdapterModelsRequest 定义从兼容接口读取模型列表所需的最小配置。
type ModelAdapterModelsRequest struct {
Type string `json:"type"`
BaseURL string `json:"baseURL"`
APIKey string `json:"apiKey"`
CustomHeadersEnabled bool `json:"customHeadersEnabled"`
CustomHeadersJSON string `json:"customHeadersJSON"`
}
// ModelAdapterModelsResult 定义可供前端下拉选择的模型列表。
type ModelAdapterModelsResult struct {
Models []string `json:"models"`
}
// ModelAdapterTestResultsPayload 用于向前端广播当前测速结果快照。
type ModelAdapterTestResultsPayload struct {
Results []ModelAdapterTestResult `json:"results"`
@@ -108,6 +163,254 @@ func (s *ProxyService) GetModelAdapterTestResults() []ModelAdapterTestResult {
return s.snapshotModelAdapterTestResults()
}
func (s *ProxyService) FetchModelAdapterModels(input ModelAdapterModelsRequest) (ModelAdapterModelsResult, error) {
_ = s
provider := strings.ToLower(strings.TrimSpace(input.Type))
baseURL := strings.TrimSpace(input.BaseURL)
apiKey := strings.TrimSpace(input.APIKey)
rule, supported := modelListProviderRules[provider]
if !supported {
return ModelAdapterModelsResult{}, errors.New("模型类型仅支持 OpenAI 或 Anthropic")
}
if baseURL == "" {
return ModelAdapterModelsResult{}, errors.New("接口地址不能为空")
}
if apiKey == "" {
return ModelAdapterModelsResult{}, errors.New("访问密钥不能为空")
}
ctx, cancel := context.WithTimeout(context.Background(), modelAdapterListTimeout)
defer cancel()
var lastErr error
for _, endpoint := range buildModelListEndpointCandidates(rule, baseURL) {
models, err := fetchModelListEndpoint(ctx, rule, endpoint, apiKey, input)
if err == nil {
return ModelAdapterModelsResult{Models: models}, nil
}
lastErr = err
}
if lastErr != nil {
return ModelAdapterModelsResult{}, lastErr
}
return ModelAdapterModelsResult{}, errors.New("未找到可用的模型列表接口")
}
func buildModelListEndpointCandidates(rule modelListProviderRule, rawBaseURL string) []string {
base := strings.TrimRight(strings.TrimSpace(rawBaseURL), "/")
for _, suffix := range []string{"/chat/completions", "/responses", "/messages"} {
if strings.HasSuffix(strings.ToLower(base), suffix) {
base = base[:len(base)-len(suffix)]
}
}
base = strings.TrimRight(base, "/")
tail := strings.ToLower(base[strings.LastIndex(base, "/")+1:])
var candidates []string
switch {
case tail == "models" || tail == "model":
// 用户已经填到模型列表地址本身,直接用
candidates = []string{base}
case modelListVersionSegments[tail]:
candidates = prefixModelListPaths(base, "", rule.paths)
default:
// base 没带版本段,优先试 /v1,再退回裸路径
candidates = append(
prefixModelListPaths(base, "/v1", rule.paths),
prefixModelListPaths(base, "", rule.paths)...,
)
}
seen := map[string]struct{}{}
endpoints := make([]string, 0, len(candidates))
for _, endpoint := range candidates {
if _, err := url.ParseRequestURI(endpoint); err != nil {
continue
}
if _, exists := seen[endpoint]; exists {
continue
}
seen[endpoint] = struct{}{}
endpoints = append(endpoints, endpoint)
}
return endpoints
}
func prefixModelListPaths(base string, version string, paths []string) []string {
endpoints := make([]string, 0, len(paths))
for _, path := range paths {
endpoints = append(endpoints, base+version+path)
}
return endpoints
}
func fetchModelListEndpoint(ctx context.Context, rule modelListProviderRule, endpoint string, apiKey string, input ModelAdapterModelsRequest) ([]string, error) {
collected := []string{}
cursor := ""
for page := 0; page < modelAdapterListMaxPages; page++ {
requestURL := endpoint
if rule.paginated {
requestURL = appendModelListCursor(endpoint, cursor)
}
payload, err := requestModelListPayload(ctx, rule, requestURL, apiKey, input)
if err != nil {
return nil, err
}
collected = append(collected, extractModelIDs(payload)...)
if !rule.paginated {
break
}
cursor = nextModelListCursor(payload)
if cursor == "" {
break
}
if page == modelAdapterListMaxPages-1 {
return nil, fmt.Errorf("模型列表分页超过 %d 页,结果可能不完整", modelAdapterListMaxPages)
}
}
models := normalizeFetchedModelIDs(collected)
if len(models) == 0 {
return nil, errors.New("模型列表响应中没有可用模型")
}
return models, nil
}
func requestModelListPayload(
ctx context.Context,
rule modelListProviderRule,
requestURL string,
apiKey string,
input ModelAdapterModelsRequest,
) (any, error) {
req, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil)
if err != nil {
return nil, err
}
req.Header.Set(rule.authHeader, rule.authPrefix+apiKey)
for key, value := range rule.extraHeader {
req.Header.Set(key, value)
}
req.Header.Set("Accept", "application/json")
applyModelListCustomHeaders(req.Header, input)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
body, readErr := io.ReadAll(io.LimitReader(resp.Body, modelAdapterListMaxBodyBytes))
if readErr != nil {
return nil, readErr
}
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
message := strings.TrimSpace(string(body))
if len(message) > modelAdapterTestMaxErrorBodyBytes {
message = message[:modelAdapterTestMaxErrorBodyBytes]
}
if message == "" {
message = resp.Status
}
return nil, fmt.Errorf("读取模型列表失败:%s", message)
}
var payload any
if err := json.Unmarshal(body, &payload); err != nil {
return nil, fmt.Errorf("模型列表响应不是合法 JSON%w", err)
}
return payload, nil
}
func appendModelListCursor(endpoint string, cursor string) string {
query := url.Values{}
query.Set("limit", strconv.Itoa(modelAdapterListPageSize))
if cursor != "" {
query.Set("after_id", cursor)
}
separator := "?"
if strings.Contains(endpoint, "?") {
separator = "&"
}
return endpoint + separator + query.Encode()
}
func nextModelListCursor(payload any) string {
object, ok := payload.(map[string]any)
if !ok {
return ""
}
if hasMore, _ := object["has_more"].(bool); !hasMore {
return ""
}
cursor, _ := object["last_id"].(string)
return strings.TrimSpace(cursor)
}
func applyModelListCustomHeaders(header http.Header, input ModelAdapterModelsRequest) {
if !input.CustomHeadersEnabled || strings.TrimSpace(input.CustomHeadersJSON) == "" {
return
}
var parsed map[string]string
if err := json.Unmarshal([]byte(input.CustomHeadersJSON), &parsed); err != nil {
return
}
for key, value := range parsed {
if strings.TrimSpace(key) == "" {
continue
}
header.Set(key, value)
}
}
func extractModelIDs(value any) []string {
switch typed := value.(type) {
case string:
if strings.TrimSpace(typed) == "" {
return []string{}
}
return []string{typed}
case []any:
models := make([]string, 0, len(typed))
for _, item := range typed {
models = append(models, extractModelIDs(item)...)
}
return models
case map[string]any:
for _, key := range []string{"id", "name"} {
if text, ok := typed[key].(string); ok && strings.TrimSpace(text) != "" {
return []string{text}
}
}
models := []string{}
for _, key := range []string{"data", "models"} {
if child, ok := typed[key]; ok {
models = append(models, extractModelIDs(child)...)
}
}
return models
default:
return []string{}
}
}
func normalizeFetchedModelIDs(input []string) []string {
seen := map[string]struct{}{}
models := make([]string, 0, len(input))
for _, item := range input {
model := strings.TrimSpace(item)
if model == "" {
continue
}
if _, exists := seen[model]; exists {
continue
}
seen[model] = struct{}{}
models = append(models, model)
}
sort.Strings(models)
return models
}
func (s *ProxyService) TestModelAdapter(adapter serverconfig.ModelAdapterConfig) (ModelAdapterTestResult, error) {
requestHash := buildModelAdapterTestRequestHash(adapter)
adapterID := buildModelAdapterTestCacheKey(adapter, requestHash)
@@ -0,0 +1,351 @@
package client
import (
"encoding/json"
"net/http"
"net/http/httptest"
"reflect"
"strconv"
"strings"
"testing"
)
func TestBuildModelListEndpointCandidates(t *testing.T) {
tests := []struct {
name string
provider string
baseURL string
want []string
}{
{
name: "openai 带版本段不再补 v1",
provider: "openai",
baseURL: "https://api.openai.com/v1",
want: []string{"https://api.openai.com/v1/models"},
},
{
name: "openai 裸域名优先试 v1",
provider: "openai",
baseURL: "https://api.openai.com",
want: []string{"https://api.openai.com/v1/models", "https://api.openai.com/models"},
},
{
name: "anthropic 裸域名优先试 v1",
provider: "anthropic",
baseURL: "https://api.anthropic.com",
want: []string{"https://api.anthropic.com/v1/models", "https://api.anthropic.com/models"},
},
{
name: "anthropic 带版本段不再补 v1",
provider: "anthropic",
baseURL: "https://api.anthropic.com/v1",
want: []string{"https://api.anthropic.com/v1/models"},
},
{
name: "剥离 chat completions 后缀",
provider: "openai",
baseURL: "https://api.example.com/v1/chat/completions",
want: []string{"https://api.example.com/v1/models"},
},
{
name: "剥离 responses 后缀",
provider: "openai",
baseURL: "https://api.example.com/v1/responses",
want: []string{"https://api.example.com/v1/models"},
},
{
name: "剥离 anthropic messages 后缀",
provider: "anthropic",
baseURL: "https://api.example.com/v1/messages",
want: []string{"https://api.example.com/v1/models"},
},
{
name: "已填到 models 地址本身则原样使用",
provider: "openai",
baseURL: "https://api.example.com/openai/v1/models",
want: []string{"https://api.example.com/openai/v1/models"},
},
{
name: "自定义网关前缀会补 v1",
provider: "openai",
baseURL: "https://gateway.example.com/proxy",
want: []string{
"https://gateway.example.com/proxy/v1/models",
"https://gateway.example.com/proxy/models",
},
},
{
name: "尾部斜杠不影响推导",
provider: "anthropic",
baseURL: " https://api.anthropic.com/v1/ ",
want: []string{"https://api.anthropic.com/v1/models"},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
rule, ok := modelListProviderRules[test.provider]
if !ok {
t.Fatalf("provider %q 没有对应规则", test.provider)
}
got := buildModelListEndpointCandidates(rule, test.baseURL)
if !reflect.DeepEqual(got, test.want) {
t.Fatalf("buildModelListEndpointCandidates(%q) = %v, want %v", test.baseURL, got, test.want)
}
})
}
}
func TestFetchModelAdapterModelsOpenAIUsesBearer(t *testing.T) {
var gotPath string
var gotAuth string
var gotAnthropicVersion string
var gotAPIKeyHeader string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotPath = r.URL.Path
gotAuth = r.Header.Get("Authorization")
gotAnthropicVersion = r.Header.Get("anthropic-version")
gotAPIKeyHeader = r.Header.Get("x-api-key")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"id":"gpt-5"},{"id":"gpt-4o"}]}`))
}))
defer server.Close()
service := &ProxyService{}
result, err := service.FetchModelAdapterModels(ModelAdapterModelsRequest{
Type: "openai",
BaseURL: server.URL + "/v1",
APIKey: "sk-test",
})
if err != nil {
t.Fatalf("FetchModelAdapterModels 返回错误:%v", err)
}
if gotPath != "/v1/models" {
t.Fatalf("请求路径 = %q, want /v1/models", gotPath)
}
if gotAuth != "Bearer sk-test" {
t.Fatalf("Authorization = %q, want Bearer sk-test", gotAuth)
}
if gotAPIKeyHeader != "" {
t.Fatalf("openai 不应发送 x-api-key,实际 = %q", gotAPIKeyHeader)
}
if gotAnthropicVersion != "" {
t.Fatalf("openai 不应发送 anthropic-version,实际 = %q", gotAnthropicVersion)
}
want := []string{"gpt-4o", "gpt-5"}
if !reflect.DeepEqual(result.Models, want) {
t.Fatalf("Models = %v, want %v", result.Models, want)
}
}
func TestFetchModelAdapterModelsAnthropicUsesAPIKeyHeader(t *testing.T) {
var gotAuth string
var gotAPIKeyHeader string
var gotAnthropicVersion string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotAuth = r.Header.Get("Authorization")
gotAPIKeyHeader = r.Header.Get("x-api-key")
gotAnthropicVersion = r.Header.Get("anthropic-version")
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"id":"claude-sonnet-4"}],"has_more":false}`))
}))
defer server.Close()
service := &ProxyService{}
result, err := service.FetchModelAdapterModels(ModelAdapterModelsRequest{
Type: "anthropic",
BaseURL: server.URL + "/v1",
APIKey: "sk-ant-test",
})
if err != nil {
t.Fatalf("FetchModelAdapterModels 返回错误:%v", err)
}
if gotAPIKeyHeader != "sk-ant-test" {
t.Fatalf("x-api-key = %q, want sk-ant-test", gotAPIKeyHeader)
}
if gotAnthropicVersion != "2023-06-01" {
t.Fatalf("anthropic-version = %q, want 2023-06-01", gotAnthropicVersion)
}
if gotAuth != "" {
t.Fatalf("anthropic 不应发送 Authorization,实际 = %q", gotAuth)
}
want := []string{"claude-sonnet-4"}
if !reflect.DeepEqual(result.Models, want) {
t.Fatalf("Models = %v, want %v", result.Models, want)
}
}
func TestFetchModelAdapterModelsAnthropicFollowsCursor(t *testing.T) {
var requestedQueries []string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestedQueries = append(requestedQueries, r.URL.RawQuery)
w.Header().Set("Content-Type", "application/json")
switch r.URL.Query().Get("after_id") {
case "":
_, _ = w.Write([]byte(`{"data":[{"id":"claude-a"}],"has_more":true,"last_id":"claude-a"}`))
case "claude-a":
_, _ = w.Write([]byte(`{"data":[{"id":"claude-b"}],"has_more":true,"last_id":"claude-b"}`))
default:
_, _ = w.Write([]byte(`{"data":[{"id":"claude-c"}],"has_more":false}`))
}
}))
defer server.Close()
service := &ProxyService{}
result, err := service.FetchModelAdapterModels(ModelAdapterModelsRequest{
Type: "anthropic",
BaseURL: server.URL + "/v1",
APIKey: "sk-ant-test",
})
if err != nil {
t.Fatalf("FetchModelAdapterModels 返回错误:%v", err)
}
want := []string{"claude-a", "claude-b", "claude-c"}
if !reflect.DeepEqual(result.Models, want) {
t.Fatalf("Models = %v, want %v", result.Models, want)
}
if len(requestedQueries) != 3 {
t.Fatalf("请求次数 = %d, want 3(两次翻页后停止)", len(requestedQueries))
}
for _, query := range requestedQueries {
if !strings.Contains(query, "limit=1000") {
t.Fatalf("翻页请求缺少 limit 参数:%q", query)
}
}
if !strings.Contains(requestedQueries[1], "after_id=claude-a") {
t.Fatalf("第二页未带上游标:%q", requestedQueries[1])
}
}
func TestFetchModelAdapterModelsOpenAIDoesNotPaginate(t *testing.T) {
requestCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
requestCount++
if r.URL.RawQuery != "" {
t.Errorf("openai 不应附加分页参数,实际 = %q", r.URL.RawQuery)
}
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"id":"gpt-5"}],"has_more":true,"last_id":"gpt-5"}`))
}))
defer server.Close()
service := &ProxyService{}
if _, err := service.FetchModelAdapterModels(ModelAdapterModelsRequest{
Type: "openai",
BaseURL: server.URL + "/v1",
APIKey: "sk-test",
}); err != nil {
t.Fatalf("FetchModelAdapterModels 返回错误:%v", err)
}
if requestCount != 1 {
t.Fatalf("请求次数 = %d, want 1openai 忽略 has_more", requestCount)
}
}
func TestFetchModelAdapterModelsReadsLargeBody(t *testing.T) {
models := make([]map[string]string, 0, 400)
for index := 0; index < 400; index++ {
models = append(models, map[string]string{
"id": "vendor/model-with-a-fairly-long-identifier-" + strings.Repeat("x", 40) + "-" + string(rune('a'+index%26)) + strconv.Itoa(index),
})
}
body, err := json.Marshal(map[string]any{"data": models})
if err != nil {
t.Fatalf("构造响应失败:%v", err)
}
if len(body) <= modelAdapterTestMaxErrorBodyBytes {
t.Fatalf("测试响应体只有 %d 字节,需要大于 %d 才能覆盖截断场景", len(body), modelAdapterTestMaxErrorBodyBytes)
}
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write(body)
}))
defer server.Close()
service := &ProxyService{}
result, err := service.FetchModelAdapterModels(ModelAdapterModelsRequest{
Type: "openai",
BaseURL: server.URL + "/v1",
APIKey: "sk-test",
})
if err != nil {
t.Fatalf("FetchModelAdapterModels 返回错误:%v", err)
}
if len(result.Models) != len(models) {
t.Fatalf("Models 数量 = %d, want %d", len(result.Models), len(models))
}
}
func TestFetchModelAdapterModelsSupportsStringItems(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":["gpt-4o","gpt-4.1"]}`))
}))
defer server.Close()
service := &ProxyService{}
result, err := service.FetchModelAdapterModels(ModelAdapterModelsRequest{
Type: "openai",
BaseURL: server.URL + "/v1",
APIKey: "sk-test",
})
if err != nil {
t.Fatalf("FetchModelAdapterModels 返回错误:%v", err)
}
want := []string{"gpt-4.1", "gpt-4o"}
if !reflect.DeepEqual(result.Models, want) {
t.Fatalf("Models = %v, want %v", result.Models, want)
}
}
func TestFetchModelAdapterModelsRejectsPaginationTruncation(t *testing.T) {
requestCount := 0
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
requestCount++
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{"data":[{"id":"claude-model"}],"has_more":true,"last_id":"next"}`))
}))
defer server.Close()
service := &ProxyService{}
_, err := service.FetchModelAdapterModels(ModelAdapterModelsRequest{
Type: "anthropic",
BaseURL: server.URL + "/v1",
APIKey: "sk-ant-test",
})
if err == nil || !strings.Contains(err.Error(), "结果可能不完整") {
t.Fatalf("期望分页截断错误,实际 = %v", err)
}
if requestCount != modelAdapterListMaxPages {
t.Fatalf("请求次数 = %d, want %d", requestCount, modelAdapterListMaxPages)
}
}
func TestFetchModelAdapterModelsRejectsInvalidInput(t *testing.T) {
tests := []struct {
name string
request ModelAdapterModelsRequest
}{
{name: "未知类型", request: ModelAdapterModelsRequest{Type: "gemini", BaseURL: "https://x.com", APIKey: "k"}},
{name: "缺少地址", request: ModelAdapterModelsRequest{Type: "openai", APIKey: "k"}},
{name: "缺少密钥", request: ModelAdapterModelsRequest{Type: "openai", BaseURL: "https://x.com"}},
}
service := &ProxyService{}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if _, err := service.FetchModelAdapterModels(test.request); err == nil {
t.Fatal("期望返回错误,实际为 nil")
}
})
}
}
+2500 -739
View File
File diff suppressed because it is too large Load Diff
+10930 -4348
View File
File diff suppressed because it is too large Load Diff
+27
View File
@@ -0,0 +1,27 @@
#!/usr/bin/env bash
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TEMP_DIR="$(mktemp -d "${TMPDIR:-/tmp}/cursor-proto-sync.XXXXXX")"
cleanup() {
rm -rf "$TEMP_DIR"
}
trap cleanup EXIT
for PROTO_NAME in agent_v1.proto aiserver_v1.proto; do
ROOT_PROTO="$SCRIPT_DIR/$PROTO_NAME"
EXTRACTED_PROTO="$SCRIPT_DIR/from_extensions/$PROTO_NAME"
if [[ ! -f "$ROOT_PROTO" || ! -f "$EXTRACTED_PROTO" ]]; then
echo "Missing proto pair for $PROTO_NAME" >&2
exit 1
fi
sed -E 's|^option go_package = ".*";$|option go_package = "__NORMALIZED__";|' "$ROOT_PROTO" > "$TEMP_DIR/root-$PROTO_NAME"
sed -E 's|^option go_package = ".*";$|option go_package = "__NORMALIZED__";|' "$EXTRACTED_PROTO" > "$TEMP_DIR/extracted-$PROTO_NAME"
if ! cmp -s "$TEMP_DIR/root-$PROTO_NAME" "$TEMP_DIR/extracted-$PROTO_NAME"; then
echo "Proto snapshot is out of sync: $PROTO_NAME" >&2
diff -u "$TEMP_DIR/root-$PROTO_NAME" "$TEMP_DIR/extracted-$PROTO_NAME" >&2 || true
exit 1
fi
done
+205 -39
View File
@@ -113,10 +113,14 @@ var (
mapValueRe = regexp.MustCompile(`V:\s*\{([^}]*)\}`)
mapValueKRe = regexp.MustCompile(`(?:^|[,{]\s*)kind:\s*["'](\w+)["']`)
mapValueTRe = regexp.MustCompile(`[,\s]T:\s*([\w$.]+)`)
shorthandTRe = regexp.MustCompile(`(?:^|[,\{])\s*T\s*(?:[,\}])`)
oneofNameRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
fieldNameRe = regexp.MustCompile(`^[A-Za-z_][A-Za-z0-9_]*$`)
placeholderRe = regexp.MustCompile(`^\s*(optional\s+|repeated\s+)?[A-Za-z_][A-Za-z0-9_.<>]*\s+(field_\d+|unknown(?:_[A-Za-z0-9_]+)?)\s*=\s*\d+\s*;`)
varAliasRe = regexp.MustCompile(`\b(?:let|const|var)\s+([\w$]+)\s*=\s*([\w$]+)\s*(?:[,;])`)
webpackExportBlockRe = regexp.MustCompile(`[\w$]+\.d\(\s*[\w$]+\s*,\s*\{`)
webpackExportEntryRe = regexp.MustCompile(`(?:^|[,\{])\s*([\w$]+)\s*:\s*\(\s*\)\s*=>\s*([\w$]+)`)
moduleImportRe = regexp.MustCompile(`(?:\b(?:var|let|const)\s+|,)\s*([\w$]+)\s*=\s*[\w$]+\(\s*(\d+)\s*\)`)
streamCloseRe = regexp.MustCompile(`(?s)message\s+ExecClientControlMessage\s*\{.*?ExecClientStreamClose\s+stream_close\s*=\s*1\s*;`)
shellStdoutRe = regexp.MustCompile(`(?s)message\s+ShellStream\s*\{.*?ShellStreamStdout\s+stdout\s*=\s*1\s*;`)
)
@@ -186,12 +190,17 @@ type symbolDef struct {
type TypeResolver struct {
bySymbol map[string][]symbolDef
byAlias map[string][]symbolDef
byShort map[string][]symbolDef
moduleImports map[int]map[string]int
}
func newTypeResolver(messages []Message, enums []Enum, aliases map[string][]string) *TypeResolver {
type aliasIndex map[int]map[string][]string
func newTypeResolver(messages []Message, enums []Enum, aliases aliasIndex, exportAliases aliasIndex) *TypeResolver {
resolver := &TypeResolver{
bySymbol: make(map[string][]symbolDef),
byAlias: make(map[string][]symbolDef),
byShort: make(map[string][]symbolDef),
}
@@ -218,43 +227,64 @@ func newTypeResolver(messages []Message, enums []Enum, aliases map[string][]stri
}
}
}
addAlias := func(symbol, typeName string, pos int, moduleStart int, kind string) {
symbol = strings.TrimSpace(symbol)
typeName = strings.TrimSpace(typeName)
if symbol == "" || typeName == "" {
return
}
resolver.byAlias[symbol] = append(resolver.byAlias[symbol], symbolDef{
TypeName: typeName, Pos: pos, ModuleStart: moduleStart, Kind: kind,
})
}
for _, msg := range messages {
add(msg.VarName, msg.TypeName, msg.Pos, msg.ModuleStart, "message")
if msg.InternalName != "" && msg.InternalName != msg.VarName {
add(msg.InternalName, msg.TypeName, msg.Pos, msg.ModuleStart, "message")
}
for _, alias := range aliasesForSymbols(aliases, msg.VarName, msg.InternalName) {
add(alias, msg.TypeName, msg.Pos, msg.ModuleStart, "message")
for _, alias := range aliasesForSymbols(aliases[msg.ModuleStart], msg.VarName, msg.InternalName) {
addAlias(alias, msg.TypeName, msg.Pos, msg.ModuleStart, "message")
}
}
for _, enum := range enums {
add(enum.VarName, enum.TypeName, enum.Pos, enum.ModuleStart, "enum")
for _, alias := range aliasesForSymbols(aliases, enum.VarName) {
add(alias, enum.TypeName, enum.Pos, enum.ModuleStart, "enum")
for _, alias := range aliasesForSymbols(aliases[enum.ModuleStart], enum.VarName) {
addAlias(alias, enum.TypeName, enum.Pos, enum.ModuleStart, "enum")
}
}
for _, msg := range messages {
for _, alias := range aliasesForSymbols(exportAliases[msg.ModuleStart], msg.VarName, msg.InternalName) {
addAlias(alias, msg.TypeName, msg.Pos, msg.ModuleStart, "message")
}
}
for _, enum := range enums {
for _, alias := range aliasesForSymbols(exportAliases[enum.ModuleStart], enum.VarName) {
addAlias(alias, enum.TypeName, enum.Pos, enum.ModuleStart, "enum")
}
}
return resolver
}
func buildAliasIndex(text string) map[string][]string {
matches := varAliasRe.FindAllStringSubmatch(text, -1)
if len(matches) == 0 {
return nil
}
direct := make(map[string]string, len(matches))
func buildAliasIndex(text string, moduleStarts []int) aliasIndex {
matches := varAliasRe.FindAllStringSubmatchIndex(text, -1)
directByModule := make(map[int]map[string]string)
for _, match := range matches {
alias := strings.TrimSpace(match[1])
target := strings.TrimSpace(match[2])
alias := strings.TrimSpace(text[match[2]:match[3]])
target := strings.TrimSpace(text[match[4]:match[5]])
if alias == "" || target == "" || alias == target {
continue
}
direct[alias] = target
moduleStart := moduleStartForPos(moduleStarts, match[0])
if directByModule[moduleStart] == nil {
directByModule[moduleStart] = make(map[string]string)
}
directByModule[moduleStart][alias] = target
}
resolveRoot := func(symbol string) string {
resolveRoot := func(direct map[string]string, symbol string) string {
seen := make(map[string]bool)
current := symbol
for {
@@ -270,16 +300,90 @@ func buildAliasIndex(text string) map[string][]string {
}
}
aliases := make(map[string][]string)
aliasSets := make(map[int]map[string]map[string]bool)
addAlias := func(moduleStart int, root string, alias string) {
root = strings.TrimSpace(root)
alias = strings.TrimSpace(alias)
if root == "" || alias == "" || root == alias {
return
}
if aliasSets[moduleStart] == nil {
aliasSets[moduleStart] = make(map[string]map[string]bool)
}
if aliasSets[moduleStart][root] == nil {
aliasSets[moduleStart][root] = make(map[string]bool)
}
aliasSets[moduleStart][root][alias] = true
}
for moduleStart, direct := range directByModule {
for alias := range direct {
root := resolveRoot(alias)
if root == alias {
root := resolveRoot(direct, alias)
addAlias(moduleStart, root, alias)
}
}
if len(aliasSets) == 0 {
return nil
}
aliases := make(aliasIndex, len(aliasSets))
for moduleStart, roots := range aliasSets {
aliases[moduleStart] = make(map[string][]string, len(roots))
for root, set := range roots {
for alias := range set {
aliases[moduleStart][root] = append(aliases[moduleStart][root], alias)
}
sort.Strings(aliases[moduleStart][root])
}
}
return aliases
}
func buildWebpackExportAliasIndex(text string, moduleStarts []int) aliasIndex {
aliasSets := make(map[int]map[string]map[string]bool)
addAlias := func(moduleStart int, root string, alias string) {
root = strings.TrimSpace(root)
alias = strings.TrimSpace(alias)
if root == "" || alias == "" || root == alias {
return
}
if aliasSets[moduleStart] == nil {
aliasSets[moduleStart] = make(map[string]map[string]bool)
}
if aliasSets[moduleStart][root] == nil {
aliasSets[moduleStart][root] = make(map[string]bool)
}
aliasSets[moduleStart][root][alias] = true
}
// Webpack exposes module members through tables such as
// n.d(t, { KS: () => T }). Service descriptors refer to the exported
// name (r.KS), while message definitions use the local symbol (T).
for _, blockMatch := range webpackExportBlockRe.FindAllStringIndex(text, -1) {
moduleStart := moduleStartForPos(moduleStarts, blockMatch[0])
blockStart := blockMatch[1] - 1
blockEnd := findMatchingBrace(text, blockStart)
if blockEnd == -1 {
continue
}
aliases[root] = append(aliases[root], alias)
block := text[blockStart:blockEnd]
for _, entry := range webpackExportEntryRe.FindAllStringSubmatch(block, -1) {
addAlias(moduleStart, entry[2], entry[1])
}
}
if len(aliasSets) == 0 {
return nil
}
aliases := make(aliasIndex, len(aliasSets))
for moduleStart, roots := range aliasSets {
aliases[moduleStart] = make(map[string][]string, len(roots))
for root, set := range roots {
for alias := range set {
aliases[moduleStart][root] = append(aliases[moduleStart][root], alias)
}
sort.Strings(aliases[moduleStart][root])
}
for root := range aliases {
sort.Strings(aliases[root])
}
return aliases
}
@@ -318,11 +422,10 @@ func pickBestDefinition(candidates []symbolDef, contextPos int, contextModuleSta
}
filtered := candidates
if strings.TrimSpace(preferredPkg) != "" {
if strings.TrimSpace(expectedKind) != "" {
tmp := make([]symbolDef, 0, len(candidates))
for _, item := range candidates {
pkg, _ := parseTypeName(item.TypeName)
if pkg == preferredPkg {
if item.Kind == expectedKind {
tmp = append(tmp, item)
}
}
@@ -331,10 +434,11 @@ func pickBestDefinition(candidates []symbolDef, contextPos int, contextModuleSta
}
}
if strings.TrimSpace(expectedKind) != "" {
if strings.TrimSpace(preferredPkg) != "" {
tmp := make([]symbolDef, 0, len(filtered))
for _, item := range filtered {
if item.Kind == expectedKind {
pkg, _ := parseTypeName(item.TypeName)
if pkg == preferredPkg {
tmp = append(tmp, item)
}
}
@@ -416,6 +520,17 @@ func (resolver *TypeResolver) ResolveTypeName(ref string, contextPos int, contex
}
return best.TypeName, true
}
resolveByAlias := func(symbol string, targetModuleStart int) (string, bool) {
candidates := resolver.byAlias[symbol]
if len(candidates) == 0 {
return "", false
}
best, ok := pickBestDefinition(candidates, contextPos, targetModuleStart, preferredPkg, expectedKind)
if !ok {
return "", false
}
return best.TypeName, true
}
resolveByShort := func(symbol string, preferSameModule bool) (string, bool) {
candidates := resolver.byShort[symbol]
if len(candidates) == 0 {
@@ -435,17 +550,30 @@ func (resolver *TypeResolver) ResolveTypeName(ref string, contextPos int, contex
if typeName, ok := resolveBySymbol(trimmed, !strings.Contains(trimmed, ".")); ok {
return typeName, true
}
if typeName, ok := resolveByAlias(trimmed, 0); ok {
return typeName, true
}
if typeName, ok := resolveByShort(trimmed, !strings.Contains(trimmed, ".")); ok {
return typeName, true
}
if strings.Contains(trimmed, ".") {
parts := strings.Split(trimmed, ".")
first := parts[0]
last := parts[len(parts)-1]
targetModuleStart := 0
if imports := resolver.moduleImports[contextModuleStart]; imports != nil {
targetModuleStart = imports[first]
}
if typeName, ok := resolveByAlias(last, targetModuleStart); ok {
return typeName, true
}
if typeName, ok := resolveBySymbol(last, false); ok {
return typeName, true
}
if typeName, ok := resolveByShort(last, false); ok {
return typeName, true
}
first := parts[0]
if typeName, ok := resolveBySymbol(first, false); ok {
return typeName, true
}
@@ -473,7 +601,7 @@ func absInt(value int) int {
return value
}
var moduleStartRe = regexp.MustCompile(`(?:^|,)(\d+):(?:function\([\w$,]*\)|\([\w$,]*\)=>)\{`)
var moduleStartRe = regexp.MustCompile(`(?:^|,)\s*(\d+)\s*:\s*(?:function\s*\(\s*[\w$,\s]*\s*\)|\(\s*[\w$,\s]*\s*\)\s*=>)\s*\{`)
func buildModuleStarts(text string) []int {
matches := moduleStartRe.FindAllStringSubmatchIndex(text, -1)
@@ -497,6 +625,38 @@ func moduleStartForPos(moduleStarts []int, pos int) int {
return moduleStarts[index]
}
func buildModuleImportIndex(text string, moduleStarts []int) map[int]map[string]int {
if len(moduleStarts) == 0 {
return nil
}
moduleMatches := moduleStartRe.FindAllStringSubmatchIndex(text, -1)
moduleStartByID := make(map[string]int, len(moduleMatches))
for _, match := range moduleMatches {
moduleStartByID[text[match[2]:match[3]]] = match[0]
}
importsByModule := make(map[int]map[string]int)
for index, moduleStart := range moduleStarts {
moduleEnd := len(text)
if index+1 < len(moduleStarts) {
moduleEnd = moduleStarts[index+1]
}
body := text[moduleStart:moduleEnd]
for _, match := range moduleImportRe.FindAllStringSubmatch(body, -1) {
targetModuleStart, ok := moduleStartByID[match[2]]
if !ok {
continue
}
if importsByModule[moduleStart] == nil {
importsByModule[moduleStart] = make(map[string]int)
}
importsByModule[moduleStart][match[1]] = targetModuleStart
}
}
return importsByModule
}
// ExtractProtos extracts proto definitions from formatted JS file
func ExtractProtos(inputFile, outputDir string) {
activeDiagnostics = newExtractionDiagnostics()
@@ -512,7 +672,8 @@ func ExtractProtos(inputFile, outputDir string) {
text := string(content)
moduleStarts := buildModuleStarts(text)
aliases := buildAliasIndex(text)
aliases := buildAliasIndex(text, moduleStarts)
exportAliases := buildWebpackExportAliasIndex(text, moduleStarts)
// Extract messages, enums, and services
messages := extractMessages(text, moduleStarts)
@@ -524,7 +685,8 @@ func ExtractProtos(inputFile, outputDir string) {
}
}
resolver := newTypeResolver(messages, enums, aliases)
resolver := newTypeResolver(messages, enums, aliases, exportAliases)
resolver.moduleImports = buildModuleImportIndex(text, moduleStarts)
// Generate proto files
generateProtos(messages, enums, services, resolver, outputDir)
@@ -900,6 +1062,8 @@ func parseFieldObject(obj string) (*Field, error) {
} else {
field.T = tMatch[1]
}
} else if shorthandTRe.MatchString(obj) {
field.T = "T"
}
}
@@ -1195,8 +1359,9 @@ func copyAllExternalTypes(pkgName string, pkg struct {
neededTypes := make(map[string]bool)
for _, msg := range result.messages {
preferredPkg, _ := parseTypeName(msg.TypeName)
for _, f := range msg.Fields {
collectFieldRefsSimple(f, pkgName, msg.Pos, msg.ModuleStart, resolver, neededTypes, localTypes)
collectFieldRefsSimple(f, pkgName, preferredPkg, msg.Pos, msg.ModuleStart, resolver, neededTypes, localTypes)
}
}
for _, svc := range result.services {
@@ -1268,7 +1433,7 @@ func copyAllExternalTypes(pkgName string, pkg struct {
}
// collectFieldRefsSimple collects external type references from a field (non-recursive, just this field)
func collectFieldRefsSimple(f Field, currentPkg string, contextPos int, contextModuleStart int, resolver *TypeResolver,
func collectFieldRefsSimple(f Field, currentPkg string, preferredPkg string, contextPos int, contextModuleStart int, resolver *TypeResolver,
neededTypes map[string]bool, localTypes map[string]bool) {
type refWithKind struct {
@@ -1289,7 +1454,7 @@ func collectFieldRefsSimple(f Field, currentPkg string, contextPos int, contextM
}
for _, item := range refs {
typeName, ok := resolver.ResolveTypeName(item.ref, contextPos, contextModuleStart, currentPkg, item.kind)
typeName, ok := resolver.ResolveTypeName(item.ref, contextPos, contextModuleStart, preferredPkg, item.kind)
if !ok {
continue
}
@@ -1637,6 +1802,7 @@ func writeMessageFields(msg *Message, sb *strings.Builder, resolver *TypeResolve
// Get the current message's path prefix for relative type resolution
msgPath := msg.ShortName
currentPkg := msg.Package
preferredPkg, _ := parseTypeName(msg.TypeName)
// Group fields by oneof
oneofGroups := make(map[string][]Field)
@@ -1652,7 +1818,7 @@ func writeMessageFields(msg *Message, sb *strings.Builder, resolver *TypeResolve
// Write regular fields
for _, f := range regularFields {
fieldType := resolveFieldTypeWithPkg(f, resolver, msgPath, currentPkg, msg.Pos, msg.ModuleStart)
fieldType := resolveFieldTypeWithPkg(f, resolver, msgPath, currentPkg, preferredPkg, msg.Pos, msg.ModuleStart)
prefix := ""
if f.Repeated {
prefix = "repeated "
@@ -1673,7 +1839,7 @@ func writeMessageFields(msg *Message, sb *strings.Builder, resolver *TypeResolve
fields := oneofGroups[oneofName]
sb.WriteString(fmt.Sprintf("%soneof %s {\n", indentStr, oneofName))
for _, f := range fields {
fieldType := resolveFieldTypeWithPkg(f, resolver, msgPath, currentPkg, msg.Pos, msg.ModuleStart)
fieldType := resolveFieldTypeWithPkg(f, resolver, msgPath, currentPkg, preferredPkg, msg.Pos, msg.ModuleStart)
sb.WriteString(fmt.Sprintf("%s %s %s = %d;\n", indentStr, fieldType, f.Name, f.No))
}
sb.WriteString(fmt.Sprintf("%s}\n", indentStr))
@@ -1721,15 +1887,15 @@ func getNestedPath(shortName string) []string {
}
func resolveFieldType(f Field, resolver *TypeResolver, contextPos int, contextModuleStart int) string {
return resolveFieldTypeWithPkg(f, resolver, "", "", contextPos, contextModuleStart)
return resolveFieldTypeWithPkg(f, resolver, "", "", "", contextPos, contextModuleStart)
}
// resolveFieldTypeWithPkg resolves field type with package awareness
// parentPath is like "ConversationMessage" or "ConversationMessage.ToolResult"
// currentPkg is the package of the current message being written (e.g., "agent.v1")
func resolveFieldTypeWithPkg(f Field, resolver *TypeResolver, parentPath string, currentPkg string, contextPos int, contextModuleStart int) string {
func resolveFieldTypeWithPkg(f Field, resolver *TypeResolver, parentPath string, currentPkg string, preferredPkg string, contextPos int, contextModuleStart int) string {
resolveNamedType := func(ref string, expectedKind string) string {
typeName, ok := resolver.ResolveTypeName(ref, contextPos, contextModuleStart, currentPkg, expectedKind)
typeName, ok := resolver.ResolveTypeName(ref, contextPos, contextModuleStart, preferredPkg, expectedKind)
if !ok {
activeDiagnostics.addUnresolvedType(expectedKind + ":" + ref)
return fallbackTypeToken(ref)
+72
View File
@@ -0,0 +1,72 @@
package main
import "testing"
func TestParseFieldObjectSupportsShorthandType(t *testing.T) {
field, err := parseFieldObject(`{no:4,name:"file_not_found",kind:"message",T,oneof:"result"}`)
if err != nil {
t.Fatalf("parse shorthand T: %v", err)
}
if field.T != "T" {
t.Fatalf("parsed shorthand T as %#v, want T", field.T)
}
}
func TestWebpackExportAliasResolvesServiceMessageType(t *testing.T) {
const bundle = `
1:(e,t,n)=>{
n.d(t,{KS:()=>T,_B:()=>r});
var r;
class T {}
T.typeName="agent.v1.AgentClientMessage";
n.proto3.util.setEnumType(r,"agent.v1.DiagnosticSeverity",[]);
},
2:(e,t,n)=>{
var r=n(1);
const service={typeName:"agent.v1.AgentService",methods:{run:{name:"Run",I:r.KS,O:r.KS,kind:n.MethodKind.BiDiStreaming}}};
}`
moduleStarts := buildModuleStarts(bundle)
messages := []Message{{
TypeName: "agent.v1.AgentClientMessage",
VarName: "T",
InternalName: "T",
Package: "agent.v1",
Pos: 35,
ModuleStart: moduleStartForPos(moduleStarts, 35),
}}
enums := []Enum{{
TypeName: "agent.v1.DiagnosticSeverity",
VarName: "r",
Package: "agent.v1",
Pos: 100,
ModuleStart: moduleStartForPos(moduleStarts, 100),
}}
resolver := newTypeResolver(messages, enums, buildAliasIndex(bundle, moduleStarts), buildWebpackExportAliasIndex(bundle, moduleStarts))
resolver.moduleImports = buildModuleImportIndex(bundle, moduleStarts)
typeName, ok := resolver.ResolveTypeName("r.KS", len(bundle)-1, moduleStartForPos(moduleStarts, len(bundle)-1), "agent.v1", "message")
if !ok {
t.Fatal("expected webpack export alias to resolve")
}
if typeName != "agent.v1.AgentClientMessage" {
t.Fatalf("resolved r.KS to %q, want agent.v1.AgentClientMessage", typeName)
}
}
func TestResolverPrefersExpectedKindOverCurrentPackage(t *testing.T) {
resolver := &TypeResolver{bySymbol: map[string][]symbolDef{
"nt": {
{TypeName: "git_forge.v1.GetTagResponse", Kind: "message", Pos: 10, ModuleStart: 1},
{TypeName: "origin.v1.TeamGroupKind", Kind: "enum", Pos: 20, ModuleStart: 1},
},
}}
typeName, ok := resolver.ResolveTypeName("nt", 30, 1, "origin.v1", "message")
if !ok {
t.Fatal("expected cross-package message type to resolve")
}
if typeName != "git_forge.v1.GetTagResponse" {
t.Fatalf("resolved nt to %q, want git_forge.v1.GetTagResponse", typeName)
}
}
@@ -1,2 +0,0 @@
src/proto/**
media/index.js
@@ -1 +0,0 @@
{"name":"cursor-always-local","description":"Implements experimentation features for Cursor","author":"Anysphere, Inc.","publisher":"anysphere","version":"0.0.1","private":true,"repository":{"type":"git","url":"https://github.com/anysphere/vscode"},"extensionKind":["ui"],"engines":{"vscode":"^1.43.0","yarn":"please-use-npm"},"activationEvents":["onStartupFinished","onResolveRemoteAuthority:background-composer"],"enabledApiProposals":["cursor","control","externalUriOpener","contribSourceControlInputBoxMenu"],"main":"./dist/main","contributes":{"commands":[],"keybindings":[],"menus":{"scm/inputBox":[{"command":"cursor.generateGitCommitMessage","when":"scmProvider == git"}]},"jsonValidation":[{"fileMatch":".cursor/environment.json","url":"./schemas/environment.schema.json"}],"configuration":{"type":"object","title":"Cursor Always Local"}},"optionalDependencies":{"@vscode/windows-ca-certs":"^0.3.3"}}
@@ -1 +0,0 @@
{"displayName":"Cursor Always Local","description":"Experimentation @ cursor.sh"}
@@ -1 +0,0 @@
{"$schema":"https://json-schema.org/draft/2019-09/schema","description":"Defines a dev environment","allowComments":true,"allowTrailingCommas":false,"definitions":{"common":{"type":"object","properties":{"name":{"type":"string","description":"The name of the environment."},"user":{"type":"string","description":"The user to run the environment as."},"install":{"type":"string","description":"The update command to run on VM startup (after pulling latest changes) to refresh dependencies."},"start":{"type":"string","description":"The start command to run when the environment is started."},"repositoryDependencies":{"type":"array","description":"Repositories that are required for the environment to work, and need to be included in the GitHub access token that is generated for the environment.","items":{"type":"string","description":"The URL of the dependent repository, e.g. `github.com/org/repo`."}},"ports":{"type":"array","description":"Ports to expose from the container. Similar to devcontainers port forwarding.","items":{"type":"object","required":["port"],"properties":{"name":{"type":"string","description":"A descriptive name for the port (e.g., 'web server', 'api')."},"port":{"type":"integer","minimum":1,"maximum":65535,"description":"The port number inside the container to expose."}}}},"terminals":{"type":"array","description":"The terminals to run when the environment is started.","items":{"oneOf":[{"type":"array","items":{"type":"object","required":["command"],"properties":{"name":{"type":"string","description":"The name of the terminal."},"command":{"type":"string","description":"The command to run in the terminal."},"description":{"type":"string","description":"A description of what the terminal does. This is displayed to the agent."}}}},{"type":"object","required":["command"],"properties":{"name":{"type":"string","description":"The name of the terminal."},"command":{"type":"string","description":"The command to run in the terminal."},"description":{"type":"string","description":"A description of what the terminal does. This is displayed to the agent."}}}]}}}},"container":{"type":"object","properties":{"build":{"type":"object","description":"Docker build-related options.","properties":{"dockerfile":{"type":"string","description":"The location of the Dockerfile that defines the contents of the container. The path is relative to the folder containing the `environment.json` file."},"context":{"type":"string","description":"The location of the context folder for building the Docker image. The path is relative to the folder containing the `environment.json` file."}},"required":["dockerfile"],"unevaluatedProperties":false},"snapshot":{"type":"string","description":"A snapshot ID for the base environment."},"agentCanUpdateSnapshot":{"type":"boolean","description":"Whether the agent can update the snapshot."}},"required":[]}},"allOf":[{"$ref":"#/definitions/container"},{"$ref":"#/definitions/common"}],"unevaluatedProperties":false}
@@ -1,15 +0,0 @@
#!/usr/bin/env bash
# Run vitest with any additional arguments passed after --
npx vitest run --config vitest.config.ts "$@"
# Capture the exit code
exit_code=$?
# If tests failed, echo the colored error message
if [ $exit_code -ne 0 ]; then
echo -e "\033[1;31m❌ Test failed -- you can set CURSOR_EXT_TEST_LOG_LEVEL=info to see more logs\033[0m"
fi
# Exit with the same code as vitest
exit $exit_code
@@ -1,29 +0,0 @@
#!/bin/bash
include_files=()
for f in "$@"; do
include_files+=("${f#$PWD/}")
done
node_modules/.bin/tsc --noEmit -p . | (
status=0
show_continuation=false
while IFS='' read -r line; do
case "$line" in
(' '*)
if $show_continuation; then
echo "$line" >&2
fi
;;
(*)
file="${line%%(*}"
if [[ " ${include_files[@]} " =~ " ${file} " ]]; then
show_continuation=true
echo "$line" >&2
status=1
else
show_continuation=false
fi
;;
esac
done
exit $status
)
+73 -20
View File
@@ -2,27 +2,30 @@
set -euo pipefail
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SNAPSHOT_DEFAULT="$SCRIPT_DIR/extensions-cursor-app/cursor-always-local"
INSTALLED_CURSOR_DEFAULT="/Applications/Cursor.app/Contents/Resources/app/extensions/cursor-always-local/dist/main.js"
LATEST_EXT_DIR="$(
find "$SCRIPT_DIR" -maxdepth 1 -type d -name 'extensions-*' 2>/dev/null \
| sort -V \
| tail -n 1
)"
if [[ -f "$SNAPSHOT_DEFAULT/dist/main.js" ]]; then
INPUT_DEFAULT="$SNAPSHOT_DEFAULT"
elif [[ -f "$INSTALLED_CURSOR_DEFAULT" ]]; then
INPUT_DEFAULT="$INSTALLED_CURSOR_DEFAULT"
elif [[ -n "$LATEST_EXT_DIR" ]]; then
INPUT_DEFAULT="$LATEST_EXT_DIR"
else
INPUT_DEFAULT="$SCRIPT_DIR/extensions-2.6.19"
fi
INPUT_DEFAULT="$INSTALLED_CURSOR_DEFAULT"
OUTPUT_DEFAULT="$SCRIPT_DIR/from_extensions"
INPUT_PATH="${1:-$INPUT_DEFAULT}"
OUTPUT_DIR="${2:-$OUTPUT_DEFAULT}"
canonicalize_path() {
local path="$1"
local parent
local base
if [[ -d "$path" ]]; then
(cd "$path" && pwd -P)
return
fi
parent="$(dirname "$path")"
base="$(basename "$path")"
if [[ ! -d "$parent" ]]; then
echo "Parent directory does not exist: $parent" >&2
return 1
fi
printf '%s/%s\n' "$(cd "$parent" && pwd -P)" "$base"
}
# Resolve input: accept either a single JS file or an extensions root directory.
if [[ -d "$INPUT_PATH" ]]; then
CANDIDATES=(
@@ -40,7 +43,10 @@ if [[ -d "$INPUT_PATH" ]]; then
if [[ -n "$FOUND_CANDIDATE" ]]; then
INPUT_PATH="$FOUND_CANDIDATE"
else
mapfile -t JS_FILES < <(find "$INPUT_PATH" -type f -path "*/dist/main.js" | sort)
JS_FILES=()
while IFS= read -r JS_FILE; do
JS_FILES+=("$JS_FILE")
done < <(find "$INPUT_PATH" -type f -path "*/dist/main.js" | sort)
if [[ ${#JS_FILES[@]} -eq 1 ]]; then
INPUT_PATH="${JS_FILES[0]}"
elif [[ ${#JS_FILES[@]} -eq 0 ]]; then
@@ -57,15 +63,62 @@ fi
if [[ ! -f "$INPUT_PATH" ]]; then
echo "Input JS not found: $INPUT_PATH" >&2
echo "Usage: $0 [input-js-file-or-extensions-dir] [output-dir]" >&2
echo "Install/update Cursor, or pass an explicit input bundle:" >&2
echo " $0 /path/to/cursor-always-local/dist/main.js [output-dir]" >&2
exit 1
fi
rm -rf "$OUTPUT_DIR"
mkdir -p "$OUTPUT_DIR"
INPUT_PATH="$(canonicalize_path "$INPUT_PATH")"
OUTPUT_DIR="$(canonicalize_path "$OUTPUT_DIR")"
REPO_ROOT="$(cd "$SCRIPT_DIR/.." && pwd -P)"
CURRENT_DIR="$(pwd -P)"
case "$OUTPUT_DIR" in
"/"|"$HOME"|"$REPO_ROOT"|"$SCRIPT_DIR"|"$CURRENT_DIR")
echo "Refusing unsafe output directory: $OUTPUT_DIR" >&2
exit 1
;;
esac
case "$INPUT_PATH" in
"$OUTPUT_DIR"|"$OUTPUT_DIR"/*)
echo "Refusing output directory that contains the input bundle: $OUTPUT_DIR" >&2
exit 1
;;
esac
OUTPUT_PARENT="$(dirname "$OUTPUT_DIR")"
OUTPUT_BASENAME="$(basename "$OUTPUT_DIR")"
TEMP_DIR="$(mktemp -d "$OUTPUT_PARENT/.${OUTPUT_BASENAME}.tmp.XXXXXX")"
BACKUP_DIR=""
cleanup() {
if [[ -n "$TEMP_DIR" && -d "$TEMP_DIR" ]]; then
rm -rf "$TEMP_DIR"
fi
if [[ -n "$BACKUP_DIR" && -e "$BACKUP_DIR" ]]; then
if [[ ! -e "$OUTPUT_DIR" ]]; then
mv "$BACKUP_DIR" "$OUTPUT_DIR"
else
rm -rf "$BACKUP_DIR"
fi
fi
}
trap cleanup EXIT
go run "$SCRIPT_DIR/ext_tool" \
-input "$INPUT_PATH" \
-output "$OUTPUT_DIR" \
-output "$TEMP_DIR" \
-skip-format \
-strict
if [[ -e "$OUTPUT_DIR" ]]; then
BACKUP_DIR="$(mktemp -d "$OUTPUT_PARENT/.${OUTPUT_BASENAME}.backup.XXXXXX")"
rmdir "$BACKUP_DIR"
mv "$OUTPUT_DIR" "$BACKUP_DIR"
fi
mv "$TEMP_DIR" "$OUTPUT_DIR"
TEMP_DIR=""
if [[ -n "$BACKUP_DIR" ]]; then
rm -rf "$BACKUP_DIR"
BACKUP_DIR=""
fi
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+809
View File
@@ -0,0 +1,809 @@
syntax = "proto3";
package git_forge.v1;
option go_package = "react-admin/cursor-server/gen/git_forge/v1;git_forgev1";
// Copied from: local:git_forge.v1.BatchGetRepoContentRequest (var: Qt)
message BatchGetRepoContentRequest {
string repo_uuid = 1;
string revision = 2;
repeated string paths = 3;
}
// Copied from: local:git_forge.v1.BatchGetRepoContentResponse (var: Ht)
message BatchGetRepoContentResponse {
repeated BatchRepoContentResult results = 1;
string resolved_commit_sha = 2;
}
// Copied from: local:git_forge.v1.BatchRepoContentResult (var: Gt)
message BatchRepoContentResult {
string path = 1;
bool found = 2;
oneof content {
FileContent file_content = 3;
DirectoryContent directory_content = 4;
}
}
// Copied from: local:git_forge.v1.BlameChunk (var: sn)
message BlameChunk {
repeated ShortCommit commits = 1;
repeated BlameLineRange line_ranges = 2;
}
// Copied from: local:git_forge.v1.BlameLineRange (var: rn)
message BlameLineRange {
bytes commit_sha = 1;
uint32 start_in_blamed_file = 2;
uint32 len = 3;
}
// Copied from: local:git_forge.v1.CanMergeRequest (var: ft)
message CanMergeRequest {
string repo_uuid = 1;
string ours = 2;
string theirs = 3;
uint64 change_number = 4;
MergeMode mode = 7;
}
// Copied from: local:git_forge.v1.CanMergeResponse (var: gt)
message CanMergeResponse {
bool can_merge_without_conflicts = 1;
optional bytes merged_tree_sha = 2;
repeated string conflicted_paths = 3;
}
// Copied from: local:git_forge.v1.ChangeKind (var: _)
enum ChangeKind {
CHANGE_KIND_UNSPECIFIED = 0;
CHANGE_KIND_ADDED = 1;
CHANGE_KIND_DELETED = 2;
CHANGE_KIND_MODIFIED = 3;
CHANGE_KIND_RENAMED = 4;
CHANGE_KIND_COPIED = 5;
}
// Copied from: local:git_forge.v1.ChangedFile (var: Nn)
message ChangedFile {
string path = 1;
optional string old_path = 2;
ChangeKind change_kind = 3;
optional FileMode old_mode = 4;
optional FileMode new_mode = 5;
optional string old_sha = 6;
optional string new_sha = 7;
}
// Copied from: local:git_forge.v1.ChangedFileWithStats (var: Pn)
message ChangedFileWithStats {
string path = 1;
optional string old_path = 2;
ChangeKind change_kind = 3;
bool is_binary = 4;
int32 additions = 5;
int32 deletions = 6;
optional FileMode old_mode = 7;
optional FileMode new_mode = 8;
optional string old_sha = 9;
optional string new_sha = 10;
}
// Copied from: local:git_forge.v1.Commit (var: bt)
message Commit {
string sha = 1;
string message = 2;
Signature author = 3;
Signature committer = 4;
repeated string parent_shas = 5;
string tree_sha = 7;
optional string change_id = 8;
}
// Copied from: local:git_forge.v1.CommitDiffChunk (var: Jn)
message CommitDiffChunk {
optional CommitDiffHeader header = 1;
repeated FileDiff file_diffs = 2;
}
// Copied from: local:git_forge.v1.CommitDiffHeader (var: Bn)
message CommitDiffHeader {
Commit commit = 1;
optional string base_commit_sha = 2;
CommitDiffStats stats = 3;
repeated ChangedFileWithStats changed_files = 4;
bool has_more = 5;
optional string next_page_cursor = 6;
}
// Copied from: local:git_forge.v1.CommitDiffStats (var: Rn)
message CommitDiffStats {
uint32 files_changed = 1;
int32 additions = 2;
int32 deletions = 3;
}
// Copied from: local:git_forge.v1.CommitFileDelete (var: Ct)
message CommitFileDelete {
}
// Copied from: local:git_forge.v1.CommitFileMode (var: g)
enum CommitFileMode {
COMMIT_FILE_MODE_UNSPECIFIED = 0;
COMMIT_FILE_MODE_REGULAR = 1;
COMMIT_FILE_MODE_EXECUTABLE = 2;
COMMIT_FILE_MODE_SYMLINK = 3;
}
// Copied from: local:git_forge.v1.CommitFileOperation (var: Nt)
message CommitFileOperation {
string path = 1;
oneof operation {
CommitFileUpsert upsert = 2;
CommitFileDelete delete = 3;
}
}
// Copied from: local:git_forge.v1.CommitFileUpsert (var: Jt)
message CommitFileUpsert {
bytes content = 1;
CommitFileMode mode = 2;
}
// Copied from: local:git_forge.v1.CompareCommitsRequest (var: dt)
message CompareCommitsRequest {
string repo_uuid = 1;
string base_revision = 2;
string head_revision = 3;
}
// Copied from: local:git_forge.v1.CompareCommitsResponse (var: pt)
message CompareCommitsResponse {
CompareCommitsStatus status = 1;
int32 ahead_by = 2;
int32 behind_by = 3;
string base_commit_sha = 4;
string head_commit_sha = 5;
string merge_base_commit_sha = 6;
}
// Copied from: local:git_forge.v1.CompareCommitsStatus (var: p)
enum CompareCommitsStatus {
COMPARE_COMMITS_STATUS_UNSPECIFIED = 0;
COMPARE_COMMITS_STATUS_IDENTICAL = 1;
COMPARE_COMMITS_STATUS_AHEAD = 2;
COMPARE_COMMITS_STATUS_BEHIND = 3;
COMPARE_COMMITS_STATUS_DIVERGED = 4;
}
// Copied from: local:git_forge.v1.ComputeMergeCommitRequest (var: _t)
message ComputeMergeCommitRequest {
string repo_uuid = 1;
string ours_sha = 2;
string theirs_sha = 3;
string message = 4;
Signature author = 5;
Signature committer = 6;
MergeMode mode = 7;
}
// Copied from: local:git_forge.v1.ComputeMergeCommitResponse (var: Tt)
message ComputeMergeCommitResponse {
string merge_commit_sha = 1;
bytes packfile = 2;
}
// Copied from: local:git_forge.v1.CreateCommitFromFilesRequest (var: Rt)
message CreateCommitFromFilesRequest {
string repo_uuid = 1;
string target_ref = 2;
optional string expected_head_sha = 3;
string message = 4;
Signature author = 5;
optional Signature committer = 6;
repeated CommitFileOperation files = 7;
}
// Copied from: local:git_forge.v1.CreateCommitFromFilesResponse (var: Pt)
message CreateCommitFromFilesResponse {
string commit_sha = 1;
string tree_sha = 2;
string old_head_sha = 3;
string wal_entry_key = 4;
}
// Copied from: local:git_forge.v1.CreateMergeCommitRequest (var: ht)
message CreateMergeCommitRequest {
string repo_uuid = 1;
optional string ours_sha = 2;
optional string theirs_sha = 3;
string ours_ref = 4;
string theirs_ref = 5;
string message = 6;
Signature author = 7;
Signature committer = 8;
uint64 change_number = 9;
MergeMode mode = 10;
}
// Copied from: local:git_forge.v1.CreateMergeCommitResponse (var: At)
message CreateMergeCommitResponse {
string merge_commit_sha = 1;
string wal_entry_key = 2;
}
// Copied from: local:git_forge.v1.CreateRepoRequest (var: wn)
message CreateRepoRequest {
string repo_uuid = 1;
}
// Copied from: local:git_forge.v1.CreateRepoResponse (var: En)
message CreateRepoResponse {
}
// Copied from: local:git_forge.v1.DiffHeader (var: Cn)
message DiffHeader {
string merge_base_commit_sha = 1;
repeated ChangedFile files = 2;
repeated ChangedFileWithStats files_with_stats = 3;
bool has_more = 4;
optional string next_page_cursor = 5;
}
// Copied from: local:git_forge.v1.DirectoryContent (var: qt)
message DirectoryContent {
repeated RepoContentEntry entries = 1;
string sha = 2;
}
// Copied from: local:git_forge.v1.FastForwardRefRequest (var: qn)
message FastForwardRefRequest {
string repo_uuid = 1;
string target_ref = 2;
string expected_head_sha = 3;
string new_head_sha = 4;
}
// Copied from: local:git_forge.v1.FastForwardRefResponse (var: Dn)
message FastForwardRefResponse {
string old_head_sha = 1;
string new_head_sha = 2;
string wal_entry_key = 3;
bool unchanged = 4;
}
// Copied from: local:git_forge.v1.FileContent (var: Ft)
message FileContent {
string size = 1;
string encoding = 2;
string content = 3;
string sha = 4;
}
// Copied from: local:git_forge.v1.FileDiff (var: bn)
message FileDiff {
string path = 1;
optional string old_path = 2;
bool is_binary = 3;
string patch = 4;
int32 additions = 5;
int32 deletions = 6;
optional FileMode old_mode = 7;
optional FileMode new_mode = 8;
optional string old_sha = 9;
optional string new_sha = 10;
}
// Copied from: local:git_forge.v1.FileHistoryCommitEntry (var: Zt)
message FileHistoryCommitEntry {
ShortCommit commit = 1;
optional string diff_base_commit_sha = 2;
optional FileHistoryPathStats path_stats = 8;
}
// Copied from: local:git_forge.v1.FileHistoryPathStats (var: Xt)
message FileHistoryPathStats {
int32 additions = 1;
int32 deletions = 2;
bool is_binary = 3;
}
// Copied from: local:git_forge.v1.FileHistoryWithDiffStatsChunk (var: en)
message FileHistoryWithDiffStatsChunk {
repeated FileHistoryCommitEntry entries = 1;
bool exhausted = 2;
}
// Copied from: local:git_forge.v1.FileMode (var: A)
enum FileMode {
FILE_MODE_UNSPECIFIED = 0;
FILE_MODE_REGULAR = 1;
FILE_MODE_EXECUTABLE = 2;
FILE_MODE_SYMLINK = 3;
FILE_MODE_GITLINK = 4;
}
// Copied from: local:git_forge.v1.GetBlameRequest (var: nn)
message GetBlameRequest {
string repo_uuid = 1;
string start_commit_sha = 2;
string path = 3;
}
// Copied from: local:git_forge.v1.GetBlobRequest (var: $e)
message GetBlobRequest {
string repo_uuid = 1;
string blob_sha = 2;
}
// Copied from: local:git_forge.v1.GetBlobResponse (var: et)
message GetBlobResponse {
FileContent blob = 1;
}
// Copied from: local:git_forge.v1.GetCommitDiffRequest (var: vn)
message GetCommitDiffRequest {
string repo_uuid = 1;
string commit_sha = 2;
optional string base_commit_sha = 3;
bool include_patches = 4;
repeated string paths = 5;
optional uint32 page_size = 6;
optional string page_cursor = 7;
}
// Copied from: local:git_forge.v1.GetCommitRequest (var: Xe)
message GetCommitRequest {
string repo_uuid = 1;
string commit_sha = 2;
}
// Copied from: local:git_forge.v1.GetCommitResponse (var: Ze)
message GetCommitResponse {
Commit commit = 1;
}
// Copied from: local:git_forge.v1.GetFileHistoryPageWithDiffStatsResponse (var: tn)
message GetFileHistoryPageWithDiffStatsResponse {
repeated FileHistoryCommitEntry entries = 1;
bool has_more = 2;
optional string next_cursor = 3;
}
// Copied from: local:git_forge.v1.GetFileHistoryRequest (var: Wt)
message GetFileHistoryRequest {
string repo_uuid = 1;
string start_commit_sha = 2;
optional string path = 3;
uint32 max_commits = 4;
}
// Copied from: local:git_forge.v1.GetFileHistoryResponse (var: zt)
message GetFileHistoryResponse {
repeated ShortCommit commits = 1;
}
// Copied from: local:git_forge.v1.GetFileHistoryWithDiffStatsRequest (var: jt)
message GetFileHistoryWithDiffStatsRequest {
string repo_uuid = 1;
string start_commit_sha = 2;
optional string path = 3;
uint32 max_commits = 4;
optional string next_cursor = 5;
bool include_diff_stats = 6;
}
// Copied from: local:git_forge.v1.GetFileHistoryWithDiffStatsResponse (var: $t)
message GetFileHistoryWithDiffStatsResponse {
repeated FileHistoryCommitEntry entries = 1;
bool has_more = 2;
optional string next_cursor = 3;
}
// Copied from: local:git_forge.v1.GetFuzzyPathsRequest (var: un)
message GetFuzzyPathsRequest {
string repo_uuid = 1;
string commit_sha = 2;
string query = 3;
uint32 limit = 4;
}
// Copied from: local:git_forge.v1.GetFuzzyPathsResponse (var: mn)
message GetFuzzyPathsResponse {
repeated string paths = 1;
bool has_more = 2;
}
// Copied from: local:git_forge.v1.GetLocalDevInfoRequest (var: ze)
message GetLocalDevInfoRequest {
}
// Copied from: local:git_forge.v1.GetLocalDevInfoResponse (var: je)
message GetLocalDevInfoResponse {
string repo_uuid = 1;
string git_forge_root_dir = 2;
}
// Copied from: local:git_forge.v1.GetPullRequestDiffRequest (var: Sn)
message GetPullRequestDiffRequest {
string repo_uuid = 1;
string head_commit_sha = 2;
string base_commit_sha = 3;
optional bool include_patches = 4;
optional uint32 page_size = 5;
optional string page_cursor = 6;
optional bool include_file_stats = 7;
}
// Copied from: local:git_forge.v1.GetRepoContentDetailsRequest (var: Yt)
message GetRepoContentDetailsRequest {
string repo_uuid = 1;
PathIdentifier path_identifier = 2;
}
// Copied from: local:git_forge.v1.GetRepoContentDetailsResponse (var: Kt)
message GetRepoContentDetailsResponse {
optional RepoContentDetails details = 1;
PathIdentifier path_identifier = 2;
string resolved_commit_sha = 3;
}
// Copied from: local:git_forge.v1.GetRepoContentRequest (var: Ut)
message GetRepoContentRequest {
string repo_uuid = 1;
oneof id {
PathIdentifier path_identifier = 2;
string ref_and_path = 3;
}
}
// Copied from: local:git_forge.v1.GetRepoContentResponse (var: xt)
message GetRepoContentResponse {
PathIdentifier path_identifier = 3;
string resolved_commit_sha = 4;
oneof content {
FileContent file_content = 1;
DirectoryContent directory_content = 2;
}
}
// Copied from: local:git_forge.v1.GetTagRequest (var: tt)
message GetTagRequest {
string repo_uuid = 1;
string tag_sha = 2;
}
// Copied from: local:git_forge.v1.GetTagResponse (var: nt)
message GetTagResponse {
Tag tag = 1;
}
// Copied from: local:git_forge.v1.GetTreeBlameRequest (var: on)
message GetTreeBlameRequest {
string repo_uuid = 1;
string start_commit_sha = 2;
string path = 3;
}
// Copied from: local:git_forge.v1.GetTreeBlameResponse (var: ln)
message GetTreeBlameResponse {
repeated TreeEntryBlame entries = 1;
}
// Copied from: local:git_forge.v1.GetTreeRequest (var: rt)
message GetTreeRequest {
string repo_uuid = 1;
string tree_sha = 2;
bool recursive = 3;
}
// Copied from: local:git_forge.v1.GetTreeResponse (var: st)
message GetTreeResponse {
Tree tree = 1;
}
// Copied from: local:git_forge.v1.GrepLineKind (var: h)
enum GrepLineKind {
GREP_LINE_KIND_UNSPECIFIED = 0;
GREP_LINE_KIND_MATCH = 1;
GREP_LINE_KIND_CONTEXT = 2;
}
// Copied from: local:git_forge.v1.GrepMatch (var: hn)
message GrepMatch {
string path = 1;
string lines = 2;
uint32 line_number = 3;
uint64 absolute_offset = 4;
repeated GrepSubmatch submatches = 5;
GrepLineKind kind = 6;
}
// Copied from: local:git_forge.v1.GrepRepoChunk (var: An)
message GrepRepoChunk {
repeated GrepMatch matches = 1;
bool limit_hit = 2;
}
// Copied from: local:git_forge.v1.GrepRepoRequest (var: fn)
message GrepRepoRequest {
string repo_uuid = 1;
string revision = 2;
string query = 3;
GrepSearchOptions options = 4;
uint32 max_results = 5;
}
// Copied from: local:git_forge.v1.GrepSearchOptions (var: pn)
message GrepSearchOptions {
bool literal = 1;
bool case_insensitive = 2;
bool whole_word = 3;
uint32 context_before = 4;
uint32 context_after = 5;
optional uint64 max_lines = 6;
optional string filter_path = 7;
repeated string includes = 8;
repeated string excludes = 9;
}
// Copied from: local:git_forge.v1.GrepSubmatch (var: gn)
message GrepSubmatch {
uint32 start = 1;
uint32 end = 2;
}
// Copied from: local:git_forge.v1.ListCommitsInRangeRequest (var: mt)
message ListCommitsInRangeRequest {
string repo_uuid = 1;
string base_revision = 2;
string head_revision = 3;
optional int32 max_commits = 4;
bool oldest_first = 5;
ListCommitsSort sort = 6;
}
// Copied from: local:git_forge.v1.ListCommitsInRangeResponse (var: ct)
message ListCommitsInRangeResponse {
repeated Commit commits = 1;
string base_commit_sha = 2;
string head_commit_sha = 3;
string merge_base_commit_sha = 4;
bool truncated = 5;
}
// Copied from: local:git_forge.v1.ListCommitsRequest (var: lt)
message ListCommitsRequest {
string repo_uuid = 1;
string revision = 2;
int32 page = 3;
int32 per_page = 4;
ListCommitsSort sort = 5;
}
// Copied from: local:git_forge.v1.ListCommitsResponse (var: ut)
message ListCommitsResponse {
repeated Commit commits = 1;
optional int32 next_page = 2;
}
// Copied from: local:git_forge.v1.ListCommitsSort (var: y)
enum ListCommitsSort {
LIST_COMMITS_SORT_UNSPECIFIED = 0;
LIST_COMMITS_SORT_COMMIT_TIME = 1;
LIST_COMMITS_SORT_TOPOLOGICAL = 2;
}
// Copied from: local:git_forge.v1.ListRefsFilter (var: T)
enum ListRefsFilter {
LIST_REFS_FILTER_UNSPECIFIED = 0;
LIST_REFS_FILTER_ALL = 1;
LIST_REFS_FILTER_BRANCHES = 2;
LIST_REFS_FILTER_TAGS = 3;
}
// Copied from: local:git_forge.v1.ListRefsRequest (var: Mn)
message ListRefsRequest {
string repo_uuid = 1;
ListRefsFilter filter = 2;
bool names_only = 3;
string prefix = 4;
}
// Copied from: local:git_forge.v1.ListRefsResponse (var: Fn)
message ListRefsResponse {
repeated string refs = 1;
repeated RefInfo ref_infos = 2;
}
// Copied from: local:git_forge.v1.ListTreePathsRequest (var: cn)
message ListTreePathsRequest {
string repo_uuid = 1;
string revision = 2;
repeated string includes = 3;
repeated string excludes = 4;
uint32 limit = 5;
}
// Copied from: local:git_forge.v1.ListTreePathsResponse (var: dn)
message ListTreePathsResponse {
repeated string paths = 1;
bool has_more = 2;
}
// Copied from: local:git_forge.v1.MergeMode (var: f)
enum MergeMode {
MERGE_MODE_UNSPECIFIED = 0;
MERGE_MODE_MERGE_COMMIT = 1;
MERGE_MODE_SQUASH = 2;
}
// Copied from: local:git_forge.v1.NotifyRepoPushedRequest (var: _n)
message NotifyRepoPushedRequest {
string repo_uuid = 1;
}
// Copied from: local:git_forge.v1.NotifyRepoPushedResponse (var: Tn)
message NotifyRepoPushedResponse {
}
// Copied from: local:git_forge.v1.PathIdentifier (var: Lt)
message PathIdentifier {
string revision = 1;
string path = 2;
}
// Copied from: local:git_forge.v1.PrepareChangeMergeRequest (var: yt)
message PrepareChangeMergeRequest {
string repo_uuid = 1;
string base_ref = 2;
string head_ref = 3;
uint64 change_number = 4;
optional string expected_base_sha = 5;
optional string expected_head_sha = 6;
MergeMode mode = 7;
}
// Copied from: local:git_forge.v1.PrepareChangeMergeResponse (var: kt)
message PrepareChangeMergeResponse {
bool mergeable = 1;
optional string merged_tree_sha = 2;
optional string change_merge_ref = 3;
optional string dummy_commit_sha = 4;
}
// Copied from: local:git_forge.v1.PullRequestDiffChunk (var: In)
message PullRequestDiffChunk {
optional DiffHeader header = 1;
repeated FileDiff file_diffs = 2;
}
// Copied from: local:git_forge.v1.RebaseStackBranch (var: Et)
message RebaseStackBranch {
string head_ref = 1;
string expected_old_oid = 2;
}
// Copied from: local:git_forge.v1.RebaseStackBranchUpdate (var: vt)
message RebaseStackBranchUpdate {
string head_ref = 1;
string old_oid = 2;
string new_oid = 3;
}
// Copied from: local:git_forge.v1.RebaseStackConflict (var: Bt)
message RebaseStackConflict {
string conflicted_head_ref = 1;
repeated string conflicted_paths = 2;
}
// Copied from: local:git_forge.v1.RebaseStackRequest (var: wt)
message RebaseStackRequest {
string repo_uuid = 1;
string onto_ref = 2;
optional string expected_onto_oid = 3;
repeated RebaseStackBranch branches = 4;
}
// Copied from: local:git_forge.v1.RebaseStackResponse (var: St)
message RebaseStackResponse {
oneof result {
RebaseStackSuccess success = 1;
RebaseStackConflict conflict = 2;
}
}
// Copied from: local:git_forge.v1.RebaseStackSuccess (var: It)
message RebaseStackSuccess {
string wal_entry_key = 1;
repeated RebaseStackBranchUpdate updates = 2;
}
// Copied from: local:git_forge.v1.RefInfo (var: Ln)
message RefInfo {
string name = 1;
string target_sha = 2;
string object_sha = 3;
string object_type = 4;
}
// Copied from: local:git_forge.v1.RepoContentDetails (var: Vt)
message RepoContentDetails {
string type = 1;
optional uint64 size = 2;
bool is_binary = 3;
bool too_large_to_introspect = 4;
}
// Copied from: local:git_forge.v1.RepoContentEntry (var: kn)
message RepoContentEntry {
string type = 1;
string name = 2;
string path = 3;
string sha = 4;
optional uint64 size = 5;
}
// Copied from: local:git_forge.v1.ResolveRefPathRequest (var: Dt)
message ResolveRefPathRequest {
string repo_uuid = 1;
string ref_path = 2;
}
// Copied from: local:git_forge.v1.ResolveRefPathResponse (var: Ot)
message ResolveRefPathResponse {
PathIdentifier path_identifier = 1;
string resolved_commit_sha = 2;
}
// Copied from: local:git_forge.v1.ShortCommit (var: yn)
message ShortCommit {
bytes sha = 1;
string summary = 2;
string author_name = 3;
string author_email = 4;
int64 timestamp = 5;
}
// Copied from: local:git_forge.v1.Signature (var: Mt)
message Signature {
string name = 1;
string email = 2;
int64 timestamp = 3;
int32 timezone_offset = 4;
}
// Copied from: local:git_forge.v1.Tag (var: at)
message Tag {
string sha = 1;
string name = 2;
string message = 3;
Signature tagger = 4;
string object_sha = 5;
string object_type = 6;
}
// Copied from: local:git_forge.v1.Tree (var: ot)
message Tree {
string sha = 1;
repeated TreeEntry tree = 2;
bool truncated = 3;
}
// Copied from: local:git_forge.v1.TreeEntry (var: it)
message TreeEntry {
string path = 1;
string mode = 2;
string type = 3;
string sha = 4;
optional uint64 size = 5;
}
// Copied from: local:git_forge.v1.TreeEntryBlame (var: an)
message TreeEntryBlame {
string name = 1;
ShortCommit last_commit = 2;
}
+4 -4
View File
@@ -4,7 +4,7 @@ package internapi.v1;
option go_package = "react-admin/cursor-server/gen/internapi/v1;internapiv1";
// Copied from: local:internapi.v1.BlobData (var: hxe)
// Copied from: local:internapi.v1.BlobData (var: Mn)
message BlobData {
BlobType blob_type = 1;
bytes blob_id = 2;
@@ -14,12 +14,12 @@ message BlobData {
}
}
// Copied from: local:internapi.v1.BlobDataPerMessage (var: Txe)
// Copied from: local:internapi.v1.BlobDataPerMessage (var: Ln)
message BlobDataPerMessage {
repeated BlobData blob_data = 1;
}
// Copied from: local:internapi.v1.BlobType (var: Axe)
// Copied from: local:internapi.v1.BlobType (var: Nn)
enum BlobType {
BLOB_TYPE_UNSPECIFIED = 0;
BLOB_TYPE_IMAGE = 1;
@@ -34,7 +34,7 @@ enum BlobType {
BLOB_TYPE_VIDEO = 10;
}
// Copied from: local:internapi.v1.ImageBlobData (var: pxe)
// Copied from: local:internapi.v1.ImageBlobData (var: bn)
message ImageBlobData {
string mime_type = 1;
}
File diff suppressed because it is too large Load Diff
+2 -7
View File
@@ -8,11 +8,6 @@ QQ交流群:
Tg群组:
https://t.me/cursor_byok
- 修复commands无法识别的问题 @DedSecer
- 修复 summarize 指令(主动压缩) @DedSecer
- 修复 MiniMax 禁止 thinking 的问题 @Octopus
- 支持Fork message (需要新开对话) @DedSecer
- 支持 @关联对话 @DedSecer
- 支持插件市场(须登录你的任意账号) @aike1202
- 新增支持 cursor debugger 调试器, 用法请看.agents/skills/coding-guidance/SKILL.md
- 支持cursor-cli
- 修复对话中错误可能导致的消失问题