返回 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.ManifestAPIVersionV1,
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":"1","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 rt.Env[fakeEnvInitResult] = `{"protocolVersion":"2","name":"bad","version":"1","stateSchemaVersion":0}`
127 })
128 manager, _, err := StartPackages(context.Background(), home, testSessionContext(), nil)
129 if err == nil {
130 t.Fatal("StartPackages succeeded with a broken required runtime")
131 }
132 var requiredErr *RequiredStartError
133 if !errors.As(err, &requiredErr) {
134 t.Fatalf("error %T is not a RequiredStartError", err)
135 }
136 if requiredErr.Plugin != "bad-required" {
137 t.Fatalf("RequiredStartError.Plugin = %q", requiredErr.Plugin)
138 }
139 if manager != nil {
140 t.Fatal("manager returned alongside the fatal error")
141 }
142 }
143
144 func TestManagerOptionalFailureWarnsAndContinues(t *testing.T) {
145 home := t.TempDir()
146 installFakePlugin(t, home, "bad-optional", func(rt *pluginpkg.RuntimeSpec) {
147 rt.Env[fakeEnvInitResult] = `{"protocolVersion":"2","name":"bad","version":"1","stateSchemaVersion":0}`
148 })
149 installFakePlugin(t, home, "good-optional", nil)
150 manager, warnings, err := StartPackages(context.Background(), home, testSessionContext(), nil)
151 if err != nil {
152 t.Fatalf("StartPackages: %v", err)
153 }
154 t.Cleanup(func() { _ = manager.Close() })
155 if len(warnings) != 1 || !strings.Contains(warnings[0], "bad-optional") {
156 t.Fatalf("warnings = %v", warnings)
157 }
158 if manager.Client("bad-optional") != nil {
159 t.Fatal("failed optional runtime has a client")
160 }
161 if manager.Client("good-optional") == nil {
162 t.Fatal("healthy optional runtime has no client")
163 }
164 }
165
166 func TestStartLoadedPackagesBoundsParallelismAndSharesCancellation(t *testing.T) {
167 packageCount := maxConcurrentPackageStarts + 2
168 packages := make([]pluginpkg.InstalledPackage, packageCount)
169 for i := range packages {
170 name := fmt.Sprintf("plugin-%02d", i)
171 packages[i] = pluginpkg.InstalledPackage{
172 Installed: pluginpkg.InstalledPlugin{Name: name, Enabled: true},
173 Package: pluginpkg.Package{Manifest: pluginpkg.Manifest{
174 Name: name,
175 Runtime: &pluginpkg.RuntimeSpec{
176 Command: "/not-started",
177 },
178 }},
179 }
180 }
181
182 ctx, cancel := context.WithCancel(context.Background())
183 defer cancel()
184 entered := make(chan string, packageCount)
185 var stateMu sync.Mutex
186 active, maxActive, started := 0, 0, 0
187 starter := func(ctx context.Context, opts ClientOptions) (*Client, error) {
188 stateMu.Lock()
189 active++
190 started++
191 if active > maxActive {
192 maxActive = active
193 }
194 stateMu.Unlock()
195 entered <- opts.Installed.Name
196 <-ctx.Done()
197 stateMu.Lock()
198 active--
199 stateMu.Unlock()
200 return nil, ctx.Err()
201 }
202
203 type startResult struct {
204 manager *Manager
205 warnings []string
206 err error
207 }
208 done := make(chan startResult, 1)
209 go func() {
210 manager, warnings, err := startLoadedPackages(ctx, packages, testSessionContext(), nil, starter)
211 done <- startResult{manager: manager, warnings: warnings, err: err}
212 }()
213
214 for i := 0; i < maxConcurrentPackageStarts; i++ {
215 select {
216 case <-entered:
217 case <-time.After(5 * time.Second):
218 t.Fatalf("only %d package starts entered the worker pool", i)
219 }
220 }
221 select {
222 case name := <-entered:
223 t.Fatalf("package %q exceeded the %d-start concurrency bound", name, maxConcurrentPackageStarts)
224 default:
225 }
226 cancel()
227
228 var result startResult
229 select {
230 case result = <-done:
231 case <-time.After(5 * time.Second):
232 t.Fatal("shared startup cancellation did not release the worker pool")
233 }
234 if result.err != nil {
235 t.Fatalf("optional startup failures returned a fatal error: %v", result.err)
236 }
237 if result.manager == nil || len(result.manager.Clients()) != 0 {
238 t.Fatalf("manager after cancelled optional starts = %#v", result.manager)
239 }
240 if len(result.warnings) != packageCount {
241 t.Fatalf("warnings = %d, want %d", len(result.warnings), packageCount)
242 }
243 for i, warning := range result.warnings {
244 if !strings.HasPrefix(warning, packages[i].Installed.Name+":") {
245 t.Fatalf("warning %d = %q, want deterministic package order", i, warning)
246 }
247 }
248 stateMu.Lock()
249 defer stateMu.Unlock()
250 if active != 0 || maxActive != maxConcurrentPackageStarts || started != maxConcurrentPackageStarts {
251 t.Fatalf("start counts active=%d max=%d started=%d, want 0/%d/%d", active, maxActive, started, maxConcurrentPackageStarts, maxConcurrentPackageStarts)
252 }
253 }
254
255 func TestManagerDisabledPackageNeverLaunches(t *testing.T) {
256 home := t.TempDir()
257 installFakePlugin(t, home, "disabled-one", nil)
258 if err := pluginpkg.SetEnabled(home, "disabled-one", false); err != nil {
259 t.Fatalf("SetEnabled: %v", err)
260 }
261 manager, warnings, err := StartPackages(context.Background(), home, testSessionContext(), nil)
262 if err != nil {
263 t.Fatalf("StartPackages: %v", err)
264 }
265 t.Cleanup(func() { _ = manager.Close() })
266 if len(warnings) != 0 {
267 t.Fatalf("warnings = %v", warnings)
268 }
269 if got := len(manager.Clients()); got != 0 {
270 t.Fatalf("disabled package produced %d clients", got)
271 }
272 }
273
274 func TestManagerCloseShutsEverythingDown(t *testing.T) {
275 home := t.TempDir()
276 installFakePlugin(t, home, "one", nil)
277 installFakePlugin(t, home, "two", func(rt *pluginpkg.RuntimeSpec) {
278 rt.Env[fakeEnvMode] = "ignore_shutdown" // force the kill path
279 })
280 manager, _, err := StartPackages(context.Background(), home, testSessionContext(), nil)
281 if err != nil {
282 t.Fatalf("StartPackages: %v", err)
283 }
284 clients := manager.Clients()
285 if len(clients) != 2 {
286 t.Fatalf("clients = %d, want 2", len(clients))
287 }
288 start := time.Now()
289 if err := manager.Close(); err != nil {
290 t.Fatalf("Close: %v", err)
291 }
292 if elapsed := time.Since(start); elapsed > 15*time.Second {
293 t.Fatalf("manager close took %s", elapsed)
294 }
295 for _, client := range clients {
296 if !client.Exited() {
297 t.Fatalf("client %s still running after manager close", client.PluginID())
298 }
299 }
300 if err := manager.Close(); err != nil {
301 t.Fatalf("second Close: %v", err)
302 }
303 }
304
305 // recordingBinder is a UIBinder test double: it records the per-plugin
306 // HandlerFor bindings and crash notifications StartPackages delivers.
307 type recordingBinder struct {
308 mu sync.Mutex
309 bound map[string]int
310 crashed map[string]int
311 }
312
313 func newRecordingBinder() *recordingBinder {
314 return &recordingBinder{bound: map[string]int{}, crashed: map[string]int{}}
315 }
316
317 func (b *recordingBinder) Publish(context.Context, protocol.UIPublishParams) (protocol.UIPublishResult, error) {
318 return protocol.UIPublishResult{}, &protocol.ProtocolError{Reason: protocol.ErrUnknownMethod, Message: "unbound"}
319 }
320
321 func (b *recordingBinder) Request(context.Context, protocol.UIRequestParams) (protocol.UIRequestResult, error) {
322 return protocol.UIRequestResult{}, &protocol.ProtocolError{Reason: protocol.ErrUnknownMethod, Message: "unbound"}
323 }
324
325 func (b *recordingBinder) HandlerFor(pluginID string) UIHandler {
326 b.mu.Lock()
327 defer b.mu.Unlock()
328 b.bound[pluginID]++
329 return bindingStub{}
330 }
331
332 func (b *recordingBinder) ClientCrashed(pluginID string) {
333 b.mu.Lock()
334 defer b.mu.Unlock()
335 b.crashed[pluginID]++
336 }
337
338 func (b *recordingBinder) boundCount(pluginID string) int {
339 b.mu.Lock()
340 defer b.mu.Unlock()
341 return b.bound[pluginID]
342 }
343
344 func (b *recordingBinder) crashedCount(pluginID string) int {
345 b.mu.Lock()
346 defer b.mu.Unlock()
347 return b.crashed[pluginID]
348 }
349
350 type bindingStub struct{}
351
352 func (bindingStub) Publish(context.Context, protocol.UIPublishParams) (protocol.UIPublishResult, error) {
353 return protocol.UIPublishResult{Accepted: true}, nil
354 }
355
356 func (bindingStub) Request(context.Context, protocol.UIRequestParams) (protocol.UIRequestResult, error) {
357 return protocol.UIRequestResult{Cancelled: true}, nil
358 }
359
360 // TestStartPackagesBindsUIHandlerPerPlugin proves the stage-8 wiring: a
361 // UIHandler implementing UIBinder receives one HandlerFor binding per started
362 // client (never the shared unbound handler), and a sidecar crash is reported
363 // through ClientCrashed.
364 func TestStartPackagesBindsUIHandlerPerPlugin(t *testing.T) {
365 home := t.TempDir()
366 installFakePlugin(t, home, "live", nil)
367 installFakePlugin(t, home, "doomed", func(rt *pluginpkg.RuntimeSpec) {
368 rt.Env[fakeEnvMode] = "crash_after_init"
369 })
370 binder := newRecordingBinder()
371 manager, _, err := StartPackages(context.Background(), home, testSessionContext(), binder)
372 if err != nil {
373 t.Fatalf("StartPackages: %v", err)
374 }
375 t.Cleanup(func() { _ = manager.Close() })
376
377 for _, pluginID := range []string{"doomed", "live"} {
378 if got := binder.boundCount(pluginID); got != 1 {
379 t.Fatalf("HandlerFor(%q) called %d times, want 1", pluginID, got)
380 }
381 }
382 // The doomed sidecar exits right after initialized: the host observes an
383 // unexpected EOF and reports the crash through the binder.
384 waitFor(t, "crash notification", 10*time.Second, func() bool {
385 return binder.crashedCount("doomed") == 1
386 })
387 if got := binder.crashedCount("live"); got != 0 {
388 t.Fatalf("ClientCrashed(live) called %d times, want 0", got)
389 }
390 }
391
391 lines GO