@antelopejs/dms-ai 0.2.1 → 0.3.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.
@@ -1,8 +1,8 @@
1
1
  <script setup lang="ts">
2
- import { computed, watch } from "vue";
2
+ import { computed } from "vue";
3
3
  import DiffView from "./DiffView.vue";
4
4
  import UnavailableState from "./UnavailableState.vue";
5
- import { useAiRequest } from "./composables/useAiRequest";
5
+ import { useAiData } from "./composables/useAiData";
6
6
  import { useAssistant } from "./composables/useAssistant";
7
7
  import { useChangeSetActions } from "./composables/useChangeSetActions";
8
8
  import { useViewFormat } from "./composables/useViewFormat";
@@ -20,28 +20,23 @@ interface Props {
20
20
  }
21
21
 
22
22
  const props = defineProps<Props>();
23
- const emit = defineEmits<{ changed: [] }>();
24
23
 
25
24
  const { t } = useI18n();
26
- const { $authFetch } = useAuthFetch();
27
25
  const { moment } = useViewFormat();
28
26
  const assistant = useAssistant();
29
- const detail = useAiRequest<ChangeSetDetail>();
30
- const actions = useChangeSetActions(() => {
31
- void load();
32
- emit("changed");
33
- });
27
+ // A set picked again shows what was read before and reads again: it may have
28
+ // been undone or redone since.
29
+ const detail = useAiData<ChangeSetDetail>(
30
+ () => `${AI_ROUTES.changes}/${encodeURIComponent(props.changeSetId)}`,
31
+ );
32
+ // Once a set is undone or redone, the page reads its data again: this panel,
33
+ // the list and the assistant's status.
34
+ const actions = useChangeSetActions();
34
35
 
