forked from CopilotKit/CopilotKit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuse-copilot-authenticated-action.ts
More file actions
76 lines (69 loc) · 2.48 KB
/
Copy pathuse-copilot-authenticated-action.ts
File metadata and controls
76 lines (69 loc) · 2.48 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
import type { Parameter } from "@copilotkit/shared";
import { Fragment, useCallback, useRef } from "react";
import { useCopilotContext } from "../context/copilot-context";
import type {
FrontendAction,
ActionRenderProps,
} from "../types/frontend-action";
import { useCopilotAction } from "./use-copilot-action";
import React from "react";
/**
* Hook to create an authenticated action that requires user sign-in before execution.
*
* @remarks
* This feature is only available when using CopilotKit's hosted cloud service.
* To use this feature, sign up at https://dashboard.operations.copilotkit.ai to get your publicApiKey.
*
* @param action - The frontend action to be wrapped with authentication
* @param dependencies - Optional array of dependencies that will trigger recreation of the action when changed
*/
export function useCopilotAuthenticatedAction_c<T extends Parameter[]>(
action: FrontendAction<T>,
dependencies?: any[],
): void {
const { authConfig_c, authStates_c, setAuthStates_c } = useCopilotContext();
const pendingActionRef = useRef<ActionRenderProps<Parameter[]> | null>(null);
const executeAction = useCallback(
(props: ActionRenderProps<Parameter[]>) => {
if (typeof action.render === "function") {
return action.render(props);
}
return action.render || React.createElement(Fragment);
},
[action],
);
const wrappedRender = useCallback(
(props: ActionRenderProps<Parameter[]>): string | React.ReactElement => {
const isAuthenticated = Object.values(authStates_c || {}).some(
(state) => state.status === "authenticated",
);
if (!isAuthenticated) {
// Store action details for later execution
pendingActionRef.current = props;
return authConfig_c?.SignInComponent
? React.createElement(authConfig_c.SignInComponent, {
onSignInComplete: (authState) => {
setAuthStates_c?.((prev) => ({
...prev,
[action.name]: authState,
}));
if (pendingActionRef.current) {
executeAction(pendingActionRef.current);
pendingActionRef.current = null;
}
},
})
: React.createElement(Fragment);
}
return executeAction(props);
},
[action, authStates_c, setAuthStates_c],
);
useCopilotAction(
{
...action,
render: wrappedRender,
} as FrontendAction<T>,
dependencies,
);
}