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
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
import { afterEach, describe, expect, it } from 'vitest';

import { SyncDescriptor } from '#/_base/di/descriptors';
import { AsyncEmitter, Emitter } from '#/_base/event';
import { IAgentPluginService } from '#/agent/plugin/agentPlugin';
import { AgentPluginService } from '#/agent/plugin/agentPluginService';
import { USER_PROMPT_ORIGIN } from '#/agent/contextMemory/types';
import { IAgentLoopService } from '#/agent/loop/loop';
import { IEventBus } from '#/app/event/eventBus';
import { TurnStarted } from '#/agent/loop/turnEvents';
import { IPluginService } from '#/app/plugin/plugin';
import type {
  EnabledPluginSessionStart,
  PluginMutationSummary,
  PluginReloadEvent,
} from '#/app/plugin/types';
import { InMemorySkillCatalog } from '#/features/skill/catalog/registry';
import { summarizeSkill } from '#/features/skill/catalog/types';
import type { SkillDefinition } from '#/features/skill/catalog/types';
import { ISessionSkillCatalog } from '#/features/skill/session/skillCatalog';

import { agentService, appService, createTestAgent, skillServices, type TestAgentContext } from '../../harness';
import { stubPluginService } from '../../app/plugin/stubs';

function pluginSkill(): SkillDefinition {
  return {
    name: 'demo-skill',
    description: 'A plugin skill',
    path: '/plugins/demo/skills/demo-skill/SKILL.md',
    dir: '/plugins/demo/skills/demo-skill',
    content: 'Do the demo thing.',
    metadata: {},
    source: 'extra',
    plugin: { id: 'demo', instructions: 'Always be helpful.' },
  };
}

function findPluginSessionStartEventMessages(ctx: TestAgentContext) {
  return ctx.contextData().history.filter(
    (message) =>
      message.origin?.kind === 'injection' && message.origin.variant === 'plugin_session_start',
  );
}

function messageText(message: { readonly content: readonly { readonly type: string; readonly text?: string }[] }): string {
  return message.content.map((part) => (part.type === 'text' ? (part.text ?? '') : '')).join('');
}

async function runInjectionBoundary(ctx: TestAgentContext): Promise<void> {
  await ctx.restorePersisted();
  await ctx.get(IAgentLoopService).hooks.onWillBeginStep.run({
    turnId: 0,
    step: 1,
    firstStepOfTurn: true,
    signal: new AbortController().signal,
  });
}

