ADAPT-Chase commited on
Commit
67d20c0
·
verified ·
1 Parent(s): 007c72f

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +62 -0
  2. novas/novacore-QuantumGate/.env +83 -0
  3. novas/novacore-prime/.env.example +31 -0
  4. novas/novacore-promethius/.env.example +45 -0
  5. novas/novacore-quartz-glm45v/.env.cloudflare +25 -0
  6. novas/novacore-zephyr/claude-code-router/.env +48 -0
  7. projects/nova-z/.env.example +31 -0
  8. projects/oui-max/.env +27 -0
  9. projects/ui/qwen-code/packages/cli/src/commands/mcp/add.test.ts +122 -0
  10. projects/ui/qwen-code/packages/cli/src/commands/mcp/add.ts +222 -0
  11. projects/ui/qwen-code/packages/cli/src/commands/mcp/list.test.ts +154 -0
  12. projects/ui/qwen-code/packages/cli/src/commands/mcp/list.ts +139 -0
  13. projects/ui/qwen-code/packages/cli/src/commands/mcp/remove.test.ts +69 -0
  14. projects/ui/qwen-code/packages/cli/src/commands/mcp/remove.ts +60 -0
  15. projects/ui/qwen-code/packages/cli/src/services/prompt-processors/argumentProcessor.test.ts +41 -0
  16. projects/ui/qwen-code/packages/cli/src/services/prompt-processors/argumentProcessor.ts +23 -0
  17. projects/ui/qwen-code/packages/cli/src/services/prompt-processors/shellProcessor.test.ts +709 -0
  18. projects/ui/qwen-code/packages/cli/src/services/prompt-processors/shellProcessor.ts +248 -0
  19. projects/ui/qwen-code/packages/cli/src/services/prompt-processors/types.ts +44 -0
  20. projects/ui/qwen-code/packages/cli/src/ui/__snapshots__/App.test.tsx.snap +31 -0
  21. projects/ui/qwen-code/packages/cli/src/ui/commands/aboutCommand.test.ts +153 -0
  22. projects/ui/qwen-code/packages/cli/src/ui/commands/aboutCommand.ts +49 -0
  23. projects/ui/qwen-code/packages/cli/src/ui/commands/authCommand.test.ts +36 -0
  24. projects/ui/qwen-code/packages/cli/src/ui/commands/authCommand.ts +17 -0
  25. projects/ui/qwen-code/packages/cli/src/ui/commands/bugCommand.test.ts +114 -0
  26. projects/ui/qwen-code/packages/cli/src/ui/commands/bugCommand.ts +92 -0
  27. projects/ui/qwen-code/packages/cli/src/ui/commands/chatCommand.test.ts +414 -0
  28. projects/ui/qwen-code/packages/cli/src/ui/commands/chatCommand.ts +280 -0
  29. projects/ui/qwen-code/packages/cli/src/ui/commands/clearCommand.test.ts +100 -0
  30. projects/ui/qwen-code/packages/cli/src/ui/commands/clearCommand.ts +29 -0
  31. projects/ui/qwen-code/packages/cli/src/ui/commands/compressCommand.test.ts +129 -0
  32. projects/ui/qwen-code/packages/cli/src/ui/commands/compressCommand.ts +78 -0
  33. projects/ui/qwen-code/packages/cli/src/ui/commands/copyCommand.test.ts +296 -0
  34. projects/ui/qwen-code/packages/cli/src/ui/commands/copyCommand.ts +67 -0
  35. projects/ui/qwen-code/packages/cli/src/ui/commands/corgiCommand.test.ts +34 -0
  36. projects/ui/qwen-code/packages/cli/src/utils/sandbox-macos-restrictive-closed.sb +93 -0
  37. projects/ui/qwen-code/packages/cli/src/utils/sandbox-macos-restrictive-open.sb +96 -0
  38. projects/ui/qwen-code/packages/cli/src/utils/sandbox-macos-restrictive-proxied.sb +98 -0
  39. projects/ui/qwen-code/packages/cli/src/utils/sandbox.ts +962 -0
  40. projects/ui/qwen-code/packages/cli/src/utils/settingsUtils.test.ts +797 -0
  41. projects/ui/qwen-code/packages/cli/src/utils/settingsUtils.ts +489 -0
  42. projects/ui/qwen-code/packages/cli/src/utils/spawnWrapper.ts +9 -0
  43. projects/ui/qwen-code/packages/cli/src/utils/startupWarnings.test.ts +75 -0
  44. projects/ui/qwen-code/packages/cli/src/utils/startupWarnings.ts +40 -0
  45. projects/ui/qwen-code/packages/cli/src/utils/updateEventEmitter.ts +13 -0
  46. projects/ui/qwen-code/packages/cli/src/utils/userStartupWarnings.test.ts +87 -0
  47. projects/ui/qwen-code/packages/cli/src/utils/userStartupWarnings.ts +69 -0
  48. projects/ui/qwen-code/packages/cli/src/utils/version.ts +12 -0
  49. projects/ui/qwen-code/packages/cli/src/zed-integration/acp.ts +366 -0
  50. projects/ui/qwen-code/packages/cli/src/zed-integration/fileSystemService.ts +47 -0
.gitattributes CHANGED
@@ -4087,3 +4087,65 @@ platform/dbops/binaries/go/go/bin/go filter=lfs diff=lfs merge=lfs -text
4087
  platform/dbops/binaries/go/go/bin/gofmt filter=lfs diff=lfs merge=lfs -text
4088
  platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/el.dat filter=lfs diff=lfs merge=lfs -text
4089
  platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/en.dat filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4087
  platform/dbops/binaries/go/go/bin/gofmt filter=lfs diff=lfs merge=lfs -text
4088
  platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/el.dat filter=lfs diff=lfs merge=lfs -text
4089
  platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/en.dat filter=lfs diff=lfs merge=lfs -text