35
- function load(): Promise<ChangeSetDetail | null> {
36
- return detail.run(() =>
37
- $authFetch<ChangeSetDetail>(
38
- `${AI_ROUTES.changes}/${encodeURIComponent(props.changeSetId)}`,
39
- ),
40
- );
36
+ function load(): Promise<void> {
37
+ return detail.refresh();
41
38
  }
42
39
 
43
- watch(() => props.changeSetId, load, { immediate: true });
44
-
45
40
  const changeSet = computed<ChangeSetSummary | null>(
46
41
  () => detail.data.value?.changeSet ?? null,
47
42
  );
@@ -128,7 +123,7 @@ function openPage(): void {
128
123
  <USkeleton class="mt-4 h-24 w-full" />
129
124
  <USkeleton class="h-40 w-full" />
130
125
  </div>
131
- <article v-else :aria-busy="detail.isLoading.value">
126
+ <article v-else :aria-busy="detail.pending.value">
132
127
  <header class="flex min-h-16 flex-wrap items-start gap-3 px-5 py-3.5">
133
128
  <div class="min-w-0 flex-1">
134
129
  <p
@@ -1,6 +1,6 @@
1
1
  <script setup lang="ts">
2
2
  import { computed } from "vue";
3
- import type { RequestFailure } from "./composables/useAiRequest";
3
+ import type { RequestFailure } from "./composables/useAiData";
4
4
  import { useViewFormat } from "./composables/useViewFormat";
5
5
 
6
6
  type UnavailableStateSize = "sm" | "md" | "lg";
@@ -0,0 +1,116 @@
1
+ import { computed, type ComputedRef, type MaybeRefOrGetter } from "vue";
2
+ import type {
3
+ ApiDataRequest,
4
+ ApiDataResult,
5
+ ApiPagedDataHandler,
6
+ ApiPagedDataResult,
7
+ UseApiDataOptions,
8
+ } from "#dms-core/app/composables/auth/useApiData";
9
+ import type {
10
+ DmsAsyncDataKey,
11
+ UseDmsPagedDataOptions,
12
+ } from "#dms/frontend-module";
13
+ import { HTTP_SERVICE_UNAVAILABLE } from "../constants";
14
+
15
+ /** Why a request failed: the sidecar is down (503), or anything else. */
16
+ export type RequestFailure = "unavailable" | "error";
17
+
18
+ /** Why a read failed, and the server's message for it. */
19
+ interface FailureDescription {
20
+ /** Why the last read failed; none while a retry is in flight. */
21
+ failure: ComputedRef<RequestFailure | null>;
22
+ /** The server's message for the failure. */
23
+ message: ComputedRef<string>;
24
+ }
25
+
26
+ /** A view's read, and why it failed. */
27
+ export type AiData<T> = ApiDataResult<T> & FailureDescription;
28
+
29
+ /** A view's list read page by page, and why it failed. */
30
+ export type AiPagedData<TPage, TCursor> = ApiPagedDataResult<TPage, TCursor> &
31
+ FailureDescription;
32
+
33
+ /** What a failure description needs of a read. */
34
+ interface FailingRead {
35
+ error: { value: unknown };
36
+ status: { value: string };
37
+ }
38
+
39
+ interface FetchErrorResponse {
40
+ status?: number;
41
+ }
42
+
43
+ interface FetchErrorBody {
44
+ message?: unknown;
45
+ }
46
+
47
+ interface FetchErrorLike {
48
+ status?: number;
49
+ statusCode?: number;
50
+ response?: FetchErrorResponse;
51
+ data?: FetchErrorBody;
52
+ message?: string;
53
+ }
54
+
55
+ /** The HTTP status of a `$authFetch` rejection, if it got an answer. */
56
+ function errorStatus(error: unknown): number | undefined {
57
+ const candidate = error as FetchErrorLike | null;
58
+ return (
59
+ candidate?.status ?? candidate?.statusCode ?? candidate?.response?.status
60
+ );
61
+ }
62
+
63
+ /** The server's `{ message }`, else the error's own text. */
64
+ export function errorMessage(error: unknown): string {
65
+ const candidate = error as FetchErrorLike | null;
66
+ const serverMessage = candidate?.data?.message;
67
+ if (typeof serverMessage === "string") return serverMessage;
68
+ return candidate?.message ?? String(error);
69
+ }
70
+
71
+ export function classifyFailure(error: unknown): RequestFailure {
72
+ return errorStatus(error) === HTTP_SERVICE_UNAVAILABLE
73
+ ? "unavailable"
74
+ : "error";
75
+ }
76
+
77
+ /**
78
+ * A view's read of the assistant's data, with the page (`useApiData`): a
79
+ * server render reads it and hands it to the browser. Its failure says
80
+ * whether the assistant isn't running (503) rather than an error.
81
+ */
82
+ function describeFailure(result: FailingRead): FailureDescription {
83
+ return {
84
+ failure: computed(() =>
85
+ result.error.value && result.status.value !== "pending"
86
+ ? classifyFailure(result.error.value)
87
+ : null,
88
+ ),
89
+ message: computed(() =>
90
+ result.error.value ? errorMessage(result.error.value) : "",
91
+ ),
92
+ };
93
+ }
94
+
95
+ export function useAiData<T>(
96
+ url: ApiDataRequest,
97
+ options?: UseApiDataOptions<T>,
98
+ ): AiData<T> {
99
+ const result = useApiData<T>(url, options);
100
+ return Object.assign(result, describeFailure(result));
101
+ }
102
+
103
+ /**
104
+ * A view's list read page by page ("Load more"), with the page
105
+ * (`useApiPagedData`): a server render reads the first page, and the page's
106
+ * refreshes read every page loaded again. Its failure says whether the
107
+ * assistant isn't running (503) rather than an error.
108
+ */
109
+ export function useAiPagedData<TPage, TCursor>(
110
+ key: MaybeRefOrGetter<DmsAsyncDataKey>,
111
+ handler: ApiPagedDataHandler<TPage, TCursor>,
112
+ options: UseDmsPagedDataOptions<TPage, TCursor>,
113
+ ): AiPagedData<TPage, TCursor> {
114
+ const result = useApiPagedData<TPage, TCursor>(key, handler, options);
115
+ return Object.assign(result, describeFailure(result));
116
+ }
@@ -1,4 +1,4 @@
1
- import { inject } from "vue";
1
+ import { getCurrentInstance, inject, onMounted, ref } from "vue";
2
2
  import { useDmsRouter } from "#dms/frontend-module";
3
3
  import { ASSISTANT_SESSION_KEY } from "../../runtime/assistant-session";
4
4
 
@@ -16,13 +16,19 @@ export interface AssistantActions {
16
16
  * The tab's assistant session as the workspace views use it. Until it runs
17
17
  * (its first probe pending) and without one (production, sidecar disabled) the
18
18
  * actions do nothing and `isAvailable` hides the buttons that need them.
19
+ *
20
+ * A view only offers them once mounted: the server never has a session, and a
21
+ * probe that answered before the view hydrated would otherwise make the
22
+ * browser render buttons the server's HTML lacks.
19
23
  */
20
24
  export function useAssistant(): AssistantActions {
21
25
  const session = inject(ASSISTANT_SESSION_KEY, null);
22
26
  const router = useDmsRouter();
27
+ const isMounted = ref(!getCurrentInstance());
28
+ if (!isMounted.value) onMounted(() => (isMounted.value = true));
23
29
  return {
24
30
  get isAvailable() {
25
- return (session?.value ?? null) !== null;
31
+ return isMounted.value && (session?.value ?? null) !== null;
26
32
  },
27
33
  openPanel: () => session?.value?.panel.open(),
28
34
  openConversation: (conversationId) =>
@@ -1,7 +1,7 @@
1
1
  import { ref, type Ref } from "vue";
2
2
  import { AI_ROUTES } from "../constants";
3
3
  import type { ChangeSetSummary } from "../types";
4
- import { classifyFailure, errorMessage } from "./useAiRequest";
4
+ import { classifyFailure, errorMessage } from "./useAiData";
5
5
 
6
6
  export interface ChangeSetActions {
7
7
  isBusy: Ref<boolean>;
@@ -21,10 +21,11 @@ function changeSetPath(changeSetId: string, action: string): string {
21
21
  }
22
22
 
23
23
  /**
24
- * Undo and redo of a change set, each confirmed by a toast; `onChanged` runs
25
- * once the sidecar has restored the files.
24
+ * Undo and redo of a change set, each confirmed by a toast; the page is read
25
+ * again once the sidecar has restored the files, and the action stays busy
26
+ * until it is: the set shows its new state before it can be acted on again.
26
27
  */
27
- export function useChangeSetActions(onChanged: () => void): ChangeSetActions {
28
+ export function useChangeSetActions(): ChangeSetActions {
28
29
  const { t } = useI18n();
29
30
  const toast = useToast();
30
31
  const { $authFetch } = useAuthFetch();
@@ -56,7 +57,7 @@ export function useChangeSetActions(onChanged: () => void): ChangeSetActions {
56
57
  color: AI_COLOR,
57
58
  icon: "i-ph-arrow-clockwise",
58
59
  });
59
- onChanged();
60
+ await refreshPageBlocks();
60
61
  } catch (error) {
61
62
  failureToast(error);
62
63
  } finally {
@@ -88,7 +89,7 @@ export function useChangeSetActions(onChanged: () => void): ChangeSetActions {
88
89
  },
89
90
  ],
90
91
  });
91
- onChanged();
92
+ await refreshPageBlocks();
92
93
  }
93
94
 
94
95
  async function undo(changeSet: ChangeSetSummary): Promise<void> {
@@ -26,13 +26,6 @@ export function matchesSearch(
26
26
  return haystack.some((text) => text.toLowerCase().includes(needle));
27
27
  }
28
28
 
29
- /** The `?set=<id>` deep link of the page, if any. */
30
- export function readSelectedSet(): string | undefined {
31
- if (typeof window === "undefined") return undefined;
32
- const params = new URLSearchParams(window.location.search);
33
- return params.get(CHANGE_SET_QUERY_KEY) ?? undefined;
34
- }
35
-
36
29
  /**
37
30
  * Keeps the selected set in the URL without a visit, so a reload or a shared
38
31
  * link opens it again.
@@ -6,7 +6,7 @@
6
6
  "license": "Apache-2.0",
7
7
  "packageManager": "pnpm@10.6.5",
8
8
  "engines": {
9
- "@antelopejs/dms-frontend": ">=0.5.5 <0.6.0"
9
+ "@antelopejs/dms-frontend": ">=0.6.0 <0.7.0"
10
10
  },
11
11
  "scripts": {
12
12
  "build": "pnpm --dir \"${DMS_FRONTEND_WORKSPACE:?Set DMS_FRONTEND_WORKSPACE to the generated Inertia workspace}\" build",
@@ -0,0 +1,69 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { nextTick, ref } from "vue";
3
+ import {
4
+ type AssistantStatusPayload,
5
+ createAssistantActivity,
6
+ } from "../app/runtime/assistant-activity";
7
+ import type { ChatTransport } from "../app/runtime/chat-transport";
8
+
9
+ type Listener = (msg: object) => void;
10
+
11
+ function fakeChat() {
12
+ const listeners = new Set<Listener>();
13
+ const chat = {
14
+ onMessage: (listener: Listener) => {
15
+ listeners.add(listener);
16
+ return () => listeners.delete(listener);
17
+ },
18
+ } as unknown as ChatTransport;
19
+ return { chat, emit: (msg: object) => listeners.forEach((l) => l(msg)) };
20
+ }
21
+
22
+ describe("assistant activity", () => {
23
+ it("polls the status through the read's interval while it is useful, and stops on teardown", async () => {
24
+ const data = ref<AssistantStatusPayload | null>(null);
25
+ let interval: () => number = () => -1;
26
+ const isPanelOpen = ref(false);
27
+ const { chat } = fakeChat();
28
+ const activity = createAssistantActivity({
29
+ readStatus: (given) => {
30
+ interval = given;
31
+ return { data, refresh: async () => undefined };
32
+ },
33
+ chat,
34
+ shouldPoll: () => !isPanelOpen.value,
35
+ });
36
+ expect(interval()).toBe(15_000);
37
+ isPanelOpen.value = true;
38
+ expect(interval()).toBe(0);
39
+ isPanelOpen.value = false;
40
+ activity.stop();
41
+ expect(interval()).toBe(0);
42
+ });
43
+
44
+ it("takes its counts from each status answer and from the stream's lists", async () => {
45
+ const data = ref<AssistantStatusPayload | null>(null);
46
+ const { chat, emit } = fakeChat();
47
+ const activity = createAssistantActivity({
48
+ readStatus: () => ({ data, refresh: async () => undefined }),
49
+ chat,
50
+ shouldPoll: () => true,
51
+ });
52
+ data.value = { pendingApprovals: 2, workingConversations: 0 };
53
+ await nextTick();
54
+ expect(activity.pendingApprovals.value).toBe(2);
55
+ expect(activity.isBusy.value).toBe(true);
56
+ emit({ type: "conversation_list", conversations: [{ isRunning: true }] });
57
+ expect(activity.pendingApprovals.value).toBe(0);
58
+ expect(activity.workingConversations.value).toBe(1);
59
+ data.value = {
60
+ pendingApprovals: 0,
61
+ workingConversations: 0,
62
+ lastError: "boom",
63
+ };
64
+ await nextTick();
65
+ expect(activity.workingConversations.value).toBe(0);
66
+ expect(activity.lastError.value).toBe("boom");
67
+ activity.stop();
68
+ });
69
+ });
@@ -57,7 +57,7 @@ function loadPlugin(loggedIn: Ref<boolean>): PluginHarness {
57
57
  new Function(
58
58
  "require",
59
59
  "exports",
60
- "useUserSession",
60
+ "useDmsUserSession",
61
61
  "useAuthFetch",
62
62
  "useToast",
63
63
  "useDevReload",
@@ -1,39 +1,117 @@
1
1
  import { describe, expect, it, vi } from "vitest";
2
- import { createSidecarStatusController } from "../app/runtime/sidecar-status";
2
+ import { computed, nextTick, type Ref, ref } from "vue";
3
+ import {
4
+ createSidecarStatusController,
5
+ type SidecarInfoPayload,
6
+ type SidecarInfoRead,
7
+ } from "../app/runtime/sidecar-status";
8
+
9
+ type Answer = SidecarInfoPayload | Error;
10
+
11
+ interface FakeRead extends SidecarInfoRead {
12
+ /** The polling interval the controller asks for. */
13
+ interval: Readonly<Ref<number>>;
14
+ reads: () => number;
15
+ }
16
+
17
+ /** `useApiData` as the controller uses it: each read takes the next answer. */
18
+ function fakeRead(answers: Answer[]) {
19
+ let opened: FakeRead | undefined;
20
+ const open = (interval: Readonly<Ref<number>>): SidecarInfoRead => {
21
+ const data = ref<SidecarInfoPayload | null>(null);
22
+ const error = ref<unknown>(null);
23
+ const status = ref<"idle" | "pending" | "done">("idle");
24
+ let count = 0;
25
+ const refresh = async (): Promise<void> => {
26
+ status.value = "pending";
27
+ await Promise.resolve();
28
+ const answer = answers[Math.min(count, answers.length - 1)];
29
+ count += 1;
30
+ if (answer instanceof Error) error.value = answer;
31
+ else {
32
+ data.value = answer ?? null;
33
+ error.value = null;
34
+ }
35
+ status.value = "done";
36
+ };
37
+ opened = {
38
+ data,
39
+ error,
40
+ pending: computed(() => status.value === "pending"),
41
+ execute: refresh,
42
+ refresh,
43
+ interval,
44
+ reads: () => count,
45
+ };
46
+ return opened;
47
+ };
48
+ return { open, read: () => opened! };
49
+ }
3
50
 
4
51
  describe("sidecar status", () => {
5
52
  it("reports connected from the status alone, and keeps no port or credential", async () => {
6
- const controller = createSidecarStatusController(async () => ({
7
- isRunning: true,
8
- }));
53
+ const { open, read } = fakeRead([{ isRunning: true }]);
54
+ const controller = createSidecarStatusController(open);
9
55
  expect(await controller.init()).toBe(true);
10
56
  expect(controller.getStatus()).toBe("connected");
57
+ expect(read().interval.value).toBe(0);
11
58
  expect(Object.keys(controller)).not.toContain("getPort");
12
59
  expect(Object.keys(controller)).not.toContain("getClientToken");
13
60
  controller.dispose();
14
61
  });
15
62
 
16
63
  it("re-probes when the channel drops, and reports connected once the sidecar answers", async () => {
17
- const fetchInfo = vi
18
- .fn()
19
- .mockResolvedValueOnce({ isRunning: true })
20
- .mockResolvedValueOnce({ isRunning: true });
64
+ const { open, read } = fakeRead([{ isRunning: true }]);
21
65
  const statuses: string[] = [];
22
- const controller = createSidecarStatusController(fetchInfo);
66
+ const controller = createSidecarStatusController(open);
23
67
  await controller.init();
24
68
  controller.subscribe((status) => statuses.push(status));
25
69
  controller.reportChannelDown();
26
70
  await vi.waitFor(() => expect(statuses.at(-1)).toBe("connected"));
27
71
  expect(statuses).toEqual(["connected", "reviving", "connected"]);
28
- expect(fetchInfo).toHaveBeenCalledTimes(2);
72
+ expect(read().reads()).toBe(2);
29
73
  controller.dispose();
30
74
  });
31
75
 
32
- it("does not show the assistant when spawning is disabled", async () => {
33
- const controller = createSidecarStatusController(async () => ({
34
- disabled: true,
35
- }));
36
- expect(await controller.init()).toBe(false);
76
+ it("polls through the read's interval, backing off while the sidecar comes back, and stops once it runs", async () => {
77
+ const { open, read } = fakeRead([
78
+ { isRunning: false },
79
+ new Error("Bad Gateway"),
80
+ { isRunning: true },
81
+ ]);
82
+ const controller = createSidecarStatusController(open);
83
+ expect(await controller.init()).toBe(true);
84
+ expect(controller.getStatus()).toBe("reviving");
85
+ expect(read().interval.value).toBe(500);
86
+ await read().refresh();
87
+ expect(read().interval.value).toBe(1000);
88
+ await read().refresh();
89
+ await nextTick();
90
+ expect(controller.getStatus()).toBe("connected");
91
+ expect(read().interval.value).toBe(0);
92
+ controller.dispose();
93
+ });
94
+
95
+ it("stops polling once the sidecar gives up", async () => {
96
+ const { open, read } = fakeRead([{ hasGivenUp: true }]);
97
+ const controller = createSidecarStatusController(open);
98
+ await controller.init();
99
+ expect(controller.getStatus()).toBe("unavailable");
100
+ expect(read().interval.value).toBe(0);
37
101
  controller.dispose();
38
102
  });
103
+
104
+ it("does not show the assistant when spawning is disabled, and polls nothing", async () => {
105
+ const { open, read } = fakeRead([{ disabled: true }]);
106
+ const controller = createSidecarStatusController(open);
107
+ expect(await controller.init()).toBe(false);
108
+ expect(read().interval.value).toBe(0);
109
+ });
110
+
111
+ it("does not show the assistant when the first probe fails", async () => {
112
+ const { open, read } = fakeRead([new Error("Not Found")]);
113
+ const controller = createSidecarStatusController(open);
114
+ expect(await controller.init()).toBe(false);
115
+ expect(read().interval.value).toBe(0);
116
+ });
39
117
  });
@@ -0,0 +1,9 @@
1
+ // The renderer's runtime (`#dms/frontend-module`), which only the generated
2
+ // application provides: the suites that import a view mock what they use.
3
+ export function useDmsRoute(): never {
4
+ throw new Error("Mock #dms/frontend-module in the suite that needs it");
5
+ }
6
+
7
+ export function useDmsRouter(): never {
8
+ throw new Error("Mock #dms/frontend-module in the suite that needs it");
9
+ }