@tambo-ai/react 0.66.1 → 0.67.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 (159) hide show
  1. package/dist/context-helpers/current-interactables-context-helper.d.ts +2 -2
  2. package/dist/context-helpers/current-interactables-context-helper.d.ts.map +1 -1
  3. package/dist/context-helpers/current-interactables-context-helper.js +17 -23
  4. package/dist/context-helpers/current-interactables-context-helper.js.map +1 -1
  5. package/dist/hoc/with-tambo-interactable.d.ts.map +1 -1
  6. package/dist/hoc/with-tambo-interactable.js +0 -1
  7. package/dist/hoc/with-tambo-interactable.js.map +1 -1
  8. package/dist/hooks/use-component-state.d.ts +16 -1
  9. package/dist/hooks/use-component-state.d.ts.map +1 -1
  10. package/dist/hooks/use-component-state.js +72 -12
  11. package/dist/hooks/use-component-state.js.map +1 -1
  12. package/dist/hooks/use-component-state.test.js +42 -0
  13. package/dist/hooks/use-component-state.test.js.map +1 -1
  14. package/dist/hooks/use-current-message.d.ts +3 -0
  15. package/dist/hooks/use-current-message.d.ts.map +1 -1
  16. package/dist/hooks/use-current-message.js +6 -5
  17. package/dist/hooks/use-current-message.js.map +1 -1
  18. package/dist/hooks/use-current-message.test.js +5 -0
  19. package/dist/hooks/use-current-message.test.js.map +1 -1
  20. package/dist/model/component-metadata.d.ts +2 -2
  21. package/dist/model/component-metadata.d.ts.map +1 -1
  22. package/dist/model/component-metadata.js.map +1 -1
  23. package/dist/model/tambo-interactable.d.ts +6 -0
  24. package/dist/model/tambo-interactable.d.ts.map +1 -1
  25. package/dist/model/tambo-interactable.js.map +1 -1
  26. package/dist/providers/tambo-interactable-provider-partial-updates.test.js +87 -87
  27. package/dist/providers/tambo-interactable-provider-partial-updates.test.js.map +1 -1
  28. package/dist/providers/tambo-interactable-provider.d.ts +1 -0
  29. package/dist/providers/tambo-interactable-provider.d.ts.map +1 -1
  30. package/dist/providers/tambo-interactable-provider.js +83 -47
  31. package/dist/providers/tambo-interactable-provider.js.map +1 -1
  32. package/dist/providers/tambo-interactable-provider.test.d.ts +2 -0
  33. package/dist/providers/tambo-interactable-provider.test.d.ts.map +1 -0
  34. package/dist/providers/tambo-interactable-provider.test.js +62 -0
  35. package/dist/providers/tambo-interactable-provider.test.js.map +1 -0
  36. package/dist/providers/tambo-interactables-additional-context-edge-cases.test.js +8 -8
  37. package/dist/providers/tambo-interactables-additional-context-edge-cases.test.js.map +1 -1
  38. package/dist/providers/tambo-interactables-additional-context.test.js +10 -10
  39. package/dist/providers/tambo-interactables-additional-context.test.js.map +1 -1
  40. package/dist/providers/tambo-registry-provider.test.js +28 -18
  41. package/dist/providers/tambo-registry-provider.test.js.map +1 -1
  42. package/dist/providers/tambo-registry-schema-compat.test.js +57 -28
  43. package/dist/providers/tambo-registry-schema-compat.test.js.map +1 -1
  44. package/dist/providers/tambo-thread-provider.test.js +21 -19
  45. package/dist/providers/tambo-thread-provider.test.js.map +1 -1
  46. package/dist/schema/alias.d.ts +3 -0
  47. package/dist/schema/alias.d.ts.map +1 -0
  48. package/dist/schema/alias.js +6 -0
  49. package/dist/schema/alias.js.map +1 -0
  50. package/dist/schema/json-schema.js +29 -29
  51. package/dist/schema/json-schema.js.map +1 -1
  52. package/dist/schema/schema.d.ts.map +1 -1
  53. package/dist/schema/schema.js +20 -9
  54. package/dist/schema/schema.js.map +1 -1
  55. package/dist/schema/schema.test.js +291 -3
  56. package/dist/schema/schema.test.js.map +1 -1
  57. package/dist/schema/standard-schema.js +8 -8
  58. package/dist/schema/standard-schema.js.map +1 -1
  59. package/dist/schema/validate.test.js +31 -31
  60. package/dist/schema/validate.test.js.map +1 -1
  61. package/dist/schema/zod.d.ts +1 -1
  62. package/dist/schema/zod.d.ts.map +1 -1
  63. package/dist/schema/zod.js +27 -26
  64. package/dist/schema/zod.js.map +1 -1
  65. package/dist/schema/zod.test.d.ts +2 -0
  66. package/dist/schema/zod.test.d.ts.map +1 -0
  67. package/dist/schema/zod.test.js +551 -0
  68. package/dist/schema/zod.test.js.map +1 -0
  69. package/dist/util/registry-validators.d.ts.map +1 -1
  70. package/dist/util/registry-validators.js +40 -0
  71. package/dist/util/registry-validators.js.map +1 -1
  72. package/dist/util/registry-validators.test.js +69 -0
  73. package/dist/util/registry-validators.test.js.map +1 -1
  74. package/dist/util/registry.d.ts +1 -5
  75. package/dist/util/registry.d.ts.map +1 -1
  76. package/dist/util/registry.js +1 -5
  77. package/dist/util/registry.js.map +1 -1
  78. package/dist/util/registry.test.js +80 -67
  79. package/dist/util/registry.test.js.map +1 -1
  80. package/esm/context-helpers/current-interactables-context-helper.d.ts +2 -2
  81. package/esm/context-helpers/current-interactables-context-helper.d.ts.map +1 -1
  82. package/esm/context-helpers/current-interactables-context-helper.js +17 -23
  83. package/esm/context-helpers/current-interactables-context-helper.js.map +1 -1
  84. package/esm/hoc/with-tambo-interactable.d.ts.map +1 -1
  85. package/esm/hoc/with-tambo-interactable.js +0 -1
  86. package/esm/hoc/with-tambo-interactable.js.map +1 -1
  87. package/esm/hooks/use-component-state.d.ts +16 -1
  88. package/esm/hooks/use-component-state.d.ts.map +1 -1
  89. package/esm/hooks/use-component-state.js +74 -14
  90. package/esm/hooks/use-component-state.js.map +1 -1
  91. package/esm/hooks/use-component-state.test.js +40 -1
  92. package/esm/hooks/use-component-state.test.js.map +1 -1
  93. package/esm/hooks/use-current-message.d.ts +3 -0
  94. package/esm/hooks/use-current-message.d.ts.map +1 -1
  95. package/esm/hooks/use-current-message.js +2 -1
  96. package/esm/hooks/use-current-message.js.map +1 -1
  97. package/esm/hooks/use-current-message.test.js +5 -0
  98. package/esm/hooks/use-current-message.test.js.map +1 -1
  99. package/esm/model/component-metadata.d.ts +2 -2
  100. package/esm/model/component-metadata.d.ts.map +1 -1
  101. package/esm/model/component-metadata.js.map +1 -1
  102. package/esm/model/tambo-interactable.d.ts +6 -0
  103. package/esm/model/tambo-interactable.d.ts.map +1 -1
  104. package/esm/model/tambo-interactable.js.map +1 -1
  105. package/esm/providers/tambo-interactable-provider-partial-updates.test.js +1 -1
  106. package/esm/providers/tambo-interactable-provider-partial-updates.test.js.map +1 -1
  107. package/esm/providers/tambo-interactable-provider.d.ts +1 -0
  108. package/esm/providers/tambo-interactable-provider.d.ts.map +1 -1
  109. package/esm/providers/tambo-interactable-provider.js +55 -19
  110. package/esm/providers/tambo-interactable-provider.js.map +1 -1
  111. package/esm/providers/tambo-interactable-provider.test.d.ts +2 -0
  112. package/esm/providers/tambo-interactable-provider.test.d.ts.map +1 -0
  113. package/esm/providers/tambo-interactable-provider.test.js +57 -0
  114. package/esm/providers/tambo-interactable-provider.test.js.map +1 -0
  115. package/esm/providers/tambo-interactables-additional-context-edge-cases.test.js +1 -1
  116. package/esm/providers/tambo-interactables-additional-context-edge-cases.test.js.map +1 -1
  117. package/esm/providers/tambo-interactables-additional-context.test.js +1 -1
  118. package/esm/providers/tambo-interactables-additional-context.test.js.map +1 -1
  119. package/esm/providers/tambo-registry-provider.test.js +16 -6
  120. package/esm/providers/tambo-registry-provider.test.js.map +1 -1
  121. package/esm/providers/tambo-registry-schema-compat.test.js +57 -28
  122. package/esm/providers/tambo-registry-schema-compat.test.js.map +1 -1
  123. package/esm/providers/tambo-thread-provider.test.js +8 -6
  124. package/esm/providers/tambo-thread-provider.test.js.map +1 -1
  125. package/esm/schema/alias.d.ts +3 -0
  126. package/esm/schema/alias.d.ts.map +1 -0
  127. package/esm/schema/alias.js +13 -0
  128. package/esm/schema/alias.js.map +1 -0
  129. package/esm/schema/json-schema.js +1 -1
  130. package/esm/schema/json-schema.js.map +1 -1
  131. package/esm/schema/schema.d.ts.map +1 -1
  132. package/esm/schema/schema.js +20 -9
  133. package/esm/schema/schema.js.map +1 -1
  134. package/esm/schema/schema.test.js +258 -3
  135. package/esm/schema/schema.test.js.map +1 -1
  136. package/esm/schema/standard-schema.js +1 -1
  137. package/esm/schema/standard-schema.js.map +1 -1
  138. package/esm/schema/validate.test.js +1 -1
  139. package/esm/schema/validate.test.js.map +1 -1
  140. package/esm/schema/zod.d.ts +1 -1
  141. package/esm/schema/zod.d.ts.map +1 -1
  142. package/esm/schema/zod.js +27 -26
  143. package/esm/schema/zod.js.map +1 -1
  144. package/esm/schema/zod.test.d.ts +2 -0
  145. package/esm/schema/zod.test.d.ts.map +1 -0
  146. package/esm/schema/zod.test.js +516 -0
  147. package/esm/schema/zod.test.js.map +1 -0
  148. package/esm/util/registry-validators.d.ts.map +1 -1
  149. package/esm/util/registry-validators.js +40 -0
  150. package/esm/util/registry-validators.js.map +1 -1
  151. package/esm/util/registry-validators.test.js +69 -0
  152. package/esm/util/registry-validators.test.js.map +1 -1
  153. package/esm/util/registry.d.ts +1 -5
  154. package/esm/util/registry.d.ts.map +1 -1
  155. package/esm/util/registry.js +1 -5
  156. package/esm/util/registry.js.map +1 -1
  157. package/esm/util/registry.test.js +80 -67
  158. package/esm/util/registry.test.js.map +1 -1
  159. package/package.json +2 -3
@@ -21,8 +21,8 @@ export declare const currentInteractablesContextHelper: ContextHelperFn;
21
21
  /**
22
22
  * Creates an interactables context helper with access to the current components.
23
23
  * This is used internally by TamboInteractableProvider.
24
- * @param getComponents Function to get current interactable components
24
+ * @param components Array of interactable components
25
25
  * @returns Context helper function
26
26
  */
27
- export declare const createInteractablesContextHelper: (getComponents: () => any[]) => ContextHelperFn;
27
+ export declare const createInteractablesContextHelper: (components: any[]) => ContextHelperFn;
28
28
  //# sourceMappingURL=current-interactables-context-helper.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"current-interactables-context-helper.d.ts","sourceRoot":"","sources":["../../src/context-helpers/current-interactables-context-helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE1C;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,iCAAiC,EAAE,eAI/C,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,GAC3C,eAAe,MAAM,GAAG,EAAE,KACzB,eA2BF,CAAC"}
