Skip to content

Commit

Permalink
- feature: added set oauth token
Browse files Browse the repository at this point in the history
  • Loading branch information
agallardol committed Dec 11, 2024
1 parent 69fee3b commit fdd11d5
Show file tree
Hide file tree
Showing 12 changed files with 175 additions and 11 deletions.
1 change: 1 addition & 0 deletions apps/shinkai-desktop/src-tauri/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion apps/shinkai-desktop/src-tauri/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ uuid = "1.10.0"

tauri-plugin-global-shortcut = "2.2"
tauri-plugin-shell = "2.2"
tauri-plugin-single-instance = "2.2"
tauri-plugin-single-instance = { version = "2.2", features = ["deep-link"] }
tauri-plugin-updater = "2.3"
tauri-plugin-dialog = "2.2"
tauri-plugin-fs ="2.2"
Expand Down
45 changes: 45 additions & 0 deletions apps/shinkai-desktop/src-tauri/src/deep_links.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use tauri::{Emitter, EventTarget};
use tauri_plugin_deep_link::DeepLinkExt;

use crate::windows::{recreate_window, Window};

#[derive(Debug, Clone, serde::Serialize)]
pub struct OAuthDeepLinkPayload {
pub state: String,
pub code: String,
}

pub fn setup_deep_links(app: &tauri::AppHandle) -> tauri::Result<()> {
#[cfg(any(windows, target_os = "linux"))]
{
use tauri_plugin_deep_link::DeepLinkExt;
app.deep_link()
.register_all()
.map_err(|e| tauri::Error::Anyhow(e.into()))?;
}
let app_handle = app.clone();
app.deep_link().on_open_url(move |event| {
let urls: Vec<_> = event.urls().into_iter().collect();
log::debug!("deep link URLs: {:?}", urls);
for url in urls {
log::debug!("handling deep link: {:?}", url);
if let Some(host) = url.host() {
if host.to_string() == "oauth" {
log::debug!("oauth deep link: {:?}", url);
let payload = OAuthDeepLinkPayload {
state: url.query().unwrap_or_default().to_string(),
code: url.query().unwrap_or_default().to_string(),
};
log::debug!("emitting oauth-deep-link event to {}", Window::Coordinator.as_str());
let _ = recreate_window(app_handle.clone(), Window::Main, true);
let _ = app_handle.emit_to(
EventTarget::webview_window(Window::Coordinator.as_str()),
"oauth-deep-link",
payload,
);
}
}
}
});
Ok(())
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,5 +11,5 @@ pub fn toggle_spotlight(app: &tauri::AppHandle, _: Shortcut, _: ShortcutEvent) {
return;
}
}
recreate_window(app.clone(), Window::Spotlight, true)
recreate_window(app.clone(), Window::Spotlight, true);
}
15 changes: 10 additions & 5 deletions apps/shinkai-desktop/src-tauri/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ use tauri::{Manager, RunEvent};
use tokio::sync::Mutex;
use tray::create_tray;
use windows::{recreate_window, Window};

use deep_links::setup_deep_links;
mod audio;
mod commands;
mod galxe;
Expand All @@ -32,6 +32,7 @@ mod hardware;
mod local_shinkai_node;
mod tray;
mod windows;
mod deep_links;

