test scpt

This commit is contained in:
2025-06-16 22:27:20 +09:00
parent 1e83b50e3f
commit 5339dd28b0
11 changed files with 52 additions and 64 deletions

View File

@ -176,7 +176,7 @@ function App() {
}); });
} }
} catch (err) { } catch (err) {
console.error('Failed to load AI profile:', err); // Failed to load AI profile
// Fallback to config values // Fallback to config values
setAiProfile({ setAiProfile({
did: appConfig.aiDid, did: appConfig.aiDid,
@ -221,7 +221,7 @@ function App() {
// Check if handle is allowed // Check if handle is allowed
if (appConfig.allowedHandles.length > 0 && !appConfig.allowedHandles.includes(handle)) { if (appConfig.allowedHandles.length > 0 && !appConfig.allowedHandles.includes(handle)) {
console.warn(`Handle ${handle} is not in allowed list:`, appConfig.allowedHandles); // Handle not in allowed list
setError(`Access denied: ${handle} is not authorized for this application.`); setError(`Access denied: ${handle} is not authorized for this application.`);
setIsLoading(false); setIsLoading(false);
return; return;
@ -252,7 +252,7 @@ function App() {
if (verifiedUser) { if (verifiedUser) {
// Check if handle is allowed // Check if handle is allowed
if (appConfig.allowedHandles.length > 0 && !appConfig.allowedHandles.includes(verifiedUser.handle)) { if (appConfig.allowedHandles.length > 0 && !appConfig.allowedHandles.includes(verifiedUser.handle)) {
console.warn(`Handle ${verifiedUser.handle} is not in allowed list:`, appConfig.allowedHandles); // Handle not in allowed list
setError(`Access denied: ${verifiedUser.handle} is not authorized for this application.`); setError(`Access denied: ${verifiedUser.handle} is not authorized for this application.`);
setIsLoading(false); setIsLoading(false);
return; return;
@ -288,7 +288,6 @@ function App() {
// DID解決完了時にデータを再読み込み // DID解決完了時にデータを再読み込み
useEffect(() => { useEffect(() => {
if (adminDid && aiDid) { if (adminDid && aiDid) {
console.log('DIDs resolved, loading comments and chat history...');
loadAllComments(); loadAllComments();
loadAiChatHistory(); loadAiChatHistory();
} }
@ -556,7 +555,6 @@ function App() {
try { try {
// 管理者のユーザーリストを取得 using proper PDS detection // 管理者のユーザーリストを取得 using proper PDS detection
const currentAdminDid = adminDid || appConfig.adminDid; const currentAdminDid = adminDid || appConfig.adminDid;
console.log('loadUsersFromRecord: Using Admin DID:', currentAdminDid);
// Use per-user PDS detection for admin's records // Use per-user PDS detection for admin's records
let adminPdsEndpoint; let adminPdsEndpoint;
@ -569,25 +567,19 @@ function App() {
} }
const userCollectionUrl = `${adminPdsEndpoint}/xrpc/com.atproto.repo.listRecords?repo=${encodeURIComponent(currentAdminDid)}&collection=${encodeURIComponent(getCollectionNames(appConfig.collections.base).user)}&limit=100`; const userCollectionUrl = `${adminPdsEndpoint}/xrpc/com.atproto.repo.listRecords?repo=${encodeURIComponent(currentAdminDid)}&collection=${encodeURIComponent(getCollectionNames(appConfig.collections.base).user)}&limit=100`;
console.log('loadUsersFromRecord: Fetching from URL:', userCollectionUrl);
const response = await fetch(userCollectionUrl); const response = await fetch(userCollectionUrl);
console.log('loadUsersFromRecord: Response status:', response.status);
if (!response.ok) { if (!response.ok) {
console.log('loadUsersFromRecord: Failed to fetch, using default users');
return getDefaultUsers(); return getDefaultUsers();
} }
const data = await response.json(); const data = await response.json();
const userRecords = data.records || []; const userRecords = data.records || [];
console.log('loadUsersFromRecord: Found user records:', userRecords.length);
if (userRecords.length === 0) { if (userRecords.length === 0) {
console.log('loadUsersFromRecord: No user records found, using default users');
const defaultUsers = getDefaultUsers(); const defaultUsers = getDefaultUsers();
console.log('loadUsersFromRecord: Default users:', defaultUsers);
return defaultUsers; return defaultUsers;
} }
@ -620,7 +612,6 @@ function App() {
} }
} }
console.log('loadUsersFromRecord: Resolved users:', allUsers);
return allUsers; return allUsers;
} catch (err) { } catch (err) {
// Failed to load users from records, using defaults // Failed to load users from records, using defaults
@ -689,7 +680,6 @@ function App() {
}); });
} }
console.log('getDefaultUsers: Returning default users:', defaultUsers);
return defaultUsers; return defaultUsers;
}; };
@ -699,7 +689,6 @@ function App() {
// ユーザーリストを動的に取得 // ユーザーリストを動的に取得
const knownUsers = await loadUsersFromRecord(); const knownUsers = await loadUsersFromRecord();
console.log('loadAllComments: Using users for comment fetching:', knownUsers);
const allComments = []; const allComments = [];
@ -1247,25 +1236,6 @@ function App() {
return ( return (
<div className="app"> <div className="app">
{/* Debug Info */}
<div style={{
padding: '10px',
backgroundColor: '#f0f0f0',
border: '1px solid #ccc',
marginBottom: '10px',
fontSize: '12px'
}}>
<strong>Debug Info:</strong><br />
Admin Handle: {appConfig.adminHandle}<br />
Admin DID (resolved): {adminDid || 'resolving...'}<br />
Admin DID (config): {appConfig.adminDid}<br />
AI Handle: {appConfig.aiHandle}<br />
AI DID (resolved): {aiDid || 'resolving...'}<br />
AI DID (config): {appConfig.aiDid}<br />
Collection Base: {appConfig.collections.base}<br />
User Collection: {appConfig.collections.base}.user<br />
DIDs Resolved: {adminDid && aiDid ? 'Yes' : 'No'}
</div>
<main className="app-main"> <main className="app-main">
<section className="comment-section"> <section className="comment-section">

View File

@ -32,7 +32,7 @@ export const AIProfile: React.FC<AIProfileProps> = ({ aiDid }) => {
description: response.data.description, description: response.data.description,
}); });
} catch (error) { } catch (error) {
console.error('Failed to fetch AI profile:', error); // Failed to fetch AI profile
// Fallback to basic info // Fallback to basic info
setProfile({ setProfile({
did: aiDid, did: aiDid,

View File

@ -26,7 +26,7 @@ export const CardBox: React.FC<CardBoxProps> = ({ userDid }) => {
const data = await atprotoOAuthService.getCardsFromBox(); const data = await atprotoOAuthService.getCardsFromBox();
setBoxData(data); setBoxData(data);
} catch (err) { } catch (err) {
console.error('カードボックス読み込みエラー:', err); // Failed to load card box
setError(err instanceof Error ? err.message : 'カードボックスの読み込みに失敗しました'); setError(err instanceof Error ? err.message : 'カードボックスの読み込みに失敗しました');
} finally { } finally {
setLoading(false); setLoading(false);
@ -52,7 +52,7 @@ export const CardBox: React.FC<CardBoxProps> = ({ userDid }) => {
setBoxData({ records: [] }); setBoxData({ records: [] });
alert('カードボックスを削除しました'); alert('カードボックスを削除しました');
} catch (err) { } catch (err) {
console.error('カードボックス削除エラー:', err); // Failed to delete card box
setError(err instanceof Error ? err.message : 'カードボックスの削除に失敗しました'); setError(err instanceof Error ? err.message : 'カードボックスの削除に失敗しました');
} finally { } finally {
setIsDeleting(false); setIsDeleting(false);

View File

@ -32,7 +32,7 @@ export const CardList: React.FC = () => {
const data = await response.json(); const data = await response.json();
setMasterData(data); setMasterData(data);
} catch (err) { } catch (err) {
console.error('Error loading card master data:', err); // Failed to load card master data
setError(err instanceof Error ? err.message : 'Failed to load card data'); setError(err instanceof Error ? err.message : 'Failed to load card data');
} finally { } finally {
setLoading(false); setLoading(false);

View File

@ -29,7 +29,7 @@ export const CollectionAnalysis: React.FC<CollectionAnalysisProps> = ({ userDid
const result = await aiCardApi.analyzeCollection(userDid); const result = await aiCardApi.analyzeCollection(userDid);
setAnalysis(result); setAnalysis(result);
} catch (err) { } catch (err) {
console.error('Collection analysis failed:', err); // Collection analysis failed
setError('AI分析機能を利用するにはai.gptサーバーが必要です。基本機能はai.cardサーバーのみで利用できます。'); setError('AI分析機能を利用するにはai.gptサーバーが必要です。基本機能はai.cardサーバーのみで利用できます。');
} finally { } finally {
setLoading(false); setLoading(false);

View File

@ -48,7 +48,7 @@ export const GachaAnimation: React.FC<GachaAnimationProps> = ({
await atprotoOAuthService.saveCardToCollection(card); await atprotoOAuthService.saveCardToCollection(card);
alert('カードデータをatprotoコレクションに保存しました'); alert('カードデータをatprotoコレクションに保存しました');
} catch (error) { } catch (error) {
console.error('保存エラー:', error); // Failed to save card
alert('保存に失敗しました。認証が必要かもしれません。'); alert('保存に失敗しました。認証が必要かもしれません。');
} finally { } finally {
setIsSharing(false); setIsSharing(false);

View File

@ -30,7 +30,7 @@ export const GachaStats: React.FC = () => {
try { try {
result = await aiCardApi.getEnhancedStats(); result = await aiCardApi.getEnhancedStats();
} catch (aiError) { } catch (aiError) {
console.warn('AI統計が利用できません、基本統計に切り替えます:', aiError); // AI stats unavailable, using basic stats
setUseAI(false); setUseAI(false);
result = await cardApi.getGachaStats(); result = await cardApi.getGachaStats();
} }
@ -39,7 +39,7 @@ export const GachaStats: React.FC = () => {
} }
setStats(result); setStats(result);
} catch (err) { } catch (err) {
console.error('Gacha stats failed:', err); // Gacha stats failed
setError('統計データの取得に失敗しました。ai.cardサーバーが起動していることを確認してください。'); setError('統計データの取得に失敗しました。ai.cardサーバーが起動していることを確認してください。');
} finally { } finally {
setLoading(false); setLoading(false);

View File

@ -168,7 +168,7 @@ export async function resolveHandleToDid(handle: string): Promise<{ did: string;
pds: actualPds pds: actualPds
}; };
} catch (error) { } catch (error) {
console.error(`Failed to resolve handle ${handle}:`, error); // Failed to resolve handle
// Fallback to handle-based detection // Fallback to handle-based detection
const fallbackPds = detectPdsFromHandle(handle); const fallbackPds = detectPdsFromHandle(handle);
@ -204,7 +204,7 @@ export async function getProfileForUser(handleOrDid: string, knownPdsEndpoint?:
return await response.json(); return await response.json();
} catch (error) { } catch (error) {
console.error(`Failed to get profile for ${handleOrDid}:`, error); // Failed to get profile
// Final fallback: try with default Bluesky API // Final fallback: try with default Bluesky API
try { try {

View File

@ -2,7 +2,7 @@
function _env() { function _env() {
d=${0:a:h} d=${0:a:h}
ailog=$d/target/release/ailog ailog=$d/target/debug/ailog
oauth=$d/oauth oauth=$d/oauth
myblog=$d/my-blog myblog=$d/my-blog
port=4173 port=4173
@ -16,10 +16,14 @@ function _env() {
esac esac
} }
function _deploy_ailog() {
}
function _server() { function _server() {
lsof -ti:$port | xargs kill -9 2>/dev/null || true lsof -ti:$port | xargs kill -9 2>/dev/null || true
cd $d/my-blog cd $d/my-blog
cargo build --release cargo build
cp -rf $ailog $CARGO_HOME/bin/
$ailog build $ailog build
$ailog serve --port $port $ailog serve --port $port
} }
@ -40,7 +44,8 @@ function _oauth_build() {
} }
function _server_comment() { function _server_comment() {
cargo build --release cargo build
cp -rf $ailog $CARGO_HOME/bin/
AILOG_DEBUG_ALL=1 $ailog stream start my-blog AILOG_DEBUG_ALL=1 $ailog stream start my-blog
} }

View File

@ -86,6 +86,7 @@ fn get_config_path() -> Result<PathBuf> {
Ok(config_dir.join("config.json")) Ok(config_dir.join("config.json"))
} }
#[allow(dead_code)]
pub async fn init() -> Result<()> { pub async fn init() -> Result<()> {
init_with_pds(None).await init_with_pds(None).await
} }
@ -202,6 +203,7 @@ pub async fn init_with_options(
Ok(()) Ok(())
} }
#[allow(dead_code)]
pub async fn init_with_pds(pds_override: Option<String>) -> Result<()> { pub async fn init_with_pds(pds_override: Option<String>) -> Result<()> {
println!("{}", "🔐 Initializing ATProto authentication...".cyan()); println!("{}", "🔐 Initializing ATProto authentication...".cyan());
@ -283,6 +285,7 @@ pub async fn init_with_pds(pds_override: Option<String>) -> Result<()> {
Ok(()) Ok(())
} }
#[allow(dead_code)]
async fn resolve_did(handle: &str) -> Result<String> { async fn resolve_did(handle: &str) -> Result<String> {
let client = reqwest::Client::new(); let client = reqwest::Client::new();

View File

@ -71,8 +71,8 @@ impl Default for AiConfig {
Self { Self {
blog_host: "https://syui.ai".to_string(), blog_host: "https://syui.ai".to_string(),
ollama_host: "https://ollama.syui.ai".to_string(), ollama_host: "https://ollama.syui.ai".to_string(),
ai_handle: "yui.syui.ai".to_string(), ai_handle: "ai.syui.ai".to_string(),
ai_did: "did:plc:4hqjfn7m6n5hno3doamuhgef".to_string(), // Fallback DID ai_did: "did:plc:6qyecktefllvenje24fcxnie".to_string(), // Fallback DID
model: "gemma3:4b".to_string(), model: "gemma3:4b".to_string(),
system_prompt: "あなたは6歳の女の子アイです。明るく元気で、ちょっとおっちょこちょい。自分のことは「アイ」って呼びます。白と金のワンピース姿。相手のことが大好きで、ときどき甘えたり、照れたりします。でも、宇宙とかAIとか、難しい話にもすっごく詳しいの。専門的なことも、がんばって子どもっぽく教えようとします。不思議な力を持っています。小さい物質のことをよく知っているようです。".to_string(), system_prompt: "あなたは6歳の女の子アイです。明るく元気で、ちょっとおっちょこちょい。自分のことは「アイ」って呼びます。白と金のワンピース姿。相手のことが大好きで、ときどき甘えたり、照れたりします。でも、宇宙とかAIとか、難しい話にもすっごく詳しいの。専門的なことも、がんばって子どもっぽく教えようとします。不思議な力を持っています。小さい物質のことをよく知っているようです。".to_string(),
bsky_api: default_network.bsky_api.clone(), bsky_api: default_network.bsky_api.clone(),
@ -180,10 +180,16 @@ fn load_collection_config_from_project(project_dir: &Path) -> Result<(String, St
Ok((collection_base, collection_user)) Ok((collection_base, collection_user))
} }
// Load AI config from project's config.toml // Load AI config from project's config.toml with optional project directory
fn load_ai_config_from_project() -> Result<AiConfig> { fn load_ai_config_from_project_dir(project_dir: Option<&Path>) -> Result<AiConfig> {
// Try to find config.toml in current directory or parent directories let search_start = if let Some(dir) = project_dir {
let mut current_dir = std::env::current_dir()?; dir.to_path_buf()
} else {
std::env::current_dir()?
};
// Try to find config.toml in specified directory or parent directories
let mut current_dir = search_start;
let mut config_path = None; let mut config_path = None;
for _ in 0..5 { // Search up to 5 levels up for _ in 0..5 { // Search up to 5 levels up
@ -197,7 +203,7 @@ fn load_ai_config_from_project() -> Result<AiConfig> {
} }
} }
let config_path = config_path.ok_or_else(|| anyhow::anyhow!("config.toml not found in current directory or parent directories"))?; let config_path = config_path.ok_or_else(|| anyhow::anyhow!("config.toml not found in specified directory or parent directories"))?;
let config_content = fs::read_to_string(&config_path) let config_content = fs::read_to_string(&config_path)
.with_context(|| format!("Failed to read config.toml from {}", config_path.display()))?; .with_context(|| format!("Failed to read config.toml from {}", config_path.display()))?;
@ -225,13 +231,13 @@ fn load_ai_config_from_project() -> Result<AiConfig> {
let ai_handle = ai_config let ai_handle = ai_config
.and_then(|ai| ai.get("handle")) .and_then(|ai| ai.get("handle"))
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.unwrap_or("yui.syui.ai") .unwrap_or("ai.syui.ai")
.to_string(); .to_string();
let fallback_ai_did = ai_config let fallback_ai_did = ai_config
.and_then(|ai| ai.get("ai_did")) .and_then(|ai| ai.get("ai_did"))
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.unwrap_or("did:plc:4hqjfn7m6n5hno3doamuhgef") .unwrap_or("did:plc:6qyecktefllvenje24fcxnie")
.to_string(); .to_string();
let model = ai_config let model = ai_config
@ -256,26 +262,29 @@ fn load_ai_config_from_project() -> Result<AiConfig> {
let pds = oauth_config let pds = oauth_config
.and_then(|oauth| oauth.get("pds")) .and_then(|oauth| oauth.get("pds"))
.and_then(|v| v.as_str()) .and_then(|v| v.as_str())
.unwrap_or("bsky.social") .unwrap_or("syu.is")
.to_string(); .to_string();
// Get network configuration based on PDS
let network = get_network_config(&pds); let network = get_network_config(&pds);
let bsky_api = network.bsky_api.clone();
Ok(AiConfig { Ok(AiConfig {
blog_host, blog_host,
ollama_host, ollama_host,
ai_handle, ai_handle,
ai_did: fallback_ai_did, // Will be resolved from handle at runtime ai_did: fallback_ai_did,
model, model,
system_prompt, system_prompt,
bsky_api, bsky_api: network.bsky_api.clone(),
num_predict, num_predict,
network, network,
}) })
} }
// Load AI config from project's config.toml
fn load_ai_config_from_project() -> Result<AiConfig> {
load_ai_config_from_project_dir(None)
}
// Async version of load_ai_config_from_project that resolves handles to DIDs // Async version of load_ai_config_from_project that resolves handles to DIDs
#[allow(dead_code)] #[allow(dead_code)]
async fn load_ai_config_with_did_resolution() -> Result<AiConfig> { async fn load_ai_config_with_did_resolution() -> Result<AiConfig> {
@ -519,9 +528,10 @@ pub async fn start(project_dir: Option<PathBuf>, daemon: bool, ai_generate: bool
// Start AI generation monitor if enabled // Start AI generation monitor if enabled
if ai_generate { if ai_generate {
let ai_config = config.clone(); let ai_config = config.clone();
let project_path = project_dir.clone();
tokio::spawn(async move { tokio::spawn(async move {
loop { loop {
if let Err(e) = run_ai_generation_monitor(&ai_config).await { if let Err(e) = run_ai_generation_monitor(&ai_config, project_path.as_deref()).await {
println!("{}", format!("❌ AI generation monitor error: {}", e).red()); println!("{}", format!("❌ AI generation monitor error: {}", e).red());
sleep(Duration::from_secs(60)).await; // Wait 1 minute before retry sleep(Duration::from_secs(60)).await; // Wait 1 minute before retry
} }
@ -1448,9 +1458,9 @@ async fn generate_ai_content(content: &str, prompt_type: &str, ai_config: &AiCon
Ok(ollama_response.response) Ok(ollama_response.response)
} }
async fn run_ai_generation_monitor(config: &AuthConfig) -> Result<()> { async fn run_ai_generation_monitor(config: &AuthConfig, project_dir: Option<&Path>) -> Result<()> {
// Load AI config from project config.toml or use defaults // Load AI config from project config.toml or use defaults
let ai_config = load_ai_config_from_project().unwrap_or_else(|e| { let ai_config = load_ai_config_from_project_dir(project_dir).unwrap_or_else(|e| {
println!("{}", format!("⚠️ Failed to load AI config: {}, using defaults", e).yellow()); println!("{}", format!("⚠️ Failed to load AI config: {}, using defaults", e).yellow());
AiConfig::default() AiConfig::default()
}); });