@pi-in-go/pigpen-ahp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (304) hide show
  1. package/CREDITS.md +27 -0
  2. package/LICENSE +23 -0
  3. package/README.md +148 -0
  4. package/extensions/ahp/access_options_test.go +116 -0
  5. package/extensions/ahp/extension.go +54 -0
  6. package/extensions/ahp/go.mod +12 -0
  7. package/extensions/ahp/go.sum +2 -0
  8. package/extensions/ahp/go.work +8 -0
  9. package/extensions/ahp/internal/channels/chat.go +110 -0
  10. package/extensions/ahp/internal/channels/root.go +32 -0
  11. package/extensions/ahp/internal/channels/session.go +128 -0
  12. package/extensions/ahp/internal/channels/session_test.go +108 -0
  13. package/extensions/ahp/internal/compose/compose.go +153 -0
  14. package/extensions/ahp/internal/compose/compose_test.go +120 -0
  15. package/extensions/ahp/internal/gaps/gaps_test.go +88 -0
  16. package/extensions/ahp/internal/host/handshake_test.go +206 -0
  17. package/extensions/ahp/internal/host/host.go +1305 -0
  18. package/extensions/ahp/internal/host/reconnect_test.go +197 -0
  19. package/extensions/ahp/internal/host/replaywindow_test.go +31 -0
  20. package/extensions/ahp/internal/host/schema_test.go +79 -0
  21. package/extensions/ahp/internal/host/store.go +291 -0
  22. package/extensions/ahp/internal/host/store_update_test.go +85 -0
  23. package/extensions/ahp/internal/host/subscriptions_test.go +160 -0
  24. package/extensions/ahp/internal/host/surface_test.go +95 -0
  25. package/extensions/ahp/internal/host/workarounds.go +458 -0
  26. package/extensions/ahp/internal/host/workarounds_test.go +96 -0
  27. package/extensions/ahp/internal/live/live.go +328 -0
  28. package/extensions/ahp/internal/live/live_test.go +91 -0
  29. package/extensions/ahp/internal/live/store.go +113 -0
  30. package/extensions/ahp/internal/mapper/activity.go +199 -0
  31. package/extensions/ahp/internal/mapper/activity_test.go +188 -0
  32. package/extensions/ahp/internal/mapper/bench_test.go +38 -0
  33. package/extensions/ahp/internal/mapper/event_mapper_test.go +380 -0
  34. package/extensions/ahp/internal/mapper/fixtures_test.go +387 -0
  35. package/extensions/ahp/internal/mapper/helpers_test.go +251 -0
  36. package/extensions/ahp/internal/mapper/js.go +131 -0
  37. package/extensions/ahp/internal/mapper/mapper.go +600 -0
  38. package/extensions/ahp/internal/mapper/message_input_test.go +196 -0
  39. package/extensions/ahp/internal/mapper/messageinput.go +272 -0
  40. package/extensions/ahp/internal/mapper/schema_helpers_test.go +5 -0
  41. package/extensions/ahp/internal/mapper/testdata/LICENSE-pi-ahp +21 -0
  42. package/extensions/ahp/internal/mapper/testdata/fixtures/abort.json +711 -0
  43. package/extensions/ahp/internal/mapper/testdata/fixtures/bash-long-output.json +1312 -0
  44. package/extensions/ahp/internal/mapper/testdata/fixtures/compaction.json +6285 -0
  45. package/extensions/ahp/internal/mapper/testdata/fixtures/parallel-tools.json +2622 -0
  46. package/extensions/ahp/internal/mapper/testdata/fixtures/plain-text.json +1856 -0
  47. package/extensions/ahp/internal/mapper/testdata/fixtures/single-tool.json +1128 -0
  48. package/extensions/ahp/internal/mapper/testdata/fixtures/steering.json +3926 -0
  49. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-bash.json +2372 -0
  50. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-edit.json +3983 -0
  51. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-error.json +2850 -0
  52. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-find.json +1162 -0
  53. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-grep.json +2783 -0
  54. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-loop.json +1693 -0
  55. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-ls.json +2427 -0
  56. package/extensions/ahp/internal/mapper/testdata/fixtures/tool-write.json +1271 -0
  57. package/extensions/ahp/internal/mapper/title.go +34 -0
  58. package/extensions/ahp/internal/mapper/usermsg.go +87 -0
  59. package/extensions/ahp/internal/pi/activeturn_test.go +296 -0
  60. package/extensions/ahp/internal/pi/backend.go +64 -0
  61. package/extensions/ahp/internal/pi/catalogue.go +370 -0
  62. package/extensions/ahp/internal/pi/catalogue_test.go +271 -0
  63. package/extensions/ahp/internal/pi/chatdriver.go +533 -0
  64. package/extensions/ahp/internal/pi/chatdriver_test.go +416 -0
  65. package/extensions/ahp/internal/pi/clientactions.go +212 -0
  66. package/extensions/ahp/internal/pi/clientactions_test.go +273 -0
  67. package/extensions/ahp/internal/pi/completions.go +230 -0
  68. package/extensions/ahp/internal/pi/completions_test.go +272 -0
  69. package/extensions/ahp/internal/pi/config_test.go +269 -0
  70. package/extensions/ahp/internal/pi/deletesession.go +69 -0
  71. package/extensions/ahp/internal/pi/deletesession_test.go +153 -0
  72. package/extensions/ahp/internal/pi/disposal_test.go +362 -0
  73. package/extensions/ahp/internal/pi/fixture_test.go +308 -0
  74. package/extensions/ahp/internal/pi/foreign_test.go +122 -0
  75. package/extensions/ahp/internal/pi/harness_test.go +83 -0
  76. package/extensions/ahp/internal/pi/history.go +269 -0
  77. package/extensions/ahp/internal/pi/hydrated_test.go +171 -0
  78. package/extensions/ahp/internal/pi/hydratedlifecycle_test.go +196 -0
  79. package/extensions/ahp/internal/pi/hydration_test.go +209 -0
  80. package/extensions/ahp/internal/pi/hydrator.go +212 -0
  81. package/extensions/ahp/internal/pi/imageinput.go +224 -0
  82. package/extensions/ahp/internal/pi/imageinput_test.go +57 -0
  83. package/extensions/ahp/internal/pi/lifecycle_test.go +381 -0
  84. package/extensions/ahp/internal/pi/models.go +212 -0
  85. package/extensions/ahp/internal/pi/models_test.go +128 -0
  86. package/extensions/ahp/internal/pi/paging.go +95 -0
  87. package/extensions/ahp/internal/pi/pagingtruncate_test.go +323 -0
  88. package/extensions/ahp/internal/pi/projecttrust.go +222 -0
  89. package/extensions/ahp/internal/pi/registry.go +924 -0
  90. package/extensions/ahp/internal/pi/restart_test.go +185 -0
  91. package/extensions/ahp/internal/pi/services.go +70 -0
  92. package/extensions/ahp/internal/pi/sessionconfig.go +64 -0
  93. package/extensions/ahp/internal/pi/sessionfiles_test.go +74 -0
  94. package/extensions/ahp/internal/pi/sessionstore.go +83 -0
  95. package/extensions/ahp/internal/pi/summary_test.go +426 -0
  96. package/extensions/ahp/internal/pi/workarounds_wire_test.go +208 -0
  97. package/extensions/ahp/internal/pisession/fromentries_test.go +32 -0
  98. package/extensions/ahp/internal/pisession/json.go +31 -0
  99. package/extensions/ahp/internal/pisession/pisession.go +580 -0
  100. package/extensions/ahp/internal/settings/access.go +63 -0
  101. package/extensions/ahp/internal/settings/access_test.go +52 -0
  102. package/extensions/ahp/internal/settings/settings.go +117 -0
  103. package/extensions/ahp/internal/settings/settings_test.go +104 -0
  104. package/extensions/ahp/internal/svc/etag_other.go +15 -0
  105. package/extensions/ahp/internal/svc/etag_unix.go +34 -0
  106. package/extensions/ahp/internal/svc/glob.go +197 -0
  107. package/extensions/ahp/internal/svc/mime.go +37 -0
  108. package/extensions/ahp/internal/svc/paths.go +108 -0
  109. package/extensions/ahp/internal/svc/pty.go +64 -0
  110. package/extensions/ahp/internal/svc/pty_darwin.go +42 -0
  111. package/extensions/ahp/internal/svc/pty_linux.go +36 -0
  112. package/extensions/ahp/internal/svc/pty_other.go +9 -0
  113. package/extensions/ahp/internal/svc/pty_test.go +114 -0
  114. package/extensions/ahp/internal/svc/pty_unix.go +147 -0
  115. package/extensions/ahp/internal/svc/resource.go +495 -0
  116. package/extensions/ahp/internal/svc/resource_test.go +501 -0
  117. package/extensions/ahp/internal/svc/stat_bsd.go +9 -0
  118. package/extensions/ahp/internal/svc/stat_linux.go +9 -0
  119. package/extensions/ahp/internal/svc/terminal.go +454 -0
  120. package/extensions/ahp/internal/svc/terminal_test.go +512 -0
  121. package/extensions/ahp/internal/svc/watch.go +590 -0
  122. package/extensions/ahp/internal/svc/watch_test.go +627 -0
  123. package/extensions/ahp/internal/svc/watchevents_test.go +452 -0
  124. package/extensions/ahp/internal/svc/watchpolicy.go +81 -0
  125. package/extensions/ahp/internal/svc/watchpolicy_test.go +151 -0
  126. package/extensions/ahp/internal/svc/watchracy_test.go +61 -0
  127. package/extensions/ahp/internal/testkit/schema/LICENSE-agent-host-protocol +21 -0
  128. package/extensions/ahp/internal/testkit/schema/actions.schema.json +9208 -0
  129. package/extensions/ahp/internal/testkit/schema/commands.schema.json +10862 -0
  130. package/extensions/ahp/internal/testkit/schema/errors.schema.json +10928 -0
  131. package/extensions/ahp/internal/testkit/schema/notifications.schema.json +6667 -0
  132. package/extensions/ahp/internal/testkit/schema/state.schema.json +6392 -0
  133. package/extensions/ahp/internal/testkit/schema.go +360 -0
  134. package/extensions/ahp/internal/testkit/testkit.go +367 -0
  135. package/extensions/ahp/internal/twin/twin.go +27 -0
  136. package/extensions/ahp/internal/wire/dispatchable.go +106 -0
  137. package/extensions/ahp/internal/wire/dispatchable_list.go +15 -0
  138. package/extensions/ahp/internal/wire/helpers_test.go +5 -0
  139. package/extensions/ahp/internal/wire/wire.go +218 -0
  140. package/extensions/ahp/internal/wire/wire_test.go +123 -0
  141. package/extensions/ahp/internal/ws/helpers_test.go +7 -0
  142. package/extensions/ahp/internal/ws/vscode_test.go +198 -0
  143. package/extensions/ahp/internal/ws/ws.go +674 -0
  144. package/extensions/ahp/internal/ws/ws_test.go +324 -0
  145. package/extensions/ahp/realpig_test.go +589 -0
  146. package/extensions/ahp/runtime.go +311 -0
  147. package/extensions/ahp/runtime_test.go +110 -0
  148. package/extensions/ahp/testdata/upstream-tests.json +3833 -0
  149. package/extensions/ahp/third_party/agent-host-protocol-go/LICENSE +21 -0
  150. package/extensions/ahp/third_party/agent-host-protocol-go/NOTICE-PIGPEN.md +18 -0
  151. package/extensions/ahp/third_party/agent-host-protocol-go/ahp/client.go +1011 -0
  152. package/extensions/ahp/third_party/agent-host-protocol-go/ahp/error.go +111 -0
  153. package/extensions/ahp/third_party/agent-host-protocol-go/ahp/multi_host_state_mirror.go +239 -0
  154. package/extensions/ahp/third_party/agent-host-protocol-go/ahp/reducers.go +1939 -0
  155. package/extensions/ahp/third_party/agent-host-protocol-go/ahp/transport.go +176 -0
  156. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/actions.generated.go +2447 -0
  157. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/commands.generated.go +1546 -0
  158. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/common.go +205 -0
  159. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/errors.generated.go +65 -0
  160. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/messages.generated.go +138 -0
  161. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/notifications.generated.go +264 -0
  162. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/state.generated.go +6171 -0
  163. package/extensions/ahp/third_party/agent-host-protocol-go/ahptypes/version.generated.go +31 -0
  164. package/extensions/ahp/third_party/agent-host-protocol-go/go.mod +3 -0
  165. package/extensions/ahp/twins_test.go +91 -0
  166. package/package.json +40 -0
  167. package/proof/PORT.md +121 -0
  168. package/proof/mutations.json +152 -0
  169. package/proof/oracle/LICENSE +21 -0
  170. package/proof/oracle/README.md +120 -0
  171. package/proof/oracle/UPSTREAM.md +7 -0
  172. package/proof/oracle/package.json +68 -0
  173. package/proof/oracle/src/bin/cli.ts +66 -0
  174. package/proof/oracle/src/bin/tunnel.ts +128 -0
  175. package/proof/oracle/src/channels/chat.ts +134 -0
  176. package/proof/oracle/src/channels/root.ts +39 -0
  177. package/proof/oracle/src/channels/session.ts +118 -0
  178. package/proof/oracle/src/channels/terminal.ts +11 -0
  179. package/proof/oracle/src/core/channels.ts +108 -0
  180. package/proof/oracle/src/core/client-workarounds.ts +358 -0
  181. package/proof/oracle/src/core/connection.ts +41 -0
  182. package/proof/oracle/src/core/host.ts +882 -0
  183. package/proof/oracle/src/core/sequencer.ts +75 -0
  184. package/proof/oracle/src/core/state-store.ts +162 -0
  185. package/proof/oracle/src/core/uri.ts +25 -0
  186. package/proof/oracle/src/host/direct-settings.ts +110 -0
  187. package/proof/oracle/src/host/pi-host.ts +220 -0
  188. package/proof/oracle/src/host/serve.ts +71 -0
  189. package/proof/oracle/src/host/terminal-service.ts +346 -0
  190. package/proof/oracle/src/pi/activity.ts +171 -0
  191. package/proof/oracle/src/pi/changeset-service.ts +646 -0
  192. package/proof/oracle/src/pi/changeset-uri.ts +64 -0
  193. package/proof/oracle/src/pi/chat-driver.ts +529 -0
  194. package/proof/oracle/src/pi/completions.ts +160 -0
  195. package/proof/oracle/src/pi/delete-session.ts +53 -0
  196. package/proof/oracle/src/pi/event-mapper.ts +648 -0
  197. package/proof/oracle/src/pi/git-changes.ts +605 -0
  198. package/proof/oracle/src/pi/history.ts +305 -0
  199. package/proof/oracle/src/pi/image-input.ts +56 -0
  200. package/proof/oracle/src/pi/image-mime.ts +8 -0
  201. package/proof/oracle/src/pi/in-process-backend.ts +155 -0
  202. package/proof/oracle/src/pi/message-input.ts +212 -0
  203. package/proof/oracle/src/pi/models.ts +124 -0
  204. package/proof/oracle/src/pi/project-trust.ts +66 -0
  205. package/proof/oracle/src/pi/provider.ts +2 -0
  206. package/proof/oracle/src/pi/resource-paths.ts +80 -0
  207. package/proof/oracle/src/pi/resource-service.ts +356 -0
  208. package/proof/oracle/src/pi/resource-watch-policy.ts +35 -0
  209. package/proof/oracle/src/pi/resource-watch.ts +357 -0
  210. package/proof/oracle/src/pi/session-catalogue.ts +318 -0
  211. package/proof/oracle/src/pi/session-config.ts +84 -0
  212. package/proof/oracle/src/pi/session-history.ts +75 -0
  213. package/proof/oracle/src/pi/session-hydrator.ts +219 -0
  214. package/proof/oracle/src/pi/session-registry.ts +815 -0
  215. package/proof/oracle/src/pi/session-storage.ts +29 -0
  216. package/proof/oracle/src/pi/session-title.ts +18 -0
  217. package/proof/oracle/src/pi/turn-paging.ts +94 -0
  218. package/proof/oracle/src/pi/user-message.ts +66 -0
  219. package/proof/oracle/src/protocol/errors.ts +44 -0
  220. package/proof/oracle/src/protocol/jsonrpc.ts +89 -0
  221. package/proof/oracle/src/protocol/version.ts +39 -0
  222. package/proof/oracle/src/transport/websocket.ts +136 -0
  223. package/proof/oracle/src/tunnel/devtunnel.ts +293 -0
  224. package/proof/oracle/src/tunnel/discovery.ts +37 -0
  225. package/proof/oracle/test/active-turn-reconnect.test.ts +274 -0
  226. package/proof/oracle/test/activity.test.ts +171 -0
  227. package/proof/oracle/test/changeset-lifecycle.test.serial.ts +303 -0
  228. package/proof/oracle/test/changeset-uri.test.ts +37 -0
  229. package/proof/oracle/test/changeset.test.serial.ts +487 -0
  230. package/proof/oracle/test/chat-driver.test.ts +691 -0
  231. package/proof/oracle/test/client-actions.test.ts +409 -0
  232. package/proof/oracle/test/client-workarounds.test.ts +320 -0
  233. package/proof/oracle/test/completions.test.ts +323 -0
  234. package/proof/oracle/test/delete-session.test.ts +142 -0
  235. package/proof/oracle/test/direct-settings.test.ts +81 -0
  236. package/proof/oracle/test/event-mapper.test.ts +619 -0
  237. package/proof/oracle/test/fetch-turns.test.ts +207 -0
  238. package/proof/oracle/test/fixtures/abort.json +711 -0
  239. package/proof/oracle/test/fixtures/bash-long-output.json +1312 -0
  240. package/proof/oracle/test/fixtures/compaction.json +6285 -0
  241. package/proof/oracle/test/fixtures/parallel-tools.json +2622 -0
  242. package/proof/oracle/test/fixtures/plain-text.json +1856 -0
  243. package/proof/oracle/test/fixtures/single-tool.json +1128 -0
  244. package/proof/oracle/test/fixtures/steering.json +3926 -0
  245. package/proof/oracle/test/fixtures/tool-bash.json +2372 -0
  246. package/proof/oracle/test/fixtures/tool-edit.json +3983 -0
  247. package/proof/oracle/test/fixtures/tool-error.json +2850 -0
  248. package/proof/oracle/test/fixtures/tool-find.json +1162 -0
  249. package/proof/oracle/test/fixtures/tool-grep.json +2783 -0
  250. package/proof/oracle/test/fixtures/tool-loop.json +1693 -0
  251. package/proof/oracle/test/fixtures/tool-ls.json +2427 -0
  252. package/proof/oracle/test/fixtures/tool-write.json +1271 -0
  253. package/proof/oracle/test/handshake.test.ts +275 -0
  254. package/proof/oracle/test/harness.ts +153 -0
  255. package/proof/oracle/test/hydrated-session-lifecycle.test.ts +211 -0
  256. package/proof/oracle/test/image-input.test.ts +28 -0
  257. package/proof/oracle/test/image-session.test.ts +69 -0
  258. package/proof/oracle/test/live-turn.test.ts +304 -0
  259. package/proof/oracle/test/mapper-fixtures.test.ts +293 -0
  260. package/proof/oracle/test/message-input.test.ts +181 -0
  261. package/proof/oracle/test/model-discovery.test.ts +170 -0
  262. package/proof/oracle/test/models.test.ts +109 -0
  263. package/proof/oracle/test/pi-host.test.ts +91 -0
  264. package/proof/oracle/test/pi-replay.test.ts +141 -0
  265. package/proof/oracle/test/project-trust.test.ts +125 -0
  266. package/proof/oracle/test/protocol-surface.test.ts +121 -0
  267. package/proof/oracle/test/pty.test.ts +100 -0
  268. package/proof/oracle/test/reconnect.test.ts +389 -0
  269. package/proof/oracle/test/resource-watch-policy.test.ts +78 -0
  270. package/proof/oracle/test/resource-watch.test.serial.ts +536 -0
  271. package/proof/oracle/test/resource.test.ts +499 -0
  272. package/proof/oracle/test/schema.test.ts +88 -0
  273. package/proof/oracle/test/session-catalogue.test.ts +314 -0
  274. package/proof/oracle/test/session-config.test.ts +224 -0
  275. package/proof/oracle/test/session-disposal.test.ts +364 -0
  276. package/proof/oracle/test/session-hydration.test.ts +194 -0
  277. package/proof/oracle/test/session-lifecycle.test.ts +416 -0
  278. package/proof/oracle/test/session-storage.test.serial.ts +32 -0
  279. package/proof/oracle/test/session-summary.test.ts +418 -0
  280. package/proof/oracle/test/subscriptions.test.ts +198 -0
  281. package/proof/oracle/test/support/assertions.ts +32 -0
  282. package/proof/oracle/test/support/async.ts +26 -0
  283. package/proof/oracle/test/support/hydrated-session.ts +205 -0
  284. package/proof/oracle/test/support/images.ts +8 -0
  285. package/proof/oracle/test/support/recorded-fixtures.ts +60 -0
  286. package/proof/oracle/test/support/recorded-scenarios.ts +145 -0
  287. package/proof/oracle/test/support/replay.ts +194 -0
  288. package/proof/oracle/test/support/schema.ts +221 -0
  289. package/proof/oracle/test/support/session-files.ts +12 -0
  290. package/proof/oracle/test/support/session-storage.ts +22 -0
  291. package/proof/oracle/test/support/upstream.ts +25 -0
  292. package/proof/oracle/test/support/watch-events.ts +108 -0
  293. package/proof/oracle/test/terminal-service.test.ts +495 -0
  294. package/proof/oracle/test/truncate.test.ts +230 -0
  295. package/proof/oracle/test/tunnel.test.ts +258 -0
  296. package/proof/oracle/test/upstream-workarounds.test.ts +37 -0
  297. package/proof/oracle/test/uri.test.ts +24 -0
  298. package/proof/oracle/test/watch-events.test.ts +118 -0
  299. package/proof/oracle/tsconfig.json +32 -0
  300. package/proof/proof-piglet/piglet.yaml +18 -0
  301. package/proof/tools/fakellm/go.mod +3 -0
  302. package/proof/tools/fakellm/main.go +109 -0
  303. package/proof/tools/gen-dispatchable.py +30 -0
  304. package/provenance.json +28 -0