#[derive(Clone, serde::Serialize)]
struct Payload {
Expand All @@ -41,16 +42,16 @@ struct Payload {

fn main() {
tauri::Builder::default()
.plugin(tauri_plugin_single_instance::init(|app, argv, cwd| {
app.emit("single-instance", Payload { args: argv, cwd })
.unwrap();
}))
.plugin(tauri_plugin_log::Builder::new().build())
.plugin(tauri_plugin_os::init())
.plugin(tauri_plugin_updater::Builder::new().build())
.plugin(tauri_plugin_shell::init())
.plugin(tauri_plugin_fs::init())
.plugin(tauri_plugin_process::init())
.plugin(tauri_plugin_single_instance::init(|app, argv, cwd| {
app.emit("single-instance", Payload { args: argv, cwd })
.unwrap();
}))
.plugin(tauri_plugin_dialog::init())
.plugin(
tauri_plugin_global_shortcut::Builder::new()
Expand All @@ -70,6 +71,7 @@ fn main() {
)
.build(),
)
.plugin(tauri_plugin_deep_link::init())
.invoke_handler(tauri::generate_handler![
hide_spotlight_window_app,
show_spotlight_window_app,
Expand Down Expand Up @@ -102,6 +104,7 @@ fn main() {
}

create_tray(app.handle())?;
setup_deep_links(app.handle())?;

/*
This is the initialization pipeline
Expand Down Expand Up @@ -139,6 +142,8 @@ fn main() {
}
});



Ok(())
})
.build(tauri::generate_context!())
Expand Down
14 changes: 10 additions & 4 deletions apps/shinkai-desktop/src-tauri/src/windows/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use tauri::{AppHandle, Manager, WebviewWindowBuilder};
use tauri::{AppHandle, Manager, WebviewWindow, WebviewWindowBuilder};

#[derive(Debug, Clone, Copy)]
pub enum Window {
Expand All @@ -19,7 +19,7 @@ impl Window {
}
}

pub fn recreate_window(app_handle: AppHandle, window_name: Window, focus: bool) {
pub fn recreate_window(app_handle: AppHandle, window_name: Window, focus: bool) -> tauri::Result<WebviewWindow> {
let label = window_name.as_str();
if let Some(window) = app_handle.get_webview_window(label) {
log::info!("window {} found, bringing to front", label);
Expand All @@ -32,6 +32,7 @@ pub fn recreate_window(app_handle: AppHandle, window_name: Window, focus: bool)
// window.center().unwrap();
let _ = window.set_focus();
}
return Ok(window);
} else {
log::info!("window {} not found, recreating...", label);
let window_config = app_handle
Expand All @@ -44,13 +45,18 @@ pub fn recreate_window(app_handle: AppHandle, window_name: Window, focus: bool)
.clone();
match WebviewWindowBuilder::from_config(&app_handle, &window_config) {
Ok(builder) => match builder.build() {
Ok(_) => {
Ok(window) => {
log::info!("window {} created", label);
return Ok(window)
}
Err(e) => log::error!("failed to recreate window: {}", e),
Err(e) => {
log::error!("failed to recreate window: {}", e);
Err(e)
},
},
Err(e) => {
log::error!("failed to recreate window from config: {}", e);
Err(e)
}
}
}
Expand Down
5 changes: 5 additions & 0 deletions apps/shinkai-desktop/src-tauri/tauri.conf.json
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,11 @@
"windows": {
"installMode": "basicUi"
}
},
"deep-link": {
"desktop": {
"schemes": ["shinkai"]
}
}
},
"app": {
Expand Down
34 changes: 34 additions & 0 deletions apps/shinkai-desktop/src/hooks/use-oauth-deep-link.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import { useSetOAuthToken } from '@shinkai_network/shinkai-node-state/v2/mutations/setOAuthToken/index';
import { emit, listen } from '@tauri-apps/api/event';
import { useEffect } from 'react';

import { useAuth } from '../store/auth';

export const useOAuthDeepLink = () => {
const { mutateAsync: setOAuthToken } = useSetOAuthToken({
onSuccess: (data) => {
console.log('oauth-success', data);
emit('oauth-success', data);
},
});
const auth = useAuth((s) => s.auth);

useEffect(() => {
if (!auth) return;
const unlisten = listen('oauth-deep-link', (event) => {
console.log('useOAuthDeepLink');

const payload = event.payload as { state: string; code: string };
setOAuthToken({
state: payload.state,
code: payload.code,
nodeAddress: auth.node_address ?? '',
token: auth.api_v2_key ?? '',
});
});

return () => {
unlisten.then((fn) => fn());
};
}, [setOAuthToken, auth]);
};
3 changes: 3 additions & 0 deletions apps/shinkai-desktop/src/windows/coordinator/main.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { info } from '@tauri-apps/plugin-log';
import React, { useEffect } from 'react';
import ReactDOM from 'react-dom/client';

import { useOAuthDeepLink } from '../../hooks/use-oauth-deep-link';
import {
useSyncStorageMain,
useSyncStorageSecondary,
Expand All @@ -15,6 +16,8 @@ const App = () => {
useSyncStorageMain();
useSyncStorageSecondary();
useSyncStorageSideEffects();
useOAuthDeepLink();

return null;
};

Expand Down
19 changes: 19 additions & 0 deletions libs/shinkai-message-ts/src/api/tools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import {
SaveToolCodeRequest,
SaveToolCodeResponse,
SearchPromptsResponse,
SetOAuthTokenRequest,
SetOAuthTokenResponse,
UndoToolImplementationRequest,
UndoToolImplementationResponse,
UpdatePromptRequest,
Expand Down Expand Up @@ -273,6 +275,7 @@ export const saveToolCode = async (
);
return response.data as SaveToolCodeResponse;
};

export const getPlaygroundTools = async (
nodeAddress: string,
bearerToken: string,
Expand Down Expand Up @@ -366,3 +369,19 @@ export const exportTool = async (
);
return response.data as ExportToolResponse;
};

export const setOAuthToken = async (
nodeAddress: string,
bearerToken: string,
payload: SetOAuthTokenRequest,
): Promise<SetOAuthTokenResponse> => {
const response = await httpClient.post(
urlJoin(nodeAddress, '/v2/set_oauth_token'),
payload,
{
headers: { Authorization: `Bearer ${bearerToken}` },
responseType: 'json',
},
);
return response.data as SetOAuthTokenResponse;
};
10 changes: 10 additions & 0 deletions libs/shinkai-message-ts/src/api/tools/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -292,3 +292,13 @@ export type ExportToolRequest = {
};

export type ExportToolResponse = Blob;

export type SetOAuthTokenRequest = {
code: string;
state: string;
};

export type SetOAuthTokenResponse = {
message: string;
status: string;
};
36 changes: 36 additions & 0 deletions libs/shinkai-node-state/src/v2/mutations/setOAuthToken/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { setOAuthToken } from '@shinkai_network/shinkai-message-ts/api/tools/index';
import { useMutation, UseMutationOptions } from '@tanstack/react-query';

import { APIError } from '../../types';

export type SetOAuthTokenInput = {
nodeAddress: string;
token: string;
state: string;
code: string;
};

export type SetOAuthTokenOutput = {
state: string;
code: string;
};

type Options = UseMutationOptions<
SetOAuthTokenOutput,
APIError,
SetOAuthTokenInput
>;

export const useSetOAuthToken = (options?: Options) => {
return useMutation({
mutationFn: async (variables) => {
const { nodeAddress, token, state, code } = variables;
await setOAuthToken(nodeAddress, token, {
code,
state,
});
return { code, state };
},
...options,
});
};

0 comments on commit fdd11d5

Please sign in to comment.