first version of proper braindump composer
This commit is contained in:
+52
-3
@@ -1,18 +1,67 @@
|
||||
import './styles/app.scss';
|
||||
import './styles/brain-dump.scss';
|
||||
import htmx from 'htmx.org';
|
||||
|
||||
window.htmx = htmx;
|
||||
|
||||
document.body.addEventListener('htmx:beforeRequest', function () {
|
||||
document.getElementById('request-failed').hidden = true;
|
||||
const error = document.getElementById('request-failed');
|
||||
if (error) error.hidden = true;
|
||||
});
|
||||
|
||||
document.body.addEventListener('htmx:responseError', function () {
|
||||
document.getElementById('request-failed').hidden = false;
|
||||
const error = document.getElementById('request-failed');
|
||||
if (error) error.hidden = false;
|
||||
});
|
||||
|
||||
document.body.addEventListener('htmx:sendError', function () {
|
||||
document.getElementById('request-failed').hidden = false;
|
||||
const error = document.getElementById('request-failed');
|
||||
if (error) error.hidden = false;
|
||||
});
|
||||
|
||||
function activateComposerTab(tab) {
|
||||
const composer = tab.closest('.task-composer');
|
||||
if (!composer) return;
|
||||
|
||||
composer.querySelectorAll('[role="tab"]').forEach((candidate) => {
|
||||
const selected = candidate === tab;
|
||||
candidate.setAttribute('aria-selected', String(selected));
|
||||
candidate.tabIndex = selected ? 0 : -1;
|
||||
const panel = document.getElementById(candidate.getAttribute('aria-controls'));
|
||||
if (panel) panel.hidden = !selected;
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener('click', (event) => {
|
||||
const tab = event.target.closest('.task-composer [role="tab"]');
|
||||
if (tab) activateComposerTab(tab);
|
||||
|
||||
const closeButton = event.target.closest('[data-close-brain-dump-dialog]');
|
||||
if (closeButton) closeButton.closest('dialog')?.close();
|
||||
});
|
||||
|
||||
document.addEventListener('keydown', (event) => {
|
||||
const tab = event.target.closest?.('.task-composer [role="tab"]');
|
||||
if (!tab || !['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
|
||||
|
||||
const tabs = [...tab.closest('[role="tablist"]').querySelectorAll('[role="tab"]')];
|
||||
const currentIndex = tabs.indexOf(tab);
|
||||
const nextIndex = event.key === 'Home' ? 0
|
||||
: event.key === 'End' ? tabs.length - 1
|
||||
: (currentIndex + (event.key === 'ArrowRight' ? 1 : -1) + tabs.length) % tabs.length;
|
||||
event.preventDefault();
|
||||
tabs[nextIndex].focus();
|
||||
activateComposerTab(tabs[nextIndex]);
|
||||
});
|
||||
|
||||
document.body.addEventListener('htmx:afterSwap', (event) => {
|
||||
const dialog = event.detail.target?.querySelector('.brain-dump-proposal-dialog');
|
||||
if (!dialog) return;
|
||||
|
||||
dialog.addEventListener('close', () => dialog.remove(), {once: true});
|
||||
if (typeof dialog.showModal === 'function' && !dialog.open) dialog.showModal();
|
||||
});
|
||||
|
||||
document.addEventListener('click', (event) => {
|
||||
const button = event.target.closest('[data-weather-location]');
|
||||
if (!button) return;
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
.task-composer__tabs {
|
||||
display: flex;
|
||||
gap: .5rem;
|
||||
padding: 0 25px 1rem;
|
||||
border-bottom: 1px solid #d9e6eb;
|
||||
|
||||
[role='tab'] {
|
||||
background: #eef8fb;
|
||||
border: 1px solid #b9d8e4;
|
||||
color: #075d7f;
|
||||
padding: .55rem .8rem;
|
||||
}
|
||||
|
||||
[role='tab'][aria-selected='true'] {
|
||||
background: #087aa9;
|
||||
border-color: #087aa9;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
[role='tab']:focus-visible {
|
||||
outline: 3px solid #f2ad00;
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
#manual-task-panel,
|
||||
#brain-dump-panel {
|
||||
padding: 25px;
|
||||
}
|
||||
|
||||
.brain-dump-feedback {
|
||||
margin-top: 1rem;
|
||||
}
|
||||
|
||||
.brain-dump-feedback--error {
|
||||
color: #8b1a1a;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.brain-dump-proposal-dialog {
|
||||
width: min(720px, calc(100vw - 2rem));
|
||||
max-height: min(80vh, 760px);
|
||||
}
|
||||
|
||||
.brain-dump-proposal-dialog__content {
|
||||
display: grid;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.brain-dump-proposal-list {
|
||||
display: grid;
|
||||
gap: .75rem;
|
||||
padding: 0;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
.brain-dump-proposal-list > li {
|
||||
padding: 1rem;
|
||||
border: 1px solid #d9e6eb;
|
||||
border-radius: .5rem;
|
||||
}
|
||||
|
||||
.brain-dump-proposal-list h3,
|
||||
.brain-dump-proposal-list h4,
|
||||
.brain-dump-proposal-list p {
|
||||
margin: 0 0 .4rem;
|
||||
}
|
||||
|
||||
.brain-dump-proposal-list__meta,
|
||||
.brain-dump-proposal-list li li span {
|
||||
color: #4f7280;
|
||||
font-size: .9rem;
|
||||
}
|
||||
|
||||
.brain-dump-proposal-list ul {
|
||||
display: grid;
|
||||
gap: .45rem;
|
||||
margin: .5rem 0 0;
|
||||
}
|
||||
|
||||
.brain-dump-proposal-list li li {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.brain-dump-proposal-dialog__actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: .75rem;
|
||||
margin: 0;
|
||||
}
|
||||
@@ -2,159 +2,152 @@
|
||||
|
||||
namespace App\Controller;
|
||||
|
||||
use App\Entity\Settings;
|
||||
use App\Entity\User;
|
||||
use App\Service\BrainDumpProposalService;
|
||||
use App\Service\TaskProposalPersistenceService;
|
||||
use App\Service\TaskRecommendationService;
|
||||
use App\Service\TaskSchedulingService;
|
||||
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\HttpFoundation\Request;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
use Symfony\Component\Routing\Attribute\Route;
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
|
||||
final class BraindumpController extends AbstractController
|
||||
{
|
||||
#[Route('/braindump', name: 'app_braindump')]
|
||||
#[Route('/braindump', name: 'app_braindump', methods: ['GET'])]
|
||||
public function index(): Response
|
||||
{
|
||||
return $this->render('braindump/index.html.twig');
|
||||
}
|
||||
|
||||
/** Retained as a development view; the reviewed workflow lives on the task page. */
|
||||
#[Route('/braindump/dump', name: 'app_braindump_dump', methods: ['POST'])]
|
||||
public function dump(
|
||||
Request $request,
|
||||
HttpClientInterface $client
|
||||
): Response {
|
||||
// Give Ollama enough time to process a larger brain dump.
|
||||
set_time_limit(120);
|
||||
|
||||
// Check the CSRF token.
|
||||
if (
|
||||
!$this->isCsrfTokenValid(
|
||||
'braindump_dump',
|
||||
$request->getPayload()->getString('_token')
|
||||
)
|
||||
) {
|
||||
public function dump(Request $request, BrainDumpProposalService $proposals): Response
|
||||
{
|
||||
if (!$this->isCsrfTokenValid('braindump_dump', $request->getPayload()->getString('_token'))) {
|
||||
throw $this->createAccessDeniedException('Invalid CSRF token.');
|
||||
}
|
||||
|
||||
// Get the user's brain dump.
|
||||
$brainDump = $request->getPayload()->getString('brain_dump');
|
||||
// dd('THIS IS THE NEW CONTROLLER', $brainDump);
|
||||
// Tell Ollama exactly what structure we want back.
|
||||
$schema = [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'tasks' => [
|
||||
'type' => 'array',
|
||||
'items' => [
|
||||
'type' => 'object',
|
||||
'properties' => [
|
||||
'title' => [
|
||||
'type' => 'string',
|
||||
],
|
||||
'description' => [
|
||||
'type' => 'string',
|
||||
],
|
||||
'estimatedDurationMinutes' => [
|
||||
'type' => 'integer',
|
||||
],
|
||||
'priority' => [
|
||||
'type' => 'string',
|
||||
'enum' => [
|
||||
'Low',
|
||||
'Medium',
|
||||
'High',
|
||||
],
|
||||
],
|
||||
'category' => [
|
||||
'type' => 'string',
|
||||
],
|
||||
'isRecurring' => [
|
||||
'type' => 'boolean',
|
||||
],
|
||||
],
|
||||
'required' => [
|
||||
'title',
|
||||
'description',
|
||||
'estimatedDurationMinutes',
|
||||
'priority',
|
||||
'category',
|
||||
'isRecurring',
|
||||
],
|
||||
],
|
||||
],
|
||||
],
|
||||
'required' => [
|
||||
'tasks',
|
||||
],
|
||||
];
|
||||
|
||||
// Ask Ollama to turn the brain dump into concrete tasks.
|
||||
$response = $client->request(
|
||||
'POST',
|
||||
'http://192.168.1.238:11434/api/generate',
|
||||
[
|
||||
'timeout' => 120,
|
||||
'max_duration' => 120,
|
||||
|
||||
'json' => [
|
||||
'model' => 'qwen3:4b',
|
||||
'think' => false,
|
||||
'prompt' => <<<PROMPT
|
||||
You are a task extraction assistant.
|
||||
|
||||
Turn the user's brain dump into a list of concrete, actionable tasks.
|
||||
|
||||
Rules:
|
||||
- Break large tasks into sensible individual tasks.
|
||||
- Keep task titles concise.
|
||||
- Write a short description where useful.
|
||||
- Estimate realistic durations in minutes.
|
||||
- Use Low, Medium, or High priority.
|
||||
- Use a short, sensible category.
|
||||
- Only mark a task as recurring if the user explicitly indicates that it should recur.
|
||||
- Do not invent tasks that are not reasonably implied by the brain dump.
|
||||
- Return only the requested JSON structure.
|
||||
|
||||
User's brain dump:
|
||||
|
||||
$brainDump
|
||||
PROMPT,
|
||||
|
||||
// Structured output using the JSON schema above.
|
||||
'format' => $schema,
|
||||
|
||||
// We want one complete response rather than a stream.
|
||||
'stream' => false,
|
||||
|
||||
// More deterministic output is useful for structured data.
|
||||
'options' => [
|
||||
'temperature' => 0,
|
||||
],
|
||||
],
|
||||
]
|
||||
);
|
||||
|
||||
$data = $response->toArray();
|
||||
// dd($data);
|
||||
// dd($data['response']);
|
||||
file_put_contents(
|
||||
'/tmp/ollama-response.txt',
|
||||
$data['response'] ?? 'NO RESPONSE'
|
||||
);
|
||||
|
||||
//$json = $data['response'] ?? '{"tasks":[]}';
|
||||
$json = $data['response'] ?? '{"tasks":[]}';
|
||||
$tasks = json_decode($json, true);
|
||||
|
||||
if (json_last_error() !== JSON_ERROR_NONE) {
|
||||
throw new \RuntimeException(
|
||||
'Invalid JSON returned by Ollama: '
|
||||
. json_last_error_msg()
|
||||
. "\n\nRaw response:\n"
|
||||
. $json
|
||||
);
|
||||
try {
|
||||
$tasks = $proposals->generate($request->getPayload()->getString('brain_dump'));
|
||||
} catch (\Throwable $exception) {
|
||||
return $this->render('braindump/_task_result.html.twig', ['tasks' => [], 'error' => $this->friendlyError($exception)]);
|
||||
}
|
||||
// Give the tasks to our HTMX partial.
|
||||
return $this->render('braindump/_task_result.html.twig', [
|
||||
'tasks' => $tasks['tasks'] ?? [],
|
||||
|
||||
return $this->render('braindump/_task_result.html.twig', ['tasks' => $tasks]);
|
||||
}
|
||||
|
||||
#[Route('/task/brain-dump/generate', name: 'app_task_braindump_generate', methods: ['POST'])]
|
||||
public function generate(Request $request, BrainDumpProposalService $proposals): Response
|
||||
{
|
||||
if (!$this->isCsrfTokenValid('task_braindump_generate', $request->getPayload()->getString('_token'))) {
|
||||
throw $this->createAccessDeniedException('Invalid CSRF token.');
|
||||
}
|
||||
|
||||
set_time_limit(120);
|
||||
|
||||
try {
|
||||
$tasks = $proposals->generate($request->getPayload()->getString('brain_dump'));
|
||||
} catch (\Throwable $exception) {
|
||||
return $this->renderGenerationError($this->friendlyError($exception));
|
||||
}
|
||||
|
||||
$date = $this->selectedDate($request);
|
||||
$proposalId = bin2hex(random_bytes(16));
|
||||
$request->getSession()->set('brain_dump_proposal', [
|
||||
'id' => $proposalId,
|
||||
'tasks' => $tasks,
|
||||
'scheduled_for' => $date->format('Y-m-d'),
|
||||
]);
|
||||
|
||||
return $this->render('task/_brain_dump_proposal.html.twig', [
|
||||
'tasks' => $tasks,
|
||||
'proposal_id' => $proposalId,
|
||||
'selected_date' => $date,
|
||||
]);
|
||||
}
|
||||
|
||||
#[Route('/task/brain-dump/confirm', name: 'app_task_braindump_confirm', methods: ['POST'])]
|
||||
public function confirm(
|
||||
Request $request,
|
||||
BrainDumpProposalService $proposals,
|
||||
TaskProposalPersistenceService $taskCreator,
|
||||
TaskSchedulingService $taskSchedulingService,
|
||||
TaskRecommendationService $taskRecommendationService,
|
||||
): Response {
|
||||
if (!$this->isCsrfTokenValid('task_braindump_confirm', $request->getPayload()->getString('_token'))) {
|
||||
throw $this->createAccessDeniedException('Invalid CSRF token.');
|
||||
}
|
||||
|
||||
$stored = $request->getSession()->get('brain_dump_proposal');
|
||||
$proposalId = $request->getPayload()->getString('proposal_id');
|
||||
if (!is_array($stored) || !isset($stored['id']) || !is_string($stored['id']) || !hash_equals($stored['id'], $proposalId)) {
|
||||
return $this->renderGenerationError('This proposal has expired. Generate a new one before adding tasks.');
|
||||
}
|
||||
|
||||
$date = isset($stored['scheduled_for']) && is_string($stored['scheduled_for'])
|
||||
? \DateTimeImmutable::createFromFormat('!Y-m-d', $stored['scheduled_for'])
|
||||
: false;
|
||||
if (!$date instanceof \DateTimeImmutable) {
|
||||
$request->getSession()->remove('brain_dump_proposal');
|
||||
|
||||
return $this->renderGenerationError('This proposal has expired. Generate a new one before adding tasks.');
|
||||
}
|
||||
|
||||
try {
|
||||
// Revalidate the server-side session proposal before it is written.
|
||||
$tasks = $proposals->normalise(['tasks' => $stored['tasks'] ?? null]);
|
||||
$taskCreator->createFromProposal($tasks, $date);
|
||||
} catch (\Throwable $exception) {
|
||||
return $this->render('task/_brain_dump_proposal.html.twig', [
|
||||
'tasks' => is_array($stored['tasks'] ?? null) ? $stored['tasks'] : [],
|
||||
'proposal_id' => $stored['id'],
|
||||
'selected_date' => $date,
|
||||
'error' => $this->friendlyError($exception),
|
||||
]);
|
||||
}
|
||||
|
||||
$request->getSession()->remove('brain_dump_proposal');
|
||||
$batteryLevel = $taskRecommendationService->normaliseBatteryLevel($request->getSession()->get('social_battery', 3));
|
||||
$taskGroups = $taskSchedulingService->taskGroupsForDate($batteryLevel, $date, $this->currentSettings());
|
||||
|
||||
return $this->render('task/_brain_dump_confirmation_response.html.twig', [
|
||||
'tasks' => $taskGroups['tasks'],
|
||||
'subtasks_by_parent' => $taskGroups['subtasks_by_parent'],
|
||||
'selected_date' => $date,
|
||||
]);
|
||||
}
|
||||
|
||||
private function renderGenerationError(string $message): Response
|
||||
{
|
||||
$response = $this->render('task/_brain_dump_error.html.twig', ['message' => $message]);
|
||||
$response->headers->set('HX-Retarget', '#brain-dump-feedback');
|
||||
|
||||
return $response;
|
||||
}
|
||||
|
||||
private function selectedDate(Request $request): \DateTimeImmutable
|
||||
{
|
||||
$date = $request->getPayload()->getString('date');
|
||||
if ('' !== $date && false !== ($selectedDate = \DateTimeImmutable::createFromFormat('!Y-m-d', $date))) {
|
||||
return $selectedDate;
|
||||
}
|
||||
|
||||
return new \DateTimeImmutable('today');
|
||||
}
|
||||
|
||||
private function currentSettings(): ?Settings
|
||||
{
|
||||
$user = $this->getUser();
|
||||
|
||||
return $user instanceof User ? $user->getSettings() : null;
|
||||
}
|
||||
|
||||
private function friendlyError(\Throwable $exception): string
|
||||
{
|
||||
return $exception instanceof \InvalidArgumentException
|
||||
? $exception->getMessage()
|
||||
: 'The task generator could not complete that request. Please try again shortly.';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use Symfony\Contracts\HttpClient\HttpClientInterface;
|
||||
|
||||
/** Turns free-form text into a validated, non-persistent task proposal. */
|
||||
final class BrainDumpProposalService
|
||||
{
|
||||
private const OLLAMA_URL = 'http://192.168.1.238:11434/api/generate';
|
||||
|
||||
/** @var list<string> */
|
||||
private const PRIORITIES = ['low', 'medium', 'high'];
|
||||
|
||||
public function __construct(private HttpClientInterface $client)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<array{title: string, description: ?string, estimatedDurationMinutes: int, priority: string, category: ?string, subtasks: list<array{title: string, description: ?string, estimatedDurationMinutes: int, priority: string, category: ?string}>}>
|
||||
*/
|
||||
public function generate(string $brainDump): array
|
||||
{
|
||||
$brainDump = trim($brainDump);
|
||||
if ('' === $brainDump) {
|
||||
throw new \InvalidArgumentException('Please enter a brain dump before generating tasks.');
|
||||
}
|
||||
|
||||
if (mb_strlen($brainDump) > 12000) {
|
||||
throw new \InvalidArgumentException('Please shorten the brain dump to 12,000 characters or fewer.');
|
||||
}
|
||||
|
||||
try {
|
||||
$response = $this->client->request('POST', self::OLLAMA_URL, [
|
||||
'timeout' => 120,
|
||||
'max_duration' => 120,
|
||||
'json' => [
|
||||
'model' => 'qwen3:4b',
|
||||
'think' => false,
|
||||
'prompt' => $this->prompt($brainDump),
|
||||
'format' => $this->schema(),
|
||||
'stream' => false,
|
||||
'options' => ['temperature' => 0],
|
||||
],
|
||||
]);
|
||||
$payload = $response->toArray(false);
|
||||
} catch (\Throwable $exception) {
|
||||
throw new \RuntimeException('The task generator is unavailable right now. Please try again shortly.', 0, $exception);
|
||||
}
|
||||
|
||||
if (!isset($payload['response']) || !is_string($payload['response'])) {
|
||||
throw new \RuntimeException('The task generator returned an incomplete response. Please try again.');
|
||||
}
|
||||
|
||||
try {
|
||||
$proposal = json_decode($payload['response'], true, 512, JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $exception) {
|
||||
throw new \RuntimeException('The task generator returned an unreadable proposal. Please try again.', 0, $exception);
|
||||
}
|
||||
|
||||
return $this->normalise($proposal);
|
||||
}
|
||||
|
||||
/**
|
||||
* Revalidate the session value before persistence. This intentionally accepts no client supplied proposal.
|
||||
*
|
||||
* @return list<array{title: string, description: ?string, estimatedDurationMinutes: int, priority: string, category: ?string, subtasks: list<array{title: string, description: ?string, estimatedDurationMinutes: int, priority: string, category: ?string}>}>
|
||||
*/
|
||||
public function normalise(mixed $proposal): array
|
||||
{
|
||||
if (!is_array($proposal) || !isset($proposal['tasks']) || !is_array($proposal['tasks']) || !array_is_list($proposal['tasks'])) {
|
||||
throw new \InvalidArgumentException('The generated proposal has an invalid task list.');
|
||||
}
|
||||
|
||||
if ([] === $proposal['tasks']) {
|
||||
throw new \InvalidArgumentException('No actionable tasks were found. Try adding a little more detail.');
|
||||
}
|
||||
|
||||
if (count($proposal['tasks']) > 25) {
|
||||
throw new \InvalidArgumentException('The generated proposal contains too many tasks. Please use a smaller brain dump.');
|
||||
}
|
||||
|
||||
$tasks = [];
|
||||
foreach ($proposal['tasks'] as $task) {
|
||||
$tasks[] = $this->normaliseTask($task, true);
|
||||
}
|
||||
|
||||
return $tasks;
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array{title: string, description: ?string, estimatedDurationMinutes: int, priority: string, category: ?string, subtasks?: list<array{title: string, description: ?string, estimatedDurationMinutes: int, priority: string, category: ?string}>}
|
||||
*/
|
||||
private function normaliseTask(mixed $task, bool $allowSubtasks): array
|
||||
{
|
||||
if (!is_array($task)) {
|
||||
throw new \InvalidArgumentException('Every proposed task must be an object.');
|
||||
}
|
||||
|
||||
$title = $this->requiredString($task, 'title', 255);
|
||||
$description = $this->optionalString($task, 'description', 10000);
|
||||
$category = $this->optionalString($task, 'category', 100);
|
||||
|
||||
$duration = $task['estimatedDurationMinutes'] ?? null;
|
||||
if (!is_int($duration) || $duration < 1 || $duration > 1440) {
|
||||
throw new \InvalidArgumentException('Each task needs an estimated duration between 1 and 1,440 minutes.');
|
||||
}
|
||||
|
||||
$priority = $task['priority'] ?? null;
|
||||
if (!is_string($priority) || !in_array(strtolower($priority), self::PRIORITIES, true)) {
|
||||
throw new \InvalidArgumentException('Each task must use low, medium, or high priority.');
|
||||
}
|
||||
|
||||
$normalised = [
|
||||
'title' => $title,
|
||||
'description' => $description,
|
||||
'estimatedDurationMinutes' => $duration,
|
||||
'priority' => strtolower($priority),
|
||||
'category' => $category,
|
||||
];
|
||||
|
||||
if (!$allowSubtasks) {
|
||||
if (array_key_exists('subtasks', $task)) {
|
||||
throw new \InvalidArgumentException('Only one level of subtasks is supported.');
|
||||
}
|
||||
|
||||
return $normalised;
|
||||
}
|
||||
|
||||
$subtasks = $task['subtasks'] ?? [];
|
||||
if (!is_array($subtasks) || !array_is_list($subtasks) || count($subtasks) > 12) {
|
||||
throw new \InvalidArgumentException('Each task can have at most 12 subtasks.');
|
||||
}
|
||||
|
||||
$normalised['subtasks'] = [];
|
||||
foreach ($subtasks as $subtask) {
|
||||
$normalised['subtasks'][] = $this->normaliseTask($subtask, false);
|
||||
}
|
||||
|
||||
return $normalised;
|
||||
}
|
||||
|
||||
/** @param array<mixed> $task */
|
||||
private function requiredString(array $task, string $field, int $maxLength): string
|
||||
{
|
||||
if (!isset($task[$field]) || !is_string($task[$field])) {
|
||||
throw new \InvalidArgumentException(sprintf('Each task needs a %s.', $field));
|
||||
}
|
||||
|
||||
$value = trim($task[$field]);
|
||||
if ('' === $value || mb_strlen($value) > $maxLength) {
|
||||
throw new \InvalidArgumentException(sprintf('Each task needs a %s no longer than %d characters.', $field, $maxLength));
|
||||
}
|
||||
|
||||
return $value;
|
||||
}
|
||||
|
||||
/** @param array<mixed> $task */
|
||||
private function optionalString(array $task, string $field, int $maxLength): ?string
|
||||
{
|
||||
if (!array_key_exists($field, $task) || null === $task[$field]) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!is_string($task[$field])) {
|
||||
throw new \InvalidArgumentException(sprintf('Each task %s must be text.', $field));
|
||||
}
|
||||
|
||||
$value = trim($task[$field]);
|
||||
if (mb_strlen($value) > $maxLength) {
|
||||
throw new \InvalidArgumentException(sprintf('Each task %s is too long.', $field));
|
||||
}
|
||||
|
||||
return '' === $value ? null : $value;
|
||||
}
|
||||
|
||||
/** @return array<string, mixed> */
|
||||
private function schema(): array
|
||||
{
|
||||
$subtask = [
|
||||
'type' => 'object',
|
||||
'properties' => $this->taskProperties(),
|
||||
'required' => ['title', 'description', 'estimatedDurationMinutes', 'priority', 'category'],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
$task = [
|
||||
'type' => 'object',
|
||||
'properties' => $this->taskProperties() + ['subtasks' => ['type' => 'array', 'items' => $subtask, 'maxItems' => 12]],
|
||||
'required' => ['title', 'description', 'estimatedDurationMinutes', 'priority', 'category', 'subtasks'],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
|
||||
return [
|
||||
'type' => 'object',
|
||||
'properties' => ['tasks' => ['type' => 'array', 'items' => $task, 'maxItems' => 25]],
|
||||
'required' => ['tasks'],
|
||||
'additionalProperties' => false,
|
||||
];
|
||||
}
|
||||
|
||||
/** @return array<string, array<string, mixed>> */
|
||||
private function taskProperties(): array
|
||||
{
|
||||
return [
|
||||
'title' => ['type' => 'string'],
|
||||
'description' => ['type' => 'string'],
|
||||
'estimatedDurationMinutes' => ['type' => 'integer', 'minimum' => 1, 'maximum' => 1440],
|
||||
'priority' => ['type' => 'string', 'enum' => self::PRIORITIES],
|
||||
'category' => ['type' => 'string'],
|
||||
];
|
||||
}
|
||||
|
||||
private function prompt(string $brainDump): string
|
||||
{
|
||||
return <<<PROMPT
|
||||
You are a task extraction assistant.
|
||||
|
||||
Turn the user's brain dump into a concise list of concrete, actionable tasks.
|
||||
|
||||
Rules:
|
||||
- Use only details reasonably implied by the brain dump; do not invent unrelated work.
|
||||
- Keep task titles concise and use a short description only when it adds useful context.
|
||||
- Estimate realistic durations in minutes and use exactly one of: low, medium, high.
|
||||
- Use a short sensible category, or an empty string when none fits.
|
||||
- Add subtasks only for a meaningfully large task where they make execution clearer.
|
||||
- Do not split tiny tasks and do not over-decompose work.
|
||||
- At most one subtask level is allowed. Subtasks are independently completable tasks.
|
||||
- Return only the requested JSON structure.
|
||||
|
||||
User's brain dump:
|
||||
|
||||
{$brainDump}
|
||||
PROMPT;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?php
|
||||
|
||||
namespace App\Service;
|
||||
|
||||
use App\Entity\Task;
|
||||
use Doctrine\ORM\EntityManagerInterface;
|
||||
|
||||
/** Creates tasks only after a reviewed proposal has passed server-side validation. */
|
||||
final class TaskProposalPersistenceService
|
||||
{
|
||||
public function __construct(private EntityManagerInterface $entityManager)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* @param list<array{title: string, description: ?string, estimatedDurationMinutes: int, priority: string, category: ?string, subtasks: list<array{title: string, description: ?string, estimatedDurationMinutes: int, priority: string, category: ?string}>}> $proposals
|
||||
*/
|
||||
public function createFromProposal(array $proposals, \DateTimeImmutable $scheduledFor): void
|
||||
{
|
||||
foreach ($proposals as $proposal) {
|
||||
$parent = $this->createTask($proposal, $scheduledFor);
|
||||
$this->entityManager->persist($parent);
|
||||
|
||||
foreach ($proposal['subtasks'] as $subtaskProposal) {
|
||||
$subtask = $this->createTask($subtaskProposal, $scheduledFor);
|
||||
$subtask->setParentTask($parent);
|
||||
$this->entityManager->persist($subtask);
|
||||
}
|
||||
}
|
||||
|
||||
$this->entityManager->flush();
|
||||
}
|
||||
|
||||
/** @param array{title: string, description: ?string, estimatedDurationMinutes: int, priority: string, category: ?string} $proposal */
|
||||
private function createTask(array $proposal, \DateTimeImmutable $scheduledFor): Task
|
||||
{
|
||||
return (new Task())
|
||||
->setTitle($proposal['title'])
|
||||
->setDescription($proposal['description'])
|
||||
->setEstimatedDurationMinutes($proposal['estimatedDurationMinutes'])
|
||||
->setPriority($proposal['priority'])
|
||||
->setCategory($proposal['category'])
|
||||
->setScheduledFor($scheduledFor)
|
||||
->setIsActive(true);
|
||||
}
|
||||
}
|
||||
@@ -1,38 +1,29 @@
|
||||
{% if tasks is empty %}
|
||||
{% if error|default(null) %}
|
||||
<p class="brain-dump-feedback brain-dump-feedback--error" role="alert">{{ error }}</p>
|
||||
{% elseif tasks is empty %}
|
||||
<p>No tasks were suggested.</p>
|
||||
{% else %}
|
||||
<h2>Suggested tasks</h2>
|
||||
<ul class="suggested-tasks">
|
||||
{% for task in tasks %}
|
||||
<li>
|
||||
{{ dump(task|json_encode) }}
|
||||
<button><span class="material-symbols-outlined">menu</span></button>
|
||||
<article>
|
||||
<div class="summary">
|
||||
<h3>{{ task.title }}</h3>
|
||||
{% if task.description %}
|
||||
<p>{{ task.description }}</p>
|
||||
{% endif %}
|
||||
{% if task.description %}<p>{{ task.description }}</p>{% endif %}
|
||||
</div>
|
||||
<div class="info">
|
||||
<ul>
|
||||
<li>
|
||||
<span>Duration</span> <span>{{ task.estimatedDurationMinutes }} minutes</span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Priority</span><span>{{ task.priority }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Category</span><span>{{ task.category }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span>Recurring</span><span>{{ task.isRecurring ? 'Yes' : 'No' }}</span>
|
||||
</li>
|
||||
<li><span>Duration</span><span>{{ task.estimatedDurationMinutes }} minutes</span></li>
|
||||
<li><span>Priority</span><span>{{ task.priority|capitalize }}</span></li>
|
||||
{% if task.category %}<li><span>Category</span><span>{{ task.category }}</span></li>{% endif %}
|
||||
</ul>
|
||||
</div>
|
||||
{% if task.subtasks is not empty %}
|
||||
<p><strong>Subtasks:</strong> {{ task.subtasks|map(subtask => subtask.title)|join(', ') }}</p>
|
||||
{% endif %}
|
||||
</article>
|
||||
</li>
|
||||
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
@@ -0,0 +1,2 @@
|
||||
<div id="brain-dump-modal-container" hx-swap-oob="innerHTML"></div>
|
||||
{{ include('task/_task_list.html.twig', {tasks: tasks, subtasks_by_parent: subtasks_by_parent, selected_date: selected_date, out_of_band: true}) }}
|
||||
@@ -0,0 +1 @@
|
||||
<p class="brain-dump-feedback brain-dump-feedback--error" role="alert">{{ message }}</p>
|
||||
@@ -0,0 +1,47 @@
|
||||
<dialog class="brain-dump-proposal-dialog" aria-labelledby="brain-dump-proposal-title">
|
||||
<div class="brain-dump-proposal-dialog__content">
|
||||
<h2 id="brain-dump-proposal-title">Proposed tasks</h2>
|
||||
<p>Review these suggestions before they are added to {{ selected_date|date('l, j F') }}.</p>
|
||||
|
||||
{% if error|default(null) %}
|
||||
<p class="brain-dump-feedback brain-dump-feedback--error" role="alert">{{ error }}</p>
|
||||
{% endif %}
|
||||
|
||||
<ul class="brain-dump-proposal-list">
|
||||
{% for task in tasks %}
|
||||
<li>
|
||||
<article>
|
||||
<h3>{{ task.title }}</h3>
|
||||
<p class="brain-dump-proposal-list__meta">{{ task.estimatedDurationMinutes }} min · {{ task.priority|capitalize }}{% if task.category %} · {{ task.category }}{% endif %}</p>
|
||||
{% if task.description %}<p>{{ task.description }}</p>{% endif %}
|
||||
{% if task.subtasks is not empty %}
|
||||
<h4>Subtasks</h4>
|
||||
<ul>
|
||||
{% for subtask in task.subtasks %}
|
||||
<li>
|
||||
<strong>{{ subtask.title }}</strong>
|
||||
<span>{{ subtask.estimatedDurationMinutes }} min · {{ subtask.priority|capitalize }}{% if subtask.category %} · {{ subtask.category }}{% endif %}</span>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
{% endif %}
|
||||
</article>
|
||||
</li>
|
||||
{% endfor %}
|
||||
</ul>
|
||||
|
||||
<form
|
||||
class="brain-dump-proposal-dialog__actions"
|
||||
method="post"
|
||||
hx-post="{{ path('app_task_braindump_confirm') }}"
|
||||
hx-target="#brain-dump-modal-container"
|
||||
hx-swap="innerHTML"
|
||||
hx-disabled-elt="button[type=submit]"
|
||||
>
|
||||
<input type="hidden" name="_token" value="{{ csrf_token('task_braindump_confirm') }}">
|
||||
<input type="hidden" name="proposal_id" value="{{ proposal_id }}">
|
||||
<button type="button" data-close-brain-dump-dialog>Cancel</button>
|
||||
<button class="task-composer__submit" type="submit">Confirm adding these tasks</button>
|
||||
</form>
|
||||
</div>
|
||||
</dialog>
|
||||
@@ -4,6 +4,12 @@
|
||||
<p>Capture it now; the details can wait.</p>
|
||||
</div>
|
||||
|
||||
<div class="task-composer__tabs" role="tablist" aria-label="Task creation mode">
|
||||
<button id="manual-task-tab" type="button" role="tab" aria-selected="true" aria-controls="manual-task-panel" tabindex="0">Manual Task</button>
|
||||
<button id="brain-dump-tab" type="button" role="tab" aria-selected="false" aria-controls="brain-dump-panel" tabindex="-1">Brain Dump</button>
|
||||
</div>
|
||||
|
||||
<div id="manual-task-panel" role="tabpanel" aria-labelledby="manual-task-tab">
|
||||
{{ form_start(form, {
|
||||
action: path('app_task_new'),
|
||||
attr: {
|
||||
@@ -51,4 +57,31 @@
|
||||
<button class="task-composer__submit" type="submit"><span class="material-symbols-outlined" aria-hidden="true">add</span>Add task</button>
|
||||
</div>
|
||||
{{ form_end(form) }}
|
||||
</div>
|
||||
|
||||
<div id="brain-dump-panel" role="tabpanel" aria-labelledby="brain-dump-tab" hidden>
|
||||
<form
|
||||
class="braindump-form"
|
||||
method="post"
|
||||
action="{{ path('app_task_braindump_generate') }}"
|
||||
hx-post="{{ path('app_task_braindump_generate') }}"
|
||||
hx-target="#brain-dump-modal-container"
|
||||
hx-swap="innerHTML"
|
||||
hx-indicator="#brain-dump-thinking"
|
||||
hx-disabled-elt="button[type=submit]"
|
||||
>
|
||||
<input type="hidden" name="_token" value="{{ csrf_token('task_braindump_generate') }}">
|
||||
<input type="hidden" name="date" value="{{ form.vars.data.scheduledFor|date('Y-m-d') }}">
|
||||
<label for="task-brain-dump">What's on your mind?</label>
|
||||
<textarea id="task-brain-dump" name="brain_dump" rows="8" placeholder="Dump everything that's on your mind..." required></textarea>
|
||||
<div class="task-composer__actions">
|
||||
<button class="task-composer__submit" type="submit"><span class="material-symbols-outlined" aria-hidden="true">robot_2</span>Generate tasks</button>
|
||||
</div>
|
||||
<span id="brain-dump-thinking" class="thinking htmx-indicator" aria-live="polite">
|
||||
<span class="material-symbols-outlined spinner" aria-hidden="true">progress_activity</span>Thinking…
|
||||
</span>
|
||||
</form>
|
||||
<div id="brain-dump-feedback" aria-live="assertive"></div>
|
||||
</div>
|
||||
</section>
|
||||
<div id="brain-dump-modal-container"></div>
|
||||
|
||||
Reference in New Issue
Block a user