@adminide-stack/clock-tik-mobile 0.0.0-stage → 12.0.37-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (376) hide show
  1. package/.claude-flow/data/pending-insights.jsonl +43 -0
  2. package/.claude-flow/sessions/session-1794323376548.json +14 -0
  3. package/CHANGELOG.md +31 -0
  4. package/jest.config.cjs +22 -0
  5. package/lib/assets/home/loop-day.jpg +0 -0
  6. package/lib/assets/home/loop-day.mp4 +0 -0
  7. package/lib/assets/home/loop-time-back.jpg +0 -0
  8. package/lib/assets/home/loop-time-back.mp4 +0 -0
  9. package/lib/assets/home/loop-where.jpg +0 -0
  10. package/lib/assets/home/loop-where.mp4 +0 -0
  11. package/lib/assets/home/reel-gym.jpg +0 -0
  12. package/lib/assets/home/reel-gym.mp4 +0 -0
  13. package/lib/assets/home/reel-internet.jpg +0 -0
  14. package/lib/assets/home/reel-internet.mp4 +0 -0
  15. package/lib/assets/icon.png +0 -0
  16. package/lib/assets/lottie/.claude-flow/data/pending-insights.jsonl +1 -0
  17. package/lib/assets/lottie/lucy-mark-calendar.json +1827 -0
  18. package/lib/assets/lottie/lucy-mark-call.json +1470 -0
  19. package/lib/assets/lottie/lucy-mark-connect.json +2552 -0
  20. package/lib/assets/lottie/lucy-mark-details.json +1735 -0
  21. package/lib/assets/lottie/lucy-mark-email.json +1363 -0
  22. package/lib/assets/lottie/lucy-mark-message.json +1154 -0
  23. package/lib/assets/lottie/lucy-mark-search.json +1067 -0
  24. package/lib/assets/lottie/lucy-mark-think.json +1253 -0
  25. package/lib/assets/lottie/lucy-mark-write.json +1532 -0
  26. package/lib/assets/lottie/time-back.json +16458 -0
  27. package/lib/assets/lottie/where-lucy-works-chat.json +6170 -0
  28. package/lib/assets/lottie/where-lucy-works-cloud.json +10066 -0
  29. package/lib/assets/lottie/where-lucy-works-mine-none.json +2478 -0
  30. package/lib/assets/lottie/where-lucy-works-mine-offline.json +2373 -0
  31. package/lib/assets/lottie/where-lucy-works-mine-online.json +7881 -0
  32. package/lib/assets/sounds/hours-back.m4a +0 -0
  33. package/lib/assets/sounds/meet-lucy.m4a +0 -0
  34. package/lib/assets/sounds/power-on.m4a +0 -0
  35. package/lib/assets/sounds/wind-back.m4a +0 -0
  36. package/lib/assets/sounds/youre-in.m4a +0 -0
  37. package/lib/chat/agent.js +358 -0
  38. package/lib/chat/agent.js.map +1 -0
  39. package/lib/chat/appFront.js +32 -0
  40. package/lib/chat/appFront.js.map +1 -0
  41. package/lib/chat/auth.js +370 -0
  42. package/lib/chat/auth.js.map +1 -0
  43. package/lib/chat/chores.js +360 -0
  44. package/lib/chat/chores.js.map +1 -0
  45. package/lib/chat/connectors.js +42 -0
  46. package/lib/chat/connectors.js.map +1 -0
  47. package/lib/chat/jobs.js +223 -0
  48. package/lib/chat/jobs.js.map +1 -0
  49. package/lib/chat/lucyMotion.js +6 -0
  50. package/lib/chat/lucyMotion.js.map +1 -0
  51. package/lib/chat/protocol.js +111 -0
  52. package/lib/chat/protocol.js.map +1 -0
  53. package/lib/chat/results.js +133 -0
  54. package/lib/chat/results.js.map +1 -0
  55. package/lib/chat/store.js +81 -0
  56. package/lib/chat/store.js.map +1 -0
  57. package/lib/chat/useDictation.js +168 -0
  58. package/lib/chat/useDictation.js.map +1 -0
  59. package/lib/chat/useLucyChat.js +451 -0
  60. package/lib/chat/useLucyChat.js.map +1 -0
  61. package/lib/chat/useMyComputer.js +32 -0
  62. package/lib/chat/useMyComputer.js.map +1 -0
  63. package/lib/chat/whereLucyWorks.js +52 -0
  64. package/lib/chat/whereLucyWorks.js.map +1 -0
  65. package/lib/chat/workspace.js +124 -0
  66. package/lib/chat/workspace.js.map +1 -0
  67. package/lib/components/AreaShot.js +289 -0
  68. package/lib/components/AreaShot.js.map +1 -0
  69. package/lib/components/Backdrops.js +262 -0
  70. package/lib/components/Backdrops.js.map +1 -0
  71. package/lib/components/BottomSheet.js +61 -0
  72. package/lib/components/BottomSheet.js.map +1 -0
  73. package/lib/components/ChatSheets.js +429 -0
  74. package/lib/components/ChatSheets.js.map +1 -0
  75. package/lib/components/ConnectorLogo.js +91 -0
  76. package/lib/components/ConnectorLogo.js.map +1 -0
  77. package/lib/components/CustomDrawer.js +534 -0
  78. package/lib/components/CustomDrawer.js.map +1 -0
  79. package/lib/components/IdeasPane.js +394 -0
  80. package/lib/components/IdeasPane.js.map +1 -0
  81. package/lib/components/ImessageSheet.js +261 -0
  82. package/lib/components/ImessageSheet.js.map +1 -0
  83. package/lib/components/KeyboardAvoider.js +29 -0
  84. package/lib/components/KeyboardAvoider.js.map +1 -0
  85. package/lib/components/Logo.js +81 -0
  86. package/lib/components/Logo.js.map +1 -0
  87. package/lib/components/LucyWorking.js +67 -0
  88. package/lib/components/LucyWorking.js.map +1 -0
  89. package/lib/components/Markdown.js +260 -0
  90. package/lib/components/Markdown.js.map +1 -0
  91. package/lib/components/Media.js +93 -0
  92. package/lib/components/Media.js.map +1 -0
  93. package/lib/components/MessagesAppIcon.js +23 -0
  94. package/lib/components/MessagesAppIcon.js.map +1 -0
  95. package/lib/components/MicButton.js +71 -0
  96. package/lib/components/MicButton.js.map +1 -0
  97. package/lib/components/ResultCards.js +974 -0
  98. package/lib/components/ResultCards.js.map +1 -0
  99. package/lib/components/SignInPrompt.js +148 -0
  100. package/lib/components/SignInPrompt.js.map +1 -0
  101. package/lib/components/SignedOut.js +38 -0
  102. package/lib/components/SignedOut.js.map +1 -0
  103. package/lib/components/TalkToLucyHero.js +487 -0
  104. package/lib/components/TalkToLucyHero.js.map +1 -0
  105. package/lib/components/TalkToLucySheet.js +182 -0
  106. package/lib/components/TalkToLucySheet.js.map +1 -0
  107. package/lib/components/WhereLucyWorks.js +277 -0
  108. package/lib/components/WhereLucyWorks.js.map +1 -0
  109. package/lib/components/WorkspaceSection.js +271 -0
  110. package/lib/components/WorkspaceSection.js.map +1 -0
  111. package/lib/components/YantraMark.js +13 -0
  112. package/lib/components/YantraMark.js.map +1 -0
  113. package/lib/components/drawerHeader.js +38 -0
  114. package/lib/components/drawerHeader.js.map +1 -0
  115. package/lib/components/lottieInstalled.js +6 -0
  116. package/lib/components/lottieInstalled.js.map +1 -0
  117. package/lib/components/ui.js +550 -0
  118. package/lib/components/ui.js.map +1 -0
  119. package/lib/components/useSignOut.js +7 -0
  120. package/lib/components/useSignOut.js.map +1 -0
  121. package/lib/components/viewport.js +121 -0
  122. package/lib/components/viewport.js.map +1 -0
  123. package/lib/components/voiceDial.js +10 -0
  124. package/lib/components/voiceDial.js.map +1 -0
  125. package/lib/compute.js +157 -0
  126. package/lib/compute.js.map +1 -0
  127. package/lib/config/env-config.js +21 -0
  128. package/lib/config/env-config.js.map +1 -0
  129. package/lib/config/routes.js +15 -0
  130. package/lib/config/routes.js.map +1 -0
  131. package/lib/content.js +25 -0
  132. package/lib/content.js.map +1 -0
  133. package/lib/hooks/keyboardCover.js +39 -0
  134. package/lib/hooks/keyboardCover.js.map +1 -0
  135. package/lib/hooks/useKeyboard.js +121 -0
  136. package/lib/hooks/useKeyboard.js.map +1 -0
  137. package/lib/hooks/useReducedMotion.js +13 -0
  138. package/lib/hooks/useReducedMotion.js.map +1 -0
  139. package/lib/imessage/openMessages.js +25 -0
  140. package/lib/imessage/openMessages.js.map +1 -0
  141. package/lib/imessage/platform.js +12 -0
  142. package/lib/imessage/platform.js.map +1 -0
  143. package/lib/imessage/textLink.js +262 -0
  144. package/lib/imessage/textLink.js.map +1 -0
  145. package/lib/index.js +1 -0
  146. package/lib/index.js.map +1 -0
  147. package/lib/live/card.js +28 -0
  148. package/lib/live/card.js.map +1 -0
  149. package/lib/live/liveActivity.js +144 -0
  150. package/lib/live/liveActivity.js.map +1 -0
  151. package/lib/module.js +3 -0
  152. package/lib/module.js.map +1 -0
  153. package/lib/offer/BlackFridayOffer.js +378 -0
  154. package/lib/offer/BlackFridayOffer.js.map +1 -0
  155. package/lib/offer/blackFriday.js +78 -0
  156. package/lib/offer/blackFriday.js.map +1 -0
  157. package/lib/offer/parts.js +624 -0
  158. package/lib/offer/parts.js.map +1 -0
  159. package/lib/offer/state.js +63 -0
  160. package/lib/offer/state.js.map +1 -0
  161. package/lib/push/push.js +142 -0
  162. package/lib/push/push.js.map +1 -0
  163. package/lib/push/usePushNotifications.js +39 -0
  164. package/lib/push/usePushNotifications.js.map +1 -0
  165. package/lib/routes.json +175 -0
  166. package/lib/screens/Account/index.js +209 -0
  167. package/lib/screens/Account/index.js.map +1 -0
  168. package/lib/screens/Chat/index.js +710 -0
  169. package/lib/screens/Chat/index.js.map +1 -0
  170. package/lib/screens/Chores/index.js +18 -0
  171. package/lib/screens/Chores/index.js.map +1 -0
  172. package/lib/screens/Connectors/index.js +17 -0
  173. package/lib/screens/Connectors/index.js.map +1 -0
  174. package/lib/screens/History/index.js +380 -0
  175. package/lib/screens/History/index.js.map +1 -0
  176. package/lib/screens/Home/index.js +2711 -0
  177. package/lib/screens/Home/index.js.map +1 -0
  178. package/lib/screens/Home/media.js +25 -0
  179. package/lib/screens/Home/media.js.map +1 -0
  180. package/lib/screens/Welcome/index.js +1066 -0
  181. package/lib/screens/Welcome/index.js.map +1 -0
  182. package/lib/talk/talkToLucy.js +139 -0
  183. package/lib/talk/talkToLucy.js.map +1 -0
  184. package/lib/theme/colors.js +29 -0
  185. package/lib/theme/colors.js.map +1 -0
  186. package/lib/theme/fonts.js +17 -0
  187. package/lib/theme/fonts.js.map +1 -0
  188. package/lib/theme/muse.js +134 -0
  189. package/lib/theme/muse.js.map +1 -0
  190. package/lib/utils/links.js +54 -0
  191. package/lib/utils/links.js.map +1 -0
  192. package/lib/utils/yantraLinks.js +68 -0
  193. package/lib/utils/yantraLinks.js.map +1 -0
  194. package/lib/welcome/flow.js +375 -0
  195. package/lib/welcome/flow.js.map +1 -0
  196. package/lib/welcome/haptics.js +125 -0
  197. package/lib/welcome/haptics.js.map +1 -0
  198. package/lib/welcome/parts.js +1996 -0
  199. package/lib/welcome/parts.js.map +1 -0
  200. package/lib/welcome/powerOn.js +29 -0
  201. package/lib/welcome/powerOn.js.map +1 -0
  202. package/lib/welcome/seen.js +41 -0
  203. package/lib/welcome/seen.js.map +1 -0
  204. package/lib/welcome/sound.js +110 -0
  205. package/lib/welcome/sound.js.map +1 -0
  206. package/package.json +66 -5
  207. package/rollup.config.mjs +42 -0
  208. package/src/.claude-flow/data/pending-insights.jsonl +19 -0
  209. package/src/.claude-flow/sessions/session-1795013028422.json +14 -0
  210. package/src/__tests__/auth.test.ts +94 -0
  211. package/src/__tests__/blackFriday.test.ts +75 -0
  212. package/src/__tests__/cardTokens.test.ts +77 -0
  213. package/src/__tests__/chores.test.ts +179 -0
  214. package/src/__tests__/choresList.test.ts +100 -0
  215. package/src/__tests__/content.test.ts +54 -0
  216. package/src/__tests__/dictation.test.ts +186 -0
  217. package/src/__tests__/haptics.test.ts +202 -0
  218. package/src/__tests__/jobs.test.ts +130 -0
  219. package/src/__tests__/keyboardCover.test.ts +84 -0
  220. package/src/__tests__/liveCard.test.ts +39 -0
  221. package/src/__tests__/lockedPhone.test.ts +355 -0
  222. package/src/__tests__/lucyMotion.test.ts +34 -0
  223. package/src/__tests__/platform.test.ts +32 -0
  224. package/src/__tests__/powerOn.test.ts +62 -0
  225. package/src/__tests__/protocol.test.ts +125 -0
  226. package/src/__tests__/push.test.ts +111 -0
  227. package/src/__tests__/results.test.ts +256 -0
  228. package/src/__tests__/sound.test.ts +248 -0
  229. package/src/__tests__/talkToLucy.test.ts +205 -0
  230. package/src/__tests__/textLink.test.ts +91 -0
  231. package/src/__tests__/voiceDial.test.ts +53 -0
  232. package/src/__tests__/welcomeFlow.test.ts +157 -0
  233. package/src/__tests__/whereLucyWorks.test.ts +81 -0
  234. package/src/__tests__/yantraLinks.test.ts +96 -0
  235. package/src/assets/home/loop-day.jpg +0 -0
  236. package/src/assets/home/loop-day.mp4 +0 -0
  237. package/src/assets/home/loop-time-back.jpg +0 -0
  238. package/src/assets/home/loop-time-back.mp4 +0 -0
  239. package/src/assets/home/loop-where.jpg +0 -0
  240. package/src/assets/home/loop-where.mp4 +0 -0
  241. package/src/assets/home/reel-gym.jpg +0 -0
  242. package/src/assets/home/reel-gym.mp4 +0 -0
  243. package/src/assets/home/reel-internet.jpg +0 -0
  244. package/src/assets/home/reel-internet.mp4 +0 -0
  245. package/src/assets/icon.png +0 -0
  246. package/src/assets/lottie/.claude-flow/data/pending-insights.jsonl +1 -0
  247. package/src/assets/lottie/lucy-mark-calendar.json +1827 -0
  248. package/src/assets/lottie/lucy-mark-call.json +1470 -0
  249. package/src/assets/lottie/lucy-mark-connect.json +2552 -0
  250. package/src/assets/lottie/lucy-mark-details.json +1735 -0
  251. package/src/assets/lottie/lucy-mark-email.json +1363 -0
  252. package/src/assets/lottie/lucy-mark-message.json +1154 -0
  253. package/src/assets/lottie/lucy-mark-search.json +1067 -0
  254. package/src/assets/lottie/lucy-mark-think.json +1253 -0
  255. package/src/assets/lottie/lucy-mark-write.json +1532 -0
  256. package/src/assets/lottie/time-back.json +16458 -0
  257. package/src/assets/lottie/where-lucy-works-chat.json +6170 -0
  258. package/src/assets/lottie/where-lucy-works-cloud.json +10066 -0
  259. package/src/assets/lottie/where-lucy-works-mine-none.json +2478 -0
  260. package/src/assets/lottie/where-lucy-works-mine-offline.json +2373 -0
  261. package/src/assets/lottie/where-lucy-works-mine-online.json +7881 -0
  262. package/src/assets/sounds/hours-back.m4a +0 -0
  263. package/src/assets/sounds/meet-lucy.m4a +0 -0
  264. package/src/assets/sounds/power-on.m4a +0 -0
  265. package/src/assets/sounds/wind-back.m4a +0 -0
  266. package/src/assets/sounds/youre-in.m4a +0 -0
  267. package/src/chat/.claude-flow/data/pending-insights.jsonl +1 -0
  268. package/src/chat/agent.ts +376 -0
  269. package/src/chat/appFront.ts +39 -0
  270. package/src/chat/auth.ts +433 -0
  271. package/src/chat/chores.ts +394 -0
  272. package/src/chat/connectors.ts +65 -0
  273. package/src/chat/jobs.ts +228 -0
  274. package/src/chat/lucyMotion.ts +33 -0
  275. package/src/chat/protocol.ts +192 -0
  276. package/src/chat/results.ts +224 -0
  277. package/src/chat/store.ts +87 -0
  278. package/src/chat/useDictation.ts +201 -0
  279. package/src/chat/useLucyChat.ts +458 -0
  280. package/src/chat/useMyComputer.ts +41 -0
  281. package/src/chat/whereLucyWorks.ts +97 -0
  282. package/src/chat/workspace.ts +127 -0
  283. package/src/components/.claude-flow/data/pending-insights.jsonl +3 -0
  284. package/src/components/AreaShot.tsx +239 -0
  285. package/src/components/Backdrops.tsx +323 -0
  286. package/src/components/BottomSheet.tsx +96 -0
  287. package/src/components/ChatSheets.tsx +565 -0
  288. package/src/components/ConnectorLogo.tsx +116 -0
  289. package/src/components/CustomDrawer.tsx +526 -0
  290. package/src/components/IdeasPane.tsx +318 -0
  291. package/src/components/ImessageSheet.tsx +280 -0
  292. package/src/components/KeyboardAvoider.tsx +45 -0
  293. package/src/components/Logo.tsx +97 -0
  294. package/src/components/LucyWorking.tsx +122 -0
  295. package/src/components/Markdown.tsx +219 -0
  296. package/src/components/Media.tsx +173 -0
  297. package/src/components/MessagesAppIcon.tsx +51 -0
  298. package/src/components/MicButton.tsx +92 -0
  299. package/src/components/ResultCards.tsx +1067 -0
  300. package/src/components/SignInPrompt.tsx +182 -0
  301. package/src/components/SignedOut.tsx +47 -0
  302. package/src/components/TalkToLucyHero.tsx +540 -0
  303. package/src/components/TalkToLucySheet.tsx +208 -0
  304. package/src/components/VoiceOrb.tsx +364 -0
  305. package/src/components/WhereLucyWorks.tsx +261 -0
  306. package/src/components/WorkspaceSection.tsx +307 -0
  307. package/src/components/YantraMark.tsx +30 -0
  308. package/src/components/drawerHeader.tsx +46 -0
  309. package/src/components/kit.tsx +309 -0
  310. package/src/components/lottieInstalled.ts +7 -0
  311. package/src/components/ui.tsx +700 -0
  312. package/src/components/useSignOut.ts +21 -0
  313. package/src/components/viewport.tsx +166 -0
  314. package/src/components/voiceDial.ts +45 -0
  315. package/src/compute.ts +168 -0
  316. package/src/config/env-config.ts +37 -0
  317. package/src/config/routes.ts +28 -0
  318. package/src/content.ts +217 -0
  319. package/src/hooks/keyboardCover.ts +70 -0
  320. package/src/hooks/useKeyboard.ts +135 -0
  321. package/src/hooks/useReducedMotion.ts +19 -0
  322. package/src/imessage/openMessages.ts +53 -0
  323. package/src/imessage/platform.ts +32 -0
  324. package/src/imessage/textLink.ts +307 -0
  325. package/src/index.ts +24 -0
  326. package/src/live/card.ts +62 -0
  327. package/src/live/liveActivity.ts +192 -0
  328. package/src/module.ts +8 -0
  329. package/src/offer/BlackFridayOffer.tsx +394 -0
  330. package/src/offer/blackFriday.ts +109 -0
  331. package/src/offer/parts.tsx +650 -0
  332. package/src/offer/state.ts +78 -0
  333. package/src/push/push.ts +171 -0
  334. package/src/push/usePushNotifications.ts +47 -0
  335. package/src/screens/Account/index.tsx +310 -0
  336. package/src/screens/Chat/.claude-flow/data/pending-insights.jsonl +4 -0
  337. package/src/screens/Chat/index.tsx +891 -0
  338. package/src/screens/Chores/index.tsx +35 -0
  339. package/src/screens/Connectors/index.tsx +35 -0
  340. package/src/screens/History/index.tsx +346 -0
  341. package/src/screens/Home/index.tsx +2773 -0
  342. package/src/screens/Home/media.ts +31 -0
  343. package/src/screens/Welcome/index.tsx +1182 -0
  344. package/src/talk/talkToLucy.ts +187 -0
  345. package/src/theme/colors.ts +38 -0
  346. package/src/theme/fonts.ts +30 -0
  347. package/src/theme/muse.ts +86 -0
  348. package/src/utils/links.ts +84 -0
  349. package/src/utils/yantraLinks.ts +94 -0
  350. package/src/welcome/flow.ts +418 -0
  351. package/src/welcome/haptics.ts +179 -0
  352. package/src/welcome/parts.tsx +2160 -0
  353. package/src/welcome/powerOn.ts +84 -0
  354. package/src/welcome/seen.ts +68 -0
  355. package/src/welcome/sound.ts +173 -0
  356. package/tools/lottie/chat.motion +0 -0
  357. package/tools/lottie/cloud.motion +0 -0
  358. package/tools/lottie/generate.mjs +1209 -0
  359. package/tools/lottie/inter-glyphs.json +4416 -0
  360. package/tools/lottie/lucy-mark-calendar.motion +0 -0
  361. package/tools/lottie/lucy-mark-call.motion +0 -0
  362. package/tools/lottie/lucy-mark-connect.motion +0 -0
  363. package/tools/lottie/lucy-mark-details.motion +0 -0
  364. package/tools/lottie/lucy-mark-email.motion +0 -0
  365. package/tools/lottie/lucy-mark-message.motion +0 -0
  366. package/tools/lottie/lucy-mark-search.motion +0 -0
  367. package/tools/lottie/lucy-mark-think.motion +0 -0
  368. package/tools/lottie/lucy-mark-write.motion +0 -0
  369. package/tools/lottie/mark.json +1 -0
  370. package/tools/lottie/mine-none.motion +0 -0
  371. package/tools/lottie/mine-offline.motion +0 -0
  372. package/tools/lottie/mine-online.motion +0 -0
  373. package/tools/lottie/time-back.mjs +604 -0
  374. package/tools/sounds/render.mjs +730 -0
  375. package/tsconfig.json +17 -0
  376. package/README.md +0 -3