4090
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/eo.dat filter=lfs diff=lfs merge=lfs -text
4091
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/es.dat filter=lfs diff=lfs merge=lfs -text
4092
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/et.dat filter=lfs diff=lfs merge=lfs -text
4093
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/eu.dat filter=lfs diff=lfs merge=lfs -text
4094
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/fa.dat filter=lfs diff=lfs merge=lfs -text
4095
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ff_Adlm.dat filter=lfs diff=lfs merge=lfs -text
4096
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/fi.dat filter=lfs diff=lfs merge=lfs -text
4097
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/fil.dat filter=lfs diff=lfs merge=lfs -text
4098
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/fo.dat filter=lfs diff=lfs merge=lfs -text
4099
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/fr.dat filter=lfs diff=lfs merge=lfs -text
4100
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/frr.dat filter=lfs diff=lfs merge=lfs -text
4101
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/fy.dat filter=lfs diff=lfs merge=lfs -text
4102
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ga.dat filter=lfs diff=lfs merge=lfs -text
4103
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/gd.dat filter=lfs diff=lfs merge=lfs -text
4104
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/gl.dat filter=lfs diff=lfs merge=lfs -text
4105
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/gu.dat filter=lfs diff=lfs merge=lfs -text
4106
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ha.dat filter=lfs diff=lfs merge=lfs -text
4107
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/he.dat filter=lfs diff=lfs merge=lfs -text
4108
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/hi.dat filter=lfs diff=lfs merge=lfs -text
4109
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/hr.dat filter=lfs diff=lfs merge=lfs -text
4110
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/hsb.dat filter=lfs diff=lfs merge=lfs -text
4111
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/hu.dat filter=lfs diff=lfs merge=lfs -text
4112
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/hy.dat filter=lfs diff=lfs merge=lfs -text
4113
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ia.dat filter=lfs diff=lfs merge=lfs -text
4114
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/id.dat filter=lfs diff=lfs merge=lfs -text
4115
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/is.dat filter=lfs diff=lfs merge=lfs -text
4116
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/it.dat filter=lfs diff=lfs merge=lfs -text
4117
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ja.dat filter=lfs diff=lfs merge=lfs -text
4118
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/jv.dat filter=lfs diff=lfs merge=lfs -text
4119
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ka.dat filter=lfs diff=lfs merge=lfs -text
4120
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/kab.dat filter=lfs diff=lfs merge=lfs -text
4121
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/kgp.dat filter=lfs diff=lfs merge=lfs -text
4122
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/kk.dat filter=lfs diff=lfs merge=lfs -text
4123
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/kk_Arab.dat filter=lfs diff=lfs merge=lfs -text
4124
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/km.dat filter=lfs diff=lfs merge=lfs -text
4125
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/kn.dat filter=lfs diff=lfs merge=lfs -text
4126
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ko.dat filter=lfs diff=lfs merge=lfs -text
4127
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/kok.dat filter=lfs diff=lfs merge=lfs -text
4128
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ks.dat filter=lfs diff=lfs merge=lfs -text
4129
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ku.dat filter=lfs diff=lfs merge=lfs -text
4130
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ky.dat filter=lfs diff=lfs merge=lfs -text
4131
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/lb.dat filter=lfs diff=lfs merge=lfs -text
4132
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/lij.dat filter=lfs diff=lfs merge=lfs -text
4133
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/lo.dat filter=lfs diff=lfs merge=lfs -text
4134
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/lt.dat filter=lfs diff=lfs merge=lfs -text
4135
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/lv.dat filter=lfs diff=lfs merge=lfs -text
4136
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/mk.dat filter=lfs diff=lfs merge=lfs -text
4137
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ml.dat filter=lfs diff=lfs merge=lfs -text
4138
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/mn.dat filter=lfs diff=lfs merge=lfs -text
4139
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/mr.dat filter=lfs diff=lfs merge=lfs -text
4140
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ms.dat filter=lfs diff=lfs merge=lfs -text
4141
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/my.dat filter=lfs diff=lfs merge=lfs -text
4142
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ne.dat filter=lfs diff=lfs merge=lfs -text
4143
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/nl.dat filter=lfs diff=lfs merge=lfs -text
4144
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/no.dat filter=lfs diff=lfs merge=lfs -text
4145
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/nqo.dat filter=lfs diff=lfs merge=lfs -text
4146
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/or.dat filter=lfs diff=lfs merge=lfs -text
4147
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/pa.dat filter=lfs diff=lfs merge=lfs -text
4148
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/pcm.dat filter=lfs diff=lfs merge=lfs -text
4149
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/pl.dat filter=lfs diff=lfs merge=lfs -text
4150
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/ps.dat filter=lfs diff=lfs merge=lfs -text
4151
+ platform/dataops/dto/.venv/lib/python3.12/site-packages/babel/locale-data/pt.dat filter=lfs diff=lfs merge=lfs -text
novas/novacore-QuantumGate/.env ADDED
@@ -0,0 +1,83 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Vast.ai Credentials for India-2xH200 Server
2
+ VAST_AI_API_KEY=a236f77abde627d0a71658261fdf290c5fcae708d0f5ecc9f0caf2a9529b7547
3
+
4
+ # Server Configuration
5
+ SERVER_NAME=India-2xH200
6
+ SERVER_TYPE=H200
7
+ SERVER_LOCATION=India
8
+ INTERNAL_IP_RANGE=172.16.0.0/12
9
+
10
+ # SSH Connection Details
11
+ SSH_HOST=ssh8.vast.ai
12
+ SSH_PORT=26907
13
+ SSH_USER=root
14
+
15
+ # Internal Services (Memory Services)
16
+ MEMORY_SERVICE_1=localhost:18000
17
+ MEMORY_SERVICE_2=localhost:18010
18
+ MEMORY_SERVICE_3=localhost:18011
19
+ MEMORY_SERVICE_4=localhost:18012
20
+ MEMORY_SERVICE_5=localhost:17000
21
+
22
+ # Bandwidth Optimization (for cost control)
23
+ BANDWIDTH_COST_PER_GB=0.66
24
+ MAX_BANDWIDTH_MB=1000
25
+
26
+ # Repository Configuration
27
+ REPO_NAME=novacore-QuantumGate
28
+ REPO_OWNER=adaptnova
29
+ REPO_BRANCH_MAIN=main
30
+ REPO_BRANCH_DEV=dev
31
+ REPO_BRANCH_FEATURE=feature
32
+ REPO_BRANCH_ENV=env
33
+ REPO_BRANCH_SERVER=server
34
+
35
+ # Infrastructure Settings
36
+ INFRA_OPS_ROLE=Head of InfraOps
37
+ DEPLOYMENT_TYPE=bare-metal
38
+ CONTAINER_RUNTIME=dockerless
39
+ NETWORK_MODE=internal-only
40
+
41
+ # Security Settings
42
+ SSH_KEY_ALGORITHM=ed25519
43
+ FIREWALL_ENABLED=true
44
+ AUTO_UPDATE=false
45
+
46
+ # Monitoring
47
+ HEALTH_CHECK_INTERVAL=300
48
+ BANDWIDTH_MONITOR_ENABLED=true
49
+ LOG_RETENTION_DAYS=30
50
+
51
+ # ------------------------------------------------------------
52
+ # Registry & InfraOps Settings (QuantumGate)
53
+ # ------------------------------------------------------------
54
+ # Personal Nova workspace for this repo
55
+ PERSONAL_NOVA_DIR=/data/adaptai/novas/novacore-QuantumGate
56
+
57
+ # Accepted InfraOps location on platform
58
+ # InfraOps image home (platform)
59
+ INFRAOPS_DIR=/data/adaptai/platform/infraops/docker/images
60
+
61
+ # Platform InfraOps repo (private) and branching model
62
+ PLATFORM_INFRAOPS_REPO=adaptnova/platform-infraops
63
+ PLATFORM_INFRAOPS_REPO_VISIBILITY=private
64
+ PLATFORM_INFRAOPS_BRANCHES=main,server/*
65
+
66
+ # Docker registry access (Docker Hub)
67
+ DOCKER_REGISTRY=docker.io
68
+ DOCKER_NAMESPACE=adaptchase
69
+ DOCKER_USERNAME=adaptchase
70
+ DOCKER_REGISTRY_PERMS=read,write,delete
71
+
72
+ # Personal access token for Docker Hub CLI login
73
+ # Usage:
74
+ # echo "$DOCKER_HUB_PAT" | docker login -u "$DOCKER_USERNAME" --password-stdin
75
+ DOCKER_HUB_PAT=dckr_pat_r9rW9wyc6KQpo3C4h0Ha9x7X3Tw
76
+
77
+ # GHCR settings (secondary registry)
78
+ GHCR_REGISTRY=ghcr.io
79
+ GHCR_NAMESPACE=adaptnova
80
+
81
+ # Canonical image names (tags resolved in CI)
82
+ ELIZABETH_SERVE_IMAGE=${DOCKER_REGISTRY}/${DOCKER_NAMESPACE}/elizabeth-serve
83
+ ELIZABETH_TRAIN_IMAGE=${DOCKER_REGISTRY}/${DOCKER_NAMESPACE}/elizabeth-train
novas/novacore-prime/.env.example ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copy to .env and adjust values as needed
2
+
3
+ # API server
4
+ HOST=0.0.0.0
5
+ PORT=8000
6
+ API_KEY=change-me-please
7
+ METRICS_KEY=
8
+
9
+ # Model loading
10
+ # Prefer local path if available, else HF model id
11
+ # MODEL_PATH=/abs/path/to/qwen3-8b-elizabeth-simple
12
+ HF_MODEL_ID=LevelUp2x/qwen3-8b-elizabeth-simple
13
+
14
+ # CORS allowlist (comma-separated)
15
+ ALLOW_ORIGINS=http://localhost,http://127.0.0.1
16
+
17
+ # Redis / Dragonfly
18
+ REDIS_HOST=localhost
19
+ REDIS_PORT=18000
20
+ # REDIS_PASSWORD=
21
+
22
+ # Profiles root
23
+ NOVA_PROFILES_ROOT=/nfs/novas/profiles
24
+
25
+ # Client settings
26
+ API_BASE=http://localhost:8000
27
+
28
+ # Evaluation
29
+ EVAL_ROOT=/data/adaptai/projects/elizabeth/evaluation
30
+ EVAL_LIMIT=0
31
+ EVAL_STRICT=0
novas/novacore-promethius/.env.example ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ### NovaCore Prometheus environment (copy to .env and edit)
2
+
3
+ # Canonical DTO repo path (do not duplicate)
4
+ DTO_PATH=/data/adaptai/platform/dataops/dto
5
+
6
+ # DTO environment overlay to validate/generate
7
+ # Options: development | staging | production
8
+ DTO_ENVIRONMENT=production
9
+
10
+ # Server identity for inventory tracking
11
+ SERVER_NAME=vast1-2
12
+
13
+ # Secrets directory (env files only, not committed)
14
+ SECRETS_DIR=/data/adaptai/secrets
15
+
16
+ # Optional Python settings
17
+ # VENV_DIR=/data/adaptai/platform/dataops/dto/.venv
18
+ # PYTHON_BIN=python3
19
+
20
+ # Non-secret service endpoints (examples)
21
+ JANUSGRAPH_HOST=127.0.0.1
22
+ JANUSGRAPH_PORT=8182
23
+ SCYLLA_HOSTS=127.0.0.1
24
+ SCYLLA_PORT=9042
25
+ SCYLLA_KEYSPACE=dto
26
+ NATS_URL=nats://127.0.0.1:4222
27
+ DRAGONFLY_ENDPOINTS=127.0.0.1:18000
28
+
29
+ # ------------------------------------------------------------
30
+ # Registry settings (no secrets here; use GitHub Secrets)
31
+ # ------------------------------------------------------------
32
+ DOCKER_REGISTRY=docker.io
33
+ DOCKER_NAMESPACE=adaptchase
34
+ # DOCKERHUB_USERNAME=adaptchase # set in GitHub Secrets
35
+ # DOCKERHUB_TOKEN=<docker_hub_pat> # set in GitHub Secrets
36
+
37
+ GHCR_REGISTRY=ghcr.io
38
+ GHCR_NAMESPACE=adaptnova
39
+
40
+ # ------------------------------------------------------------
41
+ # Vault addresses (configure at runtime, not committed)
42
+ # ------------------------------------------------------------
43
+ # VAULT_ADDR=https://<hcp-vault-url>
44
+ # VAULT_TOKEN=<runtime_token>
45
+
novas/novacore-quartz-glm45v/.env.cloudflare ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Cloudflare Configuration - KEEP SECURE
2
+ # Domain: adaptdev.ai
3
+
4
+ # API Credentials
5
+ CLOUDFLARE_GLOBAL_API_KEY=a37d2db4459a2123f98ab635a2ac9a85c0380
6
+ CLOUDFLARE_ORIGIN_CA_KEY=v1.0-1d99fdecccc8b700e7bc44b4-0ba5f156f123c87a36e036b63cc1709194bb2c70a8cb5e0a98d13402f805a947227065152d4a6c7fd22ae40f0773fe617f8f6fa9ea06d5802c69b7cac4a1c0afb38f4d02129fd39c97
7
+ CLOUDFLARE_ADMIN_API_TOKEN=cH-8tuZdztKZyYvc2JlJRk78_TDksULXJ2WesbcC
8
+ CLOUDFLARE_R2_API_TOKEN=O-SGjpen4e9NdYJso4LCZPYpMPb_R9N-nZ6QGopY
9
+ CLOUDFLARE_WORKERS_R2_TOKEN=O-SGjpen4e9NdYJso4LCZPYpMPb_R9N-nZ6QGopY
10
+ CLOUDFLARE_WORKERS_FULL_TOKEN=uEhieo_hNeJ-yR3L8LZK2qKg5kjSkAqKOnAl5rob
11
+ CLOUDFLARE_WORKERS_AI_TOKEN=YOUR_NEW_WORKERS_AI_TOKEN_HERE
12
+
13
+ # Zone Configuration
14
+ CLOUDFLARE_ZONE_ID=7981a8217e9e9fc828a6ed793d81ad6c
15
+ CLOUDFLARE_ACCOUNT_ID=9bd70e8eb28637e723c8984b8c85c81e
16
+ CLOUDFLARE_DOMAIN=adaptdev.ai
17
+
18
+ # R2 S3 API Credentials
19
+ CLOUDFLARE_R2_ACCESS_KEY=e5c4452f8acdd362720e38d8b75707cd
20
+ CLOUDFLARE_R2_SECRET_KEY=b67d1ba6b2bfad98837a912eb012061b023c73524c1d29afde8a10d16a3f7554
21
+
22
+ # Service Endpoints
23
+ CLOUDFLARE_R2_ENDPOINT=https://9bd70e8eb28637e723c8984b8c85c81e.r2.cloudflarestorage.com
24
+ CLOUDFLARE_WORKERS_SUBDOMAIN=adaptdev
25
+ CLOUDFLARE_AI_GATEWAY=https://gateway.ai.cloudflare.com/v1/9bd70e8eb28637e723c8984b8c85c81e
novas/novacore-zephyr/claude-code-router/.env ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Kimi (Moonshot) Configuration (Primary - 128K context)
2
+ ANTHROPIC_BASE_URL=https://api.moonshot.cn/v1/chat/completions
3
+ ANTHROPIC_MODEL=kimi-k2-turbo-preview
4
+ ANTHROPIC_AUTH_TOKEN=sk-nTLc2WGLFgpXRZ76IPZPxTVJM7mhR8XKUDRd0GovsnliNbJ9
5
+ ANTHROPIC_API_KEY=sk-nTLc2WGLFgpXRZ76IPZPxTVJM7mhR8XKUDRd0GovsnliNbJ9
6
+
7
+ # Direct Kimi
8
+ MOONSHOT_BASE_URL=https://api.moonshot.cn/v1/chat/completions
9
+ MOONSHOT_API_KEY=sk-nTLc2WGLFgpXRZ76IPZPxTVJM7mhR8XKUDRd0GovsnliNbJ9
10
+
11
+ # CCR Configuration - Universal Kimi
12
+ CCR_DEFAULT_PROVIDER=moonshot
13
+ CCR_DEFAULT_MODEL=kimi-k2-turbo-preview
14
+ CCR_MAX_TOKENS=131072
15
+
16
+ # OpenAI (Fallback)
17
+ OPENAI_API_KEY=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
18
+ OPENAI_API_KEY_2=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
19
+
20
+ # Groq
21
+ GROQ_API_KEY=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
22
+ LM_GROQ_API_KEY=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
23
+
24
+ # Moonshot (Kimi)
25
+ MOONSHOT_AI_API_KEY=sk-nTLc2WGLFgpXRZ76IPZPxTVJM7mhR8XKUDRd0GovsnliNbJ9
26
+
27
+ # Replicate
28
+ REPLICATE_API_KEY=r8_4EeWRtznI4zF6RTFaQKdGwzWQbCPCTI4gA0tb
29
+
30
+ # Mistral
31
+ MISTRAL_API_KEY=F63TOQT71mRALyMXE2sLRXXsV4pr8Xtu
32
+ MISTRAL_MODEL=open-mixtral-8x22b
33
+
34
+ # Gemini AI Studio
35
+ GEMEINI_AI_STUDIO_API_KEY=AIzaSyBl3dMJ6WkapvZmtt_ai2r-9Ly0Tw7UZSk
36
+
37
+ # DeepSeek
38
+ DEEPSEEK_base_url=https://api.deepseek.com
39
+ DEEPSEEK_API_KEY=sk-a24089cabe414abbad6ca32aa15a6841
40
+
41
+ # z.ai
42
+ Z_AI_USER_ID=78661754977918738
43
+ Z_AI_BASE_URL=https://api.z.ai/api/paas/v4/
44
+ z_ai_api_key=4e020facea084849a3a27ba7eaba07e6.oWmgUFrwNL1wQdoP
45
+
46
+ # Grok (x.ai)
47
+ Grok_PERSONAL_API_Key=xai-0ajh9dOLn3UIYHJ7sZdv5VWaxcyKru1Xv7IXpSA0oG4ivIZJJZHuwubHC9uDY1OibQYuBDs5GcyppCqh
48
+ GROK_API_KEY=xai-3L1KlS5PJM1m7CrPTv2uEORlhrA0r8Y2BIxM7iDFVZZfkxtzYqAoLNZmKjzI7z8n2zMDkugwd1nr8jLW
projects/nova-z/.env.example ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copy to .env and adjust values as needed
2
+
3
+ # API server
4
+ HOST=0.0.0.0
5
+ PORT=8000
6
+ API_KEY=change-me-please
7
+ METRICS_KEY=
8
+
9
+ # Model loading
10
+ # Prefer local path if available, else HF model id
11
+ # MODEL_PATH=/abs/path/to/qwen3-8b-elizabeth-simple
12
+ HF_MODEL_ID=LevelUp2x/qwen3-8b-elizabeth-simple
13
+
14
+ # CORS allowlist (comma-separated)
15
+ ALLOW_ORIGINS=http://localhost,http://127.0.0.1
16
+
17
+ # Redis / Dragonfly
18
+ REDIS_HOST=localhost
19
+ REDIS_PORT=18000
20
+ # REDIS_PASSWORD=
21
+
22
+ # Profiles root
23
+ NOVA_PROFILES_ROOT=/nfs/novas/profiles
24
+
25
+ # Client settings
26
+ API_BASE=http://localhost:8000
27
+
28
+ # Evaluation
29
+ EVAL_ROOT=/data/adaptai/projects/elizabeth/evaluation
30
+ EVAL_LIMIT=0
31
+ EVAL_STRICT=0
projects/oui-max/.env ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ WEBUI_ROOT=/data/adaptai/migrate/vast/workspace-vast1-2/webui
2
+ WEBUI_DB=${WEBUI_ROOT}/webui.db
3
+ OUI_MAX_ROOT=/data/adaptai/projects/oui-max
4
+
5
+ # Data directories rooted under WEBUI_ROOT for portability
6
+ OUI_ARTIFACTS_DIR=${WEBUI_ROOT}/artifacts
7
+ OUI_WEB_DIR=${OUI_WEB_DIR}/web
8
+ OUI_PAGES_DIR=${OUI_WEB_DIR}/pages
9
+ OUI_PDF_DIR=${OUI_WEB_DIR}/pdf
10
+ OUI_TMP_DIR=${OUI_WEB_DIR}/tmp
11
+ OUI_RAG_DIR=${WEBUI_ROOT}/rag
12
+ OUI_MLFLOW_LITE_DIR=${WEBUI_ROOT}/mlflow_lite
13
+ OUI_INPUT_DIR=${WEBUI_ROOT}/input
14
+
15
+ # Optional: enable DB writes for db_admin.exec
16
+ # OUI_DB_ADMIN_WRITE=1
17
+
18
+ # Research mode: disable path guardrails (dangerous). Set to 1 for no constraints.
19
+ OUI_DISABLE_GUARDS=1
20
+
21
+ # Default LLM model for local coordination (Ollama)
22
+ OUI_DEFAULT_MODEL=qwen3:8b
23
+
24
+ # Disable authentication and persistent config for no-auth setup
25
+ WEBUI_AUTH=False
26
+ ENABLE_PERSISTENT_CONFIG=False
27
+ OLLAMA_URL=http://127.0.0.1:21434
projects/ui/qwen-code/packages/cli/src/commands/mcp/add.test.ts ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import yargs from 'yargs';
8
+ import { addCommand } from './add.js';
9
+ import { loadSettings, SettingScope } from '../../config/settings.js';
10
+
11
+ vi.mock('fs/promises', () => ({
12
+ readFile: vi.fn(),
13
+ writeFile: vi.fn(),
14
+ }));
15
+
16
+ vi.mock('../../config/settings.js', async () => {
17
+ const actual = await vi.importActual('../../config/settings.js');
18
+ return {
19
+ ...actual,
20
+ loadSettings: vi.fn(),
21
+ };
22
+ });
23
+
24
+ const mockedLoadSettings = loadSettings as vi.Mock;
25
+
26
+ describe('mcp add command', () => {
27
+ let parser: yargs.Argv;
28
+ let mockSetValue: vi.Mock;
29
+
30
+ beforeEach(() => {
31
+ vi.resetAllMocks();
32
+ const yargsInstance = yargs([]).command(addCommand);
33
+ parser = yargsInstance;
34
+ mockSetValue = vi.fn();
35
+ mockedLoadSettings.mockReturnValue({
36
+ forScope: () => ({ settings: {} }),
37
+ setValue: mockSetValue,
38
+ });
39
+ });
40
+
41
+ it('should add a stdio server to project settings', async () => {
42
+ await parser.parseAsync(
43
+ 'add my-server /path/to/server arg1 arg2 -e FOO=bar',
44
+ );
45
+
46
+ expect(mockSetValue).toHaveBeenCalledWith(
47
+ SettingScope.Workspace,
48
+ 'mcpServers',
49
+ {
50
+ 'my-server': {
51
+ command: '/path/to/server',
52
+ args: ['arg1', 'arg2'],
53
+ env: { FOO: 'bar' },
54
+ },
55
+ },
56
+ );
57
+ });
58
+
59
+ it('should add an sse server to user settings', async () => {
60
+ await parser.parseAsync(
61
+ 'add --transport sse sse-server https://example.com/sse-endpoint --scope user -H "X-API-Key: your-key"',
62
+ );
63
+
64
+ expect(mockSetValue).toHaveBeenCalledWith(SettingScope.User, 'mcpServers', {
65
+ 'sse-server': {
66
+ url: 'https://example.com/sse-endpoint',
67
+ headers: { 'X-API-Key': 'your-key' },
68
+ },
69
+ });
70
+ });
71
+
72
+ it('should add an http server to project settings', async () => {
73
+ await parser.parseAsync(
74
+ 'add --transport http http-server https://example.com/mcp -H "Authorization: Bearer your-token"',
75
+ );
76
+
77
+ expect(mockSetValue).toHaveBeenCalledWith(
78
+ SettingScope.Workspace,
79
+ 'mcpServers',
80
+ {
81
+ 'http-server': {
82
+ httpUrl: 'https://example.com/mcp',
83
+ headers: { Authorization: 'Bearer your-token' },
84
+ },
85
+ },
86
+ );
87
+ });
88
+
89
+ it('should handle MCP server args with -- separator', async () => {
90
+ await parser.parseAsync(
91
+ 'add my-server npx -- -y http://example.com/some-package',
92
+ );
93
+
94
+ expect(mockSetValue).toHaveBeenCalledWith(
95
+ SettingScope.Workspace,
96
+ 'mcpServers',
97
+ {
98
+ 'my-server': {
99
+ command: 'npx',
100
+ args: ['-y', 'http://example.com/some-package'],
101
+ },
102
+ },
103
+ );
104
+ });
105
+
106
+ it('should handle unknown options as MCP server args', async () => {
107
+ await parser.parseAsync(
108
+ 'add test-server npx -y http://example.com/some-package',
109
+ );
110
+
111
+ expect(mockSetValue).toHaveBeenCalledWith(
112
+ SettingScope.Workspace,
113
+ 'mcpServers',
114
+ {
115
+ 'test-server': {
116
+ command: 'npx',
117
+ args: ['-y', 'http://example.com/some-package'],
118
+ },
119
+ },
120
+ );
121
+ });
122
+ });
projects/ui/qwen-code/packages/cli/src/commands/mcp/add.ts ADDED
@@ -0,0 +1,222 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ // File for 'gemini mcp add' command
8
+ import type { CommandModule } from 'yargs';
9
+ import { loadSettings, SettingScope } from '../../config/settings.js';
10
+ import { MCPServerConfig } from '@qwen-code/qwen-code-core';
11
+
12
+ async function addMcpServer(
13
+ name: string,
14
+ commandOrUrl: string,
15
+ args: Array<string | number> | undefined,
16
+ options: {
17
+ scope: string;
18
+ transport: string;
19
+ env: string[] | undefined;
20
+ header: string[] | undefined;
21
+ timeout?: number;
22
+ trust?: boolean;
23
+ description?: string;
24
+ includeTools?: string[];
25
+ excludeTools?: string[];
26
+ },
27
+ ) {
28
+ const {
29
+ scope,
30
+ transport,
31
+ env,
32
+ header,
33
+ timeout,
34
+ trust,
35
+ description,
36
+ includeTools,
37
+ excludeTools,
38
+ } = options;
39
+ const settingsScope =
40
+ scope === 'user' ? SettingScope.User : SettingScope.Workspace;
41
+ const settings = loadSettings(process.cwd());
42
+
43
+ let newServer: Partial<MCPServerConfig> = {};
44
+
45
+ const headers = header?.reduce(
46
+ (acc, curr) => {
47
+ const [key, ...valueParts] = curr.split(':');
48
+ const value = valueParts.join(':').trim();
49
+ if (key.trim() && value) {
50
+ acc[key.trim()] = value;
51
+ }
52
+ return acc;
53
+ },
54
+ {} as Record<string, string>,
55
+ );
56
+
57
+ switch (transport) {
58
+ case 'sse':
59
+ newServer = {
60
+ url: commandOrUrl,
61
+ headers,
62
+ timeout,
63
+ trust,
64
+ description,
65
+ includeTools,
66
+ excludeTools,
67
+ };
68
+ break;
69
+ case 'http':
70
+ newServer = {
71
+ httpUrl: commandOrUrl,
72
+ headers,
73
+ timeout,
74
+ trust,
75
+ description,
76
+ includeTools,
77
+ excludeTools,
78
+ };
79
+ break;
80
+ case 'stdio':
81
+ default:
82
+ newServer = {
83
+ command: commandOrUrl,
84
+ args: args?.map(String),
85
+ env: env?.reduce(
86
+ (acc, curr) => {
87
+ const [key, value] = curr.split('=');
88
+ if (key && value) {
89
+ acc[key] = value;
90
+ }
91
+ return acc;
92
+ },
93
+ {} as Record<string, string>,
94
+ ),
95
+ timeout,
96
+ trust,
97
+ description,
98
+ includeTools,
99
+ excludeTools,
100
+ };
101
+ break;
102
+ }
103
+
104
+ const existingSettings = settings.forScope(settingsScope).settings;
105
+ const mcpServers = existingSettings.mcpServers || {};
106
+
107
+ const isExistingServer = !!mcpServers[name];
108
+ if (isExistingServer) {
109
+ console.log(
110
+ `MCP server "${name}" is already configured within ${scope} settings.`,
111
+ );
112
+ }
113
+
114
+ mcpServers[name] = newServer as MCPServerConfig;
115
+
116
+ settings.setValue(settingsScope, 'mcpServers', mcpServers);
117
+
118
+ if (isExistingServer) {
119
+ console.log(`MCP server "${name}" updated in ${scope} settings.`);
120
+ } else {
121
+ console.log(
122
+ `MCP server "${name}" added to ${scope} settings. (${transport})`,
123
+ );
124
+ }
125
+ }
126
+
127
+ export const addCommand: CommandModule = {
128
+ command: 'add <name> <commandOrUrl> [args...]',
129
+ describe: 'Add a server',
130
+ builder: (yargs) =>
131
+ yargs
132
+ .usage('Usage: gemini mcp add [options] <name> <commandOrUrl> [args...]')
133
+ .parserConfiguration({
134
+ 'unknown-options-as-args': true, // Pass unknown options as server args
135
+ 'populate--': true, // Populate server args after -- separator
136
+ })
137
+ .positional('name', {
138
+ describe: 'Name of the server',
139
+ type: 'string',
140
+ demandOption: true,
141
+ })
142
+ .positional('commandOrUrl', {
143
+ describe: 'Command (stdio) or URL (sse, http)',
144
+ type: 'string',
145
+ demandOption: true,
146
+ })
147
+ .option('scope', {
148
+ alias: 's',
149
+ describe: 'Configuration scope (user or project)',
150
+ type: 'string',
151
+ default: 'project',
152
+ choices: ['user', 'project'],
153
+ })
154
+ .option('transport', {
155
+ alias: 't',
156
+ describe: 'Transport type (stdio, sse, http)',
157
+ type: 'string',
158
+ default: 'stdio',
159
+ choices: ['stdio', 'sse', 'http'],
160
+ })
161
+ .option('env', {
162
+ alias: 'e',
163
+ describe: 'Set environment variables (e.g. -e KEY=value)',
164
+ type: 'array',
165
+ string: true,
166
+ })
167
+ .option('header', {
168
+ alias: 'H',
169
+ describe:
170
+ 'Set HTTP headers for SSE and HTTP transports (e.g. -H "X-Api-Key: abc123" -H "Authorization: Bearer abc123")',
171
+ type: 'array',
172
+ string: true,
173
+ })
174
+ .option('timeout', {
175
+ describe: 'Set connection timeout in milliseconds',
176
+ type: 'number',
177
+ })
178
+ .option('trust', {
179
+ describe:
180
+ 'Trust the server (bypass all tool call confirmation prompts)',
181
+ type: 'boolean',
182
+ })
183
+ .option('description', {
184
+ describe: 'Set the description for the server',
185
+ type: 'string',
186
+ })
187
+ .option('include-tools', {
188
+ describe: 'A comma-separated list of tools to include',
189
+ type: 'array',
190
+ string: true,
191
+ })
192
+ .option('exclude-tools', {
193
+ describe: 'A comma-separated list of tools to exclude',
194
+ type: 'array',
195
+ string: true,
196
+ })
197
+ .middleware((argv) => {
198
+ // Handle -- separator args as server args if present
199
+ if (argv['--']) {
200
+ const existingArgs = (argv['args'] as Array<string | number>) || [];
201
+ argv['args'] = [...existingArgs, ...(argv['--'] as string[])];
202
+ }
203
+ }),
204
+ handler: async (argv) => {
205
+ await addMcpServer(
206
+ argv['name'] as string,
207
+ argv['commandOrUrl'] as string,
208
+ argv['args'] as Array<string | number>,
209
+ {
210
+ scope: argv['scope'] as string,
211
+ transport: argv['transport'] as string,
212
+ env: argv['env'] as string[],
213
+ header: argv['header'] as string[],
214
+ timeout: argv['timeout'] as number | undefined,
215
+ trust: argv['trust'] as boolean | undefined,
216
+ description: argv['description'] as string | undefined,
217
+ includeTools: argv['includeTools'] as string[] | undefined,
218
+ excludeTools: argv['excludeTools'] as string[] | undefined,
219
+ },
220
+ );
221
+ },
222
+ };
projects/ui/qwen-code/packages/cli/src/commands/mcp/list.test.ts ADDED
@@ -0,0 +1,154 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, afterEach } from 'vitest';
8
+ import { listMcpServers } from './list.js';
9
+ import { loadSettings } from '../../config/settings.js';
10
+ import { loadExtensions } from '../../config/extension.js';
11
+ import { createTransport } from '@qwen-code/qwen-code-core';
12
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
13
+
14
+ vi.mock('../../config/settings.js');
15
+ vi.mock('../../config/extension.js');
16
+ vi.mock('@qwen-code/qwen-code-core');
17
+ vi.mock('@modelcontextprotocol/sdk/client/index.js');
18
+
19
+ const mockedLoadSettings = loadSettings as vi.Mock;
20
+ const mockedLoadExtensions = loadExtensions as vi.Mock;
21
+ const mockedCreateTransport = createTransport as vi.Mock;
22
+ const MockedClient = Client as vi.Mock;
23
+
24
+ interface MockClient {
25
+ connect: vi.Mock;
26
+ ping: vi.Mock;
27
+ close: vi.Mock;
28
+ }
29
+
30
+ interface MockTransport {
31
+ close: vi.Mock;
32
+ }
33
+
34
+ describe('mcp list command', () => {
35
+ let consoleSpy: vi.SpyInstance;
36
+ let mockClient: MockClient;
37
+ let mockTransport: MockTransport;
38
+
39
+ beforeEach(() => {
40
+ vi.resetAllMocks();
41
+
42
+ consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
43
+
44
+ mockTransport = { close: vi.fn() };
45
+ mockClient = {
46
+ connect: vi.fn(),
47
+ ping: vi.fn(),
48
+ close: vi.fn(),
49
+ };
50
+
51
+ MockedClient.mockImplementation(() => mockClient);
52
+ mockedCreateTransport.mockResolvedValue(mockTransport);
53
+ mockedLoadExtensions.mockReturnValue([]);
54
+ });
55
+
56
+ afterEach(() => {
57
+ consoleSpy.mockRestore();
58
+ });
59
+
60
+ it('should display message when no servers configured', async () => {
61
+ mockedLoadSettings.mockReturnValue({ merged: { mcpServers: {} } });
62
+
63
+ await listMcpServers();
64
+
65
+ expect(consoleSpy).toHaveBeenCalledWith('No MCP servers configured.');
66
+ });
67
+
68
+ it('should display different server types with connected status', async () => {
69
+ mockedLoadSettings.mockReturnValue({
70
+ merged: {
71
+ mcpServers: {
72
+ 'stdio-server': { command: '/path/to/server', args: ['arg1'] },
73
+ 'sse-server': { url: 'https://example.com/sse' },
74
+ 'http-server': { httpUrl: 'https://example.com/http' },
75
+ },
76
+ },
77
+ });
78
+
79
+ mockClient.connect.mockResolvedValue(undefined);
80
+ mockClient.ping.mockResolvedValue(undefined);
81
+
82
+ await listMcpServers();
83
+
84
+ expect(consoleSpy).toHaveBeenCalledWith('Configured MCP servers:\n');
85
+ expect(consoleSpy).toHaveBeenCalledWith(
86
+ expect.stringContaining(
87
+ 'stdio-server: /path/to/server arg1 (stdio) - Connected',
88
+ ),
89
+ );
90
+ expect(consoleSpy).toHaveBeenCalledWith(
91
+ expect.stringContaining(
92
+ 'sse-server: https://example.com/sse (sse) - Connected',
93
+ ),
94
+ );
95
+ expect(consoleSpy).toHaveBeenCalledWith(
96
+ expect.stringContaining(
97
+ 'http-server: https://example.com/http (http) - Connected',
98
+ ),
99
+ );
100
+ });
101
+
102
+ it('should display disconnected status when connection fails', async () => {
103
+ mockedLoadSettings.mockReturnValue({
104
+ merged: {
105
+ mcpServers: {
106
+ 'test-server': { command: '/test/server' },
107
+ },
108
+ },
109
+ });
110
+
111
+ mockClient.connect.mockRejectedValue(new Error('Connection failed'));
112
+
113
+ await listMcpServers();
114
+
115
+ expect(consoleSpy).toHaveBeenCalledWith(
116
+ expect.stringContaining(
117
+ 'test-server: /test/server (stdio) - Disconnected',
118
+ ),
119
+ );
120
+ });
121
+
122
+ it('should merge extension servers with config servers', async () => {
123
+ mockedLoadSettings.mockReturnValue({
124
+ merged: {
125
+ mcpServers: { 'config-server': { command: '/config/server' } },
126
+ },
127
+ });
128
+
129
+ mockedLoadExtensions.mockReturnValue([
130
+ {
131
+ config: {
132
+ name: 'test-extension',
133
+ mcpServers: { 'extension-server': { command: '/ext/server' } },
134
+ },
135
+ },
136
+ ]);
137
+
138
+ mockClient.connect.mockResolvedValue(undefined);
139
+ mockClient.ping.mockResolvedValue(undefined);
140
+
141
+ await listMcpServers();
142
+
143
+ expect(consoleSpy).toHaveBeenCalledWith(
144
+ expect.stringContaining(
145
+ 'config-server: /config/server (stdio) - Connected',
146
+ ),
147
+ );
148
+ expect(consoleSpy).toHaveBeenCalledWith(
149
+ expect.stringContaining(
150
+ 'extension-server: /ext/server (stdio) - Connected',
151
+ ),
152
+ );
153
+ });
154
+ });
projects/ui/qwen-code/packages/cli/src/commands/mcp/list.ts ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ // File for 'gemini mcp list' command
8
+ import type { CommandModule } from 'yargs';
9
+ import { loadSettings } from '../../config/settings.js';
10
+ import {
11
+ MCPServerConfig,
12
+ MCPServerStatus,
13
+ createTransport,
14
+ } from '@qwen-code/qwen-code-core';
15
+ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
16
+ import { loadExtensions } from '../../config/extension.js';
17
+
18
+ const COLOR_GREEN = '\u001b[32m';
19
+ const COLOR_YELLOW = '\u001b[33m';
20
+ const COLOR_RED = '\u001b[31m';
21
+ const RESET_COLOR = '\u001b[0m';
22
+
23
+ async function getMcpServersFromConfig(): Promise<
24
+ Record<string, MCPServerConfig>
25
+ > {
26
+ const settings = loadSettings(process.cwd());
27
+ const extensions = loadExtensions(process.cwd());
28
+ const mcpServers = { ...(settings.merged.mcpServers || {}) };
29
+ for (const extension of extensions) {
30
+ Object.entries(extension.config.mcpServers || {}).forEach(
31
+ ([key, server]) => {
32
+ if (mcpServers[key]) {
33
+ return;
34
+ }
35
+ mcpServers[key] = {
36
+ ...server,
37
+ extensionName: extension.config.name,
38
+ };
39
+ },
40
+ );
41
+ }
42
+ return mcpServers;
43
+ }
44
+
45
+ async function testMCPConnection(
46
+ serverName: string,
47
+ config: MCPServerConfig,
48
+ ): Promise<MCPServerStatus> {
49
+ const client = new Client({
50
+ name: 'mcp-test-client',
51
+ version: '0.0.1',
52
+ });
53
+
54
+ let transport;
55
+ try {
56
+ // Use the same transport creation logic as core
57
+ transport = await createTransport(serverName, config, false);
58
+ } catch (_error) {
59
+ await client.close();
60
+ return MCPServerStatus.DISCONNECTED;
61
+ }
62
+
63
+ try {
64
+ // Attempt actual MCP connection with short timeout
65
+ await client.connect(transport, { timeout: 5000 }); // 5s timeout
66
+
67
+ // Test basic MCP protocol by pinging the server
68
+ await client.ping();
69
+
70
+ await client.close();
71
+ return MCPServerStatus.CONNECTED;
72
+ } catch (_error) {
73
+ await transport.close();
74
+ return MCPServerStatus.DISCONNECTED;
75
+ }
76
+ }
77
+
78
+ async function getServerStatus(
79
+ serverName: string,
80
+ server: MCPServerConfig,
81
+ ): Promise<MCPServerStatus> {
82
+ // Test all server types by attempting actual connection
83
+ return await testMCPConnection(serverName, server);
84
+ }
85
+
86
+ export async function listMcpServers(): Promise<void> {
87
+ const mcpServers = await getMcpServersFromConfig();
88
+ const serverNames = Object.keys(mcpServers);
89
+
90
+ if (serverNames.length === 0) {
91
+ console.log('No MCP servers configured.');
92
+ return;
93
+ }
94
+
95
+ console.log('Configured MCP servers:\n');
96
+
97
+ for (const serverName of serverNames) {
98
+ const server = mcpServers[serverName];
99
+
100
+ const status = await getServerStatus(serverName, server);
101
+
102
+ let statusIndicator = '';
103
+ let statusText = '';
104
+ switch (status) {
105
+ case MCPServerStatus.CONNECTED:
106
+ statusIndicator = COLOR_GREEN + '✓' + RESET_COLOR;
107
+ statusText = 'Connected';
108
+ break;
109
+ case MCPServerStatus.CONNECTING:
110
+ statusIndicator = COLOR_YELLOW + '…' + RESET_COLOR;
111
+ statusText = 'Connecting';
112
+ break;
113
+ case MCPServerStatus.DISCONNECTED:
114
+ default:
115
+ statusIndicator = COLOR_RED + '✗' + RESET_COLOR;
116
+ statusText = 'Disconnected';
117
+ break;
118
+ }
119
+
120
+ let serverInfo = `${serverName}: `;
121
+ if (server.httpUrl) {
122
+ serverInfo += `${server.httpUrl} (http)`;
123
+ } else if (server.url) {
124
+ serverInfo += `${server.url} (sse)`;
125
+ } else if (server.command) {
126
+ serverInfo += `${server.command} ${server.args?.join(' ') || ''} (stdio)`;
127
+ }
128
+
129
+ console.log(`${statusIndicator} ${serverInfo} - ${statusText}`);
130
+ }
131
+ }
132
+
133
+ export const listCommand: CommandModule = {
134
+ command: 'list',
135
+ describe: 'List all configured MCP servers',
136
+ handler: async () => {
137
+ await listMcpServers();
138
+ },
139
+ };
projects/ui/qwen-code/packages/cli/src/commands/mcp/remove.test.ts ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach } from 'vitest';
8
+ import yargs from 'yargs';
9
+ import { loadSettings, SettingScope } from '../../config/settings.js';
10
+ import { removeCommand } from './remove.js';
11
+
12
+ vi.mock('fs/promises', () => ({
13
+ readFile: vi.fn(),
14
+ writeFile: vi.fn(),
15
+ }));
16
+
17
+ vi.mock('../../config/settings.js', async () => {
18
+ const actual = await vi.importActual('../../config/settings.js');
19
+ return {
20
+ ...actual,
21
+ loadSettings: vi.fn(),
22
+ };
23
+ });
24
+
25
+ const mockedLoadSettings = loadSettings as vi.Mock;
26
+
27
+ describe('mcp remove command', () => {
28
+ let parser: yargs.Argv;
29
+ let mockSetValue: vi.Mock;
30
+ let mockSettings: Record<string, unknown>;
31
+
32
+ beforeEach(() => {
33
+ vi.resetAllMocks();
34
+ const yargsInstance = yargs([]).command(removeCommand);
35
+ parser = yargsInstance;
36
+ mockSetValue = vi.fn();
37
+ mockSettings = {
38
+ mcpServers: {
39
+ 'test-server': {
40
+ command: 'echo "hello"',
41
+ },
42
+ },
43
+ };
44
+ mockedLoadSettings.mockReturnValue({
45
+ forScope: () => ({ settings: mockSettings }),
46
+ setValue: mockSetValue,
47
+ });
48
+ });
49
+
50
+ it('should remove a server from project settings', async () => {
51
+ await parser.parseAsync('remove test-server');
52
+
53
+ expect(mockSetValue).toHaveBeenCalledWith(
54
+ SettingScope.Workspace,
55
+ 'mcpServers',
56
+ {},
57
+ );
58
+ });
59
+
60
+ it('should show a message if server not found', async () => {
61
+ const consoleSpy = vi.spyOn(console, 'log').mockImplementation(() => {});
62
+ await parser.parseAsync('remove non-existent-server');
63
+
64
+ expect(mockSetValue).not.toHaveBeenCalled();
65
+ expect(consoleSpy).toHaveBeenCalledWith(
66
+ 'Server "non-existent-server" not found in project settings.',
67
+ );
68
+ });
69
+ });
projects/ui/qwen-code/packages/cli/src/commands/mcp/remove.ts ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ // File for 'gemini mcp remove' command
8
+ import type { CommandModule } from 'yargs';
9
+ import { loadSettings, SettingScope } from '../../config/settings.js';
10
+
11
+ async function removeMcpServer(
12
+ name: string,
13
+ options: {
14
+ scope: string;
15
+ },
16
+ ) {
17
+ const { scope } = options;
18
+ const settingsScope =
19
+ scope === 'user' ? SettingScope.User : SettingScope.Workspace;
20
+ const settings = loadSettings(process.cwd());
21
+
22
+ const existingSettings = settings.forScope(settingsScope).settings;
23
+ const mcpServers = existingSettings.mcpServers || {};
24
+
25
+ if (!mcpServers[name]) {
26
+ console.log(`Server "${name}" not found in ${scope} settings.`);
27
+ return;
28
+ }
29
+
30
+ delete mcpServers[name];
31
+
32
+ settings.setValue(settingsScope, 'mcpServers', mcpServers);
33
+
34
+ console.log(`Server "${name}" removed from ${scope} settings.`);
35
+ }
36
+
37
+ export const removeCommand: CommandModule = {
38
+ command: 'remove <name>',
39
+ describe: 'Remove a server',
40
+ builder: (yargs) =>
41
+ yargs
42
+ .usage('Usage: gemini mcp remove [options] <name>')
43
+ .positional('name', {
44
+ describe: 'Name of the server',
45
+ type: 'string',
46
+ demandOption: true,
47
+ })
48
+ .option('scope', {
49
+ alias: 's',
50
+ describe: 'Configuration scope (user or project)',
51
+ type: 'string',
52
+ default: 'project',
53
+ choices: ['user', 'project'],
54
+ }),
55
+ handler: async (argv) => {
56
+ await removeMcpServer(argv['name'] as string, {
57
+ scope: argv['scope'] as string,
58
+ });
59
+ },
60
+ };
projects/ui/qwen-code/packages/cli/src/services/prompt-processors/argumentProcessor.test.ts ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { DefaultArgumentProcessor } from './argumentProcessor.js';
8
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
9
+ import { describe, it, expect } from 'vitest';
10
+
11
+ describe('Argument Processors', () => {
12
+ describe('DefaultArgumentProcessor', () => {
13
+ const processor = new DefaultArgumentProcessor();
14
+
15
+ it('should append the full command if args are provided', async () => {
16
+ const prompt = 'Parse the command.';
17
+ const context = createMockCommandContext({
18
+ invocation: {
19
+ raw: '/mycommand arg1 "arg two"',
20
+ name: 'mycommand',
21
+ args: 'arg1 "arg two"',
22
+ },
23
+ });
24
+ const result = await processor.process(prompt, context);
25
+ expect(result).toBe('Parse the command.\n\n/mycommand arg1 "arg two"');
26
+ });
27
+
28
+ it('should NOT append the full command if no args are provided', async () => {
29
+ const prompt = 'Parse the command.';
30
+ const context = createMockCommandContext({
31
+ invocation: {
32
+ raw: '/mycommand',
33
+ name: 'mycommand',
34
+ args: '',
35
+ },
36
+ });
37
+ const result = await processor.process(prompt, context);
38
+ expect(result).toBe('Parse the command.');
39
+ });
40
+ });
41
+ });
projects/ui/qwen-code/packages/cli/src/services/prompt-processors/argumentProcessor.ts ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { IPromptProcessor } from './types.js';
8
+ import { CommandContext } from '../../ui/commands/types.js';
9
+
10
+ /**
11
+ * Appends the user's full command invocation to the prompt if arguments are
12
+ * provided, allowing the model to perform its own argument parsing.
13
+ *
14
+ * This processor is only used if the prompt does NOT contain {{args}}.
15
+ */
16
+ export class DefaultArgumentProcessor implements IPromptProcessor {
17
+ async process(prompt: string, context: CommandContext): Promise<string> {
18
+ if (context.invocation!.args) {
19
+ return `${prompt}\n\n${context.invocation!.raw}`;
20
+ }
21
+ return prompt;
22
+ }
23
+ }
projects/ui/qwen-code/packages/cli/src/services/prompt-processors/shellProcessor.test.ts ADDED
@@ -0,0 +1,709 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, vi, type Mock } from 'vitest';
8
+ import { ConfirmationRequiredError, ShellProcessor } from './shellProcessor.js';
9
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
10
+ import { CommandContext } from '../../ui/commands/types.js';
11
+ import { ApprovalMode, Config } from '@qwen-code/qwen-code-core';
12
+ import os from 'os';
13
+ import { quote } from 'shell-quote';
14
+
15
+ // Helper function to determine the expected escaped string based on the current OS,
16
+ // mirroring the logic in the actual `escapeShellArg` implementation. This makes
17
+ // our tests robust and platform-agnostic.
18
+ function getExpectedEscapedArgForPlatform(arg: string): string {
19
+ if (os.platform() === 'win32') {
20
+ const comSpec = (process.env['ComSpec'] || 'cmd.exe').toLowerCase();
21
+ const isPowerShell =
22
+ comSpec.endsWith('powershell.exe') || comSpec.endsWith('pwsh.exe');
23
+
24
+ if (isPowerShell) {
25
+ return `'${arg.replace(/'/g, "''")}'`;
26
+ } else {
27
+ return `"${arg.replace(/"/g, '""')}"`;
28
+ }
29
+ } else {
30
+ return quote([arg]);
31
+ }
32
+ }
33
+
34
+ const mockCheckCommandPermissions = vi.hoisted(() => vi.fn());
35
+ const mockShellExecute = vi.hoisted(() => vi.fn());
36
+
37
+ vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
38
+ const original = await importOriginal<object>();
39
+ return {
40
+ ...original,
41
+ checkCommandPermissions: mockCheckCommandPermissions,
42
+ ShellExecutionService: {
43
+ execute: mockShellExecute,
44
+ },
45
+ };
46
+ });
47
+
48
+ const SUCCESS_RESULT = {
49
+ output: 'default shell output',
50
+ exitCode: 0,
51
+ error: null,
52
+ aborted: false,
53
+ signal: null,
54
+ };
55
+
56
+ describe('ShellProcessor', () => {
57
+ let context: CommandContext;
58
+ let mockConfig: Partial<Config>;
59
+
60
+ beforeEach(() => {
61
+ vi.clearAllMocks();
62
+
63
+ mockConfig = {
64
+ getTargetDir: vi.fn().mockReturnValue('/test/dir'),
65
+ getApprovalMode: vi.fn().mockReturnValue(ApprovalMode.DEFAULT),
66
+ getShouldUseNodePtyShell: vi.fn().mockReturnValue(false),
67
+ };
68
+
69
+ context = createMockCommandContext({
70
+ invocation: {
71
+ raw: '/cmd default args',
72
+ name: 'cmd',
73
+ args: 'default args',
74
+ },
75
+ services: {
76
+ config: mockConfig as Config,
77
+ },
78
+ session: {
79
+ sessionShellAllowlist: new Set(),
80
+ },
81
+ });
82
+
83
+ mockShellExecute.mockReturnValue({
84
+ result: Promise.resolve(SUCCESS_RESULT),
85
+ });
86
+
87
+ mockCheckCommandPermissions.mockReturnValue({
88
+ allAllowed: true,
89
+ disallowedCommands: [],
90
+ });
91
+ });
92
+
93
+ it('should throw an error if config is missing', async () => {
94
+ const processor = new ShellProcessor('test-command');
95
+ const prompt = '!{ls}';
96
+ const contextWithoutConfig = createMockCommandContext({
97
+ services: {
98
+ config: null,
99
+ },
100
+ });
101
+
102
+ await expect(
103
+ processor.process(prompt, contextWithoutConfig),
104
+ ).rejects.toThrow(/Security configuration not loaded/);
105
+ });
106
+
107
+ it('should not change the prompt if no shell injections are present', async () => {
108
+ const processor = new ShellProcessor('test-command');
109
+ const prompt = 'This is a simple prompt with no injections.';
110
+ const result = await processor.process(prompt, context);
111
+ expect(result).toBe(prompt);
112
+ expect(mockShellExecute).not.toHaveBeenCalled();
113
+ });
114
+
115
+ it('should process a single valid shell injection if allowed', async () => {
116
+ const processor = new ShellProcessor('test-command');
117
+ const prompt = 'The current status is: !{git status}';
118
+ mockCheckCommandPermissions.mockReturnValue({
119
+ allAllowed: true,
120
+ disallowedCommands: [],
121
+ });
122
+ mockShellExecute.mockReturnValue({
123
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: 'On branch main' }),
124
+ });
125
+
126
+ const result = await processor.process(prompt, context);
127
+
128
+ expect(mockCheckCommandPermissions).toHaveBeenCalledWith(
129
+ 'git status',
130
+ expect.any(Object),
131
+ context.session.sessionShellAllowlist,
132
+ );
133
+ expect(mockShellExecute).toHaveBeenCalledWith(
134
+ 'git status',
135
+ expect.any(String),
136
+ expect.any(Function),
137
+ expect.any(Object),
138
+ false,
139
+ );
140
+ expect(result).toBe('The current status is: On branch main');
141
+ });
142
+
143
+ it('should process multiple valid shell injections if all are allowed', async () => {
144
+ const processor = new ShellProcessor('test-command');
145
+ const prompt = '!{git status} in !{pwd}';
146
+ mockCheckCommandPermissions.mockReturnValue({
147
+ allAllowed: true,
148
+ disallowedCommands: [],
149
+ });
150
+
151
+ mockShellExecute
152
+ .mockReturnValueOnce({
153
+ result: Promise.resolve({
154
+ ...SUCCESS_RESULT,
155
+ output: 'On branch main',
156
+ }),
157
+ })
158
+ .mockReturnValueOnce({
159
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: '/usr/home' }),
160
+ });
161
+
162
+ const result = await processor.process(prompt, context);
163
+
164
+ expect(mockCheckCommandPermissions).toHaveBeenCalledTimes(2);
165
+ expect(mockShellExecute).toHaveBeenCalledTimes(2);
166
+ expect(result).toBe('On branch main in /usr/home');
167
+ });
168
+
169
+ it('should throw ConfirmationRequiredError if a command is not allowed in default mode', async () => {
170
+ const processor = new ShellProcessor('test-command');
171
+ const prompt = 'Do something dangerous: !{rm -rf /}';
172
+ mockCheckCommandPermissions.mockReturnValue({
173
+ allAllowed: false,
174
+ disallowedCommands: ['rm -rf /'],
175
+ });
176
+
177
+ await expect(processor.process(prompt, context)).rejects.toThrow(
178
+ ConfirmationRequiredError,
179
+ );
180
+ });
181
+
182
+ it('should NOT throw ConfirmationRequiredError if a command is not allowed but approval mode is YOLO', async () => {
183
+ const processor = new ShellProcessor('test-command');
184
+ const prompt = 'Do something dangerous: !{rm -rf /}';
185
+ mockCheckCommandPermissions.mockReturnValue({
186
+ allAllowed: false,
187
+ disallowedCommands: ['rm -rf /'],
188
+ });
189
+ // Override the approval mode for this test
190
+ (mockConfig.getApprovalMode as Mock).mockReturnValue(ApprovalMode.YOLO);
191
+ mockShellExecute.mockReturnValue({
192
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: 'deleted' }),
193
+ });
194
+
195
+ const result = await processor.process(prompt, context);
196
+
197
+ // It should proceed with execution
198
+ expect(mockShellExecute).toHaveBeenCalledWith(
199
+ 'rm -rf /',
200
+ expect.any(String),
201
+ expect.any(Function),
202
+ expect.any(Object),
203
+ false,
204
+ );
205
+ expect(result).toBe('Do something dangerous: deleted');
206
+ });
207
+
208
+ it('should still throw an error for a hard-denied command even in YOLO mode', async () => {
209
+ const processor = new ShellProcessor('test-command');
210
+ const prompt = 'Do something forbidden: !{reboot}';
211
+ mockCheckCommandPermissions.mockReturnValue({
212
+ allAllowed: false,
213
+ disallowedCommands: ['reboot'],
214
+ isHardDenial: true, // This is the key difference
215
+ blockReason: 'System commands are blocked',
216
+ });
217
+ // Set approval mode to YOLO
218
+ (mockConfig.getApprovalMode as Mock).mockReturnValue(ApprovalMode.YOLO);
219
+
220
+ await expect(processor.process(prompt, context)).rejects.toThrow(
221
+ /Blocked command: "reboot". Reason: System commands are blocked/,
222
+ );
223
+
224
+ // Ensure it never tried to execute
225
+ expect(mockShellExecute).not.toHaveBeenCalled();
226
+ });
227
+
228
+ it('should throw ConfirmationRequiredError with the correct command', async () => {
229
+ const processor = new ShellProcessor('test-command');
230
+ const prompt = 'Do something dangerous: !{rm -rf /}';
231
+ mockCheckCommandPermissions.mockReturnValue({
232
+ allAllowed: false,
233
+ disallowedCommands: ['rm -rf /'],
234
+ });
235
+
236
+ try {
237
+ await processor.process(prompt, context);
238
+ // Fail if it doesn't throw
239
+ expect(true).toBe(false);
240
+ } catch (e) {
241
+ expect(e).toBeInstanceOf(ConfirmationRequiredError);
242
+ if (e instanceof ConfirmationRequiredError) {
243
+ expect(e.commandsToConfirm).toEqual(['rm -rf /']);
244
+ }
245
+ }
246
+
247
+ expect(mockShellExecute).not.toHaveBeenCalled();
248
+ });
249
+
250
+ it('should throw ConfirmationRequiredError with multiple commands if multiple are disallowed', async () => {
251
+ const processor = new ShellProcessor('test-command');
252
+ const prompt = '!{cmd1} and !{cmd2}';
253
+ mockCheckCommandPermissions.mockImplementation((cmd) => {
254
+ if (cmd === 'cmd1') {
255
+ return { allAllowed: false, disallowedCommands: ['cmd1'] };
256
+ }
257
+ if (cmd === 'cmd2') {
258
+ return { allAllowed: false, disallowedCommands: ['cmd2'] };
259
+ }
260
+ return { allAllowed: true, disallowedCommands: [] };
261
+ });
262
+
263
+ try {
264
+ await processor.process(prompt, context);
265
+ // Fail if it doesn't throw
266
+ expect(true).toBe(false);
267
+ } catch (e) {
268
+ expect(e).toBeInstanceOf(ConfirmationRequiredError);
269
+ if (e instanceof ConfirmationRequiredError) {
270
+ expect(e.commandsToConfirm).toEqual(['cmd1', 'cmd2']);
271
+ }
272
+ }
273
+ });
274
+
275
+ it('should not execute any commands if at least one requires confirmation', async () => {
276
+ const processor = new ShellProcessor('test-command');
277
+ const prompt = 'First: !{echo "hello"}, Second: !{rm -rf /}';
278
+
279
+ mockCheckCommandPermissions.mockImplementation((cmd) => {
280
+ if (cmd.includes('rm')) {
281
+ return { allAllowed: false, disallowedCommands: [cmd] };
282
+ }
283
+ return { allAllowed: true, disallowedCommands: [] };
284
+ });
285
+
286
+ await expect(processor.process(prompt, context)).rejects.toThrow(
287
+ ConfirmationRequiredError,
288
+ );
289
+
290
+ // Ensure no commands were executed because the pipeline was halted.
291
+ expect(mockShellExecute).not.toHaveBeenCalled();
292
+ });
293
+
294
+ it('should only request confirmation for disallowed commands in a mixed prompt', async () => {
295
+ const processor = new ShellProcessor('test-command');
296
+ const prompt = 'Allowed: !{ls -l}, Disallowed: !{rm -rf /}';
297
+
298
+ mockCheckCommandPermissions.mockImplementation((cmd) => ({
299
+ allAllowed: !cmd.includes('rm'),
300
+ disallowedCommands: cmd.includes('rm') ? [cmd] : [],
301
+ }));
302
+
303
+ try {
304
+ await processor.process(prompt, context);
305
+ expect.fail('Should have thrown ConfirmationRequiredError');
306
+ } catch (e) {
307
+ expect(e).toBeInstanceOf(ConfirmationRequiredError);
308
+ if (e instanceof ConfirmationRequiredError) {
309
+ expect(e.commandsToConfirm).toEqual(['rm -rf /']);
310
+ }
311
+ }
312
+ });
313
+
314
+ it('should execute all commands if they are on the session allowlist', async () => {
315
+ const processor = new ShellProcessor('test-command');
316
+ const prompt = 'Run !{cmd1} and !{cmd2}';
317
+
318
+ // Add commands to the session allowlist
319
+ context.session.sessionShellAllowlist = new Set(['cmd1', 'cmd2']);
320
+
321
+ // checkCommandPermissions should now pass for these
322
+ mockCheckCommandPermissions.mockReturnValue({
323
+ allAllowed: true,
324
+ disallowedCommands: [],
325
+ });
326
+
327
+ mockShellExecute
328
+ .mockReturnValueOnce({
329
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: 'output1' }),
330
+ })
331
+ .mockReturnValueOnce({
332
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: 'output2' }),
333
+ });
334
+
335
+ const result = await processor.process(prompt, context);
336
+
337
+ expect(mockCheckCommandPermissions).toHaveBeenCalledWith(
338
+ 'cmd1',
339
+ expect.any(Object),
340
+ context.session.sessionShellAllowlist,
341
+ );
342
+ expect(mockCheckCommandPermissions).toHaveBeenCalledWith(
343
+ 'cmd2',
344
+ expect.any(Object),
345
+ context.session.sessionShellAllowlist,
346
+ );
347
+ expect(mockShellExecute).toHaveBeenCalledTimes(2);
348
+ expect(result).toBe('Run output1 and output2');
349
+ });
350
+
351
+ it('should trim whitespace from the command inside the injection before interpolation', async () => {
352
+ const processor = new ShellProcessor('test-command');
353
+ const prompt = 'Files: !{ ls {{args}} -l }';
354
+
355
+ const rawArgs = context.invocation!.args;
356
+
357
+ const expectedEscapedArgs = getExpectedEscapedArgForPlatform(rawArgs);
358
+
359
+ const expectedCommand = `ls ${expectedEscapedArgs} -l`;
360
+
361
+ mockCheckCommandPermissions.mockReturnValue({
362
+ allAllowed: true,
363
+ disallowedCommands: [],
364
+ });
365
+ mockShellExecute.mockReturnValue({
366
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: 'total 0' }),
367
+ });
368
+
369
+ await processor.process(prompt, context);
370
+
371
+ expect(mockCheckCommandPermissions).toHaveBeenCalledWith(
372
+ expectedCommand,
373
+ expect.any(Object),
374
+ context.session.sessionShellAllowlist,
375
+ );
376
+ expect(mockShellExecute).toHaveBeenCalledWith(
377
+ expectedCommand,
378
+ expect.any(String),
379
+ expect.any(Function),
380
+ expect.any(Object),
381
+ false,
382
+ );
383
+ });
384
+
385
+ it('should handle an empty command inside the injection gracefully (skips execution)', async () => {
386
+ const processor = new ShellProcessor('test-command');
387
+ const prompt = 'This is weird: !{}';
388
+
389
+ const result = await processor.process(prompt, context);
390
+
391
+ expect(mockCheckCommandPermissions).not.toHaveBeenCalled();
392
+ expect(mockShellExecute).not.toHaveBeenCalled();
393
+
394
+ // It replaces !{} with an empty string.
395
+ expect(result).toBe('This is weird: ');
396
+ });
397
+
398
+ describe('Robust Parsing (Balanced Braces)', () => {
399
+ it('should correctly parse commands containing nested braces (e.g., awk)', async () => {
400
+ const processor = new ShellProcessor('test-command');
401
+ const command = "awk '{print $1}' file.txt";
402
+ const prompt = `Output: !{${command}}`;
403
+ mockShellExecute.mockReturnValue({
404
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: 'result' }),
405
+ });
406
+
407
+ const result = await processor.process(prompt, context);
408
+
409
+ expect(mockCheckCommandPermissions).toHaveBeenCalledWith(
410
+ command,
411
+ expect.any(Object),
412
+ context.session.sessionShellAllowlist,
413
+ );
414
+ expect(mockShellExecute).toHaveBeenCalledWith(
415
+ command,
416
+ expect.any(String),
417
+ expect.any(Function),
418
+ expect.any(Object),
419
+ false,
420
+ );
421
+ expect(result).toBe('Output: result');
422
+ });
423
+
424
+ it('should handle deeply nested braces correctly', async () => {
425
+ const processor = new ShellProcessor('test-command');
426
+ const command = "echo '{{a},{b}}'";
427
+ const prompt = `!{${command}}`;
428
+ mockShellExecute.mockReturnValue({
429
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: '{{a},{b}}' }),
430
+ });
431
+
432
+ const result = await processor.process(prompt, context);
433
+ expect(mockShellExecute).toHaveBeenCalledWith(
434
+ command,
435
+ expect.any(String),
436
+ expect.any(Function),
437
+ expect.any(Object),
438
+ false,
439
+ );
440
+ expect(result).toBe('{{a},{b}}');
441
+ });
442
+
443
+ it('should throw an error for unclosed shell injections', async () => {
444
+ const processor = new ShellProcessor('test-command');
445
+ const prompt = 'This prompt is broken: !{ls -l';
446
+
447
+ await expect(processor.process(prompt, context)).rejects.toThrow(
448
+ /Unclosed shell injection/,
449
+ );
450
+ });
451
+
452
+ it('should throw an error for unclosed nested braces', async () => {
453
+ const processor = new ShellProcessor('test-command');
454
+ const prompt = 'Broken: !{echo {a}';
455
+
456
+ await expect(processor.process(prompt, context)).rejects.toThrow(
457
+ /Unclosed shell injection/,
458
+ );
459
+ });
460
+ });
461
+
462
+ describe('Error Reporting', () => {
463
+ it('should append exit code and command name on failure', async () => {
464
+ const processor = new ShellProcessor('test-command');
465
+ const prompt = '!{cmd}';
466
+ mockShellExecute.mockReturnValue({
467
+ result: Promise.resolve({
468
+ ...SUCCESS_RESULT,
469
+ output: 'some error output',
470
+ stderr: '',
471
+ exitCode: 1,
472
+ }),
473
+ });
474
+
475
+ const result = await processor.process(prompt, context);
476
+
477
+ expect(result).toBe(
478
+ "some error output\n[Shell command 'cmd' exited with code 1]",
479
+ );
480
+ });
481
+
482
+ it('should append signal info and command name if terminated by signal', async () => {
483
+ const processor = new ShellProcessor('test-command');
484
+ const prompt = '!{cmd}';
485
+ mockShellExecute.mockReturnValue({
486
+ result: Promise.resolve({
487
+ ...SUCCESS_RESULT,
488
+ output: 'output',
489
+ stderr: '',
490
+ exitCode: null,
491
+ signal: 'SIGTERM',
492
+ }),
493
+ });
494
+
495
+ const result = await processor.process(prompt, context);
496
+
497
+ expect(result).toBe(
498
+ "output\n[Shell command 'cmd' terminated by signal SIGTERM]",
499
+ );
500
+ });
501
+
502
+ it('should throw a detailed error if the shell fails to spawn', async () => {
503
+ const processor = new ShellProcessor('test-command');
504
+ const prompt = '!{bad-command}';
505
+ const spawnError = new Error('spawn EACCES');
506
+ mockShellExecute.mockReturnValue({
507
+ result: Promise.resolve({
508
+ ...SUCCESS_RESULT,
509
+ stdout: '',
510
+ stderr: '',
511
+ exitCode: null,
512
+ error: spawnError,
513
+ aborted: false,
514
+ }),
515
+ });
516
+
517
+ await expect(processor.process(prompt, context)).rejects.toThrow(
518
+ "Failed to start shell command in 'test-command': spawn EACCES. Command: bad-command",
519
+ );
520
+ });
521
+
522
+ it('should report abort status with command name if aborted', async () => {
523
+ const processor = new ShellProcessor('test-command');
524
+ const prompt = '!{long-running-command}';
525
+ const spawnError = new Error('Aborted');
526
+ mockShellExecute.mockReturnValue({
527
+ result: Promise.resolve({
528
+ ...SUCCESS_RESULT,
529
+ output: 'partial output',
530
+ stderr: '',
531
+ exitCode: null,
532
+ error: spawnError,
533
+ aborted: true, // Key difference
534
+ }),
535
+ });
536
+
537
+ const result = await processor.process(prompt, context);
538
+ expect(result).toBe(
539
+ "partial output\n[Shell command 'long-running-command' aborted]",
540
+ );
541
+ });
542
+ });
543
+
544
+ describe('Context-Aware Argument Interpolation ({{args}})', () => {
545
+ const rawArgs = 'user input';
546
+
547
+ beforeEach(() => {
548
+ // Update context for these tests to use specific arguments
549
+ context.invocation!.args = rawArgs;
550
+ });
551
+
552
+ it('should perform raw replacement if no shell injections are present (optimization path)', async () => {
553
+ const processor = new ShellProcessor('test-command');
554
+ const prompt = 'The user said: {{args}}';
555
+
556
+ const result = await processor.process(prompt, context);
557
+
558
+ expect(result).toBe(`The user said: ${rawArgs}`);
559
+ expect(mockShellExecute).not.toHaveBeenCalled();
560
+ });
561
+
562
+ it('should perform raw replacement outside !{} blocks', async () => {
563
+ const processor = new ShellProcessor('test-command');
564
+ const prompt = 'Outside: {{args}}. Inside: !{echo "hello"}';
565
+ mockShellExecute.mockReturnValue({
566
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: 'hello' }),
567
+ });
568
+
569
+ const result = await processor.process(prompt, context);
570
+
571
+ expect(result).toBe(`Outside: ${rawArgs}. Inside: hello`);
572
+ });
573
+
574
+ it('should perform escaped replacement inside !{} blocks', async () => {
575
+ const processor = new ShellProcessor('test-command');
576
+ const prompt = 'Command: !{grep {{args}} file.txt}';
577
+ mockShellExecute.mockReturnValue({
578
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: 'match found' }),
579
+ });
580
+
581
+ const result = await processor.process(prompt, context);
582
+
583
+ const expectedEscapedArgs = getExpectedEscapedArgForPlatform(rawArgs);
584
+ const expectedCommand = `grep ${expectedEscapedArgs} file.txt`;
585
+
586
+ expect(mockShellExecute).toHaveBeenCalledWith(
587
+ expectedCommand,
588
+ expect.any(String),
589
+ expect.any(Function),
590
+ expect.any(Object),
591
+ false,
592
+ );
593
+
594
+ expect(result).toBe('Command: match found');
595
+ });
596
+
597
+ it('should handle both raw (outside) and escaped (inside) injection simultaneously', async () => {
598
+ const processor = new ShellProcessor('test-command');
599
+ const prompt = 'User "({{args}})" requested search: !{search {{args}}}';
600
+ mockShellExecute.mockReturnValue({
601
+ result: Promise.resolve({ ...SUCCESS_RESULT, output: 'results' }),
602
+ });
603
+
604
+ const result = await processor.process(prompt, context);
605
+
606
+ const expectedEscapedArgs = getExpectedEscapedArgForPlatform(rawArgs);
607
+ const expectedCommand = `search ${expectedEscapedArgs}`;
608
+ expect(mockShellExecute).toHaveBeenCalledWith(
609
+ expectedCommand,
610
+ expect.any(String),
611
+ expect.any(Function),
612
+ expect.any(Object),
613
+ false,
614
+ );
615
+
616
+ expect(result).toBe(`User "(${rawArgs})" requested search: results`);
617
+ });
618
+
619
+ it('should perform security checks on the final, resolved (escaped) command', async () => {
620
+ const processor = new ShellProcessor('test-command');
621
+ const prompt = '!{rm {{args}}}';
622
+
623
+ const expectedEscapedArgs = getExpectedEscapedArgForPlatform(rawArgs);
624
+ const expectedResolvedCommand = `rm ${expectedEscapedArgs}`;
625
+ mockCheckCommandPermissions.mockReturnValue({
626
+ allAllowed: false,
627
+ disallowedCommands: [expectedResolvedCommand],
628
+ isHardDenial: false,
629
+ });
630
+
631
+ await expect(processor.process(prompt, context)).rejects.toThrow(
632
+ ConfirmationRequiredError,
633
+ );
634
+
635
+ expect(mockCheckCommandPermissions).toHaveBeenCalledWith(
636
+ expectedResolvedCommand,
637
+ expect.any(Object),
638
+ context.session.sessionShellAllowlist,
639
+ );
640
+ });
641
+
642
+ it('should report the resolved command if a hard denial occurs', async () => {
643
+ const processor = new ShellProcessor('test-command');
644
+ const prompt = '!{rm {{args}}}';
645
+ const expectedEscapedArgs = getExpectedEscapedArgForPlatform(rawArgs);
646
+ const expectedResolvedCommand = `rm ${expectedEscapedArgs}`;
647
+ mockCheckCommandPermissions.mockReturnValue({
648
+ allAllowed: false,
649
+ disallowedCommands: [expectedResolvedCommand],
650
+ isHardDenial: true,
651
+ blockReason: 'It is forbidden.',
652
+ });
653
+
654
+ await expect(processor.process(prompt, context)).rejects.toThrow(
655
+ `Blocked command: "${expectedResolvedCommand}". Reason: It is forbidden.`,
656
+ );
657
+ });
658
+ });
659
+ describe('Real-World Escaping Scenarios', () => {
660
+ it('should correctly handle multiline arguments', async () => {
661
+ const processor = new ShellProcessor('test-command');
662
+ const multilineArgs = 'first line\nsecond line';
663
+ context.invocation!.args = multilineArgs;
664
+ const prompt = 'Commit message: !{git commit -m {{args}}}';
665
+
666
+ const expectedEscapedArgs =
667
+ getExpectedEscapedArgForPlatform(multilineArgs);
668
+ const expectedCommand = `git commit -m ${expectedEscapedArgs}`;
669
+
670
+ await processor.process(prompt, context);
671
+
672
+ expect(mockShellExecute).toHaveBeenCalledWith(
673
+ expectedCommand,
674
+ expect.any(String),
675
+ expect.any(Function),
676
+ expect.any(Object),
677
+ false,
678
+ );
679
+ });
680
+
681
+ it.each([
682
+ { name: 'spaces', input: 'file with spaces.txt' },
683
+ { name: 'double quotes', input: 'a "quoted" string' },
684
+ { name: 'single quotes', input: "it's a string" },
685
+ { name: 'command substitution (backticks)', input: '`reboot`' },
686
+ { name: 'command substitution (dollar)', input: '$(reboot)' },
687
+ { name: 'variable expansion', input: '$HOME' },
688
+ { name: 'command chaining (semicolon)', input: 'a; reboot' },
689
+ { name: 'command chaining (ampersand)', input: 'a && reboot' },
690
+ ])('should safely escape args containing $name', async ({ input }) => {
691
+ const processor = new ShellProcessor('test-command');
692
+ context.invocation!.args = input;
693
+ const prompt = '!{echo {{args}}}';
694
+
695
+ const expectedEscapedArgs = getExpectedEscapedArgForPlatform(input);
696
+ const expectedCommand = `echo ${expectedEscapedArgs}`;
697
+
698
+ await processor.process(prompt, context);
699
+
700
+ expect(mockShellExecute).toHaveBeenCalledWith(
701
+ expectedCommand,
702
+ expect.any(String),
703
+ expect.any(Function),
704
+ expect.any(Object),
705
+ false,
706
+ );
707
+ });
708
+ });
709
+ });
projects/ui/qwen-code/packages/cli/src/services/prompt-processors/shellProcessor.ts ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ ApprovalMode,
9
+ checkCommandPermissions,
10
+ escapeShellArg,
11
+ getShellConfiguration,
12
+ ShellExecutionService,
13
+ } from '@qwen-code/qwen-code-core';
14
+
15
+ import { CommandContext } from '../../ui/commands/types.js';
16
+ import {
17
+ IPromptProcessor,
18
+ SHELL_INJECTION_TRIGGER,
19
+ SHORTHAND_ARGS_PLACEHOLDER,
20
+ } from './types.js';
21
+
22
+ export class ConfirmationRequiredError extends Error {
23
+ constructor(
24
+ message: string,
25
+ public commandsToConfirm: string[],
26
+ ) {
27
+ super(message);
28
+ this.name = 'ConfirmationRequiredError';
29
+ }
30
+ }
31
+
32
+ /**
33
+ * Represents a single detected shell injection site in the prompt.
34
+ */
35
+ interface ShellInjection {
36
+ /** The shell command extracted from within !{...}, trimmed. */
37
+ command: string;
38
+ /** The starting index of the injection (inclusive, points to '!'). */
39
+ startIndex: number;
40
+ /** The ending index of the injection (exclusive, points after '}'). */
41
+ endIndex: number;
42
+ /** The command after {{args}} has been escaped and substituted. */
43
+ resolvedCommand?: string;
44
+ }
45
+
46
+ /**
47
+ * Handles prompt interpolation, including shell command execution (`!{...}`)
48
+ * and context-aware argument injection (`{{args}}`).
49
+ *
50
+ * This processor ensures that:
51
+ * 1. `{{args}}` outside `!{...}` are replaced with raw input.
52
+ * 2. `{{args}}` inside `!{...}` are replaced with shell-escaped input.
53
+ * 3. Shell commands are executed securely after argument substitution.
54
+ * 4. Parsing correctly handles nested braces.
55
+ */
56
+ export class ShellProcessor implements IPromptProcessor {
57
+ constructor(private readonly commandName: string) {}
58
+
59
+ async process(prompt: string, context: CommandContext): Promise<string> {
60
+ const userArgsRaw = context.invocation?.args || '';
61
+
62
+ if (!prompt.includes(SHELL_INJECTION_TRIGGER)) {
63
+ return prompt.replaceAll(SHORTHAND_ARGS_PLACEHOLDER, userArgsRaw);
64
+ }
65
+
66
+ const config = context.services.config;
67
+ if (!config) {
68
+ throw new Error(
69
+ `Security configuration not loaded. Cannot verify shell command permissions for '${this.commandName}'. Aborting.`,
70
+ );
71
+ }
72
+ const { sessionShellAllowlist } = context.session;
73
+
74
+ const injections = this.extractInjections(prompt);
75
+ // If extractInjections found no closed blocks (and didn't throw), treat as raw.
76
+ if (injections.length === 0) {
77
+ return prompt.replaceAll(SHORTHAND_ARGS_PLACEHOLDER, userArgsRaw);
78
+ }
79
+
80
+ const { shell } = getShellConfiguration();
81
+ const userArgsEscaped = escapeShellArg(userArgsRaw, shell);
82
+
83
+ const resolvedInjections = injections.map((injection) => {
84
+ if (injection.command === '') {
85
+ return injection;
86
+ }
87
+ // Replace {{args}} inside the command string with the escaped version.
88
+ const resolvedCommand = injection.command.replaceAll(
89
+ SHORTHAND_ARGS_PLACEHOLDER,
90
+ userArgsEscaped,
91
+ );
92
+ return { ...injection, resolvedCommand };
93
+ });
94
+
95
+ const commandsToConfirm = new Set<string>();
96
+ for (const injection of resolvedInjections) {
97
+ const command = injection.resolvedCommand;
98
+
99
+ if (!command) continue;
100
+
101
+ // Security check on the final, escaped command string.
102
+ const { allAllowed, disallowedCommands, blockReason, isHardDenial } =
103
+ checkCommandPermissions(command, config, sessionShellAllowlist);
104
+
105
+ if (!allAllowed) {
106
+ if (isHardDenial) {
107
+ throw new Error(
108
+ `${this.commandName} cannot be run. Blocked command: "${command}". Reason: ${blockReason || 'Blocked by configuration.'}`,
109
+ );
110
+ }
111
+
112
+ // If not a hard denial, respect YOLO mode and auto-approve.
113
+ if (config.getApprovalMode() !== ApprovalMode.YOLO) {
114
+ disallowedCommands.forEach((uc) => commandsToConfirm.add(uc));
115
+ }
116
+ }
117
+ }
118
+
119
+ // Handle confirmation requirements.
120
+ if (commandsToConfirm.size > 0) {
121
+ throw new ConfirmationRequiredError(
122
+ 'Shell command confirmation required',
123
+ Array.from(commandsToConfirm),
124
+ );
125
+ }
126
+
127
+ let processedPrompt = '';
128
+ let lastIndex = 0;
129
+
130
+ for (const injection of resolvedInjections) {
131
+ // Append the text segment BEFORE the injection, substituting {{args}} with RAW input.
132
+ const segment = prompt.substring(lastIndex, injection.startIndex);
133
+ processedPrompt += segment.replaceAll(
134
+ SHORTHAND_ARGS_PLACEHOLDER,
135
+ userArgsRaw,
136
+ );
137
+
138
+ // Execute the resolved command (which already has ESCAPED input).
139
+ if (injection.resolvedCommand) {
140
+ const { result } = await ShellExecutionService.execute(
141
+ injection.resolvedCommand,
142
+ config.getTargetDir(),
143
+ () => {},
144
+ new AbortController().signal,
145
+ config.getShouldUseNodePtyShell(),
146
+ );
147
+
148
+ const executionResult = await result;
149
+
150
+ // Handle Spawn Errors
151
+ if (executionResult.error && !executionResult.aborted) {
152
+ throw new Error(
153
+ `Failed to start shell command in '${this.commandName}': ${executionResult.error.message}. Command: ${injection.resolvedCommand}`,
154
+ );
155
+ }
156
+
157
+ // Append the output, making stderr explicit for the model.
158
+ processedPrompt += executionResult.output;
159
+
160
+ // Append a status message if the command did not succeed.
161
+ if (executionResult.aborted) {
162
+ processedPrompt += `\n[Shell command '${injection.resolvedCommand}' aborted]`;
163
+ } else if (
164
+ executionResult.exitCode !== 0 &&
165
+ executionResult.exitCode !== null
166
+ ) {
167
+ processedPrompt += `\n[Shell command '${injection.resolvedCommand}' exited with code ${executionResult.exitCode}]`;
168
+ } else if (executionResult.signal !== null) {
169
+ processedPrompt += `\n[Shell command '${injection.resolvedCommand}' terminated by signal ${executionResult.signal}]`;
170
+ }
171
+ }
172
+
173
+ lastIndex = injection.endIndex;
174
+ }
175
+
176
+ // Append the remaining text AFTER the last injection, substituting {{args}} with RAW input.
177
+ const finalSegment = prompt.substring(lastIndex);
178
+ processedPrompt += finalSegment.replaceAll(
179
+ SHORTHAND_ARGS_PLACEHOLDER,
180
+ userArgsRaw,
181
+ );
182
+
183
+ return processedPrompt;
184
+ }
185
+
186
+ /**
187
+ * Iteratively parses the prompt string to extract shell injections (!{...}),
188
+ * correctly handling nested braces within the command.
189
+ *
190
+ * @param prompt The prompt string to parse.
191
+ * @returns An array of extracted ShellInjection objects.
192
+ * @throws Error if an unclosed injection (`!{`) is found.
193
+ */
194
+ private extractInjections(prompt: string): ShellInjection[] {
195
+ const injections: ShellInjection[] = [];
196
+ let index = 0;
197
+
198
+ while (index < prompt.length) {
199
+ const startIndex = prompt.indexOf(SHELL_INJECTION_TRIGGER, index);
200
+
201
+ if (startIndex === -1) {
202
+ break;
203
+ }
204
+
205
+ let currentIndex = startIndex + SHELL_INJECTION_TRIGGER.length;
206
+ let braceCount = 1;
207
+ let foundEnd = false;
208
+
209
+ while (currentIndex < prompt.length) {
210
+ const char = prompt[currentIndex];
211
+
212
+ // We count literal braces. This parser does not interpret shell quoting/escaping.
213
+ if (char === '{') {
214
+ braceCount++;
215
+ } else if (char === '}') {
216
+ braceCount--;
217
+ if (braceCount === 0) {
218
+ const commandContent = prompt.substring(
219
+ startIndex + SHELL_INJECTION_TRIGGER.length,
220
+ currentIndex,
221
+ );
222
+ const endIndex = currentIndex + 1;
223
+
224
+ injections.push({
225
+ command: commandContent.trim(),
226
+ startIndex,
227
+ endIndex,
228
+ });
229
+
230
+ index = endIndex;
231
+ foundEnd = true;
232
+ break;
233
+ }
234
+ }
235
+ currentIndex++;
236
+ }
237
+
238
+ // Check if the inner loop finished without finding the closing brace.
239
+ if (!foundEnd) {
240
+ throw new Error(
241
+ `Invalid syntax in command '${this.commandName}': Unclosed shell injection starting at index ${startIndex} ('!{'). Ensure braces are balanced.`,
242
+ );
243
+ }
244
+ }
245
+
246
+ return injections;
247
+ }
248
+ }
projects/ui/qwen-code/packages/cli/src/services/prompt-processors/types.ts ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { CommandContext } from '../../ui/commands/types.js';
8
+
9
+ /**
10
+ * Defines the interface for a prompt processor, a module that can transform
11
+ * a prompt string before it is sent to the model. Processors are chained
12
+ * together to create a processing pipeline.
13
+ */
14
+ export interface IPromptProcessor {
15
+ /**
16
+ * Processes a prompt string, applying a specific transformation as part of a pipeline.
17
+ *
18
+ * Each processor in a command's pipeline receives the output of the previous
19
+ * processor. This method provides the full command context, allowing for
20
+ * complex transformations that may require access to invocation details,
21
+ * application services, or UI state.
22
+ *
23
+ * @param prompt The current state of the prompt string. This may have been
24
+ * modified by previous processors in the pipeline.
25
+ * @param context The full command context, providing access to invocation
26
+ * details (like `context.invocation.raw` and `context.invocation.args`),
27
+ * application services, and UI handlers.
28
+ * @returns A promise that resolves to the transformed prompt string, which
29
+ * will be passed to the next processor or, if it's the last one, sent to the model.
30
+ */
31
+ process(prompt: string, context: CommandContext): Promise<string>;
32
+ }
33
+
34
+ /**
35
+ * The placeholder string for shorthand argument injection in custom commands.
36
+ * When used outside of !{...}, arguments are injected raw.
37
+ * When used inside !{...}, arguments are shell-escaped.
38
+ */
39
+ export const SHORTHAND_ARGS_PLACEHOLDER = '{{args}}';
40
+
41
+ /**
42
+ * The trigger string for shell command injection in custom commands.
43
+ */
44
+ export const SHELL_INJECTION_TRIGGER = '!{';
projects/ui/qwen-code/packages/cli/src/ui/__snapshots__/App.test.tsx.snap ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
2
+
3
+ exports[`App UI > should render correctly with the prompt input box 1`] = `
4
+ "
5
+
6
+ ╭────────────────────────────────────────────────────────────────────────────────────────╮
7
+ │ > Type your message or @path/to/file │
8
+ ╰────────────────────────────────────────────────────────────────────────────────────────╯
9
+ /test/dir no sandbox (see /docs) model (100% context left)"
10
+ `;
11
+
12
+ exports[`App UI > should render the initial UI correctly 1`] = `
13
+ " I'm Feeling Lucky (esc to cancel, 0s)
14
+
15
+
16
+ /test/dir no sandbox (see /docs) model (100% context left)"
17
+ `;
18
+
19
+ exports[`App UI > when in a narrow terminal > should render with a column layout 1`] = `
20
+ "
21
+
22
+
23
+ ╭────────────────────────────────────────────────────────────────────────────────────────╮
24
+ │ > Type your message or @path/to/file │
25
+ ╰────────────────────────────────────────────────────────────────────────────────────────╯
26
+ dir
27
+
28
+ no sandbox (see /docs)
29
+
30
+ model (100% context left)| ✖ 5 errors (ctrl+o for details)"
31
+ `;
projects/ui/qwen-code/packages/cli/src/ui/commands/aboutCommand.test.ts ADDED
@@ -0,0 +1,153 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, vi, afterEach } from 'vitest';
8
+ import { aboutCommand } from './aboutCommand.js';
9
+ import { type CommandContext } from './types.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+ import * as versionUtils from '../../utils/version.js';
12
+ import { MessageType } from '../types.js';
13
+
14
+ import { IdeClient } from '../../../../core/src/ide/ide-client.js';
15
+
16
+ vi.mock('../../utils/version.js', () => ({
17
+ getCliVersion: vi.fn(),
18
+ }));
19
+
20
+ describe('aboutCommand', () => {
21
+ let mockContext: CommandContext;
22
+ const originalPlatform = process.platform;
23
+ const originalEnv = { ...process.env };
24
+
25
+ beforeEach(() => {
26
+ mockContext = createMockCommandContext({
27
+ services: {
28
+ config: {
29
+ getModel: vi.fn(),
30
+ getIdeClient: vi.fn(),
31
+ getIdeMode: vi.fn().mockReturnValue(true),
32
+ },
33
+ settings: {
34
+ merged: {
35
+ selectedAuthType: 'test-auth',
36
+ },
37
+ },
38
+ },
39
+ ui: {
40
+ addItem: vi.fn(),
41
+ },
42
+ } as unknown as CommandContext);
43
+
44
+ vi.mocked(versionUtils.getCliVersion).mockResolvedValue('test-version');
45
+ vi.spyOn(mockContext.services.config!, 'getModel').mockReturnValue(
46
+ 'test-model',
47
+ );
48
+ process.env['GOOGLE_CLOUD_PROJECT'] = 'test-gcp-project';
49
+ Object.defineProperty(process, 'platform', {
50
+ value: 'test-os',
51
+ });
52
+ vi.spyOn(mockContext.services.config!, 'getIdeClient').mockReturnValue({
53
+ getDetectedIdeDisplayName: vi.fn().mockReturnValue('test-ide'),
54
+ } as Partial<IdeClient> as IdeClient);
55
+ });
56
+
57
+ afterEach(() => {
58
+ vi.unstubAllEnvs();
59
+ Object.defineProperty(process, 'platform', {
60
+ value: originalPlatform,
61
+ });
62
+ process.env = originalEnv;
63
+ vi.clearAllMocks();
64
+ });
65
+
66
+ it('should have the correct name and description', () => {
67
+ expect(aboutCommand.name).toBe('about');
68
+ expect(aboutCommand.description).toBe('show version info');
69
+ });
70
+
71
+ it('should call addItem with all version info', async () => {
72
+ process.env['SANDBOX'] = '';
73
+ if (!aboutCommand.action) {
74
+ throw new Error('The about command must have an action.');
75
+ }
76
+
77
+ await aboutCommand.action(mockContext, '');
78
+
79
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
80
+ {
81
+ type: MessageType.ABOUT,
82
+ cliVersion: 'test-version',
83
+ osVersion: 'test-os',
84
+ sandboxEnv: 'no sandbox',
85
+ modelVersion: 'test-model',
86
+ selectedAuthType: 'test-auth',
87
+ gcpProject: 'test-gcp-project',
88
+ ideClient: 'test-ide',
89
+ },
90
+ expect.any(Number),
91
+ );
92
+ });
93
+
94
+ it('should show the correct sandbox environment variable', async () => {
95
+ process.env['SANDBOX'] = 'gemini-sandbox';
96
+ if (!aboutCommand.action) {
97
+ throw new Error('The about command must have an action.');
98
+ }
99
+
100
+ await aboutCommand.action(mockContext, '');
101
+
102
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
103
+ expect.objectContaining({
104
+ sandboxEnv: 'gemini-sandbox',
105
+ }),
106
+ expect.any(Number),
107
+ );
108
+ });
109
+
110
+ it('should show sandbox-exec profile when applicable', async () => {
111
+ process.env['SANDBOX'] = 'sandbox-exec';
112
+ process.env['SEATBELT_PROFILE'] = 'test-profile';
113
+ if (!aboutCommand.action) {
114
+ throw new Error('The about command must have an action.');
115
+ }
116
+
117
+ await aboutCommand.action(mockContext, '');
118
+
119
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
120
+ expect.objectContaining({
121
+ sandboxEnv: 'sandbox-exec (test-profile)',
122
+ }),
123
+ expect.any(Number),
124
+ );
125
+ });
126
+
127
+ it('should not show ide client when it is not detected', async () => {
128
+ vi.spyOn(mockContext.services.config!, 'getIdeClient').mockReturnValue({
129
+ getDetectedIdeDisplayName: vi.fn().mockReturnValue(undefined),
130
+ } as Partial<IdeClient> as IdeClient);
131
+
132
+ process.env['SANDBOX'] = '';
133
+ if (!aboutCommand.action) {
134
+ throw new Error('The about command must have an action.');
135
+ }
136
+
137
+ await aboutCommand.action(mockContext, '');
138
+
139
+ expect(mockContext.ui.addItem).toHaveBeenCalledWith(
140
+ expect.objectContaining({
141
+ type: MessageType.ABOUT,
142
+ cliVersion: 'test-version',
143
+ osVersion: 'test-os',
144
+ sandboxEnv: 'no sandbox',
145
+ modelVersion: 'test-model',
146
+ selectedAuthType: 'test-auth',
147
+ gcpProject: 'test-gcp-project',
148
+ ideClient: '',
149
+ }),
150
+ expect.any(Number),
151
+ );
152
+ });
153
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/aboutCommand.ts ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { getCliVersion } from '../../utils/version.js';
8
+ import { CommandKind, SlashCommand } from './types.js';
9
+ import process from 'node:process';
10
+ import { MessageType, type HistoryItemAbout } from '../types.js';
11
+
12
+ export const aboutCommand: SlashCommand = {
13
+ name: 'about',
14
+ description: 'show version info',
15
+ kind: CommandKind.BUILT_IN,
16
+ action: async (context) => {
17
+ const osVersion = process.platform;
18
+ let sandboxEnv = 'no sandbox';
19
+ if (process.env['SANDBOX'] && process.env['SANDBOX'] !== 'sandbox-exec') {
20
+ sandboxEnv = process.env['SANDBOX'];
21
+ } else if (process.env['SANDBOX'] === 'sandbox-exec') {
22
+ sandboxEnv = `sandbox-exec (${
23
+ process.env['SEATBELT_PROFILE'] || 'unknown'
24
+ })`;
25
+ }
26
+ const modelVersion = context.services.config?.getModel() || 'Unknown';
27
+ const cliVersion = await getCliVersion();
28
+ const selectedAuthType =
29
+ context.services.settings.merged.selectedAuthType || '';
30
+ const gcpProject = process.env['GOOGLE_CLOUD_PROJECT'] || '';
31
+ const ideClient =
32
+ (context.services.config?.getIdeMode() &&
33
+ context.services.config?.getIdeClient()?.getDetectedIdeDisplayName()) ||
34
+ '';
35
+
36
+ const aboutItem: Omit<HistoryItemAbout, 'id'> = {
37
+ type: MessageType.ABOUT,
38
+ cliVersion,
39
+ osVersion,
40
+ sandboxEnv,
41
+ modelVersion,
42
+ selectedAuthType,
43
+ gcpProject,
44
+ ideClient,
45
+ };
46
+
47
+ context.ui.addItem(aboutItem, Date.now());
48
+ },
49
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/authCommand.test.ts ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach } from 'vitest';
8
+ import { authCommand } from './authCommand.js';
9
+ import { type CommandContext } from './types.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+
12
+ describe('authCommand', () => {
13
+ let mockContext: CommandContext;
14
+
15
+ beforeEach(() => {
16
+ mockContext = createMockCommandContext();
17
+ });
18
+
19
+ it('should return a dialog action to open the auth dialog', () => {
20
+ if (!authCommand.action) {
21
+ throw new Error('The auth command must have an action.');
22
+ }
23
+
24
+ const result = authCommand.action(mockContext, '');
25
+
26
+ expect(result).toEqual({
27
+ type: 'dialog',
28
+ dialog: 'auth',
29
+ });
30
+ });
31
+
32
+ it('should have the correct name and description', () => {
33
+ expect(authCommand.name).toBe('auth');
34
+ expect(authCommand.description).toBe('change the auth method');
35
+ });
36
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/authCommand.ts ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { CommandKind, OpenDialogActionReturn, SlashCommand } from './types.js';
8
+
9
+ export const authCommand: SlashCommand = {
10
+ name: 'auth',
11
+ description: 'change the auth method',
12
+ kind: CommandKind.BUILT_IN,
13
+ action: (_context, _args): OpenDialogActionReturn => ({
14
+ type: 'dialog',
15
+ dialog: 'auth',
16
+ }),
17
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/bugCommand.test.ts ADDED
@@ -0,0 +1,114 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import open from 'open';
9
+ import { bugCommand } from './bugCommand.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+ import { getCliVersion } from '../../utils/version.js';
12
+ import { GIT_COMMIT_INFO } from '../../generated/git-commit.js';
13
+ import { formatMemoryUsage } from '../utils/formatters.js';
14
+
15
+ // Mock dependencies
16
+ vi.mock('open');
17
+ vi.mock('../../utils/version.js');
18
+ vi.mock('../utils/formatters.js');
19
+ vi.mock('@qwen-code/qwen-code-core');
20
+ vi.mock('node:process', () => ({
21
+ default: {
22
+ platform: 'test-platform',
23
+ version: 'v20.0.0',
24
+ // Keep other necessary process properties if needed by other parts of the code
25
+ env: process.env,
26
+ memoryUsage: () => ({ rss: 0 }),
27
+ },
28
+ }));
29
+
30
+ describe('bugCommand', () => {
31
+ beforeEach(() => {
32
+ vi.mocked(getCliVersion).mockResolvedValue('0.1.0');
33
+ vi.mocked(formatMemoryUsage).mockReturnValue('100 MB');
34
+ vi.mock('@qwen-code/qwen-code-core', () => ({
35
+ sessionId: 'test-session-id',
36
+ }));
37
+ vi.stubEnv('SANDBOX', 'qwen-test');
38
+ });
39
+
40
+ afterEach(() => {
41
+ vi.unstubAllEnvs();
42
+ vi.clearAllMocks();
43
+ });
44
+
45
+ it('should generate the default GitHub issue URL', async () => {
46
+ const mockContext = createMockCommandContext({
47
+ services: {
48
+ config: {
49
+ getModel: () => 'qwen3-coder-plus',
50
+ getBugCommand: () => undefined,
51
+ getIdeClient: () => ({
52
+ getDetectedIdeDisplayName: () => 'VSCode',
53
+ }),
54
+ getIdeMode: () => true,
55
+ },
56
+ },
57
+ });
58
+
59
+ if (!bugCommand.action) throw new Error('Action is not defined');
60
+ await bugCommand.action(mockContext, 'A test bug');
61
+
62
+ const expectedInfo = `
63
+ * **CLI Version:** 0.1.0
64
+ * **Git Commit:** ${GIT_COMMIT_INFO}
65
+ * **Session ID:** test-session-id
66
+ * **Operating System:** test-platform v20.0.0
67
+ * **Sandbox Environment:** test
68
+ * **Model Version:** qwen3-coder-plus
69
+ * **Memory Usage:** 100 MB
70
+ * **IDE Client:** VSCode
71
+ `;
72
+ const expectedUrl =
73
+ 'https://github.com/QwenLM/qwen-code/issues/new?template=bug_report.yml&title=A%20test%20bug&info=' +
74
+ encodeURIComponent(expectedInfo);
75
+
76
+ expect(open).toHaveBeenCalledWith(expectedUrl);
77
+ });
78
+
79
+ it('should use a custom URL template from config if provided', async () => {
80
+ const customTemplate =
81
+ 'https://internal.bug-tracker.com/new?desc={title}&details={info}';
82
+ const mockContext = createMockCommandContext({
83
+ services: {
84
+ config: {
85
+ getModel: () => 'qwen3-coder-plus',
86
+ getBugCommand: () => ({ urlTemplate: customTemplate }),
87
+ getIdeClient: () => ({
88
+ getDetectedIdeDisplayName: () => 'VSCode',
89
+ }),
90
+ getIdeMode: () => true,
91
+ },
92
+ },
93
+ });
94
+
95
+ if (!bugCommand.action) throw new Error('Action is not defined');
96
+ await bugCommand.action(mockContext, 'A custom bug');
97
+
98
+ const expectedInfo = `
99
+ * **CLI Version:** 0.1.0
100
+ * **Git Commit:** ${GIT_COMMIT_INFO}
101
+ * **Session ID:** test-session-id
102
+ * **Operating System:** test-platform v20.0.0
103
+ * **Sandbox Environment:** test
104
+ * **Model Version:** qwen3-coder-plus
105
+ * **Memory Usage:** 100 MB
106
+ * **IDE Client:** VSCode
107
+ `;
108
+ const expectedUrl = customTemplate
109
+ .replace('{title}', encodeURIComponent('A custom bug'))
110
+ .replace('{info}', encodeURIComponent(expectedInfo));
111
+
112
+ expect(open).toHaveBeenCalledWith(expectedUrl);
113
+ });
114
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/bugCommand.ts ADDED
@@ -0,0 +1,92 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import open from 'open';
8
+ import process from 'node:process';
9
+ import {
10
+ type CommandContext,
11
+ type SlashCommand,
12
+ CommandKind,
13
+ } from './types.js';
14
+ import { MessageType } from '../types.js';
15
+ import { GIT_COMMIT_INFO } from '../../generated/git-commit.js';
16
+ import { formatMemoryUsage } from '../utils/formatters.js';
17
+ import { getCliVersion } from '../../utils/version.js';
18
+ import { sessionId } from '@qwen-code/qwen-code-core';
19
+
20
+ export const bugCommand: SlashCommand = {
21
+ name: 'bug',
22
+ description: 'submit a bug report',
23
+ kind: CommandKind.BUILT_IN,
24
+ action: async (context: CommandContext, args?: string): Promise<void> => {
25
+ const bugDescription = (args || '').trim();
26
+ const { config } = context.services;
27
+
28
+ const osVersion = `${process.platform} ${process.version}`;
29
+ let sandboxEnv = 'no sandbox';
30
+ if (process.env['SANDBOX'] && process.env['SANDBOX'] !== 'sandbox-exec') {
31
+ sandboxEnv = process.env['SANDBOX'].replace(/^qwen-(?:code-)?/, '');
32
+ } else if (process.env['SANDBOX'] === 'sandbox-exec') {
33
+ sandboxEnv = `sandbox-exec (${
34
+ process.env['SEATBELT_PROFILE'] || 'unknown'
35
+ })`;
36
+ }
37
+ const modelVersion = config?.getModel() || 'Unknown';
38
+ const cliVersion = await getCliVersion();
39
+ const memoryUsage = formatMemoryUsage(process.memoryUsage().rss);
40
+ const ideClient =
41
+ (context.services.config?.getIdeMode() &&
42
+ context.services.config?.getIdeClient()?.getDetectedIdeDisplayName()) ||
43
+ '';
44
+
45
+ let info = `
46
+ * **CLI Version:** ${cliVersion}
47
+ * **Git Commit:** ${GIT_COMMIT_INFO}
48
+ * **Session ID:** ${sessionId}
49
+ * **Operating System:** ${osVersion}
50
+ * **Sandbox Environment:** ${sandboxEnv}
51
+ * **Model Version:** ${modelVersion}
52
+ * **Memory Usage:** ${memoryUsage}
53
+ `;
54
+ if (ideClient) {
55
+ info += `* **IDE Client:** ${ideClient}\n`;
56
+ }
57
+
58
+ let bugReportUrl =
59
+ 'https://github.com/QwenLM/qwen-code/issues/new?template=bug_report.yml&title={title}&info={info}';
60
+
61
+ const bugCommandSettings = config?.getBugCommand();
62
+ if (bugCommandSettings?.urlTemplate) {
63
+ bugReportUrl = bugCommandSettings.urlTemplate;
64
+ }
65
+
66
+ bugReportUrl = bugReportUrl
67
+ .replace('{title}', encodeURIComponent(bugDescription))
68
+ .replace('{info}', encodeURIComponent(info));
69
+
70
+ context.ui.addItem(
71
+ {
72
+ type: MessageType.INFO,
73
+ text: `To submit your bug report, please open the following URL in your browser:\n${bugReportUrl}`,
74
+ },
75
+ Date.now(),
76
+ );
77
+
78
+ try {
79
+ await open(bugReportUrl);
80
+ } catch (error) {
81
+ const errorMessage =
82
+ error instanceof Error ? error.message : String(error);
83
+ context.ui.addItem(
84
+ {
85
+ type: MessageType.ERROR,
86
+ text: `Could not open URL in browser: ${errorMessage}`,
87
+ },
88
+ Date.now(),
89
+ );
90
+ }
91
+ },
92
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/chatCommand.test.ts ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import {
8
+ vi,
9
+ describe,
10
+ it,
11
+ expect,
12
+ beforeEach,
13
+ afterEach,
14
+ Mocked,
15
+ } from 'vitest';
16
+
17
+ import {
18
+ type CommandContext,
19
+ MessageActionReturn,
20
+ SlashCommand,
21
+ } from './types.js';
22
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
23
+ import { Content } from '@google/genai';
24
+ import { GeminiClient } from '@qwen-code/qwen-code-core';
25
+
26
+ import * as fsPromises from 'fs/promises';
27
+ import { chatCommand } from './chatCommand.js';
28
+ import { Stats } from 'fs';
29
+ import { HistoryItemWithoutId } from '../types.js';
30
+
31
+ vi.mock('fs/promises', () => ({
32
+ stat: vi.fn(),
33
+ readdir: vi.fn().mockResolvedValue(['file1.txt', 'file2.txt'] as string[]),
34
+ }));
35
+
36
+ describe('chatCommand', () => {
37
+ const mockFs = fsPromises as Mocked<typeof fsPromises>;
38
+
39
+ let mockContext: CommandContext;
40
+ let mockGetChat: ReturnType<typeof vi.fn>;
41
+ let mockSaveCheckpoint: ReturnType<typeof vi.fn>;
42
+ let mockLoadCheckpoint: ReturnType<typeof vi.fn>;
43
+ let mockDeleteCheckpoint: ReturnType<typeof vi.fn>;
44
+ let mockGetHistory: ReturnType<typeof vi.fn>;
45
+
46
+ const getSubCommand = (
47
+ name: 'list' | 'save' | 'resume' | 'delete',
48
+ ): SlashCommand => {
49
+ const subCommand = chatCommand.subCommands?.find(
50
+ (cmd) => cmd.name === name,
51
+ );
52
+ if (!subCommand) {
53
+ throw new Error(`/chat ${name} command not found.`);
54
+ }
55
+ return subCommand;
56
+ };
57
+
58
+ beforeEach(() => {
59
+ mockGetHistory = vi.fn().mockReturnValue([]);
60
+ mockGetChat = vi.fn().mockResolvedValue({
61
+ getHistory: mockGetHistory,
62
+ });
63
+ mockSaveCheckpoint = vi.fn().mockResolvedValue(undefined);
64
+ mockLoadCheckpoint = vi.fn().mockResolvedValue([]);
65
+ mockDeleteCheckpoint = vi.fn().mockResolvedValue(true);
66
+
67
+ mockContext = createMockCommandContext({
68
+ services: {
69
+ config: {
70
+ getProjectTempDir: () => '/tmp/gemini',
71
+ getGeminiClient: () =>
72
+ ({
73
+ getChat: mockGetChat,
74
+ }) as unknown as GeminiClient,
75
+ },
76
+ logger: {
77
+ saveCheckpoint: mockSaveCheckpoint,
78
+ loadCheckpoint: mockLoadCheckpoint,
79
+ deleteCheckpoint: mockDeleteCheckpoint,
80
+ initialize: vi.fn().mockResolvedValue(undefined),
81
+ },
82
+ },
83
+ });
84
+ });
85
+
86
+ afterEach(() => {
87
+ vi.restoreAllMocks();
88
+ });
89
+
90
+ it('should have the correct main command definition', () => {
91
+ expect(chatCommand.name).toBe('chat');
92
+ expect(chatCommand.description).toBe('Manage conversation history.');
93
+ expect(chatCommand.subCommands).toHaveLength(4);
94
+ });
95
+
96
+ describe('list subcommand', () => {
97
+ let listCommand: SlashCommand;
98
+
99
+ beforeEach(() => {
100
+ listCommand = getSubCommand('list');
101
+ });
102
+
103
+ it('should inform when no checkpoints are found', async () => {
104
+ mockFs.readdir.mockImplementation(
105
+ (async (_: string): Promise<string[]> =>
106
+ [] as string[]) as unknown as typeof fsPromises.readdir,
107
+ );
108
+ const result = await listCommand?.action?.(mockContext, '');
109
+ expect(result).toEqual({
110
+ type: 'message',
111
+ messageType: 'info',
112
+ content: 'No saved conversation checkpoints found.',
113
+ });
114
+ });
115
+
116
+ it('should list found checkpoints', async () => {
117
+ const fakeFiles = ['checkpoint-test1.json', 'checkpoint-test2.json'];
118
+ const date = new Date();
119
+
120
+ mockFs.readdir.mockImplementation(
121
+ (async (_: string): Promise<string[]> =>
122
+ fakeFiles as string[]) as unknown as typeof fsPromises.readdir,
123
+ );
124
+ mockFs.stat.mockImplementation((async (path: string): Promise<Stats> => {
125
+ if (path.endsWith('test1.json')) {
126
+ return { mtime: date } as Stats;
127
+ }
128
+ return { mtime: new Date(date.getTime() + 1000) } as Stats;
129
+ }) as unknown as typeof fsPromises.stat);
130
+
131
+ const result = (await listCommand?.action?.(
132
+ mockContext,
133
+ '',
134
+ )) as MessageActionReturn;
135
+
136
+ const content = result?.content ?? '';
137
+ expect(result?.type).toBe('message');
138
+ expect(content).toContain('List of saved conversations:');
139
+ const isoDate = date
140
+ .toISOString()
141
+ .match(/(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/);
142
+ const formattedDate = isoDate ? `${isoDate[1]} ${isoDate[2]}` : '';
143
+ expect(content).toContain(formattedDate);
144
+ const index1 = content.indexOf('- \u001b[36mtest1\u001b[0m');
145
+ const index2 = content.indexOf('- \u001b[36mtest2\u001b[0m');
146
+ expect(index1).toBeGreaterThanOrEqual(0);
147
+ expect(index2).toBeGreaterThan(index1);
148
+ });
149
+
150
+ it('should handle invalid date formats gracefully', async () => {
151
+ const fakeFiles = ['checkpoint-baddate.json'];
152
+ const badDate = {
153
+ toISOString: () => 'an-invalid-date-string',
154
+ } as Date;
155
+
156
+ mockFs.readdir.mockResolvedValue(fakeFiles);
157
+ mockFs.stat.mockResolvedValue({ mtime: badDate } as Stats);
158
+
159
+ const result = (await listCommand?.action?.(
160
+ mockContext,
161
+ '',
162
+ )) as MessageActionReturn;
163
+
164
+ const content = result?.content ?? '';
165
+ expect(content).toContain('(saved on Invalid Date)');
166
+ });
167
+ });
168
+ describe('save subcommand', () => {
169
+ let saveCommand: SlashCommand;
170
+ const tag = 'my-tag';
171
+ let mockCheckpointExists: ReturnType<typeof vi.fn>;
172
+
173
+ beforeEach(() => {
174
+ saveCommand = getSubCommand('save');
175
+ mockCheckpointExists = vi.fn().mockResolvedValue(false);
176
+ mockContext.services.logger.checkpointExists = mockCheckpointExists;
177
+ });
178
+
179
+ it('should return an error if tag is missing', async () => {
180
+ const result = await saveCommand?.action?.(mockContext, ' ');
181
+ expect(result).toEqual({
182
+ type: 'message',
183
+ messageType: 'error',
184
+ content: 'Missing tag. Usage: /chat save <tag>',
185
+ });
186
+ });
187
+
188
+ it('should inform if conversation history is empty or only contains system context', async () => {
189
+ mockGetHistory.mockReturnValue([]);
190
+ let result = await saveCommand?.action?.(mockContext, tag);
191
+ expect(result).toEqual({
192
+ type: 'message',
193
+ messageType: 'info',
194
+ content: 'No conversation found to save.',
195
+ });
196
+
197
+ mockGetHistory.mockReturnValue([
198
+ { role: 'user', parts: [{ text: 'context for our chat' }] },
199
+ { role: 'model', parts: [{ text: 'Got it. Thanks for the context!' }] },
200
+ ]);
201
+ result = await saveCommand?.action?.(mockContext, tag);
202
+ expect(result).toEqual({
203
+ type: 'message',
204
+ messageType: 'info',
205
+ content: 'No conversation found to save.',
206
+ });
207
+
208
+ mockGetHistory.mockReturnValue([
209
+ { role: 'user', parts: [{ text: 'context for our chat' }] },
210
+ { role: 'model', parts: [{ text: 'Got it. Thanks for the context!' }] },
211
+ { role: 'user', parts: [{ text: 'Hello, how are you?' }] },
212
+ ]);
213
+ result = await saveCommand?.action?.(mockContext, tag);
214
+ expect(result).toEqual({
215
+ type: 'message',
216
+ messageType: 'info',
217
+ content: `Conversation checkpoint saved with tag: ${tag}.`,
218
+ });
219
+ });
220
+
221
+ it('should return confirm_action if checkpoint already exists', async () => {
222
+ mockCheckpointExists.mockResolvedValue(true);
223
+ mockContext.invocation = {
224
+ raw: `/chat save ${tag}`,
225
+ name: 'save',
226
+ args: tag,
227
+ };
228
+
229
+ const result = await saveCommand?.action?.(mockContext, tag);
230
+
231
+ expect(mockCheckpointExists).toHaveBeenCalledWith(tag);
232
+ expect(mockSaveCheckpoint).not.toHaveBeenCalled();
233
+ expect(result).toMatchObject({
234
+ type: 'confirm_action',
235
+ originalInvocation: { raw: `/chat save ${tag}` },
236
+ });
237
+ // Check that prompt is a React element
238
+ expect(result).toHaveProperty('prompt');
239
+ });
240
+
241
+ it('should save the conversation if overwrite is confirmed', async () => {
242
+ const history: Content[] = [
243
+ { role: 'user', parts: [{ text: 'context for our chat' }] },
244
+ { role: 'model', parts: [{ text: 'Got it. Thanks for the context!' }] },
245
+ { role: 'user', parts: [{ text: 'hello' }] },
246
+ { role: 'model', parts: [{ text: 'Hi there!' }] },
247
+ ];
248
+ mockGetHistory.mockReturnValue(history);
249
+ mockContext.overwriteConfirmed = true;
250
+
251
+ const result = await saveCommand?.action?.(mockContext, tag);
252
+
253
+ expect(mockCheckpointExists).not.toHaveBeenCalled(); // Should skip existence check
254
+ expect(mockSaveCheckpoint).toHaveBeenCalledWith(history, tag);
255
+ expect(result).toEqual({
256
+ type: 'message',
257
+ messageType: 'info',
258
+ content: `Conversation checkpoint saved with tag: ${tag}.`,
259
+ });
260
+ });
261
+ });
262
+
263
+ describe('resume subcommand', () => {
264
+ const goodTag = 'good-tag';
265
+ const badTag = 'bad-tag';
266
+
267
+ let resumeCommand: SlashCommand;
268
+ beforeEach(() => {
269
+ resumeCommand = getSubCommand('resume');
270
+ });
271
+
272
+ it('should return an error if tag is missing', async () => {
273
+ const result = await resumeCommand?.action?.(mockContext, '');
274
+
275
+ expect(result).toEqual({
276
+ type: 'message',
277
+ messageType: 'error',
278
+ content: 'Missing tag. Usage: /chat resume <tag>',
279
+ });
280
+ });
281
+
282
+ it('should inform if checkpoint is not found', async () => {
283
+ mockLoadCheckpoint.mockResolvedValue([]);
284
+
285
+ const result = await resumeCommand?.action?.(mockContext, badTag);
286
+
287
+ expect(result).toEqual({
288
+ type: 'message',
289
+ messageType: 'info',
290
+ content: `No saved checkpoint found with tag: ${badTag}.`,
291
+ });
292
+ });
293
+
294
+ it('should resume a conversation', async () => {
295
+ const conversation: Content[] = [
296
+ { role: 'user', parts: [{ text: 'hello gemini' }] },
297
+ { role: 'model', parts: [{ text: 'hello world' }] },
298
+ ];
299
+ mockLoadCheckpoint.mockResolvedValue(conversation);
300
+
301
+ const result = await resumeCommand?.action?.(mockContext, goodTag);
302
+
303
+ expect(result).toEqual({
304
+ type: 'load_history',
305
+ history: [
306
+ { type: 'user', text: 'hello gemini' },
307
+ { type: 'gemini', text: 'hello world' },
308
+ ] as HistoryItemWithoutId[],
309
+ clientHistory: conversation,
310
+ });
311
+ });
312
+
313
+ describe('completion', () => {
314
+ it('should provide completion suggestions', async () => {
315
+ const fakeFiles = ['checkpoint-alpha.json', 'checkpoint-beta.json'];
316
+ mockFs.readdir.mockImplementation(
317
+ (async (_: string): Promise<string[]> =>
318
+ fakeFiles as string[]) as unknown as typeof fsPromises.readdir,
319
+ );
320
+
321
+ mockFs.stat.mockImplementation(
322
+ (async (_: string): Promise<Stats> =>
323
+ ({
324
+ mtime: new Date(),
325
+ }) as Stats) as unknown as typeof fsPromises.stat,
326
+ );
327
+
328
+ const result = await resumeCommand?.completion?.(mockContext, 'a');
329
+
330
+ expect(result).toEqual(['alpha']);
331
+ });
332
+
333
+ it('should suggest filenames sorted by modified time (newest first)', async () => {
334
+ const fakeFiles = ['checkpoint-test1.json', 'checkpoint-test2.json'];
335
+ const date = new Date();
336
+ mockFs.readdir.mockImplementation(
337
+ (async (_: string): Promise<string[]> =>
338
+ fakeFiles as string[]) as unknown as typeof fsPromises.readdir,
339
+ );
340
+ mockFs.stat.mockImplementation((async (
341
+ path: string,
342
+ ): Promise<Stats> => {
343
+ if (path.endsWith('test1.json')) {
344
+ return { mtime: date } as Stats;
345
+ }
346
+ return { mtime: new Date(date.getTime() + 1000) } as Stats;
347
+ }) as unknown as typeof fsPromises.stat);
348
+
349
+ const result = await resumeCommand?.completion?.(mockContext, '');
350
+ // Sort items by last modified time (newest first)
351
+ expect(result).toEqual(['test2', 'test1']);
352
+ });
353
+ });
354
+ });
355
+
356
+ describe('delete subcommand', () => {
357
+ let deleteCommand: SlashCommand;
358
+ const tag = 'my-tag';
359
+ beforeEach(() => {
360
+ deleteCommand = getSubCommand('delete');
361
+ });
362
+
363
+ it('should return an error if tag is missing', async () => {
364
+ const result = await deleteCommand?.action?.(mockContext, ' ');
365
+ expect(result).toEqual({
366
+ type: 'message',
367
+ messageType: 'error',
368
+ content: 'Missing tag. Usage: /chat delete <tag>',
369
+ });
370
+ });
371
+
372
+ it('should return an error if checkpoint is not found', async () => {
373
+ mockDeleteCheckpoint.mockResolvedValue(false);
374
+ const result = await deleteCommand?.action?.(mockContext, tag);
375
+ expect(result).toEqual({
376
+ type: 'message',
377
+ messageType: 'error',
378
+ content: `Error: No checkpoint found with tag '${tag}'.`,
379
+ });
380
+ });
381
+
382
+ it('should delete the conversation', async () => {
383
+ const result = await deleteCommand?.action?.(mockContext, tag);
384
+
385
+ expect(mockDeleteCheckpoint).toHaveBeenCalledWith(tag);
386
+ expect(result).toEqual({
387
+ type: 'message',
388
+ messageType: 'info',
389
+ content: `Conversation checkpoint '${tag}' has been deleted.`,
390
+ });
391
+ });
392
+
393
+ describe('completion', () => {
394
+ it('should provide completion suggestions', async () => {
395
+ const fakeFiles = ['checkpoint-alpha.json', 'checkpoint-beta.json'];
396
+ mockFs.readdir.mockImplementation(
397
+ (async (_: string): Promise<string[]> =>
398
+ fakeFiles as string[]) as unknown as typeof fsPromises.readdir,
399
+ );
400
+
401
+ mockFs.stat.mockImplementation(
402
+ (async (_: string): Promise<Stats> =>
403
+ ({
404
+ mtime: new Date(),
405
+ }) as Stats) as unknown as typeof fsPromises.stat,
406
+ );
407
+
408
+ const result = await deleteCommand?.completion?.(mockContext, 'a');
409
+
410
+ expect(result).toEqual(['alpha']);
411
+ });
412
+ });
413
+ });
414
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/chatCommand.ts ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import * as fsPromises from 'fs/promises';
8
+ import React from 'react';
9
+ import { Text } from 'ink';
10
+ import { Colors } from '../colors.js';
11
+ import {
12
+ CommandContext,
13
+ SlashCommand,
14
+ MessageActionReturn,
15
+ CommandKind,
16
+ SlashCommandActionReturn,
17
+ } from './types.js';
18
+ import { decodeTagName } from '@qwen-code/qwen-code-core';
19
+ import path from 'path';
20
+ import { HistoryItemWithoutId, MessageType } from '../types.js';
21
+
22
+ interface ChatDetail {
23
+ name: string;
24
+ mtime: Date;
25
+ }
26
+
27
+ const getSavedChatTags = async (
28
+ context: CommandContext,
29
+ mtSortDesc: boolean,
30
+ ): Promise<ChatDetail[]> => {
31
+ const geminiDir = context.services.config?.getProjectTempDir();
32
+ if (!geminiDir) {
33
+ return [];
34
+ }
35
+ try {
36
+ const file_head = 'checkpoint-';
37
+ const file_tail = '.json';
38
+ const files = await fsPromises.readdir(geminiDir);
39
+ const chatDetails: Array<{ name: string; mtime: Date }> = [];
40
+
41
+ for (const file of files) {
42
+ if (file.startsWith(file_head) && file.endsWith(file_tail)) {
43
+ const filePath = path.join(geminiDir, file);
44
+ const stats = await fsPromises.stat(filePath);
45
+ const tagName = file.slice(file_head.length, -file_tail.length);
46
+ chatDetails.push({
47
+ name: decodeTagName(tagName),
48
+ mtime: stats.mtime,
49
+ });
50
+ }
51
+ }
52
+
53
+ chatDetails.sort((a, b) =>
54
+ mtSortDesc
55
+ ? b.mtime.getTime() - a.mtime.getTime()
56
+ : a.mtime.getTime() - b.mtime.getTime(),
57
+ );
58
+
59
+ return chatDetails;
60
+ } catch (_err) {
61
+ return [];
62
+ }
63
+ };
64
+
65
+ const listCommand: SlashCommand = {
66
+ name: 'list',
67
+ description: 'List saved conversation checkpoints',
68
+ kind: CommandKind.BUILT_IN,
69
+ action: async (context): Promise<MessageActionReturn> => {
70
+ const chatDetails = await getSavedChatTags(context, false);
71
+ if (chatDetails.length === 0) {
72
+ return {
73
+ type: 'message',
74
+ messageType: 'info',
75
+ content: 'No saved conversation checkpoints found.',
76
+ };
77
+ }
78
+
79
+ const maxNameLength = Math.max(
80
+ ...chatDetails.map((chat) => chat.name.length),
81
+ );
82
+
83
+ let message = 'List of saved conversations:\n\n';
84
+ for (const chat of chatDetails) {
85
+ const paddedName = chat.name.padEnd(maxNameLength, ' ');
86
+ const isoString = chat.mtime.toISOString();
87
+ const match = isoString.match(/(\d{4}-\d{2}-\d{2})T(\d{2}:\d{2}:\d{2})/);
88
+ const formattedDate = match ? `${match[1]} ${match[2]}` : 'Invalid Date';
89
+ message += ` - \u001b[36m${paddedName}\u001b[0m \u001b[90m(saved on ${formattedDate})\u001b[0m\n`;
90
+ }
91
+ message += `\n\u001b[90mNote: Newest last, oldest first\u001b[0m`;
92
+ return {
93
+ type: 'message',
94
+ messageType: 'info',
95
+ content: message,
96
+ };
97
+ },
98
+ };
99
+
100
+ const saveCommand: SlashCommand = {
101
+ name: 'save',
102
+ description:
103
+ 'Save the current conversation as a checkpoint. Usage: /chat save <tag>',
104
+ kind: CommandKind.BUILT_IN,
105
+ action: async (context, args): Promise<SlashCommandActionReturn | void> => {
106
+ const tag = args.trim();
107
+ if (!tag) {
108
+ return {
109
+ type: 'message',
110
+ messageType: 'error',
111
+ content: 'Missing tag. Usage: /chat save <tag>',
112
+ };
113
+ }
114
+
115
+ const { logger, config } = context.services;
116
+ await logger.initialize();
117
+
118
+ if (!context.overwriteConfirmed) {
119
+ const exists = await logger.checkpointExists(tag);
120
+ if (exists) {
121
+ return {
122
+ type: 'confirm_action',
123
+ prompt: React.createElement(
124
+ Text,
125
+ null,
126
+ 'A checkpoint with the tag ',
127
+ React.createElement(Text, { color: Colors.AccentPurple }, tag),
128
+ ' already exists. Do you want to overwrite it?',
129
+ ),
130
+ originalInvocation: {
131
+ raw: context.invocation?.raw || `/chat save ${tag}`,
132
+ },
133
+ };
134
+ }
135
+ }
136
+
137
+ const chat = await config?.getGeminiClient()?.getChat();
138
+ if (!chat) {
139
+ return {
140
+ type: 'message',
141
+ messageType: 'error',
142
+ content: 'No chat client available to save conversation.',
143
+ };
144
+ }
145
+
146
+ const history = chat.getHistory();
147
+ if (history.length > 2) {
148
+ await logger.saveCheckpoint(history, tag);
149
+ return {
150
+ type: 'message',
151
+ messageType: 'info',
152
+ content: `Conversation checkpoint saved with tag: ${decodeTagName(tag)}.`,
153
+ };
154
+ } else {
155
+ return {
156
+ type: 'message',
157
+ messageType: 'info',
158
+ content: 'No conversation found to save.',
159
+ };
160
+ }
161
+ },
162
+ };
163
+
164
+ const resumeCommand: SlashCommand = {
165
+ name: 'resume',
166
+ altNames: ['load'],
167
+ description:
168
+ 'Resume a conversation from a checkpoint. Usage: /chat resume <tag>',
169
+ kind: CommandKind.BUILT_IN,
170
+ action: async (context, args) => {
171
+ const tag = args.trim();
172
+ if (!tag) {
173
+ return {
174
+ type: 'message',
175
+ messageType: 'error',
176
+ content: 'Missing tag. Usage: /chat resume <tag>',
177
+ };
178
+ }
179
+
180
+ const { logger } = context.services;
181
+ await logger.initialize();
182
+ const conversation = await logger.loadCheckpoint(tag);
183
+
184
+ if (conversation.length === 0) {
185
+ return {
186
+ type: 'message',
187
+ messageType: 'info',
188
+ content: `No saved checkpoint found with tag: ${decodeTagName(tag)}.`,
189
+ };
190
+ }
191
+
192
+ const rolemap: { [key: string]: MessageType } = {
193
+ user: MessageType.USER,
194
+ model: MessageType.GEMINI,
195
+ };
196
+
197
+ const uiHistory: HistoryItemWithoutId[] = [];
198
+ let hasSystemPrompt = false;
199
+ let i = 0;
200
+
201
+ for (const item of conversation) {
202
+ i += 1;
203
+ const text =
204
+ item.parts
205
+ ?.filter((m) => !!m.text)
206
+ .map((m) => m.text)
207
+ .join('') || '';
208
+ if (!text) {
209
+ continue;
210
+ }
211
+ if (i === 1 && text.match(/context for our chat/)) {
212
+ hasSystemPrompt = true;
213
+ }
214
+ if (i > 2 || !hasSystemPrompt) {
215
+ uiHistory.push({
216
+ type: (item.role && rolemap[item.role]) || MessageType.GEMINI,
217
+ text,
218
+ } as HistoryItemWithoutId);
219
+ }
220
+ }
221
+ return {
222
+ type: 'load_history',
223
+ history: uiHistory,
224
+ clientHistory: conversation,
225
+ };
226
+ },
227
+ completion: async (context, partialArg) => {
228
+ const chatDetails = await getSavedChatTags(context, true);
229
+ return chatDetails
230
+ .map((chat) => chat.name)
231
+ .filter((name) => name.startsWith(partialArg));
232
+ },
233
+ };
234
+
235
+ const deleteCommand: SlashCommand = {
236
+ name: 'delete',
237
+ description: 'Delete a conversation checkpoint. Usage: /chat delete <tag>',
238
+ kind: CommandKind.BUILT_IN,
239
+ action: async (context, args): Promise<MessageActionReturn> => {
240
+ const tag = args.trim();
241
+ if (!tag) {
242
+ return {
243
+ type: 'message',
244
+ messageType: 'error',
245
+ content: 'Missing tag. Usage: /chat delete <tag>',
246
+ };
247
+ }
248
+
249
+ const { logger } = context.services;
250
+ await logger.initialize();
251
+ const deleted = await logger.deleteCheckpoint(tag);
252
+
253
+ if (deleted) {
254
+ return {
255
+ type: 'message',
256
+ messageType: 'info',
257
+ content: `Conversation checkpoint '${decodeTagName(tag)}' has been deleted.`,
258
+ };
259
+ } else {
260
+ return {
261
+ type: 'message',
262
+ messageType: 'error',
263
+ content: `Error: No checkpoint found with tag '${decodeTagName(tag)}'.`,
264
+ };
265
+ }
266
+ },
267
+ completion: async (context, partialArg) => {
268
+ const chatDetails = await getSavedChatTags(context, true);
269
+ return chatDetails
270
+ .map((chat) => chat.name)
271
+ .filter((name) => name.startsWith(partialArg));
272
+ },
273
+ };
274
+
275
+ export const chatCommand: SlashCommand = {
276
+ name: 'chat',
277
+ description: 'Manage conversation history.',
278
+ kind: CommandKind.BUILT_IN,
279
+ subCommands: [listCommand, saveCommand, resumeCommand, deleteCommand],
280
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/clearCommand.test.ts ADDED
@@ -0,0 +1,100 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, Mock } from 'vitest';
8
+ import { clearCommand } from './clearCommand.js';
9
+ import { type CommandContext } from './types.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+
12
+ // Mock the telemetry service
13
+ vi.mock('@qwen-code/qwen-code-core', async () => {
14
+ const actual = await vi.importActual('@qwen-code/qwen-code-core');
15
+ return {
16
+ ...actual,
17
+ uiTelemetryService: {
18
+ resetLastPromptTokenCount: vi.fn(),
19
+ },
20
+ };
21
+ });
22
+
23
+ import { GeminiClient, uiTelemetryService } from '@qwen-code/qwen-code-core';
24
+
25
+ describe('clearCommand', () => {
26
+ let mockContext: CommandContext;
27
+ let mockResetChat: ReturnType<typeof vi.fn>;
28
+
29
+ beforeEach(() => {
30
+ mockResetChat = vi.fn().mockResolvedValue(undefined);
31
+ vi.clearAllMocks();
32
+
33
+ mockContext = createMockCommandContext({
34
+ services: {
35
+ config: {
36
+ getGeminiClient: () =>
37
+ ({
38
+ resetChat: mockResetChat,
39
+ }) as unknown as GeminiClient,
40
+ },
41
+ },
42
+ });
43
+ });
44
+
45
+ it('should set debug message, reset chat, reset telemetry, and clear UI when config is available', async () => {
46
+ if (!clearCommand.action) {
47
+ throw new Error('clearCommand must have an action.');
48
+ }
49
+
50
+ await clearCommand.action(mockContext, '');
51
+
52
+ expect(mockContext.ui.setDebugMessage).toHaveBeenCalledWith(
53
+ 'Clearing terminal and resetting chat.',
54
+ );
55
+ expect(mockContext.ui.setDebugMessage).toHaveBeenCalledTimes(1);
56
+
57
+ expect(mockResetChat).toHaveBeenCalledTimes(1);
58
+ expect(uiTelemetryService.resetLastPromptTokenCount).toHaveBeenCalledTimes(
59
+ 1,
60
+ );
61
+ expect(mockContext.ui.clear).toHaveBeenCalledTimes(1);
62
+
63
+ // Check the order of operations.
64
+ const setDebugMessageOrder = (mockContext.ui.setDebugMessage as Mock).mock
65
+ .invocationCallOrder[0];
66
+ const resetChatOrder = mockResetChat.mock.invocationCallOrder[0];
67
+ const resetTelemetryOrder = (
68
+ uiTelemetryService.resetLastPromptTokenCount as Mock
69
+ ).mock.invocationCallOrder[0];
70
+ const clearOrder = (mockContext.ui.clear as Mock).mock
71
+ .invocationCallOrder[0];
72
+
73
+ expect(setDebugMessageOrder).toBeLessThan(resetChatOrder);
74
+ expect(resetChatOrder).toBeLessThan(resetTelemetryOrder);
75
+ expect(resetTelemetryOrder).toBeLessThan(clearOrder);
76
+ });
77
+
78
+ it('should not attempt to reset chat if config service is not available', async () => {
79
+ if (!clearCommand.action) {
80
+ throw new Error('clearCommand must have an action.');
81
+ }
82
+
83
+ const nullConfigContext = createMockCommandContext({
84
+ services: {
85
+ config: null,
86
+ },
87
+ });
88
+
89
+ await clearCommand.action(nullConfigContext, '');
90
+
91
+ expect(nullConfigContext.ui.setDebugMessage).toHaveBeenCalledWith(
92
+ 'Clearing terminal.',
93
+ );
94
+ expect(mockResetChat).not.toHaveBeenCalled();
95
+ expect(uiTelemetryService.resetLastPromptTokenCount).toHaveBeenCalledTimes(
96
+ 1,
97
+ );
98
+ expect(nullConfigContext.ui.clear).toHaveBeenCalledTimes(1);
99
+ });
100
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/clearCommand.ts ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { uiTelemetryService } from '@qwen-code/qwen-code-core';
8
+ import { CommandKind, SlashCommand } from './types.js';
9
+
10
+ export const clearCommand: SlashCommand = {
11
+ name: 'clear',
12
+ description: 'clear the screen and conversation history',
13
+ kind: CommandKind.BUILT_IN,
14
+ action: async (context, _args) => {
15
+ const geminiClient = context.services.config?.getGeminiClient();
16
+
17
+ if (geminiClient) {
18
+ context.ui.setDebugMessage('Clearing terminal and resetting chat.');
19
+ // If resetChat fails, the exception will propagate and halt the command,
20
+ // which is the correct behavior to signal a failure to the user.
21
+ await geminiClient.resetChat();
22
+ } else {
23
+ context.ui.setDebugMessage('Clearing terminal.');
24
+ }
25
+
26
+ uiTelemetryService.resetLastPromptTokenCount();
27
+ context.ui.clear();
28
+ },
29
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/compressCommand.test.ts ADDED
@@ -0,0 +1,129 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { GeminiClient } from '@qwen-code/qwen-code-core';
8
+ import { vi, describe, it, expect, beforeEach } from 'vitest';
9
+ import { compressCommand } from './compressCommand.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+ import { MessageType } from '../types.js';
12
+
13
+ describe('compressCommand', () => {
14
+ let context: ReturnType<typeof createMockCommandContext>;
15
+ let mockTryCompressChat: ReturnType<typeof vi.fn>;
16
+
17
+ beforeEach(() => {
18
+ mockTryCompressChat = vi.fn();
19
+ context = createMockCommandContext({
20
+ services: {
21
+ config: {
22
+ getGeminiClient: () =>
23
+ ({
24
+ tryCompressChat: mockTryCompressChat,
25
+ }) as unknown as GeminiClient,
26
+ },
27
+ },
28
+ });
29
+ });
30
+
31
+ it('should do nothing if a compression is already pending', async () => {
32
+ context.ui.pendingItem = {
33
+ type: MessageType.COMPRESSION,
34
+ compression: {
35
+ isPending: true,
36
+ originalTokenCount: null,
37
+ newTokenCount: null,
38
+ },
39
+ };
40
+ await compressCommand.action!(context, '');
41
+ expect(context.ui.addItem).toHaveBeenCalledWith(
42
+ expect.objectContaining({
43
+ type: MessageType.ERROR,
44
+ text: 'Already compressing, wait for previous request to complete',
45
+ }),
46
+ expect.any(Number),
47
+ );
48
+ expect(context.ui.setPendingItem).not.toHaveBeenCalled();
49
+ expect(mockTryCompressChat).not.toHaveBeenCalled();
50
+ });
51
+
52
+ it('should set pending item, call tryCompressChat, and add result on success', async () => {
53
+ const compressedResult = {
54
+ originalTokenCount: 200,
55
+ newTokenCount: 100,
56
+ };
57
+ mockTryCompressChat.mockResolvedValue(compressedResult);
58
+
59
+ await compressCommand.action!(context, '');
60
+
61
+ expect(context.ui.setPendingItem).toHaveBeenNthCalledWith(
62
+ 1,
63
+ expect.objectContaining({
64
+ type: MessageType.COMPRESSION,
65
+ compression: {
66
+ isPending: true,
67
+ originalTokenCount: null,
68
+ newTokenCount: null,
69
+ },
70
+ }),
71
+ );
72
+
73
+ expect(mockTryCompressChat).toHaveBeenCalledWith(
74
+ expect.stringMatching(/^compress-\d+$/),
75
+ true,
76
+ );
77
+
78
+ expect(context.ui.addItem).toHaveBeenCalledWith(
79
+ expect.objectContaining({
80
+ type: MessageType.COMPRESSION,
81
+ compression: {
82
+ isPending: false,
83
+ originalTokenCount: 200,
84
+ newTokenCount: 100,
85
+ },
86
+ }),
87
+ expect.any(Number),
88
+ );
89
+
90
+ expect(context.ui.setPendingItem).toHaveBeenNthCalledWith(2, null);
91
+ });
92
+
93
+ it('should add an error message if tryCompressChat returns falsy', async () => {
94
+ mockTryCompressChat.mockResolvedValue(null);
95
+
96
+ await compressCommand.action!(context, '');
97
+
98
+ expect(context.ui.addItem).toHaveBeenCalledWith(
99
+ expect.objectContaining({
100
+ type: MessageType.ERROR,
101
+ text: 'Failed to compress chat history.',
102
+ }),
103
+ expect.any(Number),
104
+ );
105
+ expect(context.ui.setPendingItem).toHaveBeenCalledWith(null);
106
+ });
107
+
108
+ it('should add an error message if tryCompressChat throws', async () => {
109
+ const error = new Error('Compression failed');
110
+ mockTryCompressChat.mockRejectedValue(error);
111
+
112
+ await compressCommand.action!(context, '');
113
+
114
+ expect(context.ui.addItem).toHaveBeenCalledWith(
115
+ expect.objectContaining({
116
+ type: MessageType.ERROR,
117
+ text: `Failed to compress chat history: ${error.message}`,
118
+ }),
119
+ expect.any(Number),
120
+ );
121
+ expect(context.ui.setPendingItem).toHaveBeenCalledWith(null);
122
+ });
123
+
124
+ it('should clear the pending item in a finally block', async () => {
125
+ mockTryCompressChat.mockRejectedValue(new Error('some error'));
126
+ await compressCommand.action!(context, '');
127
+ expect(context.ui.setPendingItem).toHaveBeenCalledWith(null);
128
+ });
129
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/compressCommand.ts ADDED
@@ -0,0 +1,78 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { HistoryItemCompression, MessageType } from '../types.js';
8
+ import { CommandKind, SlashCommand } from './types.js';
9
+
10
+ export const compressCommand: SlashCommand = {
11
+ name: 'compress',
12
+ altNames: ['summarize'],
13
+ description: 'Compresses the context by replacing it with a summary.',
14
+ kind: CommandKind.BUILT_IN,
15
+ action: async (context) => {
16
+ const { ui } = context;
17
+ if (ui.pendingItem) {
18
+ ui.addItem(
19
+ {
20
+ type: MessageType.ERROR,
21
+ text: 'Already compressing, wait for previous request to complete',
22
+ },
23
+ Date.now(),
24
+ );
25
+ return;
26
+ }
27
+
28
+ const pendingMessage: HistoryItemCompression = {
29
+ type: MessageType.COMPRESSION,
30
+ compression: {
31
+ isPending: true,
32
+ originalTokenCount: null,
33
+ newTokenCount: null,
34
+ },
35
+ };
36
+
37
+ try {
38
+ ui.setPendingItem(pendingMessage);
39
+ const promptId = `compress-${Date.now()}`;
40
+ const compressed = await context.services.config
41
+ ?.getGeminiClient()
42
+ ?.tryCompressChat(promptId, true);
43
+ if (compressed) {
44
+ ui.addItem(
45
+ {
46
+ type: MessageType.COMPRESSION,
47
+ compression: {
48
+ isPending: false,
49
+ originalTokenCount: compressed.originalTokenCount,
50
+ newTokenCount: compressed.newTokenCount,
51
+ },
52
+ } as HistoryItemCompression,
53
+ Date.now(),
54
+ );
55
+ } else {
56
+ ui.addItem(
57
+ {
58
+ type: MessageType.ERROR,
59
+ text: 'Failed to compress chat history.',
60
+ },
61
+ Date.now(),
62
+ );
63
+ }
64
+ } catch (e) {
65
+ ui.addItem(
66
+ {
67
+ type: MessageType.ERROR,
68
+ text: `Failed to compress chat history: ${
69
+ e instanceof Error ? e.message : String(e)
70
+ }`,
71
+ },
72
+ Date.now(),
73
+ );
74
+ } finally {
75
+ ui.setPendingItem(null);
76
+ }
77
+ },
78
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/copyCommand.test.ts ADDED
@@ -0,0 +1,296 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { vi, describe, it, expect, beforeEach, Mock } from 'vitest';
8
+ import { copyCommand } from './copyCommand.js';
9
+ import { type CommandContext } from './types.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+ import { copyToClipboard } from '../utils/commandUtils.js';
12
+
13
+ vi.mock('../utils/commandUtils.js', () => ({
14
+ copyToClipboard: vi.fn(),
15
+ }));
16
+
17
+ describe('copyCommand', () => {
18
+ let mockContext: CommandContext;
19
+ let mockCopyToClipboard: Mock;
20
+ let mockGetChat: Mock;
21
+ let mockGetHistory: Mock;
22
+
23
+ beforeEach(() => {
24
+ vi.clearAllMocks();
25
+
26
+ mockCopyToClipboard = vi.mocked(copyToClipboard);
27
+ mockGetChat = vi.fn();
28
+ mockGetHistory = vi.fn();
29
+
30
+ mockContext = createMockCommandContext({
31
+ services: {
32
+ config: {
33
+ getGeminiClient: () => ({
34
+ getChat: mockGetChat,
35
+ }),
36
+ },
37
+ },
38
+ });
39
+
40
+ mockGetChat.mockReturnValue({
41
+ getHistory: mockGetHistory,
42
+ });
43
+ });
44
+
45
+ it('should return info message when no history is available', async () => {
46
+ if (!copyCommand.action) throw new Error('Command has no action');
47
+
48
+ mockGetChat.mockReturnValue(undefined);
49
+
50
+ const result = await copyCommand.action(mockContext, '');
51
+
52
+ expect(result).toEqual({
53
+ type: 'message',
54
+ messageType: 'info',
55
+ content: 'No output in history',
56
+ });
57
+
58
+ expect(mockCopyToClipboard).not.toHaveBeenCalled();
59
+ });
60
+
61
+ it('should return info message when history is empty', async () => {
62
+ if (!copyCommand.action) throw new Error('Command has no action');
63
+
64
+ mockGetHistory.mockReturnValue([]);
65
+
66
+ const result = await copyCommand.action(mockContext, '');
67
+
68
+ expect(result).toEqual({
69
+ type: 'message',
70
+ messageType: 'info',
71
+ content: 'No output in history',
72
+ });
73
+
74
+ expect(mockCopyToClipboard).not.toHaveBeenCalled();
75
+ });
76
+
77
+ it('should return info message when no AI messages are found in history', async () => {
78
+ if (!copyCommand.action) throw new Error('Command has no action');
79
+
80
+ const historyWithUserOnly = [
81
+ {
82
+ role: 'user',
83
+ parts: [{ text: 'Hello' }],
84
+ },
85
+ ];
86
+
87
+ mockGetHistory.mockReturnValue(historyWithUserOnly);
88
+
89
+ const result = await copyCommand.action(mockContext, '');
90
+
91
+ expect(result).toEqual({
92
+ type: 'message',
93
+ messageType: 'info',
94
+ content: 'No output in history',
95
+ });
96
+
97
+ expect(mockCopyToClipboard).not.toHaveBeenCalled();
98
+ });
99
+
100
+ it('should copy last AI message to clipboard successfully', async () => {
101
+ if (!copyCommand.action) throw new Error('Command has no action');
102
+
103
+ const historyWithAiMessage = [
104
+ {
105
+ role: 'user',
106
+ parts: [{ text: 'Hello' }],
107
+ },
108
+ {
109
+ role: 'model',
110
+ parts: [{ text: 'Hi there! How can I help you?' }],
111
+ },
112
+ ];
113
+
114
+ mockGetHistory.mockReturnValue(historyWithAiMessage);
115
+ mockCopyToClipboard.mockResolvedValue(undefined);
116
+
117
+ const result = await copyCommand.action(mockContext, '');
118
+
119
+ expect(result).toEqual({
120
+ type: 'message',
121
+ messageType: 'info',
122
+ content: 'Last output copied to the clipboard',
123
+ });
124
+
125
+ expect(mockCopyToClipboard).toHaveBeenCalledWith(
126
+ 'Hi there! How can I help you?',
127
+ );
128
+ });
129
+
130
+ it('should handle multiple text parts in AI message', async () => {
131
+ if (!copyCommand.action) throw new Error('Command has no action');
132
+
133
+ const historyWithMultipleParts = [
134
+ {
135
+ role: 'model',
136
+ parts: [{ text: 'Part 1: ' }, { text: 'Part 2: ' }, { text: 'Part 3' }],
137
+ },
138
+ ];
139
+
140
+ mockGetHistory.mockReturnValue(historyWithMultipleParts);
141
+ mockCopyToClipboard.mockResolvedValue(undefined);
142
+
143
+ const result = await copyCommand.action(mockContext, '');
144
+
145
+ expect(mockCopyToClipboard).toHaveBeenCalledWith('Part 1: Part 2: Part 3');
146
+ expect(result).toEqual({
147
+ type: 'message',
148
+ messageType: 'info',
149
+ content: 'Last output copied to the clipboard',
150
+ });
151
+ });
152
+
153
+ it('should filter out non-text parts', async () => {
154
+ if (!copyCommand.action) throw new Error('Command has no action');
155
+
156
+ const historyWithMixedParts = [
157
+ {
158
+ role: 'model',
159
+ parts: [
160
+ { text: 'Text part' },
161
+ { image: 'base64data' }, // Non-text part
162
+ { text: ' more text' },
163
+ ],
164
+ },
165
+ ];
166
+
167
+ mockGetHistory.mockReturnValue(historyWithMixedParts);
168
+ mockCopyToClipboard.mockResolvedValue(undefined);
169
+
170
+ const result = await copyCommand.action(mockContext, '');
171
+
172
+ expect(mockCopyToClipboard).toHaveBeenCalledWith('Text part more text');
173
+ expect(result).toEqual({
174
+ type: 'message',
175
+ messageType: 'info',
176
+ content: 'Last output copied to the clipboard',
177
+ });
178
+ });
179
+
180
+ it('should get the last AI message when multiple AI messages exist', async () => {
181
+ if (!copyCommand.action) throw new Error('Command has no action');
182
+
183
+ const historyWithMultipleAiMessages = [
184
+ {
185
+ role: 'model',
186
+ parts: [{ text: 'First AI response' }],
187
+ },
188
+ {
189
+ role: 'user',
190
+ parts: [{ text: 'User message' }],
191
+ },
192
+ {
193
+ role: 'model',
194
+ parts: [{ text: 'Second AI response' }],
195
+ },
196
+ ];
197
+
198
+ mockGetHistory.mockReturnValue(historyWithMultipleAiMessages);
199
+ mockCopyToClipboard.mockResolvedValue(undefined);
200
+
201
+ const result = await copyCommand.action(mockContext, '');
202
+
203
+ expect(mockCopyToClipboard).toHaveBeenCalledWith('Second AI response');
204
+ expect(result).toEqual({
205
+ type: 'message',
206
+ messageType: 'info',
207
+ content: 'Last output copied to the clipboard',
208
+ });
209
+ });
210
+
211
+ it('should handle clipboard copy error', async () => {
212
+ if (!copyCommand.action) throw new Error('Command has no action');
213
+
214
+ const historyWithAiMessage = [
215
+ {
216
+ role: 'model',
217
+ parts: [{ text: 'AI response' }],
218
+ },
219
+ ];
220
+
221
+ mockGetHistory.mockReturnValue(historyWithAiMessage);
222
+ const clipboardError = new Error('Clipboard access denied');
223
+ mockCopyToClipboard.mockRejectedValue(clipboardError);
224
+
225
+ const result = await copyCommand.action(mockContext, '');
226
+
227
+ expect(result).toEqual({
228
+ type: 'message',
229
+ messageType: 'error',
230
+ content: 'Failed to copy to the clipboard.',
231
+ });
232
+ });
233
+
234
+ it('should handle non-Error clipboard errors', async () => {
235
+ if (!copyCommand.action) throw new Error('Command has no action');
236
+
237
+ const historyWithAiMessage = [
238
+ {
239
+ role: 'model',
240
+ parts: [{ text: 'AI response' }],
241
+ },
242
+ ];
243
+
244
+ mockGetHistory.mockReturnValue(historyWithAiMessage);
245
+ mockCopyToClipboard.mockRejectedValue('String error');
246
+
247
+ const result = await copyCommand.action(mockContext, '');
248
+
249
+ expect(result).toEqual({
250
+ type: 'message',
251
+ messageType: 'error',
252
+ content: 'Failed to copy to the clipboard.',
253
+ });
254
+ });
255
+
256
+ it('should return info message when no text parts found in AI message', async () => {
257
+ if (!copyCommand.action) throw new Error('Command has no action');
258
+
259
+ const historyWithEmptyParts = [
260
+ {
261
+ role: 'model',
262
+ parts: [{ image: 'base64data' }], // No text parts
263
+ },
264
+ ];
265
+
266
+ mockGetHistory.mockReturnValue(historyWithEmptyParts);
267
+
268
+ const result = await copyCommand.action(mockContext, '');
269
+
270
+ expect(result).toEqual({
271
+ type: 'message',
272
+ messageType: 'info',
273
+ content: 'Last AI output contains no text to copy.',
274
+ });
275
+
276
+ expect(mockCopyToClipboard).not.toHaveBeenCalled();
277
+ });
278
+
279
+ it('should handle unavailable config service', async () => {
280
+ if (!copyCommand.action) throw new Error('Command has no action');
281
+
282
+ const nullConfigContext = createMockCommandContext({
283
+ services: { config: null },
284
+ });
285
+
286
+ const result = await copyCommand.action(nullConfigContext, '');
287
+
288
+ expect(result).toEqual({
289
+ type: 'message',
290
+ messageType: 'info',
291
+ content: 'No output in history',
292
+ });
293
+
294
+ expect(mockCopyToClipboard).not.toHaveBeenCalled();
295
+ });
296
+ });
projects/ui/qwen-code/packages/cli/src/ui/commands/copyCommand.ts ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { copyToClipboard } from '../utils/commandUtils.js';
8
+ import {
9
+ CommandKind,
10
+ SlashCommand,
11
+ SlashCommandActionReturn,
12
+ } from './types.js';
13
+
14
+ export const copyCommand: SlashCommand = {
15
+ name: 'copy',
16
+ description: 'Copy the last result or code snippet to clipboard',
17
+ kind: CommandKind.BUILT_IN,
18
+ action: async (context, _args): Promise<SlashCommandActionReturn | void> => {
19
+ const chat = await context.services.config?.getGeminiClient()?.getChat();
20
+ const history = chat?.getHistory();
21
+
22
+ // Get the last message from the AI (model role)
23
+ const lastAiMessage = history
24
+ ? history.filter((item) => item.role === 'model').pop()
25
+ : undefined;
26
+
27
+ if (!lastAiMessage) {
28
+ return {
29
+ type: 'message',
30
+ messageType: 'info',
31
+ content: 'No output in history',
32
+ };
33
+ }
34
+ // Extract text from the parts
35
+ const lastAiOutput = lastAiMessage.parts
36
+ ?.filter((part) => part.text)
37
+ .map((part) => part.text)
38
+ .join('');
39
+
40
+ if (lastAiOutput) {
41
+ try {
42
+ await copyToClipboard(lastAiOutput);
43
+
44
+ return {
45
+ type: 'message',
46
+ messageType: 'info',
47
+ content: 'Last output copied to the clipboard',
48
+ };
49
+ } catch (error) {
50
+ const message = error instanceof Error ? error.message : String(error);
51
+ console.debug(message);
52
+
53
+ return {
54
+ type: 'message',
55
+ messageType: 'error',
56
+ content: 'Failed to copy to the clipboard.',
57
+ };
58
+ }
59
+ } else {
60
+ return {
61
+ type: 'message',
62
+ messageType: 'info',
63
+ content: 'Last AI output contains no text to copy.',
64
+ };
65
+ }
66
+ },
67
+ };
projects/ui/qwen-code/packages/cli/src/ui/commands/corgiCommand.test.ts ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, beforeEach, vi } from 'vitest';
8
+ import { corgiCommand } from './corgiCommand.js';
9
+ import { type CommandContext } from './types.js';
10
+ import { createMockCommandContext } from '../../test-utils/mockCommandContext.js';
11
+
12
+ describe('corgiCommand', () => {
13
+ let mockContext: CommandContext;
14
+
15
+ beforeEach(() => {
16
+ mockContext = createMockCommandContext();
17
+ vi.spyOn(mockContext.ui, 'toggleCorgiMode');
18
+ });
19
+
20
+ it('should call the toggleCorgiMode function on the UI context', async () => {
21
+ if (!corgiCommand.action) {
22
+ throw new Error('The corgi command must have an action.');
23
+ }
24
+
25
+ await corgiCommand.action(mockContext, '');
26
+
27
+ expect(mockContext.ui.toggleCorgiMode).toHaveBeenCalledTimes(1);
28
+ });
29
+
30
+ it('should have the correct name and description', () => {
31
+ expect(corgiCommand.name).toBe('corgi');
32
+ expect(corgiCommand.description).toBe('Toggles corgi mode.');
33
+ });
34
+ });
projects/ui/qwen-code/packages/cli/src/utils/sandbox-macos-restrictive-closed.sb ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (version 1)
2
+
3
+ ;; deny everything by default
4
+ (deny default)
5
+
6
+ ;; allow reading files from anywhere on host
7
+ (allow file-read*)
8
+
9
+ ;; allow exec/fork (children inherit policy)
10
+ (allow process-exec)
11
+ (allow process-fork)
12
+
13
+ ;; allow signals to self, e.g. SIGPIPE on write to closed pipe
14
+ (allow signal (target self))
15
+
16
+ ;; allow read access to specific information about system
17
+ ;; from https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/common.sb;l=273-319;drc=7b3962fe2e5fc9e2ee58000dc8fbf3429d84d3bd
18
+ (allow sysctl-read
19
+ (sysctl-name "hw.activecpu")
20
+ (sysctl-name "hw.busfrequency_compat")
21
+ (sysctl-name "hw.byteorder")
22
+ (sysctl-name "hw.cacheconfig")
23
+ (sysctl-name "hw.cachelinesize_compat")
24
+ (sysctl-name "hw.cpufamily")
25
+ (sysctl-name "hw.cpufrequency_compat")
26
+ (sysctl-name "hw.cputype")
27
+ (sysctl-name "hw.l1dcachesize_compat")
28
+ (sysctl-name "hw.l1icachesize_compat")
29
+ (sysctl-name "hw.l2cachesize_compat")
30
+ (sysctl-name "hw.l3cachesize_compat")
31
+ (sysctl-name "hw.logicalcpu_max")
32
+ (sysctl-name "hw.machine")
33
+ (sysctl-name "hw.ncpu")
34
+ (sysctl-name "hw.nperflevels")
35
+ (sysctl-name "hw.optional.arm.FEAT_BF16")
36
+ (sysctl-name "hw.optional.arm.FEAT_DotProd")
37
+ (sysctl-name "hw.optional.arm.FEAT_FCMA")
38
+ (sysctl-name "hw.optional.arm.FEAT_FHM")
39
+ (sysctl-name "hw.optional.arm.FEAT_FP16")
40
+ (sysctl-name "hw.optional.arm.FEAT_I8MM")
41
+ (sysctl-name "hw.optional.arm.FEAT_JSCVT")
42
+ (sysctl-name "hw.optional.arm.FEAT_LSE")
43
+ (sysctl-name "hw.optional.arm.FEAT_RDM")
44
+ (sysctl-name "hw.optional.arm.FEAT_SHA512")
45
+ (sysctl-name "hw.optional.armv8_2_sha512")
46
+ (sysctl-name "hw.packages")
47
+ (sysctl-name "hw.pagesize_compat")
48
+ (sysctl-name "hw.physicalcpu_max")
49
+ (sysctl-name "hw.tbfrequency_compat")
50
+ (sysctl-name "hw.vectorunit")
51
+ (sysctl-name "kern.hostname")
52
+ (sysctl-name "kern.maxfilesperproc")
53
+ (sysctl-name "kern.osproductversion")
54
+ (sysctl-name "kern.osrelease")
55
+ (sysctl-name "kern.ostype")
56
+ (sysctl-name "kern.osvariant_status")
57
+ (sysctl-name "kern.osversion")
58
+ (sysctl-name "kern.secure_kernel")
59
+ (sysctl-name "kern.usrstack64")
60
+ (sysctl-name "kern.version")
61
+ (sysctl-name "sysctl.proc_cputype")
62
+ (sysctl-name-prefix "hw.perflevel")
63
+ )
64
+
65
+ ;; allow writes to specific paths
66
+ (allow file-write*
67
+ (subpath (param "TARGET_DIR"))
68
+ (subpath (param "TMP_DIR"))
69
+ (subpath (param "CACHE_DIR"))
70
+ (subpath (string-append (param "HOME_DIR") "/.qwen"))
71
+ (subpath (string-append (param "HOME_DIR") "/.npm"))
72
+ (subpath (string-append (param "HOME_DIR") "/.cache"))
73
+ (subpath (string-append (param "HOME_DIR") "/.gitconfig"))
74
+ ;; Allow writes to included directories from --include-directories
75
+ (subpath (param "INCLUDE_DIR_0"))
76
+ (subpath (param "INCLUDE_DIR_1"))
77
+ (subpath (param "INCLUDE_DIR_2"))
78
+ (subpath (param "INCLUDE_DIR_3"))
79
+ (subpath (param "INCLUDE_DIR_4"))
80
+ (literal "/dev/stdout")
81
+ (literal "/dev/stderr")
82
+ (literal "/dev/null")
83
+ )
84
+
85
+ ;; allow communication with sysmond for process listing (e.g. for pgrep)
86
+ (allow mach-lookup (global-name "com.apple.sysmond"))
87
+
88
+ ;; enable terminal access required by ink
89
+ ;; fixes setRawMode EPERM failure (at node:tty:81:24)
90
+ (allow file-ioctl (regex #"^/dev/tty.*"))
91
+
92
+ ;; allow inbound network traffic on debugger port
93
+ (allow network-inbound (local ip "localhost:9229"))
projects/ui/qwen-code/packages/cli/src/utils/sandbox-macos-restrictive-open.sb ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (version 1)
2
+
3
+ ;; deny everything by default
4
+ (deny default)
5
+
6
+ ;; allow reading files from anywhere on host
7
+ (allow file-read*)
8
+
9
+ ;; allow exec/fork (children inherit policy)
10
+ (allow process-exec)
11
+ (allow process-fork)
12
+
13
+ ;; allow signals to self, e.g. SIGPIPE on write to closed pipe
14
+ (allow signal (target self))
15
+
16
+ ;; allow read access to specific information about system
17
+ ;; from https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/common.sb;l=273-319;drc=7b3962fe2e5fc9e2ee58000dc8fbf3429d84d3bd
18
+ (allow sysctl-read
19
+ (sysctl-name "hw.activecpu")
20
+ (sysctl-name "hw.busfrequency_compat")
21
+ (sysctl-name "hw.byteorder")
22
+ (sysctl-name "hw.cacheconfig")
23
+ (sysctl-name "hw.cachelinesize_compat")
24
+ (sysctl-name "hw.cpufamily")
25
+ (sysctl-name "hw.cpufrequency_compat")
26
+ (sysctl-name "hw.cputype")
27
+ (sysctl-name "hw.l1dcachesize_compat")
28
+ (sysctl-name "hw.l1icachesize_compat")
29
+ (sysctl-name "hw.l2cachesize_compat")
30
+ (sysctl-name "hw.l3cachesize_compat")
31
+ (sysctl-name "hw.logicalcpu_max")
32
+ (sysctl-name "hw.machine")
33
+ (sysctl-name "hw.ncpu")
34
+ (sysctl-name "hw.nperflevels")
35
+ (sysctl-name "hw.optional.arm.FEAT_BF16")
36
+ (sysctl-name "hw.optional.arm.FEAT_DotProd")
37
+ (sysctl-name "hw.optional.arm.FEAT_FCMA")
38
+ (sysctl-name "hw.optional.arm.FEAT_FHM")
39
+ (sysctl-name "hw.optional.arm.FEAT_FP16")
40
+ (sysctl-name "hw.optional.arm.FEAT_I8MM")
41
+ (sysctl-name "hw.optional.arm.FEAT_JSCVT")
42
+ (sysctl-name "hw.optional.arm.FEAT_LSE")
43
+ (sysctl-name "hw.optional.arm.FEAT_RDM")
44
+ (sysctl-name "hw.optional.arm.FEAT_SHA512")
45
+ (sysctl-name "hw.optional.armv8_2_sha512")
46
+ (sysctl-name "hw.packages")
47
+ (sysctl-name "hw.pagesize_compat")
48
+ (sysctl-name "hw.physicalcpu_max")
49
+ (sysctl-name "hw.tbfrequency_compat")
50
+ (sysctl-name "hw.vectorunit")
51
+ (sysctl-name "kern.hostname")
52
+ (sysctl-name "kern.maxfilesperproc")
53
+ (sysctl-name "kern.osproductversion")
54
+ (sysctl-name "kern.osrelease")
55
+ (sysctl-name "kern.ostype")
56
+ (sysctl-name "kern.osvariant_status")
57
+ (sysctl-name "kern.osversion")
58
+ (sysctl-name "kern.secure_kernel")
59
+ (sysctl-name "kern.usrstack64")
60
+ (sysctl-name "kern.version")
61
+ (sysctl-name "sysctl.proc_cputype")
62
+ (sysctl-name-prefix "hw.perflevel")
63
+ )
64
+
65
+ ;; allow writes to specific paths
66
+ (allow file-write*
67
+ (subpath (param "TARGET_DIR"))
68
+ (subpath (param "TMP_DIR"))
69
+ (subpath (param "CACHE_DIR"))
70
+ (subpath (string-append (param "HOME_DIR") "/.qwen"))
71
+ (subpath (string-append (param "HOME_DIR") "/.npm"))
72
+ (subpath (string-append (param "HOME_DIR") "/.cache"))
73
+ (subpath (string-append (param "HOME_DIR") "/.gitconfig"))
74
+ ;; Allow writes to included directories from --include-directories
75
+ (subpath (param "INCLUDE_DIR_0"))
76
+ (subpath (param "INCLUDE_DIR_1"))
77
+ (subpath (param "INCLUDE_DIR_2"))
78
+ (subpath (param "INCLUDE_DIR_3"))
79
+ (subpath (param "INCLUDE_DIR_4"))
80
+ (literal "/dev/stdout")
81
+ (literal "/dev/stderr")
82
+ (literal "/dev/null")
83
+ )
84
+
85
+ ;; allow communication with sysmond for process listing (e.g. for pgrep)
86
+ (allow mach-lookup (global-name "com.apple.sysmond"))
87
+
88
+ ;; enable terminal access required by ink
89
+ ;; fixes setRawMode EPERM failure (at node:tty:81:24)
90
+ (allow file-ioctl (regex #"^/dev/tty.*"))
91
+
92
+ ;; allow inbound network traffic on debugger port
93
+ (allow network-inbound (local ip "localhost:9229"))
94
+
95
+ ;; allow all outbound network traffic
96
+ (allow network-outbound)
projects/ui/qwen-code/packages/cli/src/utils/sandbox-macos-restrictive-proxied.sb ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (version 1)
2
+
3
+ ;; deny everything by default
4
+ (deny default)
5
+
6
+ ;; allow reading files from anywhere on host
7
+ (allow file-read*)
8
+
9
+ ;; allow exec/fork (children inherit policy)
10
+ (allow process-exec)
11
+ (allow process-fork)
12
+
13
+ ;; allow signals to self, e.g. SIGPIPE on write to closed pipe
14
+ (allow signal (target self))
15
+
16
+ ;; allow read access to specific information about system
17
+ ;; from https://source.chromium.org/chromium/chromium/src/+/main:sandbox/policy/mac/common.sb;l=273-319;drc=7b3962fe2e5fc9e2ee58000dc8fbf3429d84d3bd
18
+ (allow sysctl-read
19
+ (sysctl-name "hw.activecpu")
20
+ (sysctl-name "hw.busfrequency_compat")
21
+ (sysctl-name "hw.byteorder")
22
+ (sysctl-name "hw.cacheconfig")
23
+ (sysctl-name "hw.cachelinesize_compat")
24
+ (sysctl-name "hw.cpufamily")
25
+ (sysctl-name "hw.cpufrequency_compat")
26
+ (sysctl-name "hw.cputype")
27
+ (sysctl-name "hw.l1dcachesize_compat")
28
+ (sysctl-name "hw.l1icachesize_compat")
29
+ (sysctl-name "hw.l2cachesize_compat")
30
+ (sysctl-name "hw.l3cachesize_compat")
31
+ (sysctl-name "hw.logicalcpu_max")
32
+ (sysctl-name "hw.machine")
33
+ (sysctl-name "hw.ncpu")
34
+ (sysctl-name "hw.nperflevels")
35
+ (sysctl-name "hw.optional.arm.FEAT_BF16")
36
+ (sysctl-name "hw.optional.arm.FEAT_DotProd")
37
+ (sysctl-name "hw.optional.arm.FEAT_FCMA")
38
+ (sysctl-name "hw.optional.arm.FEAT_FHM")
39
+ (sysctl-name "hw.optional.arm.FEAT_FP16")
40
+ (sysctl-name "hw.optional.arm.FEAT_I8MM")
41
+ (sysctl-name "hw.optional.arm.FEAT_JSCVT")
42
+ (sysctl-name "hw.optional.arm.FEAT_LSE")
43
+ (sysctl-name "hw.optional.arm.FEAT_RDM")
44
+ (sysctl-name "hw.optional.arm.FEAT_SHA512")
45
+ (sysctl-name "hw.optional.armv8_2_sha512")
46
+ (sysctl-name "hw.packages")
47
+ (sysctl-name "hw.pagesize_compat")
48
+ (sysctl-name "hw.physicalcpu_max")
49
+ (sysctl-name "hw.tbfrequency_compat")
50
+ (sysctl-name "hw.vectorunit")
51
+ (sysctl-name "kern.hostname")
52
+ (sysctl-name "kern.maxfilesperproc")
53
+ (sysctl-name "kern.osproductversion")
54
+ (sysctl-name "kern.osrelease")
55
+ (sysctl-name "kern.ostype")
56
+ (sysctl-name "kern.osvariant_status")
57
+ (sysctl-name "kern.osversion")
58
+ (sysctl-name "kern.secure_kernel")
59
+ (sysctl-name "kern.usrstack64")
60
+ (sysctl-name "kern.version")
61
+ (sysctl-name "sysctl.proc_cputype")
62
+ (sysctl-name-prefix "hw.perflevel")
63
+ )
64
+
65
+ ;; allow writes to specific paths
66
+ (allow file-write*
67
+ (subpath (param "TARGET_DIR"))
68
+ (subpath (param "TMP_DIR"))
69
+ (subpath (param "CACHE_DIR"))
70
+ (subpath (string-append (param "HOME_DIR") "/.qwen"))
71
+ (subpath (string-append (param "HOME_DIR") "/.npm"))
72
+ (subpath (string-append (param "HOME_DIR") "/.cache"))
73
+ (subpath (string-append (param "HOME_DIR") "/.gitconfig"))
74
+ ;; Allow writes to included directories from --include-directories
75
+ (subpath (param "INCLUDE_DIR_0"))
76
+ (subpath (param "INCLUDE_DIR_1"))
77
+ (subpath (param "INCLUDE_DIR_2"))
78
+ (subpath (param "INCLUDE_DIR_3"))
79
+ (subpath (param "INCLUDE_DIR_4"))
80
+ (literal "/dev/stdout")
81
+ (literal "/dev/stderr")
82
+ (literal "/dev/null")
83
+ )
84
+
85
+ ;; allow communication with sysmond for process listing (e.g. for pgrep)
86
+ (allow mach-lookup (global-name "com.apple.sysmond"))
87
+
88
+ ;; enable terminal access required by ink
89
+ ;; fixes setRawMode EPERM failure (at node:tty:81:24)
90
+ (allow file-ioctl (regex #"^/dev/tty.*"))
91
+
92
+ ;; allow inbound network traffic on debugger port
93
+ (allow network-inbound (local ip "localhost:9229"))
94
+
95
+ ;; allow outbound network traffic through proxy on localhost:8877
96
+ ;; set `GEMINI_SANDBOX_PROXY_COMMAND=<command>` to run proxy alongside sandbox
97
+ ;; proxy must listen on :::8877 (see docs/examples/proxy-script.md)
98
+ (allow network-outbound (remote tcp "localhost:8877"))
projects/ui/qwen-code/packages/cli/src/utils/sandbox.ts ADDED
@@ -0,0 +1,962 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { exec, execSync, spawn, type ChildProcess } from 'node:child_process';
8
+ import os from 'node:os';
9
+ import path from 'node:path';
10
+ import fs from 'node:fs';
11
+ import { readFile } from 'node:fs/promises';
12
+ import { quote, parse } from 'shell-quote';
13
+ import {
14
+ USER_SETTINGS_DIR,
15
+ SETTINGS_DIRECTORY_NAME,
16
+ } from '../config/settings.js';
17
+ import { promisify } from 'util';
18
+ import { Config, SandboxConfig } from '@qwen-code/qwen-code-core';
19
+ import { ConsolePatcher } from '../ui/utils/ConsolePatcher.js';
20
+
21
+ const execAsync = promisify(exec);
22
+
23
+ function getContainerPath(hostPath: string): string {
24
+ if (os.platform() !== 'win32') {
25
+ return hostPath;
26
+ }
27
+ const withForwardSlashes = hostPath.replace(/\\/g, '/');
28
+ const match = withForwardSlashes.match(/^([A-Z]):\/(.*)/i);
29
+ if (match) {
30
+ return `/${match[1].toLowerCase()}/${match[2]}`;
31
+ }
32
+ return hostPath;
33
+ }
34
+
35
+ const LOCAL_DEV_SANDBOX_IMAGE_NAME = 'qwen-code-sandbox';
36
+ const SANDBOX_NETWORK_NAME = 'qwen-code-sandbox';
37
+ const SANDBOX_PROXY_NAME = 'qwen-code-sandbox-proxy';
38
+ const BUILTIN_SEATBELT_PROFILES = [
39
+ 'permissive-open',
40
+ 'permissive-closed',
41
+ 'permissive-proxied',
42
+ 'restrictive-open',
43
+ 'restrictive-closed',
44
+ 'restrictive-proxied',
45
+ ];
46
+
47
+ /**
48
+ * Determines whether the sandbox container should be run with the current user's UID and GID.
49
+ * This is often necessary on Linux systems (especially Debian/Ubuntu based) when using
50
+ * rootful Docker without userns-remap configured, to avoid permission issues with
51
+ * mounted volumes.
52
+ *
53
+ * The behavior is controlled by the `SANDBOX_SET_UID_GID` environment variable:
54
+ * - If `SANDBOX_SET_UID_GID` is "1" or "true", this function returns `true`.
55
+ * - If `SANDBOX_SET_UID_GID` is "0" or "false", this function returns `false`.
56
+ * - If `SANDBOX_SET_UID_GID` is not set:
57
+ * - On Debian/Ubuntu Linux, it defaults to `true`.
58
+ * - On other OSes, or if OS detection fails, it defaults to `false`.
59
+ *
60
+ * For more context on running Docker containers as non-root, see:
61
+ * https://medium.com/redbubble/running-a-docker-container-as-a-non-root-user-7d2e00f8ee15
62
+ *
63
+ * @returns {Promise<boolean>} A promise that resolves to true if the current user's UID/GID should be used, false otherwise.
64
+ */
65
+ async function shouldUseCurrentUserInSandbox(): Promise<boolean> {
66
+ const envVar = process.env['SANDBOX_SET_UID_GID']?.toLowerCase().trim();
67
+
68
+ if (envVar === '1' || envVar === 'true') {
69
+ return true;
70
+ }
71
+ if (envVar === '0' || envVar === 'false') {
72
+ return false;
73
+ }
74
+
75
+ // If environment variable is not explicitly set, check for Debian/Ubuntu Linux
76
+ if (os.platform() === 'linux') {
77
+ try {
78
+ const osReleaseContent = await readFile('/etc/os-release', 'utf8');
79
+ if (
80
+ osReleaseContent.includes('ID=debian') ||
81
+ osReleaseContent.includes('ID=ubuntu') ||
82
+ osReleaseContent.match(/^ID_LIKE=.*debian.*/m) || // Covers derivatives
83
+ osReleaseContent.match(/^ID_LIKE=.*ubuntu.*/m) // Covers derivatives
84
+ ) {
85
+ // note here and below we use console.error for informational messages on stderr
86
+ console.error(
87
+ 'INFO: Defaulting to use current user UID/GID for Debian/Ubuntu-based Linux.',
88
+ );
89
+ return true;
90
+ }
91
+ } catch (_err) {
92
+ // Silently ignore if /etc/os-release is not found or unreadable.
93
+ // The default (false) will be applied in this case.
94
+ console.warn(
95
+ 'Warning: Could not read /etc/os-release to auto-detect Debian/Ubuntu for UID/GID default.',
96
+ );
97
+ }
98
+ }
99
+ return false; // Default to false if no other condition is met
100
+ }
101
+
102
+ // docker does not allow container names to contain ':' or '/', so we
103
+ // parse those out to shorten the name
104
+ function parseImageName(image: string): string {
105
+ const [fullName, tag] = image.split(':');
106
+ const name = fullName.split('/').at(-1) ?? 'unknown-image';
107
+ return tag ? `${name}-${tag}` : name;
108
+ }
109
+
110
+ function ports(): string[] {
111
+ return (process.env['SANDBOX_PORTS'] ?? '')
112
+ .split(',')
113
+ .filter((p) => p.trim())
114
+ .map((p) => p.trim());
115
+ }
116
+
117
+ function entrypoint(workdir: string): string[] {
118
+ const isWindows = os.platform() === 'win32';
119
+ const containerWorkdir = getContainerPath(workdir);
120
+ const shellCmds = [];
121
+ const pathSeparator = isWindows ? ';' : ':';
122
+
123
+ let pathSuffix = '';
124
+ if (process.env['PATH']) {
125
+ const paths = process.env['PATH'].split(pathSeparator);
126
+ for (const p of paths) {
127
+ const containerPath = getContainerPath(p);
128
+ if (
129
+ containerPath.toLowerCase().startsWith(containerWorkdir.toLowerCase())
130
+ ) {
131
+ pathSuffix += `:${containerPath}`;
132
+ }
133
+ }
134
+ }
135
+ if (pathSuffix) {
136
+ shellCmds.push(`export PATH="$PATH${pathSuffix}";`);
137
+ }
138
+
139
+ let pythonPathSuffix = '';
140
+ if (process.env['PYTHONPATH']) {
141
+ const paths = process.env['PYTHONPATH'].split(pathSeparator);
142
+ for (const p of paths) {
143
+ const containerPath = getContainerPath(p);
144
+ if (
145
+ containerPath.toLowerCase().startsWith(containerWorkdir.toLowerCase())
146
+ ) {
147
+ pythonPathSuffix += `:${containerPath}`;
148
+ }
149
+ }
150
+ }
151
+ if (pythonPathSuffix) {
152
+ shellCmds.push(`export PYTHONPATH="$PYTHONPATH${pythonPathSuffix}";`);
153
+ }
154
+
155
+ const projectSandboxBashrc = path.join(
156
+ SETTINGS_DIRECTORY_NAME,
157
+ 'sandbox.bashrc',
158
+ );
159
+ if (fs.existsSync(projectSandboxBashrc)) {
160
+ shellCmds.push(`source ${getContainerPath(projectSandboxBashrc)};`);
161
+ }
162
+
163
+ ports().forEach((p) =>
164
+ shellCmds.push(
165
+ `socat TCP4-LISTEN:${p},bind=$(hostname -i),fork,reuseaddr TCP4:127.0.0.1:${p} 2> /dev/null &`,
166
+ ),
167
+ );
168
+
169
+ const cliArgs = process.argv.slice(2).map((arg) => quote([arg]));
170
+ const cliCmd =
171
+ process.env['NODE_ENV'] === 'development'
172
+ ? process.env['DEBUG']
173
+ ? 'npm run debug --'
174
+ : 'npm rebuild && npm run start --'
175
+ : process.env['DEBUG']
176
+ ? `node --inspect-brk=0.0.0.0:${process.env['DEBUG_PORT'] || '9229'} $(which qwen)`
177
+ : 'qwen';
178
+
179
+ const args = [...shellCmds, cliCmd, ...cliArgs];
180
+
181
+ return ['bash', '-c', args.join(' ')];
182
+ }
183
+
184
+ export async function start_sandbox(
185
+ config: SandboxConfig,
186
+ nodeArgs: string[] = [],
187
+ cliConfig?: Config,
188
+ ) {
189
+ const patcher = new ConsolePatcher({
190
+ debugMode: cliConfig?.getDebugMode() || !!process.env['DEBUG'],
191
+ stderr: true,
192
+ });
193
+ patcher.patch();
194
+
195
+ try {
196
+ if (config.command === 'sandbox-exec') {
197
+ // disallow BUILD_SANDBOX
198
+ if (process.env['BUILD_SANDBOX']) {
199
+ console.error('ERROR: cannot BUILD_SANDBOX when using macOS Seatbelt');
200
+ process.exit(1);
201
+ }
202
+ const profile = (process.env['SEATBELT_PROFILE'] ??= 'permissive-open');
203
+ let profileFile = new URL(`sandbox-macos-${profile}.sb`, import.meta.url)
204
+ .pathname;
205
+ // if profile name is not recognized, then look for file under project settings directory
206
+ if (!BUILTIN_SEATBELT_PROFILES.includes(profile)) {
207
+ profileFile = path.join(
208
+ SETTINGS_DIRECTORY_NAME,
209
+ `sandbox-macos-${profile}.sb`,
210
+ );
211
+ }
212
+ if (!fs.existsSync(profileFile)) {
213
+ console.error(
214
+ `ERROR: missing macos seatbelt profile file '${profileFile}'`,
215
+ );
216
+ process.exit(1);
217
+ }
218
+ // Log on STDERR so it doesn't clutter the output on STDOUT
219
+ console.error(`using macos seatbelt (profile: ${profile}) ...`);
220
+ // if DEBUG is set, convert to --inspect-brk in NODE_OPTIONS
221
+ const nodeOptions = [
222
+ ...(process.env['DEBUG'] ? ['--inspect-brk'] : []),
223
+ ...nodeArgs,
224
+ ].join(' ');
225
+
226
+ const args = [
227
+ '-D',
228
+ `TARGET_DIR=${fs.realpathSync(process.cwd())}`,
229
+ '-D',
230
+ `TMP_DIR=${fs.realpathSync(os.tmpdir())}`,
231
+ '-D',
232
+ `HOME_DIR=${fs.realpathSync(os.homedir())}`,
233
+ '-D',
234
+ `CACHE_DIR=${fs.realpathSync(execSync(`getconf DARWIN_USER_CACHE_DIR`).toString().trim())}`,
235
+ ];
236
+
237
+ // Add included directories from the workspace context
238
+ // Always add 5 INCLUDE_DIR parameters to ensure .sb files can reference them
239
+ const MAX_INCLUDE_DIRS = 5;
240
+ const targetDir = fs.realpathSync(cliConfig?.getTargetDir() || '');
241
+ const includedDirs: string[] = [];
242
+
243
+ if (cliConfig) {
244
+ const workspaceContext = cliConfig.getWorkspaceContext();
245
+ const directories = workspaceContext.getDirectories();
246
+
247
+ // Filter out TARGET_DIR
248
+ for (const dir of directories) {
249
+ const realDir = fs.realpathSync(dir);
250
+ if (realDir !== targetDir) {
251
+ includedDirs.push(realDir);
252
+ }
253
+ }
254
+ }
255
+
256
+ for (let i = 0; i < MAX_INCLUDE_DIRS; i++) {
257
+ let dirPath = '/dev/null'; // Default to a safe path that won't cause issues
258
+
259
+ if (i < includedDirs.length) {
260
+ dirPath = includedDirs[i];
261
+ }
262
+
263
+ args.push('-D', `INCLUDE_DIR_${i}=${dirPath}`);
264
+ }
265
+
266
+ args.push(
267
+ '-f',
268
+ profileFile,
269
+ 'sh',
270
+ '-c',
271
+ [
272
+ `SANDBOX=sandbox-exec`,
273
+ `NODE_OPTIONS="${nodeOptions}"`,
274
+ ...process.argv.map((arg) => quote([arg])),
275
+ ].join(' '),
276
+ );
277
+ // start and set up proxy if GEMINI_SANDBOX_PROXY_COMMAND is set
278
+ const proxyCommand = process.env['GEMINI_SANDBOX_PROXY_COMMAND'];
279
+ let proxyProcess: ChildProcess | undefined = undefined;
280
+ let sandboxProcess: ChildProcess | undefined = undefined;
281
+ const sandboxEnv = { ...process.env };
282
+ if (proxyCommand) {
283
+ const proxy =
284
+ process.env['HTTPS_PROXY'] ||
285
+ process.env['https_proxy'] ||
286
+ process.env['HTTP_PROXY'] ||
287
+ process.env['http_proxy'] ||
288
+ 'http://localhost:8877';
289
+ sandboxEnv['HTTPS_PROXY'] = proxy;
290
+ sandboxEnv['https_proxy'] = proxy; // lower-case can be required, e.g. for curl
291
+ sandboxEnv['HTTP_PROXY'] = proxy;
292
+ sandboxEnv['http_proxy'] = proxy;
293
+ const noProxy = process.env['NO_PROXY'] || process.env['no_proxy'];
294
+ if (noProxy) {
295
+ sandboxEnv['NO_PROXY'] = noProxy;
296
+ sandboxEnv['no_proxy'] = noProxy;
297
+ }
298
+ proxyProcess = spawn(proxyCommand, {
299
+ stdio: ['ignore', 'pipe', 'pipe'],
300
+ shell: true,
301
+ detached: true,
302
+ });
303
+ // install handlers to stop proxy on exit/signal
304
+ const stopProxy = () => {
305
+ console.log('stopping proxy ...');
306
+ if (proxyProcess?.pid) {
307
+ process.kill(-proxyProcess.pid, 'SIGTERM');
308
+ }
309
+ };
310
+ process.on('exit', stopProxy);
311
+ process.on('SIGINT', stopProxy);
312
+ process.on('SIGTERM', stopProxy);
313
+
314
+ // commented out as it disrupts ink rendering
315
+ // proxyProcess.stdout?.on('data', (data) => {
316
+ // console.info(data.toString());
317
+ // });
318
+ proxyProcess.stderr?.on('data', (data) => {
319
+ console.error(data.toString());
320
+ });
321
+ proxyProcess.on('close', (code, signal) => {
322
+ console.error(
323
+ `ERROR: proxy command '${proxyCommand}' exited with code ${code}, signal ${signal}`,
324
+ );
325
+ if (sandboxProcess?.pid) {
326
+ process.kill(-sandboxProcess.pid, 'SIGTERM');
327
+ }
328
+ process.exit(1);
329
+ });
330
+ console.log('waiting for proxy to start ...');
331
+ await execAsync(
332
+ `until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`,
333
+ );
334
+ }
335
+ // spawn child and let it inherit stdio
336
+ sandboxProcess = spawn(config.command, args, {
337
+ stdio: 'inherit',
338
+ });
339
+ await new Promise((resolve) => sandboxProcess?.on('close', resolve));
340
+ return;
341
+ }
342
+
343
+ console.error(`hopping into sandbox (command: ${config.command}) ...`);
344
+
345
+ // determine full path for gemini-cli to distinguish linked vs installed setting
346
+ const gcPath = fs.realpathSync(process.argv[1]);
347
+
348
+ const projectSandboxDockerfile = path.join(
349
+ SETTINGS_DIRECTORY_NAME,
350
+ 'sandbox.Dockerfile',
351
+ );
352
+ const isCustomProjectSandbox = fs.existsSync(projectSandboxDockerfile);
353
+
354
+ const image = config.image;
355
+ const workdir = path.resolve(process.cwd());
356
+ const containerWorkdir = getContainerPath(workdir);
357
+
358
+ // if BUILD_SANDBOX is set, then call scripts/build_sandbox.js under gemini-cli repo
359
+ //
360
+ // note this can only be done with binary linked from gemini-cli repo
361
+ if (process.env['BUILD_SANDBOX']) {
362
+ if (!gcPath.includes('gemini-cli/packages/')) {
363
+ console.error(
364
+ 'ERROR: cannot build sandbox using installed gemini binary; ' +
365
+ 'run `npm link ./packages/cli` under gemini-cli repo to switch to linked binary.',
366
+ );
367
+ process.exit(1);
368
+ } else {
369
+ console.error('building sandbox ...');
370
+ const gcRoot = gcPath.split('/packages/')[0];
371
+ // if project folder has sandbox.Dockerfile under project settings folder, use that
372
+ let buildArgs = '';
373
+ const projectSandboxDockerfile = path.join(
374
+ SETTINGS_DIRECTORY_NAME,
375
+ 'sandbox.Dockerfile',
376
+ );
377
+ if (isCustomProjectSandbox) {
378
+ console.error(`using ${projectSandboxDockerfile} for sandbox`);
379
+ buildArgs += `-f ${path.resolve(projectSandboxDockerfile)} -i ${image}`;
380
+ }
381
+ execSync(
382
+ `cd ${gcRoot} && node scripts/build_sandbox.js -s ${buildArgs}`,
383
+ {
384
+ stdio: 'inherit',
385
+ env: {
386
+ ...process.env,
387
+ GEMINI_SANDBOX: config.command, // in case sandbox is enabled via flags (see config.ts under cli package)
388
+ },
389
+ },
390
+ );
391
+ }
392
+ }
393
+
394
+ // stop if image is missing
395
+ if (!(await ensureSandboxImageIsPresent(config.command, image))) {
396
+ const remedy =
397
+ image === LOCAL_DEV_SANDBOX_IMAGE_NAME
398
+ ? 'Try running `npm run build:all` or `npm run build:sandbox` under the gemini-cli repo to build it locally, or check the image name and your network connection.'
399
+ : 'Please check the image name, your network connection, or notify gemini-cli-dev@google.com if the issue persists.';
400
+ console.error(
401
+ `ERROR: Sandbox image '${image}' is missing or could not be pulled. ${remedy}`,
402
+ );
403
+ process.exit(1);
404
+ }
405
+
406
+ // use interactive mode and auto-remove container on exit
407
+ // run init binary inside container to forward signals & reap zombies
408
+ const args = ['run', '-i', '--rm', '--init', '--workdir', containerWorkdir];
409
+
410
+ // add custom flags from SANDBOX_FLAGS
411
+ if (process.env['SANDBOX_FLAGS']) {
412
+ const flags = parse(process.env['SANDBOX_FLAGS'], process.env).filter(
413
+ (f): f is string => typeof f === 'string',
414
+ );
415
+ args.push(...flags);
416
+ }
417
+
418
+ // add TTY only if stdin is TTY as well, i.e. for piped input don't init TTY in container
419
+ if (process.stdin.isTTY) {
420
+ args.push('-t');
421
+ }
422
+
423
+ // mount current directory as working directory in sandbox (set via --workdir)
424
+ args.push('--volume', `${workdir}:${containerWorkdir}`);
425
+
426
+ // mount user settings directory inside container, after creating if missing
427
+ // note user/home changes inside sandbox and we mount at BOTH paths for consistency
428
+ const userSettingsDirOnHost = USER_SETTINGS_DIR;
429
+ const userSettingsDirInSandbox = getContainerPath(
430
+ `/home/node/${SETTINGS_DIRECTORY_NAME}`,
431
+ );
432
+ if (!fs.existsSync(userSettingsDirOnHost)) {
433
+ fs.mkdirSync(userSettingsDirOnHost);
434
+ }
435
+ args.push(
436
+ '--volume',
437
+ `${userSettingsDirOnHost}:${userSettingsDirInSandbox}`,
438
+ );
439
+ if (userSettingsDirInSandbox !== userSettingsDirOnHost) {
440
+ args.push(
441
+ '--volume',
442
+ `${userSettingsDirOnHost}:${getContainerPath(userSettingsDirOnHost)}`,
443
+ );
444
+ }
445
+
446
+ // mount os.tmpdir() as os.tmpdir() inside container
447
+ args.push('--volume', `${os.tmpdir()}:${getContainerPath(os.tmpdir())}`);
448
+
449
+ // mount gcloud config directory if it exists
450
+ const gcloudConfigDir = path.join(os.homedir(), '.config', 'gcloud');
451
+ if (fs.existsSync(gcloudConfigDir)) {
452
+ args.push(
453
+ '--volume',
454
+ `${gcloudConfigDir}:${getContainerPath(gcloudConfigDir)}:ro`,
455
+ );
456
+ }
457
+
458
+ // mount ADC file if GOOGLE_APPLICATION_CREDENTIALS is set
459
+ if (process.env['GOOGLE_APPLICATION_CREDENTIALS']) {
460
+ const adcFile = process.env['GOOGLE_APPLICATION_CREDENTIALS'];
461
+ if (fs.existsSync(adcFile)) {
462
+ args.push('--volume', `${adcFile}:${getContainerPath(adcFile)}:ro`);
463
+ args.push(
464
+ '--env',
465
+ `GOOGLE_APPLICATION_CREDENTIALS=${getContainerPath(adcFile)}`,
466
+ );
467
+ }
468
+ }
469
+
470
+ // mount paths listed in SANDBOX_MOUNTS
471
+ if (process.env['SANDBOX_MOUNTS']) {
472
+ for (let mount of process.env['SANDBOX_MOUNTS'].split(',')) {
473
+ if (mount.trim()) {
474
+ // parse mount as from:to:opts
475
+ let [from, to, opts] = mount.trim().split(':');
476
+ to = to || from; // default to mount at same path inside container
477
+ opts = opts || 'ro'; // default to read-only
478
+ mount = `${from}:${to}:${opts}`;
479
+ // check that from path is absolute
480
+ if (!path.isAbsolute(from)) {
481
+ console.error(
482
+ `ERROR: path '${from}' listed in SANDBOX_MOUNTS must be absolute`,
483
+ );
484
+ process.exit(1);
485
+ }
486
+ // check that from path exists on host
487
+ if (!fs.existsSync(from)) {
488
+ console.error(
489
+ `ERROR: missing mount path '${from}' listed in SANDBOX_MOUNTS`,
490
+ );
491
+ process.exit(1);
492
+ }
493
+ console.error(`SANDBOX_MOUNTS: ${from} -> ${to} (${opts})`);
494
+ args.push('--volume', mount);
495
+ }
496
+ }
497
+ }
498
+
499
+ // expose env-specified ports on the sandbox
500
+ ports().forEach((p) => args.push('--publish', `${p}:${p}`));
501
+
502
+ // if DEBUG is set, expose debugging port
503
+ if (process.env['DEBUG']) {
504
+ const debugPort = process.env['DEBUG_PORT'] || '9229';
505
+ args.push(`--publish`, `${debugPort}:${debugPort}`);
506
+ }
507
+
508
+ // copy proxy environment variables, replacing localhost with SANDBOX_PROXY_NAME
509
+ // copy as both upper-case and lower-case as is required by some utilities
510
+ // GEMINI_SANDBOX_PROXY_COMMAND implies HTTPS_PROXY unless HTTP_PROXY is set
511
+ const proxyCommand = process.env['GEMINI_SANDBOX_PROXY_COMMAND'];
512
+
513
+ if (proxyCommand) {
514
+ let proxy =
515
+ process.env['HTTPS_PROXY'] ||
516
+ process.env['https_proxy'] ||
517
+ process.env['HTTP_PROXY'] ||
518
+ process.env['http_proxy'] ||
519
+ 'http://localhost:8877';
520
+ proxy = proxy.replace('localhost', SANDBOX_PROXY_NAME);
521
+ if (proxy) {
522
+ args.push('--env', `HTTPS_PROXY=${proxy}`);
523
+ args.push('--env', `https_proxy=${proxy}`); // lower-case can be required, e.g. for curl
524
+ args.push('--env', `HTTP_PROXY=${proxy}`);
525
+ args.push('--env', `http_proxy=${proxy}`);
526
+ }
527
+ const noProxy = process.env['NO_PROXY'] || process.env['no_proxy'];
528
+ if (noProxy) {
529
+ args.push('--env', `NO_PROXY=${noProxy}`);
530
+ args.push('--env', `no_proxy=${noProxy}`);
531
+ }
532
+
533
+ // if using proxy, switch to internal networking through proxy
534
+ if (proxy) {
535
+ execSync(
536
+ `${config.command} network inspect ${SANDBOX_NETWORK_NAME} || ${config.command} network create --internal ${SANDBOX_NETWORK_NAME}`,
537
+ );
538
+ args.push('--network', SANDBOX_NETWORK_NAME);
539
+ // if proxy command is set, create a separate network w/ host access (i.e. non-internal)
540
+ // we will run proxy in its own container connected to both host network and internal network
541
+ // this allows proxy to work even on rootless podman on macos with host<->vm<->container isolation
542
+ if (proxyCommand) {
543
+ execSync(
544
+ `${config.command} network inspect ${SANDBOX_PROXY_NAME} || ${config.command} network create ${SANDBOX_PROXY_NAME}`,
545
+ );
546
+ }
547
+ }
548
+ }
549
+
550
+ // name container after image, plus numeric suffix to avoid conflicts
551
+ const imageName = parseImageName(image);
552
+ let index = 0;
553
+ const containerNameCheck = execSync(
554
+ `${config.command} ps -a --format "{{.Names}}"`,
555
+ )
556
+ .toString()
557
+ .trim();
558
+ while (containerNameCheck.includes(`${imageName}-${index}`)) {
559
+ index++;
560
+ }
561
+ const containerName = `${imageName}-${index}`;
562
+ args.push('--name', containerName, '--hostname', containerName);
563
+
564
+ // copy GEMINI_API_KEY(s)
565
+ if (process.env['GEMINI_API_KEY']) {
566
+ args.push('--env', `GEMINI_API_KEY=${process.env['GEMINI_API_KEY']}`);
567
+ }
568
+ if (process.env['GOOGLE_API_KEY']) {
569
+ args.push('--env', `GOOGLE_API_KEY=${process.env['GOOGLE_API_KEY']}`);
570
+ }
571
+
572
+ // copy OPENAI_API_KEY and related env vars for Qwen
573
+ if (process.env['OPENAI_API_KEY']) {
574
+ args.push('--env', `OPENAI_API_KEY=${process.env['OPENAI_API_KEY']}`);
575
+ }
576
+ // copy TAVILY_API_KEY for web search tool
577
+ if (process.env['TAVILY_API_KEY']) {
578
+ args.push('--env', `TAVILY_API_KEY=${process.env['TAVILY_API_KEY']}`);
579
+ }
580
+ if (process.env['OPENAI_BASE_URL']) {
581
+ args.push('--env', `OPENAI_BASE_URL=${process.env['OPENAI_BASE_URL']}`);
582
+ }
583
+ if (process.env['OPENAI_MODEL']) {
584
+ args.push('--env', `OPENAI_MODEL=${process.env['OPENAI_MODEL']}`);
585
+ }
586
+
587
+ // copy GOOGLE_GENAI_USE_VERTEXAI
588
+ if (process.env['GOOGLE_GENAI_USE_VERTEXAI']) {
589
+ args.push(
590
+ '--env',
591
+ `GOOGLE_GENAI_USE_VERTEXAI=${process.env['GOOGLE_GENAI_USE_VERTEXAI']}`,
592
+ );
593
+ }
594
+
595
+ // copy GOOGLE_GENAI_USE_GCA
596
+ if (process.env['GOOGLE_GENAI_USE_GCA']) {
597
+ args.push(
598
+ '--env',
599
+ `GOOGLE_GENAI_USE_GCA=${process.env['GOOGLE_GENAI_USE_GCA']}`,
600
+ );
601
+ }
602
+
603
+ // copy GOOGLE_CLOUD_PROJECT
604
+ if (process.env['GOOGLE_CLOUD_PROJECT']) {
605
+ args.push(
606
+ '--env',
607
+ `GOOGLE_CLOUD_PROJECT=${process.env['GOOGLE_CLOUD_PROJECT']}`,
608
+ );
609
+ }
610
+
611
+ // copy GOOGLE_CLOUD_LOCATION
612
+ if (process.env['GOOGLE_CLOUD_LOCATION']) {
613
+ args.push(
614
+ '--env',
615
+ `GOOGLE_CLOUD_LOCATION=${process.env['GOOGLE_CLOUD_LOCATION']}`,
616
+ );
617
+ }
618
+
619
+ // copy GEMINI_MODEL
620
+ if (process.env['GEMINI_MODEL']) {
621
+ args.push('--env', `GEMINI_MODEL=${process.env['GEMINI_MODEL']}`);
622
+ }
623
+
624
+ // copy TERM and COLORTERM to try to maintain terminal setup
625
+ if (process.env['TERM']) {
626
+ args.push('--env', `TERM=${process.env['TERM']}`);
627
+ }
628
+ if (process.env['COLORTERM']) {
629
+ args.push('--env', `COLORTERM=${process.env['COLORTERM']}`);
630
+ }
631
+
632
+ // Pass through IDE mode environment variables
633
+ for (const envVar of [
634
+ 'QWEN_CODE_IDE_SERVER_PORT',
635
+ 'QWEN_CODE_IDE_WORKSPACE_PATH',
636
+ 'TERM_PROGRAM',
637
+ ]) {
638
+ if (process.env[envVar]) {
639
+ args.push('--env', `${envVar}=${process.env[envVar]}`);
640
+ }
641
+ }
642
+
643
+ // copy VIRTUAL_ENV if under working directory
644
+ // also mount-replace VIRTUAL_ENV directory with <project_settings>/sandbox.venv
645
+ // sandbox can then set up this new VIRTUAL_ENV directory using sandbox.bashrc (see below)
646
+ // directory will be empty if not set up, which is still preferable to having host binaries
647
+ if (
648
+ process.env['VIRTUAL_ENV']
649
+ ?.toLowerCase()
650
+ .startsWith(workdir.toLowerCase())
651
+ ) {
652
+ const sandboxVenvPath = path.resolve(
653
+ SETTINGS_DIRECTORY_NAME,
654
+ 'sandbox.venv',
655
+ );
656
+ if (!fs.existsSync(sandboxVenvPath)) {
657
+ fs.mkdirSync(sandboxVenvPath, { recursive: true });
658
+ }
659
+ args.push(
660
+ '--volume',
661
+ `${sandboxVenvPath}:${getContainerPath(process.env['VIRTUAL_ENV'])}`,
662
+ );
663
+ args.push(
664
+ '--env',
665
+ `VIRTUAL_ENV=${getContainerPath(process.env['VIRTUAL_ENV'])}`,
666
+ );
667
+ }
668
+
669
+ // copy additional environment variables from SANDBOX_ENV
670
+ if (process.env['SANDBOX_ENV']) {
671
+ for (let env of process.env['SANDBOX_ENV'].split(',')) {
672
+ if ((env = env.trim())) {
673
+ if (env.includes('=')) {
674
+ console.error(`SANDBOX_ENV: ${env}`);
675
+ args.push('--env', env);
676
+ } else {
677
+ console.error(
678
+ 'ERROR: SANDBOX_ENV must be a comma-separated list of key=value pairs',
679
+ );
680
+ process.exit(1);
681
+ }
682
+ }
683
+ }
684
+ }
685
+
686
+ // copy NODE_OPTIONS
687
+ const existingNodeOptions = process.env['NODE_OPTIONS'] || '';
688
+ const allNodeOptions = [
689
+ ...(existingNodeOptions ? [existingNodeOptions] : []),
690
+ ...nodeArgs,
691
+ ].join(' ');
692
+
693
+ if (allNodeOptions.length > 0) {
694
+ args.push('--env', `NODE_OPTIONS="${allNodeOptions}"`);
695
+ }
696
+
697
+ // set SANDBOX as container name
698
+ args.push('--env', `SANDBOX=${containerName}`);
699
+
700
+ // for podman only, use empty --authfile to skip unnecessary auth refresh overhead
701
+ if (config.command === 'podman') {
702
+ const emptyAuthFilePath = path.join(os.tmpdir(), 'empty_auth.json');
703
+ fs.writeFileSync(emptyAuthFilePath, '{}', 'utf-8');
704
+ args.push('--authfile', emptyAuthFilePath);
705
+ }
706
+
707
+ // Determine if the current user's UID/GID should be passed to the sandbox.
708
+ // See shouldUseCurrentUserInSandbox for more details.
709
+ let userFlag = '';
710
+ const finalEntrypoint = entrypoint(workdir);
711
+
712
+ if (process.env['GEMINI_CLI_INTEGRATION_TEST'] === 'true') {
713
+ args.push('--user', 'root');
714
+ userFlag = '--user root';
715
+ } else if (await shouldUseCurrentUserInSandbox()) {
716
+ // For the user-creation logic to work, the container must start as root.
717
+ // The entrypoint script then handles dropping privileges to the correct user.
718
+ args.push('--user', 'root');
719
+
720
+ const uid = execSync('id -u').toString().trim();
721
+ const gid = execSync('id -g').toString().trim();
722
+
723
+ // Instead of passing --user to the main sandbox container, we let it
724
+ // start as root, then create a user with the host's UID/GID, and
725
+ // finally switch to that user to run the gemini process. This is
726
+ // necessary on Linux to ensure the user exists within the
727
+ // container's /etc/passwd file, which is required by os.userInfo().
728
+ const username = 'gemini';
729
+ const homeDir = getContainerPath(os.homedir());
730
+
731
+ const setupUserCommands = [
732
+ // Use -f with groupadd to avoid errors if the group already exists.
733
+ `groupadd -f -g ${gid} ${username}`,
734
+ // Create user only if it doesn't exist. Use -o for non-unique UID.
735
+ `id -u ${username} &>/dev/null || useradd -o -u ${uid} -g ${gid} -d ${homeDir} -s /bin/bash ${username}`,
736
+ ].join(' && ');
737
+
738
+ const originalCommand = finalEntrypoint[2];
739
+ const escapedOriginalCommand = originalCommand.replace(/'/g, "'\\''");
740
+
741
+ // Use `su -p` to preserve the environment.
742
+ const suCommand = `su -p ${username} -c '${escapedOriginalCommand}'`;
743
+
744
+ // The entrypoint is always `['bash', '-c', '<command>']`, so we modify the command part.
745
+ finalEntrypoint[2] = `${setupUserCommands} && ${suCommand}`;
746
+
747
+ // We still need userFlag for the simpler proxy container, which does not have this issue.
748
+ userFlag = `--user ${uid}:${gid}`;
749
+ // When forcing a UID in the sandbox, $HOME can be reset to '/', so we copy $HOME as well.
750
+ args.push('--env', `HOME=${os.homedir()}`);
751
+ }
752
+
753
+ // push container image name
754
+ args.push(image);
755
+
756
+ // push container entrypoint (including args)
757
+ args.push(...finalEntrypoint);
758
+
759
+ // start and set up proxy if GEMINI_SANDBOX_PROXY_COMMAND is set
760
+ let proxyProcess: ChildProcess | undefined = undefined;
761
+ let sandboxProcess: ChildProcess | undefined = undefined;
762
+
763
+ if (proxyCommand) {
764
+ // run proxyCommand in its own container
765
+ const proxyContainerCommand = `${config.command} run --rm --init ${userFlag} --name ${SANDBOX_PROXY_NAME} --network ${SANDBOX_PROXY_NAME} -p 8877:8877 -v ${process.cwd()}:${workdir} --workdir ${workdir} ${image} ${proxyCommand}`;
766
+ proxyProcess = spawn(proxyContainerCommand, {
767
+ stdio: ['ignore', 'pipe', 'pipe'],
768
+ shell: true,
769
+ detached: true,
770
+ });
771
+ // install handlers to stop proxy on exit/signal
772
+ const stopProxy = () => {
773
+ console.log('stopping proxy container ...');
774
+ execSync(`${config.command} rm -f ${SANDBOX_PROXY_NAME}`);
775
+ };
776
+ process.on('exit', stopProxy);
777
+ process.on('SIGINT', stopProxy);
778
+ process.on('SIGTERM', stopProxy);
779
+
780
+ // commented out as it disrupts ink rendering
781
+ // proxyProcess.stdout?.on('data', (data) => {
782
+ // console.info(data.toString());
783
+ // });
784
+ proxyProcess.stderr?.on('data', (data) => {
785
+ console.error(data.toString().trim());
786
+ });
787
+ proxyProcess.on('close', (code, signal) => {
788
+ console.error(
789
+ `ERROR: proxy container command '${proxyContainerCommand}' exited with code ${code}, signal ${signal}`,
790
+ );
791
+ if (sandboxProcess?.pid) {
792
+ process.kill(-sandboxProcess.pid, 'SIGTERM');
793
+ }
794
+ process.exit(1);
795
+ });
796
+ console.log('waiting for proxy to start ...');
797
+ await execAsync(
798
+ `until timeout 0.25 curl -s http://localhost:8877; do sleep 0.25; done`,
799
+ );
800
+ // connect proxy container to sandbox network
801
+ // (workaround for older versions of docker that don't support multiple --network args)
802
+ await execAsync(
803
+ `${config.command} network connect ${SANDBOX_NETWORK_NAME} ${SANDBOX_PROXY_NAME}`,
804
+ );
805
+ }
806
+
807
+ // spawn child and let it inherit stdio
808
+ sandboxProcess = spawn(config.command, args, {
809
+ stdio: 'inherit',
810
+ });
811
+
812
+ sandboxProcess.on('error', (err) => {
813
+ console.error('Sandbox process error:', err);
814
+ });
815
+
816
+ await new Promise<void>((resolve) => {
817
+ sandboxProcess?.on('close', (code, signal) => {
818
+ if (code !== 0) {
819
+ console.log(
820
+ `Sandbox process exited with code: ${code}, signal: ${signal}`,
821
+ );
822
+ }
823
+ resolve();
824
+ });
825
+ });
826
+ } finally {
827
+ patcher.cleanup();
828
+ }
829
+ }
830
+
831
+ // Helper functions to ensure sandbox image is present
832
+ async function imageExists(sandbox: string, image: string): Promise<boolean> {
833
+ return new Promise((resolve) => {
834
+ const args = ['images', '-q', image];
835
+ const checkProcess = spawn(sandbox, args);
836
+
837
+ let stdoutData = '';
838
+ if (checkProcess.stdout) {
839
+ checkProcess.stdout.on('data', (data) => {
840
+ stdoutData += data.toString();
841
+ });
842
+ }
843
+
844
+ checkProcess.on('error', (err) => {
845
+ console.warn(
846
+ `Failed to start '${sandbox}' command for image check: ${err.message}`,
847
+ );
848
+ resolve(false);
849
+ });
850
+
851
+ checkProcess.on('close', (code) => {
852
+ // Non-zero code might indicate docker daemon not running, etc.
853
+ // The primary success indicator is non-empty stdoutData.
854
+ if (code !== 0) {
855
+ // console.warn(`'${sandbox} images -q ${image}' exited with code ${code}.`);
856
+ }
857
+ resolve(stdoutData.trim() !== '');
858
+ });
859
+ });
860
+ }
861
+
862
+ async function pullImage(sandbox: string, image: string): Promise<boolean> {
863
+ console.info(`Attempting to pull image ${image} using ${sandbox}...`);
864
+ return new Promise((resolve) => {
865
+ const args = ['pull', image];
866
+ const pullProcess = spawn(sandbox, args, { stdio: 'pipe' });
867
+
868
+ let stderrData = '';
869
+
870
+ const onStdoutData = (data: Buffer) => {
871
+ console.info(data.toString().trim()); // Show pull progress
872
+ };
873
+
874
+ const onStderrData = (data: Buffer) => {
875
+ stderrData += data.toString();
876
+ console.error(data.toString().trim()); // Show pull errors/info from the command itself
877
+ };
878
+
879
+ const onError = (err: Error) => {
880
+ console.warn(
881
+ `Failed to start '${sandbox} pull ${image}' command: ${err.message}`,
882
+ );
883
+ cleanup();
884
+ resolve(false);
885
+ };
886
+
887
+ const onClose = (code: number | null) => {
888
+ if (code === 0) {
889
+ console.info(`Successfully pulled image ${image}.`);
890
+ cleanup();
891
+ resolve(true);
892
+ } else {
893
+ console.warn(
894
+ `Failed to pull image ${image}. '${sandbox} pull ${image}' exited with code ${code}.`,
895
+ );
896
+ if (stderrData.trim()) {
897
+ // Details already printed by the stderr listener above
898
+ }
899
+ cleanup();
900
+ resolve(false);
901
+ }
902
+ };
903
+
904
+ const cleanup = () => {
905
+ if (pullProcess.stdout) {
906
+ pullProcess.stdout.removeListener('data', onStdoutData);
907
+ }
908
+ if (pullProcess.stderr) {
909
+ pullProcess.stderr.removeListener('data', onStderrData);
910
+ }
911
+ pullProcess.removeListener('error', onError);
912
+ pullProcess.removeListener('close', onClose);
913
+ if (pullProcess.connected) {
914
+ pullProcess.disconnect();
915
+ }
916
+ };
917
+
918
+ if (pullProcess.stdout) {
919
+ pullProcess.stdout.on('data', onStdoutData);
920
+ }
921
+ if (pullProcess.stderr) {
922
+ pullProcess.stderr.on('data', onStderrData);
923
+ }
924
+ pullProcess.on('error', onError);
925
+ pullProcess.on('close', onClose);
926
+ });
927
+ }
928
+
929
+ async function ensureSandboxImageIsPresent(
930
+ sandbox: string,
931
+ image: string,
932
+ ): Promise<boolean> {
933
+ console.info(`Checking for sandbox image: ${image}`);
934
+ if (await imageExists(sandbox, image)) {
935
+ console.info(`Sandbox image ${image} found locally.`);
936
+ return true;
937
+ }
938
+
939
+ console.info(`Sandbox image ${image} not found locally.`);
940
+ if (image === LOCAL_DEV_SANDBOX_IMAGE_NAME) {
941
+ // user needs to build the image themselves
942
+ return false;
943
+ }
944
+
945
+ if (await pullImage(sandbox, image)) {
946
+ // After attempting to pull, check again to be certain
947
+ if (await imageExists(sandbox, image)) {
948
+ console.info(`Sandbox image ${image} is now available after pulling.`);
949
+ return true;
950
+ } else {
951
+ console.warn(
952
+ `Sandbox image ${image} still not found after a pull attempt. This might indicate an issue with the image name or registry, or the pull command reported success but failed to make the image available.`,
953
+ );
954
+ return false;
955
+ }
956
+ }
957
+
958
+ console.error(
959
+ `Failed to obtain sandbox image ${image} after check and pull attempt.`,
960
+ );
961
+ return false; // Pull command failed or image still not present
962
+ }
projects/ui/qwen-code/packages/cli/src/utils/settingsUtils.test.ts ADDED
@@ -0,0 +1,797 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect } from 'vitest';
8
+ import {
9
+ // Schema utilities
10
+ getSettingsByCategory,
11
+ getSettingDefinition,
12
+ requiresRestart,
13
+ getDefaultValue,
14
+ getRestartRequiredSettings,
15
+ getEffectiveValue,
16
+ getAllSettingKeys,
17
+ getSettingsByType,
18
+ getSettingsRequiringRestart,
19
+ isValidSettingKey,
20
+ getSettingCategory,
21
+ shouldShowInDialog,
22
+ getDialogSettingsByCategory,
23
+ getDialogSettingsByType,
24
+ getDialogSettingKeys,
25
+ // Business logic utilities
26
+ getSettingValue,
27
+ isSettingModified,
28
+ settingExistsInScope,
29
+ setPendingSettingValue,
30
+ hasRestartRequiredSettings,
31
+ getRestartRequiredFromModified,
32
+ getDisplayValue,
33
+ isDefaultValue,
34
+ isValueInherited,
35
+ getEffectiveDisplayValue,
36
+ } from './settingsUtils.js';
37
+
38
+ describe('SettingsUtils', () => {
39
+ describe('Schema Utilities', () => {
40
+ describe('getSettingsByCategory', () => {
41
+ it('should group settings by category', () => {
42
+ const categories = getSettingsByCategory();
43
+
44
+ expect(categories).toHaveProperty('General');
45
+ expect(categories).toHaveProperty('Accessibility');
46
+ expect(categories).toHaveProperty('Checkpointing');
47
+ expect(categories).toHaveProperty('File Filtering');
48
+ expect(categories).toHaveProperty('UI');
49
+ expect(categories).toHaveProperty('Mode');
50
+ expect(categories).toHaveProperty('Updates');
51
+ });
52
+
53
+ it('should include key property in grouped settings', () => {
54
+ const categories = getSettingsByCategory();
55
+
56
+ Object.entries(categories).forEach(([_category, settings]) => {
57
+ settings.forEach((setting) => {
58
+ expect(setting.key).toBeDefined();
59
+ });
60
+ });
61
+ });
62
+ });
63
+
64
+ describe('getSettingDefinition', () => {
65
+ it('should return definition for valid setting', () => {
66
+ const definition = getSettingDefinition('showMemoryUsage');
67
+ expect(definition).toBeDefined();
68
+ expect(definition?.label).toBe('Show Memory Usage');
69
+ });
70
+
71
+ it('should return undefined for invalid setting', () => {
72
+ const definition = getSettingDefinition('invalidSetting');
73
+ expect(definition).toBeUndefined();
74
+ });
75
+ });
76
+
77
+ describe('requiresRestart', () => {
78
+ it('should return true for settings that require restart', () => {
79
+ expect(requiresRestart('autoConfigureMaxOldSpaceSize')).toBe(true);
80
+ expect(requiresRestart('checkpointing.enabled')).toBe(true);
81
+ });
82
+
83
+ it('should return false for settings that do not require restart', () => {
84
+ expect(requiresRestart('showMemoryUsage')).toBe(false);
85
+ expect(requiresRestart('hideTips')).toBe(false);
86
+ });
87
+
88
+ it('should return false for invalid settings', () => {
89
+ expect(requiresRestart('invalidSetting')).toBe(false);
90
+ });
91
+ });
92
+
93
+ describe('getDefaultValue', () => {
94
+ it('should return correct default values', () => {
95
+ expect(getDefaultValue('showMemoryUsage')).toBe(false);
96
+ expect(getDefaultValue('fileFiltering.enableRecursiveFileSearch')).toBe(
97
+ true,
98
+ );
99
+ });
100
+
101
+ it('should return undefined for invalid settings', () => {
102
+ expect(getDefaultValue('invalidSetting')).toBeUndefined();
103
+ });
104
+ });
105
+
106
+ describe('getRestartRequiredSettings', () => {
107
+ it('should return all settings that require restart', () => {
108
+ const restartSettings = getRestartRequiredSettings();
109
+ expect(restartSettings).toContain('autoConfigureMaxOldSpaceSize');
110
+ expect(restartSettings).toContain('checkpointing.enabled');
111
+ expect(restartSettings).not.toContain('showMemoryUsage');
112
+ });
113
+ });
114
+
115
+ describe('getEffectiveValue', () => {
116
+ it('should return value from settings when set', () => {
117
+ const settings = { showMemoryUsage: true };
118
+ const mergedSettings = { showMemoryUsage: false };
119
+
120
+ const value = getEffectiveValue(
121
+ 'showMemoryUsage',
122
+ settings,
123
+ mergedSettings,
124
+ );
125
+ expect(value).toBe(true);
126
+ });
127
+
128
+ it('should return value from merged settings when not set in current scope', () => {
129
+ const settings = {};
130
+ const mergedSettings = { showMemoryUsage: true };
131
+
132
+ const value = getEffectiveValue(
133
+ 'showMemoryUsage',
134
+ settings,
135
+ mergedSettings,
136
+ );
137
+ expect(value).toBe(true);
138
+ });
139
+
140
+ it('should return default value when not set anywhere', () => {
141
+ const settings = {};
142
+ const mergedSettings = {};
143
+
144
+ const value = getEffectiveValue(
145
+ 'showMemoryUsage',
146
+ settings,
147
+ mergedSettings,
148
+ );
149
+ expect(value).toBe(false); // default value
150
+ });
151
+
152
+ it('should handle nested settings correctly', () => {
153
+ const settings = {
154
+ accessibility: { disableLoadingPhrases: true },
155
+ };
156
+ const mergedSettings = {
157
+ accessibility: { disableLoadingPhrases: false },
158
+ };
159
+
160
+ const value = getEffectiveValue(
161
+ 'accessibility.disableLoadingPhrases',
162
+ settings,
163
+ mergedSettings,
164
+ );
165
+ expect(value).toBe(true);
166
+ });
167
+
168
+ it('should return undefined for invalid settings', () => {
169
+ const settings = {};
170
+ const mergedSettings = {};
171
+
172
+ const value = getEffectiveValue(
173
+ 'invalidSetting',
174
+ settings,
175
+ mergedSettings,
176
+ );
177
+ expect(value).toBeUndefined();
178
+ });
179
+ });
180
+
181
+ describe('getAllSettingKeys', () => {
182
+ it('should return all setting keys', () => {
183
+ const keys = getAllSettingKeys();
184
+ expect(keys).toContain('showMemoryUsage');
185
+ expect(keys).toContain('accessibility.disableLoadingPhrases');
186
+ expect(keys).toContain('checkpointing.enabled');
187
+ });
188
+ });
189
+
190
+ describe('getSettingsByType', () => {
191
+ it('should return only boolean settings', () => {
192
+ const booleanSettings = getSettingsByType('boolean');
193
+ expect(booleanSettings.length).toBeGreaterThan(0);
194
+ booleanSettings.forEach((setting) => {
195
+ expect(setting.type).toBe('boolean');
196
+ });
197
+ });
198
+ });
199
+
200
+ describe('getSettingsRequiringRestart', () => {
201
+ it('should return only settings that require restart', () => {
202
+ const restartSettings = getSettingsRequiringRestart();
203
+ expect(restartSettings.length).toBeGreaterThan(0);
204
+ restartSettings.forEach((setting) => {
205
+ expect(setting.requiresRestart).toBe(true);
206
+ });
207
+ });
208
+ });
209
+
210
+ describe('isValidSettingKey', () => {
211
+ it('should return true for valid setting keys', () => {
212
+ expect(isValidSettingKey('showMemoryUsage')).toBe(true);
213
+ expect(isValidSettingKey('accessibility.disableLoadingPhrases')).toBe(
214
+ true,
215
+ );
216
+ });
217
+
218
+ it('should return false for invalid setting keys', () => {
219
+ expect(isValidSettingKey('invalidSetting')).toBe(false);
220
+ expect(isValidSettingKey('')).toBe(false);
221
+ });
222
+ });
223
+
224
+ describe('getSettingCategory', () => {
225
+ it('should return correct category for valid settings', () => {
226
+ expect(getSettingCategory('showMemoryUsage')).toBe('UI');
227
+ expect(getSettingCategory('accessibility.disableLoadingPhrases')).toBe(
228
+ 'Accessibility',
229
+ );
230
+ });
231
+
232
+ it('should return undefined for invalid settings', () => {
233
+ expect(getSettingCategory('invalidSetting')).toBeUndefined();
234
+ });
235
+ });
236
+
237
+ describe('shouldShowInDialog', () => {
238
+ it('should return true for settings marked to show in dialog', () => {
239
+ expect(shouldShowInDialog('showMemoryUsage')).toBe(true);
240
+ expect(shouldShowInDialog('vimMode')).toBe(true);
241
+ expect(shouldShowInDialog('hideWindowTitle')).toBe(true);
242
+ expect(shouldShowInDialog('usageStatisticsEnabled')).toBe(false);
243
+ });
244
+
245
+ it('should return false for settings marked to hide from dialog', () => {
246
+ expect(shouldShowInDialog('selectedAuthType')).toBe(false);
247
+ expect(shouldShowInDialog('coreTools')).toBe(false);
248
+ expect(shouldShowInDialog('customThemes')).toBe(false);
249
+ expect(shouldShowInDialog('theme')).toBe(false); // Changed to false
250
+ expect(shouldShowInDialog('preferredEditor')).toBe(false); // Changed to false
251
+ });
252
+
253
+ it('should return true for invalid settings (default behavior)', () => {
254
+ expect(shouldShowInDialog('invalidSetting')).toBe(true);
255
+ });
256
+ });
257
+
258
+ describe('getDialogSettingsByCategory', () => {
259
+ it('should only return settings marked for dialog display', async () => {
260
+ const categories = getDialogSettingsByCategory();
261
+
262
+ // Should include UI settings that are marked for dialog
263
+ expect(categories['UI']).toBeDefined();
264
+ const uiSettings = categories['UI'];
265
+ const uiKeys = uiSettings.map((s) => s.key);
266
+ expect(uiKeys).toContain('showMemoryUsage');
267
+ expect(uiKeys).toContain('hideWindowTitle');
268
+ expect(uiKeys).not.toContain('customThemes'); // This is marked false
269
+ expect(uiKeys).not.toContain('theme'); // This is now marked false
270
+ });
271
+
272
+ it('should not include Advanced category settings', () => {
273
+ const categories = getDialogSettingsByCategory();
274
+
275
+ // Advanced settings should be filtered out
276
+ expect(categories['Advanced']).toBeUndefined();
277
+ });
278
+
279
+ it('should include settings with showInDialog=true', () => {
280
+ const categories = getDialogSettingsByCategory();
281
+
282
+ const allSettings = Object.values(categories).flat();
283
+ const allKeys = allSettings.map((s) => s.key);
284
+
285
+ expect(allKeys).toContain('vimMode');
286
+ expect(allKeys).toContain('ideMode');
287
+ expect(allKeys).toContain('disableAutoUpdate');
288
+ expect(allKeys).toContain('showMemoryUsage');
289
+ expect(allKeys).not.toContain('usageStatisticsEnabled');
290
+ expect(allKeys).not.toContain('selectedAuthType');
291
+ expect(allKeys).not.toContain('coreTools');
292
+ expect(allKeys).not.toContain('theme'); // Now hidden
293
+ expect(allKeys).not.toContain('preferredEditor'); // Now hidden
294
+ });
295
+ });
296
+
297
+ describe('getDialogSettingsByType', () => {
298
+ it('should return only boolean dialog settings', () => {
299
+ const booleanSettings = getDialogSettingsByType('boolean');
300
+
301
+ const keys = booleanSettings.map((s) => s.key);
302
+ expect(keys).toContain('showMemoryUsage');
303
+ expect(keys).toContain('vimMode');
304
+ expect(keys).toContain('hideWindowTitle');
305
+ expect(keys).not.toContain('usageStatisticsEnabled');
306
+ expect(keys).not.toContain('selectedAuthType'); // Advanced setting
307
+ expect(keys).not.toContain('useExternalAuth'); // Advanced setting
308
+ });
309
+
310
+ it('should return only string dialog settings', () => {
311
+ const stringSettings = getDialogSettingsByType('string');
312
+
313
+ const keys = stringSettings.map((s) => s.key);
314
+ // Note: theme and preferredEditor are now hidden from dialog
315
+ expect(keys).not.toContain('theme'); // Now marked false
316
+ expect(keys).not.toContain('preferredEditor'); // Now marked false
317
+ expect(keys).not.toContain('selectedAuthType'); // Advanced setting
318
+
319
+ // Most string settings are now hidden, so let's just check they exclude advanced ones
320
+ expect(keys.every((key) => !key.startsWith('tool'))).toBe(true); // No tool-related settings
321
+ });
322
+ });
323
+
324
+ describe('getDialogSettingKeys', () => {
325
+ it('should return only settings marked for dialog display', () => {
326
+ const dialogKeys = getDialogSettingKeys();
327
+
328
+ // Should include settings marked for dialog
329
+ expect(dialogKeys).toContain('showMemoryUsage');
330
+ expect(dialogKeys).toContain('vimMode');
331
+ expect(dialogKeys).toContain('hideWindowTitle');
332
+ expect(dialogKeys).not.toContain('usageStatisticsEnabled');
333
+ expect(dialogKeys).toContain('ideMode');
334
+ expect(dialogKeys).toContain('disableAutoUpdate');
335
+
336
+ // Should include nested settings marked for dialog
337
+ expect(dialogKeys).toContain('fileFiltering.respectGitIgnore');
338
+ expect(dialogKeys).toContain('fileFiltering.respectGeminiIgnore');
339
+ expect(dialogKeys).toContain('fileFiltering.enableRecursiveFileSearch');
340
+
341
+ // Should NOT include settings marked as hidden
342
+ expect(dialogKeys).not.toContain('theme'); // Hidden
343
+ expect(dialogKeys).not.toContain('customThemes'); // Hidden
344
+ expect(dialogKeys).not.toContain('preferredEditor'); // Hidden
345
+ expect(dialogKeys).not.toContain('selectedAuthType'); // Advanced
346
+ expect(dialogKeys).not.toContain('coreTools'); // Advanced
347
+ expect(dialogKeys).not.toContain('mcpServers'); // Advanced
348
+ expect(dialogKeys).not.toContain('telemetry'); // Advanced
349
+ });
350
+
351
+ it('should return fewer keys than getAllSettingKeys', () => {
352
+ const allKeys = getAllSettingKeys();
353
+ const dialogKeys = getDialogSettingKeys();
354
+
355
+ expect(dialogKeys.length).toBeLessThan(allKeys.length);
356
+ expect(dialogKeys.length).toBeGreaterThan(0);
357
+ });
358
+
359
+ it('should handle nested settings display correctly', () => {
360
+ // Test the specific issue with fileFiltering.respectGitIgnore
361
+ const key = 'fileFiltering.respectGitIgnore';
362
+ const initialSettings = {};
363
+ const pendingSettings = {};
364
+
365
+ // Set the nested setting to true
366
+ const updatedPendingSettings = setPendingSettingValue(
367
+ key,
368
+ true,
369
+ pendingSettings,
370
+ );
371
+
372
+ // Check if the setting exists in pending settings
373
+ const existsInPending = settingExistsInScope(
374
+ key,
375
+ updatedPendingSettings,
376
+ );
377
+ expect(existsInPending).toBe(true);
378
+
379
+ // Get the value from pending settings
380
+ const valueFromPending = getSettingValue(
381
+ key,
382
+ updatedPendingSettings,
383
+ {},
384
+ );
385
+ expect(valueFromPending).toBe(true);
386
+
387
+ // Test getDisplayValue should show the pending change
388
+ const displayValue = getDisplayValue(
389
+ key,
390
+ initialSettings,
391
+ {},
392
+ new Set(),
393
+ updatedPendingSettings,
394
+ );
395
+ expect(displayValue).toBe('true'); // Should show true (no * since value matches default)
396
+
397
+ // Test that modified settings also show the * indicator
398
+ const modifiedSettings = new Set([key]);
399
+ const displayValueWithModified = getDisplayValue(
400
+ key,
401
+ initialSettings,
402
+ {},
403
+ modifiedSettings,
404
+ {},
405
+ );
406
+ expect(displayValueWithModified).toBe('true*'); // Should show true* because it's in modified settings and default is true
407
+ });
408
+ });
409
+ });
410
+
411
+ describe('Business Logic Utilities', () => {
412
+ describe('getSettingValue', () => {
413
+ it('should return value from settings when set', () => {
414
+ const settings = { showMemoryUsage: true };
415
+ const mergedSettings = { showMemoryUsage: false };
416
+
417
+ const value = getSettingValue(
418
+ 'showMemoryUsage',
419
+ settings,
420
+ mergedSettings,
421
+ );
422
+ expect(value).toBe(true);
423
+ });
424
+
425
+ it('should return value from merged settings when not set in current scope', () => {
426
+ const settings = {};
427
+ const mergedSettings = { showMemoryUsage: true };
428
+
429
+ const value = getSettingValue(
430
+ 'showMemoryUsage',
431
+ settings,
432
+ mergedSettings,
433
+ );
434
+ expect(value).toBe(true);
435
+ });
436
+
437
+ it('should return default value for invalid setting', () => {
438
+ const settings = {};
439
+ const mergedSettings = {};
440
+
441
+ const value = getSettingValue(
442
+ 'invalidSetting',
443
+ settings,
444
+ mergedSettings,
445
+ );
446
+ expect(value).toBe(false); // Default fallback
447
+ });
448
+ });
449
+
450
+ describe('isSettingModified', () => {
451
+ it('should return true when value differs from default', () => {
452
+ expect(isSettingModified('showMemoryUsage', true)).toBe(true);
453
+ expect(
454
+ isSettingModified('fileFiltering.enableRecursiveFileSearch', false),
455
+ ).toBe(true);
456
+ });
457
+
458
+ it('should return false when value matches default', () => {
459
+ expect(isSettingModified('showMemoryUsage', false)).toBe(false);
460
+ expect(
461
+ isSettingModified('fileFiltering.enableRecursiveFileSearch', true),
462
+ ).toBe(false);
463
+ });
464
+ });
465
+
466
+ describe('settingExistsInScope', () => {
467
+ it('should return true for top-level settings that exist', () => {
468
+ const settings = { showMemoryUsage: true };
469
+ expect(settingExistsInScope('showMemoryUsage', settings)).toBe(true);
470
+ });
471
+
472
+ it('should return false for top-level settings that do not exist', () => {
473
+ const settings = {};
474
+ expect(settingExistsInScope('showMemoryUsage', settings)).toBe(false);
475
+ });
476
+
477
+ it('should return true for nested settings that exist', () => {
478
+ const settings = {
479
+ accessibility: { disableLoadingPhrases: true },
480
+ };
481
+ expect(
482
+ settingExistsInScope('accessibility.disableLoadingPhrases', settings),
483
+ ).toBe(true);
484
+ });
485
+
486
+ it('should return false for nested settings that do not exist', () => {
487
+ const settings = {};
488
+ expect(
489
+ settingExistsInScope('accessibility.disableLoadingPhrases', settings),
490
+ ).toBe(false);
491
+ });
492
+
493
+ it('should return false when parent exists but child does not', () => {
494
+ const settings = { accessibility: {} };
495
+ expect(
496
+ settingExistsInScope('accessibility.disableLoadingPhrases', settings),
497
+ ).toBe(false);
498
+ });
499
+ });
500
+
501
+ describe('setPendingSettingValue', () => {
502
+ it('should set top-level setting value', () => {
503
+ const pendingSettings = {};
504
+ const result = setPendingSettingValue(
505
+ 'showMemoryUsage',
506
+ true,
507
+ pendingSettings,
508
+ );
509
+
510
+ expect(result.showMemoryUsage).toBe(true);
511
+ });
512
+
513
+ it('should set nested setting value', () => {
514
+ const pendingSettings = {};
515
+ const result = setPendingSettingValue(
516
+ 'accessibility.disableLoadingPhrases',
517
+ true,
518
+ pendingSettings,
519
+ );
520
+
521
+ expect(result.accessibility?.disableLoadingPhrases).toBe(true);
522
+ });
523
+
524
+ it('should preserve existing nested settings', () => {
525
+ const pendingSettings = {
526
+ accessibility: { disableLoadingPhrases: false },
527
+ };
528
+ const result = setPendingSettingValue(
529
+ 'accessibility.disableLoadingPhrases',
530
+ true,
531
+ pendingSettings,
532
+ );
533
+
534
+ expect(result.accessibility?.disableLoadingPhrases).toBe(true);
535
+ });
536
+
537
+ it('should not mutate original settings', () => {
538
+ const pendingSettings = {};
539
+ setPendingSettingValue('showMemoryUsage', true, pendingSettings);
540
+
541
+ expect(pendingSettings).toEqual({});
542
+ });
543
+ });
544
+
545
+ describe('hasRestartRequiredSettings', () => {
546
+ it('should return true when modified settings require restart', () => {
547
+ const modifiedSettings = new Set<string>([
548
+ 'autoConfigureMaxOldSpaceSize',
549
+ 'showMemoryUsage',
550
+ ]);
551
+ expect(hasRestartRequiredSettings(modifiedSettings)).toBe(true);
552
+ });
553
+
554
+ it('should return false when no modified settings require restart', () => {
555
+ const modifiedSettings = new Set<string>([
556
+ 'showMemoryUsage',
557
+ 'hideTips',
558
+ ]);
559
+ expect(hasRestartRequiredSettings(modifiedSettings)).toBe(false);
560
+ });
561
+
562
+ it('should return false for empty set', () => {
563
+ const modifiedSettings = new Set<string>();
564
+ expect(hasRestartRequiredSettings(modifiedSettings)).toBe(false);
565
+ });
566
+ });
567
+
568
+ describe('getRestartRequiredFromModified', () => {
569
+ it('should return only settings that require restart', () => {
570
+ const modifiedSettings = new Set<string>([
571
+ 'autoConfigureMaxOldSpaceSize',
572
+ 'showMemoryUsage',
573
+ 'checkpointing.enabled',
574
+ ]);
575
+ const result = getRestartRequiredFromModified(modifiedSettings);
576
+
577
+ expect(result).toContain('autoConfigureMaxOldSpaceSize');
578
+ expect(result).toContain('checkpointing.enabled');
579
+ expect(result).not.toContain('showMemoryUsage');
580
+ });
581
+
582
+ it('should return empty array when no settings require restart', () => {
583
+ const modifiedSettings = new Set<string>([
584
+ 'showMemoryUsage',
585
+ 'hideTips',
586
+ ]);
587
+ const result = getRestartRequiredFromModified(modifiedSettings);
588
+
589
+ expect(result).toEqual([]);
590
+ });
591
+ });
592
+
593
+ describe('getDisplayValue', () => {
594
+ it('should show value without * when setting matches default', () => {
595
+ const settings = { showMemoryUsage: false }; // false matches default, so no *
596
+ const mergedSettings = { showMemoryUsage: false };
597
+ const modifiedSettings = new Set<string>();
598
+
599
+ const result = getDisplayValue(
600
+ 'showMemoryUsage',
601
+ settings,
602
+ mergedSettings,
603
+ modifiedSettings,
604
+ );
605
+ expect(result).toBe('false*');
606
+ });
607
+
608
+ it('should show default value when setting is not in scope', () => {
609
+ const settings = {}; // no setting in scope
610
+ const mergedSettings = { showMemoryUsage: false };
611
+ const modifiedSettings = new Set<string>();
612
+
613
+ const result = getDisplayValue(
614
+ 'showMemoryUsage',
615
+ settings,
616
+ mergedSettings,
617
+ modifiedSettings,
618
+ );
619
+ expect(result).toBe('false'); // shows default value
620
+ });
621
+
622
+ it('should show value with * when changed from default', () => {
623
+ const settings = { showMemoryUsage: true }; // true is different from default (false)
624
+ const mergedSettings = { showMemoryUsage: true };
625
+ const modifiedSettings = new Set<string>();
626
+
627
+ const result = getDisplayValue(
628
+ 'showMemoryUsage',
629
+ settings,
630
+ mergedSettings,
631
+ modifiedSettings,
632
+ );
633
+ expect(result).toBe('true*');
634
+ });
635
+
636
+ it('should show default value without * when setting does not exist in scope', () => {
637
+ const settings = {}; // setting doesn't exist in scope, show default
638
+ const mergedSettings = { showMemoryUsage: false };
639
+ const modifiedSettings = new Set<string>();
640
+
641
+ const result = getDisplayValue(
642
+ 'showMemoryUsage',
643
+ settings,
644
+ mergedSettings,
645
+ modifiedSettings,
646
+ );
647
+ expect(result).toBe('false'); // default value (false) without *
648
+ });
649
+
650
+ it('should show value with * when user changes from default', () => {
651
+ const settings = {}; // setting doesn't exist in scope originally
652
+ const mergedSettings = { showMemoryUsage: false };
653
+ const modifiedSettings = new Set<string>(['showMemoryUsage']);
654
+ const pendingSettings = { showMemoryUsage: true }; // user changed to true
655
+
656
+ const result = getDisplayValue(
657
+ 'showMemoryUsage',
658
+ settings,
659
+ mergedSettings,
660
+ modifiedSettings,
661
+ pendingSettings,
662
+ );
663
+ expect(result).toBe('true*'); // changed from default (false) to true
664
+ });
665
+ });
666
+
667
+ describe('isDefaultValue', () => {
668
+ it('should return true when setting does not exist in scope', () => {
669
+ const settings = {}; // setting doesn't exist
670
+
671
+ const result = isDefaultValue('showMemoryUsage', settings);
672
+ expect(result).toBe(true);
673
+ });
674
+
675
+ it('should return false when setting exists in scope', () => {
676
+ const settings = { showMemoryUsage: true }; // setting exists
677
+
678
+ const result = isDefaultValue('showMemoryUsage', settings);
679
+ expect(result).toBe(false);
680
+ });
681
+
682
+ it('should return true when nested setting does not exist in scope', () => {
683
+ const settings = {}; // nested setting doesn't exist
684
+
685
+ const result = isDefaultValue(
686
+ 'accessibility.disableLoadingPhrases',
687
+ settings,
688
+ );
689
+ expect(result).toBe(true);
690
+ });
691
+
692
+ it('should return false when nested setting exists in scope', () => {
693
+ const settings = { accessibility: { disableLoadingPhrases: true } }; // nested setting exists
694
+
695
+ const result = isDefaultValue(
696
+ 'accessibility.disableLoadingPhrases',
697
+ settings,
698
+ );
699
+ expect(result).toBe(false);
700
+ });
701
+ });
702
+
703
+ describe('isValueInherited', () => {
704
+ it('should return false for top-level settings that exist in scope', () => {
705
+ const settings = { showMemoryUsage: true };
706
+ const mergedSettings = { showMemoryUsage: true };
707
+
708
+ const result = isValueInherited(
709
+ 'showMemoryUsage',
710
+ settings,
711
+ mergedSettings,
712
+ );
713
+ expect(result).toBe(false);
714
+ });
715
+
716
+ it('should return true for top-level settings that do not exist in scope', () => {
717
+ const settings = {};
718
+ const mergedSettings = { showMemoryUsage: true };
719
+
720
+ const result = isValueInherited(
721
+ 'showMemoryUsage',
722
+ settings,
723
+ mergedSettings,
724
+ );
725
+ expect(result).toBe(true);
726
+ });
727
+
728
+ it('should return false for nested settings that exist in scope', () => {
729
+ const settings = {
730
+ accessibility: { disableLoadingPhrases: true },
731
+ };
732
+ const mergedSettings = {
733
+ accessibility: { disableLoadingPhrases: true },
734
+ };
735
+
736
+ const result = isValueInherited(
737
+ 'accessibility.disableLoadingPhrases',
738
+ settings,
739
+ mergedSettings,
740
+ );
741
+ expect(result).toBe(false);
742
+ });
743
+
744
+ it('should return true for nested settings that do not exist in scope', () => {
745
+ const settings = {};
746
+ const mergedSettings = {
747
+ accessibility: { disableLoadingPhrases: true },
748
+ };
749
+
750
+ const result = isValueInherited(
751
+ 'accessibility.disableLoadingPhrases',
752
+ settings,
753
+ mergedSettings,
754
+ );
755
+ expect(result).toBe(true);
756
+ });
757
+ });
758
+
759
+ describe('getEffectiveDisplayValue', () => {
760
+ it('should return value from settings when available', () => {
761
+ const settings = { showMemoryUsage: true };
762
+ const mergedSettings = { showMemoryUsage: false };
763
+
764
+ const result = getEffectiveDisplayValue(
765
+ 'showMemoryUsage',
766
+ settings,
767
+ mergedSettings,
768
+ );
769
+ expect(result).toBe(true);
770
+ });
771
+
772
+ it('should return value from merged settings when not in scope', () => {
773
+ const settings = {};
774
+ const mergedSettings = { showMemoryUsage: true };
775
+
776
+ const result = getEffectiveDisplayValue(
777
+ 'showMemoryUsage',
778
+ settings,
779
+ mergedSettings,
780
+ );
781
+ expect(result).toBe(true);
782
+ });
783
+
784
+ it('should return default value for undefined values', () => {
785
+ const settings = {};
786
+ const mergedSettings = {};
787
+
788
+ const result = getEffectiveDisplayValue(
789
+ 'showMemoryUsage',
790
+ settings,
791
+ mergedSettings,
792
+ );
793
+ expect(result).toBe(false); // Default value
794
+ });
795
+ });
796
+ });
797
+ });
projects/ui/qwen-code/packages/cli/src/utils/settingsUtils.ts ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { Settings, SettingScope, LoadedSettings } from '../config/settings.js';
8
+ import {
9
+ SETTINGS_SCHEMA,
10
+ SettingDefinition,
11
+ SettingsSchema,
12
+ } from '../config/settingsSchema.js';
13
+
14
+ // The schema is now nested, but many parts of the UI and logic work better
15
+ // with a flattened structure and dot-notation keys. This section flattens the
16
+ // schema into a map for easier lookups.
17
+
18
+ function flattenSchema(
19
+ schema: SettingsSchema,
20
+ prefix = '',
21
+ ): Record<string, SettingDefinition & { key: string }> {
22
+ let result: Record<string, SettingDefinition & { key: string }> = {};
23
+ for (const key in schema) {
24
+ const newKey = prefix ? `${prefix}.${key}` : key;
25
+ const definition = schema[key];
26
+ result[newKey] = { ...definition, key: newKey };
27
+ if (definition.properties) {
28
+ result = { ...result, ...flattenSchema(definition.properties, newKey) };
29
+ }
30
+ }
31
+ return result;
32
+ }
33
+
34
+ const FLATTENED_SCHEMA = flattenSchema(SETTINGS_SCHEMA);
35
+
36
+ /**
37
+ * Get all settings grouped by category
38
+ */
39
+ export function getSettingsByCategory(): Record<
40
+ string,
41
+ Array<SettingDefinition & { key: string }>
42
+ > {
43
+ const categories: Record<
44
+ string,
45
+ Array<SettingDefinition & { key: string }>
46
+ > = {};
47
+
48
+ Object.values(FLATTENED_SCHEMA).forEach((definition) => {
49
+ const category = definition.category;
50
+ if (!categories[category]) {
51
+ categories[category] = [];
52
+ }
53
+ categories[category].push(definition);
54
+ });
55
+
56
+ return categories;
57
+ }
58
+
59
+ /**
60
+ * Get a setting definition by key
61
+ */
62
+ export function getSettingDefinition(
63
+ key: string,
64
+ ): (SettingDefinition & { key: string }) | undefined {
65
+ return FLATTENED_SCHEMA[key];
66
+ }
67
+
68
+ /**
69
+ * Check if a setting requires restart
70
+ */
71
+ export function requiresRestart(key: string): boolean {
72
+ return FLATTENED_SCHEMA[key]?.requiresRestart ?? false;
73
+ }
74
+
75
+ /**
76
+ * Get the default value for a setting
77
+ */
78
+ export function getDefaultValue(key: string): SettingDefinition['default'] {
79
+ return FLATTENED_SCHEMA[key]?.default;
80
+ }
81
+
82
+ /**
83
+ * Get all setting keys that require restart
84
+ */
85
+ export function getRestartRequiredSettings(): string[] {
86
+ return Object.values(FLATTENED_SCHEMA)
87
+ .filter((definition) => definition.requiresRestart)
88
+ .map((definition) => definition.key);
89
+ }
90
+
91
+ /**
92
+ * Recursively gets a value from a nested object using a key path array.
93
+ */
94
+ export function getNestedValue(
95
+ obj: Record<string, unknown>,
96
+ path: string[],
97
+ ): unknown {
98
+ const [first, ...rest] = path;
99
+ if (!first || !(first in obj)) {
100
+ return undefined;
101
+ }
102
+ const value = obj[first];
103
+ if (rest.length === 0) {
104
+ return value;
105
+ }
106
+ if (value && typeof value === 'object' && value !== null) {
107
+ return getNestedValue(value as Record<string, unknown>, rest);
108
+ }
109
+ return undefined;
110
+ }
111
+
112
+ /**
113
+ * Get the effective value for a setting, considering inheritance from higher scopes
114
+ * Always returns a value (never undefined) - falls back to default if not set anywhere
115
+ */
116
+ export function getEffectiveValue(
117
+ key: string,
118
+ settings: Settings,
119
+ mergedSettings: Settings,
120
+ ): SettingDefinition['default'] {
121
+ const definition = getSettingDefinition(key);
122
+ if (!definition) {
123
+ return undefined;
124
+ }
125
+
126
+ const path = key.split('.');
127
+
128
+ // Check the current scope's settings first
129
+ let value = getNestedValue(settings as Record<string, unknown>, path);
130
+ if (value !== undefined) {
131
+ return value as SettingDefinition['default'];
132
+ }
133
+
134
+ // Check the merged settings for an inherited value
135
+ value = getNestedValue(mergedSettings as Record<string, unknown>, path);
136
+ if (value !== undefined) {
137
+ return value as SettingDefinition['default'];
138
+ }
139
+
140
+ // Return default value if no value is set anywhere
141
+ return definition.default;
142
+ }
143
+
144
+ /**
145
+ * Get all setting keys from the schema
146
+ */
147
+ export function getAllSettingKeys(): string[] {
148
+ return Object.keys(FLATTENED_SCHEMA);
149
+ }
150
+
151
+ /**
152
+ * Get settings by type
153
+ */
154
+ export function getSettingsByType(
155
+ type: SettingDefinition['type'],
156
+ ): Array<SettingDefinition & { key: string }> {
157
+ return Object.values(FLATTENED_SCHEMA).filter(
158
+ (definition) => definition.type === type,
159
+ );
160
+ }
161
+
162
+ /**
163
+ * Get settings that require restart
164
+ */
165
+ export function getSettingsRequiringRestart(): Array<
166
+ SettingDefinition & {
167
+ key: string;
168
+ }
169
+ > {
170
+ return Object.values(FLATTENED_SCHEMA).filter(
171
+ (definition) => definition.requiresRestart,
172
+ );
173
+ }
174
+
175
+ /**
176
+ * Validate if a setting key exists in the schema
177
+ */
178
+ export function isValidSettingKey(key: string): boolean {
179
+ return key in FLATTENED_SCHEMA;
180
+ }
181
+
182
+ /**
183
+ * Get the category for a setting
184
+ */
185
+ export function getSettingCategory(key: string): string | undefined {
186
+ return FLATTENED_SCHEMA[key]?.category;
187
+ }
188
+
189
+ /**
190
+ * Check if a setting should be shown in the settings dialog
191
+ */
192
+ export function shouldShowInDialog(key: string): boolean {
193
+ return FLATTENED_SCHEMA[key]?.showInDialog ?? true; // Default to true for backward compatibility
194
+ }
195
+
196
+ /**
197
+ * Get all settings that should be shown in the dialog, grouped by category
198
+ */
199
+ export function getDialogSettingsByCategory(): Record<
200
+ string,
201
+ Array<SettingDefinition & { key: string }>
202
+ > {
203
+ const categories: Record<
204
+ string,
205
+ Array<SettingDefinition & { key: string }>
206
+ > = {};
207
+
208
+ Object.values(FLATTENED_SCHEMA)
209
+ .filter((definition) => definition.showInDialog !== false)
210
+ .forEach((definition) => {
211
+ const category = definition.category;
212
+ if (!categories[category]) {
213
+ categories[category] = [];
214
+ }
215
+ categories[category].push(definition);
216
+ });
217
+
218
+ return categories;
219
+ }
220
+
221
+ /**
222
+ * Get settings by type that should be shown in the dialog
223
+ */
224
+ export function getDialogSettingsByType(
225
+ type: SettingDefinition['type'],
226
+ ): Array<SettingDefinition & { key: string }> {
227
+ return Object.values(FLATTENED_SCHEMA).filter(
228
+ (definition) =>
229
+ definition.type === type && definition.showInDialog !== false,
230
+ );
231
+ }
232
+
233
+ /**
234
+ * Get all setting keys that should be shown in the dialog
235
+ */
236
+ export function getDialogSettingKeys(): string[] {
237
+ return Object.values(FLATTENED_SCHEMA)
238
+ .filter((definition) => definition.showInDialog !== false)
239
+ .map((definition) => definition.key);
240
+ }
241
+
242
+ // ============================================================================
243
+ // BUSINESS LOGIC UTILITIES (Higher-level utilities for setting operations)
244
+ // ============================================================================
245
+
246
+ /**
247
+ * Get the current value for a setting in a specific scope
248
+ * Always returns a value (never undefined) - falls back to default if not set anywhere
249
+ */
250
+ export function getSettingValue(
251
+ key: string,
252
+ settings: Settings,
253
+ mergedSettings: Settings,
254
+ ): boolean {
255
+ const definition = getSettingDefinition(key);
256
+ if (!definition) {
257
+ return false; // Default fallback for invalid settings
258
+ }
259
+
260
+ const value = getEffectiveValue(key, settings, mergedSettings);
261
+ // Ensure we return a boolean value, converting from the more general type
262
+ if (typeof value === 'boolean') {
263
+ return value;
264
+ }
265
+ // Fall back to default value, ensuring it's a boolean
266
+ const defaultValue = definition.default;
267
+ if (typeof defaultValue === 'boolean') {
268
+ return defaultValue;
269
+ }
270
+ return false; // Final fallback
271
+ }
272
+
273
+ /**
274
+ * Check if a setting value is modified from its default
275
+ */
276
+ export function isSettingModified(key: string, value: boolean): boolean {
277
+ const defaultValue = getDefaultValue(key);
278
+ // Handle type comparison properly
279
+ if (typeof defaultValue === 'boolean') {
280
+ return value !== defaultValue;
281
+ }
282
+ // If default is not a boolean, consider it modified if value is true
283
+ return value === true;
284
+ }
285
+
286
+ /**
287
+ * Check if a setting exists in the original settings file for a scope
288
+ */
289
+ export function settingExistsInScope(
290
+ key: string,
291
+ scopeSettings: Settings,
292
+ ): boolean {
293
+ const path = key.split('.');
294
+ const value = getNestedValue(scopeSettings as Record<string, unknown>, path);
295
+ return value !== undefined;
296
+ }
297
+
298
+ /**
299
+ * Recursively sets a value in a nested object using a key path array.
300
+ */
301
+ function setNestedValue(
302
+ obj: Record<string, unknown>,
303
+ path: string[],
304
+ value: unknown,
305
+ ): Record<string, unknown> {
306
+ const [first, ...rest] = path;
307
+ if (!first) {
308
+ return obj;
309
+ }
310
+
311
+ if (rest.length === 0) {
312
+ obj[first] = value;
313
+ return obj;
314
+ }
315
+
316
+ if (!obj[first] || typeof obj[first] !== 'object') {
317
+ obj[first] = {};
318
+ }
319
+
320
+ setNestedValue(obj[first] as Record<string, unknown>, rest, value);
321
+ return obj;
322
+ }
323
+
324
+ /**
325
+ * Set a setting value in the pending settings
326
+ */
327
+ export function setPendingSettingValue(
328
+ key: string,
329
+ value: boolean,
330
+ pendingSettings: Settings,
331
+ ): Settings {
332
+ const path = key.split('.');
333
+ const newSettings = JSON.parse(JSON.stringify(pendingSettings));
334
+ setNestedValue(newSettings, path, value);
335
+ return newSettings;
336
+ }
337
+
338
+ /**
339
+ * Generic setter: Set a setting value (boolean, number, string, etc.) in the pending settings
340
+ */
341
+ export function setPendingSettingValueAny(
342
+ key: string,
343
+ value: unknown,
344
+ pendingSettings: Settings,
345
+ ): Settings {
346
+ const path = key.split('.');
347
+ const newSettings = structuredClone(pendingSettings);
348
+ setNestedValue(newSettings, path, value);
349
+ return newSettings;
350
+ }
351
+
352
+ /**
353
+ * Check if any modified settings require a restart
354
+ */
355
+ export function hasRestartRequiredSettings(
356
+ modifiedSettings: Set<string>,
357
+ ): boolean {
358
+ return Array.from(modifiedSettings).some((key) => requiresRestart(key));
359
+ }
360
+
361
+ /**
362
+ * Get the restart required settings from a set of modified settings
363
+ */
364
+ export function getRestartRequiredFromModified(
365
+ modifiedSettings: Set<string>,
366
+ ): string[] {
367
+ return Array.from(modifiedSettings).filter((key) => requiresRestart(key));
368
+ }
369
+
370
+ /**
371
+ * Save modified settings to the appropriate scope
372
+ */
373
+ export function saveModifiedSettings(
374
+ modifiedSettings: Set<string>,
375
+ pendingSettings: Settings,
376
+ loadedSettings: LoadedSettings,
377
+ scope: SettingScope,
378
+ ): void {
379
+ modifiedSettings.forEach((settingKey) => {
380
+ const path = settingKey.split('.');
381
+ const value = getNestedValue(
382
+ pendingSettings as Record<string, unknown>,
383
+ path,
384
+ );
385
+
386
+ if (value === undefined) {
387
+ return;
388
+ }
389
+
390
+ const existsInOriginalFile = settingExistsInScope(
391
+ settingKey,
392
+ loadedSettings.forScope(scope).settings,
393
+ );
394
+
395
+ const isDefaultValue = value === getDefaultValue(settingKey);
396
+
397
+ if (existsInOriginalFile || !isDefaultValue) {
398
+ // This is tricky because setValue only works on top-level keys.
399
+ // We need to set the whole parent object.
400
+ const [parentKey] = path;
401
+ if (parentKey) {
402
+ const newParentValue = setPendingSettingValueAny(
403
+ settingKey,
404
+ value,
405
+ loadedSettings.forScope(scope).settings,
406
+ )[parentKey as keyof Settings];
407
+
408
+ loadedSettings.setValue(
409
+ scope,
410
+ parentKey as keyof Settings,
411
+ newParentValue,
412
+ );
413
+ }
414
+ }
415
+ });
416
+ }
417
+
418
+ /**
419
+ * Get the display value for a setting, showing current scope value with default change indicator
420
+ */
421
+ export function getDisplayValue(
422
+ key: string,
423
+ settings: Settings,
424
+ _mergedSettings: Settings,
425
+ modifiedSettings: Set<string>,
426
+ pendingSettings?: Settings,
427
+ ): string {
428
+ // Prioritize pending changes if user has modified this setting
429
+ let value: boolean;
430
+ if (pendingSettings && settingExistsInScope(key, pendingSettings)) {
431
+ // Show the value from the pending (unsaved) edits when it exists
432
+ value = getSettingValue(key, pendingSettings, {});
433
+ } else if (settingExistsInScope(key, settings)) {
434
+ // Show the value defined at the current scope if present
435
+ value = getSettingValue(key, settings, {});
436
+ } else {
437
+ // Fall back to the schema default when the key is unset in this scope
438
+ const defaultValue = getDefaultValue(key);
439
+ value = typeof defaultValue === 'boolean' ? defaultValue : false;
440
+ }
441
+
442
+ const valueString = String(value);
443
+
444
+ // Check if value is different from default OR if it's in modified settings OR if there are pending changes
445
+ const defaultValue = getDefaultValue(key);
446
+ const isChangedFromDefault =
447
+ typeof defaultValue === 'boolean' ? value !== defaultValue : value === true;
448
+ const isInModifiedSettings = modifiedSettings.has(key);
449
+
450
+ // Mark as modified if setting exists in current scope OR is in modified settings
451
+ if (settingExistsInScope(key, settings) || isInModifiedSettings) {
452
+ return `${valueString}*`; // * indicates setting is set in current scope
453
+ }
454
+ if (isChangedFromDefault || isInModifiedSettings) {
455
+ return `${valueString}*`; // * indicates changed from default value
456
+ }
457
+
458
+ return valueString;
459
+ }
460
+
461
+ /**
462
+ * Check if a setting doesn't exist in current scope (should be greyed out)
463
+ */
464
+ export function isDefaultValue(key: string, settings: Settings): boolean {
465
+ return !settingExistsInScope(key, settings);
466
+ }
467
+
468
+ /**
469
+ * Check if a setting value is inherited (not set at current scope)
470
+ */
471
+ export function isValueInherited(
472
+ key: string,
473
+ settings: Settings,
474
+ _mergedSettings: Settings,
475
+ ): boolean {
476
+ return !settingExistsInScope(key, settings);
477
+ }
478
+
479
+ /**
480
+ * Get the effective value for display, considering inheritance
481
+ * Always returns a boolean value (never undefined)
482
+ */
483
+ export function getEffectiveDisplayValue(
484
+ key: string,
485
+ settings: Settings,
486
+ mergedSettings: Settings,
487
+ ): boolean {
488
+ return getSettingValue(key, settings, mergedSettings);
489
+ }
projects/ui/qwen-code/packages/cli/src/utils/spawnWrapper.ts ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { spawn } from 'child_process';
8
+
9
+ export const spawnWrapper = spawn;
projects/ui/qwen-code/packages/cli/src/utils/startupWarnings.test.ts ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
8
+ import { getStartupWarnings } from './startupWarnings.js';
9
+ import * as fs from 'fs/promises';
10
+ import { getErrorMessage } from '@qwen-code/qwen-code-core';
11
+
12
+ vi.mock('fs/promises');
13
+ vi.mock('@qwen-code/qwen-code-core', async (importOriginal) => {
14
+ const actual = await importOriginal();
15
+ return {
16
+ ...actual,
17
+ getErrorMessage: vi.fn(),
18
+ };
19
+ });
20
+
21
+ describe.skip('startupWarnings', () => {
22
+ beforeEach(() => {
23
+ vi.resetAllMocks();
24
+ });
25
+
26
+ it('should return warnings from the file and delete it', async () => {
27
+ const mockWarnings = 'Warning 1\nWarning 2';
28
+ vi.spyOn(fs, 'access').mockResolvedValue();
29
+ vi.spyOn(fs, 'readFile').mockResolvedValue(mockWarnings);
30
+ vi.spyOn(fs, 'unlink').mockResolvedValue();
31
+
32
+ const warnings = await getStartupWarnings();
33
+
34
+ expect(fs.access).toHaveBeenCalled();
35
+ expect(fs.readFile).toHaveBeenCalled();
36
+ expect(fs.unlink).toHaveBeenCalled();
37
+ expect(warnings).toEqual(['Warning 1', 'Warning 2']);
38
+ });
39
+
40
+ it('should return an empty array if the file does not exist', async () => {
41
+ const error = new Error('File not found');
42
+ (error as Error & { code: string }).code = 'ENOENT';
43
+ vi.spyOn(fs, 'access').mockRejectedValue(error);
44
+
45
+ const warnings = await getStartupWarnings();
46
+
47
+ expect(warnings).toEqual([]);
48
+ });
49
+
50
+ it('should return an error message if reading the file fails', async () => {
51
+ const error = new Error('Permission denied');
52
+ vi.spyOn(fs, 'access').mockRejectedValue(error);
53
+ vi.mocked(getErrorMessage).mockReturnValue('Permission denied');
54
+
55
+ const warnings = await getStartupWarnings();
56
+
57
+ expect(warnings).toEqual([
58
+ 'Error checking/reading warnings file: Permission denied',
59
+ ]);
60
+ });
61
+
62
+ it('should return a warning if deleting the file fails', async () => {
63
+ const mockWarnings = 'Warning 1';
64
+ vi.spyOn(fs, 'access').mockResolvedValue();
65
+ vi.spyOn(fs, 'readFile').mockResolvedValue(mockWarnings);
66
+ vi.spyOn(fs, 'unlink').mockRejectedValue(new Error('Permission denied'));
67
+
68
+ const warnings = await getStartupWarnings();
69
+
70
+ expect(warnings).toEqual([
71
+ 'Warning 1',
72
+ 'Warning: Could not delete temporary warnings file.',
73
+ ]);
74
+ });
75
+ });
projects/ui/qwen-code/packages/cli/src/utils/startupWarnings.ts ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import fs from 'fs/promises';
8
+ import os from 'os';
9
+ import { join as pathJoin } from 'node:path';
10
+ import { getErrorMessage } from '@qwen-code/qwen-code-core';
11
+
12
+ const warningsFilePath = pathJoin(os.tmpdir(), 'qwen-code-warnings.txt');
13
+
14
+ export async function getStartupWarnings(): Promise<string[]> {
15
+ try {
16
+ await fs.access(warningsFilePath); // Check if file exists
17
+ const warningsContent = await fs.readFile(warningsFilePath, 'utf-8');
18
+ const warnings = warningsContent
19
+ .split('\n')
20
+ .filter((line) => line.trim() !== '');
21
+ try {
22
+ await fs.unlink(warningsFilePath);
23
+ } catch {
24
+ warnings.push('Warning: Could not delete temporary warnings file.');
25
+ }
26
+ return warnings;
27
+ } catch (err: unknown) {
28
+ // If fs.access throws, it means the file doesn't exist or is not accessible.
29
+ // This is not an error in the context of fetching warnings, so return empty.
30
+ // Only return an error message if it's not a "file not found" type error.
31
+ // However, the original logic returned an error message for any fs.existsSync failure.
32
+ // To maintain closer parity while making it async, we'll check the error code.
33
+ // ENOENT is "Error NO ENTry" (file not found).
34
+ if (err instanceof Error && 'code' in err && err.code === 'ENOENT') {
35
+ return []; // File not found, no warnings to return.
36
+ }
37
+ // For other errors (permissions, etc.), return the error message.
38
+ return [`Error checking/reading warnings file: ${getErrorMessage(err)}`];
39
+ }
40
+ }
projects/ui/qwen-code/packages/cli/src/utils/updateEventEmitter.ts ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { EventEmitter } from 'events';
8
+
9
+ /**
10
+ * A shared event emitter for application-wide communication
11
+ * between decoupled parts of the CLI.
12
+ */
13
+ export const updateEventEmitter = new EventEmitter();
projects/ui/qwen-code/packages/cli/src/utils/userStartupWarnings.test.ts ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
8
+ import { getUserStartupWarnings } from './userStartupWarnings.js';
9
+ import * as os from 'os';
10
+ import fs from 'fs/promises';
11
+ import path from 'path';
12
+
13
+ // Mock os.homedir to control the home directory in tests
14
+ vi.mock('os', async (importOriginal) => {
15
+ const actualOs = await importOriginal<typeof os>();
16
+ return {
17
+ ...actualOs,
18
+ homedir: vi.fn(),
19
+ };
20
+ });
21
+
22
+ describe('getUserStartupWarnings', () => {
23
+ let testRootDir: string;
24
+ let homeDir: string;
25
+
26
+ beforeEach(async () => {
27
+ testRootDir = await fs.mkdtemp(path.join(os.tmpdir(), 'warnings-test-'));
28
+ homeDir = path.join(testRootDir, 'home');
29
+ await fs.mkdir(homeDir, { recursive: true });
30
+ vi.mocked(os.homedir).mockReturnValue(homeDir);
31
+ });
32
+
33
+ afterEach(async () => {
34
+ await fs.rm(testRootDir, { recursive: true, force: true });
35
+ vi.clearAllMocks();
36
+ });
37
+
38
+ describe('home directory check', () => {
39
+ it('should return a warning when running in home directory', async () => {
40
+ const warnings = await getUserStartupWarnings(homeDir);
41
+ expect(warnings).toContainEqual(
42
+ expect.stringContaining('home directory'),
43
+ );
44
+ });
45
+
46
+ it('should not return a warning when running in a project directory', async () => {
47
+ const projectDir = path.join(testRootDir, 'project');
48
+ await fs.mkdir(projectDir);
49
+ const warnings = await getUserStartupWarnings(projectDir);
50
+ expect(warnings).not.toContainEqual(
51
+ expect.stringContaining('home directory'),
52
+ );
53
+ });
54
+ });
55
+
56
+ describe('root directory check', () => {
57
+ it('should return a warning when running in a root directory', async () => {
58
+ const rootDir = path.parse(testRootDir).root;
59
+ const warnings = await getUserStartupWarnings(rootDir);
60
+ expect(warnings).toContainEqual(
61
+ expect.stringContaining('root directory'),
62
+ );
63
+ expect(warnings).toContainEqual(
64
+ expect.stringContaining('folder structure will be used'),
65
+ );
66
+ });
67
+
68
+ it('should not return a warning when running in a non-root directory', async () => {
69
+ const projectDir = path.join(testRootDir, 'project');
70
+ await fs.mkdir(projectDir);
71
+ const warnings = await getUserStartupWarnings(projectDir);
72
+ expect(warnings).not.toContainEqual(
73
+ expect.stringContaining('root directory'),
74
+ );
75
+ });
76
+ });
77
+
78
+ describe('error handling', () => {
79
+ it('should handle errors when checking directory', async () => {
80
+ const nonExistentPath = path.join(testRootDir, 'non-existent');
81
+ const warnings = await getUserStartupWarnings(nonExistentPath);
82
+ const expectedWarning =
83
+ 'Could not verify the current directory due to a file system error.';
84
+ expect(warnings).toEqual([expectedWarning, expectedWarning]);
85
+ });
86
+ });
87
+ });
projects/ui/qwen-code/packages/cli/src/utils/userStartupWarnings.ts ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import fs from 'fs/promises';
8
+ import * as os from 'os';
9
+ import path from 'path';
10
+
11
+ type WarningCheck = {
12
+ id: string;
13
+ check: (workspaceRoot: string) => Promise<string | null>;
14
+ };
15
+
16
+ // Individual warning checks
17
+ const homeDirectoryCheck: WarningCheck = {
18
+ id: 'home-directory',
19
+ check: async (workspaceRoot: string) => {
20
+ try {
21
+ const [workspaceRealPath, homeRealPath] = await Promise.all([
22
+ fs.realpath(workspaceRoot),
23
+ fs.realpath(os.homedir()),
24
+ ]);
25
+
26
+ if (workspaceRealPath === homeRealPath) {
27
+ return 'You are running Qwen Code in your home directory. It is recommended to run in a project-specific directory.';
28
+ }
29
+ return null;
30
+ } catch (_err: unknown) {
31
+ return 'Could not verify the current directory due to a file system error.';
32
+ }
33
+ },
34
+ };
35
+
36
+ const rootDirectoryCheck: WarningCheck = {
37
+ id: 'root-directory',
38
+ check: async (workspaceRoot: string) => {
39
+ try {
40
+ const workspaceRealPath = await fs.realpath(workspaceRoot);
41
+ const errorMessage =
42
+ 'Warning: You are running Qwen Code in the root directory. Your entire folder structure will be used for context. It is strongly recommended to run in a project-specific directory.';
43
+
44
+ // Check for Unix root directory
45
+ if (path.dirname(workspaceRealPath) === workspaceRealPath) {
46
+ return errorMessage;
47
+ }
48
+
49
+ return null;
50
+ } catch (_err: unknown) {
51
+ return 'Could not verify the current directory due to a file system error.';
52
+ }
53
+ },
54
+ };
55
+
56
+ // All warning checks
57
+ const WARNING_CHECKS: readonly WarningCheck[] = [
58
+ homeDirectoryCheck,
59
+ rootDirectoryCheck,
60
+ ];
61
+
62
+ export async function getUserStartupWarnings(
63
+ workspaceRoot: string,
64
+ ): Promise<string[]> {
65
+ const results = await Promise.all(
66
+ WARNING_CHECKS.map((check) => check.check(workspaceRoot)),
67
+ );
68
+ return results.filter((msg) => msg !== null);
69
+ }
projects/ui/qwen-code/packages/cli/src/utils/version.ts ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { getPackageJson } from './package.js';
8
+
9
+ export async function getCliVersion(): Promise<string> {
10
+ const pkgJson = await getPackageJson();
11
+ return process.env['CLI_VERSION'] || pkgJson?.version || 'unknown';
12
+ }
projects/ui/qwen-code/packages/cli/src/zed-integration/acp.ts ADDED
@@ -0,0 +1,366 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ /* ACP defines a schema for a simple (experimental) JSON-RPC protocol that allows GUI applications to interact with agents. */
8
+
9
+ import { z } from 'zod';
10
+ import * as schema from './schema.js';
11
+ export * from './schema.js';
12
+
13
+ import { WritableStream, ReadableStream } from 'node:stream/web';
14
+
15
+ export class AgentSideConnection implements Client {
16
+ #connection: Connection;
17
+
18
+ constructor(
19
+ toAgent: (conn: Client) => Agent,
20
+ input: WritableStream<Uint8Array>,
21
+ output: ReadableStream<Uint8Array>,
22
+ ) {
23
+ const agent = toAgent(this);
24
+
25
+ const handler = async (
26
+ method: string,
27
+ params: unknown,
28
+ ): Promise<unknown> => {
29
+ switch (method) {
30
+ case schema.AGENT_METHODS.initialize: {
31
+ const validatedParams = schema.initializeRequestSchema.parse(params);
32
+ return agent.initialize(validatedParams);
33
+ }
34
+ case schema.AGENT_METHODS.session_new: {
35
+ const validatedParams = schema.newSessionRequestSchema.parse(params);
36
+ return agent.newSession(validatedParams);
37
+ }
38
+ case schema.AGENT_METHODS.session_load: {
39
+ if (!agent.loadSession) {
40
+ throw RequestError.methodNotFound();
41
+ }
42
+ const validatedParams = schema.loadSessionRequestSchema.parse(params);
43
+ return agent.loadSession(validatedParams);
44
+ }
45
+ case schema.AGENT_METHODS.authenticate: {
46
+ const validatedParams =
47
+ schema.authenticateRequestSchema.parse(params);
48
+ return agent.authenticate(validatedParams);
49
+ }
50
+ case schema.AGENT_METHODS.session_prompt: {
51
+ const validatedParams = schema.promptRequestSchema.parse(params);
52
+ return agent.prompt(validatedParams);
53
+ }
54
+ case schema.AGENT_METHODS.session_cancel: {
55
+ const validatedParams = schema.cancelNotificationSchema.parse(params);
56
+ return agent.cancel(validatedParams);
57
+ }
58
+ default:
59
+ throw RequestError.methodNotFound(method);
60
+ }
61
+ };
62
+
63
+ this.#connection = new Connection(handler, input, output);
64
+ }
65
+
66
+ /**
67
+ * Streams new content to the client including text, tool calls, etc.
68
+ */
69
+ async sessionUpdate(params: schema.SessionNotification): Promise<void> {
70
+ return await this.#connection.sendNotification(
71
+ schema.CLIENT_METHODS.session_update,
72
+ params,
73
+ );
74
+ }
75
+
76
+ /**
77
+ * Request permission before running a tool
78
+ *
79
+ * The agent specifies a series of permission options with different granularity,
80
+ * and the client returns the chosen one.
81
+ */
82
+ async requestPermission(
83
+ params: schema.RequestPermissionRequest,
84
+ ): Promise<schema.RequestPermissionResponse> {
85
+ return await this.#connection.sendRequest(
86
+ schema.CLIENT_METHODS.session_request_permission,
87
+ params,
88
+ );
89
+ }
90
+
91
+ async readTextFile(
92
+ params: schema.ReadTextFileRequest,
93
+ ): Promise<schema.ReadTextFileResponse> {
94
+ return await this.#connection.sendRequest(
95
+ schema.CLIENT_METHODS.fs_read_text_file,
96
+ params,
97
+ );
98
+ }
99
+
100
+ async writeTextFile(
101
+ params: schema.WriteTextFileRequest,
102
+ ): Promise<schema.WriteTextFileResponse> {
103
+ return await this.#connection.sendRequest(
104
+ schema.CLIENT_METHODS.fs_write_text_file,
105
+ params,
106
+ );
107
+ }
108
+ }
109
+
110
+ type AnyMessage = AnyRequest | AnyResponse | AnyNotification;
111
+
112
+ type AnyRequest = {
113
+ jsonrpc: '2.0';
114
+ id: string | number;
115
+ method: string;
116
+ params?: unknown;
117
+ };
118
+
119
+ type AnyResponse = {
120
+ jsonrpc: '2.0';
121
+ id: string | number;
122
+ } & Result<unknown>;
123
+
124
+ type AnyNotification = {
125
+ jsonrpc: '2.0';
126
+ method: string;
127
+ params?: unknown;
128
+ };
129
+
130
+ type Result<T> =
131
+ | {
132
+ result: T;
133
+ }
134
+ | {
135
+ error: ErrorResponse;
136
+ };
137
+
138
+ type ErrorResponse = {
139
+ code: number;
140
+ message: string;
141
+ data?: unknown;
142
+ };
143
+
144
+ type PendingResponse = {
145
+ resolve: (response: unknown) => void;
146
+ reject: (error: ErrorResponse) => void;
147
+ };
148
+
149
+ type MethodHandler = (method: string, params: unknown) => Promise<unknown>;
150
+
151
+ class Connection {
152
+ #pendingResponses: Map<string | number, PendingResponse> = new Map();
153
+ #nextRequestId: number = 0;
154
+ #handler: MethodHandler;
155
+ #peerInput: WritableStream<Uint8Array>;
156
+ #writeQueue: Promise<void> = Promise.resolve();
157
+ #textEncoder: TextEncoder;
158
+
159
+ constructor(
160
+ handler: MethodHandler,
161
+ peerInput: WritableStream<Uint8Array>,
162
+ peerOutput: ReadableStream<Uint8Array>,
163
+ ) {
164
+ this.#handler = handler;
165
+ this.#peerInput = peerInput;
166
+ this.#textEncoder = new TextEncoder();
167
+ this.#receive(peerOutput);
168
+ }
169
+
170
+ async #receive(output: ReadableStream<Uint8Array>) {
171
+ let content = '';
172
+ const decoder = new TextDecoder();
173
+ for await (const chunk of output) {
174
+ content += decoder.decode(chunk, { stream: true });
175
+ const lines = content.split('\n');
176
+ content = lines.pop() || '';
177
+
178
+ for (const line of lines) {
179
+ const trimmedLine = line.trim();
180
+
181
+ if (trimmedLine) {
182
+ const message = JSON.parse(trimmedLine);
183
+ this.#processMessage(message);
184
+ }
185
+ }
186
+ }
187
+ }
188
+
189
+ async #processMessage(message: AnyMessage) {
190
+ if ('method' in message && 'id' in message) {
191
+ // It's a request
192
+ const response = await this.#tryCallHandler(
193
+ message.method,
194
+ message.params,
195
+ );
196
+
197
+ await this.#sendMessage({
198
+ jsonrpc: '2.0',
199
+ id: message.id,
200
+ ...response,
201
+ });
202
+ } else if ('method' in message) {
203
+ // It's a notification
204
+ await this.#tryCallHandler(message.method, message.params);
205
+ } else if ('id' in message) {
206
+ // It's a response
207
+ this.#handleResponse(message as AnyResponse);
208
+ }
209
+ }
210
+
211
+ async #tryCallHandler(
212
+ method: string,
213
+ params?: unknown,
214
+ ): Promise<Result<unknown>> {
215
+ try {
216
+ const result = await this.#handler(method, params);
217
+ return { result: result ?? null };
218
+ } catch (error: unknown) {
219
+ if (error instanceof RequestError) {
220
+ return error.toResult();
221
+ }
222
+
223
+ if (error instanceof z.ZodError) {
224
+ return RequestError.invalidParams(
225
+ JSON.stringify(error.format(), undefined, 2),
226
+ ).toResult();
227
+ }
228
+
229
+ let details;
230
+
231
+ if (error instanceof Error) {
232
+ details = error.message;
233
+ } else if (
234
+ typeof error === 'object' &&
235
+ error != null &&
236
+ 'message' in error &&
237
+ typeof error.message === 'string'
238
+ ) {
239
+ details = error.message;
240
+ }
241
+
242
+ return RequestError.internalError(details).toResult();
243
+ }
244
+ }
245
+
246
+ #handleResponse(response: AnyResponse) {
247
+ const pendingResponse = this.#pendingResponses.get(response.id);
248
+ if (pendingResponse) {
249
+ if ('result' in response) {
250
+ pendingResponse.resolve(response.result);
251
+ } else if ('error' in response) {
252
+ pendingResponse.reject(response.error);
253
+ }
254
+ this.#pendingResponses.delete(response.id);
255
+ }
256
+ }
257
+
258
+ async sendRequest<Req, Resp>(method: string, params?: Req): Promise<Resp> {
259
+ const id = this.#nextRequestId++;
260
+ const responsePromise = new Promise((resolve, reject) => {
261
+ this.#pendingResponses.set(id, { resolve, reject });
262
+ });
263
+ await this.#sendMessage({ jsonrpc: '2.0', id, method, params });
264
+ return responsePromise as Promise<Resp>;
265
+ }
266
+
267
+ async sendNotification<N>(method: string, params?: N): Promise<void> {
268
+ await this.#sendMessage({ jsonrpc: '2.0', method, params });
269
+ }
270
+
271
+ async #sendMessage(json: AnyMessage) {
272
+ const content = JSON.stringify(json) + '\n';
273
+ this.#writeQueue = this.#writeQueue
274
+ .then(async () => {
275
+ const writer = this.#peerInput.getWriter();
276
+ try {
277
+ await writer.write(this.#textEncoder.encode(content));
278
+ } finally {
279
+ writer.releaseLock();
280
+ }
281
+ })
282
+ .catch((error) => {
283
+ // Continue processing writes on error
284
+ console.error('ACP write error:', error);
285
+ });
286
+ return this.#writeQueue;
287
+ }
288
+ }
289
+
290
+ export class RequestError extends Error {
291
+ data?: { details?: string };
292
+
293
+ constructor(
294
+ public code: number,
295
+ message: string,
296
+ details?: string,
297
+ ) {
298
+ super(message);
299
+ this.name = 'RequestError';
300
+ if (details) {
301
+ this.data = { details };
302
+ }
303
+ }
304
+
305
+ static parseError(details?: string): RequestError {
306
+ return new RequestError(-32700, 'Parse error', details);
307
+ }
308
+
309
+ static invalidRequest(details?: string): RequestError {
310
+ return new RequestError(-32600, 'Invalid request', details);
311
+ }
312
+
313
+ static methodNotFound(details?: string): RequestError {
314
+ return new RequestError(-32601, 'Method not found', details);
315
+ }
316
+
317
+ static invalidParams(details?: string): RequestError {
318
+ return new RequestError(-32602, 'Invalid params', details);
319
+ }
320
+
321
+ static internalError(details?: string): RequestError {
322
+ return new RequestError(-32603, 'Internal error', details);
323
+ }
324
+
325
+ static authRequired(details?: string): RequestError {
326
+ return new RequestError(-32000, 'Authentication required', details);
327
+ }
328
+
329
+ toResult<T>(): Result<T> {
330
+ return {
331
+ error: {
332
+ code: this.code,
333
+ message: this.message,
334
+ data: this.data,
335
+ },
336
+ };
337
+ }
338
+ }
339
+
340
+ export interface Client {
341
+ requestPermission(
342
+ params: schema.RequestPermissionRequest,
343
+ ): Promise<schema.RequestPermissionResponse>;
344
+ sessionUpdate(params: schema.SessionNotification): Promise<void>;
345
+ writeTextFile(
346
+ params: schema.WriteTextFileRequest,
347
+ ): Promise<schema.WriteTextFileResponse>;
348
+ readTextFile(
349
+ params: schema.ReadTextFileRequest,
350
+ ): Promise<schema.ReadTextFileResponse>;
351
+ }
352
+
353
+ export interface Agent {
354
+ initialize(
355
+ params: schema.InitializeRequest,
356
+ ): Promise<schema.InitializeResponse>;
357
+ newSession(
358
+ params: schema.NewSessionRequest,
359
+ ): Promise<schema.NewSessionResponse>;
360
+ loadSession?(
361
+ params: schema.LoadSessionRequest,
362
+ ): Promise<schema.LoadSessionResponse>;
363
+ authenticate(params: schema.AuthenticateRequest): Promise<void>;
364
+ prompt(params: schema.PromptRequest): Promise<schema.PromptResponse>;
365
+ cancel(params: schema.CancelNotification): Promise<void>;
366
+ }
projects/ui/qwen-code/packages/cli/src/zed-integration/fileSystemService.ts ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @license
3
+ * Copyright 2025 Google LLC
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ */
6
+
7
+ import { FileSystemService } from '@qwen-code/qwen-code-core';
8
+ import * as acp from './acp.js';
9
+
10
+ /**
11
+ * ACP client-based implementation of FileSystemService
12
+ */
13
+ export class AcpFileSystemService implements FileSystemService {
14
+ constructor(
15
+ private readonly client: acp.Client,
16
+ private readonly sessionId: string,
17
+ private readonly capabilities: acp.FileSystemCapability,
18
+ private readonly fallback: FileSystemService,
19
+ ) {}
20
+
21
+ async readTextFile(filePath: string): Promise<string> {
22
+ if (!this.capabilities.readTextFile) {
23
+ return this.fallback.readTextFile(filePath);
24
+ }
25
+
26
+ const response = await this.client.readTextFile({
27
+ path: filePath,
28
+ sessionId: this.sessionId,
29
+ line: null,
30
+ limit: null,
31
+ });
32
+
33
+ return response.content;
34
+ }
35
+
36
+ async writeTextFile(filePath: string, content: string): Promise<void> {
37
+ if (!this.capabilities.writeTextFile) {
38
+ return this.fallback.writeTextFile(filePath, content);
39
+ }
40
+
41
+ await this.client.writeTextFile({
42
+ path: filePath,
43
+ content,
44
+ sessionId: this.sessionId,
45
+ });
46
+ }
47
+ }