describe('AgentPluginService plugin session-start wiring', () => {
  let ctx: TestAgentContext | undefined;

  afterEach(async () => {
    if (ctx !== undefined) await ctx.dispose();
    ctx = undefined;
  });

  it('injects the plugin session-start reminder through the real service registration', async () => {
    const catalog = new InMemorySkillCatalog();
    catalog.register(pluginSkill());

    ctx = createTestAgent(
      { autoConfigure: true },
      appService(
        IPluginService,
        stubPluginService({ sessionStarts: [{ pluginId: 'demo', skillName: 'demo-skill' }] }),
      ),
      skillServices(catalog),
      agentService(
        IAgentPluginService,
        new SyncDescriptor(AgentPluginService),
      ),
    );

    ctx.get(IAgentPluginService);

    await runInjectionBoundary(ctx);

    const injected = findPluginSessionStartEventMessages(ctx).at(-1);
    expect(injected).toBeDefined();
    const text = injected === undefined ? '' : messageText(injected);
    expect(text).toContain('<plugin_session_start plugin="demo" skill="demo-skill">');
    expect(text).toContain('Do the demo thing.');
    expect(text).toContain('Always be helpful.');
  });

  it('does not re-inject the plugin session-start reminder on later turns while it remains live', async () => {
    const catalog = new InMemorySkillCatalog();
    catalog.register(pluginSkill());

    ctx = createTestAgent(
      { autoConfigure: true },
      appService(
        IPluginService,
        stubPluginService({ sessionStarts: [{ pluginId: 'demo', skillName: 'demo-skill' }] }),
      ),
      skillServices(catalog),
      agentService(
        IAgentPluginService,
        new SyncDescriptor(AgentPluginService),
      ),
    );

    ctx.get(IAgentPluginService);

    await runInjectionBoundary(ctx);
    ctx.get(IEventBus).publish(
      new TurnStarted({ agentId: 'main', turnId: 2, origin: USER_PROMPT_ORIGIN }),
    );
    await runInjectionBoundary(ctx);

    expect(findPluginSessionStartEventMessages(ctx)).toHaveLength(1);
  });

  it('refreshes the frozen session-start guidance through the explicit service path', async () => {
    const catalog = new InMemorySkillCatalog();
    catalog.register(pluginSkill());

    ctx = createTestAgent(
      { autoConfigure: true },
      appService(
        IPluginService,
        stubPluginService({
          sessionStarts: [{ pluginId: 'demo', skillName: 'demo-skill' }],
        }),
      ),
      skillServices(catalog),
      agentService(IAgentPluginService, new SyncDescriptor(AgentPluginService)),
    );

    const plugins = ctx.get(IAgentPluginService);
    await runInjectionBoundary(ctx);
    expect(messageText(findPluginSessionStartEventMessages(ctx).at(-1)!)).toContain(
      'Do the demo thing.',
    );

    catalog.register(
      { ...pluginSkill(), content: 'Do the explicitly refreshed demo thing.' },
      { replace: true },
    );
    await plugins.refreshSessionStart();

    const messages = findPluginSessionStartEventMessages(ctx);
    expect(messages).toHaveLength(2);
    expect(messageText(messages.at(-1)!)).toContain(
      'Do the explicitly refreshed demo thing.',
    );
    expect(messageText(messages.at(-1)!)).toContain(
      'supersedes any earlier plugin_session_start reminder',
    );
  });

  it('does not inject when no plugin session starts are enabled', async () => {
    const catalog = new InMemorySkillCatalog();
    catalog.register(pluginSkill());

    ctx = createTestAgent(
      { autoConfigure: true },
      appService(IPluginService, stubPluginService({ sessionStarts: [] })),
      skillServices(catalog),
      agentService(
        IAgentPluginService,
        new SyncDescriptor(AgentPluginService),
      ),
    );

    ctx.get(IAgentPluginService);

    await runInjectionBoundary(ctx);

    expect(findPluginSessionStartEventMessages(ctx)).toHaveLength(0);
  });

  it('re-appends a fresh reminder when the plugin skill source finishes refreshing', async () => {
    const catalog = new InMemorySkillCatalog();
    catalog.register(pluginSkill());
    const sinkChange = new Emitter<string>();
    const skillCatalog: ISessionSkillCatalog = {
      _serviceBrand: undefined,
      catalog,
      ready: Promise.resolve(),
      onDidChange: sinkChange.event,
      load: async () => {},
      reload: async () => {},
      list: async () => catalog.listSkills().map(summarizeSkill),
    };

    ctx = createTestAgent(
      { autoConfigure: true },
      appService(
        IPluginService,
        stubPluginService({
          sessionStarts: [{ pluginId: 'demo', skillName: 'demo-skill' }],
        }),
      ),
      skillServices(skillCatalog),
      agentService(
        IAgentPluginService,
        new SyncDescriptor(AgentPluginService),
      ),
    );

    ctx.get(IAgentPluginService);

    await runInjectionBoundary(ctx);

    expect(findPluginSessionStartEventMessages(ctx)).toHaveLength(1);

    sinkChange.fire('plugin');
    expect(findPluginSessionStartEventMessages(ctx)).toHaveLength(1);
    await runInjectionBoundary(ctx);

    const messages = findPluginSessionStartEventMessages(ctx);
    expect(messages.length).toBeGreaterThanOrEqual(2);
    const latest = messageText(messages.at(-1)!);
    expect(latest).toContain('<plugin_session_start plugin="demo" skill="demo-skill">');
    expect(latest).toContain('supersedes any earlier plugin_session_start reminder');
    sinkChange.dispose();
  });

  it('appends only for the plugin source when unrelated and plugin changes arrive together', async () => {
    const catalog = new InMemorySkillCatalog();
    catalog.register(pluginSkill());
    const sinkChange = new Emitter<string>();
    const skillCatalog: ISessionSkillCatalog = {
      _serviceBrand: undefined,
      catalog,
      ready: Promise.resolve(),
      onDidChange: sinkChange.event,
      load: async () => {},
      reload: async () => {},
      list: async () => catalog.listSkills().map(summarizeSkill),
    };

    ctx = createTestAgent(
      { autoConfigure: true },
      appService(
        IPluginService,
        stubPluginService({
          sessionStarts: [{ pluginId: 'demo', skillName: 'demo-skill' }],
        }),
      ),
      skillServices(skillCatalog),
      agentService(
        IAgentPluginService,
        new SyncDescriptor(AgentPluginService),
      ),
    );

    ctx.get(IAgentPluginService);

    await runInjectionBoundary(ctx);
    expect(findPluginSessionStartEventMessages(ctx)).toHaveLength(1);

    sinkChange.fire('user');
    sinkChange.fire('plugin');
    await runInjectionBoundary(ctx);

    expect(findPluginSessionStartEventMessages(ctx)).toHaveLength(2);
    sinkChange.dispose();
  });

  it('reconciles the current plugin guidance after undo removes its latest render', async () => {
    const catalog = new InMemorySkillCatalog();
    catalog.register(pluginSkill());
    const sinkChange = new Emitter<string>();
    const skillCatalog: ISessionSkillCatalog = {
      _serviceBrand: undefined,
      catalog,
      ready: Promise.resolve(),
      onDidChange: sinkChange.event,
      load: async () => {},
      reload: async () => {},
      list: async () => catalog.listSkills().map(summarizeSkill),
    };

    ctx = createTestAgent(
      { autoConfigure: true },
      appService(
        IPluginService,
        stubPluginService({
          sessionStarts: [{ pluginId: 'demo', skillName: 'demo-skill' }],
        }),
      ),
      skillServices(skillCatalog),
      agentService(IAgentPluginService, new SyncDescriptor(AgentPluginService)),
    );
    ctx.get(IAgentPluginService);
    await ctx.restorePersisted();

    ctx.mockNextResponse({ type: 'text', text: 'first answer' });
    await ctx.rpc.prompt({ input: [{ type: 'text', text: 'first prompt' }] });
    await ctx.untilTurnEnd();

    catalog.register(
      { ...pluginSkill(), content: 'Do the updated demo thing.' },
      { replace: true },
    );
    sinkChange.fire('plugin');
    ctx.mockNextResponse({ type: 'text', text: 'second answer' });
    await ctx.rpc.prompt({ input: [{ type: 'text', text: 'second prompt' }] });
    await ctx.untilTurnEnd();

    await ctx.undoHistory(1);
    ctx.mockNextResponse({ type: 'text', text: 'third answer' });
    await ctx.rpc.prompt({ input: [{ type: 'text', text: 'third prompt' }] });
    await ctx.untilTurnEnd();

    const latest = findPluginSessionStartEventMessages(ctx).at(-1);
    expect(latest).toBeDefined();
    expect(messageText(latest!)).toContain('Do the updated demo thing.');
    expect(messageText(latest!)).toContain(
      'supersedes any earlier plugin_session_start reminder',
    );
    sinkChange.dispose();
  });
});