@@ -0,0 +1,394 @@
1
+ /**
2
+ * Lucy's chores, as the web chat's Chores panel lists them (browser src/pages/Home/chat/chores.ts, ChoresPanel.tsx):
3
+ * the records the agent keeps on Yantra's Task API for the Clockbook surface (`getSurfaceJobs(surface: "clockbook")`),
4
+ * read with the person's agent token (chat/auth.ts). The same records show in the web chat and in the Yantra app's
5
+ * Tasks panel, so a chore handed to Lucy anywhere is listed here.
6
+ *
7
+ * Read-only: the phone lists what Lucy is on and what she finished; the web page keeps the records.
8
+ */
9
+ import AsyncStorage from '@react-native-async-storage/async-storage';
10
+ import { accountKey, agentBackendUrl, getChatToken } from './auth';
11
+
12
+ export const CLOCKBOOK_SURFACE = 'clockbook';
13
+ /** Finished chores listed, newest first, and for how long after they finished (chores.ts DONE_SHOWN / DONE_FOR_MS). */
14
+ const DONE_SHOWN = 8;
15
+ const DONE_FOR_MS = 7 * 24 * 60 * 60_000;
16
+ /** A chore done this fast was a quick answer the person watched arrive: the list is better without it. */
17
+ const QUICK_ANSWER_MS = 20_000;
18
+ /** A record from before deadlines existed may read as running for a day (remoteRecord LEGACY_JOB_DEADLINE_MS). */
19
+ const LEGACY_DEADLINE_MS = 24 * 60 * 60_000;
20
+ const LIST_LIMIT = 50;
21
+
22
+ const ROW = 'id title description status createdAt updatedAt source { type id details }';
23
+ const LIST_OWN = `query SurfaceJobsOwn($surface: String, $limit: Int) {
24
+ getSurfaceJobs(surface: $surface, limit: $limit) { ${ROW} }
25
+ }`;
26
+
27
+ export type ChoreStatus = 'asking' | 'working' | 'done' | 'failed';
28
+
29
+ export interface Chore {
30
+ /** The chore's id, shared by its turns (the record's `handle.boardId`, else its own id). */
31
+ id: string;
32
+ title: string;
33
+ status: ChoreStatus;
34
+ startedAt: number;
35
+ endedAt?: number;
36
+ /** What Lucy says she is doing, while it runs; what came back, once done. */
37
+ line?: string;
38
+ }
39
+
40
+ export interface ChoreList {
41
+ /** Lucy asked something in the chat and waits for the answer (the web's "Needs your answer"). */
42
+ asking: Chore[];
43
+ working: Chore[];
44
+ failed: Chore[];
45
+ done: Chore[];
46
+ /** Every chore the groups came from: grouped again as the chat's live state changes (liveChores). */
47
+ all?: Chore[];
48
+ }
49
+
50
+ interface TaskRow {
51
+ id?: string | null;
52
+ title?: string | null;
53
+ description?: string | null;
54
+ status?: string | null;
55
+ createdAt?: string | null;
56
+ source?: { details?: unknown } | null;
57
+ }
58
+
59
+ const str = (v: unknown) => (typeof v === 'string' && v.trim() ? v.trim() : undefined);
60
+ const num = (v: unknown) => (typeof v === 'number' && Number.isFinite(v) ? v : undefined);
61
+
62
+ /** Job state for a server task status (remoteRecord jobStateFor): anything not running or completed failed. */
63
+ function stateFor(status: string | null | undefined): 'running' | 'succeeded' | 'failed' {
64
+ if (status === 'COMPLETED') return 'succeeded';
65
+ if (status === 'IN_PROGRESS' || status === 'NOT_STARTED') return 'running';
66
+ return 'failed';
67
+ }
68
+
69
+ function oneLine(text: string | undefined, max = 160): string | undefined {
70
+ if (!text) return undefined;
71
+ const flat = text.replace(/\s+/g, ' ').trim();
72
+ return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat;
73
+ }
74
+
75
+ /** One record as a chore; null for anything that is not a Clockbook surface job (remoteRecord jobFromTaskRow). */
76
+ export function choreFromRow(row: TaskRow, now = Date.now()): Chore | null {
77
+ const d = row.source?.details as Record<string, unknown> | undefined;
78
+ // The surface-job marker, or (a record the server wrote without it) a Clockbook chore lane.
79
+ if (!d || typeof d !== 'object' || str(d.surface) !== CLOCKBOOK_SURFACE) return null;
80
+ if (d.kind !== 'surface-job' && str(d.lane) !== 'chore') return null;
81
+ const own = str(d.id) ?? str(row.id);
82
+ if (!own) return null;
83
+ const id = str((d.handle as { boardId?: unknown } | undefined)?.boardId) ?? own;
84
+ const state = row.status ? stateFor(row.status) : (str(d.state) as 'running' | 'succeeded' | 'failed') || 'running';
85
+ const startedAt = num(d.createdAt) ?? (row.createdAt ? Date.parse(row.createdAt) : 0);
86
+ const endedAt = num(d.endedAt);
87
+ const deadline = num(d.deadlineAt) ?? startedAt + LEGACY_DEADLINE_MS;
88
+ const result = d.result as { text?: unknown } | undefined;
89
+ const stage = d.stage as { label?: unknown; detail?: unknown } | undefined;
90
+ const reply = str(result?.text);
91
+ const progress = str(stage?.detail) ?? str(stage?.label) ?? str(d.progress);
92
+ const stale = state === 'running' && now > deadline;
93
+ const status: ChoreStatus = state === 'succeeded' ? 'done' : state === 'running' && !stale ? 'working' : 'failed';
94
+ return {
95
+ id,
96
+ title: str(d.title) ?? str(row.title) ?? 'Chore',
97
+ status,
98
+ startedAt: Number.isFinite(startedAt) ? startedAt : 0,
99
+ ...(endedAt ? { endedAt } : {}),
100
+ ...(status === 'working'
101
+ ? progress
102
+ ? { line: oneLine(progress) }
103
+ : {}
104
+ : status === 'failed'
105
+ ? { line: oneLine(str(d.error) ?? (stale ? 'Stopped responding' : undefined)) }
106
+ : reply
107
+ ? { line: oneLine(reply) }
108
+ : {}),
109
+ };
110
+ }
111
+
112
+ /* What the chat on this phone knows before the record does: what Lucy is doing right now, and which chore's reply
113
+ holds a question still waiting for its answer. Kept in memory, and told to the Chores list as it changes. */
114
+ const liveProgress = new Map<string, string>();
115
+ let askingId: string | null = null;
116
+ const liveListeners = new Set<() => void>();
117
+ const liveChanged = () => liveListeners.forEach((l) => l());
118
+
119
+ /** What Lucy says she is doing on a chore ("Searching…"), while its reply streams here; null once it ends. */
120
+ export function setChoreProgress(remoteId: string, progress: string | null): void {
121
+ const was = liveProgress.get(remoteId) ?? null;
122
+ if (was === progress) return;
123
+ if (progress) liveProgress.set(remoteId, progress);
124
+ else liveProgress.delete(remoteId);
125
+ liveChanged();
126
+ }
127
+
128
+ /** The chore whose reply asks a question still waiting for an answer, or null. */
129
+ export function setAskingChore(remoteId: string | null): void {
130
+ if (askingId === remoteId) return;
131
+ askingId = remoteId;
132
+ liveChanged();
133
+ }
134
+
135
+ export function onChoreLiveChanged(listener: () => void): () => void {
136
+ liveListeners.add(listener);
137
+ return () => liveListeners.delete(listener);
138
+ }
139
+
140
+ /** The panel's groups: a question waiting first, then under way, then what didn't finish, then the recent finished ones. */
141
+ export function groupChores(chores: readonly Chore[], now = Date.now()): ChoreList {
142
+ const byNewest = (a: Chore, b: Chore) => (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt);
143
+ const recent = (c: Chore) => now - (c.endedAt ?? c.startedAt) <= DONE_FOR_MS;
144
+ const merged = mergeTurns(chores);
145
+ const asking = merged.filter((c) => c.id === askingId).map((c): Chore => ({ ...c, status: 'asking' }));
146
+ const rest = merged
147
+ .filter((c) => c.id !== askingId)
148
+ .map((c) => {
149
+ const live = c.status === 'working' ? liveProgress.get(c.id) : undefined;
150
+ return live ? { ...c, line: live } : c;
151
+ });
152
+ return {
153
+ asking,
154
+ working: rest.filter((c) => c.status === 'working').sort((a, b) => b.startedAt - a.startedAt),
155
+ failed: rest
156
+ .filter((c) => c.status === 'failed' && recent(c))
157
+ .sort(byNewest)
158
+ .slice(0, DONE_SHOWN),
159
+ done: rest
160
+ .filter(
161
+ (c) =>
162
+ c.status === 'done' &&
163
+ recent(c) &&
164
+ (c.endedAt === undefined || c.endedAt - c.startedAt >= QUICK_ANSWER_MS),
165
+ )
166
+ .sort(byNewest)
167
+ .slice(0, DONE_SHOWN),
168
+ all: [...chores],
169
+ };
170
+ }
171
+
172
+ /**
173
+ * A chore's turns as one chore (the web's choreList): named by its first turn, under way while any turn is, else
174
+ * ended as its last turn to end did.
175
+ */
176
+ function mergeTurns(turns: readonly Chore[]): Chore[] {
177
+ const boards = new Map<string, Chore[]>();
178
+ for (const t of turns) boards.set(t.id, [...(boards.get(t.id) ?? []), t]);
179
+ return [...boards.values()].map((group) => {
180
+ if (group.length === 1) return group[0];
181
+ const byStart = [...group].sort((a, b) => a.startedAt - b.startedAt);
182
+ const running = byStart.filter((t) => t.status === 'working');
183
+ if (running.length) {
184
+ const latest = running[running.length - 1];
185
+ return { ...byStart[0], status: 'working', ...(latest.line ? { line: latest.line } : {}) };
186
+ }
187
+ const last = [...group].sort((a, b) => (a.endedAt ?? a.startedAt) - (b.endedAt ?? b.startedAt)).pop() as Chore;
188
+ const { line, ...head } = byStart[0];
189
+ return {
190
+ ...head,
191
+ status: last.status,
192
+ ...(last.endedAt ? { endedAt: last.endedAt } : {}),
193
+ ...(last.line ? { line: last.line } : {}),
194
+ };
195
+ });
196
+ }
197
+
198
+ /** A list grouped again with what the chat knows now (a list saved by an older version has no `all`: kept as is). */
199
+ export function liveChores(list: ChoreList): ChoreList {
200
+ return list.all ? groupChores(list.all) : { ...list, asking: list.asking ?? [] };
201
+ }
202
+
203
+ const READ_ONE = `query SurfaceJobOne($id: ID!) {
204
+ getSurfaceJob(id: $id) { ${ROW} }
205
+ }`;
206
+
207
+ /** The chores this phone asked for, kept per account: read by id, since the listing can miss them (see fetchChores). */
208
+ const KNOWN_KEY = (account: string) => `clockbook.chores.ids:v1:${account}`;
209
+ const KNOWN_MAX = 40;
210
+
211
+ async function knownChoreIds(account: string): Promise<string[]> {
212
+ const raw = await AsyncStorage.getItem(KNOWN_KEY(account)).catch(() => null);
213
+ try {
214
+ const ids = raw ? (JSON.parse(raw) as unknown) : [];
215
+ return Array.isArray(ids) ? ids.filter((x): x is string => typeof x === 'string') : [];
216
+ } catch {
217
+ return [];
218
+ }
219
+ }
220
+
221
+ /** How this phone saw each of its chores end, by server id: the server can read "running" after the turn ended here. */
222
+ const VERDICTS_KEY = (account: string) => `clockbook.chores.verdicts:v1:${account}`;
223
+ type Verdict = { state: 'succeeded' | 'failed'; endedAt: number; error?: string };
224
+
225
+ async function localVerdicts(account: string): Promise<Record<string, Verdict>> {
226
+ const raw = await AsyncStorage.getItem(VERDICTS_KEY(account)).catch(() => null);
227
+ try {
228
+ const v = raw ? (JSON.parse(raw) as unknown) : {};
229
+ return v && typeof v === 'object' ? (v as Record<string, Verdict>) : {};
230
+ } catch {
231
+ return {};
232
+ }
233
+ }
234
+
235
+ /** Note how a chore ended here; the list shows it so while the server still reads it running. */
236
+ export async function noteChoreVerdict(
237
+ remoteId: string,
238
+ verdict: Verdict,
239
+ { ifMissing = false }: { ifMissing?: boolean } = {},
240
+ ): Promise<void> {
241
+ const account = accountKey(await getChatToken());
242
+ const all = await localVerdicts(account);
243
+ if (ifMissing && all[remoteId]) return;
244
+ all[remoteId] = verdict;
245
+ // Bounded: only the chores this phone still remembers.
246
+ const keep = new Set(await knownChoreIds(account));
247
+ for (const id of Object.keys(all)) if (!keep.has(id) && id !== remoteId) delete all[id];
248
+ await AsyncStorage.setItem(VERDICTS_KEY(account), JSON.stringify(all)).catch(() => undefined);
249
+ choresChanged();
250
+ }
251
+
252
+ type Listener = () => void;
253
+ const listeners = new Set<Listener>();
254
+ /** Told when a chore starts or ends here, so the Chores list and its count read again at once. */
255
+ export function onChoresChanged(listener: Listener): () => void {
256
+ listeners.add(listener);
257
+ return () => listeners.delete(listener);
258
+ }
259
+ export function choresChanged(): void {
260
+ listeners.forEach((l) => l());
261
+ }
262
+
263
+ /** Remember a chore this phone recorded (its server id), so the Chores list can read it back. */
264
+ export async function rememberChore(remoteId: string): Promise<void> {
265
+ const account = accountKey(await getChatToken());
266
+ const ids = await knownChoreIds(account);
267
+ const next = [remoteId, ...ids.filter((x) => x !== remoteId)].slice(0, KNOWN_MAX);
268
+ await AsyncStorage.setItem(KNOWN_KEY(account), JSON.stringify(next)).catch(() => undefined);
269
+ choresChanged();
270
+ }
271
+
272
+ /**
273
+ * This account's Clockbook chores. Throws when Lucy can't be reached or the sign-in is refused.
274
+ *
275
+ * Two sources, merged by id: the backend's listing (`getSurfaceJobs`), and the chores this phone recorded, each read by
276
+ * its id (`getSurfaceJob`). The listing returned nothing for chores recorded from the app (the record itself reads back
277
+ * fine by id), so the app does not depend on it alone.
278
+ */
279
+ /** Settled chores never change: kept here (and on the phone) so they are not read again. */
280
+ const ROWS_KEY = (account: string) => `clockbook.chores.rows:v1:${account}`;
281
+ const settledRow = (r: TaskRow) => r.status === 'COMPLETED' || r.status === 'BLOCKED';
282
+
283
+ async function savedRows(account: string): Promise<Record<string, TaskRow>> {
284
+ const raw = await AsyncStorage.getItem(ROWS_KEY(account)).catch(() => null);
285
+ try {
286
+ const v = raw ? (JSON.parse(raw) as unknown) : {};
287
+ return v && typeof v === 'object' ? (v as Record<string, TaskRow>) : {};
288
+ } catch {
289
+ return {};
290
+ }
291
+ }
292
+
293
+ /** The last list this phone showed, so the Chores screen opens on it while it reads again. */
294
+ let lastList: ChoreList | null = null;
295
+ export function cachedChores(): ChoreList | null {
296
+ return lastList;
297
+ }
298
+
299
+ function toList(rows: TaskRow[], verdicts: Record<string, Verdict>): ChoreList {
300
+ // What ended here wins over a record still reading "running" (the agent's own verdict, once in, is the same).
301
+ const settled = rows.map((r) => {
302
+ const v = r.id ? verdicts[r.id] : undefined;
303
+ if (!v || (r.status !== 'IN_PROGRESS' && r.status !== 'NOT_STARTED')) return r;
304
+ const d = (r.source?.details ?? {}) as Record<string, unknown>;
305
+ return {
306
+ ...r,
307
+ status: v.state === 'succeeded' ? 'COMPLETED' : 'BLOCKED',
308
+ source: { ...r.source, details: { ...d, endedAt: v.endedAt, ...(v.error ? { error: v.error } : {}) } },
309
+ };
310
+ });
311
+ const now = Date.now();
312
+ return groupChores(settled.map((r) => choreFromRow(r, now)).filter(Boolean) as Chore[], now);
313
+ }
314
+
315
+ export async function fetchChores(signal?: AbortSignal): Promise<ChoreList> {
316
+ const [url, firstToken] = await Promise.all([agentBackendUrl(), getChatToken()]);
317
+ let token = firstToken;
318
+ const ask = (query: string, variables: Record<string, unknown>) =>
319
+ fetch(url, {
320
+ method: 'POST',
321
+ headers: { 'content-type': 'application/json', Authorization: `Bearer ${token}` },
322
+ body: JSON.stringify({ query, variables }),
323
+ signal,
324
+ });
325
+ const account = accountKey(token);
326
+ const [known, saved, verdicts] = await Promise.all([
327
+ knownChoreIds(account),
328
+ savedRows(account),
329
+ localVerdicts(account),
330
+ ]);
331
+
332
+ // Only what can still change is asked about: a chore settled on its record, or ended here, is read from the phone.
333
+ const toRead = known.filter((id) => !(saved[id] && (settledRow(saved[id]) || verdicts[id])));
334
+ const listing = (async () => {
335
+ let res = await ask(LIST_OWN, { surface: CLOCKBOOK_SURFACE, limit: LIST_LIMIT });
336
+ if (res.status === 401) {
337
+ token = await getChatToken({ fresh: true });
338
+ res = await ask(LIST_OWN, { surface: CLOCKBOOK_SURFACE, limit: LIST_LIMIT });
339
+ }
340
+ const json = (await res.json().catch(() => null)) as {
341
+ data?: { getSurfaceJobs?: TaskRow[] | null };
342
+ errors?: { message?: string }[];
343
+ } | null;
344
+ if (json?.errors?.length) throw new Error(json.errors[0]?.message || 'Lucy could not list the chores');
345
+ if (!res.ok) throw new Error(`Lucy answered ${res.status}`);
346
+ return json?.data?.getSurfaceJobs ?? [];
347
+ })();
348
+ const gone: string[] = [];
349
+ const reads = Promise.all(
350
+ toRead.map(async (id) => {
351
+ const one = await ask(READ_ONE, { id })
352
+ .then((r) => r.json() as Promise<{ data?: { getSurfaceJob?: TaskRow | null } }>)
353
+ .catch(() => null);
354
+ if (one === null) return saved[id] ?? null; // could not ask: what the phone had
355
+ const row = one.data?.getSurfaceJob ?? null;
356
+ if (!row) gone.push(id);
357
+ return row;
358
+ }),
359
+ );
360
+ const [listed, read] = await Promise.all([listing, reads]);
361
+
362
+ // Merge by server id: the listing, then each known chore's freshest copy (read now, or kept on the phone).
363
+ const byId = new Map<string, TaskRow>();
364
+ for (const id of known) if (saved[id] && !gone.includes(id)) byId.set(id, saved[id]);
365
+ for (const row of read) if (row?.id) byId.set(row.id, row);
366
+ for (const row of listed) if (row?.id) byId.set(row.id, row);
367
+ const rows = [...byId.values()];
368
+
369
+ // Keep what was read for next time, and forget what the server no longer has.
370
+ const keepRows: Record<string, TaskRow> = {};
371
+ for (const id of known) if (byId.has(id)) keepRows[id] = byId.get(id) as TaskRow;
372
+ AsyncStorage.setItem(ROWS_KEY(account), JSON.stringify(keepRows)).catch(() => undefined);
373
+ if (gone.length) {
374
+ AsyncStorage.setItem(KNOWN_KEY(account), JSON.stringify(known.filter((id) => !gone.includes(id)))).catch(
375
+ () => undefined,
376
+ );
377
+ }
378
+
379
+ lastList = toList(rows, verdicts);
380
+ return lastList;
381
+ }
382
+
383
+ /** The list from what the phone already has (no network): what the Chores screen shows the moment it opens. */
384
+ export async function savedChores(): Promise<ChoreList | null> {
385
+ if (lastList) return lastList;
386
+ const account = accountKey(await getChatToken());
387
+ const [known, saved, verdicts] = await Promise.all([
388
+ knownChoreIds(account),
389
+ savedRows(account),
390
+ localVerdicts(account),
391
+ ]);
392
+ const rows = known.map((id) => saved[id]).filter(Boolean) as TaskRow[];
393
+ return rows.length ? toList(rows, verdicts) : null;
394
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * What Lucy can use once it is connected, as the web chat lists it (browser src/pages/Home/chat/connectors.ts; keep
3
+ * the two in step), and where each one is connected.
4
+ *
5
+ * Clockbook connects nothing itself: the connection is the person's Yantra account's (Clockbook runs on Yantra), so
6
+ * Connect opens the Yantra app's public `/connect/<connector>` page, which signs them in when needed and opens the
7
+ * connector's form. Once saved, Lucy can use it here and everywhere else on Yantra.
8
+ */
9
+ export type ConnectorGroup = 'apps' | 'saved';
10
+
11
+ export interface LucyConnector {
12
+ id: string;
13
+ name: string;
14
+ does: string;
15
+ group: ConnectorGroup;
16
+ }
17
+
18
+ export const LUCY_CONNECTORS: readonly LucyConnector[] = [
19
+ {
20
+ id: 'google-calendar',
21
+ name: 'Google Calendar',
22
+ does: 'Books calls and appointments when you’re free.',
23
+ group: 'apps',
24
+ },
25
+ { id: 'google-gmail', name: 'Gmail', does: 'Finds bills, receipts and confirmation numbers.', group: 'apps' },
26
+ {
27
+ id: 'site-login',
28
+ name: 'Website logins',
29
+ does: 'Signs in to your accounts to cancel or change a plan.',
30
+ group: 'saved',
31
+ },
32
+ {
33
+ id: 'autofill-address',
34
+ name: 'Your address',
35
+ does: 'Fills it in on forms, bookings and deliveries.',
36
+ group: 'saved',
37
+ },
38
+ { id: 'autofill-payment-card', name: 'Payment card', does: 'Pays only after you say yes.', group: 'saved' },
39
+ ];
40
+
41
+ export const CONNECTOR_GROUPS: ReadonlyArray<readonly [ConnectorGroup, string]> = [
42
+ ['apps', 'Your apps'],
43
+ ['saved', 'Kept for Lucy'],
44
+ ];
45
+
46
+ /** A button's word: an app is connected, the rest are added. */
47
+ export function connectVerb(connector: Pick<LucyConnector, 'group'>): string {
48
+ return connector.group === 'apps' ? 'Connect' : 'Add';
49
+ }
50
+
51
+ const base = (appUrl: string) => appUrl.trim().replace(/\/+$/, '');
52
+
53
+ /** Yantra's page that connects `id`: `<app>/connect/<id>?via=surface`. '' without an app or an id. */
54
+ export function connectLink(appUrl: string, id: string): string {
55
+ const app = base(appUrl);
56
+ const connector = id.trim();
57
+ if (!app || !connector) return '';
58
+ return `${app}/connect/${encodeURIComponent(connector)}?via=surface`;
59
+ }
60
+
61
+ /** Yantra's Connectors page: every connector there is, and what is connected already. */
62
+ export function allConnectorsLink(appUrl: string): string {
63
+ const app = base(appUrl);
64
+ return app ? `${app}/account/connectors` : '';
65
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Each message to Lucy as a chore record, as the web chat keeps them (browser chat/useChores.ts over
3
+ * @yantra/surface-kit tasks/serverJob.ts): recorded on Yantra's Task API BEFORE it goes out
4
+ * (`recordSurfaceJob`, an idempotent upsert), so the agent can report how it went, and what Lucy said, onto
5
+ * that record whether or not this app is still open. The same records are Lucy's chores (chat/chores.ts reads
6
+ * them with `getSurfaceJobs(surface: "clockbook")`), and how a reply that outlived its screen is picked up again.
7
+ */
8
+ import { agentBackendUrl, getChatToken } from './auth';
9
+ import { CLOCKBOOK_SURFACE, noteChoreVerdict, rememberChore } from './chores';
10
+ import { cardTokenFor, onCardToken } from '../live/liveActivity';
11
+ import { registeredPushToken } from '../push/push';
12
+
13
+ /** The lane a chore's turns are recorded in (the web's CHORE_LANE). */
14
+ const CHORE_LANE = 'chore';
15
+ /** How long one turn may run on the agent, plus the kit's grace: past it, a running record has stopped responding. */
16
+ const TURN_BUDGET_MS = 20 * 60_000 + 10 * 60_000;
17
+ /** A message never waits longer than this on its own record (it is written while the session opens); without one it goes out as before, and the record lands a moment later. */
18
+ const RECORD_BUDGET_MS = 1_200;
19
+
20
+ /** What a turn carries so the agent reports to its record (snake_case: the agent's own field names). */
21
+ export interface JobRef {
22
+ task_id: string;
23
+ report_token: string;
24
+ }
25
+
26
+ export interface RecordedChore {
27
+ /** The record's server id: what the chat keeps on the reply, to read it back. */
28
+ remoteId: string;
29
+ /** Absent when the backend has no report secret: then the turn goes without `job`. */
30
+ job?: JobRef;
31
+ }
32
+
33
+ export type ChoreVerdict =
34
+ | { state: 'running' }
35
+ | { state: 'succeeded'; text?: string }
36
+ | { state: 'failed'; error?: string };
37
+
38
+ async function post<T>(query: string, variables: Record<string, unknown>): Promise<T | undefined> {
39
+ const [url, token] = await Promise.all([agentBackendUrl(), getChatToken()]);
40
+ const res = await fetch(url, {
41
+ method: 'POST',
42
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
43
+ body: JSON.stringify({ query, variables }),
44
+ });
45
+ const json = (await res.json().catch(() => ({}))) as { data?: T; errors?: { message?: string }[] };
46
+ if (!res.ok || json.errors?.length) {
47
+ throw new Error(json.errors?.map((e) => e.message).join('; ') || `HTTP ${res.status}`);
48
+ }
49
+ return json.data;
50
+ }
51
+
52
+ /** A chore's title from what was asked (the web's choreTitle): its first line, plain, short. */
53
+ export function choreTitle(text: string, max = 60): string {
54
+ const line = (text.split('\n').find((l) => l.trim()) ?? '')
55
+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')
56
+ .replace(/[*_`#>~]+/g, '')
57
+ .replace(/\s+/g, ' ')
58
+ .trim();
59
+ if (!line) return 'A chore for Lucy';
60
+ return line.length > max ? `${line.slice(0, max - 1).trimEnd()}…` : line;
61
+ }
62
+
63
+ const RECORD = `mutation SurfaceJobRecord($job: JSON!) {
64
+ recordSurfaceJob(job: $job) { id status reportToken }
65
+ }`;
66
+
67
+ const PATCH = `mutation SurfaceJobPatch($id: ID!, $patch: JSON!) {
68
+ updateSurfaceJob(id: $id, patch: $patch)
69
+ }`;
70
+
71
+ /** The records of each chore's latest turns: a card token that comes after them (or changes) is put on them. */
72
+ const recordsByChore = new Map<string, string[]>();
73
+ const RECORDS_PER_CHORE = 3;
74
+ const CHORES_FOLLOWED = 30;
75
+ let followingCardTokens = false;
76
+
77
+ function followCardToken(choreId: string, remoteId: string): void {
78
+ const ids = [...(recordsByChore.get(choreId) ?? []).filter((x) => x !== remoteId), remoteId];
79
+ recordsByChore.delete(choreId);
80
+ recordsByChore.set(choreId, ids.slice(-RECORDS_PER_CHORE));
81
+ while (recordsByChore.size > CHORES_FOLLOWED) recordsByChore.delete(recordsByChore.keys().next().value as string);
82
+ if (followingCardTokens) return;
83
+ followingCardTokens = true;
84
+ // iOS reports a card's token a moment after the card goes up, usually after its record was written.
85
+ onCardToken((chore, token) => {
86
+ (recordsByChore.get(chore) ?? []).forEach((rid) => {
87
+ post(PATCH, { id: rid, patch: { cardToken: token } }).catch(() => undefined);
88
+ });
89
+ });
90
+ }
91
+
92
+ /**
93
+ * Records a message as a running chore. Null when the backend has no surface jobs, refused, or took longer than
94
+ * two seconds: the message then goes out exactly as it did before.
95
+ */
96
+ export function recordChore(input: {
97
+ /** This reply's own id: the same message always lands on the same record. */
98
+ id: string;
99
+ prompt: string;
100
+ owner?: string;
101
+ sessionId?: string | null;
102
+ /** The chore this turn belongs to (an answer goes on the chore that asked): its own id when absent. */
103
+ board?: string;
104
+ }): { now: Promise<RecordedChore | null>; later: Promise<RecordedChore | null> } {
105
+ const later = writeChore(input);
106
+ let timer: ReturnType<typeof setTimeout> | undefined;
107
+ const outOfTime = new Promise<null>((resolve) => {
108
+ timer = setTimeout(() => resolve(null), RECORD_BUDGET_MS);
109
+ });
110
+ // `now`: what the message can wait for (two seconds at most). `later`: the record however long it takes, so a slow
111
+ // backend still gets the chore on record (it just goes out without the agent reporting to it).
112
+ return { now: Promise.race([later, outOfTime]).finally(() => clearTimeout(timer)), later };
113
+ }
114
+
115
+ async function writeChore({
116
+ id,
117
+ prompt,
118
+ owner,
119
+ sessionId,
120
+ board,
121
+ }: {
122
+ id: string;
123
+ prompt: string;
124
+ owner?: string;
125
+ sessionId?: string | null;
126
+ board?: string;
127
+ }): Promise<RecordedChore | null> {
128
+ const now = Date.now();
129
+ const choreId = board ?? id;
130
+ // This phone, so Yantra can tell it how the chore goes while the app is closed: the "done" notification (its
131
+ // registered push token) and the chore's Lock Screen card (its token, once the card has one).
132
+ const pushToken = registeredPushToken();
133
+ const cardToken = await cardTokenFor(choreId).catch(() => undefined);
134
+ const job = {
135
+ id,
136
+ surface: CLOCKBOOK_SURFACE,
137
+ lane: CHORE_LANE,
138
+ title: choreTitle(prompt),
139
+ brief: prompt,
140
+ state: 'running',
141
+ createdAt: now,
142
+ startedAt: now,
143
+ deadlineAt: now + TURN_BUDGET_MS,
144
+ input: { prompt },
145
+ ...(owner ? { owner } : {}),
146
+ // The web's `handle.boardId`: every turn of a chore under one id, so it stays one row in Lucy's chores.
147
+ handle: { kind: 'session', boardId: choreId, ...(sessionId ? { sessionId } : {}) },
148
+ ...(pushToken ? { pushToken } : {}),
149
+ ...(cardToken ? { cardToken } : {}),
150
+ };
151
+ try {
152
+ const d = await post<{ recordSurfaceJob?: { id?: string; reportToken?: string } }>(RECORD, { job });
153
+ const rec = d?.recordSurfaceJob;
154
+ if (!rec?.id) {
155
+ console.warn('[chores] recordSurfaceJob returned no id');
156
+ return null;
157
+ }
158
+ rememberChore(rec.id).catch(() => undefined);
159
+ followCardToken(choreId, rec.id);
160
+ return {
161
+ remoteId: rec.id,
162
+ ...(rec.reportToken ? { job: { task_id: rec.id, report_token: rec.reportToken } } : {}),
163
+ };
164
+ } catch (err) {
165
+ // Not fatal (the message goes out without a record), but say why: Lucy's chores stay empty without it.
166
+ console.warn('[chores] could not record the chore:', (err as Error).message);
167
+ return null;
168
+ }
169
+ }
170
+
171
+ /**
172
+ * This app's word on how a chore ended. The agent's own verdict is final, and the server keeps it over this one;
173
+ * a reply placed here is marked delivered, so it is not placed a second time.
174
+ */
175
+ export async function settleChore(
176
+ remoteId: string,
177
+ outcome: { state: 'succeeded'; text?: string } | { state: 'failed'; error: string },
178
+ ): Promise<void> {
179
+ const patch =
180
+ outcome.state === 'succeeded'
181
+ ? { state: 'succeeded', endedAt: Date.now(), delivered: true }
182
+ : { state: 'failed', endedAt: Date.now(), error: outcome.error };
183
+ noteChoreVerdict(remoteId, {
184
+ state: outcome.state,
185
+ endedAt: patch.endedAt,
186
+ ...(outcome.state === 'failed' ? { error: outcome.error } : {}),
187
+ }).catch(() => undefined);
188
+ await post(PATCH, { id: remoteId, patch }).catch(() => undefined);
189
+ }
190
+
191
+ const READ = `query SurfaceJobOne($id: ID!) {
192
+ getSurfaceJob(id: $id) { id status source { details } }
193
+ }`;
194
+ const RESULT = `query SurfaceJobStoredResult($id: ID!) {
195
+ surfaceJobResult(id: $id)
196
+ }`;
197
+
198
+ const textOf = (value: unknown): string | undefined => {
199
+ if (typeof value === 'string' && value.trim()) return value;
200
+ const t = (value as { text?: unknown } | null)?.text;
201
+ return typeof t === 'string' && t.trim() ? t : undefined;
202
+ };
203
+
204
+ /** Where a chore stands on its record: still going, done (with what Lucy said, when the agent kept it), or failed. */
205
+ export async function readChore(remoteId: string): Promise<ChoreVerdict> {
206
+ const d = await post<{ getSurfaceJob?: { status?: string; source?: { details?: unknown } } | null }>(READ, {
207
+ id: remoteId,
208
+ });
209
+ const row = d?.getSurfaceJob;
210
+ if (!row) return { state: 'failed', error: 'This chore is no longer on record' };
211
+ const details = (row.source?.details ?? {}) as Record<string, unknown>;
212
+ if (row.status === 'COMPLETED') {
213
+ let text = textOf(details.result);
214
+ if (!text && details.hasResult) {
215
+ const r = await post<{ surfaceJobResult?: unknown }>(RESULT, { id: remoteId }).catch(() => undefined);
216
+ text = textOf(r?.surfaceJobResult);
217
+ }
218
+ return { state: 'succeeded', ...(text ? { text } : {}) };
219
+ }
220
+ if (row.status === 'IN_PROGRESS' || row.status === 'NOT_STARTED') return { state: 'running' };
221
+ const error = typeof details.error === 'string' ? details.error : undefined;
222
+ return { state: 'failed', ...(error ? { error } : {}) };
223
+ }
224
+
225
+ /** Where the agent reports a job: the backend Lucy's token was minted at (sent in the body; see agent.ts). */
226
+ export function jobBackendUrl(): Promise<string> {
227
+ return agentBackendUrl();
228
+ }