返回 DeepSeek-Reasonix
manager_test.go
根目录 / internal / extension / sidecar / manager_test.go
1 package sidecar
2
3 import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "os"
9 "path/filepath"
10 "strings"
11 "sync"
12 "testing"
13 "time"
14
15 "reasonix/internal/extension"
16 "reasonix/internal/extension/protocol"
17 "reasonix/internal/pluginpkg"
18 )
19
20 // installFakePlugin writes a v1 manifest for a fake sidecar package and
21 // registers it (enabled) in the pluginpkg installed state of home.
22 func installFakePlugin(t *testing.T, home, name string, configure func(rt *pluginpkg.RuntimeSpec)) {
23 t.Helper()
24 rt := fakeSidecarRuntime(t, configure)
25 root := filepath.Join(home, "plugins", name)
26 if err := os.MkdirAll(root, 0o755); err != nil {
27 t.Fatalf("MkdirAll: %v", err)
28 }
29 manifest := map[string]any{
30 "apiVersion": pluginpkg.ManifestAPIVersionV2,
31 "name": name,
32 "version": "1.0.0",
33 "runtime": rt,
34 }
35 raw, err := json.Marshal(manifest)
36 if err != nil {
37 t.Fatalf("marshal manifest: %v", err)
38 }
39 if err := os.WriteFile(filepath.Join(root, pluginpkg.NativeManifest), raw, 0o644); err != nil {
40 t.Fatalf("write manifest: %v", err)
41 }
42 installed := pluginpkg.InstalledPlugin{
43 Name: name,
44 Root: pluginpkg.RelativeRoot(home, root),
45 Version: "1.0.0",
46 Enabled: true,
47 }
48 if err := pluginpkg.Upsert(home, installed); err != nil {
49 t.Fatalf("Upsert: %v", err)
50 }
51 }
52
53 func TestManagerStartsEnabledRuntimePackages(t *testing.T) {
54 home := t.TempDir()
55 installFakePlugin(t, home, "alpha", func(rt *pluginpkg.RuntimeSpec) {
56 rt.Intercepts = []string{"input.receive"}
57 rt.Replaces = []string{"compaction"}
58 rt.Capabilities = []string{"providers", "ui"}
59 rt.Env[fakeEnvInitResult] = `{"protocolVersion":"2","name":"alpha","version":"1.0.0",` +
60 `"subscriptions":["input.receive"],"replaces":["compaction"],` +
61 `"providers":[{"ref":"plugin/alpha/openai/gpt-5"}],` +
62 `"uiActions":[{"actionId":"act1"}],"stateSchemaVersion":0}`
63 })
64
65 manager, warnings, err := StartPackages(context.Background(), home, testSessionContext(), nil)
66 if err != nil {
67 t.Fatalf("StartPackages: %v", err)
68 }
69 if len(warnings) != 0 {
70 t.Fatalf("warnings = %v", warnings)
71 }
72 t.Cleanup(func() { _ = manager.Close() })
73
74 client := manager.Client("alpha")
75 if client == nil {
76 t.Fatal("manager has no client for alpha")
77 }
78 result, err := client.Intercept(context.Background(), protocol.EventInputReceive, json.RawMessage(`{}`), 5*time.Second)
79 if err != nil || result.Decision != protocol.DecisionContinue {
80 t.Fatalf("Intercept = %+v, %v", result, err)
81 }
82
83 // Declaration-level contributions: interceptor stub, strategy claim,
84 // provider and UI action declarations.
85 contributions := manager.Contributions()
86 byKind := map[extension.ContributionKind][]extension.Contribution{}
87 for _, c := range contributions {
88 byKind[c.Kind] = append(byKind[c.Kind], c)
89 }
90 interceptors := byKind[extension.KindInterceptor]
91 if len(interceptors) != 1 || interceptors[0].ID != "input.receive" {
92 t.Fatalf("interceptor contributions = %+v", interceptors)
93 }
94 if interceptors[0].Source.PluginID != "alpha" || interceptors[0].Source.Scope != extension.ScopePlugin {
95 t.Fatalf("interceptor source = %+v", interceptors[0].Source)
96 }
97 strategies := byKind[extension.KindStrategy]
98 if len(strategies) != 1 || strategies[0].ID != "compaction" {
99 t.Fatalf("strategy contributions = %+v", strategies)
100 }
101 claimer, ok := strategies[0].Payload.(extension.SlotClaimer)
102 if !ok {
103 t.Fatalf("strategy payload %T is not a SlotClaimer", strategies[0].Payload)
104 }
105 claims := extension.NewReplaceClaims()
106 for _, slot := range claimer.ReplacementSlots() {
107 if err := claims.Claim(slot, strategies[0].Source); err != nil {
108 t.Fatalf("claim %q: %v", slot, err)
109 }
110 }
111 providers := byKind[extension.KindProvider]
112 if len(providers) != 1 || providers[0].ID != "openai/gpt-5" {
113 t.Fatalf("provider contributions = %+v", providers)
114 }
115 uiActions := byKind[extension.KindUIAction]
116 if len(uiActions) != 1 || uiActions[0].ID != "act1" {
117 t.Fatalf("ui action contributions = %+v", uiActions)
118 }
119 }
120
121 func TestManagerRequiredFailureFailsEverything(t *testing.T) {
122 home := t.TempDir()
123 installFakePlugin(t, home, "good-optional", nil)
124 installFakePlugin(t, home, "bad-required", func(rt *pluginpkg.RuntimeSpec) {
125 rt.Required = true
126 // v1 protocol is rejected by the v2 host.
127 rt.Env[fakeEnvInitResult] = `{"protocolVersion":"1","name":"bad","version":"1","stateSchemaVersion":0}`
128 })
129 manager, _, err := StartPackages(context.Background(), home, testSessionContext(), nil)
130 if err == nil {
131 t.Fatal("StartPackages succeeded with a broken required runtime")
132 }
133 var requiredErr *RequiredStartError
134 if !errors.As(err, &requiredErr) {
135 t.Fatalf("error %T is not a RequiredStartError", err)
136 }
137 if requiredErr.Plugin != "bad-required" {
138 t.Fatalf("RequiredStartError.Plugin = %q", requiredErr.Plugin)
139 }
140 if manager != nil {
141 t.Fatal("manager returned alongside the fatal error")
142 }
143 }
144
145 func TestManagerOptionalFailureWarnsAndContinues(t *testing.T) {
146 home := t.TempDir()
147 installFakePlugin(t, home, "bad-optional", func(rt *pluginpkg.RuntimeSpec) {
148 rt.Env[fakeEnvInitResult] = `{"protocolVersion":"1","name":"bad","version":"1","stateSchemaVersion":0}`
149 })
150 installFakePlugin(t, home, "good-optional", nil)
151 manager, warnings, err := StartPackages(context.Background(), home, testSessionContext(), nil)
152 if err != nil {
153 t.Fatalf("StartPackages: %v", err)
154 }
155 t.Cleanup(func() { _ = manager.Close() })
156 if len(warnings) != 1 || !strings.Contains(warnings[0], "bad-optional") {
157 t.Fatalf("warnings = %v", warnings)
158 }
159 if manager.Client("bad-optional") != nil {
160 t.Fatal("failed optional runtime has a client")
161 }
162 if manager.Client("good-optional") == nil {
163 t.Fatal("healthy optional runtime has no client")
164 }
165 }
166
167 func TestStartLoadedPackagesBoundsParallelismAndSharesCancellation(t *testing.T) {
168 packageCount := maxConcurrentPackageStarts + 2
169 packages := make([]pluginpkg.InstalledPackage, packageCount)
170 for i := range packages {
171 name := fmt.Sprintf("plugin-%02d", i)
172 packages[i] = pluginpkg.InstalledPackage{
173 Installed: pluginpkg.InstalledPlugin{Name: name, Enabled: true},
174 Package: pluginpkg.Package{Manifest: pluginpkg.Manifest{
175 Name: name,
176 Runtime: &pluginpkg.RuntimeSpec{
177 Command: "/not-started",
178 },
179 }},
180 }
181 }
182
183 ctx, cancel := context.WithCancel(context.Background())
184 defer cancel()
185 entered := make(chan string, packageCount)
186 var stateMu sync.Mutex
187 active, maxActive, started := 0, 0, 0
188 starter := func(ctx context.Context, opts ClientOptions) (*Client, error) {
189 stateMu.Lock()
190 active++
191 started++
192 if active > maxActive {
193 maxActive = active
194 }
195 stateMu.Unlock()
196 entered <- opts.Installed.Name
197 <-ctx.Done()
198 stateMu.Lock()
199 active--
200 stateMu.Unlock()
201 return nil, ctx.Err()
202 }
203
204 type startResult struct {
205 manager *Manager
206 warnings []string
207 err error
208 }
209 done := make(chan startResult, 1)
210 go func() {
211 manager, warnings, err := startLoadedPackages(ctx, packages, testSessionContext(), nil, starter)
212 done <- startResult{manager: manager, warnings: warnings, err: err}
213 }()
214
215 for i := range maxConcurrentPackageStarts {
216 select {
217 case <-entered:
218 case <-time.After(5 * time.Second):
219 t.Fatalf("only %d package starts entered the worker pool", i)
220 }
221 }
222 select {
223 case name := <-entered:
224 t.Fatalf("package %q exceeded the %d-start concurrency bound", name, maxConcurrentPackageStarts)
225 default:
226 }
227 cancel()
228
229 var result startResult
230 select {
231 case result = <-done:
232 case <-time.After(5 * time.Second):
233 t.Fatal("shared startup cancellation did not release the worker pool")
234 }
235 if result.err != nil {
236 t.Fatalf("optional startup failures returned a fatal error: %v", result.err)
237 }
238 if result.manager == nil || len(result.manager.Clients()) != 0 {
239 t.Fatalf("manager after cancelled optional starts = %#v", result.manager)
240 }
241 if len(result.warnings) != packageCount {
242 t.Fatalf("warnings = %d, want %d", len(result.warnings), packageCount)
243 }
244 for i, warning := range result.warnings {
245 if !strings.HasPrefix(warning, packages[i].Installed.Name+":") {
246 t.Fatalf("warning %d = %q, want deterministic package order", i, warning)
247 }
248 }
249 stateMu.Lock()
250 defer stateMu.Unlock()
251 if active != 0 || maxActive != maxConcurrentPackageStarts || started != maxConcurrentPackageStarts {
252 t.Fatalf("start counts active=%d max=%d started=%d, want 0/%d/%d", active, maxActive, started, maxConcurrentPackageStarts, maxConcurrentPackageStarts)
253 }
254 }
255
256 func TestManagerDisabledPackageNeverLaunches(t *testing.T) {
257 home := t.TempDir()
258 installFakePlugin(t, home, "disabled-one", nil)
259 if err := pluginpkg.SetEnabled(home, "disabled-one", false); err != nil {
260 t.Fatalf("SetEnabled: %v", err)
261 }
262 manager, warnings, err := StartPackages(context.Background(), home, testSessionContext(), nil)
263 if err != nil {
264 t.Fatalf("StartPackages: %v", err)
265 }
266 t.Cleanup(func() { _ = manager.Close() })
267 if len(warnings) != 0 {
268 t.Fatalf("warnings = %v", warnings)
269 }
270 if got := len(manager.Clients()); got != 0 {
271 t.Fatalf("disabled package produced %d clients", got)
272 }
273 }
274
275 func TestManagerCloseShutsEverythingDown(t *testing.T) {
276 home := t.TempDir()
277 installFakePlugin(t, home, "one", nil)
278 installFakePlugin(t, home, "two", func(rt *pluginpkg.RuntimeSpec) {
279 rt.Env[fakeEnvMode] = "ignore_shutdown" // force the kill path
280 })
281 manager, _, err := StartPackages(context.Background(), home, testSessionContext(), nil)
282 if err != nil {
283 t.Fatalf("StartPackages: %v", err)
284 }
285 clients := manager.Clients()
286 if len(clients) != 2 {
287 t.Fatalf("clients = %d, want 2", len(clients))
288 }
289 start := time.Now()
290 if err := manager.Close(); err != nil {
291 t.Fatalf("Close: %v", err)
292 }
293 if elapsed := time.Since(start); elapsed > 15*time.Second {
294 t.Fatalf("manager close took %s", elapsed)
295 }
296 for _, client := range clients {
297 if !client.Exited() {
298 t.Fatalf("client %s still running after manager close", client.PluginID())
299 }
300 }
301 if err := manager.Close(); err != nil {
302 t.Fatalf("second Close: %v", err)
303 }
304 }
305
306 // recordingBinder is a UIBinder test double: it records the per-plugin
307 // HandlerFor bindings and crash notifications StartPackages delivers.
308 type recordingBinder struct {
309 mu sync.Mutex
310 bound map[string]int
311 crashed map[string]int
312 }
313
314 func newRecordingBinder() *recordingBinder {
315 return &recordingBinder{bound: map[string]int{}, crashed: map[string]int{}}
316 }
317
318 func (b *recordingBinder) Publish(context.Context, protocol.UIPublishParams) (protocol.UIPublishResult, error) {
319 return protocol.UIPublishResult{}, &protocol.ProtocolError{Reason: protocol.ErrUnknownMethod, Message: "unbound"}
320 }
321
322 func (b *recordingBinder) Request(context.Context, protocol.UIRequestParams) (protocol.UIRequestResult, error) {
323 return protocol.UIRequestResult{}, &protocol.ProtocolError{Reason: protocol.ErrUnknownMethod, Message: "unbound"}
324 }
325
326 func (b *recordingBinder) HandlerFor(pluginID string) UIHandler {
327 b.mu.Lock()
328 defer b.mu.Unlock()
329 b.bound[pluginID]++
330 return bindingStub{}
331 }
332
333 func (b *recordingBinder) ClientCrashed(pluginID string) {
334 b.mu.Lock()
335 defer b.mu.Unlock()
336 b.crashed[pluginID]++
337 }
338
339 func (b *recordingBinder) boundCount(pluginID string) int {
340 b.mu.Lock()
341 defer b.mu.Unlock()
342 return b.bound[pluginID]
343 }
344
345 func (b *recordingBinder) crashedCount(pluginID string) int {
346 b.mu.Lock()
347 defer b.mu.Unlock()
348 return b.crashed[pluginID]
349 }
350
351 type bindingStub struct{}
352
353 func (bindingStub) Publish(context.Context, protocol.UIPublishParams) (protocol.UIPublishResult, error) {
354 return protocol.UIPublishResult{Accepted: true}, nil
355 }
356
357 func (bindingStub) Request(context.Context, protocol.UIRequestParams) (protocol.UIRequestResult, error) {
358 return protocol.UIRequestResult{Cancelled: true}, nil
359 }
360
361 // TestStartPackagesBindsUIHandlerPerPlugin proves the stage-8 wiring: a
362 // UIHandler implementing UIBinder receives one HandlerFor binding per started
363 // client (never the shared unbound handler), and a sidecar crash is reported
364 // through ClientCrashed.
365 func TestStartPackagesBindsUIHandlerPerPlugin(t *testing.T) {
366 home := t.TempDir()
367 installFakePlugin(t, home, "live", nil)
368 installFakePlugin(t, home, "doomed", func(rt *pluginpkg.RuntimeSpec) {
369 rt.Env[fakeEnvMode] = "crash_after_init"
370 })
371 binder := newRecordingBinder()
372 manager, _, err := StartPackages(context.Background(), home, testSessionContext(), binder)
373 if err != nil {
374 t.Fatalf("StartPackages: %v", err)
375 }
376 t.Cleanup(func() { _ = manager.Close() })
377
378 for _, pluginID := range []string{"doomed", "live"} {
379 if got := binder.boundCount(pluginID); got != 1 {
380 t.Fatalf("HandlerFor(%q) called %d times, want 1", pluginID, got)
381 }
382 }
383 // The doomed sidecar exits right after initialized: the host observes an
384 // unexpected EOF and reports the crash through the binder.
385 waitFor(t, "crash notification", 10*time.Second, func() bool {
386 return binder.crashedCount("doomed") == 1
387 })
388 if got := binder.crashedCount("live"); got != 0 {
389 t.Fatalf("ClientCrashed(live) called %d times, want 0", got)
390 }
391 }
392
392 lines GO