Macro is a unified workspace for teams: email, chat, docs, tasks, agents, calls, and CRM — @-linked together with shared AI memory.
TypeScript agentaiai-agentsall-in-onecrmcrm-systememaillinearmcpmessagingnotesnotionofficerustslackslack-alternativestartupstartup-toolstypescriptworkspace
feat(channel): message/task mode toggle for channel and DM inputs (#5387)
Jacob Beckerman282ab15189cc
diff --git a/apps/web/justfile b/apps/web/justfileindex e1451fe4a9..ac04fa3eba 100644--- a/apps/web/justfile+++ b/apps/web/justfile@@ -57,20 +57,26 @@ local-email: ensure-cache-wasm# All app builds need the gitignored wasm pkg (src/lib/graphql-cache/wasm):# without it the cache worker's dynamic import 404s at runtime and the# normalized cache silently degrades to network-only.+#+# The vite build's chunk-rendering peaks right at node's default ~4GB heap+# cap, so CI builds flap with "Ineffective mark-compacts near heap limit".+# Lift the ceiling; peak usage stays the same, it just stops aborting.+node_heap := "--max-old-space-size=6144"+build-dev: build-cache-wasm- MODE=development NODE_ENV=production bun run --bun build+ MODE=development NODE_ENV=production NODE_OPTIONS="{{node_heap}}" bun run --bun buildbuild-staging: build-cache-wasm- MODE=staging NODE_ENV=production bun run --bun build+ MODE=staging NODE_ENV=production NODE_OPTIONS="{{node_heap}}" bun run --bun buildbuild-prod: build-cache-wasm- MODE=production NODE_ENV=production bun run --bun build+ MODE=production NODE_ENV=production NODE_OPTIONS="{{node_heap}}" bun run --bun build# Tauri build hook (run automatically via beforeBuildCommand) — not meant to be run directly[private]build-tauri: build-cache-wasmprintf production > tauri/src-tauri/.macro-tauri-env- MODE=production NODE_ENV=production bun run --bun build+ MODE=production NODE_ENV=production NODE_OPTIONS="{{node_heap}}" bun run --bun build# Build the bundle, zip it, and install it at# tooling/native_app_server/app-archive.zip for the bundlediff --git a/apps/web/src/components/ui/components/ToggleSwitch.tsx b/apps/web/src/components/ui/components/ToggleSwitch.tsxindex 8121f34a9f..9527b8c750 100644--- a/apps/web/src/components/ui/components/ToggleSwitch.tsx+++ b/apps/web/src/components/ui/components/ToggleSwitch.tsx@@ -57,6 +57,14 @@ export const ToggleSwitch = (props: ToggleSwitchProps): JSX.Element => {local.onChange?.(checked);};+ // Kobalte's switch root is an inert div — only the control and the label+ // toggle. Forward clicks that land on the root itself (its padding/gap) to+ // the hidden input so the whole component is one hit target.+ const handleRootClick = (event: MouseEvent) => {+ if (event.target !== event.currentTarget) return;+ (event.currentTarget as HTMLElement).querySelector('input')?.click();+ };+onCleanup(() => {if (stretchTimeout) clearTimeout(stretchTimeout);});@@ -68,6 +76,7 @@ export const ToggleSwitch = (props: ToggleSwitchProps): JSX.Element => {onChange={handleChange}disabled={local.disabled}checked={local.checked}+ onClick={handleRootClick}{...others}><KobalteSwitch.Input class="sr-only" />diff --git a/apps/web/src/features/block-md/component/ComposeTask.tsx b/apps/web/src/features/block-md/component/ComposeTask.tsxindex 7b590a6e1e..b09fa2dca0 100644--- a/apps/web/src/features/block-md/component/ComposeTask.tsx+++ b/apps/web/src/features/block-md/component/ComposeTask.tsx@@ -25,8 +25,6 @@ import type { PortalScope } from '@core/component/ScopedPortal';import { toast } from '@core/component/Toast/Toast';import { useUserId } from '@core/context/user';import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';-import { createTask } from '@core/util/create';-import { filterMap } from '@core/util/list';import { buildSimpleEntityUrl } from '@core/util/url';import { mergeRegister } from '@lexical/utils';import ArrowSquareOutIcon from '@phosphor/arrow-square-out.svg';@@ -34,31 +32,13 @@ import ArrowsOutIcon from '@phosphor/arrows-out.svg';import PaperclipIcon from '@phosphor/paperclip.svg';import SplitIcon from '@phosphor/square-half.svg';import XIcon from '@phosphor/x.svg';-import {- propertyApiValuesToNormalized,- propertyValueToApi,-} from '@property/api/converters';import { Modals } from '@property/component/modal';-import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';-import {- PropertiesProvider,- type PropertySaveHandler,-} from '@property/context/PropertiesContext';-import { InlineTagsPill, useLocalDocTags } from '@property/tags';-import type {- Property,- PropertyApiValues,- PropertyOption,-} from '@property/types';+import { PropertiesProvider } from '@property/context/PropertiesContext';+import { InlineTagsPill } from '@property/tags';+import type { PropertyApiValues } from '@property/types';import { useUpsertToHistoryMutation } from '@queries/history/history';-import { useTagsQuery } from '@queries/properties/tags';-import { refetchSoupEntity } from '@queries/soup/cache';-import { propertiesServiceClient } from '@service-properties/client';-import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';-import type { PropertyDefinitionDetailResponse } from '@service-properties/generated/schemas/propertyDefinitionDetailResponse';import { onElementConnect } from '@solid-primitives/lifecycle';import { debounce } from '@solid-primitives/scheduled';-import { useQuery } from '@tanstack/solid-query';import { Button, Hotkey, Scroll, ToggleSwitch } from '@ui';import {$getRoot,@@ -84,8 +64,13 @@ import {Suspense,untrack,} from 'solid-js';-import { createStore, reconcile, type Store, unwrap } from 'solid-js/store';+import { reconcile, unwrap } from 'solid-js/store';import { tabbable } from 'tabbable';+import {+ createTaskComposerProperties,+ createTaskWithProperties,+ defaultTaskPropertyValues,+} from '../util/taskComposerProperties';import {clearTaskComposerDraft,loadTaskComposerDraft,@@ -95,14 +80,6 @@ import {import { InlinePropertyValue } from './InlinePropertyValue';import { SimilarTasksSection } from './TaskDuplicateList';-// Show these props in the composer (Linear-style left-to-right order).-const COMPOSER_PROPERTIES = [- SYSTEM_PROPERTY_IDS.STATUS,- SYSTEM_PROPERTY_IDS.PRIORITY,- SYSTEM_PROPERTY_IDS.ASSIGNEES,- SYSTEM_PROPERTY_IDS.DUE_DATE,-];-const COMPOSER_PROPERTY_SET = new Set<string>(COMPOSER_PROPERTIES);type ComposerTagLayoutMode = 'bottom' | 'title';function composerTitleNavigationPlugin(@@ -190,7 +167,7 @@ function isTitleSelectionAtStart() {return true;}-function ComposeTaskTitleEditor(props: {+export function ComposeTaskTitleEditor(props: {value: Accessor<string>;onChange: (value: string) => void;disabled: Accessor<boolean>;@@ -333,93 +310,6 @@ function ComposeTaskTitleEditor(props: {);}-/**- * Make a task and append props using the create_task endpoint.- * @param taskTitle Title string- * @param taskContent content markdown string- * @param properties Stored prop value map- * @param definitions The definitions map for extra meta data- * @returns- */-async function createTaskWithProperties(- taskTitle: string,- taskContent: string,- properties: Array<[string, PropertyApiValues]>,- definitions: Map<- string,- PropertyDefinition | PropertyDefinitionDetailResponse- >,- upsertToHistory: (params: { itemId: string; itemType: 'document' }) => void-) {- // Convert properties to API format (filter out null values)- const propertyValues = properties.flatMap(([id, value]) => {- const definition = definitions.get(id);- const isMultiSelect = definition- ? 'is_multi_select' in definition- ? definition.is_multi_select- : definition.isMultiSelect- : value.valueType === 'SELECT_STRING' && !COMPOSER_PROPERTY_SET.has(id);- const apiValue = propertyValueToApi(value, isMultiSelect);- if (apiValue === null) return [];- return [{ propertyId: id, value: apiValue }];- });-- const documentId = await createTask({- title: taskTitle,- content: taskContent,- propertyValues: propertyValues.length > 0 ? propertyValues : undefined,- });-- if (!documentId) {- toast.failure('Failed to create Task');- return null;- }-- // refetchSoupEntity is already called inside createTask — just upsert to history- refetchSoupEntity(documentId, 'document');-- // Upsert the new task to history- upsertToHistory({- itemId: documentId,- itemType: 'document',- });-- return documentId;-}--/**- * Helper to get display value of local property- * @param definition The prop definition- * @param savedValues The map of saved vals by propDef id- * @param options The map of the options for the prop from the server- * @returns- */-function extractPropertyValue(- definition: PropertyDefinition,- savedValues: Store<Record<string, PropertyApiValues>>,- options: Map<string, PropertyOption[]>-) {- const { type, value } = propertyApiValuesToNormalized(- savedValues[definition.id]- );- if (type === 'EMPTY') return null;- if (- definition.data_type === 'SELECT_NUMBER' ||- definition.data_type === 'SELECT_STRING'- ) {- const opts = options.get(definition.id);- if (!opts) return null;- if (Array.isArray(value)) {- return filterMap(value as string[], (id) => {- const opt = opts.find((opt) => opt.id === id);- return opt ? opt.id : undefined;- });- }- } else {- return value;- }-}-/*** Toast preview component for successful task creation.* @param props@@ -465,24 +355,12 @@ export function ComposeTask(props: ComposeTaskProps) {const getDefaultPropertyValues = (): Record<string, PropertyApiValues> => {const ids = (() => {if (props.initialAssigneeIds && props.initialAssigneeIds.length > 0) {- return [...new Set(props.initialAssigneeIds)];+ return props.initialAssigneeIds;}const id = currentUserId();return id ? [id] : [];})();- return {- [SYSTEM_PROPERTY_IDS.ASSIGNEES]: {- valueType: 'ENTITY' as const,- refs: ids.map((entity_id) => ({- entity_id,- entity_type: 'USER' as const,- })),- },- [SYSTEM_PROPERTY_IDS.STATUS]: {- valueType: 'SELECT_STRING' as const,- values: [PROPERTY_OPTION_IDS.STATUS.NOT_STARTED],- },- };+ return defaultTaskPropertyValues(ids);};// draft init logic@@ -544,9 +422,17 @@ export function ComposeTask(props: ComposeTaskProps) {}};- const [propertyValues, setPropertyValues] = createStore<- Record<string, PropertyApiValues>- >(initialState.propertyValues);+ const {+ propertyValues,+ setPropertyValues,+ properties,+ saveHandler,+ composerTags,+ clearComposerTags,+ createDefinitions,+ } = createTaskComposerProperties({+ initialValues: initialState.propertyValues,+ });// History upsert mutationconst upsertToHistoryMutation = useUpsertToHistoryMutation();@@ -577,124 +463,6 @@ export function ComposeTask(props: ComposeTaskProps) {});});- const systemPropertiesQuery = useQuery(() => ({- queryKey: ['compose-task', 'system-properties'],- queryFn: async () => {- const result = await propertiesServiceClient.listProperties({- scope: 'system',- include_options: true,- });- if (result.isErr()) {- throw new Error('Failed to fetch system properties');- }- const data = result.value;- return data;- },- staleTime: 1000 * 60 * 10, // TODO (seamus) Ask daniel what might make us wanna refetch this- retry: 1,- refetchOnWindowFocus: false,- refetchOnMount: false,- refetchOnReconnect: false,- placeholderData: (prev) => prev,- }));- const tagsQuery = useTagsQuery();-- const definitions = () => {- if (!systemPropertiesQuery.isSuccess) return new Map();- const data = systemPropertiesQuery.data;- return new Map(- data.map((p) => {- const definition = 'definition' in p ? p.definition : p;- return [definition.id, definition];- })- );- };-- const createDefinitions = () => {- const map = new Map<- PropertyDefinition['id'],- PropertyDefinition | PropertyDefinitionDetailResponse- >(definitions());- for (const tagSet of tagsQuery.data ?? []) {- if (tagSet.definition) {- map.set(tagSet.definition.id, tagSet.definition);- }- }- return map;- };-- const options = () => {- if (!systemPropertiesQuery.isSuccess) return new Map();- const data = systemPropertiesQuery.data;- return new Map(- data.map((p) => {- const definition = 'definition' in p ? p.definition : p;- const options = 'property_options' in p ? p.property_options : [];- return [definition.id, options];- })- );- };-- const properties = (): Property[] => {- return filterMap(COMPOSER_PROPERTIES, (id) => {- const definition = definitions().get(id);- if (!definition) return;- return {- propertyId: `compose-${definition.display_name}`,- propertyDefinitionId: definition.id,- displayName: definition.display_name,- isMultiSelect: definition.is_multi_select,- owner: definition.owner,- specificEntityType: definition.specific_entity_type ?? null,- updatedAt: new Date(0),- createdAt: new Date(0),- valueType: definition.data_type,- value: extractPropertyValue(definition, propertyValues, options()),- options: options().get(definition.id),- } as Property;- });- };-- const saveHandler: PropertySaveHandler = {- saveProperty: async (property: Property, value: PropertyApiValues) => {- setPropertyValues(property.propertyDefinitionId, value);- },- saveDate: async (property: Property, date: Date) => {- setPropertyValues(property.propertyDefinitionId, {- valueType: 'DATE',- value: date,- });- },- };-- const composerTags = useLocalDocTags(- (definitionId) => {- const value = propertyValues[definitionId];- return value?.valueType === 'SELECT_STRING' && value.values- ? value.values- : [];- },- (definition, optionIds) => {- setPropertyValues(definition.id, {- valueType: 'SELECT_STRING',- values: optionIds,- });- }- );-- const clearComposerTags = () => {- const next = structuredClone(unwrap(propertyValues));- for (const [definitionId, value] of Object.entries(next)) {- if (- value.valueType === 'SELECT_STRING' &&- !COMPOSER_PROPERTY_SET.has(definitionId)- ) {- delete next[definitionId];- }- }- setPropertyValues(reconcile(next));- };-const deleteTitleTagsAtStart = () => {if (tagLayoutMode() !== 'title') return false;clearComposerTags();diff --git a/apps/web/src/features/block-md/util/taskComposerProperties.ts b/apps/web/src/features/block-md/util/taskComposerProperties.tsnew file mode 100644index 0000000000..c92088dc05--- /dev/null+++ b/apps/web/src/features/block-md/util/taskComposerProperties.ts@@ -0,0 +1,264 @@+import { toast } from '@core/component/Toast/Toast';+import { createTask } from '@core/util/create';+import { filterMap } from '@core/util/list';+import {+ propertyApiValuesToNormalized,+ propertyValueToApi,+} from '@property/api/converters';+import { PROPERTY_OPTION_IDS, SYSTEM_PROPERTY_IDS } from '@property/constants';+import type { PropertySaveHandler } from '@property/context/PropertiesContext';+import { useLocalDocTags } from '@property/tags';+import type {+ Property,+ PropertyApiValues,+ PropertyOption,+} from '@property/types';+import { useListPropertiesQuery } from '@queries/properties/definitions';+import { useTagsQuery } from '@queries/properties/tags';+import { refetchSoupEntity } from '@queries/soup/cache';+import type { PropertyDefinition } from '@service-properties/generated/schemas/propertyDefinition';+import type { PropertyDefinitionDetailResponse } from '@service-properties/generated/schemas/propertyDefinitionDetailResponse';+import { createStore, reconcile, type Store, unwrap } from 'solid-js/store';++/** Props shown in the composer (Linear-style left-to-right order). */+const COMPOSER_PROPERTIES = [+ SYSTEM_PROPERTY_IDS.STATUS,+ SYSTEM_PROPERTY_IDS.PRIORITY,+ SYSTEM_PROPERTY_IDS.ASSIGNEES,+ SYSTEM_PROPERTY_IDS.DUE_DATE,+];+const COMPOSER_PROPERTY_SET = new Set<string>(COMPOSER_PROPERTIES);++/** The default property values a fresh task composer starts from. */+export function defaultTaskPropertyValues(+ assigneeIds: string[]+): Record<string, PropertyApiValues> {+ return {+ [SYSTEM_PROPERTY_IDS.ASSIGNEES]: {+ valueType: 'ENTITY' as const,+ refs: [...new Set(assigneeIds)].map((entity_id) => ({+ entity_id,+ entity_type: 'USER' as const,+ })),+ },+ [SYSTEM_PROPERTY_IDS.STATUS]: {+ valueType: 'SELECT_STRING' as const,+ values: [PROPERTY_OPTION_IDS.STATUS.NOT_STARTED],+ },+ };+}++/**+ * Make a task and append props using the create_task endpoint.+ * @param taskTitle Title string+ * @param taskContent content markdown string+ * @param properties Stored prop value map+ * @param definitions The definitions map for extra meta data+ * @param upsertToHistory Callback that upserts the created task to history+ * @returns+ */+export async function createTaskWithProperties(+ taskTitle: string,+ taskContent: string,+ properties: Array<[string, PropertyApiValues]>,+ definitions: Map<+ string,+ PropertyDefinition | PropertyDefinitionDetailResponse+ >,+ upsertToHistory: (params: { itemId: string; itemType: 'document' }) => void+) {+ // Convert properties to API format (filter out null values)+ const propertyValues = properties.flatMap(([id, value]) => {+ const definition = definitions.get(id);+ const isMultiSelect = definition+ ? 'is_multi_select' in definition+ ? definition.is_multi_select+ : definition.isMultiSelect+ : value.valueType === 'SELECT_STRING' && !COMPOSER_PROPERTY_SET.has(id);+ const apiValue = propertyValueToApi(value, isMultiSelect);+ if (apiValue === null) return [];+ return [{ propertyId: id, value: apiValue }];+ });++ const documentId = await createTask({+ title: taskTitle,+ content: taskContent,+ propertyValues: propertyValues.length > 0 ? propertyValues : undefined,+ });++ if (!documentId) {+ toast.failure('Failed to create Task');+ return null;+ }++ // refetchSoupEntity is already called inside createTask — just upsert to history+ refetchSoupEntity(documentId, 'document');++ // Upsert the new task to history+ upsertToHistory({+ itemId: documentId,+ itemType: 'document',+ });++ return documentId;+}++/**+ * Helper to get display value of local property+ * @param definition The prop definition+ * @param savedValues The map of saved vals by propDef id+ * @param options The map of the options for the prop from the server+ * @returns+ */+function extractPropertyValue(+ definition: PropertyDefinition,+ savedValues: Store<Record<string, PropertyApiValues>>,+ options: Map<string, PropertyOption[]>+) {+ const { type, value } = propertyApiValuesToNormalized(+ savedValues[definition.id]+ );+ if (type === 'EMPTY') return null;+ if (+ definition.data_type === 'SELECT_NUMBER' ||+ definition.data_type === 'SELECT_STRING'+ ) {+ const opts = options.get(definition.id);+ if (!opts) return null;+ if (Array.isArray(value)) {+ return filterMap(value as string[], (id) => {+ const opt = opts.find((opt) => opt.id === id);+ return opt ? opt.id : undefined;+ });+ }+ } else {+ return value;+ }+}++/**+ * Local (not-yet-persisted) property state for a task composer: the system+ * property pills (status/priority/assignees/due date), tag state, and the+ * save handler that writes edits back into the local store. Shared between+ * the task compose dialog and the channel input's task mode.+ */+export function createTaskComposerProperties(args: {+ initialValues: Record<string, PropertyApiValues>;+}) {+ const [propertyValues, setPropertyValues] = createStore<+ Record<string, PropertyApiValues>+ >(args.initialValues);++ const systemPropertiesQuery = useListPropertiesQuery(() => ({+ scope: 'system',+ includeOptions: true,+ }));+ const tagsQuery = useTagsQuery();++ const definitions = () => {+ if (!systemPropertiesQuery.isSuccess) return new Map();+ const data = systemPropertiesQuery.data;+ return new Map(+ data.map((p) => {+ const definition = 'definition' in p ? p.definition : p;+ return [definition.id, definition];+ })+ );+ };++ const createDefinitions = () => {+ const map = new Map<+ PropertyDefinition['id'],+ PropertyDefinition | PropertyDefinitionDetailResponse+ >(definitions());+ for (const tagSet of tagsQuery.data ?? []) {+ if (tagSet.definition) {+ map.set(tagSet.definition.id, tagSet.definition);+ }+ }+ return map;+ };++ const options = () => {+ if (!systemPropertiesQuery.isSuccess) return new Map();+ const data = systemPropertiesQuery.data;+ return new Map(+ data.map((p) => {+ const definition = 'definition' in p ? p.definition : p;+ const options = 'property_options' in p ? p.property_options : [];+ return [definition.id, options];+ })+ );+ };++ const properties = (): Property[] => {+ return filterMap(COMPOSER_PROPERTIES, (id) => {+ const definition = definitions().get(id);+ if (!definition) return;+ return {+ propertyId: `compose-${definition.display_name}`,+ propertyDefinitionId: definition.id,+ displayName: definition.display_name,+ isMultiSelect: definition.is_multi_select,+ owner: definition.owner,+ specificEntityType: definition.specific_entity_type ?? null,+ updatedAt: new Date(0),+ createdAt: new Date(0),+ valueType: definition.data_type,+ value: extractPropertyValue(definition, propertyValues, options()),+ options: options().get(definition.id),+ } as Property;+ });+ };++ const saveHandler: PropertySaveHandler = {+ saveProperty: async (property: Property, value: PropertyApiValues) => {+ setPropertyValues(property.propertyDefinitionId, value);+ },+ saveDate: async (property: Property, date: Date) => {+ setPropertyValues(property.propertyDefinitionId, {+ valueType: 'DATE',+ value: date,+ });+ },+ };++ const composerTags = useLocalDocTags(+ (definitionId) => {+ const value = propertyValues[definitionId];+ return value?.valueType === 'SELECT_STRING' && value.values+ ? value.values+ : [];+ },+ (definition, optionIds) => {+ setPropertyValues(definition.id, {+ valueType: 'SELECT_STRING',+ values: optionIds,+ });+ }+ );++ /** Drops every applied tag value, keeping the composer's system props. */+ const clearComposerTags = () => {+ const next = structuredClone(unwrap(propertyValues));+ for (const [definitionId, value] of Object.entries(next)) {+ if (+ value.valueType === 'SELECT_STRING' &&+ !COMPOSER_PROPERTY_SET.has(definitionId)+ ) {+ delete next[definitionId];+ }+ }+ setPropertyValues(reconcile(next));+ };++ return {+ propertyValues,+ setPropertyValues,+ properties,+ saveHandler,+ composerTags,+ clearComposerTags,+ createDefinitions,+ };+}diff --git a/apps/web/src/features/block-md/util/taskComposerStorage.test.ts b/apps/web/src/features/block-md/util/taskComposerStorage.test.tsnew file mode 100644index 0000000000..28dc8ab978--- /dev/null+++ b/apps/web/src/features/block-md/util/taskComposerStorage.test.ts@@ -0,0 +1,97 @@+/**+ * @vitest-environment jsdom+ */++import { beforeEach, describe, expect, it } from 'vitest';+import {+ clearTaskComposerDraft,+ loadTaskComposerDraft,+ saveTaskComposerDraft,+ type TaskComposerDraft,+} from './taskComposerStorage';++const DEFAULT_KEY = 'task-composer-draft';++const draft = {+ title: 'A task',+ content: 'body',+ propertyValues: {},+};++function readRaw(key: string): TaskComposerDraft | null {+ const stored = localStorage.getItem(key);+ return stored ? JSON.parse(stored) : null;+}++function writeRaw(key: string, value: TaskComposerDraft) {+ localStorage.setItem(key, JSON.stringify(value));+}++describe('taskComposerStorage', () => {+ beforeEach(() => {+ localStorage.clear();+ });++ it('round-trips a draft under the default key', () => {+ saveTaskComposerDraft(draft);+ expect(loadTaskComposerDraft()?.title).toBe('A task');+ expect(readRaw(DEFAULT_KEY)).toBeTruthy();+ });++ it('scopes drafts to a custom storage key', () => {+ const storage = { storageKey: 'task-composer-draft-channel:c1' };+ saveTaskComposerDraft(draft, storage);++ expect(readRaw(DEFAULT_KEY)).toBeNull();+ expect(loadTaskComposerDraft()).toBeNull();+ expect(loadTaskComposerDraft(storage)?.title).toBe('A task');++ clearTaskComposerDraft(storage);+ expect(loadTaskComposerDraft(storage)).toBeNull();+ });++ it('expires default-key drafts after the expiry window', () => {+ saveTaskComposerDraft(draft);+ const stored = readRaw(DEFAULT_KEY);+ writeRaw(DEFAULT_KEY, {+ ...(stored as TaskComposerDraft),+ timestamp: Date.now() - 10 * 60 * 1000,+ });++ expect(loadTaskComposerDraft()).toBeNull();+ // The expired entry is dropped from storage as a side effect.+ expect(readRaw(DEFAULT_KEY)).toBeNull();+ });++ it('never expires drafts stored with expiryMs null', () => {+ const storage = {+ storageKey: 'task-composer-draft-channel:c1',+ expiryMs: null,+ };+ saveTaskComposerDraft(draft, storage);+ const stored = readRaw(storage.storageKey);+ writeRaw(storage.storageKey, {+ ...(stored as TaskComposerDraft),+ timestamp: Date.now() - 365 * 24 * 60 * 60 * 1000,+ });++ expect(loadTaskComposerDraft(storage)?.title).toBe('A task');+ });++ it('rehydrates DATE property values into Date instances', () => {+ const storage = { storageKey: 'task-composer-draft-channel:c1' };+ saveTaskComposerDraft(+ {+ ...draft,+ propertyValues: {+ due: { valueType: 'DATE', value: new Date('2026-08-04T00:00:00Z') },+ },+ },+ storage+ );++ const loaded = loadTaskComposerDraft(storage);+ const due = loaded?.propertyValues.due as { value: unknown };+ expect(due.value).toBeInstanceOf(Date);+ });+});diff --git a/apps/web/src/features/block-md/util/taskComposerStorage.ts b/apps/web/src/features/block-md/util/taskComposerStorage.tsindex 2aeb2c34c5..90c013ecc4 100644--- a/apps/web/src/features/block-md/util/taskComposerStorage.ts+++ b/apps/web/src/features/block-md/util/taskComposerStorage.ts@@ -4,6 +4,18 @@ import type { SerializedEditorState } from 'lexical';const STORAGE_KEY = 'task-composer-draft';const EXPIRY_TIME_MS = 2 * 60 * 1000; // 2 minutes+/**+ * Where a task composer draft is stored and how long it stays valid.+ * Defaults describe the global compose-task dialog draft; other hosts+ * (e.g. the channel input's task mode) pass their own scoped key.+ */+export type TaskComposerDraftStorage = {+ /** localStorage key. Defaults to the compose-task dialog's draft. */+ storageKey?: string;+ /** Max draft age in ms; `null` means drafts never expire. Defaults to 2 minutes. */+ expiryMs?: number | null;+};+export interface TaskComposerDraft {title: string;/** Serialized Lexical editor state (lossless — preserves images, dimensions, etc.) */@@ -18,14 +30,18 @@ export interface TaskComposerDraft {* Save task composer draft to local storage*/export function saveTaskComposerDraft(- draft: Omit<TaskComposerDraft, 'timestamp'>+ draft: Omit<TaskComposerDraft, 'timestamp'>,+ storage?: TaskComposerDraftStorage): void {try {const draftWithTimestamp: TaskComposerDraft = {...draft,timestamp: Date.now(),};- localStorage.setItem(STORAGE_KEY, JSON.stringify(draftWithTimestamp));+ localStorage.setItem(+ storage?.storageKey ?? STORAGE_KEY,+ JSON.stringify(draftWithTimestamp)+ );} catch (error) {console.warn('Failed to save task composer draft:', error);}@@ -34,18 +50,21 @@ export function saveTaskComposerDraft(/*** Load task composer draft from local storage if not expired*/-export function loadTaskComposerDraft(): TaskComposerDraft | null {+export function loadTaskComposerDraft(+ storage?: TaskComposerDraftStorage+): TaskComposerDraft | null {try {- const stored = localStorage.getItem(STORAGE_KEY);+ const stored = localStorage.getItem(storage?.storageKey ?? STORAGE_KEY);if (!stored) return null;const draft: TaskComposerDraft = JSON.parse(stored);- const now = Date.now();- const elapsed = now - draft.timestamp;+ const expiryMs =+ storage?.expiryMs === undefined ? EXPIRY_TIME_MS : storage.expiryMs;+ const elapsed = Date.now() - draft.timestamp;- if (elapsed > EXPIRY_TIME_MS) {+ if (expiryMs !== null && elapsed > expiryMs) {// Draft expired, remove it- clearTaskComposerDraft();+ clearTaskComposerDraft(storage);return null;}@@ -53,7 +72,7 @@ export function loadTaskComposerDraft(): TaskComposerDraft | null {return draft;} catch (error) {console.warn('Failed to load task composer draft:', error);- clearTaskComposerDraft();+ clearTaskComposerDraft(storage);return null;}}@@ -82,9 +101,11 @@ function rehydratePropertyValues(/*** Clear task composer draft from local storage*/-export function clearTaskComposerDraft(): void {+export function clearTaskComposerDraft(+ storage?: TaskComposerDraftStorage+): void {try {- localStorage.removeItem(STORAGE_KEY);+ localStorage.removeItem(storage?.storageKey ?? STORAGE_KEY);} catch (error) {console.warn('Failed to clear task composer draft:', error);}@@ -93,14 +114,15 @@ export function clearTaskComposerDraft(): void {/*** Update timestamp of existing draft (used when closing composer)*/-export function updateDraftTimestamp(): void {+export function updateDraftTimestamp(storage?: TaskComposerDraftStorage): void {try {- const stored = localStorage.getItem(STORAGE_KEY);+ const key = storage?.storageKey ?? STORAGE_KEY;+ const stored = localStorage.getItem(key);if (!stored) return;const draft: TaskComposerDraft = JSON.parse(stored);draft.timestamp = Date.now();- localStorage.setItem(STORAGE_KEY, JSON.stringify(draft));+ localStorage.setItem(key, JSON.stringify(draft));} catch (error) {console.warn('Failed to update draft timestamp:', error);}diff --git a/apps/web/src/features/channel/Channel/Channel.tsx b/apps/web/src/features/channel/Channel/Channel.tsxindex 68af338809..0b35269b0a 100644--- a/apps/web/src/features/channel/Channel/Channel.tsx+++ b/apps/web/src/features/channel/Channel/Channel.tsx@@ -6,6 +6,7 @@ import { buildPostMessageSendPayload } from '@channel/Input/message-payload';import {makeAttachmentTrackerPersistenceKey,makeInputValuePersistenceKey,+ makeTaskPersistence,} from '@channel/Input/utils/persistence';import {type MessageData,@@ -22,7 +23,11 @@ import { useSplitPanel } from '@components/app/split-layout/layoutUtils';import { FindBar } from '@core/component/FindBar';import { StaticMarkdownContext } from '@core/component/LexicalMarkdown/component/core/StaticMarkdown';import { toast } from '@core/component/Toast/Toast';-import { useChannelActivity, useChannelName } from '@core/context/channels';+import {+ useChannelActivity,+ useChannelName,+ useChannelType,+} from '@core/context/channels';import { useUserId } from '@core/context/user';import { isMobile } from '@core/mobile/isMobile';import type { DateValue } from '@core/util/date';@@ -57,6 +62,7 @@ import {import { threadRepliesQueryOptions } from '@queries/channel/thread-replies';import { usePostTypingUpdateMutation } from '@queries/channel/typing';import { queryClient } from '@queries/client';+import { ChannelTypeEnum } from '@service-storage/client';import { useBeforeLeave } from '@solidjs/router';import {type Accessor,@@ -337,7 +343,23 @@ export function Channel(props: ChannelProps) {});const channelName = useChannelName(props.channelId);- const { popoverSplit } = useSplitLayout();+ const channelType = useChannelType(props.channelId);+ const { popoverSplit, openWithSplit } = useSplitLayout();++ // Placeholder name: a 1:1 DM named "First Last" shortens to the first+ // name; channels (and group DMs like "A, B") keep their full name.+ const inputPlaceholderName = () => {+ const name = channelName();+ if (!name) return undefined;+ if (channelType() !== ChannelTypeEnum.DirectMessage) return name;+ const parts = name.split(' ');+ return parts.length === 2 && !parts[0]?.endsWith(',') ? parts[0] : name;+ };++ const inputPlaceholder = () => {+ const name = inputPlaceholderName();+ return name ? `Type @ to share with ${name}.` : 'Type @ to share.';+ };const buildChannelMessageMention = (message: {id: string;@@ -594,6 +616,50 @@ export function Channel(props: ChannelProps) {);};+ // Task mode: post the freshly created task into the channel as a message+ // carrying a task mention.+ const onSendTask: ChannelInputProps['onSendTask'] = (task) => {+ const senderId = userId();+ if (!senderId) return;+ sendMessageMutation.mutate(+ {+ channelID: props.channelId,+ senderId,+ optimisticId: crypto.randomUUID(),+ message: {+ content: buildMentionMarkdownString({+ type: 'document',+ documentId: task.documentId,+ documentName: task.title,+ blockName: 'task',+ }),+ mentions: [{ entity_type: 'document', entity_id: task.documentId }],+ attachments: [],+ },+ optimisticAttachments: [],+ },+ {+ // The task itself was created before this send, so don't restore the+ // composer (retrying there would create a duplicate) — point at the+ // task instead.+ onError: () => {+ toast.failure('Task created, but sharing it to the channel failed', {+ actions: [+ {+ label: 'Open task',+ onClick: () =>+ openWithSplit(+ { type: 'task', id: task.documentId },+ { referredFrom: null }+ ),+ },+ ],+ });+ },+ }+ );+ };+const isChannelReady = () => {return (messagesQuery.isFetched &&@@ -835,7 +901,7 @@ export function Channel(props: ChannelProps) {input={{mode: 'channel',id: `channel-input-${props.channelId}`,- placeholder: 'Message channel',+ placeholder: inputPlaceholder(),}}participants={participants.users}bots={channelBotMentionUsers}@@ -854,6 +920,10 @@ export function Channel(props: ChannelProps) {void setChannelInputSnapshot(snapshot)}onSend={onSend}+ onSendTask={onSendTask}+ taskPersistence={makeTaskPersistence({+ channelId: props.channelId,+ })}onStartTyping={() =>typingMutation.mutate({channelId: props.channelId,diff --git a/apps/web/src/features/channel/Input/ChannelInput.tsx b/apps/web/src/features/channel/Input/ChannelInput.tsxindex 8672ee561f..c489d9d8cd 100644--- a/apps/web/src/features/channel/Input/ChannelInput.tsx+++ b/apps/web/src/features/channel/Input/ChannelInput.tsx@@ -23,6 +23,7 @@ import {} from '@core/util/upload';import type { EntityData } from '@entity';import { isIOS } from '@solid-primitives/platform';+import { makePersisted } from '@solid-primitives/storage';import { CollapsedInput, cn, Surface } from '@ui';import { $getRoot } from 'lexical';import {@@ -30,6 +31,7 @@ import {createSignal,type JSX,Match,+ onCleanup,Show,Switch,} from 'solid-js';@@ -43,6 +45,8 @@ import { createTypingTracker } from './create-typing-tracker';import { FormatButtons } from './FormatButtons';import { Input } from './Input';import { createMentionsTracker } from './mentions-tracker';+import { TaskComposer, type TaskComposerSendPayload } from './TaskComposer';+import { TaskModeSwitch } from './TaskModeSwitch';import type {EntityMentionInsertCoordinates,InputAttachmentTracker,@@ -57,6 +61,7 @@ import { isReplyInput } from './types';import { uploadInputAttachments } from './upload-attachments';import { entityToDocumentMentionInfo } from './utils/entity-mention';import { applyInlineFormat, applyNodeFormat } from './utils/formatting';+import type { InputTaskPersistence } from './utils/persistence';import { $selectTrailingParagraph } from './utils/select-trailing-paragraph';import { hasSendableInputContent } from './utils/sendable-content';@@ -77,14 +82,34 @@ export type ChannelInputProps = InputCallbacks & {* Defaults to `false`.*/collapsible?: boolean;+ /**+ * Fires when a task composed in the input's task mode has been created,+ * so the host can post it into the channel. Providing this enables the+ * message/task mode switch (desktop only).+ */+ onSendTask?: (task: TaskComposerSendPayload) => void;+ /**+ * Persists the task draft and the message/task mode flag across visits+ * (e.g. per channel), the way `persistenceKey` persists the message draft.+ */+ taskPersistence?: InputTaskPersistence;};-function WebDefaultActions(props: { input: InputData }) {+function WebDefaultActions(props: {+ input: InputData;+ onEnterTaskMode?: () => void;+}) {return (<Input.Actions><Input.Actions.Left><Input.AttachFilesAction /><Input.ToggleFormatAction />+ <Show when={props.onEnterTaskMode}>+ <TaskModeSwitch+ checked={false}+ onChange={() => props.onEnterTaskMode?.()}+ />+ </Show><Show when={isReplyInput(props.input)}><Input.CloseReplyAction /></Show>@@ -113,11 +138,19 @@ function IosDefaultActions(props: { input: InputData }) {);}-function DefaultActions(props: { input: InputData }) {+function DefaultActions(props: {+ input: InputData;+ onEnterTaskMode?: () => void;+}) {return (<Showwhen={isPlatform('ios')}- fallback={<WebDefaultActions input={props.input} />}+ fallback={+ <WebDefaultActions+ input={props.input}+ onEnterTaskMode={props.onEnterTaskMode}+ />+ }><IosDefaultActions input={props.input} /></Show>@@ -179,7 +212,60 @@ export function ChannelInput(props: ChannelInputProps) {inputId: () => props.input.id,attachFiles: (files) => inputState.commands.attachFiles(files),});- const isCollapsed = () => !!props.collapsible && collapsedInput.isCollapsed();++ // Message/task mode. Task mode swaps the message editor for an embedded+ // task composer. Desktop only — mobile keeps the plain message input.+ const canUseTaskMode = () =>+ !!props.onSendTask && !isPlatform('ios') && !isMobile();+ const taskModeSignal = createSignal(false);+ const [taskModeRequested, setTaskModeRequested] = props.taskPersistence+ ? makePersisted(taskModeSignal, { name: props.taskPersistence.modeKey })+ : taskModeSignal;+ // True when the input opens directly in task mode (persisted from a prior+ // visit); it decides who receives the mount-time autofocus.+ const taskModeRestored = taskModeRequested() === true;+ // Mount the composer on first use only, then keep it alive so a draft+ // survives toggling back and forth.+ const [taskComposerMounted, setTaskComposerMounted] =+ createSignal(taskModeRestored);+ const isTaskMode = () => canUseTaskMode() && taskModeRequested();++ const isCollapsed = () =>+ !!props.collapsible && collapsedInput.isCollapsed() && !isTaskMode();++ // Height morph between the two input faces: pin the wrapper at its current+ // height, swap faces, then transition to the new content height. The+ // wrapper is measured for the start (mid-transition it reflects the+ // animated height); the inner content for the target.+ let morphWrapperEl: HTMLDivElement | undefined;+ let morphContentEl: HTMLDivElement | undefined;+ const [morphHeight, setMorphHeight] = createSignal<number>();+ let morphTimer: ReturnType<typeof setTimeout> | undefined;+ onCleanup(() => clearTimeout(morphTimer));++ const setTaskMode = (task: boolean) => {+ if (task === taskModeRequested()) return;+ if (task) setTaskComposerMounted(true);+ const from = morphWrapperEl?.offsetHeight;+ setTaskModeRequested(task);+ if (!task) focusEditor();+ if (from === undefined) return;+ setMorphHeight(from);+ requestAnimationFrame(() => {+ // Reading offsetHeight forces a layout with the start height committed,+ // so the height change below actually transitions.+ const to = morphContentEl?.offsetHeight;+ if (to === undefined) return;+ setMorphHeight(to);+ clearTimeout(morphTimer);+ morphTimer = setTimeout(() => setMorphHeight(undefined), 350);+ });+ };++ const onTaskComposerSend = (task: TaskComposerSendPayload) => {+ props.onSendTask?.(task);+ setTaskMode(false);+ };let isEditorConnected = false;let pendingRestore:@@ -411,7 +497,9 @@ export function ChannelInput(props: ChannelInputProps) {singleLine/>)}- placeholder={inputState.view().placeholder}+ // Read through the reactive prop — the view freezes the input at+ // mount, but the placeholder can update (e.g. channel name loads).+ placeholder={props.input.placeholder}attachmentCount={inputState.view().attachments?.length ?? 0}pending={inputState.view().hasPendingAttachments}disabled={!hasSendableInputContent(inputState.view())}@@ -426,6 +514,7 @@ export function ChannelInput(props: ChannelInputProps) {const next = e.relatedTarget as Node | null;if (next && e.currentTarget.contains(next)) return;if (isInternalRefocus) return;+ if (isTaskMode()) return;collapsedInput.collapse();}}class={cn(@@ -437,65 +526,131 @@ export function ChannelInput(props: ChannelInputProps) {depth={isMobile() ? 3 : 2}solid>- <Input.DropZone- onDragStart={(valid) => inputState.setIsDraggedOver(valid)}- onDragEnd={() => inputState.setIsDraggedOver(false)}+ <div+ ref={(el) => {+ morphWrapperEl = el;+ }}+ class={cn(+ morphHeight() !== undefined &&+ 'overflow-hidden transition-[height] duration-300 ease-in-out'+ )}+ style={{+ height:+ morphHeight() !== undefined ? `${morphHeight()}px` : undefined,+ }}>- <Input.Layout>- <Input.DropOverlay />- <Input.FormatRibbon>- <FormatButtons- selectionState={() => markdownEditor.selection}- onInlineFormat={(format) =>- applyInlineFormat(markdownEditor.lexical, format)- }- onNodeFormat={(format) =>- applyNodeFormat(markdownEditor.lexical, format)- }- />- </Input.FormatRibbon>- <Input.EditorShell- ref={setScrollContainer}- onClick={(event) => {- if (!isMobile()) {- event.stopPropagation();- markdownEditor.controls.focus();- }- }}+ <div+ ref={(el) => {+ morphContentEl = el;+ }}+ >+ <div+ class={cn(+ isTaskMode() && 'hidden',+ taskComposerMounted() &&+ 'animate-[dialog-fullscreen-open_200ms_ease-out]'+ )}+ data-input-face="message">- <Input.Editor>- <MarkdownShell- config={markdownEditor}- placeholder={inputState.view().placeholder}- initialValue={inputState.view().value}- autofocus={!isMobile() && (props.autofocus ?? true)}- class="text-sm"- refFn={attach}- onConnect={() => {- isEditorConnected = true;- flushPendingRestore();- flushPendingFocus();- }}- />- <DragInsertIndicator- editor={lexicalEditor()}- state={entityDragInsertStore}- active+ <Input.DropZone+ onDragStart={(valid) => inputState.setIsDraggedOver(valid)}+ onDragEnd={() => inputState.setIsDraggedOver(false)}+ >+ <Input.Layout>+ <Input.DropOverlay />+ <Input.FormatRibbon>+ <FormatButtons+ selectionState={() => markdownEditor.selection}+ onInlineFormat={(format) =>+ applyInlineFormat(markdownEditor.lexical, format)+ }+ onNodeFormat={(format) =>+ applyNodeFormat(markdownEditor.lexical, format)+ }+ />+ </Input.FormatRibbon>+ <Input.EditorShell+ ref={setScrollContainer}+ onClick={(event) => {+ if (!isMobile()) {+ event.stopPropagation();+ markdownEditor.controls.focus();+ }+ }}+ >+ <Input.Editor>+ <MarkdownShell+ config={markdownEditor}+ placeholder={props.input.placeholder}+ initialValue={inputState.view().value}+ autofocus={+ !isMobile() &&+ (props.autofocus ?? true) &&+ !isTaskMode()+ }+ class="text-sm"+ refFn={attach}+ onConnect={() => {+ isEditorConnected = true;+ flushPendingRestore();+ flushPendingFocus();+ }}+ />+ <DragInsertIndicator+ editor={lexicalEditor()}+ state={entityDragInsertStore}+ active+ />+ </Input.Editor>+ </Input.EditorShell>+ <Input.Attachments kind="media" />+ <Input.Attachments kind="document" />+ <Input.Footer>+ <Switch>+ <Match when={props.children}>{props.children}</Match>+ <Match when>+ <DefaultActions+ input={inputState.view()}+ onEnterTaskMode={+ canUseTaskMode()+ ? () => setTaskMode(true)+ : undefined+ }+ />+ </Match>+ </Switch>+ </Input.Footer>+ </Input.Layout>+ </Input.DropZone>+ </div>+ <Show when={taskComposerMounted()}>+ <div+ class={cn(+ !isTaskMode() && 'hidden',+ 'animate-[dialog-fullscreen-open_200ms_ease-out]'+ )}+ data-input-face="task"+ >+ <TaskComposer+ active={isTaskMode()}+ autofocus={+ taskModeRestored+ ? !isMobile() && (props.autofocus ?? true)+ : true+ }+ draftPersistenceKey={props.taskPersistence?.draftKey}+ modeSwitch={+ <TaskModeSwitch+ checked={true}+ onChange={() => setTaskMode(false)}+ />+ }+ onSend={onTaskComposerSend}/>- </Input.Editor>- </Input.EditorShell>- <Input.Attachments kind="media" />- <Input.Attachments kind="document" />- <Input.Footer>- <Switch>- <Match when={props.children}>{props.children}</Match>- <Match when>- <DefaultActions input={inputState.view()} />- </Match>- </Switch>- </Input.Footer>- </Input.Layout>- </Input.DropZone>+ </div>+ </Show>+ </div>+ </div></Surface></Input.Root>);diff --git a/apps/web/src/features/channel/Input/TaskComposer.tsx b/apps/web/src/features/channel/Input/TaskComposer.tsxnew file mode 100644index 0000000000..497fca119c--- /dev/null+++ b/apps/web/src/features/channel/Input/TaskComposer.tsx@@ -0,0 +1,383 @@+import { ComposeTaskTitleEditor } from '@block-md/component/ComposeTask';+import { InlinePropertyValue } from '@block-md/component/InlinePropertyValue';+import {+ createTaskComposerProperties,+ createTaskWithProperties,+ defaultTaskPropertyValues,+} from '@block-md/util/taskComposerProperties';+import {+ loadTaskComposerDraft,+ saveTaskComposerDraft,+ type TaskComposerDraft,+ type TaskComposerDraftStorage,+} from '@block-md/util/taskComposerStorage';+import { buildConfig } from '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder';+import { MarkdownShell } from '@core/component/LexicalMarkdown/builder/MarkdownShell';+import { addMediaFromFile } from '@core/component/LexicalMarkdown/plugins/media';+import { initializeEditorEmpty } from '@core/component/LexicalMarkdown/utils';+import { useUserId } from '@core/context/user';+import { registerHotkey, useHotkeyDOMScope } from '@core/hotkey/hotkeys';+import PaperclipIcon from '@phosphor-icons/core/regular/paperclip.svg?component-solid';+import { Modals } from '@property/component/modal';+import { PropertiesProvider } from '@property/context/PropertiesContext';+import { InlineTagsPill } from '@property/tags';+import { useUpsertToHistoryMutation } from '@queries/history/history';+import { debounce } from '@solid-primitives/scheduled';+import { Scroll, SendButton } from '@ui';+import type { LexicalEditor } from 'lexical';+import {+ createEffect,+ createSignal,+ For,+ type JSX,+ on,+ onCleanup,+ onMount,+ Show,+ Suspense,+} from 'solid-js';+import { reconcile, unwrap } from 'solid-js/store';+import { InputActionButton } from './ActionButton';++export type TaskComposerSendPayload = {+ documentId: string;+ title: string;+ content: string;+};++/**+ * The channel input's task face: a slimmed-down task compose dialog+ * (title, description, property pills) that swaps in for the message+ * editor when the input is toggled into task mode. Sending creates the+ * task and hands it to the host, which posts it into the channel.+ */+export function TaskComposer(props: {+ /** Whether the composer is the visible face of the input. */+ active: boolean;+ /** Fires after the task is created; the host posts it to the channel. */+ onSend: (task: TaskComposerSendPayload) => void;+ /** The message/task mode switch, rendered in the composer footer. */+ modeSwitch?: JSX.Element;+ /**+ * Whether to focus the title editor when the composer mounts already+ * active (e.g. a restored task-mode draft). Later activations always+ * focus. Defaults to `true`.+ */+ autofocus?: boolean;+ /**+ * localStorage key to persist the draft under, scoped by the host (e.g.+ * per channel). Without it the draft only lives as long as the composer.+ */+ draftPersistenceKey?: string;+}) {+ const currentUserId = useUserId();++ // Per-host drafts follow the message input's persistence semantics (kept+ // until sent) rather than the compose dialog's short expiry window.+ const draftStorage: TaskComposerDraftStorage | undefined =+ props.draftPersistenceKey+ ? { storageKey: props.draftPersistenceKey, expiryMs: null }+ : undefined;+ const restoredDraft = draftStorage+ ? loadTaskComposerDraft(draftStorage)+ : null;++ const [title, setTitle] = createSignal(restoredDraft?.title ?? '');+ const [content, setContent] = createSignal(restoredDraft?.content ?? '');+ const [bodyEditor, setBodyEditor] = createSignal<LexicalEditor>();+ const [containerRef, setContainerRef] = createSignal<HTMLDivElement>();+ const [isCreating, setIsCreating] = createSignal(false);+ const [tagLayoutMode, setTagLayoutMode] = createSignal<'bottom' | 'title'>(+ 'bottom'+ );+ let titleEditorRoot: HTMLDivElement | undefined;+ let attachInputRef: HTMLInputElement | undefined;++ const defaultPropertyValues = () => {+ const id = currentUserId();+ return defaultTaskPropertyValues(id ? [id] : []);+ };++ const {+ propertyValues,+ setPropertyValues,+ properties,+ saveHandler,+ composerTags,+ clearComposerTags,+ createDefinitions,+ } = createTaskComposerProperties({+ initialValues: restoredDraft?.propertyValues ?? defaultPropertyValues(),+ });++ const upsertToHistoryMutation = useUpsertToHistoryMutation();++ if (draftStorage) {+ const snapshotDraft = (): Omit<TaskComposerDraft, 'timestamp'> => ({+ title: title(),+ content: content(),+ editorState: bodyEditor()?.getEditorState().toJSON(),+ propertyValues: structuredClone(unwrap(propertyValues)),+ });++ // Mirrors the compose dialog's draft autosave: skip the first run (it+ // would just rewrite what was restored), subscribe deeply to property+ // edits, and debounce the localStorage writes.+ let hasInitializedFromDraft = restoredDraft !== null;+ const debouncedSave = debounce(+ (draft: Omit<TaskComposerDraft, 'timestamp'>) =>+ saveTaskComposerDraft(draft, draftStorage),+ 300+ );+ createEffect(() => {+ title();+ content();+ JSON.stringify(propertyValues);+ if (hasInitializedFromDraft) {+ hasInitializedFromDraft = false;+ return;+ }+ debouncedSave(snapshotDraft());+ });+ onCleanup(() => {+ // Flush the latest state so navigating away never drops keystrokes+ // that were still inside the debounce window.+ debouncedSave.clear();+ saveTaskComposerDraft(snapshotDraft(), draftStorage);+ });+ }++ const deleteTitleTagsAtStart = () => {+ if (tagLayoutMode() !== 'title') return false;+ clearComposerTags();+ setTagLayoutMode('bottom');+ return true;+ };++ const handleAttachFiles = async (event: Event) => {+ const input = event.currentTarget as HTMLInputElement;+ const files = Array.from(input.files ?? []);+ input.value = '';+ const editor = bodyEditor();+ if (!editor || files.length === 0) return;+ for (const file of files) {+ const mediaType = file.type.startsWith('video/') ? 'video' : 'image';+ await addMediaFromFile(editor, file, mediaType);+ }+ };++ const canSend = () => title().trim().length > 0 && !isCreating();++ const resetComposer = () => {+ setTitle('');+ setContent('');+ setTagLayoutMode('bottom');+ setPropertyValues(reconcile(defaultPropertyValues()));+ const editor = bodyEditor();+ editor && initializeEditorEmpty(editor);+ };++ const handleSend = async () => {+ if (!canSend()) return;+ const taskTitle = title().trim();+ const taskContent = content().trim();+ setIsCreating(true);+ const taskProperties = structuredClone(+ Object.entries(unwrap(propertyValues))+ );+ const documentId = await createTaskWithProperties(+ taskTitle,+ taskContent,+ taskProperties,+ createDefinitions(),+ (params) => upsertToHistoryMutation.mutate(params)+ );+ setIsCreating(false);+ // createTaskWithProperties surfaces its own failure toast; keep the+ // draft so the user can retry.+ if (!documentId) return;+ resetComposer();+ props.onSend({ documentId, title: taskTitle, content: taskContent });+ };++ const [attachHotkeys, composerHotkeyScope] = useHotkeyDOMScope(+ 'channel-input-task-composer',+ true+ );+ onMount(() => {+ const container = containerRef();+ if (container) attachHotkeys(container);+ });++ registerHotkey({+ hotkey: 'cmd+enter',+ scopeId: composerHotkeyScope,+ description: 'Create task and send',+ keyDownHandler: () => {+ void handleSend();+ return true;+ },+ runWithInputFocused: true,+ });++ const editorConfig = buildConfig('markdown')+ .withMentions()+ .withTags({+ applyTargetLabel: 'Task',+ isApplied: (tag) => composerTags.isApplied(tag.optionId),+ onCreate: (tag) => {+ void composerTags.applyTag(tag.scope, tag.optionId);+ },+ })+ .withEmojis()+ .withActions()+ .withCode()+ .withMedia({ fileDrop: true })+ .withSelectionData()+ .withHistory()+ .onChange(setContent)+ .onEscape(() => {+ containerRef()?.focus();+ return true;+ });++ const editor = editorConfig.buildHandle().lexical;+ setBodyEditor(editor);++ // Imperative DOM focus: entering task mode focuses the title editor. The+ // first activation is the mount itself — a restored task-mode draft — and+ // only focuses when the host's autofocus allows it.+ let isFirstActivation = true;+ createEffect(+ on(+ () => props.active,+ (active) => {+ if (!active) return;+ const shouldFocus = isFirstActivation+ ? (props.autofocus ?? true)+ : true;+ isFirstActivation = false;+ if (!shouldFocus) return;+ requestAnimationFrame(() => titleEditorRoot?.focus());+ }+ )+ );++ return (+ // Compact edges matching the message face (content at px-3/pt-2, footer+ // mirroring Input.Footer's h-8 p-2 mb-2), with roomier gap-4 spacing+ // between title, description, and property pills.+ <div+ class="relative flex flex-col"+ tabIndex={-1}+ ref={setContainerRef}+ data-input-task-composer+ >+ <div class="flex flex-col gap-4 px-3 pt-2">+ <div class="shrink-0 flex gap-2 items-center">+ <Show when={tagLayoutMode() === 'title'}>+ <InlineTagsPill+ docTags={composerTags}+ showPlaceholder+ class="shrink-0"+ />+ </Show>+ <ComposeTaskTitleEditor+ value={title}+ onChange={setTitle}+ disabled={isCreating}+ bodyEditor={bodyEditor}+ containerRef={containerRef}+ onUserInput={() => {}}+ onTagSelected={(tag) => {+ setTagLayoutMode('title');+ void composerTags.applyTag(tag.scope, tag.optionId);+ }}+ onDeleteTagsAtStart={deleteTitleTagsAtStart}+ ref={(el) => {+ titleEditorRoot = el;+ }}+ />+ </div>++ <div class="overflow-y-auto scrollbar-hidden min-h-24 max-h-[calc(30*var(--dvh,1dvh))]">+ <Scroll>+ <MarkdownShell+ config={editorConfig}+ initialState={restoredDraft?.editorState}+ initialValue={+ restoredDraft?.editorState+ ? undefined+ : restoredDraft?.content || undefined+ }+ placeholder="Add description, type @ to insert or / for commands"+ class="text-sm"+ />+ </Scroll>+ </div>++ <Suspense fallback={<div class="h-7" />}>+ <PropertiesProvider+ entityType="TASK"+ canEdit={true}+ properties={properties}+ onRefresh={() => {}}+ onPropertyAdded={() => {}}+ onPropertyDeleted={() => {}}+ saveHandler={saveHandler}+ >+ <div class="flex min-h-7 flex-row flex-wrap items-center gap-2 text-sm">+ <For each={properties()}>+ {(property) => (+ <InlinePropertyValue+ property={property}+ emptyLabel={property.displayName}+ />+ )}+ </For>+ <Show when={tagLayoutMode() === 'bottom'}>+ <InlineTagsPill docTags={composerTags} showPlaceholder />+ </Show>+ </div>+ <Modals />+ </PropertiesProvider>+ </Suspense>+ </div>++ <div class="shrink-0 flex h-8 w-full flex-row justify-between items-center p-2 mb-2 space-x-2">+ <div class="flex items-center gap-2">+ <input+ ref={(el) => {+ attachInputRef = el;+ }}+ type="file"+ class="hidden"+ multiple+ accept="image/*,video/*"+ onChange={handleAttachFiles}+ data-input-task-attach-picker+ />+ <InputActionButton+ label="Attach image or video"+ onClick={() => attachInputRef?.click()}+ >+ <PaperclipIcon />+ </InputActionButton>+ {props.modeSwitch}+ </div>+ <SendButton+ tooltip="Create task and send"+ shortcut="cmd+enter"+ aria-label="Create task and send"+ data-input-action="send-task"+ pending={isCreating()}+ disabled={!canSend()}+ onPointerDown={(event) => {+ event.preventDefault();+ void handleSend();+ }}+ />+ </div>+ </div>+ );+}diff --git a/apps/web/src/features/channel/Input/TaskModeSwitch.tsx b/apps/web/src/features/channel/Input/TaskModeSwitch.tsxnew file mode 100644index 0000000000..4ed0fc8068--- /dev/null+++ b/apps/web/src/features/channel/Input/TaskModeSwitch.tsx@@ -0,0 +1,25 @@+import { ToggleSwitch } from '@ui';++/**+ * The message/task mode switch shown in the input footer, next to the+ * format (`Aa`) button in message mode and next to the attach button in+ * task mode. Checked means the input is composing a task. Outlined as a+ * pill so the label and switch read as one control.+ */+export function TaskModeSwitch(props: {+ checked: boolean;+ onChange: (checked: boolean) => void;+}) {+ return (+ <ToggleSwitch+ checked={props.checked}+ onChange={props.onChange}+ label="Task"+ // Concentric rounding: the h-4 switch has an 8px radius, so a uniform+ // 6px ring around it needs a 14px outer radius (h-7 rounded-full) and+ // matching 6px padding on the switch side.+ class="h-7 gap-1.5 rounded-full border border-edge-muted bg-surface pl-1.5 pr-2.5 hover:bg-hover"+ labelClass="text-xs text-ink-muted font-normal whitespace-nowrap"+ />+ );+}diff --git a/apps/web/src/features/channel/Input/tests/task-mode.test.tsx b/apps/web/src/features/channel/Input/tests/task-mode.test.tsxnew file mode 100644index 0000000000..2421cd7add--- /dev/null+++ b/apps/web/src/features/channel/Input/tests/task-mode.test.tsx@@ -0,0 +1,359 @@+/**+ * @vitest-environment jsdom+ */++import { render, screen, within } from '@solidjs/testing-library';+import userEvent from '@testing-library/user-event';+import type { JSX } from 'solid-js';+import { describe, expect, it, vi } from 'vitest';++vi.hoisted(() => {+ Object.defineProperty(window, 'matchMedia', {+ writable: true,+ value: (query: string) => ({+ matches: false,+ media: query,+ onchange: null,+ addListener: () => {},+ removeListener: () => {},+ addEventListener: () => {},+ removeEventListener: () => {},+ dispatchEvent: () => true,+ }),+ });+});++vi.mock('@core/util/upload', () => ({+ chatRuleset: {},+ uploadFile: vi.fn(),+}));++// Several service clients in StaticMarkdown's import graph build websocket+// connections at module scope, which jsdom cannot do. Stub the builder so+// every module-scope socket is inert.+vi.mock('@macro-inc/collaboration/websocket', async (importOriginal) => {+ const actual = await importOriginal<object>();+ const socket = {+ addEventListener: () => {},+ removeEventListener: () => {},+ send: () => {},+ close: () => {},+ };+ const builder: object = new Proxy(+ {},+ {+ get: (_target, prop) => {+ if (typeof prop === 'symbol' || prop === 'then') return undefined;+ return prop === 'build' ? () => socket : () => builder;+ },+ }+ );+ return {+ ...actual,+ WebsocketBuilder: function WebsocketBuilder() {+ return builder;+ },+ };+});++vi.mock('@core/constant/allBlocks', () => ({+ fileTypeToBlockName: (type?: string | null) => type ?? 'unknown',+}));++vi.mock('@phosphor-icons/core/regular/paperclip.svg?component-solid', () => ({+ default: () => <span data-testid="paperclip-icon" />,+}));++vi.mock('@phosphor/text-aa.svg', () => ({+ default: () => <span data-testid="format-icon" />,+}));++vi.mock('@phosphor/trash.svg', () => ({+ default: () => <span data-testid="trash-icon" />,+}));++vi.mock('@phosphor/x.svg', () => ({+ default: () => <span data-testid="close-icon" />,+}));++vi.mock('@phosphor/arrow-up.svg', () => ({+ default: () => <span data-testid="send-icon" />,+}));++vi.mock(+ '@phosphor-icons/core/regular/paper-plane-right.svg?component-solid',+ () => ({+ default: () => <span data-testid="paper-plane-icon" />,+ })+);++vi.mock('@phosphor/spinner-gap.svg', () => ({+ default: () => <span data-testid="spinner-icon" />,+}));++vi.mock('@core/component/EntityIcon', () => ({+ EntityIcon: () => <span data-testid="entity-icon" />,+}));++vi.mock('@core/component/LexicalMarkdown/builder/MarkdownShell', () => ({+ MarkdownShell: (props: { placeholder?: string; initialValue?: string }) => (+ <div+ data-testid="markdown-shell"+ data-initial-value={props.initialValue ?? ''}+ >+ {props.placeholder}+ </div>+ ),+}));++vi.mock(+ '@core/component/LexicalMarkdown/builder/MarkdownConfigBuilder',+ () => ({+ buildConfig: () => {+ const controls = {+ clear: vi.fn(),+ focus: vi.fn(),+ };+ const lexical = {+ focus: vi.fn(),+ dispatchCommand: vi.fn(),+ getElementByKey: vi.fn(),+ getRootElement: vi.fn(),+ update: vi.fn((callback: () => void) => callback()),+ };+ const handle = {+ controls,+ lexical,+ plugins: { use: vi.fn() },+ selection: undefined,+ _internal: {},+ };+ type BuilderMock = Record<+ | 'namespace'+ | 'withMentions'+ | 'withEmojis'+ | 'withActions'+ | 'withLinks'+ | 'withHistory'+ | 'withCode'+ | 'withFilePaste'+ | 'withRestoreFocus'+ | 'withSelectionData'+ | 'withFloatingFormatMenu'+ | 'use'+ | 'onChange'+ | 'onEnter',+ () => BuilderMock+ > & {+ buildHandle: () => typeof handle;+ controls: typeof controls;+ lexical: typeof lexical;+ selection: undefined;+ };+ const builder: BuilderMock = {+ namespace: () => builder,+ withMentions: () => builder,+ withEmojis: () => builder,+ withActions: () => builder,+ withLinks: () => builder,+ withHistory: () => builder,+ withCode: () => builder,+ withFilePaste: () => builder,+ withRestoreFocus: () => builder,+ withSelectionData: () => builder,+ withFloatingFormatMenu: () => builder,+ use: () => builder,+ onChange: () => builder,+ onEnter: () => builder,+ buildHandle: () => handle,+ controls,+ lexical,+ selection: undefined,+ };+ return builder;+ },+ })+);++vi.mock('@core/component/LexicalMarkdown/plugins', () => ({+ createDragInsertStore: () => [+ { nodeKey: null, position: null, visible: false },+ vi.fn(),+ ],+ DefaultShortcuts: {},+ INSERT_DOCUMENT_MENTION_COMMAND: 'INSERT_DOCUMENT_MENTION_COMMAND',+ NODE_TRANSFORM: 'NODE_TRANSFORM',+ keyboardShortcutsPlugin: () => () => () => {},+}));++vi.mock('@core/component/LexicalMarkdown/plugins/tables/tablePlugin', () => ({+ tablePlugin: () => () => () => {},+}));++vi.mock(+ '@core/component/LexicalMarkdown/plugins/tables/tableCellResizerPlugin',+ () => ({+ tableCellResizerPlugin: () => () => () => {},+ })+);++vi.mock('../FormatButtons', () => ({+ FormatButtons: () => <div data-testid="format-buttons" />,+}));++// The real composer drags in the compose-task dialog's editor and property+// stack; these tests only exercise the mode switch wiring around it.+vi.mock('../TaskComposer', () => ({+ TaskComposer: (props: {+ active: boolean;+ onSend: (task: {+ documentId: string;+ title: string;+ content: string;+ }) => void;+ modeSwitch?: JSX.Element;+ }) => (+ <div data-testid="task-composer">+ {props.modeSwitch}+ <button+ type="button"+ data-testid="task-composer-send"+ onClick={() =>+ props.onSend({ documentId: 'task-1', title: 'A task', content: '' })+ }+ >+ send task+ </button>+ </div>+ ),+}));++import { ChannelInput } from '../ChannelInput';+import type { InputData } from '../types';++const baseInput: InputData = {+ mode: 'channel',+ id: 'input-1',+ placeholder: 'Message channel',+ value: '',+ showFormatRibbon: false,+ hasPendingAttachments: false,+ attachments: [],+};++describe('Channel input task mode', () => {+ it('omits the task mode switch when onSendTask is not provided', () => {+ render(() => <ChannelInput input={baseInput} />);++ expect(screen.queryByRole('switch', { name: 'Task' })).toBeNull();+ expect(screen.queryByTestId('task-composer')).toBeNull();+ });++ it('shows an unchecked task mode switch when onSendTask is provided', () => {+ render(() => <ChannelInput input={baseInput} onSendTask={() => {}} />);++ const modeSwitch = screen.getByRole('switch', { name: 'Task' });+ expect(modeSwitch).toHaveProperty('checked', false);+ expect(screen.queryByTestId('task-composer')).toBeNull();+ });++ it('swaps the input faces when toggling task mode on and off', async () => {+ const user = userEvent.setup();+ const { container } = render(() => (+ <ChannelInput input={baseInput} onSendTask={() => {}} />+ ));++ await user.click(screen.getByRole('switch', { name: 'Task' }));++ expect(screen.getByTestId('task-composer')).toBeTruthy();+ const messageFace = container.querySelector('[data-input-face="message"]');+ const taskFace = container.querySelector('[data-input-face="task"]');+ expect(messageFace?.classList.contains('hidden')).toBe(true);+ expect(taskFace?.classList.contains('hidden')).toBe(false);++ // The switch rendered inside the composer footer is checked; toggling it+ // returns to message mode but keeps the composer mounted for its draft.+ const composerSwitch = within(taskFace as HTMLElement).getByRole('switch', {+ name: 'Task',+ });+ expect(composerSwitch).toHaveProperty('checked', true);+ await user.click(composerSwitch);++ expect(messageFace?.classList.contains('hidden')).toBe(false);+ expect(taskFace?.classList.contains('hidden')).toBe(true);+ expect(screen.getByTestId('task-composer')).toBeTruthy();+ });++ it('enters task mode from clicks on the switch pill itself, not just the control', async () => {+ const user = userEvent.setup();+ render(() => <ChannelInput input={baseInput} onSendTask={() => {}} />);++ // The pill (Kobalte switch root) is the label's parent; clicking its+ // padding must toggle just like clicking the control or label.+ const pill = screen.getByText('Task').parentElement as HTMLElement;+ await user.click(pill);++ expect(screen.getByTestId('task-composer')).toBeTruthy();+ });++ it('restores a persisted task mode on remount', async () => {+ const user = userEvent.setup();+ const taskPersistence = {+ draftKey: 'task-composer-draft-channel:c1-persist-v0' as const,+ modeKey: 'input-task-mode-channel:c1-persist-v0' as const,+ };+ localStorage.removeItem(taskPersistence.modeKey);++ const first = render(() => (+ <ChannelInput+ input={baseInput}+ onSendTask={() => {}}+ taskPersistence={taskPersistence}+ />+ ));+ await user.click(screen.getByRole('switch', { name: 'Task' }));+ expect(+ first.container+ .querySelector('[data-input-face="task"]')+ ?.classList.contains('hidden')+ ).toBe(false);+ first.unmount();++ const second = render(() => (+ <ChannelInput+ input={baseInput}+ onSendTask={() => {}}+ taskPersistence={taskPersistence}+ />+ ));+ const taskFace = second.container.querySelector('[data-input-face="task"]');+ expect(taskFace).toBeTruthy();+ expect(taskFace?.classList.contains('hidden')).toBe(false);+ expect(+ second.container+ .querySelector('[data-input-face="message"]')+ ?.classList.contains('hidden')+ ).toBe(true);+ localStorage.removeItem(taskPersistence.modeKey);+ });++ it('forwards the created task and returns to message mode on send', async () => {+ const user = userEvent.setup();+ const onSendTask = vi.fn();+ const { container } = render(() => (+ <ChannelInput input={baseInput} onSendTask={onSendTask} />+ ));++ await user.click(screen.getByRole('switch', { name: 'Task' }));+ await user.click(screen.getByTestId('task-composer-send'));++ expect(onSendTask).toHaveBeenCalledOnce();+ expect(onSendTask.mock.calls[0]?.[0]).toEqual({+ documentId: 'task-1',+ title: 'A task',+ content: '',+ });+ const messageFace = container.querySelector('[data-input-face="message"]');+ expect(messageFace?.classList.contains('hidden')).toBe(false);+ });+});diff --git a/apps/web/src/features/channel/Input/utils/persistence.ts b/apps/web/src/features/channel/Input/utils/persistence.tsindex 081cd2b233..fa2919e229 100644--- a/apps/web/src/features/channel/Input/utils/persistence.ts+++ b/apps/web/src/features/channel/Input/utils/persistence.ts@@ -12,6 +12,10 @@ const ATTACHMENT_TRACKER_PREFIX = 'attachment-tracker';const ATTACHMENT_TRACKER_VERSION = 0;const INPUT_VALUE_PREFIX = 'input-value';const INPUT_VALUE_VERSION = 0;+const TASK_DRAFT_PREFIX = 'task-composer-draft';+const TASK_DRAFT_VERSION = 0;+const TASK_MODE_PREFIX = 'input-task-mode';+const TASK_MODE_VERSION = 0;function makeScopedPersistenceName(prefix: string, props: PersistenceProps) {return `${prefix}-channel:${props.channelId}${props.threadId ? `-thread:${props.threadId}` : ''}`;@@ -34,3 +38,26 @@ export function makeInputValuePersistenceKey(INPUT_VALUE_VERSION);}++export type InputTaskPersistence = {+ /** localStorage key for the task composer's draft blob. */+ draftKey: PersistenceKey;+ /** `makePersisted` key for the message/task mode flag. */+ modeKey: PersistenceKey;+};++/** Keys that persist a channel input's task draft and mode across visits. */+export function makeTaskPersistence(+ props: PersistenceProps+): InputTaskPersistence {+ return {+ draftKey: createPersistenceKey(+ makeScopedPersistenceName(TASK_DRAFT_PREFIX, props),+ TASK_DRAFT_VERSION+ ),+ modeKey: createPersistenceKey(+ makeScopedPersistenceName(TASK_MODE_PREFIX, props),+ TASK_MODE_VERSION+ ),+ };+}