Skip to content
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
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -199,3 +199,4 @@ static/uploads/

# custom
AGENTS.md
tmp/*
47 changes: 47 additions & 0 deletions apps/web/src/app/ai-planning/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,53 @@ export default function AIPlanningPage() {
const [weeklyTaskDialogOpen, setWeeklyTaskDialogOpen] = useState(false);
const [editingWeeklyTask, setEditingWeeklyTask] = useState<WeeklyRecurringTask | null>(null);

const preloadAiPlanningData = useCallback(async () => {
if (hasApiKey !== true) return;

setLoadingSchedules(true);
setLoadingWeeklyTasks(true);

try {
const [schedulesResult, weeklyTasksResult] = await Promise.allSettled([
weeklyScheduleApi.getAll(),
weeklyRecurringTasksApi.getAll(),
]);

if (schedulesResult.status === 'fulfilled') {
setSavedSchedules(schedulesResult.value);
} else {
toast({
title: '保存済み週間スケジュールの取得に失敗しました',
description: schedulesResult.reason instanceof Error
? schedulesResult.reason.message
: '不明なエラーが発生しました',
variant: 'destructive',
});
}

if (weeklyTasksResult.status === 'fulfilled') {
setWeeklyTasks(weeklyTasksResult.value);
} else {
toast({
title: 'エラー',
description: weeklyTasksResult.reason instanceof Error
? weeklyTasksResult.reason.message
: '週課の取得に失敗しました',
variant: 'destructive',
});
}
} finally {
setLoadingSchedules(false);
setLoadingWeeklyTasks(false);
}
}, [hasApiKey]);

useEffect(() => {
if (!checkingApiKey && hasApiKey === true) {
void preloadAiPlanningData();
}
}, [checkingApiKey, hasApiKey, preloadAiPlanningData]);

if (authLoading || !user) {
return (
<div className="flex items-center justify-center min-h-screen">
Expand Down
70 changes: 45 additions & 25 deletions apps/web/src/app/scheduling/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -194,12 +194,11 @@ export default function SchedulingPage() {
} else if (taskSource.type === 'all_tasks') {
// Load tasks from all projects
const allTasks: TaskInfo[] = [];
for (const project of projects) {
try {
const projectTasks = await tasksApi.getByProject(project.id);
const filtered = projectTasks
.filter(t => t.status !== 'completed' && t.status !== 'cancelled')
.map(t => ({
const taskFetches = projects.map((project) =>
tasksApi.getByProject(project.id).then((projectTasks) =>
projectTasks
.filter((t) => t.status !== 'completed' && t.status !== 'cancelled')
.map((t) => ({
id: t.id,
title: t.title,
estimate_hours: Number(t.estimate_hours) || 1,
Expand All @@ -208,31 +207,52 @@ export default function SchedulingPage() {
due_date: t.due_date ?? undefined,
goal_id: t.goal_id,
project_id: project.id,
}));
allTasks.push(...(filtered as TaskInfo[]));
} catch (err) {
logger.error(`Failed to load tasks for project ${project.id}`, err instanceof Error ? err : new Error(String(err)));
}
}

// Also load quick tasks (unclassified tasks)
try {
const quickTasks = await quickTasksApi.getAll();
const filteredQuickTasks = quickTasks
.filter(qt => qt.status !== 'completed' && qt.status !== 'cancelled')
.map(qt => ({
id: `quick_${qt.id}`, // Prefix to match backend convention
title: `📥 ${qt.title}`, // Mark as quick task
}))
)
);

const quickTasksPromise = quickTasksApi.getAll().then((quickTasks) =>
quickTasks
.filter((qt) => qt.status !== 'completed' && qt.status !== 'cancelled')
.map((qt) => ({
id: `quick_${qt.id}`, // Prefix to match backend convention
title: `📥 ${qt.title}`, // Mark as quick task
estimate_hours: Number(qt.estimate_hours) || 0.5,
priority: qt.priority || 3,
kind: qt.work_type || 'light_work',
due_date: qt.due_date ?? undefined,
goal_id: undefined,
project_id: undefined,
}));
allTasks.push(...(filteredQuickTasks as TaskInfo[]));
} catch (err) {
logger.error('Failed to load quick tasks', err instanceof Error ? err : new Error(String(err)));
}))
);

const [projectTaskResults, quickTasksResult] = await Promise.all([
Promise.allSettled(taskFetches),
quickTasksPromise
.then<PromiseSettledResult<TaskInfo[]>>((value) => ({ status: 'fulfilled', value }))
.catch<PromiseSettledResult<TaskInfo[]>>((reason) => ({ status: 'rejected', reason })),
]);

projectTaskResults.forEach((result, index) => {
if (result.status === 'fulfilled') {
allTasks.push(...(result.value as TaskInfo[]));
} else {
logger.error(
`Failed to load tasks for project ${projects[index]?.id}`,
result.reason instanceof Error ? result.reason : new Error(String(result.reason))
);
Comment on lines +236 to +243
Copy link

Copilot AI Feb 15, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The per-project failure log uses projects[index]?.id, which can become inaccurate if the projects state changes between starting the requests and handling the settled results. Capture the project id alongside each promise (or close over project.id) and use that captured id for error logs to ensure correct attribution.

Copilot uses AI. Check for mistakes.
}
});

if (quickTasksResult.status === 'fulfilled') {
allTasks.push(...(quickTasksResult.value as TaskInfo[]));
} else {
logger.error(
'Failed to load quick tasks',
quickTasksResult.reason instanceof Error
? quickTasksResult.reason
: new Error(String(quickTasksResult.reason))
);
}

tasks = allTasks;
Expand Down
31 changes: 15 additions & 16 deletions apps/web/src/app/settings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,13 @@ export default function SettingsPage() {
}
} | null>(null)

const getAuthContext = async () => {
const { data: { user } } = await supabase.auth.getUser()
const { data: { session } } = await supabase.auth.getSession()

return { user, session }
}

useEffect(() => {
// Create AbortController for cleanup
abortControllerRef.current = new AbortController()
Expand Down Expand Up @@ -134,8 +141,7 @@ export default function SettingsPage() {

const fetchUserSettings = async () => {
try {
const { data: { user } } = await supabase.auth.getUser()
const { data: { session } } = await supabase.auth.getSession()
const { user, session } = await getAuthContext()

if (!user || !session?.access_token) {
router.push("/login")
Expand Down Expand Up @@ -187,8 +193,7 @@ export default function SettingsPage() {
setSuccess("")

try {
const { data: { user } } = await supabase.auth.getUser()
const { data: { session } } = await supabase.auth.getSession()
const { user, session } = await getAuthContext()

if (!user || !session?.access_token) {
router.push("/login")
Expand Down Expand Up @@ -233,8 +238,7 @@ export default function SettingsPage() {
setSuccess("")

try {
const { data: { user } } = await supabase.auth.getUser()
const { data: { session } } = await supabase.auth.getSession()
const { user, session } = await getAuthContext()

if (!user || !session?.access_token) {
router.push("/login")
Expand Down Expand Up @@ -278,8 +282,7 @@ export default function SettingsPage() {
setSuccess("")

try {
const { data: { user } } = await supabase.auth.getUser()
const { data: { session } } = await supabase.auth.getSession()
const { user, session } = await getAuthContext()

if (!user || !session?.access_token) {
router.push("/login")
Expand Down Expand Up @@ -314,8 +317,7 @@ export default function SettingsPage() {
setSuccess("")

try {
const { data: { user } } = await supabase.auth.getUser()
const { data: { session } } = await supabase.auth.getSession()
const { user, session } = await getAuthContext()

if (!user || !session?.access_token) {
router.push("/login")
Expand Down Expand Up @@ -352,8 +354,7 @@ export default function SettingsPage() {

const fetchExportInfo = async () => {
try {
const { data: { user } } = await supabase.auth.getUser()
const { data: { session } } = await supabase.auth.getSession()
const { user, session } = await getAuthContext()

if (!user || !session?.access_token) {
return
Expand Down Expand Up @@ -384,8 +385,7 @@ export default function SettingsPage() {
setSuccess("")

try {
const { data: { user } } = await supabase.auth.getUser()
const { data: { session } } = await supabase.auth.getSession()
const { user, session } = await getAuthContext()

if (!user || !session?.access_token) {
router.push("/login")
Expand Down Expand Up @@ -431,8 +431,7 @@ export default function SettingsPage() {
setSuccess("")

try {
const { data: { user } } = await supabase.auth.getUser()
const { data: { session } } = await supabase.auth.getSession()
const { user, session } = await getAuthContext()

if (!user || !session?.access_token) {
router.push("/login")
Expand Down
20 changes: 17 additions & 3 deletions apps/web/src/components/runner/manual-task-select-dialog.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import {
} from '@/components/ui/select';
import { Clock, Search, FolderOpen, AlertCircle } from 'lucide-react';
import { projectsApi, tasksApi } from '@/lib/api';
import { log } from '@/lib/logger';
import type { Project } from '@/types/project';

interface ManualTaskSelectDialogProps {
Expand Down Expand Up @@ -63,12 +64,25 @@ export function ManualTaskSelectDialog({
queryKey: ['tasks', 'manual-select', selectedProjectId, projects.map(p => p.id).join(',')],
queryFn: async () => {
if (selectedProjectId === 'all') {
// Fetch tasks from all projects in parallel using Promise.all
// Fetch tasks from all projects in parallel.
// Ignore failures for individual projects and return other projects' tasks.
const taskPromises = projects.map((project) =>
tasksApi.getByProject(project.id, 0, 100)
);
const taskResults = await Promise.all(taskPromises);
return taskResults.flat();
const taskResults = await Promise.allSettled(taskPromises);
return taskResults.flatMap((result, index) => {
if (result.status === 'fulfilled') {
return result.value;
}

log.error(
`Failed to load tasks for project ${projects[index]?.id}`,
result.reason instanceof Error ? result.reason : new Error(String(result.reason)),
{ component: 'ManualTaskSelectDialog' }
);
Comment on lines 69 to +82
Copy link

Copilot AI Feb 15, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In the all projects fetch, the error log uses projects[index]?.id. If the projects list changes while the query is in-flight, this can log the wrong project id. Consider capturing { projectId, promise } (or closing over project.id) so the log always references the project tied to that request.

Copilot uses AI. Check for mistakes.

return [];
});
} else {
return tasksApi.getByProject(selectedProjectId, 0, 100);
}
Expand Down
2 changes: 1 addition & 1 deletion apps/web/src/hooks/use-project-page-state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ export function useProjectPageState(projectId: string): ProjectPageState {
const { data: projectProgress } = useQuery({
queryKey: ['progress', 'project', projectId],
queryFn: () => progressApi.getProject(projectId),
enabled: !!project,
enabled: !!projectId,
})

const isInitializing = authLoading || !user
Expand Down
33 changes: 25 additions & 8 deletions apps/web/src/hooks/use-runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ import { useCountdown } from './use-countdown';
import { useNotifications } from './use-notifications';
import { schedulingApi, tasksApi, goalsApi, projectsApi, workSessionsApi } from '@/lib/api';
import { queryKeys } from '@/lib/query-keys';
import type { Goal } from '@/types/goal';
import type { Project } from '@/types/project';
import type { SessionDecision } from '@/types/work-session';
import type { RescheduleSuggestion } from '@/types/reschedule';
import type {
Expand Down Expand Up @@ -87,17 +89,32 @@ export function useRunner(): UseRunnerReturn {

try {
const task = await tasksApi.getById(session.task_id);
let goal = null;
let project = null;
let goal: Goal | null = null;
let project: Project | null = null;

if (task.goal_id) {
try {
goal = await goalsApi.getById(task.goal_id);
if (goal?.project_id) {
project = await projectsApi.getById(goal.project_id);
const cachedGoal = queryClient.getQueryData<Goal>(queryKeys.goals.detail(task.goal_id));
if (cachedGoal) {
goal = cachedGoal;
} else {
try {
goal = await goalsApi.getById(task.goal_id);
} catch {
// Goal not found, continue without goal/project
}
}

if (goal?.project_id) {
const cachedProject = queryClient.getQueryData<Project>(queryKeys.projects.detail(goal.project_id));
if (cachedProject) {
project = cachedProject;
} else {
try {
project = await projectsApi.getById(goal.project_id);
} catch {
// Project not found, continue without project
}
}
} catch {
// Goal or project not found, continue without
}
}

Expand Down