subagentsStoreLoading.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. import type { ISubagentsService } from "@zcode/services";
  2. import type { ZCodeProvider } from "@zcode/shared";
  3. import { getServiceAuthorityId } from "@/store/serviceAuthorityKey.js";
  4. const inFlightAgentLoads = new Map<string, ReturnType<ISubagentsService["list"]>>();
  5. let latestAgentLoadRequestId = 0;
  6. function getAgentLoadKey(
  7. workspacePath: string,
  8. provider: ZCodeProvider,
  9. subagentsService: ISubagentsService,
  10. workspaceIdentity?: string,
  11. ): string {
  12. return `${getServiceAuthorityId(subagentsService)}::${
  13. workspaceIdentity?.trim() || workspacePath
  14. }::${provider}`;
  15. }
  16. export function loadAgentsOnce(
  17. workspacePath: string,
  18. provider: ZCodeProvider,
  19. subagentsService: ISubagentsService,
  20. workspaceIdentity?: string,
  21. options: { bypassCache?: boolean } = {},
  22. ): ReturnType<ISubagentsService["list"]> {
  23. const key = getAgentLoadKey(workspacePath, provider, subagentsService, workspaceIdentity);
  24. if (!options.bypassCache) {
  25. const current = inFlightAgentLoads.get(key);
  26. if (current) return current;
  27. }
  28. const request = subagentsService
  29. .list({ workspacePath, workspaceIdentity, provider })
  30. .finally(() => {
  31. if (inFlightAgentLoads.get(key) === request) inFlightAgentLoads.delete(key);
  32. });
  33. inFlightAgentLoads.set(key, request);
  34. return request;
  35. }
  36. export function nextAgentLoadRequestId(): number {
  37. latestAgentLoadRequestId += 1;
  38. return latestAgentLoadRequestId;
  39. }
  40. export function isLatestAgentLoadRequest(requestId: number): boolean {
  41. return requestId === latestAgentLoadRequestId;
  42. }