Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

- feature: implemented react-query and zustand #33

Merged
merged 5 commits into from
Oct 8, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 42 additions & 30 deletions apps/shinkai-visor/src/components/add-agent/add-agent.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import { zodResolver } from '@hookform/resolvers/zod';
import { useCreateAgent } from "@shinkai_network/shinkai-node-state/lib/mutations/createAgent/useCreateAgent";
import { Loader2 } from 'lucide-react';
import { useForm } from 'react-hook-form';
import { FormattedMessage, useIntl } from 'react-intl';
import { useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import { z } from 'zod';

import { RootState, useTypedDispatch } from '../../store';
import { addAgent } from '../../store/agents/agents-actions';
import { useAuth } from '../../store/auth/auth';
import { Button } from '../ui/button';
import {
Form,
Expand Down Expand Up @@ -38,11 +37,12 @@ const formSchema = z.object({
model: z.nativeEnum(Models),
});

type AddAgentFieldType = z.infer<typeof formSchema>;
type FormSchemaType = z.infer<typeof formSchema>;

export const AddAgent = () => {
const history = useHistory();
const form = useForm<AddAgentFieldType>({
const auth = useAuth((state) => state.auth);
const form = useForm<FormSchemaType>({
resolver: zodResolver(formSchema),
defaultValues: {
agentName: 'gpt',
Expand All @@ -52,9 +52,17 @@ export const AddAgent = () => {
},
});
const intl = useIntl();
const isLoading = useSelector(
(state: RootState) => state.agents?.add?.status === 'loading',
);
const {
mutateAsync: createAgent,
isLoading,
isError,
error,
} = useCreateAgent({
onSuccess: () => {
history.replace('/agents');
},
});

const modelOptions: { value: Models; label: string }[] = [
{
value: Models.OpenAI,
Expand All @@ -65,28 +73,32 @@ export const AddAgent = () => {
label: intl.formatMessage({ id: 'sleep-api' }),
},
];
const dispatch = useTypedDispatch();
const submit = (values: AddAgentFieldType) => {
dispatch(
addAgent({
agent: {
agentName: values.agentName,
externalUrl: values.externalUrl,
apiKey: values.apiKey,
model:
values.model === Models.OpenAI
? { OpenAI: { model_type: 'gpt-3.5-turbo' } }
: { SleepAPI: {} },
},
}),
)
.unwrap()
.then(() => {
history.replace('/agents');
})
.catch(() => {
console.log('error adding agent');
});
const submit = (values: FormSchemaType) => {
if (!auth) return;
createAgent({
sender_subidentity: auth.profile,
node_name: auth.shinkai_identity,
agent: {
allowed_message_senders: [],
api_key: values.apiKey,
external_url: values.externalUrl,
full_identity_name: `${auth.shinkai_identity}/${auth.profile}/agent/${values.agentName}`,
id: values.agentName,
perform_locally: false,
storage_bucket_permissions: [],
toolkit_permissions: [],
model: values.model === Models.OpenAI
? { OpenAI: { model_type: 'gpt-3.5-turbo' } }
: { SleepAPI: {} },
},
setupDetailsState: {
my_device_encryption_sk: auth.my_device_encryption_sk,
my_device_identity_sk: auth.my_device_identity_sk,
node_encryption_pk: auth.node_encryption_pk,
profile_encryption_sk: auth.profile_encryption_sk,
profile_identity_sk: auth.profile_identity_sk,
},
});
};
return (
<div className="h-full p-1">
Expand Down
114 changes: 54 additions & 60 deletions apps/shinkai-visor/src/components/add-node/add-node.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,18 +5,17 @@ import {
generateEncryptionKeys,
generateSignatureKeys,
} from '@shinkai_network/shinkai-message-ts/utils';
import { useSubmitRegistration } from '@shinkai_network/shinkai-node-state/lib/mutations/submitRegistation/useSubmitRegistration';
import { BrowserQRCodeReader } from '@zxing/browser';
import { Loader2 } from 'lucide-react';
import { useEffect, useRef, useState } from 'react';
import { useForm } from 'react-hook-form';
import { FormattedMessage } from 'react-intl';
import { useSelector } from 'react-redux';
import { useHistory } from 'react-router-dom';
import * as z from 'zod';

import ScanQrAnimation from '../../assets/animations/scan-qr.json';
import { RootState, useTypedDispatch } from '../../store';
import { connectNode } from '../../store/node/node-actions';
import { useAuth } from '../../store/auth/auth';
import { Button } from '../ui/button';
import {
Form,
Expand Down Expand Up @@ -66,6 +65,7 @@ enum AddNodeSteps {

export const AddNode = () => {
const history = useHistory();
const setAuth = useAuth((state) => state.setAuth);
const form = useForm<FormType>({
resolver: zodResolver(formSchema),
defaultValues: {
Expand All @@ -88,22 +88,48 @@ export const AddNode = () => {
myDeviceIdentitySharedKey: undefined,
},
});
const {
isLoading,
mutateAsync: submitRegistration,
} = useSubmitRegistration({
onSuccess: (response) => {
if (response.success) {
const values = form.getValues();
setAuth({
profile: values.profile,
permission_type: values.permissionType,
node_address: values.nodeAddress,
shinkai_identity: values.shinkaiIdentity,
node_signature_pk: response.data?.identity_public_key ?? values.nodeSignaturePublicKey,
node_encryption_pk: response.data?.encryption_public_key ?? values.nodeEncryptionPublicKey,
registration_name: values.registrationName,
my_device_identity_pk: values.myDeviceIdentityPublicKey,
my_device_identity_sk: values.myDeviceIdentitySharedKey,
my_device_encryption_pk: values.myDeviceEncryptionPublicKey,
my_device_encryption_sk: values.myDeviceEncryptionSharedKey,
profile_identity_pk: values.profileSignaturePublicKey,
profile_identity_sk: values.profileSignatureSharedKey,
profile_encryption_pk: values.profileEncryptionPublicKey,
profile_encryption_sk: values.profileEncryptionSharedKey,
});
history.replace('/inboxes');
} else {
throw new Error('Failed to submit registration');
}
},
});

const fileInput = useRef<HTMLInputElement>(null);
const [currentStep, setCurrentStep] = useState<AddNodeSteps>(
AddNodeSteps.ScanQR,
AddNodeSteps.ScanQR
);
// const currentFormValue = Form.useWatch([], form);
const isConnecting = useSelector(
(state: RootState) => state?.node?.status === 'loading',
);
const dispatch = useTypedDispatch();

const onFileInputClick = () => {
fileInput.current?.click();
};

const onQrImageSelected: React.ChangeEventHandler<HTMLInputElement> = async (
event,
event
): Promise<void> => {
if (!event.target.files || !event.target.files[0]) {
return;
Expand Down Expand Up @@ -177,54 +203,22 @@ export const AddNode = () => {
};
};

const connectManually = () => {
setCurrentStep(AddNodeSteps.Connect);
};

const scanQr = () => {
form.reset();
setCurrentStep(AddNodeSteps.ScanQR);
};

const connect = (values: FormType) => {
setCurrentStep(AddNodeSteps.Connect);
dispatch(
connectNode({
nodeData: {
registrationCode: values.registrationCode,
profile: values.profile,
identityType: values.identityType,
permissionType: values.permissionType,
nodeAddress: values.nodeAddress,
shinkaiIdentity: values.shinkaiIdentity,
nodeEncryptionPublicKey: values.nodeEncryptionPublicKey,
nodeSignaturePublicKey: values.nodeSignaturePublicKey,
},
userData: {
registrationName: values.registrationName,
},
credentials: {
myDeviceIdentityPublicKey: values.myDeviceEncryptionPublicKey,
myDeviceIdentitySharedKey: values.myDeviceEncryptionSharedKey,

myDeviceEncryptionPublicKey: values.myDeviceIdentityPublicKey,
myDeviceEncryptionSharedKey: values.myDeviceEncryptionSharedKey,

profileSignaturePublicKey: values.profileSignaturePublicKey,
profileSignatureSharedKey: values.profileSignatureSharedKey,

profileEncryptionPublicKey: values.profileEncryptionPublicKey,
profileEncryptionSharedKey: values.profileEncryptionSharedKey,
},
}),
)
.unwrap()
.then(() => {
history.replace('/inboxes');
})
.catch((e) => {
console.log(e);
});
console.log('values', values);
submitRegistration({
registration_code: values.registrationCode,
profile: values.profile,
identity_type: values.identityType,
permission_type: values.permissionType,
node_address: values.nodeAddress,
shinkai_identity: values.shinkaiIdentity,
node_encryption_pk: values.nodeEncryptionPublicKey,
registration_name: values.registrationName,
my_device_identity_sk: values.myDeviceIdentitySharedKey,
my_device_encryption_sk: values.myDeviceEncryptionSharedKey,
profile_identity_sk: values.profileSignatureSharedKey,
profile_encryption_sk: values.profileEncryptionSharedKey,
});
};

useEffect(() => {
Expand All @@ -247,7 +241,7 @@ export const AddNode = () => {
...profileEncryption,
...profileSignature,
}));
},
}
);
}, [form]);

Expand Down Expand Up @@ -324,10 +318,10 @@ export const AddNode = () => {
</div>
<Button
className="w-full"
disabled={!form.formState.isValid || isConnecting}
disabled={!form.formState.isValid || isLoading}
type="submit"
>
{isConnecting && (
{isLoading && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
<FormattedMessage id="connect" />
Expand Down
23 changes: 13 additions & 10 deletions apps/shinkai-visor/src/components/agents/agents.tsx
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
import { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { useAgents } from "@shinkai_network/shinkai-node-state/lib/queries/getAgents/useGetAgents";

import { RootState, useTypedDispatch } from '../../store';
import { getAgents } from '../../store/agents/agents-actions';
import { useAuth } from '../../store/auth/auth';
import { ScrollArea } from '../ui/scroll-area';
import { Separator } from '../ui/separator';

export const Agents = () => {
const dispatch = useTypedDispatch();
const agents = useSelector((state: RootState) => state.agents?.agents?.data);
useEffect(() => {
dispatch(getAgents());
}, [dispatch]);

const auth = useAuth((state) => state.auth);
const { agents } = useAgents({
sender: auth?.shinkai_identity ?? "",
senderSubidentity: `${auth?.profile}`,
shinkaiIdentity: auth?.shinkai_identity ?? "",
my_device_encryption_sk: auth?.profile_encryption_sk ?? "",
my_device_identity_sk: auth?.profile_identity_sk ?? "",
node_encryption_pk: auth?.node_encryption_pk ?? "",
profile_encryption_sk: auth?.profile_encryption_sk ?? "",
profile_identity_sk: auth?.profile_identity_sk ?? "",
});
return (
<div className="h-full flex flex-col space-y-3 justify-between">
<ScrollArea>
Expand Down
Loading