describe('AgentPluginService plugin-change reminder', () => {
  let ctx: TestAgentContext | undefined;

  afterEach(async () => {
    if (ctx !== undefined) await ctx.dispose();
    ctx = undefined;
  });

  function findPluginChangeMessages(context: TestAgentContext) {
    return context.contextData().history.filter(
      (message) =>
        message.origin?.kind === 'injection' && message.origin.variant === 'plugin_change',
    );
  }

  it('appends a plugin_change system reminder when the plugin set mutates', async () => {
    const mutateEmitter = new Emitter<PluginMutationSummary>();
    ctx = createTestAgent(
      { autoConfigure: true },
      appService(IPluginService, stubPluginService({ sessionStarts: [], mutateEmitter })),
      skillServices(new InMemorySkillCatalog()),
      agentService(IAgentPluginService, new SyncDescriptor(AgentPluginService)),
    );
    ctx.get(IAgentPluginService);

    mutateEmitter.fire({
      added: [],
      removed: [],
      errors: [],
      mutation: { kind: 'enable', id: 'demo' },
    });

    const messages = findPluginChangeMessages(ctx);
    expect(messages).toHaveLength(1);
    expect(messageText(messages[0]!)).toContain('Plugin "demo" was enabled.');
    expect(messageText(messages[0]!)).toContain('run /new or /reload to apply the change');
    mutateEmitter.dispose();
  });

  it('does not append the plugin_change reminder on an explicit reload', async () => {
    const reloadEmitter = new AsyncEmitter<PluginReloadEvent>();
    ctx = createTestAgent(
      { autoConfigure: true },
      appService(IPluginService, stubPluginService({ sessionStarts: [], reloadEmitter })),
      skillServices(new InMemorySkillCatalog()),
      agentService(IAgentPluginService, new SyncDescriptor(AgentPluginService)),
    );
    ctx.get(IAgentPluginService);

    await reloadEmitter.fireAsyncConcurrent(
      { added: [], removed: [], errors: [] },
      new AbortController().signal,
    );

    expect(findPluginChangeMessages(ctx)).toHaveLength(0);
    reloadEmitter.dispose();
  });

  function skillCatalogWithChange(catalog: InMemorySkillCatalog, change: Emitter<string>) {
    const skillCatalog: ISessionSkillCatalog = {
      _serviceBrand: undefined,
      catalog,
      ready: Promise.resolve(),
      onDidChange: change.event,
      load: async () => {},
      reload: async () => {},
      list: async () => catalog.listSkills().map(summarizeSkill),
    };
    return skillCatalog;
  }

  function fireMutation(mutateEmitter: Emitter<PluginMutationSummary>, id: string): void {
    mutateEmitter.fire({
      added: [],
      removed: [],
      errors: [],
      mutation: { kind: 'install', id },
    });
  }

  it('suppresses the session-start refresh for mutation-driven catalog changes', async () => {
    const catalog = new InMemorySkillCatalog();
    catalog.register(pluginSkill());
    const sinkChange = new Emitter<string>();
    const mutateEmitter = new Emitter<PluginMutationSummary>();
    let sessionStarts: readonly EnabledPluginSessionStart[] = [
      { pluginId: 'demo', skillName: 'demo-skill' },
    ];
    ctx = createTestAgent(
      { autoConfigure: true },
      appService(
        IPluginService,
        {
          ...stubPluginService({ sessionStarts, mutateEmitter }),
          enabledSessionStarts: async () => sessionStarts,
        },
      ),
      skillServices(skillCatalogWithChange(catalog, sinkChange)),
      agentService(IAgentPluginService, new SyncDescriptor(AgentPluginService)),
    );
    ctx.get(IAgentPluginService);
    await runInjectionBoundary(ctx);
    expect(findPluginSessionStartEventMessages(ctx)).toHaveLength(1);

    fireMutation(mutateEmitter, 'demo');
    sessionStarts = [];
    sinkChange.fire('plugin');
    await runInjectionBoundary(ctx);

    expect(findPluginChangeMessages(ctx)).toHaveLength(1);
    expect(findPluginSessionStartEventMessages(ctx)).toHaveLength(1);

    sinkChange.fire('plugin');
    await runInjectionBoundary(ctx);
    expect(findPluginSessionStartEventMessages(ctx).length).toBeGreaterThanOrEqual(2);

    sinkChange.dispose();
    mutateEmitter.dispose();
  });

  it('suppresses one session-start refresh per mutation when mutations arrive back to back', async () => {
    const catalog = new InMemorySkillCatalog();
    catalog.register(pluginSkill());
    const sinkChange = new Emitter<string>();
    const mutateEmitter = new Emitter<PluginMutationSummary>();
    ctx = createTestAgent(
      { autoConfigure: true },
      appService(
        IPluginService,
        stubPluginService({
          sessionStarts: [{ pluginId: 'demo', skillName: 'demo-skill' }],
          mutateEmitter,
        }),
      ),
      skillServices(skillCatalogWithChange(catalog, sinkChange)),
      agentService(IAgentPluginService, new SyncDescriptor(AgentPluginService)),
    );
    ctx.get(IAgentPluginService);
    await runInjectionBoundary(ctx);
    expect(findPluginSessionStartEventMessages(ctx)).toHaveLength(1);

    fireMutation(mutateEmitter, 'demo');
    fireMutation(mutateEmitter, 'demo');
    sinkChange.fire('plugin');
    sinkChange.fire('plugin');
    await new Promise((resolve) => setTimeout(resolve, 0));

    expect(findPluginChangeMessages(ctx)).toHaveLength(2);
    expect(findPluginSessionStartEventMessages(ctx)).toHaveLength(1);

    sinkChange.dispose();
    mutateEmitter.dispose();
  });
});