@@ -0,0 +1,627 @@
1
+ package svc
2
+
3
+ import (
4
+ "encoding/json"
5
+ "os"
6
+ "path/filepath"
7
+ "reflect"
8
+ "strings"
9
+ "sync"
10
+ "testing"
11
+ "time"
12
+
13
+ "github.com/MichaelKinsy/pigpen/ahp/internal/host"
14
+ "github.com/MichaelKinsy/pigpen/ahp/internal/testkit"
15
+ "github.com/MichaelKinsy/pigpen/ahp/internal/twin"
16
+ "github.com/MichaelKinsy/pigpen/ahp/internal/wire"
17
+ ahptypes "github.com/microsoft/agent-host-protocol/clients/go/ahptypes"
18
+ )
19
+
20
+ // Twins of upstream test/resource-watch.test.serial.ts: real filesystem, in-memory transport. The
21
+ // upstream lifetime cases are red in the oracle environment (mocked timers); here the grace and
22
+ // debounce timers run on a hand-driven clock, so they run for real.
23
+
24
+ type watchFixture struct {
25
+ t *testing.T
26
+ host *host.Host
27
+ watches *WatchService
28
+ client *testkit.Client
29
+ workspace string
30
+ journals []*watchEvents
31
+ }
32
+
33
+ type fixtureOptions struct {
34
+ grace time.Duration
35
+ restrict bool
36
+ clock Clock
37
+ hooks func(*WatchOptions)
38
+ }
39
+
40
+ func startWatchFixture(t *testing.T, o fixtureOptions) *watchFixture {
41
+ t.Helper()
42
+ workspace, err := filepath.EvalSymlinks(t.TempDir())
43
+ if err != nil {
44
+ t.Fatal(err)
45
+ }
46
+ var roots []string
47
+ if o.restrict {
48
+ roots = []string{workspace}
49
+ }
50
+ policy, err := NewPathPolicy(roots...)
51
+ if err != nil {
52
+ t.Fatal(err)
53
+ }
54
+ h := testkit.NewHost(host.Options{})
55
+ opts := WatchOptions{Paths: policy, Grace: o.grace, Debounce: 20 * time.Millisecond, PollInterval: 10 * time.Millisecond, Clock: o.clock}
56
+ if o.hooks != nil {
57
+ o.hooks(&opts)
58
+ }
59
+ watches := NewWatchService(h, opts)
60
+ h.Serve(host.Capabilities{ResourceWatches: watches})
61
+ client := testkit.Connect(t, h)
62
+ client.Initialize("watch-client", nil)
63
+ f := &watchFixture{t: t, host: h, watches: watches, client: client, workspace: workspace}
64
+ t.Cleanup(f.close)
65
+ return f
66
+ }
67
+
68
+ func (f *watchFixture) close() {
69
+ for _, j := range f.journals {
70
+ _ = j.Close()
71
+ }
72
+ <-f.watches.Dispose()
73
+ f.client.Close()
74
+ }
75
+
76
+ func (f *watchFixture) path(parts ...string) string {
77
+ return filepath.Join(append([]string{f.workspace}, parts...)...)
78
+ }
79
+
80
+ func (f *watchFixture) create(params map[string]any) string {
81
+ f.t.Helper()
82
+ params["channel"] = wire.RootChannel
83
+ var result ahptypes.CreateResourceWatchResult
84
+ f.client.Decode(f.client.Must("createResourceWatch", params), &result)
85
+ return result.Channel
86
+ }
87
+
88
+ func (f *watchFixture) observe(channel string) *watchEvents {
89
+ f.t.Helper()
90
+ result := f.client.Subscribe(channel)
91
+ raw, _ := json.Marshal(result)
92
+ if !strings.Contains(string(raw), `"state"`) {
93
+ f.t.Fatal("watch must still exist when subscription is accepted")
94
+ }
95
+ events := newWatchEvents(clientSource{client: f.client, channel: channel}, nil, func() any {
96
+ return map[string]any{"channel": channel, "exists": f.host.Store().Has(channel), "activeCount": f.watches.ActiveCount()}
97
+ })
98
+ f.journals = append(f.journals, events)
99
+ return events
100
+ }
101
+
102
+ func expectChange(t *testing.T, events *watchEvents, path string, kind ahptypes.ResourceChangeType, since int) ahptypes.ResourceChange {
103
+ t.Helper()
104
+ want := ahptypes.ResourceChange{Uri: wire.PathToFileURI(path), Type: kind}
105
+ changes, err := events.WaitFor(string(kind)+": "+want.Uri, hasURI(want.Uri), since, 4*time.Second)
106
+ if err != nil {
107
+ t.Fatal(err)
108
+ }
109
+ for _, c := range changes {
110
+ if c.Uri == want.Uri {
111
+ if c != want {
112
+ t.Fatalf("got %+v, want %+v", c, want)
113
+ }
114
+ return c
115
+ }
116
+ }
117
+ t.Fatal("unreachable")
118
+ return want
119
+ }
120
+
121
+ func mustWrite(t *testing.T, path, data string) {
122
+ t.Helper()
123
+ if err := os.WriteFile(path, []byte(data), 0o666); err != nil {
124
+ t.Fatal(err)
125
+ }
126
+ }
127
+
128
+ func uriOf(path string) string { return wire.PathToFileURI(path) }
129
+
130
+ func (f *watchFixture) expectError(code int, params map[string]any) {
131
+ f.t.Helper()
132
+ params["channel"] = wire.RootChannel
133
+ f.client.ExpectError("createResourceWatch", params, code)
134
+ }
135
+
136
+ func TestResourceWatch(t *testing.T) {
137
+ twin.Run(t, "resource-watch", "returns a watch channel whose state describes what is watched", func(t *testing.T) {
138
+ f := startWatchFixture(t, fixtureOptions{})
139
+ channel := f.create(map[string]any{"uri": uriOf(f.workspace), "recursive": true,
140
+ "excludes": map[string]any{"items": []string{"**/.git/**"}}, "includes": map[string]any{"items": []string{"**/*.ts"}}})
141
+ if !strings.HasPrefix(channel, "ahp-resource-watch:/") {
142
+ t.Fatal(channel)
143
+ }
144
+ result := f.client.Subscribe(channel)
145
+ raw, _ := json.Marshal(result)
146
+ var snap struct {
147
+ Snapshot struct{ State map[string]any } `json:"snapshot"`
148
+ }
149
+ _ = json.Unmarshal(raw, &snap)
150
+ want := map[string]any{"root": uriOf(f.workspace), "recursive": true,
151
+ "excludes": map[string]any{"items": []any{"**/.git/**"}}, "includes": map[string]any{"items": []any{"**/*.ts"}}}
152
+ if !reflect.DeepEqual(snap.Snapshot.State, want) {
153
+ t.Fatalf("state %v, want %v", snap.Snapshot.State, want)
154
+ }
155
+ testkit.AssertValid(t, "state", "ResourceWatchState", snap.Snapshot.State)
156
+ })
157
+
158
+ twin.Run(t, "resource-watch", "classifies newly created paths as added", func(t *testing.T) {
159
+ f := startWatchFixture(t, fixtureOptions{})
160
+ events := f.observe(f.create(map[string]any{"uri": uriOf(f.workspace)}))
161
+ target := f.path("created.txt")
162
+ mustWrite(t, target, "hi")
163
+ change := expectChange(t, events, target, ahptypes.ResourceChangeTypeAdded, 0)
164
+ testkit.AssertValid(t, "state", "ResourceChange", map[string]any{"uri": change.Uri, "type": string(change.Type)})
165
+ })
166
+
167
+ twin.Run(t, "resource-watch", "classifies changes to existing paths as updated", func(t *testing.T) {
168
+ f := startWatchFixture(t, fixtureOptions{})
169
+ target := f.path("existing.txt")
170
+ mustWrite(t, target, "before")
171
+ events := f.observe(f.create(map[string]any{"uri": uriOf(f.workspace)}))
172
+ mustWrite(t, target, "after!")
173
+ expectChange(t, events, target, ahptypes.ResourceChangeTypeUpdated, 0)
174
+ })
175
+
176
+ twin.Run(t, "resource-watch", "watches a single file at its actual URI", func(t *testing.T) {
177
+ f := startWatchFixture(t, fixtureOptions{})
178
+ target := f.path("watched.txt")
179
+ mustWrite(t, target, "before")
180
+ events := f.observe(f.create(map[string]any{"uri": uriOf(target)}))
181
+ mustWrite(t, f.path("sibling.txt"), "unrelated")
182
+ mustWrite(t, target, "after!")
183
+ expectChange(t, events, target, ahptypes.ResourceChangeTypeUpdated, 0)
184
+ // Check delivered traffic; exhaustive sibling exclusion is a pure policy test.
185
+ for _, c := range events.Changes() {
186
+ if c.Uri != uriOf(target) {
187
+ t.Fatalf("unexpected change %+v", c)
188
+ }
189
+ }
190
+ })
191
+
192
+ twin.Run(t, "resource-watch", "reports deletion and recreation of the watched file", func(t *testing.T) {
193
+ f := startWatchFixture(t, fixtureOptions{})
194
+ target := f.path("recreated.txt")
195
+ mustWrite(t, target, "before")
196
+ events := f.observe(f.create(map[string]any{"uri": uriOf(target)}))
197
+ if err := os.Remove(target); err != nil {
198
+ t.Fatal(err)
199
+ }
200
+ expectChange(t, events, target, ahptypes.ResourceChangeTypeDeleted, 0)
201
+ since := events.Mark()
202
+ mustWrite(t, target, "after")
203
+ expectChange(t, events, target, ahptypes.ResourceChangeTypeAdded, since)
204
+ })
205
+
206
+ twin.Run(t, "resource-watch", "keeps a single-file watch attached across an atomic replacement", func(t *testing.T) {
207
+ f := startWatchFixture(t, fixtureOptions{})
208
+ target, replacement := f.path("atomic.txt"), f.path(".atomic.txt.tmp")
209
+ mustWrite(t, target, "before")
210
+ events := f.observe(f.create(map[string]any{"uri": uriOf(target)}))
211
+ mustWrite(t, replacement, "replacement")
212
+ if err := os.Rename(replacement, target); err != nil {
213
+ t.Fatal(err)
214
+ }
215
+ expectChange(t, events, target, ahptypes.ResourceChangeTypeUpdated, 0)
216
+ time.Sleep(150 * time.Millisecond)
217
+ since := events.Mark()
218
+ mustWrite(t, target, "after")
219
+ expectChange(t, events, target, ahptypes.ResourceChangeTypeUpdated, since)
220
+ })
221
+
222
+ twin.Run(t, "resource-watch", "keeps a directory watch attached across deletion and recreation", func(t *testing.T) {
223
+ f := startWatchFixture(t, fixtureOptions{})
224
+ target := f.path("folder")
225
+ if err := os.Mkdir(target, 0o777); err != nil {
226
+ t.Fatal(err)
227
+ }
228
+ events := f.observe(f.create(map[string]any{"uri": uriOf(target)}))
229
+ if err := os.RemoveAll(target); err != nil {
230
+ t.Fatal(err)
231
+ }
232
+ expectChange(t, events, target, ahptypes.ResourceChangeTypeDeleted, 0)
233
+ since := events.Mark()
234
+ if err := os.Mkdir(target, 0o777); err != nil {
235
+ t.Fatal(err)
236
+ }
237
+ expectChange(t, events, target, ahptypes.ResourceChangeTypeAdded, since)
238
+ child := filepath.Join(target, "child.txt")
239
+ mustWrite(t, child, "content")
240
+ expectChange(t, events, child, ahptypes.ResourceChangeTypeAdded, since)
241
+ })
242
+
243
+ twin.Run(t, "resource-watch", "reports both sides of a rename without assuming batch boundaries", func(t *testing.T) {
244
+ f := startWatchFixture(t, fixtureOptions{})
245
+ source, destination := f.path("before.txt"), f.path("after.txt")
246
+ mustWrite(t, source, "content")
247
+ events := f.observe(f.create(map[string]any{"uri": uriOf(f.workspace)}))
248
+ if err := os.Rename(source, destination); err != nil {
249
+ t.Fatal(err)
250
+ }
251
+ expectChange(t, events, source, ahptypes.ResourceChangeTypeDeleted, 0)
252
+ expectChange(t, events, destination, ahptypes.ResourceChangeTypeAdded, 0)
253
+ })
254
+
255
+ twin.Run(t, "resource-watch", "does not lose paths from a burst", func(t *testing.T) {
256
+ f := startWatchFixture(t, fixtureOptions{})
257
+ events := f.observe(f.create(map[string]any{"uri": uriOf(f.workspace)}))
258
+ var paths []string
259
+ for i := 0; i < 5; i++ {
260
+ p := f.path("burst-" + string(rune('0'+i)) + ".txt")
261
+ paths = append(paths, p)
262
+ mustWrite(t, p, "x")
263
+ }
264
+ for _, p := range paths {
265
+ expectChange(t, events, p, ahptypes.ResourceChangeTypeAdded, 0)
266
+ }
267
+ })
268
+
269
+ twin.Run(t, "resource-watch", "reports direct children with recursive=false", func(t *testing.T) {
270
+ watchDepth(t, false)
271
+ })
272
+ twin.Run(t, "resource-watch", "reports grandchildren with recursive=true", func(t *testing.T) {
273
+ watchDepth(t, true)
274
+ })
275
+
276
+ twin.Run(t, "resource-watch", "wires includes into native watch delivery", func(t *testing.T) {
277
+ watchFilter(t, true)
278
+ })
279
+ twin.Run(t, "resource-watch", "wires excludes into native watch delivery", func(t *testing.T) {
280
+ watchFilter(t, false)
281
+ })
282
+
283
+ twin.Run(t, "resource-watch", "rejects watching something that does not exist", func(t *testing.T) {
284
+ f := startWatchFixture(t, fixtureOptions{})
285
+ f.expectError(-32008, map[string]any{"uri": uriOf(f.path("missing"))})
286
+ if f.watches.ActiveCount() != 0 {
287
+ t.Fatal("a rejected watch stayed active")
288
+ }
289
+ })
290
+
291
+ twin.Run(t, "resource-watch", "rejects a recursive watch on a file", func(t *testing.T) {
292
+ f := startWatchFixture(t, fixtureOptions{})
293
+ target := f.path("file.txt")
294
+ mustWrite(t, target, "x")
295
+ f.expectError(-32602, map[string]any{"uri": uriOf(target), "recursive": true})
296
+ if f.watches.ActiveCount() != 0 {
297
+ t.Fatal("a rejected watch stayed active")
298
+ }
299
+ })
300
+
301
+ twin.Run(t, "resource-watch", "rejects malformed filter parameters", func(t *testing.T) {
302
+ f := startWatchFixture(t, fixtureOptions{})
303
+ f.expectError(-32602, map[string]any{"uri": uriOf(f.workspace), "includes": map[string]any{"items": []any{42}}})
304
+ if f.watches.ActiveCount() != 0 {
305
+ t.Fatal("a rejected watch stayed active")
306
+ }
307
+ })
308
+ }
309
+
310
+ func watchDepth(t *testing.T, recursive bool) {
311
+ f := startWatchFixture(t, fixtureOptions{})
312
+ nested := f.path("nested")
313
+ if err := os.Mkdir(nested, 0o777); err != nil {
314
+ t.Fatal(err)
315
+ }
316
+ events := f.observe(f.create(map[string]any{"uri": uriOf(f.workspace), "recursive": recursive}))
317
+ direct, deep := f.path("direct.txt"), filepath.Join(nested, "deep.txt")
318
+ mustWrite(t, deep, "deep")
319
+ mustWrite(t, direct, "direct")
320
+ if recursive {
321
+ expectChange(t, events, deep, ahptypes.ResourceChangeTypeAdded, 0)
322
+ return
323
+ }
324
+ expectChange(t, events, direct, ahptypes.ResourceChangeTypeAdded, 0)
325
+ for _, c := range events.Changes() {
326
+ if c.Uri == uriOf(deep) {
327
+ t.Fatalf("a grandchild was reported by a non-recursive watch: %+v", c)
328
+ }
329
+ }
330
+ }
331
+
332
+ func watchFilter(t *testing.T, includes bool) {
333
+ f := startWatchFixture(t, fixtureOptions{})
334
+ params := map[string]any{"uri": uriOf(f.workspace), "recursive": true}
335
+ if includes {
336
+ params["includes"] = map[string]any{"items": []string{"**/*.md"}}
337
+ } else {
338
+ params["excludes"] = map[string]any{"items": []string{"**/node_modules/**"}}
339
+ }
340
+ events := f.observe(f.create(params))
341
+ ignored := f.path("node_modules")
342
+ if err := os.Mkdir(ignored, 0o777); err != nil {
343
+ t.Fatal(err)
344
+ }
345
+ mustWrite(t, filepath.Join(ignored, "ignored.txt"), "x")
346
+ target := f.path("kept.md")
347
+ mustWrite(t, target, "x")
348
+ expectChange(t, events, target, ahptypes.ResourceChangeTypeAdded, 0)
349
+ for _, c := range events.Changes() {
350
+ if includes && !strings.HasSuffix(c.Uri, ".md") {
351
+ t.Fatalf("include filter leaked %+v", c)
352
+ }
353
+ if !includes && strings.Contains(c.Uri, "/node_modules/") {
354
+ t.Fatalf("exclude filter leaked %+v", c)
355
+ }
356
+ }
357
+ }
358
+
359
+ func TestResourceWatchRoots(t *testing.T) {
360
+ twin.Run(t, "resource-watch", "maps a permitted directory symlink back to the requested URI", func(t *testing.T) {
361
+ f := startWatchFixture(t, fixtureOptions{restrict: true})
362
+ target, link := f.path("target"), f.path("link")
363
+ if err := os.Mkdir(target, 0o777); err != nil {
364
+ t.Fatal(err)
365
+ }
366
+ child := filepath.Join(target, "watched.txt")
367
+ mustWrite(t, child, "before")
368
+ if err := os.Symlink(target, link); err != nil {
369
+ t.Skip("symlinks unavailable: ", err)
370
+ }
371
+ events := f.observe(f.create(map[string]any{"uri": uriOf(link), "recursive": true}))
372
+ mustWrite(t, child, "after!")
373
+ expectChange(t, events, filepath.Join(link, "watched.txt"), ahptypes.ResourceChangeTypeUpdated, 0)
374
+ })
375
+
376
+ twin.Run(t, "resource-watch", "uses the same root and symlink policy as resource operations", func(t *testing.T) {
377
+ f := startWatchFixture(t, fixtureOptions{restrict: true})
378
+ outside, _ := filepath.EvalSymlinks(t.TempDir())
379
+ channel := f.create(map[string]any{"uri": uriOf(f.workspace)})
380
+ if !strings.HasPrefix(channel, "ahp-resource-watch:/") {
381
+ t.Fatal(channel)
382
+ }
383
+ f.expectError(-32009, map[string]any{"uri": uriOf(outside)})
384
+ link := f.path("escape")
385
+ if err := os.Symlink(outside, link); err != nil {
386
+ t.Skip("symlinks unavailable: ", err)
387
+ }
388
+ f.expectError(-32009, map[string]any{"uri": uriOf(link)})
389
+ if f.watches.ActiveCount() != 1 {
390
+ t.Fatalf("active=%d", f.watches.ActiveCount())
391
+ }
392
+ })
393
+ }
394
+
395
+ // ── lifetime ────────────────────────────────────────────────────────────
396
+
397
+ func waitCount(t *testing.T, f *watchFixture, want int) {
398
+ t.Helper()
399
+ if got := f.watches.ActiveCount(); got != want {
400
+ t.Fatalf("active watches = %d, want %d", got, want)
401
+ }
402
+ }
403
+
404
+ func TestResourceWatchLifetime(t *testing.T) {
405
+ const grace = 120 * time.Millisecond
406
+
407
+ twin.Run(t, "resource-watch", "waits for the last subscriber before scheduling release", func(t *testing.T) {
408
+ clock := &fakeClock{}
409
+ f := startWatchFixture(t, fixtureOptions{grace: grace, clock: clock})
410
+ other := testkit.Connect(t, f.host)
411
+ defer other.Close()
412
+ other.Initialize("other-watch-client", nil)
413
+ channel := f.create(map[string]any{"uri": uriOf(f.workspace)})
414
+ f.client.Subscribe(channel)
415
+ other.Subscribe(channel)
416
+ f.client.Unsubscribe(channel)
417
+ f.client.Ping()
418
+ clock.Tick(120 * time.Millisecond)
419
+ waitCount(t, f, 1)
420
+ other.Unsubscribe(channel)
421
+ other.Ping()
422
+ clock.Tick(119 * time.Millisecond)
423
+ waitCount(t, f, 1)
424
+ clock.Tick(1 * time.Millisecond)
425
+ waitCount(t, f, 0)
426
+ if f.host.Store().Has(channel) {
427
+ t.Fatal("the released watch channel still exists")
428
+ }
429
+ })
430
+
431
+ twin.Run(t, "resource-watch", "cancels grace on subscribe and grants a full window after the next unsubscribe", func(t *testing.T) {
432
+ cancelGrace(t, "subscribe")
433
+ })
434
+ twin.Run(t, "resource-watch", "cancels grace on initialize and grants a full window after the next unsubscribe", func(t *testing.T) {
435
+ cancelGrace(t, "initialize")
436
+ })
437
+ twin.Run(t, "resource-watch", "cancels grace on reconnect and grants a full window after the next unsubscribe", func(t *testing.T) {
438
+ cancelGrace(t, "reconnect")
439
+ })
440
+
441
+ twin.Run(t, "resource-watch", "releases a watch when the client disconnects without unsubscribing", func(t *testing.T) {
442
+ clock := &fakeClock{}
443
+ f := startWatchFixture(t, fixtureOptions{grace: grace, clock: clock})
444
+ channel := f.create(map[string]any{"uri": uriOf(f.workspace)})
445
+ f.client.Subscribe(channel)
446
+ disconnected := make(chan struct{})
447
+ var once sync.Once
448
+ unhook := f.host.OnSubscriberCountChanged(func(changed string, count int) {
449
+ if changed == channel && count == 0 {
450
+ once.Do(func() { close(disconnected) })
451
+ }
452
+ })
453
+ defer unhook()
454
+ f.client.Close()
455
+ select {
456
+ case <-disconnected:
457
+ case <-time.After(4 * time.Second):
458
+ t.Fatal("the disconnect never reached zero subscribers")
459
+ }
460
+ clock.Tick(119 * time.Millisecond)
461
+ waitCount(t, f, 1)
462
+ clock.Tick(1 * time.Millisecond)
463
+ waitCount(t, f, 0)
464
+ if f.host.Store().Has(channel) {
465
+ t.Fatal("the released watch channel still exists")
466
+ }
467
+ })
468
+
469
+ twin.Run(t, "resource-watch", "releases a watch nobody ever subscribed to", func(t *testing.T) {
470
+ clock := &fakeClock{}
471
+ f := startWatchFixture(t, fixtureOptions{grace: grace, clock: clock})
472
+ channel := f.create(map[string]any{"uri": uriOf(f.workspace)})
473
+ clock.Tick(119 * time.Millisecond)
474
+ waitCount(t, f, 1)
475
+ clock.Tick(1 * time.Millisecond)
476
+ waitCount(t, f, 0)
477
+ if f.host.Store().Has(channel) {
478
+ t.Fatal("the released watch channel still exists")
479
+ }
480
+ })
481
+
482
+ twin.Run(t, "resource-watch", "disposes every watch and returns the same shutdown promise", func(t *testing.T) {
483
+ f := startWatchFixture(t, fixtureOptions{})
484
+ channel := f.create(map[string]any{"uri": uriOf(f.workspace)})
485
+ f.client.Subscribe(channel)
486
+ closing := f.watches.Dispose()
487
+ if f.watches.Dispose() != closing {
488
+ t.Fatal("dispose must return the same shutdown handle")
489
+ }
490
+ <-closing
491
+ waitCount(t, f, 0)
492
+ if f.host.Store().Has(channel) {
493
+ t.Fatal("the released watch channel still exists")
494
+ }
495
+ })
496
+
497
+ twin.Run(t, "resource-watch", "waits for a blocked creation to settle before completing shutdown", func(t *testing.T) {
498
+ entered, gate := make(chan struct{}), make(chan struct{})
499
+ var enterOnce sync.Once
500
+ f := startWatchFixture(t, fixtureOptions{hooks: func(o *WatchOptions) {
501
+ o.afterPath = func() {
502
+ enterOnce.Do(func() { close(entered) })
503
+ <-gate
504
+ }
505
+ }})
506
+ created := make(chan error, 1)
507
+ go func() {
508
+ _, err := f.watches.Create(nil, ahptypes.CreateResourceWatchParams{Channel: wire.RootChannel, Uri: uriOf(f.workspace)})
509
+ created <- err
510
+ }()
511
+ <-entered
512
+ closing := f.watches.Dispose()
513
+ select {
514
+ case <-closing:
515
+ t.Fatal("shutdown must drain the admitted create operation")
516
+ case <-time.After(50 * time.Millisecond):
517
+ }
518
+ close(gate)
519
+ <-closing
520
+ if err := <-created; err == nil || !strings.Contains(err.Error(), "disposed") {
521
+ t.Fatalf("create: %v", err)
522
+ }
523
+ waitCount(t, f, 0)
524
+ })
525
+
526
+ twin.Run(t, "resource-watch", "closes a native watcher if shutdown wins at its ready boundary", func(t *testing.T) {
527
+ var mu sync.Mutex
528
+ closed := 0
529
+ var shutdown <-chan struct{}
530
+ var svc *WatchService
531
+ f := startWatchFixture(t, fixtureOptions{hooks: func(o *WatchOptions) {
532
+ o.afterReady = func() {
533
+ mu.Lock()
534
+ defer mu.Unlock()
535
+ shutdown = svc.Dispose()
536
+ }
537
+ o.onClosed = func() { mu.Lock(); closed++; mu.Unlock() }
538
+ }})
539
+ mu.Lock()
540
+ svc = f.watches
541
+ mu.Unlock()
542
+ _, err := f.watches.Create(nil, ahptypes.CreateResourceWatchParams{Channel: wire.RootChannel, Uri: uriOf(f.workspace)})
543
+ if err == nil || !strings.Contains(err.Error(), "disposed") {
544
+ t.Fatalf("create: %v", err)
545
+ }
546
+ mu.Lock()
547
+ s := shutdown
548
+ mu.Unlock()
549
+ if s == nil {
550
+ t.Fatal("the watcher must have reached ready")
551
+ }
552
+ <-s
553
+ mu.Lock()
554
+ defer mu.Unlock()
555
+ if closed != 1 {
556
+ t.Fatalf("closed %d watchers, want 1", closed)
557
+ }
558
+ waitCount(t, f, 0)
559
+ })
560
+
561
+ twin.Run(t, "resource-watch", "drains in-flight creations and rejects new ones after shutdown", func(t *testing.T) {
562
+ f := startWatchFixture(t, fixtureOptions{})
563
+ params := ahptypes.CreateResourceWatchParams{Channel: wire.RootChannel, Uri: uriOf(f.workspace)}
564
+ created := make(chan error, 1)
565
+ go func() { _, err := f.watches.Create(nil, params); created <- err }()
566
+ closing := f.watches.Dispose()
567
+ if f.watches.Dispose() != closing {
568
+ t.Fatal("dispose must return the same shutdown handle")
569
+ }
570
+ <-closing
571
+ // The in-flight creation either won admission (and was drained and released) or lost it.
572
+ <-created
573
+ waitCount(t, f, 0)
574
+ if _, err := f.watches.Create(nil, params); err == nil || !strings.Contains(err.Error(), "disposed") {
575
+ t.Fatalf("create after shutdown: %v", err)
576
+ }
577
+ })
578
+ }
579
+
580
+ func cancelGrace(t *testing.T, method string) {
581
+ const grace = 120 * time.Millisecond
582
+ clock := &fakeClock{}
583
+ f := startWatchFixture(t, fixtureOptions{grace: grace, clock: clock})
584
+ channel := f.create(map[string]any{"uri": uriOf(f.workspace)})
585
+ f.client.Subscribe(channel)
586
+ var mu sync.Mutex
587
+ var counts []int
588
+ unhook := f.host.OnSubscriberCountChanged(func(changed string, count int) {
589
+ if changed == channel {
590
+ mu.Lock()
591
+ counts = append(counts, count)
592
+ mu.Unlock()
593
+ }
594
+ })
595
+ defer unhook()
596
+ f.client.Unsubscribe(channel)
597
+ f.client.Ping()
598
+ clock.Tick(60 * time.Millisecond)
599
+ owner := f.client
600
+ switch method {
601
+ case "subscribe":
602
+ owner.Subscribe(channel)
603
+ default:
604
+ owner = testkit.Connect(t, f.host)
605
+ defer owner.Close()
606
+ if method == "initialize" {
607
+ owner.Initialize("replacement", map[string]any{"initialSubscriptions": []string{channel}})
608
+ } else {
609
+ owner.Must("reconnect", map[string]any{"channel": wire.RootChannel, "clientId": "replacement", "lastSeenServerSeq": f.host.ServerSeq(), "subscriptions": []string{channel}})
610
+ }
611
+ }
612
+ snapshot := func() []int { mu.Lock(); defer mu.Unlock(); return append([]int(nil), counts...) }
613
+ if got := snapshot(); !reflect.DeepEqual(got, []int{0, 1}) {
614
+ t.Fatalf("counts %v, want [0 1]", got)
615
+ }
616
+ clock.Tick(120 * time.Millisecond)
617
+ waitCount(t, f, 1)
618
+ owner.Unsubscribe(channel)
619
+ owner.Ping()
620
+ clock.Tick(119 * time.Millisecond)
621
+ waitCount(t, f, 1)
622
+ clock.Tick(1 * time.Millisecond)
623
+ waitCount(t, f, 0)
624
+ if got := snapshot(); !reflect.DeepEqual(got, []int{0, 1, 0}) {
625
+ t.Fatalf("counts %v, want [0 1 0]", got)
626
+ }
627
+ }