1
+ {"version":3,"file":"current-interactables-context-helper.d.ts","sourceRoot":"","sources":["../../src/context-helpers/current-interactables-context-helper.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,SAAS,CAAC;AAE1C;;;;;;;;;;;;;;;;;GAiBG;AACH,eAAO,MAAM,iCAAiC,EAAE,eAI/C,CAAC;AAEF;;;;;GAKG;AACH,eAAO,MAAM,gCAAgC,GAC3C,YAAY,GAAG,EAAE,KAChB,eAqBF,CAAC"}
@@ -28,33 +28,27 @@ exports.currentInteractablesContextHelper = currentInteractablesContextHelper;
28
28
  /**
29
29
  * Creates an interactables context helper with access to the current components.
30
30
  * This is used internally by TamboInteractableProvider.
31
- * @param getComponents Function to get current interactable components
31
+ * @param components Array of interactable components
32
32
  * @returns Context helper function
33
33
  */
34
- const createInteractablesContextHelper = (getComponents) => {
34
+ const createInteractablesContextHelper = (components) => {
35
35
  return () => {
36
- try {
37
- const components = getComponents();
38
- if (!Array.isArray(components) || components.length === 0) {
39
- return null; // No interactable components on the page
40
- }
41
- return {
42
- description: "These are the interactable components currently visible on the page that you can read and modify. Each component has an id, componentName, current props, and optional schema. You can use tools to update these components on behalf of the user.",
43
- components: components.map((component) => ({
44
- id: component.id,
45
- componentName: component.name,
46
- description: component.description,
47
- props: component.props,
48
- propsSchema: component.propsSchema
49
- ? "Available - use component-specific update tools"
50
- : "Not specified",
51
- })),
52
- };
53
- }
54
- catch (e) {
55
- console.error("currentInteractablesContextHelper failed:", e);
56
- return null;
36
+ if (!Array.isArray(components) || components.length === 0) {
37
+ return null; // No interactable components on the page
57
38
  }
39
+ return {
40
+ description: "These are the interactable components currently visible on the page that you can read and modify. Each component has an id, componentName, current props, current state,and optional schema. You can use tools to update these components on behalf of the user. Don't tell the user the ID of the components, only the name, unless they ask for it.",
41
+ components: components.map((component) => ({
42
+ id: component.id,
43
+ componentName: component.name,
44
+ description: component.description,
45
+ props: component.props,
46
+ propsSchema: component.propsSchema
47
+ ? "Available - use component-specific update tools"
48
+ : "Not specified",
49
+ state: component.state,
50
+ })),
51
+ };
58
52
  };
59
53
  };
60
54
  exports.createInteractablesContextHelper = createInteractablesContextHelper;
@@ -1 +1 @@
1
- {"version":3,"file":"current-interactables-context-helper.js","sourceRoot":"","sources":["../../src/context-helpers/current-interactables-context-helper.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;;;GAiBG;AACI,MAAM,iCAAiC,GAAoB,GAAG,EAAE;IACrE,mFAAmF;IACnF,wEAAwE;IACxE,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAJW,QAAA,iCAAiC,qCAI5C;AAEF;;;;;GAKG;AACI,MAAM,gCAAgC,GAAG,CAC9C,aAA0B,EACT,EAAE;IACnB,OAAO,GAAG,EAAE;QACV,IAAI,CAAC;YACH,MAAM,UAAU,GAAG,aAAa,EAAE,CAAC;YAEnC,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;gBAC1D,OAAO,IAAI,CAAC,CAAC,yCAAyC;YACxD,CAAC;YAED,OAAO;gBACL,WAAW,EACT,oPAAoP;gBACtP,UAAU,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;oBACzC,EAAE,EAAE,SAAS,CAAC,EAAE;oBAChB,aAAa,EAAE,SAAS,CAAC,IAAI;oBAC7B,WAAW,EAAE,SAAS,CAAC,WAAW;oBAClC,KAAK,EAAE,SAAS,CAAC,KAAK;oBACtB,WAAW,EAAE,SAAS,CAAC,WAAW;wBAChC,CAAC,CAAC,iDAAiD;wBACnD,CAAC,CAAC,eAAe;iBACpB,CAAC,CAAC;aACJ,CAAC;QACJ,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,OAAO,CAAC,KAAK,CAAC,2CAA2C,EAAE,CAAC,CAAC,CAAC;YAC9D,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC,CAAC;AACJ,CAAC,CAAC;AA7BW,QAAA,gCAAgC,oCA6B3C","sourcesContent":["import { ContextHelperFn } from \"./types\";\n\n/**\n * Prebuilt context helper that provides information about all interactable components currently on the page.\n * This gives the AI awareness of what components it can interact with and their current state.\n * @returns an object with description and components, or null to skip including this context.\n * To disable this helper, override it with a function that returns null:\n * @example\n * ```tsx\n * // To disable the default interactables context\n * const { addContextHelper } = useTamboContextHelpers();\n * addContextHelper(\"interactables\", () => null);\n *\n * // To customize the context\n * addContextHelper(\"interactables\", () => ({\n * description: \"Custom description\",\n * components: getCustomComponentsSubset()\n * }));\n * ```\n */\nexport const currentInteractablesContextHelper: ContextHelperFn = () => {\n // This will be provided by the interactable provider when it registers this helper\n // Since we're provider-only now, this function gets replaced at runtime\n return null;\n};\n\n/**\n * Creates an interactables context helper with access to the current components.\n * This is used internally by TamboInteractableProvider.\n * @param getComponents Function to get current interactable components\n * @returns Context helper function\n */\nexport const createInteractablesContextHelper = (\n getComponents: () => any[],\n): ContextHelperFn => {\n return () => {\n try {\n const components = getComponents();\n\n if (!Array.isArray(components) || components.length === 0) {\n return null; // No interactable components on the page\n }\n\n return {\n description:\n \"These are the interactable components currently visible on the page that you can read and modify. Each component has an id, componentName, current props, and optional schema. You can use tools to update these components on behalf of the user.\",\n components: components.map((component) => ({\n id: component.id,\n componentName: component.name,\n description: component.description,\n props: component.props,\n propsSchema: component.propsSchema\n ? \"Available - use component-specific update tools\"\n : \"Not specified\",\n })),\n };\n } catch (e) {\n console.error(\"currentInteractablesContextHelper failed:\", e);\n return null;\n }\n };\n};\n"]}
1
+ {"version":3,"file":"current-interactables-context-helper.js","sourceRoot":"","sources":["../../src/context-helpers/current-interactables-context-helper.ts"],"names":[],"mappings":";;;AAEA;;;;;;;;;;;;;;;;;GAiBG;AACI,MAAM,iCAAiC,GAAoB,GAAG,EAAE;IACrE,mFAAmF;IACnF,wEAAwE;IACxE,OAAO,IAAI,CAAC;AACd,CAAC,CAAC;AAJW,QAAA,iCAAiC,qCAI5C;AAEF;;;;;GAKG;AACI,MAAM,gCAAgC,GAAG,CAC9C,UAAiB,EACA,EAAE;IACnB,OAAO,GAAG,EAAE;QACV,IAAI,CAAC,KAAK,CAAC,OAAO,CAAC,UAAU,CAAC,IAAI,UAAU,CAAC,MAAM,KAAK,CAAC,EAAE,CAAC;YAC1D,OAAO,IAAI,CAAC,CAAC,yCAAyC;QACxD,CAAC;QAED,OAAO;YACL,WAAW,EACT,uVAAuV;YACzV,UAAU,EAAE,UAAU,CAAC,GAAG,CAAC,CAAC,SAAS,EAAE,EAAE,CAAC,CAAC;gBACzC,EAAE,EAAE,SAAS,CAAC,EAAE;gBAChB,aAAa,EAAE,SAAS,CAAC,IAAI;gBAC7B,WAAW,EAAE,SAAS,CAAC,WAAW;gBAClC,KAAK,EAAE,SAAS,CAAC,KAAK;gBACtB,WAAW,EAAE,SAAS,CAAC,WAAW;oBAChC,CAAC,CAAC,iDAAiD;oBACnD,CAAC,CAAC,eAAe;gBACnB,KAAK,EAAE,SAAS,CAAC,KAAK;aACvB,CAAC,CAAC;SACJ,CAAC;IACJ,CAAC,CAAC;AACJ,CAAC,CAAC;AAvBW,QAAA,gCAAgC,oCAuB3C","sourcesContent":["import { ContextHelperFn } from \"./types\";\n\n/**\n * Prebuilt context helper that provides information about all interactable components currently on the page.\n * This gives the AI awareness of what components it can interact with and their current state.\n * @returns an object with description and components, or null to skip including this context.\n * To disable this helper, override it with a function that returns null:\n * @example\n * ```tsx\n * // To disable the default interactables context\n * const { addContextHelper } = useTamboContextHelpers();\n * addContextHelper(\"interactables\", () => null);\n *\n * // To customize the context\n * addContextHelper(\"interactables\", () => ({\n * description: \"Custom description\",\n * components: getCustomComponentsSubset()\n * }));\n * ```\n */\nexport const currentInteractablesContextHelper: ContextHelperFn = () => {\n // This will be provided by the interactable provider when it registers this helper\n // Since we're provider-only now, this function gets replaced at runtime\n return null;\n};\n\n/**\n * Creates an interactables context helper with access to the current components.\n * This is used internally by TamboInteractableProvider.\n * @param components Array of interactable components\n * @returns Context helper function\n */\nexport const createInteractablesContextHelper = (\n components: any[],\n): ContextHelperFn => {\n return () => {\n if (!Array.isArray(components) || components.length === 0) {\n return null; // No interactable components on the page\n }\n\n return {\n description:\n \"These are the interactable components currently visible on the page that you can read and modify. Each component has an id, componentName, current props, current state,and optional schema. You can use tools to update these components on behalf of the user. Don't tell the user the ID of the components, only the name, unless they ask for it.\",\n components: components.map((component) => ({\n id: component.id,\n componentName: component.name,\n description: component.description,\n props: component.props,\n propsSchema: component.propsSchema\n ? \"Available - use component-specific update tools\"\n : \"Not specified\",\n state: component.state,\n })),\n };\n };\n};\n"]}
@@ -1 +1 @@
1
- {"version":3,"file":"with-tambo-interactable.d.ts","sourceRoot":"","sources":["../../src/hoc/with-tambo-interactable.tsx"],"names":[],"mappings":"AAEA,OAAO,KAAmD,MAAM,OAAO,CAAC;AAIxE,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAE5C,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,eAAe,CAAC;CAC/B;AAED,MAAM,WAAW,0BAA0B;IACzC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,mBAAmB,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3C,aAAa,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,IAAI,CAAC;CACzD;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,MAAM,EACpD,gBAAgB,EAAE,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,EACxC,MAAM,EAAE,kBAAkB,4CAgH3B"}
1
+ {"version":3,"file":"with-tambo-interactable.d.ts","sourceRoot":"","sources":["../../src/hoc/with-tambo-interactable.tsx"],"names":[],"mappings":"AACA,OAAO,KAAmD,MAAM,OAAO,CAAC;AAIxE,OAAO,EAAE,eAAe,EAAE,MAAM,WAAW,CAAC;AAE5C,MAAM,WAAW,kBAAkB;IACjC,aAAa,EAAE,MAAM,CAAC;IACtB,WAAW,EAAE,MAAM,CAAC;IACpB,WAAW,CAAC,EAAE,eAAe,CAAC;CAC/B;AAED,MAAM,WAAW,0BAA0B;IACzC,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,mBAAmB,CAAC,EAAE,CAAC,EAAE,EAAE,MAAM,KAAK,IAAI,CAAC;IAC3C,aAAa,CAAC,EAAE,CAAC,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,KAAK,IAAI,CAAC;CACzD;AAED;;;;;;;;;;;;;;;;;;;GAmBG;AACH,wBAAgB,qBAAqB,CAAC,CAAC,SAAS,MAAM,EACpD,gBAAgB,EAAE,KAAK,CAAC,aAAa,CAAC,CAAC,CAAC,EACxC,MAAM,EAAE,kBAAkB,4CAgH3B"}
@@ -1,5 +1,4 @@
1
1
  "use strict";
2
- // react-sdk/src/providers/with-interactable.tsx
3
2
  "use client";
4
3
  var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
4
  if (k2 === undefined) k2 = k;
@@ -1 +1 @@
1
- {"version":3,"file":"with-tambo-interactable.js","sourceRoot":"","sources":["../../src/hoc/with-tambo-interactable.tsx"],"names":[],"mappings":";AAAA,gDAAgD;AAChD,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCb,sDAkHC;AAxJD,+CAAwE;AACxE,sEAAoE;AAEpE,0FAAgF;AAehF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,qBAAqB,CACnC,gBAAwC,EACxC,MAA0B;IAE1B,MAAM,WAAW,GACf,gBAAgB,CAAC,WAAW,IAAI,gBAAgB,CAAC,IAAI,IAAI,WAAW,CAAC;IAEvE,MAAM,wBAAwB,GAA6C,CACzE,KAAK,EACL,EAAE;QACF,MAAM,EACJ,w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cAAc;gBAClB,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,WAAW,EAAE,MAAM,CAAC,WAAW;aAChC;YAED,8BAAC,gBAAgB,OAAM,cAAoB,GAAI,CAC1B,CACxB,CAAC;IACJ,CAAC,CAAC;IAEF,wBAAwB,CAAC,WAAW,GAAG,yBAAyB,WAAW,GAAG,CAAC;IAE/E,OAAO,wBAAwB,CAAC;AAClC,CAAC","sourcesContent":["// react-sdk/src/providers/with-interactable.tsx\n\"use client\";\nimport React, { useCallback, useEffect, useRef, useState } from \"react\";\nimport { TamboMessageProvider } from \"../hooks/use-current-message\";\nimport { TamboThreadMessage } from \"../model/generate-component-response\";\nimport { useTamboInteractable } from \"../providers/tambo-interactable-provider\";\nimport { SupportedSchema } from \"../schema\";\n\nexport interface InteractableConfig {\n componentName: string;\n description: string;\n propsSchema?: SupportedSchema;\n}\n\nexport interface WithTamboInteractableProps {\n interactableId?: string;\n onInteractableReady?: (id: string) => void;\n onPropsUpdate?: (newProps: Record<string, any>) => void;\n}\n\n/**\n * Higher-Order Component that makes any component interactable by tambo.\n * @param WrappedComponent - The component to make interactable\n * @param config - Configuration for the interactable component\n * @returns A new component that is automatically registered as interactable\n * @example\n * ```tsx\n * const MyInteractableNote = withTamboInteractable(MyNote, {\n * componentName: \"MyNote\",\n * description: \"A note component\",\n * propsSchema: z.object({\n * title: z.string(),\n * content: z.string(),\n * }),\n * });\n *\n * // Usage\n * <MyInteractableNote title=\"My Note\" content=\"This is my note\" />\n * ```\n */\nexport function withTamboInteractable<P extends object>(\n WrappedComponent: React.ComponentType<P>,\n config: InteractableConfig,\n) {\n const displayName =\n WrappedComponent.displayName ?? WrappedComponent.name ?? \"Component\";\n\n const TamboInteractableWrapper: React.FC<P & WithTamboInteractableProps> = (\n props,\n ) => {\n const {\n addInteractableComponent,\n updateInteractableComponentProps,\n getInteractableComponent,\n } = useTamboInteractable();\n\n const [interactableId, setInteractableId] = useState<string | null>(null);\n const isInitialized = useRef(false);\n const lastParentProps = useRef<Record<string, any>>({});\n\n // Extract interactable-specific props\n const { onInteractableReady, onPropsUpdate, ...componentProps } = props;\n\n // Get the current interactable component to track prop updates\n const currentInteractable = interactableId\n ? getInteractableComponent(interactableId)\n : null;\n\n // Use the props from the interactable component if available, otherwise use the passed props\n // We need to be careful not to create a loop, so we only use stored props if they're different from passed props\n const effectiveProps = currentInteractable?.props ?? componentProps;\n\n // Memoize the registration function\n const registerComponent = useCallback(() => {\n if (!isInitialized.current) {\n const id = addInteractableComponent({\n name: config.componentName,\n description: config.description,\n component: WrappedComponent,\n props: componentProps,\n propsSchema: config.propsSchema,\n });\n\n setInteractableId(id);\n onInteractableReady?.(id);\n isInitialized.current = true;\n }\n }, [addInteractableComponent, componentProps, onInteractableReady]);\n\n // Register the component as interactable on mount (only once)\n useEffect(() => {\n registerComponent();\n }, [registerComponent]);\n\n // Update the interactable component when props change from parent\n useEffect(() => {\n if (interactableId && isInitialized.current) {\n // Only update if the props are different from what we last sent\n const lastPropsString = JSON.stringify(lastParentProps.current);\n const currentPropsString = JSON.stringify(componentProps);\n\n if (lastPropsString !== currentPropsString) {\n updateInteractableComponentProps(interactableId, componentProps);\n onPropsUpdate?.(componentProps);\n lastParentProps.current = componentProps;\n }\n }\n }, [\n interactableId,\n componentProps,\n updateInteractableComponentProps,\n onPropsUpdate,\n ]);\n\n // If the interactable ID is not yet set, render the component without provider\n if (!interactableId) {\n return <WrappedComponent {...(effectiveProps as P)} />;\n }\n\n // Create a minimal message with interactable metadata\n // This allows useTamboCurrentComponent to work with standalone interactable components\n const minimalMessage: TamboThreadMessage = {\n id: interactableId,\n role: \"assistant\" as const,\n content: [],\n threadId: \"\",\n createdAt: new Date().toISOString(),\n component: {\n componentName: config.componentName,\n componentState: {},\n message: \"\",\n props: effectiveProps,\n },\n componentState: {},\n };\n\n // Wrap with TamboMessageProvider including interactable metadata\n return (\n <TamboMessageProvider\n message={minimalMessage}\n interactableMetadata={{\n id: interactableId,\n componentName: config.componentName,\n description: config.description,\n }}\n >\n <WrappedComponent {...(effectiveProps as P)} />\n </TamboMessageProvider>\n );\n };\n\n TamboInteractableWrapper.displayName = `withTamboInteractable(${displayName})`;\n\n return TamboInteractableWrapper;\n}\n"]}
1
+ {"version":3,"file":"with-tambo-interactable.js","sourceRoot":"","sources":["../../src/hoc/with-tambo-interactable.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuCb,sDAkHC;AAxJD,+CAAwE;AACxE,sEAAoE;AAEpE,0FAAgF;AAehF;;;;;;;;;;;;;;;;;;;GAmBG;AACH,SAAgB,qBAAqB,CACnC,gBAAwC,EACxC,MAA0B;IAE1B,MAAM,WAAW,GACf,gBAAgB,CAAC,WAAW,IAAI,gBAAgB,CAAC,IAAI,IAAI,WAAW,CAAC;IAEvE,MAAM,wBAAwB,GAA6C,CACzE,KAAK,EACL,EAAE;QACF,MAAM,EACJ,wBAAwB,EACxB,gCAAgC,EAChC,wBAAwB,GACzB,GAAG,IAAA,kDAAoB,GAAE,CAAC;QAE3B,MAAM,CAAC,cAAc,EAAE,iBAAiB,CAAC,GAAG,IAAA,gBAAQ,EAAgB,IAAI,CAAC,CAAC;QAC1E,MAAM,aAAa,GAAG,IAAA,cAAM,EAAC,KAAK,CAAC,CAAC;QACpC,MAAM,eAAe,GAAG,IAAA,cAAM,EAAsB,EAAE,CAAC,CAAC;QAExD,sCAAsC;QACtC,MAAM,EAAE,mBAAmB,EAAE,aAAa,EAAE,GAAG,cAAc,EAAE,GAAG,KAAK,CAAC;QAExE,+DAA+D;QAC/D,MAAM,mBAAmB,GAAG,cAAc;YACxC,CAAC,CAAC,wBAAwB,CAAC,cAAc,CAAC;YAC1C,CAAC,CAAC,IAAI,CAAC;QAET,6FAA6F;QAC7F,iHAAiH;QACjH,MAAM,cAAc,GAAG,mBAAmB,EAAE,KAAK,IAAI,cAAc,CAAC;QAEpE,oCAAoC;QACpC,MAAM,iBAAiB,GAAG,I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;QAC/E,IAAI,CAAC,cAAc,EAAE,CAAC;YACpB,OAAO,8BAAC,gBAAgB,OAAM,cAAoB,GAAI,CAAC;QACzD,CAAC;QAED,sDAAsD;QACtD,uFAAuF;QACvF,MAAM,cAAc,GAAuB;YACzC,EAAE,EAAE,cAAc;YAClB,IAAI,EAAE,WAAoB;YAC1B,OAAO,EAAE,EAAE;YACX,QAAQ,EAAE,EAAE;YACZ,SAAS,EAAE,IAAI,IAAI,EAAE,CAAC,WAAW,EAAE;YACnC,SAAS,EAAE;gBACT,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,cAAc,EAAE,EAAE;gBAClB,OAAO,EAAE,EAAE;gBACX,KAAK,EAAE,cAAc;aACtB;YACD,cAAc,EAAE,EAAE;SACnB,CAAC;QAEF,iEAAiE;QACjE,OAAO,CACL,8BAAC,0CAAoB,IACnB,OAAO,EAAE,cAAc,EACvB,oBAAoB,EAAE;gBACpB,EAAE,EAAE,cAAc;gBAClB,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,WAAW,EAAE,MAAM,CAAC,WAAW;aAChC;YAED,8BAAC,gBAAgB,OAAM,cAAoB,GAAI,CAC1B,CACxB,CAAC;IACJ,CAAC,CAAC;IAEF,wBAAwB,CAAC,WAAW,GAAG,yBAAyB,WAAW,GAAG,CAAC;IAE/E,OAAO,wBAAwB,CAAC;AAClC,CAAC","sourcesContent":["\"use client\";\nimport React, { useCallback, useEffect, useRef, useState } from \"react\";\nimport { TamboMessageProvider } from \"../hooks/use-current-message\";\nimport { TamboThreadMessage } from \"../model/generate-component-response\";\nimport { useTamboInteractable } from \"../providers/tambo-interactable-provider\";\nimport { SupportedSchema } from \"../schema\";\n\nexport interface InteractableConfig {\n componentName: string;\n description: string;\n propsSchema?: SupportedSchema;\n}\n\nexport interface WithTamboInteractableProps {\n interactableId?: string;\n onInteractableReady?: (id: string) => void;\n onPropsUpdate?: (newProps: Record<string, any>) => void;\n}\n\n/**\n * Higher-Order Component that makes any component interactable by tambo.\n * @param WrappedComponent - The component to make interactable\n * @param config - Configuration for the interactable component\n * @returns A new component that is automatically registered as interactable\n * @example\n * ```tsx\n * const MyInteractableNote = withTamboInteractable(MyNote, {\n * componentName: \"MyNote\",\n * description: \"A note component\",\n * propsSchema: z.object({\n * title: z.string(),\n * content: z.string(),\n * }),\n * });\n *\n * // Usage\n * <MyInteractableNote title=\"My Note\" content=\"This is my note\" />\n * ```\n */\nexport function withTamboInteractable<P extends object>(\n WrappedComponent: React.ComponentType<P>,\n config: InteractableConfig,\n) {\n const displayName =\n WrappedComponent.displayName ?? WrappedComponent.name ?? \"Component\";\n\n const TamboInteractableWrapper: React.FC<P & WithTamboInteractableProps> = (\n props,\n ) => {\n const {\n addInteractableComponent,\n updateInteractableComponentProps,\n getInteractableComponent,\n } = useTamboInteractable();\n\n const [interactableId, setInteractableId] = useState<string | null>(null);\n const isInitialized = useRef(false);\n const lastParentProps = useRef<Record<string, any>>({});\n\n // Extract interactable-specific props\n const { onInteractableReady, onPropsUpdate, ...componentProps } = props;\n\n // Get the current interactable component to track prop updates\n const currentInteractable = interactableId\n ? getInteractableComponent(interactableId)\n : null;\n\n // Use the props from the interactable component if available, otherwise use the passed props\n // We need to be careful not to create a loop, so we only use stored props if they're different from passed props\n const effectiveProps = currentInteractable?.props ?? componentProps;\n\n // Memoize the registration function\n const registerComponent = useCallback(() => {\n if (!isInitialized.current) {\n const id = addInteractableComponent({\n name: config.componentName,\n description: config.description,\n component: WrappedComponent,\n props: componentProps,\n propsSchema: config.propsSchema,\n });\n\n setInteractableId(id);\n onInteractableReady?.(id);\n isInitialized.current = true;\n }\n }, [addInteractableComponent, componentProps, onInteractableReady]);\n\n // Register the component as interactable on mount (only once)\n useEffect(() => {\n registerComponent();\n }, [registerComponent]);\n\n // Update the interactable component when props change from parent\n useEffect(() => {\n if (interactableId && isInitialized.current) {\n // Only update if the props are different from what we last sent\n const lastPropsString = JSON.stringify(lastParentProps.current);\n const currentPropsString = JSON.stringify(componentProps);\n\n if (lastPropsString !== currentPropsString) {\n updateInteractableComponentProps(interactableId, componentProps);\n onPropsUpdate?.(componentProps);\n lastParentProps.current = componentProps;\n }\n }\n }, [\n interactableId,\n componentProps,\n updateInteractableComponentProps,\n onPropsUpdate,\n ]);\n\n // If the interactable ID is not yet set, render the component without provider\n if (!interactableId) {\n return <WrappedComponent {...(effectiveProps as P)} />;\n }\n\n // Create a minimal message with interactable metadata\n // This allows useTamboCurrentComponent to work with standalone interactable components\n const minimalMessage: TamboThreadMessage = {\n id: interactableId,\n role: \"assistant\" as const,\n content: [],\n threadId: \"\",\n createdAt: new Date().toISOString(),\n component: {\n componentName: config.componentName,\n componentState: {},\n message: \"\",\n props: effectiveProps,\n },\n componentState: {},\n };\n\n // Wrap with TamboMessageProvider including interactable metadata\n return (\n <TamboMessageProvider\n message={minimalMessage}\n interactableMetadata={{\n id: interactableId,\n componentName: config.componentName,\n description: config.description,\n }}\n >\n <WrappedComponent {...(effectiveProps as P)} />\n </TamboMessageProvider>\n );\n };\n\n TamboInteractableWrapper.displayName = `withTamboInteractable(${displayName})`;\n\n return TamboInteractableWrapper;\n}\n"]}
@@ -1,6 +1,21 @@
1
1
  type StateUpdateResult<T> = [currentState: T, setState: (newState: T) => void];
2
2
  /**
3
- * Like useState, but syncs to the thread message's `componentState`.
3
+ * A React hook that acts like useState, but also automatically updates the thread message's componentState.
4
+ * If used within an interactable component (wrapped with withTamboInteractable), it updates the
5
+ * interactable provider's global state (sent to Tambo on every request) instead of the remote thread message state.
6
+ * For generated components, it updates both the local and remote thread message's componentState.
7
+ *
8
+ * Benefits: Passes user changes to AI, and when threads are returned, state is preserved.
9
+ * Works in both generative and interactable component contexts.
10
+ * @param keyName - The unique key to identify this state value within the message's componentState object
11
+ * @param initialValue - Optional initial value for the state, used if no componentState value exists in the Tambo message containing this hook usage.
12
+ * @param setFromProp - Optional value used to set the state value, only while no componentState value exists in the Tambo message containing this hook usage. Use this to allow streaming updates from a prop to the state value.
13
+ * @param debounceTime - Optional debounce time in milliseconds (default: 500ms) to limit API calls.
14
+ * @returns A tuple containing:
15
+ * - The current state value
16
+ * - A setter function to update the state (updates UI immediately, debounces server sync)
17
+ * @example
18
+ * const [count, setCount] = useTamboComponentState("counter", 0);
4
19
  *
5
20
  * Use `setFromProp` to seed state from streamed props. During streaming,
6
21
  * state updates as new prop values arrive. Once streaming completes,
@@ -1 +1 @@
1
- {"version":3,"file":"use-component-state.d.ts","sourceRoot":"","sources":["../../src/hooks/use-component-state.tsx"],"names":[],"mappings":"AAMA,KAAK,iBAAiB,CAAC,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,QAAQ,EAAE,CAAC,KAAK,IAAI,CAAC,CAAC;AAE/E;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,GAAG,SAAS,EAClD,OAAO,EAAE,MAAM,EACf,YAAY,CAAC,EAAE,CAAC,EAChB,WAAW,CAAC,EAAE,CAAC,EACf,YAAY,CAAC,EAAE,MAAM,GACpB,iBAAiB,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;AACpC,wBAAgB,sBAAsB,CAAC,CAAC,EACtC,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,CAAC,EACf,WAAW,CAAC,EAAE,CAAC,EACf,YAAY,CAAC,EAAE,MAAM,GACpB,iBAAiB,CAAC,CAAC,CAAC,CAAC"}
1
+ {"version":3,"file":"use-component-state.d.ts","sourceRoot":"","sources":["../../src/hooks/use-component-state.tsx"],"names":[],"mappings":"AAOA,KAAK,iBAAiB,CAAC,CAAC,IAAI,CAAC,YAAY,EAAE,CAAC,EAAE,QAAQ,EAAE,CAAC,QAAQ,EAAE,CAAC,KAAK,IAAI,CAAC,CAAC;AAE/E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,sBAAsB,CAAC,CAAC,GAAG,SAAS,EAClD,OAAO,EAAE,MAAM,EACf,YAAY,CAAC,EAAE,CAAC,EAChB,WAAW,CAAC,EAAE,CAAC,EACf,YAAY,CAAC,EAAE,MAAM,GACpB,iBAAiB,CAAC,CAAC,GAAG,SAAS,CAAC,CAAC;AACpC,wBAAgB,sBAAsB,CAAC,CAAC,EACtC,OAAO,EAAE,MAAM,EACf,YAAY,EAAE,CAAC,EACf,WAAW,CAAC,EAAE,CAAC,EACf,YAAY,CAAC,EAAE,MAAM,GACpB,iBAAiB,CAAC,CAAC,CAAC,CAAC"}
@@ -5,16 +5,26 @@ exports.useTamboComponentState = useTamboComponentState;
5
5
  const react_1 = require("react");
6
6
  const use_debounce_1 = require("use-debounce");
7
7
  const __1 = require("..");
8
+ const tambo_interactable_provider_1 = require("../providers/tambo-interactable-provider");
8
9
  const use_current_message_1 = require("./use-current-message");
9
10
  function useTamboComponentState(keyName, initialValue, setFromProp, debounceTime = 500) {
10
- const message = (0, use_current_message_1.useTamboCurrentMessage)();
11
+ const message = (0, react_1.useContext)(use_current_message_1.TamboMessageContext);
11
12
  const { updateThreadMessage } = (0, __1.useTamboThread)();
12
13
  const client = (0, __1.useTamboClient)();
14
+ const componentId = message?.interactableMetadata?.id ?? null;
15
+ const { setInteractableState, getInteractableComponentState } = (0, tambo_interactable_provider_1.useTamboInteractable)();
13
16
  const messageState = message?.componentState?.[keyName];
14
- const [localState, setLocalState] = (0, react_1.useState)(messageState ?? initialValue);
17
+ const interactableState = componentId
18
+ ? getInteractableComponentState(componentId)?.[keyName]
19
+ : undefined;
20
+ const initialState = interactableState ?? messageState ?? initialValue;
21
+ const [localState, setLocalState] = (0, react_1.useState)(initialState);
15
22
  const [initializedFromThreadMessage, setInitializedFromThreadMessage] = (0, react_1.useState)(messageState ? true : false);
16
23
  // Optimistically update the local thread message's componentState
17
24
  const updateLocalThreadMessage = (0, react_1.useCallback)(async (newState, existingMessage) => {
25
+ if (!existingMessage) {
26
+ return;
27
+ }
18
28
  const updatedMessage = {
19
29
  threadId: existingMessage.threadId,
20
30
  componentState: {
@@ -26,6 +36,9 @@ function useTamboComponentState(keyName, initialValue, setFromProp, debounceTime
26
36
  }, [updateThreadMessage, keyName]);
27
37
  // Debounced callback to update the remote thread message's componentState
28
38
  const updateRemoteThreadMessage = (0, use_debounce_1.useDebouncedCallback)(async (newState, existingMessage) => {
39
+ if (!existingMessage) {
40
+ return;
41
+ }
29
42
  await client.beta.threads.messages.updateComponentState(existingMessage.id, {
30
43
  id: existingMessage.threadId,
31
44
  state: { [keyName]: newState },
@@ -33,26 +46,73 @@ function useTamboComponentState(keyName, initialValue, setFromProp, debounceTime
33
46
  }, debounceTime);
34
47
  const setValue = (0, react_1.useCallback)((newState) => {
35
48
  setLocalState(newState);
36
- void updateLocalThreadMessage(newState, message);
37
- void updateRemoteThreadMessage(newState, message);
38
- }, [message, updateLocalThreadMessage, updateRemoteThreadMessage]);
39
- // Mirror the thread message's componentState value to the local state
49
+ if (componentId) {
50
+ // For interactable components, update the interactable provider's state
51
+ setInteractableState(componentId, keyName, newState);
52
+ }
53
+ else if (message) {
54
+ // For generated components, update both local and remote thread message state
55
+ void updateLocalThreadMessage(newState, message);
56
+ void updateRemoteThreadMessage(newState, message);
57
+ }
58
+ }, [
59
+ message,
60
+ updateLocalThreadMessage,
61
+ updateRemoteThreadMessage,
62
+ setInteractableState,
63
+ componentId,
64
+ keyName,
65
+ ]);
66
+ const existingInteractableState = componentId
67
+ ? getInteractableComponentState(componentId)?.[keyName]
68
+ : undefined;
69
+ const shouldUpdateInteractableInitial = !!componentId &&
70
+ existingInteractableState === undefined &&
71
+ initialValue !== undefined;
72
+ // Set initial value in interactable state if we're in an interactable context and there's no existing state
40
73
  (0, react_1.useEffect)(() => {
41
- const messageState = message?.componentState?.[keyName];
42
- if (!messageState) {
74
+ if (!shouldUpdateInteractableInitial) {
75
+ return;
76
+ }
77
+ setInteractableState(componentId, keyName, initialValue);
78
+ }, [
79
+ shouldUpdateInteractableInitial,
80
+ componentId,
81
+ keyName,
82
+ initialValue,
83
+ setInteractableState,
84
+ ]);
85
+ const shouldSyncFromMessage = !!message && messageState !== undefined && messageState !== null;
86
+ // Mirror the thread message's componentState value to the local state and interactable state
87
+ (0, react_1.useEffect)(() => {
88
+ if (!shouldSyncFromMessage) {
43
89
  return;
44
90
  }
45
91
  setInitializedFromThreadMessage(true);
46
- setLocalState(message.componentState?.[keyName]);
47
- }, [message?.componentState?.[keyName], message, keyName]);
92
+ const stateValue = messageState;
93
+ setLocalState(stateValue);
94
+ if (componentId) {
95
+ setInteractableState(componentId, keyName, stateValue);
96
+ }
97
+ }, [
98
+ shouldSyncFromMessage,
99
+ messageState,
100
+ keyName,
101
+ setInteractableState,
102
+ componentId,
103
+ ]);
48
104
  // For editable fields that are set from a prop to allow streaming updates, don't overwrite a fetched state value set from the thread message with prop value on initial load.
49
105
  (0, react_1.useEffect)(() => {
50
106
  if (setFromProp !== undefined && !initializedFromThreadMessage) {
51
107
  setLocalState(setFromProp);
52
108
  }
53
109
  }, [setFromProp, initializedFromThreadMessage]);
54
- // Ensure pending changes are flushed on unmount
110
+ // Ensure pending changes are flushed on unmount (only for generated components)
55
111
  (0, react_1.useEffect)(() => {
112
+ // Only flush remote updates for generated components, not interactable components
113
+ if (componentId) {
114
+ return;
115
+ }
56
116
  return () => {
57
117
  async function flushUpdates() {
58
118
  try {
@@ -65,7 +125,7 @@ function useTamboComponentState(keyName, initialValue, setFromProp, debounceTime
65
125
  // Fire-and-forget cleanup (errors handled inside)
66
126
  void flushUpdates();
67
127
  };
68
- }, [updateRemoteThreadMessage]);
128
+ }, [updateRemoteThreadMessage, componentId]);
69
129
  return [localState, setValue];
70
130
  }
71
131
  //# sourceMappingURL=use-component-state.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"use-component-state.js","sourceRoot":"","sources":["../../src/hooks/use-component-state.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;AAmCb,wDA0FC;AA5HD,iCAAyD;AACzD,+CAAoD;AACpD,0BAAwE;AACxE,+DAA+D;AA+B/D,SAAgB,sBAAsB,CACpC,OAAe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jD,KAAK,CACN,CAAC;gBACJ,CAAC;YACH,CAAC;YACD,kDAAkD;YAClD,KAAK,YAAY,EAAE,CAAC;QACtB,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,yBAAyB,CAAC,CAAC,CAAC;IAEhC,OAAO,CAAC,UAAe,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC","sourcesContent":["\"use client\";\nimport { useCallback, useEffect, useState } from \"react\";\nimport { useDebouncedCallback } from \"use-debounce\";\nimport { TamboThreadMessage, useTamboClient, useTamboThread } from \"..\";\nimport { useTamboCurrentMessage } from \"./use-current-message\";\n\ntype StateUpdateResult<T> = [currentState: T, setState: (newState: T) => void];\n\n/**\n * Like useState, but syncs to the thread message's `componentState`.\n *\n * Use `setFromProp` to seed state from streamed props. During streaming,\n * state updates as new prop values arrive. Once streaming completes,\n * user edits take precedence over the original prop value.\n *\n * Pair with `useTamboStreamStatus` to disable inputs while streaming.\n * @see {@link https://docs.tambo.co/concepts/streaming/streaming-best-practices}\n * @param keyName - Unique key within the message's componentState\n * @param initialValue - Default value if no componentState exists\n * @param setFromProp - Seeds state from props (updates during streaming, then user edits take over)\n * @param debounceTime - Server sync debounce in ms (default: 500)\n * @returns A tuple of [currentState, setState] similar to React's useState\n */\nexport function useTamboComponentState<S = undefined>(\n keyName: string,\n initialValue?: S,\n setFromProp?: S,\n debounceTime?: number,\n): StateUpdateResult<S | undefined>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue: S,\n setFromProp?: S,\n debounceTime?: number,\n): StateUpdateResult<S>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue?: S,\n setFromProp?: S,\n debounceTime = 500,\n): StateUpdateResult<S> {\n const message = useTamboCurrentMessage();\n const { updateThreadMessage } = useTamboThread();\n const client = useTamboClient();\n const messageState = message?.componentState?.[keyName];\n const [localState, setLocalState] = useState<S | undefined>(\n (messageState as S) ?? initialValue,\n );\n const [initializedFromThreadMessage, setInitializedFromThreadMessage] =\n useState(messageState ? true : false);\n\n // Optimistically update the local thread message's componentState\n const updateLocalThreadMessage = useCallback(\n async (newState: S, existingMessage: TamboThreadMessage) => {\n const updatedMessage = {\n threadId: existingMessage.threadId,\n componentState: {\n ...existingMessage.componentState,\n [keyName]: newState,\n },\n };\n await updateThreadMessage(existingMessage.id, updatedMessage, false);\n },\n [updateThreadMessage, keyName],\n );\n\n // Debounced callback to update the remote thread message's componentState\n const updateRemoteThreadMessage = useDebouncedCallback(\n async (newState: S, existingMessage: TamboThreadMessage) => {\n await client.beta.threads.messages.updateComponentState(\n existingMessage.id,\n {\n id: existingMessage.threadId,\n state: { [keyName]: newState },\n },\n );\n },\n debounceTime,\n );\n\n const setValue = useCallback(\n (newState: S) => {\n setLocalState(newState);\n void updateLocalThreadMessage(newState, message);\n void updateRemoteThreadMessage(newState, message);\n },\n [message, updateLocalThreadMessage, updateRemoteThreadMessage],\n );\n\n // Mirror the thread message's componentState value to the local state\n useEffect(() => {\n const messageState = message?.componentState?.[keyName];\n if (!messageState) {\n return;\n }\n setInitializedFromThreadMessage(true);\n setLocalState(message.componentState?.[keyName] as S);\n }, [message?.componentState?.[keyName], message, keyName]);\n\n // For editable fields that are set from a prop to allow streaming updates, don't overwrite a fetched state value set from the thread message with prop value on initial load.\n useEffect(() => {\n if (setFromProp !== undefined && !initializedFromThreadMessage) {\n setLocalState(setFromProp as S);\n }\n }, [setFromProp, initializedFromThreadMessage]);\n\n // Ensure pending changes are flushed on unmount\n useEffect(() => {\n return () => {\n async function flushUpdates() {\n try {\n await updateRemoteThreadMessage.flush();\n } catch (error) {\n console.error(\n \"Failed to flush pending thread message updates:\",\n error,\n );\n }\n }\n // Fire-and-forget cleanup (errors handled inside)\n void flushUpdates();\n };\n }, [updateRemoteThreadMessage]);\n\n return [localState as S, setValue];\n}\n"]}
1
+ {"version":3,"file":"use-component-state.js","sourceRoot":"","sources":["../../src/hooks/use-component-state.tsx"],"names":[],"mappings":";AAAA,YAAY,CAAC;;AAmDb,wDAyJC;AA3MD,i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F,IAAI,WAAW,EAAE,CAAC;YAChB,OAAO;QACT,CAAC;QACD,OAAO,GAAG,EAAE;YACV,KAAK,UAAU,YAAY;gBACzB,IAAI,CAAC;oBACH,MAAM,yBAAyB,CAAC,KAAK,EAAE,CAAC;gBAC1C,CAAC;gBAAC,OAAO,KAAK,EAAE,CAAC;oBACf,OAAO,CAAC,KAAK,CACX,iDAAiD,EACjD,KAAK,CACN,CAAC;gBACJ,CAAC;YACH,CAAC;YACD,kDAAkD;YAClD,KAAK,YAAY,EAAE,CAAC;QACtB,CAAC,CAAC;IACJ,CAAC,EAAE,CAAC,yBAAyB,EAAE,WAAW,CAAC,CAAC,CAAC;IAE7C,OAAO,CAAC,UAAe,EAAE,QAAQ,CAAC,CAAC;AACrC,CAAC","sourcesContent":["\"use client\";\nimport { useCallback, useContext, useEffect, useState } from \"react\";\nimport { useDebouncedCallback } from \"use-debounce\";\nimport { TamboThreadMessage, useTamboClient, useTamboThread } from \"..\";\nimport { useTamboInteractable } from \"../providers/tambo-interactable-provider\";\nimport { TamboMessageContext } from \"./use-current-message\";\n\ntype StateUpdateResult<T> = [currentState: T, setState: (newState: T) => void];\n\n/**\n * A React hook that acts like useState, but also automatically updates the thread message's componentState.\n * If used within an interactable component (wrapped with withTamboInteractable), it updates the\n * interactable provider's global state (sent to Tambo on every request) instead of the remote thread message state.\n * For generated components, it updates both the local and remote thread message's componentState.\n *\n * Benefits: Passes user changes to AI, and when threads are returned, state is preserved.\n * Works in both generative and interactable component contexts.\n * @param keyName - The unique key to identify this state value within the message's componentState object\n * @param initialValue - Optional initial value for the state, used if no componentState value exists in the Tambo message containing this hook usage.\n * @param setFromProp - Optional value used to set the state value, only while no componentState value exists in the Tambo message containing this hook usage. Use this to allow streaming updates from a prop to the state value.\n * @param debounceTime - Optional debounce time in milliseconds (default: 500ms) to limit API calls.\n * @returns A tuple containing:\n * - The current state value\n * - A setter function to update the state (updates UI immediately, debounces server sync)\n * @example\n * const [count, setCount] = useTamboComponentState(\"counter\", 0);\n *\n * Use `setFromProp` to seed state from streamed props. During streaming,\n * state updates as new prop values arrive. Once streaming completes,\n * user edits take precedence over the original prop value.\n *\n * Pair with `useTamboStreamStatus` to disable inputs while streaming.\n * @see {@link https://docs.tambo.co/concepts/streaming/streaming-best-practices}\n * @param keyName - Unique key within the message's componentState\n * @param initialValue - Default value if no componentState exists\n * @param setFromProp - Seeds state from props (updates during streaming, then user edits take over)\n * @param debounceTime - Server sync debounce in ms (default: 500)\n * @returns A tuple of [currentState, setState] similar to React's useState\n */\nexport function useTamboComponentState<S = undefined>(\n keyName: string,\n initialValue?: S,\n setFromProp?: S,\n debounceTime?: number,\n): StateUpdateResult<S | undefined>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue: S,\n setFromProp?: S,\n debounceTime?: number,\n): StateUpdateResult<S>;\nexport function useTamboComponentState<S>(\n keyName: string,\n initialValue?: S,\n setFromProp?: S,\n debounceTime = 500,\n): StateUpdateResult<S> {\n const message = useContext(TamboMessageContext);\n const { updateThreadMessage } = useTamboThread();\n const client = useTamboClient();\n const componentId = message?.interactableMetadata?.id ?? null;\n const { setInteractableState, getInteractableComponentState } =\n useTamboInteractable();\n const messageState = message?.componentState?.[keyName];\n const interactableState = componentId\n ? getInteractableComponentState(componentId)?.[keyName]\n : undefined;\n const initialState =\n (interactableState as S) ?? (messageState as S) ?? initialValue;\n const [localState, setLocalState] = useState<S | undefined>(initialState);\n const [initializedFromThreadMessage, setInitializedFromThreadMessage] =\n useState(messageState ? true : false);\n\n // Optimistically update the local thread message's componentState\n const updateLocalThreadMessage = useCallback(\n async (newState: S, existingMessage: TamboThreadMessage | null) => {\n if (!existingMessage) {\n return;\n }\n const updatedMessage = {\n threadId: existingMessage.threadId,\n componentState: {\n ...existingMessage.componentState,\n [keyName]: newState,\n },\n };\n await updateThreadMessage(existingMessage.id, updatedMessage, false);\n },\n [updateThreadMessage, keyName],\n );\n\n // Debounced callback to update the remote thread message's componentState\n const updateRemoteThreadMessage = useDebouncedCallback(\n async (newState: S, existingMessage: TamboThreadMessage | null) => {\n if (!existingMessage) {\n return;\n }\n await client.beta.threads.messages.updateComponentState(\n existingMessage.id,\n {\n id: existingMessage.threadId,\n state: { [keyName]: newState },\n },\n );\n },\n debounceTime,\n );\n\n const setValue = useCallback(\n (newState: S) => {\n setLocalState(newState);\n if (componentId) {\n // For interactable components, update the interactable provider's state\n setInteractableState(componentId, keyName, newState);\n } else if (message) {\n // For generated components, update both local and remote thread message state\n void updateLocalThreadMessage(newState, message);\n void updateRemoteThreadMessage(newState, message);\n }\n },\n [\n message,\n updateLocalThreadMessage,\n updateRemoteThreadMessage,\n setInteractableState,\n componentId,\n keyName,\n ],\n );\n\n const existingInteractableState = componentId\n ? getInteractableComponentState(componentId)?.[keyName]\n : undefined;\n const shouldUpdateInteractableInitial =\n !!componentId &&\n existingInteractableState === undefined &&\n initialValue !== undefined;\n\n // Set initial value in interactable state if we're in an interactable context and there's no existing state\n useEffect(() => {\n if (!shouldUpdateInteractableInitial) {\n return;\n }\n setInteractableState(componentId, keyName, initialValue!);\n }, [\n shouldUpdateInteractableInitial,\n componentId,\n keyName,\n initialValue,\n setInteractableState,\n ]);\n\n const shouldSyncFromMessage =\n !!message && messageState !== undefined && messageState !== null;\n\n // Mirror the thread message's componentState value to the local state and interactable state\n useEffect(() => {\n if (!shouldSyncFromMessage) {\n return;\n }\n setInitializedFromThreadMessage(true);\n const stateValue = messageState as S;\n setLocalState(stateValue);\n if (componentId) {\n setInteractableState(componentId, keyName, stateValue);\n }\n }, [\n shouldSyncFromMessage,\n messageState,\n keyName,\n setInteractableState,\n componentId,\n ]);\n\n // For editable fields that are set from a prop to allow streaming updates, don't overwrite a fetched state value set from the thread message with prop value on initial load.\n useEffect(() => {\n if (setFromProp !== undefined && !initializedFromThreadMessage) {\n setLocalState(setFromProp as S);\n }\n }, [setFromProp, initializedFromThreadMessage]);\n\n // Ensure pending changes are flushed on unmount (only for generated components)\n useEffect(() => {\n // Only flush remote updates for generated components, not interactable components\n if (componentId) {\n return;\n }\n return () => {\n async function flushUpdates() {\n try {\n await updateRemoteThreadMessage.flush();\n } catch (error) {\n console.error(\n \"Failed to flush pending thread message updates:\",\n error,\n );\n }\n }\n // Fire-and-forget cleanup (errors handled inside)\n void flushUpdates();\n };\n }, [updateRemoteThreadMessage, componentId]);\n\n return [localState as S, setValue];\n}\n"]}
@@ -1,7 +1,12 @@
1
1
  "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
2
5
  Object.defineProperty(exports, "__esModule", { value: true });
3
6
  const react_1 = require("@testing-library/react");
7
+ const react_2 = __importDefault(require("react"));
4
8
  const tambo_client_provider_1 = require("../providers/tambo-client-provider");
9
+ const tambo_interactable_provider_1 = require("../providers/tambo-interactable-provider");
5
10
  const tambo_thread_provider_1 = require("../providers/tambo-thread-provider");
6
11
  const use_component_state_1 = require("./use-component-state");
7
12
  const use_current_message_1 = require("./use-current-message");
@@ -14,6 +19,10 @@ jest.mock("../providers/tambo-thread-provider", () => ({
14
19
  }));
15
20
  jest.mock("./use-current-message", () => ({
16
21
  useTamboCurrentMessage: jest.fn(),
22
+ TamboMessageContext: react_2.default.createContext(null),
23
+ }));
24
+ jest.mock("../providers/tambo-interactable-provider", () => ({
25
+ useTamboInteractable: jest.fn(),
17
26
  }));
18
27
  // Create a mock debounced function with flush method
19
28
  const createMockDebouncedFunction = (fn) => {
@@ -42,8 +51,34 @@ describe("useTamboComponentState", () => {
42
51
  });
43
52
  const mockUpdateThreadMessage = jest.fn();
44
53
  const mockUpdateComponentState = jest.fn();
54
+ const mockSetInteractableState = jest.fn();
55
+ const mockGetInteractableComponentState = jest.fn();
56
+ // Track context values for mocking
57
+ let mockMessage = null;
45
58
  beforeEach(() => {
46
59
  jest.clearAllMocks();
60
+ // Reset context values
61
+ mockMessage = createMockMessage();
62
+ // Mock useContext to return appropriate values based on context
63
+ const originalUseContext = react_2.default.useContext;
64
+ jest.spyOn(react_2.default, "useContext").mockImplementation((context) => {
65
+ if (context === use_current_message_1.TamboMessageContext) {
66
+ // Return the message from useTamboCurrentMessage mock if available
67
+ try {
68
+ const currentMessageMock = jest.mocked(use_current_message_1.useTamboCurrentMessage);
69
+ const mockImpl = currentMessageMock.getMockImplementation();
70
+ if (mockImpl) {
71
+ return mockImpl();
72
+ }
73
+ }
74
+ catch {
75
+ // Fallback to mockMessage
76
+ }
77
+ return mockMessage;
78
+ }
79
+ // For other contexts, use the original implementation
80
+ return originalUseContext(context);
81
+ });
47
82
  // Setup default mock for useDebouncedCallback
48
83
  jest
49
84
  .mocked(use_debounce_1.useDebouncedCallback)
@@ -62,6 +97,13 @@ describe("useTamboComponentState", () => {
62
97
  updateThreadMessage: mockUpdateThreadMessage,
63
98
  });
64
99
  jest.mocked(use_current_message_1.useTamboCurrentMessage).mockReturnValue(createMockMessage());
100
+ jest.mocked(tambo_interactable_provider_1.useTamboInteractable).mockReturnValue({
101
+ setInteractableState: mockSetInteractableState,
102
+ getInteractableComponentState: mockGetInteractableComponentState,
103
+ });
104
+ });
105
+ afterEach(() => {
106
+ jest.restoreAllMocks();
65
107
  });
66
108
  describe("Initial State Management", () => {
67
109
  it("should initialize with initialValue when no componentState exists", () => {
@@ -1 +1 @@
1
- {"version":3,"file":"use-component-state.test.js","sourceRoot":"","sources":["../../src/hooks/use-component-state.test.tsx"],"names":[],"mappings":";;AAAA,kDAAyD;AAEzD,8EAAoE;AACpE,8EAAoE;AAEpE,+DAA+D;AAC/D,+DAA+D;AAE/D,8BAA8B;AAC9B,IAAI,CAAC,IAAI,CAAC,oCAAoC,EAAE,GAAG,EAAE,CAAC,CAAC;IACrD,cAAc,EAAE,IAAI,CAAC,EAAE,EAAE;CAC1B,CAAC,CAAC,CAAC;AAEJ,IAAI,CAAC,IAAI,CAAC,oCAAoC,EAAE,GAAG,EAAE,CAAC,CAAC;IACrD,cAAc,EAAE,IAAI,CAAC,EAAE,EAAE;CAC1B,CAAC,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EAAE,QAAQ,EAAE,GAAG,IAAA,kBAAU,EACrC,CAAC,EAAE,OAAO,EAAE,EAAE,EAAE;gBACd,IAAI,CAAC,MAAM,CAAC,4CAAsB,CAAC,CAAC,eAAe,CAAC,OAAO,CAAC,CAAC;gBAC7D,OAAO,IAAA,4CAAsB,EAAC,SAAS,EAAE,SAAS,CAAC,CAAC;YACtD,CAAC,EACD,EAAE,YAAY,EAAE,EAAE,OAAO,EAAE,QAAQ,EAAE,EAAE,CACxC,CAAC;YAEF,uBAAuB;YACvB,uBAAuB,CAAC,SAAS,EAAE,CAAC;YAEpC,oDAAoD;YACpD,QAAQ,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;YAEhC,wCAAwC;YACxC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { act, renderHook } from \"@testing-library/react\";\nimport { TamboThreadMessage } from \"../model/generate-component-response\";\nimport { useTamboClient } from \"../providers/tambo-client-provider\";\nimport { useTamboThread } from \"../providers/tambo-thread-provider\";\nimport { PartialTamboAI } from \"../testing/types\";\nimport { useTamboComponentState } from \"./use-component-state\";\nimport { useTamboCurrentMessage } from \"./use-current-message\";\n\n// Mock the required providers\njest.mock(\"../providers/tambo-client-provider\", () => ({\n useTamboClient: jest.fn(),\n}));\n\njest.mock(\"../providers/tambo-thread-provider\", () => ({\n useTamboThread: jest.fn(),\n}));\n\njest.mock(\"./use-current-message\", () => ({\n useTamboCurrentMessage: jest.fn(),\n}));\n\n// Create a mock debounced function with flush method\nconst createMockDebouncedFunction = (fn: any) => {\n const debouncedFn = jest.fn((...args: any[]) => fn(...args)) as jest.Mock & {\n flush: jest.Mock;\n cancel: jest.Mock;\n isPending: () => boolean;\n };\n debouncedFn.flush = jest.fn();\n debouncedFn.cancel = jest.fn();\n debouncedFn.isPending = jest.fn(() => false);\n return debouncedFn;\n};\n\n// Mock use-debounce\njest.mock(\"use-debounce\", () => ({\n useDebouncedCallback: jest.fn(),\n}));\n\n// Import the mocked useDebouncedCallback\nimport { useDebouncedCallback } from \"use-debounce\";\n\ndescribe(\"useTamboComponentState\", () => {\n // Helper function to create mock TamboThreadMessage\n const createMockMessage = (\n overrides: Partial<TamboThreadMessage> = {},\n ): TamboThreadMessage => ({\n id: \"test-message-id\",\n threadId: \"test-thread-id\",\n componentState: {},\n content: [{ type: \"text\", text: \"Test message\" }],\n createdAt: new Date().toISOString(),\n role: \"assistant\",\n ...overrides,\n });\n\n const mockUpdateThreadMessage = jest.fn();\n const mockUpdateComponentState = jest.fn();\n\n beforeEach(() => {\n jest.clearAllMocks();\n\n // Setup default mock for useDebouncedCallback\n jest\n .mocked(useDebouncedCallback)\n .mockImplementation((fn) => createMockDebouncedFunction(fn));\n\n // Setup default mocks\n jest.mocked(useTamboClient).mockReturnValue({\n beta: {\n threads: {\n messages: {\n updateComponentState: mockUpdateComponentState,\n },\n },\n },\n } satisfies PartialTamboAI as any);\n\n jest.mocked(useTamboThread).mockReturnValue({\n updateThreadMessage: mockUpdateThreadMessage,\n } as any);\n\n jest.mocked(useTamboCurrentMessage).mockReturnValue(createMockMessage());\n });\n\n describe(\"Initial State Management\", () => {\n it(\"should initialize with initialValue when no componentState exists\", () => {\n const initialValue = \"test-initial\";\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(createMockMessage({ componentState: {} }));\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", initialValue),\n );\n\n expect(result.current[0]).toBe(initialValue);\n });\n\n it(\"should use existing componentState value over initialValue\", () => {\n const initialValue = \"initial\";\n const existingValue = \"existing\";\n jest.mocked(useTamboCurrentMessage).mockReturnValue(\n createMockMessage({\n componentState: { testKey: existingValue },\n }),\n );\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", initialValue),\n );\n\n expect(result.current[0]).toBe(existingValue);\n });\n\n it(\"should handle undefined initialValue gracefully\", () => {\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(createMockMessage({ componentState: {} }));\n\n const { result } = renderHook(() => useTamboComponentState(\"testKey\"));\n\n expect(result.current[0]).toBeUndefined();\n });\n\n it(\"should handle different data types correctly\", () => {\n const testCases = [\n { value: \"string\" },\n { value: 42 },\n { value: true },\n { value: { name: \"test\" } },\n { value: [1, 2, 3] },\n ];\n\n testCases.forEach(({ value }) => {\n jest.mocked(useTamboCurrentMessage).mockReturnValue(\n createMockMessage({\n componentState: { testKey: value },\n }),\n );\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", value),\n );\n\n expect(result.current[0]).toEqual(value);\n });\n });\n });\n\n describe(\"State Updates\", () => {\n it(\"should update local state immediately when setValue is called\", () => {\n const initialValue = \"initial\";\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(\n createMockMessage({ componentState: { testKey: initialValue } }),\n );\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", initialValue),\n );\n\n const newValue = \"updated\";\n act(() => {\n result.current[1](newValue);\n });\n\n expect(result.current[0]).toBe(newValue);\n });\n\n it(\"should trigger local thread message update when setValue is called\", () => {\n const message = createMockMessage({\n componentState: { testKey: \"initial\" },\n });\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\"),\n );\n\n const newValue = \"updated\";\n act(() => {\n result.current[1](newValue);\n });\n\n expect(mockUpdateThreadMessage).toHaveBeenCalledWith(\n message.id,\n {\n threadId: message.threadId,\n componentState: {\n testKey: newValue,\n },\n },\n false,\n );\n });\n\n it(\"should trigger debounced remote API call when setValue is called\", () => {\n const message = createMockMessage({\n componentState: { testKey: \"initial\" },\n });\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\"),\n );\n\n const newValue = \"updated\";\n act(() => {\n result.current[1](newValue);\n });\n\n // The debounced function should be called\n expect(mockUpdateComponentState).toHaveBeenCalledWith(message.id, {\n id: message.threadId,\n state: { testKey: newValue },\n });\n });\n\n it(\"should work with complex objects and arrays\", () => {\n const initialValue = { name: \"test\", items: [1, 2, 3] };\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(\n createMockMessage({ componentState: { testKey: initialValue } }),\n );\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", initialValue),\n );\n\n const newValue = { name: \"updated\", items: [4, 5, 6] };\n act(() => {\n result.current[1](newValue);\n });\n\n expect(result.current[0]).toEqual(newValue);\n expect(mockUpdateThreadMessage).toHaveBeenCalledWith(\n expect.any(String),\n expect.objectContaining({\n componentState: {\n testKey: newValue,\n },\n }),\n false,\n );\n });\n });\n\n describe(\"Debouncing Behavior\", () => {\n it(\"should use default debounce time of 500ms\", () => {\n renderHook(() => useTamboComponentState(\"testKey\", \"initial\"));\n\n expect(useDebouncedCallback).toHaveBeenCalledWith(\n expect.any(Function),\n 500,\n );\n });\n\n it(\"should use custom debounce time when provided\", () => {\n const customDebounceTime = 1000;\n\n renderHook(() =>\n useTamboComponentState(\n \"testKey\",\n \"initial\",\n undefined,\n customDebounceTime,\n ),\n );\n\n expect(useDebouncedCallback).toHaveBeenCalledWith(\n expect.any(Function),\n customDebounceTime,\n );\n });\n\n it(\"should flush debounced callback on unmount\", () => {\n const mockFlush = jest.fn();\n const mockDebouncedFn = createMockDebouncedFunction(jest.fn());\n mockDebouncedFn.flush = mockFlush;\n\n // Mock the debounced callback to return our specific mock\n jest.mocked(useDebouncedCallback).mockReturnValue(mockDebouncedFn);\n\n const { unmount } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\"),\n );\n\n unmount();\n\n expect(mockFlush).toHaveBeenCalled();\n });\n });\n\n describe(\"Multi-Hook Scenarios\", () => {\n it(\"should handle multiple hooks with different keyNames independently\", () => {\n const message = createMockMessage({\n componentState: {\n key1: \"value1\",\n key2: \"value2\",\n },\n });\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n\n const { result: result1 } = renderHook(() =>\n useTamboComponentState(\"key1\", \"default1\"),\n );\n const { result: result2 } = renderHook(() =>\n useTamboComponentState(\"key2\", \"default2\"),\n );\n\n expect(result1.current[0]).toBe(\"value1\");\n expect(result2.current[0]).toBe(\"value2\");\n\n // Update first hook\n act(() => {\n result1.current[1](\"updated1\");\n });\n\n expect(result1.current[0]).toBe(\"updated1\");\n expect(result2.current[0]).toBe(\"value2\"); // Should remain unchanged\n });\n\n it(\"should preserve existing componentState when updating another key\", () => {\n const message = createMockMessage({\n componentState: {\n existingKey: \"existing\",\n testKey: \"initial\",\n },\n });\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\"),\n );\n\n act(() => {\n result.current[1](\"updated\");\n });\n\n expect(mockUpdateThreadMessage).toHaveBeenCalledWith(\n message.id,\n {\n threadId: message.threadId,\n componentState: {\n existingKey: \"existing\", // Should preserve existing keys\n testKey: \"updated\",\n },\n },\n false,\n );\n });\n });\n\n describe(\"SetFromProp Feature\", () => {\n it(\"should set value from prop when hasSetFromMessage is false\", () => {\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(createMockMessage({ componentState: {} }));\n\n const propValue = \"from-prop\";\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\", propValue),\n );\n\n // Initially, hasSetFromMessage should be false, so prop value should be used\n expect(result.current[0]).toBe(propValue);\n });\n\n it(\"should ignore setFromProp when initialized from message state\", async () => {\n const existingValue = \"existing\";\n jest.mocked(useTamboCurrentMessage).mockReturnValue(\n createMockMessage({\n componentState: { testKey: existingValue },\n }),\n );\n\n const propValue = \"from-prop\";\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\", propValue),\n );\n\n // Should use existing value from message, not prop value\n await act(async () => {\n await new Promise((resolve) => setTimeout(resolve, 0));\n });\n\n expect(result.current[0]).toBe(existingValue);\n });\n\n it(\"should update state from setFromProp changes when no message state exists\", () => {\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(createMockMessage({ componentState: {} }));\n\n const { result, rerender } = renderHook(\n ({ propValue }) =>\n useTamboComponentState(\"testKey\", \"initial\", propValue),\n { initialProps: { propValue: \"prop1\" } },\n );\n\n expect(result.current[0]).toBe(\"prop1\");\n\n // Change prop value\n rerender({ propValue: \"prop2\" });\n\n // Since hasSetFromMessage is still false (no message state),\n // it should update to new prop value\n expect(result.current[0]).toBe(\"prop2\");\n });\n\n it(\"should handle undefined setFromProp gracefully\", () => {\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(createMockMessage({ componentState: {} }));\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\", undefined),\n );\n\n expect(result.current[0]).toBe(\"initial\");\n });\n });\n\n describe(\"Message State Sync\", () => {\n it(\"should sync with message.componentState changes\", () => {\n const { result, rerender } = renderHook(\n ({ message }) => {\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n return useTamboComponentState(\"testKey\", \"initial\");\n },\n {\n initialProps: {\n message: createMockMessage({\n componentState: { testKey: \"value1\" },\n }),\n },\n },\n );\n\n // Change the message\n const newMessage = createMockMessage({\n componentState: { testKey: \"value2\" },\n });\n\n rerender({ message: newMessage });\n\n // The hook should sync with the new message state\n expect(result.current[0]).toBe(\"value2\");\n expect(mockUpdateThreadMessage).not.toHaveBeenCalled();\n });\n\n it(\"should handle message without componentState gracefully\", () => {\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(\n createMockMessage({ componentState: undefined as any }),\n );\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\"),\n );\n\n expect(result.current[0]).toBe(\"initial\");\n });\n\n it(\"should preserve state when message updates but componentState[keyName] unchanged\", () => {\n const message1 = createMockMessage({\n id: \"message1\",\n componentState: { testKey: \"unchanged\" },\n });\n const message2 = createMockMessage({\n id: \"message2\",\n componentState: { testKey: \"unchanged\" },\n });\n\n const { result, rerender } = renderHook(\n ({ message }) => {\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n return useTamboComponentState(\"testKey\", \"initial\");\n },\n { initialProps: { message: message1 } },\n );\n\n // Clear previous calls\n mockUpdateThreadMessage.mockClear();\n\n // Change message but keep same componentState value\n rerender({ message: message2 });\n\n // Should preserve the \"unchanged\" value\n expect(result.current[0]).toBe(\"unchanged\");\n });\n });\n});\n"]}
1
+ {"version":3,"file":"use-component-state.test.js","sourceRoot":"","sources":["../../src/hooks/use-component-state.test.tsx"],"names":[],"mappings":";;;;;AAAA,kDAAyD;AACzD,kDAA0B;AAE1B,8EAAoE;AACpE,0FAAgF;AAChF,8EAAoE;AAEpE,+DAA+D;AAC/D,+DAG+B;AAE/B,8BAA8B;AAC9B,IAAI,CAAC,IAAI,CAAC,oCAAoC,EAAE,GAAG,EAAE,CAAC,CAAC;IACrD,cAAc,EAAE,IAAI,CAAC,EAAE,EAAE;CAC1B,CAAC,CAAC,CAAC;AAEJ,IAAI,CAAC,IAAI,CAAC,oCAAoC,EAAE,GAAG,EAAE,CAAC,CAAC;IACrD,cAAc,EAAE,IAAI,CAAC,EAAE,EAAE;CAC1B,CAAC,CAAC,CAAC;AAEJ,IAAI,CAAC,IAAI,CAAC,uBAAuB,EAAE,GAAG,EAAE,CAAC,CAAC;IACxC,sBAAsB,EAAE,IAAI,CAAC,EAAE,EAAE;IACjC,mBAAmB,EAAE,eAAK,CAAC,aAAa,CAA4B,IAAI,CAAC;CAC1E,CAAC,CAAC,CAAC;AAEJ,IAAI,CAAC,IAAI,CAAC,0CAA0C,EAAE,GAAG,EAAE,CAAC,CAAC;IAC3D,oBAAoB,EAAE,IAAI,CAAC,EAAE,EAAE;CAChC,CAAC,CAAC,CAAC;AAEJ,qDAAqD;AACrD,MAAM,2BAA2B,GAAG,CAAC,EAAO,EAAE,EAAE;IAC9C,MAAM,WAAW,GAAG,IA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,CAAC,EAAE,OAAO,EAAE,QAAQ,EAAE,CAAC,CAAC;YAEhC,wCAAwC;YACxC,MAAM,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC;QAC9C,CAAC,CAAC,CAAC;IACL,CAAC,CAAC,CAAC;AACL,CAAC,CAAC,CAAC","sourcesContent":["import { act, renderHook } from \"@testing-library/react\";\nimport React from \"react\";\nimport { TamboThreadMessage } from \"../model/generate-component-response\";\nimport { useTamboClient } from \"../providers/tambo-client-provider\";\nimport { useTamboInteractable } from \"../providers/tambo-interactable-provider\";\nimport { useTamboThread } from \"../providers/tambo-thread-provider\";\nimport { PartialTamboAI } from \"../testing/types\";\nimport { useTamboComponentState } from \"./use-component-state\";\nimport {\n TamboMessageContext,\n useTamboCurrentMessage,\n} from \"./use-current-message\";\n\n// Mock the required providers\njest.mock(\"../providers/tambo-client-provider\", () => ({\n useTamboClient: jest.fn(),\n}));\n\njest.mock(\"../providers/tambo-thread-provider\", () => ({\n useTamboThread: jest.fn(),\n}));\n\njest.mock(\"./use-current-message\", () => ({\n useTamboCurrentMessage: jest.fn(),\n TamboMessageContext: React.createContext<TamboThreadMessage | null>(null),\n}));\n\njest.mock(\"../providers/tambo-interactable-provider\", () => ({\n useTamboInteractable: jest.fn(),\n}));\n\n// Create a mock debounced function with flush method\nconst createMockDebouncedFunction = (fn: any) => {\n const debouncedFn = jest.fn((...args: any[]) => fn(...args)) as jest.Mock & {\n flush: jest.Mock;\n cancel: jest.Mock;\n isPending: () => boolean;\n };\n debouncedFn.flush = jest.fn();\n debouncedFn.cancel = jest.fn();\n debouncedFn.isPending = jest.fn(() => false);\n return debouncedFn;\n};\n\n// Mock use-debounce\njest.mock(\"use-debounce\", () => ({\n useDebouncedCallback: jest.fn(),\n}));\n\n// Import the mocked useDebouncedCallback\nimport { useDebouncedCallback } from \"use-debounce\";\n\ndescribe(\"useTamboComponentState\", () => {\n // Helper function to create mock TamboThreadMessage\n const createMockMessage = (\n overrides: Partial<TamboThreadMessage> = {},\n ): TamboThreadMessage => ({\n id: \"test-message-id\",\n threadId: \"test-thread-id\",\n componentState: {},\n content: [{ type: \"text\", text: \"Test message\" }],\n createdAt: new Date().toISOString(),\n role: \"assistant\",\n ...overrides,\n });\n\n const mockUpdateThreadMessage = jest.fn();\n const mockUpdateComponentState = jest.fn();\n const mockSetInteractableState = jest.fn();\n const mockGetInteractableComponentState = jest.fn();\n\n // Track context values for mocking\n let mockMessage: TamboThreadMessage | null = null;\n\n beforeEach(() => {\n jest.clearAllMocks();\n\n // Reset context values\n mockMessage = createMockMessage();\n\n // Mock useContext to return appropriate values based on context\n const originalUseContext = React.useContext;\n jest.spyOn(React, \"useContext\").mockImplementation((context) => {\n if (context === TamboMessageContext) {\n // Return the message from useTamboCurrentMessage mock if available\n try {\n const currentMessageMock = jest.mocked(useTamboCurrentMessage);\n const mockImpl = currentMessageMock.getMockImplementation();\n if (mockImpl) {\n return mockImpl();\n }\n } catch {\n // Fallback to mockMessage\n }\n return mockMessage;\n }\n // For other contexts, use the original implementation\n return originalUseContext(context);\n });\n\n // Setup default mock for useDebouncedCallback\n jest\n .mocked(useDebouncedCallback)\n .mockImplementation((fn) => createMockDebouncedFunction(fn));\n\n // Setup default mocks\n jest.mocked(useTamboClient).mockReturnValue({\n beta: {\n threads: {\n messages: {\n updateComponentState: mockUpdateComponentState,\n },\n },\n },\n } satisfies PartialTamboAI as any);\n\n jest.mocked(useTamboThread).mockReturnValue({\n updateThreadMessage: mockUpdateThreadMessage,\n } as any);\n\n jest.mocked(useTamboCurrentMessage).mockReturnValue(createMockMessage());\n\n jest.mocked(useTamboInteractable).mockReturnValue({\n setInteractableState: mockSetInteractableState,\n getInteractableComponentState: mockGetInteractableComponentState,\n } as any);\n });\n\n afterEach(() => {\n jest.restoreAllMocks();\n });\n\n describe(\"Initial State Management\", () => {\n it(\"should initialize with initialValue when no componentState exists\", () => {\n const initialValue = \"test-initial\";\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(createMockMessage({ componentState: {} }));\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", initialValue),\n );\n\n expect(result.current[0]).toBe(initialValue);\n });\n\n it(\"should use existing componentState value over initialValue\", () => {\n const initialValue = \"initial\";\n const existingValue = \"existing\";\n jest.mocked(useTamboCurrentMessage).mockReturnValue(\n createMockMessage({\n componentState: { testKey: existingValue },\n }),\n );\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", initialValue),\n );\n\n expect(result.current[0]).toBe(existingValue);\n });\n\n it(\"should handle undefined initialValue gracefully\", () => {\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(createMockMessage({ componentState: {} }));\n\n const { result } = renderHook(() => useTamboComponentState(\"testKey\"));\n\n expect(result.current[0]).toBeUndefined();\n });\n\n it(\"should handle different data types correctly\", () => {\n const testCases = [\n { value: \"string\" },\n { value: 42 },\n { value: true },\n { value: { name: \"test\" } },\n { value: [1, 2, 3] },\n ];\n\n testCases.forEach(({ value }) => {\n jest.mocked(useTamboCurrentMessage).mockReturnValue(\n createMockMessage({\n componentState: { testKey: value },\n }),\n );\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", value),\n );\n\n expect(result.current[0]).toEqual(value);\n });\n });\n });\n\n describe(\"State Updates\", () => {\n it(\"should update local state immediately when setValue is called\", () => {\n const initialValue = \"initial\";\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(\n createMockMessage({ componentState: { testKey: initialValue } }),\n );\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", initialValue),\n );\n\n const newValue = \"updated\";\n act(() => {\n result.current[1](newValue);\n });\n\n expect(result.current[0]).toBe(newValue);\n });\n\n it(\"should trigger local thread message update when setValue is called\", () => {\n const message = createMockMessage({\n componentState: { testKey: \"initial\" },\n });\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\"),\n );\n\n const newValue = \"updated\";\n act(() => {\n result.current[1](newValue);\n });\n\n expect(mockUpdateThreadMessage).toHaveBeenCalledWith(\n message.id,\n {\n threadId: message.threadId,\n componentState: {\n testKey: newValue,\n },\n },\n false,\n );\n });\n\n it(\"should trigger debounced remote API call when setValue is called\", () => {\n const message = createMockMessage({\n componentState: { testKey: \"initial\" },\n });\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\"),\n );\n\n const newValue = \"updated\";\n act(() => {\n result.current[1](newValue);\n });\n\n // The debounced function should be called\n expect(mockUpdateComponentState).toHaveBeenCalledWith(message.id, {\n id: message.threadId,\n state: { testKey: newValue },\n });\n });\n\n it(\"should work with complex objects and arrays\", () => {\n const initialValue = { name: \"test\", items: [1, 2, 3] };\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(\n createMockMessage({ componentState: { testKey: initialValue } }),\n );\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", initialValue),\n );\n\n const newValue = { name: \"updated\", items: [4, 5, 6] };\n act(() => {\n result.current[1](newValue);\n });\n\n expect(result.current[0]).toEqual(newValue);\n expect(mockUpdateThreadMessage).toHaveBeenCalledWith(\n expect.any(String),\n expect.objectContaining({\n componentState: {\n testKey: newValue,\n },\n }),\n false,\n );\n });\n });\n\n describe(\"Debouncing Behavior\", () => {\n it(\"should use default debounce time of 500ms\", () => {\n renderHook(() => useTamboComponentState(\"testKey\", \"initial\"));\n\n expect(useDebouncedCallback).toHaveBeenCalledWith(\n expect.any(Function),\n 500,\n );\n });\n\n it(\"should use custom debounce time when provided\", () => {\n const customDebounceTime = 1000;\n\n renderHook(() =>\n useTamboComponentState(\n \"testKey\",\n \"initial\",\n undefined,\n customDebounceTime,\n ),\n );\n\n expect(useDebouncedCallback).toHaveBeenCalledWith(\n expect.any(Function),\n customDebounceTime,\n );\n });\n\n it(\"should flush debounced callback on unmount\", () => {\n const mockFlush = jest.fn();\n const mockDebouncedFn = createMockDebouncedFunction(jest.fn());\n mockDebouncedFn.flush = mockFlush;\n\n // Mock the debounced callback to return our specific mock\n jest.mocked(useDebouncedCallback).mockReturnValue(mockDebouncedFn);\n\n const { unmount } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\"),\n );\n\n unmount();\n\n expect(mockFlush).toHaveBeenCalled();\n });\n });\n\n describe(\"Multi-Hook Scenarios\", () => {\n it(\"should handle multiple hooks with different keyNames independently\", () => {\n const message = createMockMessage({\n componentState: {\n key1: \"value1\",\n key2: \"value2\",\n },\n });\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n\n const { result: result1 } = renderHook(() =>\n useTamboComponentState(\"key1\", \"default1\"),\n );\n const { result: result2 } = renderHook(() =>\n useTamboComponentState(\"key2\", \"default2\"),\n );\n\n expect(result1.current[0]).toBe(\"value1\");\n expect(result2.current[0]).toBe(\"value2\");\n\n // Update first hook\n act(() => {\n result1.current[1](\"updated1\");\n });\n\n expect(result1.current[0]).toBe(\"updated1\");\n expect(result2.current[0]).toBe(\"value2\"); // Should remain unchanged\n });\n\n it(\"should preserve existing componentState when updating another key\", () => {\n const message = createMockMessage({\n componentState: {\n existingKey: \"existing\",\n testKey: \"initial\",\n },\n });\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\"),\n );\n\n act(() => {\n result.current[1](\"updated\");\n });\n\n expect(mockUpdateThreadMessage).toHaveBeenCalledWith(\n message.id,\n {\n threadId: message.threadId,\n componentState: {\n existingKey: \"existing\", // Should preserve existing keys\n testKey: \"updated\",\n },\n },\n false,\n );\n });\n });\n\n describe(\"SetFromProp Feature\", () => {\n it(\"should set value from prop when hasSetFromMessage is false\", () => {\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(createMockMessage({ componentState: {} }));\n\n const propValue = \"from-prop\";\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\", propValue),\n );\n\n // Initially, hasSetFromMessage should be false, so prop value should be used\n expect(result.current[0]).toBe(propValue);\n });\n\n it(\"should ignore setFromProp when initialized from message state\", async () => {\n const existingValue = \"existing\";\n jest.mocked(useTamboCurrentMessage).mockReturnValue(\n createMockMessage({\n componentState: { testKey: existingValue },\n }),\n );\n\n const propValue = \"from-prop\";\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\", propValue),\n );\n\n // Should use existing value from message, not prop value\n await act(async () => {\n await new Promise((resolve) => setTimeout(resolve, 0));\n });\n\n expect(result.current[0]).toBe(existingValue);\n });\n\n it(\"should update state from setFromProp changes when no message state exists\", () => {\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(createMockMessage({ componentState: {} }));\n\n const { result, rerender } = renderHook(\n ({ propValue }) =>\n useTamboComponentState(\"testKey\", \"initial\", propValue),\n { initialProps: { propValue: \"prop1\" } },\n );\n\n expect(result.current[0]).toBe(\"prop1\");\n\n // Change prop value\n rerender({ propValue: \"prop2\" });\n\n // Since hasSetFromMessage is still false (no message state),\n // it should update to new prop value\n expect(result.current[0]).toBe(\"prop2\");\n });\n\n it(\"should handle undefined setFromProp gracefully\", () => {\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(createMockMessage({ componentState: {} }));\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\", undefined),\n );\n\n expect(result.current[0]).toBe(\"initial\");\n });\n });\n\n describe(\"Message State Sync\", () => {\n it(\"should sync with message.componentState changes\", () => {\n const { result, rerender } = renderHook(\n ({ message }) => {\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n return useTamboComponentState(\"testKey\", \"initial\");\n },\n {\n initialProps: {\n message: createMockMessage({\n componentState: { testKey: \"value1\" },\n }),\n },\n },\n );\n\n // Change the message\n const newMessage = createMockMessage({\n componentState: { testKey: \"value2\" },\n });\n\n rerender({ message: newMessage });\n\n // The hook should sync with the new message state\n expect(result.current[0]).toBe(\"value2\");\n expect(mockUpdateThreadMessage).not.toHaveBeenCalled();\n });\n\n it(\"should handle message without componentState gracefully\", () => {\n jest\n .mocked(useTamboCurrentMessage)\n .mockReturnValue(\n createMockMessage({ componentState: undefined as any }),\n );\n\n const { result } = renderHook(() =>\n useTamboComponentState(\"testKey\", \"initial\"),\n );\n\n expect(result.current[0]).toBe(\"initial\");\n });\n\n it(\"should preserve state when message updates but componentState[keyName] unchanged\", () => {\n const message1 = createMockMessage({\n id: \"message1\",\n componentState: { testKey: \"unchanged\" },\n });\n const message2 = createMockMessage({\n id: \"message2\",\n componentState: { testKey: \"unchanged\" },\n });\n\n const { result, rerender } = renderHook(\n ({ message }) => {\n jest.mocked(useTamboCurrentMessage).mockReturnValue(message);\n return useTamboComponentState(\"testKey\", \"initial\");\n },\n { initialProps: { message: message1 } },\n );\n\n // Clear previous calls\n mockUpdateThreadMessage.mockClear();\n\n // Change message but keep same componentState value\n rerender({ message: message2 });\n\n // Should preserve the \"unchanged\" value\n expect(result.current[0]).toBe(\"unchanged\");\n });\n });\n});\n"]}
@@ -1,5 +1,6 @@
1
1
  import React from "react";
2
2
  import { InteractableMetadata, TamboThreadMessage } from "../model/generate-component-response";
3
+ export declare const TamboMessageContext: React.Context<TamboThreadMessage | null>;
3
4
  export interface TamboMessageProviderProps {
4
5
  children: React.ReactNode;
5
6
  message: TamboThreadMessage;
@@ -44,6 +45,8 @@ export interface TamboCurrentComponent {
44
45
  interactableId?: string;
45
46
  /** Description (only present for components wrapped with withInteractable) */
46
47
  description?: string;
48
+ /** Thread ID from the message (only present when the component is part of a thread) */
49
+ threadId?: string;
47
50
  }
48
51
  /**
49
52
  * Hook to access the current component information from the message context.
@@ -1 +1 @@
1
- {"version":3,"file":"use-current-message.d.ts","sourceRoot":"","sources":["../../src/hooks/use-current-message.tsx"],"names":[],"mappings":"AACA,OAAO,KAAoC,MAAM,OAAO,CAAC;AACzD,OAAO,EACL,oBAAoB,EACpB,kBAAkB,EACnB,MAAM,sCAAsC,C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