forked from balisujohn/localwriter
-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathpanel.py
More file actions
1291 lines (1074 loc) · 57 KB
/
Copy pathpanel.py
File metadata and controls
1291 lines (1074 loc) · 57 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# WriterAgent - AI Writing Assistant for LibreOffice
# Copyright (c) 2024 John Balis
# Copyright (c) 2026 KeithCu (modifications and relicensing)
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
"""Chat sidebar panel logic: session, send/tool loop, and button listeners.
ChatSession holds conversation history. SendButtonListener drives the
streaming tool-calling loop. StopButtonListener and ClearButtonListener
are wired by panel_factory. UNO UI element factory and XDL wiring
remain in panel_factory.py.
"""
from __future__ import annotations
import logging
import threading
import uno
from plugin.chatbot.send_handlers import SendHandlersMixin
from plugin.chatbot.tool_loop import ToolCallingMixin
from plugin.framework.logging import update_activity_state
from plugin.framework.queue_executor import QueueExecutor
from plugin.chatbot.history_db import get_chat_history
# Recording shipped unless built with --no-recording (see scripts/build_oxt.py).
from typing import TYPE_CHECKING, Any, Literal
if TYPE_CHECKING:
from plugin.framework.client.llm_client import LlmClient
_AudioRecorderCls: type[Any] | None
try:
from plugin.chatbot.audio_recorder import AudioRecorder as _AR
_AudioRecorderCls = _AR
except ImportError:
_AudioRecorderCls = None
HAS_RECORDING = _AudioRecorderCls is not None
from plugin.scripting.audio_recorder_service import is_audio_recording_supported
# Default max tool rounds when not in config (get_api_config supplies chat_max_tool_rounds)
DEFAULT_MAX_TOOL_ROUNDS = 5
_GRAMMAR_STATUS_PREVIEW_CHARS = 10
def _clip_grammar_status_preview(s: str, max_len: int = _GRAMMAR_STATUS_PREVIEW_CHARS) -> str:
"""One-line snippet for the sidebar status field (short to save space)."""
compact = " ".join(s.strip().split())
if not compact:
return "(empty)"
if len(compact) <= max_len:
return compact
return f"{compact[:max_len]}…"
def _grammar_status_area(phase: str, result: str, preview: str) -> Literal["language", "grammar"]:
"""Sidebar label bucket: language-detection LLM / failures vs grammar pipeline."""
if phase == "request" and result == "Detecting language":
return "language"
if phase == "failed" and preview.strip().lower() == "language detection":
return "language"
return "grammar"
def format_grammar_status(data: dict[str, Any]) -> str:
"""Format native grammar proofreader progress for the sidebar status field."""
phase = str(data.get("phase") or "")
preview_raw = str(data.get("preview") or "")
result = str(data.get("result") or "")
try:
length = int(data.get("length") or 0)
except Exception:
length = 0
elapsed = data.get("elapsed_ms")
area = _grammar_status_area(phase, result, preview_raw)
preview = _clip_grammar_status_preview(preview_raw)
prefix = "Language:" if area == "language" else "Grammar:"
if phase == "start":
return f"{prefix} queued '{preview}' len {length}"
if phase == "join":
return f"{prefix} waiting '{preview}' len {length}"
if phase == "request":
verb = "detecting" if area == "language" else "checking"
base = f"{prefix} {verb} '{preview}' len {length}"
if result and result not in ("LLM request", "LLM batch request", "Detecting language"):
return f"{prefix} {result}"
return base
if phase == "complete":
suffix = result or "done"
if elapsed is not None:
suffix = f"{suffix}, {elapsed}ms"
return f"{prefix} done '{preview}' len {length}: {suffix}"
if phase == "done":
suffix = result or "done"
if elapsed is not None:
suffix = f"{suffix}, {elapsed}ms"
return f"{prefix} done '{preview}' len {length}: {suffix}"
if phase == "timeout":
return f"{prefix} still running '{preview}' len {length}: {result}"
if phase == "skipped":
return f"{prefix} skipped '{preview}' len {length}: {result}"
if phase == "failed":
return f"{prefix} failed '{preview}' len {length}: {result}"
return f"{prefix} {phase or 'update'} '{preview}' len {length}"
# ---------------------------------------------------------------------------
# ChatSession - holds conversation history for multi-turn chat
# ---------------------------------------------------------------------------
class ChatSession:
"""Maintains the message history for one sidebar chat session."""
tool_streamed_texts: dict[str, list[str]]
def __init__(self, system_prompt=None, session_id=None):
self.session_id = session_id
self.db = None
self.messages = []
self.base_system_prompt = system_prompt or ""
self.document_context = ""
self.active_specialized_domain = None
self.python_tool_domain = None
self.tool_streamed_texts = {}
if session_id:
try:
self.db = get_chat_history(session_id)
self.messages = self.db.get_messages()
except Exception as e:
from plugin.framework.errors import WriterAgentException
if isinstance(e, WriterAgentException):
log.error("ChatSession history load WriterAgentException: %s" % e)
else:
log.error("ChatSession history load error: %s" % e)
# If no history, or system prompt forced
if not self.messages and self.base_system_prompt:
self.set_system_context(self.base_system_prompt, "")
if self.db:
self.db.add_message("system", self.messages[0]["content"])
def set_system_context(self, base_prompt, doc_text=""):
"""Update the system prompt and document context, combining them into the first message."""
self.base_system_prompt = base_prompt
self.document_context = doc_text
content = base_prompt
if doc_text:
content += f"\n\n[DOCUMENT CONTENT]\n{doc_text}\n[END DOCUMENT]"
if not self.messages or self.messages[0]["role"] != "system":
self.messages.insert(0, {"role": "system", "content": content})
else:
self.messages[0]["content"] = content
def add_user_message(self, content):
self.messages.append({"role": "user", "content": content})
if self.db:
self.db.add_message("user", content)
def add_assistant_message(self, content=None, tool_calls=None, reasoning_replay=None):
msg = {"role": "assistant"}
if content:
msg["content"] = content
else:
msg["content"] = ""
if tool_calls:
msg["tool_calls"] = tool_calls
if reasoning_replay:
msg.update(reasoning_replay)
self.messages.append(msg)
if self.db:
# Only persist the text content to history; tool calls are ephemeral.
self.db.add_message("assistant", content)
def add_tool_result(self, tool_call_id, content):
self.messages.append({"role": "tool", "tool_call_id": tool_call_id, "content": content})
# Note: We do NOT persist tool results to history_db.
# This keeps the persistent history clean of tool formatting requirements.
def clear(self):
"""Reset to just the system prompt."""
self.messages = []
self.document_context = ""
if self.db:
self.db.clear()
if self.base_system_prompt:
self.set_system_context(self.base_system_prompt, "")
if self.db:
self.db.add_message("system", self.messages[0]["content"])
# ---------------------------------------------------------------------------
# QueryTextListener - dynamic button toggling
# ---------------------------------------------------------------------------
from plugin.chatbot.listeners import BaseActionListener, BaseKeyListener, BaseTextListener
from plugin.chatbot.audio_recorder_state import AudioRecorderState
from plugin.chatbot.send_state import SendButtonState, SendEvent, SendEventKind, StartRecordingEffect, StartSendEffect, StopRecordingEffect, StopSendEffect, UpdateUIEffect
from plugin.chatbot.sidebar_state import LogSidebarEffect, SidebarCompositeState, SidebarEvent, SidebarEventKind, sidebar_next_state
log = logging.getLogger(__name__)
def _uno_model_probe_for_log(model: Any, *, cached_doc_type: str | None = None) -> str:
"""Short UNO diagnostic for error logs. No document text or type probing."""
if model is None:
return "None"
impl = "?"
try:
impl = model.getImplementationName()
except Exception:
pass
if cached_doc_type:
return "impl=%s doc_type=%s" % (impl, cached_doc_type)
return "impl=%s" % impl
class QueryTextListener(BaseTextListener):
def __init__(self, send_listener):
# We now keep a reference to the main SendButtonListener which holds the state
self.send_listener = send_listener
def on_text_changed(self, rEvent):
model = getattr(rEvent.Source, "Model", None)
if not model:
model = rEvent.Source.getModel()
text = model.Text.strip()
# Dispatch event to the state machine
self.send_listener.dispatch(SendEvent(SendEventKind.TEXT_UPDATED, {"has_text": bool(text)}))
# UNO Key.RETURN / KeyModifier.SHIFT (test-friendly integer codes)
_QUERY_KEY_RETURN = 1280
_QUERY_KEY_MODIFIER_SHIFT = 1
def query_enter_triggers_primary_send(key_code: int, modifiers: int) -> bool:
"""True when this key event should run the same primary action as Send (Enter without Shift)."""
return bool(key_code == _QUERY_KEY_RETURN and (modifiers & _QUERY_KEY_MODIFIER_SHIFT) == 0)
_DOC_CHAT_ENTER_SENDS = "doc.chat_enter_key_sends_message"
class QueryKeyListener(BaseKeyListener):
"""Enter in the query field triggers Send when enabled in Settings (Shift+Enter inserts a newline)."""
def __init__(self, send_listener):
self.send_listener = send_listener
def on_key_pressed(self, e):
if not query_enter_triggers_primary_send(e.KeyCode, e.Modifiers):
return
try:
from plugin.framework.config import get_config_bool
if not get_config_bool(_DOC_CHAT_ENTER_SENDS):
return
except Exception:
pass
sc = self.send_listener.send_control
if not sc or not sc.getModel():
return
if not sc.getModel().Enabled:
return
try:
if hasattr(e, "Consume"):
setattr(e, "Consume", True)
except Exception:
pass
self.send_listener.on_action_performed(e)
# ---------------------------------------------------------------------------
# SendButtonListener - handles Send button click with tool-calling loop
# ---------------------------------------------------------------------------
class SendButtonListener(SendHandlersMixin, ToolCallingMixin, BaseActionListener):
"""Listener for the Send button - runs chat with document, supports tool-calling."""
client: LlmClient | None
initial_doc_type: str | None
cached_doc_type: str | None
cached_uno_services: frozenset[str] | None
_record_assistant_start: bool
def __init__(
self, ctx, frame, send_control, stop_control, query_control, response_control, image_model_selector, model_selector, status_control, session, chat_mode_selector=None, aspect_ratio_selector=None, base_size_input=None, sidebar_include_brainstorming=True, ensure_path_fn=None, clear_control=None
):
self.ctx = ctx
self.frame = frame
self.send_control = send_control
self.stop_control = stop_control
self.clear_control = clear_control
self.query_control = query_control
self.response_control = response_control
self.image_model_selector = image_model_selector
self.model_selector = model_selector
self.status_control = status_control
self.session = session
self.chat_mode_selector = chat_mode_selector
self.aspect_ratio_selector = aspect_ratio_selector
self.base_size_input = base_size_input
self.sidebar_include_brainstorming = sidebar_include_brainstorming
from plugin.chatbot.chat_sidebar_mode import SidebarModeFlags
self.sidebar_mode_flags = SidebarModeFlags(include_brainstorming=sidebar_include_brainstorming)
self.ensure_path_fn = ensure_path_fn
self.initial_doc_type = None # Set by _wireControls
self.cached_doc_type = None
self.cached_uno_services = None
self._stop_requested_fallback = False
self._send_cancellation = None
self._terminal_status = "Ready"
self._send_busy = False
self._in_librarian_mode = False
self._in_brainstorming_mode = False
self._brainstorming_topic = ""
self._in_writing_plan_mode = False
self._writing_plan_topic = ""
self._in_ppt_master_mode = False
self._ppt_master_topic = ""
self.client = None
self.audio_wav_path = None
self._current_agent_backend = None # Set during _do_send_via_agent_backend for Stop button
self._fixed_send_width = None
self._active_q: Any = None
self._active_client: Any = None
self._active_max_tokens: Any = None
self._active_tools: Any = None
self._active_execute_tool_fn: Any = None
self._active_max_tool_rounds: Any = None
self._active_query_text: Any = None
self._active_model: Any = None
self._active_async_tools: Any = None
self._active_supports_status: Any = None
self._active_round_num: Any = None
self._active_pending_tools: Any = None
self._current_tool_call_id = None
self._record_assistant_start = False
self._assistant_stream_start_len = None
self._approval_event = None
self._approval_ui_backup = None
self._approval_query_for_engine = None
self.rich_text_widget = None
self._rich_plain_fallback_warned = False
self.queue_executor = QueueExecutor()
if HAS_RECORDING:
assert _AudioRecorderCls is not None
self.audio_recorder = _AudioRecorderCls(ctx)
self.audio_recorder.set_auto_stop_callbacks(
on_auto_stop=lambda: self.queue_executor.post(self._on_audio_auto_stop),
on_silence_progress=lambda ms: self.queue_executor.post(self._on_audio_silence_progress, ms),
)
else:
self.audio_recorder = None
audio_supported = HAS_RECORDING and is_audio_recording_supported(ctx)
send_initial = SendButtonState(is_busy=False, is_recording=False, has_text=False, has_audio=False, audio_supported=audio_supported)
self.sidebar_state = SidebarCompositeState(send=send_initial, tool_loop=None, audio=AudioRecorderState(status="idle"))
# Subscribe to MCP/tool bus events
try:
from plugin.main import get_tools
from plugin.framework.event_bus import global_event_bus
event_bus = getattr(get_tools()._services, "events", None)
if event_bus:
event_bus.subscribe("mcp:request", self._on_mcp_request)
event_bus.subscribe("mcp:result", self._on_mcp_result)
log.debug(f"*** SendButtonListener subscribed to MCP events on services.events (id={id(event_bus)}) ***")
global_event_bus.subscribe("grammar:status", self._on_grammar_status, weak=True)
except Exception:
log.exception("SendButtonListener event subscribe error")
def set_rich_text_widget(self, widget):
"""Enable RichTextControl sidebar rendering via hidden-doc formatted copy."""
self.rich_text_widget = widget
log.info("[RICH-CONTROL] SendButtonListener.set_rich_text_widget called")
def rerender_rich_text_session(self):
"""Re-render the final streamed assistant response with HTML formatting, leaving previous text untouched.
Called after streaming completes to replace the last plain-text assistant response
with full HTML rendering instead of raw chunks.
"""
widget = getattr(self, "rich_text_widget", None)
if widget is None:
return
try:
widget.rerender_last_assistant_if_html(
self.session,
getattr(self, "_assistant_stream_start_len", None),
)
except Exception:
log.exception("rerender_rich_text_session (rich control) failed")
@property
def state(self):
"""Send-button slice of :attr:`sidebar_state` (migration alias)."""
return self.sidebar_state.send
@state.setter
def state(self, value):
import dataclasses
self.sidebar_state = dataclasses.replace(self.sidebar_state, send=value)
@property
def stop_requested(self) -> bool:
scope = getattr(self, "_send_cancellation", None)
if scope is not None:
return scope.is_cancelled()
return self._stop_requested_fallback
@stop_requested.setter
def stop_requested(self, value: bool) -> None:
if value:
scope = getattr(self, "_send_cancellation", None)
if scope is not None:
scope.cancel()
self._stop_requested_fallback = True
else:
self._stop_requested_fallback = False
def resolve_stop_checker(self):
"""Stable stop predicate for worker threads (survives clearing ``_send_cancellation``).
``StartSendEffect`` clears ``_send_cancellation`` when the drain loop exits while
web-research / tool workers may still run — pass this checker (not
``lambda: self.stop_requested`` alone) into ``LlmClient`` and stream drains.
See ``docs/streaming-and-threading.md`` § Stop / cancellation.
"""
from plugin.framework.queue_executor import bind_send_stop_checker
return bind_send_stop_checker(getattr(self, "_send_cancellation", None), lambda: self._stop_requested_fallback)
def sync_audio_slice(self):
"""Mirror :attr:`audio_recorder.state` into the composite (strategy A)."""
import dataclasses
if self.audio_recorder is None:
return
self.sidebar_state = dataclasses.replace(self.sidebar_state, audio=self.audio_recorder.state)
def set_session(self, session):
"""Update the active session (e.g. when switching between Document and Research chat)."""
self.session = session
self.client = None # Force client recreation if needed, though they usually share same config
def on_brainstorming_session_finished(self, spec_saved: bool = False) -> None:
"""Reset sidebar after brainstorming_finished (dropdown transitions to Writing Plan or Chat)."""
from plugin.chatbot.chat_sidebar_mode import (
CHAT_MODE_CHAT,
CHAT_MODE_WRITING_PLAN,
clear_brainstorming_session,
set_selector_mode_with_flags,
)
flags = getattr(self, "sidebar_mode_flags", None)
clear_brainstorming_session(self)
if spec_saved:
self._in_writing_plan_mode = True
self._writing_plan_topic = f"Implement the saved spec: {self._brainstorming_topic}"
if self.chat_mode_selector and flags:
set_selector_mode_with_flags(self.chat_mode_selector, CHAT_MODE_WRITING_PLAN, flags)
else:
if self.chat_mode_selector and flags:
set_selector_mode_with_flags(self.chat_mode_selector, CHAT_MODE_CHAT, flags)
def on_writing_plan_session_finished(self) -> None:
"""Reset sidebar after writing_plan_finished (dropdown returns to Chat)."""
from plugin.chatbot.chat_sidebar_mode import (
CHAT_MODE_CHAT,
clear_writing_plan_session,
set_selector_mode_with_flags,
)
flags = getattr(self, "sidebar_mode_flags", None)
clear_writing_plan_session(self)
if self.chat_mode_selector and flags:
set_selector_mode_with_flags(self.chat_mode_selector, CHAT_MODE_CHAT, flags)
def on_ppt_master_session_finished(self, exported: bool = False) -> None:
"""Reset sidebar after ppt_master_finished (dropdown returns to Chat)."""
from plugin.chatbot.chat_sidebar_mode import (
CHAT_MODE_CHAT,
clear_ppt_master_session,
set_selector_mode_with_flags,
)
del exported
flags = getattr(self, "sidebar_mode_flags", None)
clear_ppt_master_session(self)
if self.chat_mode_selector and flags:
set_selector_mode_with_flags(self.chat_mode_selector, CHAT_MODE_CHAT, flags)
def begin_inline_web_approval(self, query: str, tool: str, event: Any) -> None:
"""Replace Send/Stop/Clear with Accept/Change/Reject (all enabled). Unblock ``event`` when user chooses.
Approval mode only mutates UNO control labels/enabled flags here and restores them from
``_approval_ui_backup`` in ``_finish_inline_web_approval``. It does **not** update
``sidebar_state.send`` or go through :meth:`dispatch` for those temporary labels—by design.
Do not "fix" this by routing approval chrome through the send FSM; keep backup/restore
as the source of truth for this overlay.
"""
from plugin.framework.i18n import _
if event is None:
log.warning("begin_inline_web_approval: no event")
return
if getattr(self, "_approval_event", None) is not None:
log.warning("begin_inline_web_approval: superseding pending approval")
self._finish_inline_web_approval(False)
self._approval_event = event
self._approval_query_for_engine = query
self._approval_ui_backup = {}
try:
if self.send_control and self.send_control.getModel():
m = self.send_control.getModel()
self._approval_ui_backup["send_label"] = m.Label
self._approval_ui_backup["send_enabled"] = m.Enabled
if self.stop_control and self.stop_control.getModel():
m = self.stop_control.getModel()
self._approval_ui_backup["stop_label"] = m.Label
self._approval_ui_backup["stop_enabled"] = m.Enabled
if self.clear_control and self.clear_control.getModel():
cm = self.clear_control.getModel()
self._approval_ui_backup["clear_enabled"] = cm.Enabled
self._approval_ui_backup["clear_label"] = cm.Label
if self.status_control:
self._approval_ui_backup["status_text"] = self.status_control.getText()
except Exception as e:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
if isinstance(e, (DisposedException, RuntimeException, UnoException)):
log.debug("begin_inline_web_approval backup (likely disposed): %s", e)
else:
log.debug("begin_inline_web_approval backup: %s", e)
try:
if self.send_control and self.send_control.getModel():
m = self.send_control.getModel()
m.Label = _("Accept")
m.Enabled = True
if self._fixed_send_width:
try:
r = self.send_control.getPosSize()
if r.Width != self._fixed_send_width:
self.send_control.setPosSize(r.X, r.Y, self._fixed_send_width, r.Height, 15)
except Exception as e:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
if isinstance(e, (DisposedException, RuntimeException, UnoException)):
log.debug("begin_inline_web_approval setPosSize (likely disposed): %s", e)
if self.stop_control and self.stop_control.getModel():
m = self.stop_control.getModel()
m.Label = _("Change")
m.Enabled = True
if self.clear_control and self.clear_control.getModel():
m = self.clear_control.getModel()
m.Label = _("Reject")
m.Enabled = True
except Exception as e:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
if isinstance(e, (DisposedException, RuntimeException, UnoException)):
log.debug("begin_inline_web_approval error (likely disposed): %s", e)
else:
log.exception("begin_inline_web_approval failed")
# Approval is inline (Accept / Change / Reject); search preview is already in the transcript.
self._set_status(_("Waiting for approval…"))
log.info("Inline web approval: waiting for Accept, Change, or Reject")
def _open_web_search_change_dialog(self):
"""Open edit dialog for the pending web_search query; OK continues with optional override."""
from plugin.chatbot.dialogs import show_web_search_query_edit_dialog
initial = getattr(self, "_approval_query_for_engine", None) or ""
text = show_web_search_query_edit_dialog(self.ctx, self.frame, initial)
if text is None:
return
log.debug("_open_web_search_change_dialog: applying edited query len=%d", len(text))
self._finish_inline_web_approval(True, query_override=text)
def _finish_inline_web_approval(self, approved, query_override=None):
ev = getattr(self, "_approval_event", None)
if ev is None:
return
self._approval_event = None
self._approval_query_for_engine = None
b = self._approval_ui_backup or {}
self._approval_ui_backup = None
try:
if self.send_control and self.send_control.getModel():
m = self.send_control.getModel()
if "send_label" in b:
m.Label = b["send_label"]
if "send_enabled" in b:
m.Enabled = b["send_enabled"]
if self.stop_control and self.stop_control.getModel():
m = self.stop_control.getModel()
if "stop_label" in b:
m.Label = b["stop_label"]
if "stop_enabled" in b:
m.Enabled = b["stop_enabled"]
if self.clear_control and self.clear_control.getModel() and "clear_enabled" in b:
cm = self.clear_control.getModel()
cm.Enabled = b["clear_enabled"]
if "clear_label" in b:
cm.Label = b["clear_label"]
if self.status_control and "status_text" in b:
self.status_control.setText(b["status_text"])
except Exception as e:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
if isinstance(e, (DisposedException, RuntimeException, UnoException)):
log.debug("_finish_inline_web_approval restore (likely disposed): %s", e)
else:
log.debug("_finish_inline_web_approval restore: %s", e)
try:
ev.approved = approved
ev.query_override = query_override if approved else None
if approved and query_override is not None:
log.debug("_finish_inline_web_approval: approved with query_override len=%d", len(query_override))
ev.set()
except Exception:
log.exception("_finish_inline_web_approval threading event error")
def _set_status(self, text):
"""Update the status field in the sidebar (read-only TextField).
Uses setText() (XTextComponent) to write directly to the control/peer,
bypassing model→view notifications which can desync after document edits."""
try:
if self.status_control:
self.status_control.setText(text)
else:
log.debug("_set_status: NO CONTROL for '%s'" % text)
except Exception as e:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
if isinstance(e, (DisposedException, RuntimeException, UnoException)):
log.debug("_set_status('%s', level=logging.DEBUG) likely disposed: %s" % (text, e))
else:
log.debug("_set_status('%s', level=logging.DEBUG) EXCEPTION: %s" % (text, e))
def _on_grammar_status(self, **data):
"""Show native grammar proofreader progress in the sidebar status field."""
if self._send_busy or self._approval_event is not None:
return
text = format_grammar_status(data)
try:
from plugin.framework.queue_executor import post_to_main_thread
post_to_main_thread(self._set_status, text)
except Exception as e:
log.debug("_on_grammar_status: post_to_main_thread failed: %s", e)
self._set_status(text)
def _scroll_response_to_bottom(self):
"""Scroll the response area to show the bottom (newest content).
Uses XTextComponent.setSelection to place caret at end, which scrolls the view."""
try:
if self.response_control:
model = self.response_control.getModel()
if model and hasattr(self.response_control, "setSelection"):
text = model.Text or ""
length = len(text)
self.response_control.setSelection(uno.createUnoStruct("com.sun.star.awt.Selection", length, length))
except Exception as e:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
if isinstance(e, (DisposedException, RuntimeException, UnoException)):
log.debug("_scroll_response_to_bottom failed (likely disposed): %s", e)
'''
def _get_scrollbar(self):
... # commented out — scrollbar was never found in embedded frames
'''
def _should_auto_scroll(self):
"""Always returns True for now — forces scroll to bottom on every append.
Future: implement sticky scroll by reading VCL scrollbar position and
returning False when user has manually scrolled up.
"""
return True
def _run_rich_ui(self, fn, *args, **kwargs):
"""Run rich-control UI work inline on the main thread; post from workers."""
if threading.current_thread() is threading.main_thread():
return fn(*args, **kwargs)
self.queue_executor.post(fn, *args, **kwargs)
def _append_response(self, text, is_thinking=False, role="assistant"):
"""Append text to the response area (RichTextControl or plain multiline field)."""
try:
widget = getattr(self, "rich_text_widget", None)
if widget:
auto_scroll = self._should_auto_scroll()
log.debug("_append_response: rich-control len=%d role=%s", len(text) if text else 0, role)
if role == "user":
def _on_user_inserted(control_len: int) -> None:
self._assistant_stream_start_len = control_len
log.debug("_append_response: rich-control stream start len=%d", control_len)
self._run_rich_ui(
widget.append_user_message,
text,
on_after_insert=_on_user_inserted,
)
else:
if getattr(self, "_record_assistant_start", False):
self._record_assistant_start = False
self._assistant_stream_start_len = widget.get_text_length()
log.debug(
"_append_response: rich-control stream start len=%d (final answer)",
self._assistant_stream_start_len,
)
if getattr(self, "_plain_text_stripper", None) is not None:
clean_text = self._plain_text_stripper.feed(text)
else:
from plugin.framework.html_stripper import strip_html_tags
clean_text = strip_html_tags(text)
self._run_rich_ui(
widget.append_assistant_stream_chunk,
clean_text,
auto_scroll=auto_scroll,
)
return
if not getattr(self, "_rich_plain_fallback_warned", False):
from plugin.framework.config import get_config_bool_safe
if get_config_bool_safe("rich_text_control_sidebar"):
log.warning(
"[RICH-CONTROL] _append_response plain fallback while rich_text_control_sidebar enabled",
)
self._rich_plain_fallback_warned = True
if self.response_control and self.response_control.getModel():
from plugin.chatbot.dialogs import get_control_text, set_control_text
from plugin.framework.html_stripper import strip_html_tags
should_scroll = self._should_auto_scroll()
current = get_control_text(self.response_control) or ""
if role == "assistant" and getattr(self, "_plain_text_stripper", None) is not None:
clean_text = self._plain_text_stripper.feed(text)
else:
clean_text = strip_html_tags(text)
set_control_text(self.response_control, current + clean_text)
if should_scroll:
self._scroll_response_to_bottom()
except Exception as e:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
if isinstance(e, (DisposedException, RuntimeException, UnoException)):
log.debug("_append_response failed (likely disposed): %s", e)
def _on_mcp_request(self, tool="", args=None, method=None, **kwargs):
"""Handle MCP request events from the bus (background thread)."""
try:
from plugin.framework.logging import format_tool_call_for_display
fmt_str = format_tool_call_for_display(tool, args, method)
log.debug(f"MCP Request (hidden from UI, level=logging.DEBUG): {fmt_str}")
except Exception:
log.exception("_on_mcp_request error")
def _on_mcp_result(self, tool="", result_snippet="", **kwargs):
"""Handle MCP result events from the bus (background thread)."""
def _update_ui():
try:
from plugin.framework.logging import format_tool_result_for_display
fmt_str = format_tool_result_for_display(tool, result_snippet, args=kwargs.get("args"))
self._append_response(f"[MCP Result] {fmt_str}\n")
except Exception:
log.exception("_on_mcp_result UI update error")
try:
self.queue_executor.post(_update_ui)
except Exception:
log.exception("_on_mcp_result post error")
def _get_document_model(self):
"""Get the document model strictly from the frame.
Always prefers the document bound to this sidebar's frame (same window as the user)
instead of ``Desktop.getCurrentComponent()``, which can point at the wrong
document if focus changes.
"""
from plugin.doc.document_helpers import get_document_from_frame
model = get_document_from_frame(self.frame)
_COMPATIBLE_DOC_TYPES = frozenset({"writer", "calc", "draw", "impress"})
cached_doc_type = getattr(self, "cached_doc_type", None)
if model and cached_doc_type in _COMPATIBLE_DOC_TYPES:
return model
# Only log when chat send will fail (same moment as the sidebar error message).
detail_parts = [
"has_frame=%s" % bool(self.frame),
"cached_doc_type=%s" % cached_doc_type,
"model_probe=%s" % _uno_model_probe_for_log(model, cached_doc_type=cached_doc_type),
]
if model is not None:
detail_parts.append("reject_reason=unsupported_or_uncached_doc_type probe=%s" % _uno_model_probe_for_log(model, cached_doc_type=cached_doc_type))
log.error("SendButtonListener: no compatible document model for chat (%s)", "; ".join(detail_parts))
return None
def set_fixed_send_width(self, width_px):
self._fixed_send_width = width_px
def _set_button_states(self, send_enabled, stop_enabled):
"""Set Send/Stop enabled flags (per-control try/except so one UNO failure cannot strand the other)."""
if self.send_control and self.send_control.getModel():
try:
self.send_control.getModel().Enabled = bool(send_enabled)
except Exception as e:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
if isinstance(e, (DisposedException, RuntimeException, UnoException)):
log.debug("Failed to set send_control enabled state (likely disposed): %s", e)
if self.stop_control and self.stop_control.getModel():
try:
self.stop_control.getModel().Enabled = bool(stop_enabled)
except Exception as e:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
if isinstance(e, (DisposedException, RuntimeException, UnoException)):
log.debug("Failed to set stop_control enabled state (likely disposed): %s", e)
def dispatch(self, event):
"""Dispatch an event to the state machine, compute new state, and apply effects."""
tr = sidebar_next_state(self.sidebar_state, SidebarEvent(kind=SidebarEventKind.SEND, payload=event))
self.sidebar_state = tr.state
self._send_busy = self.sidebar_state.send.is_busy
for effect in tr.effects:
self._interpret_effect(effect)
def _on_audio_auto_stop(self) -> None:
"""Silence detector ended capture; same FSM path as clicking Stop Rec (stop + send)."""
if not self.sidebar_state.send.is_recording:
log.info("audio auto-stop ignored (not recording)")
return
log.info("Audio silence pause detected — treating as Stop Rec")
self.dispatch(SendEvent(SendEventKind.STOP_REC_CLICKED))
def _on_audio_silence_progress(self, silence_ms: int) -> None:
from plugin.framework.i18n import _
if self.sidebar_state.send.is_recording:
self._set_status(_("Recording audio… (%d ms silence)") % silence_ms)
def _interpret_effect(self, effect):
"""Interpret a state machine effect and apply side-effects."""
from plugin.framework.i18n import _
match effect:
case LogSidebarEffect():
log.debug("%s", effect.message)
case UpdateUIEffect():
self._set_button_states(effect.send_enabled, effect.stop_enabled)
if self.send_control and self.send_control.getModel():
btn_model = self.send_control.getModel()
if btn_model.Label != _(effect.send_label):
btn_model.Label = _(effect.send_label)
if self._fixed_send_width:
try:
r = self.send_control.getPosSize()
if r.Width != self._fixed_send_width:
self.send_control.setPosSize(r.X, r.Y, self._fixed_send_width, r.Height, 15)
except Exception as e:
from com.sun.star.lang import DisposedException
from com.sun.star.uno import RuntimeException, Exception as UnoException
if isinstance(e, (DisposedException, RuntimeException, UnoException)):
log.debug("Failed to set pos size for send_control (likely disposed): %s", e)
if effect.status_text is not None and effect.status_text != "":
self._set_status(_(effect.status_text))
case StartRecordingEffect():
if not self.audio_recorder:
return
try:
self.audio_recorder.start_recording()
except RuntimeError as re:
self._append_response("\n[Audio error: %s]\n" % str(re))
self.dispatch(SendEvent(SendEventKind.ERROR_OCCURRED))
self.sync_audio_slice()
case StopRecordingEffect():
if not self.audio_recorder:
return
try:
self.audio_wav_path = self.audio_recorder.stop_recording()
except Exception as e:
from plugin.framework.errors import WriterAgentException
if isinstance(e, WriterAgentException):
log.exception("WriterAgentException stopping recording")
else:
log.exception("Error stopping recording")
self.sync_audio_slice()
case StartSendEffect():
self._stop_requested_fallback = False
self._terminal_status = "Ready"
try:
from plugin.framework.queue_executor import agent_session
# Scope is cleared in finally; workers use resolve_stop_checker().
with agent_session() as cancel_scope:
self._send_cancellation = cancel_scope
try:
self._do_send()
finally:
self._send_cancellation = None
except Exception as e:
doc_type_for_log = getattr(self, "initial_doc_type", "unknown")
log.exception("SendButton unhandled exception [doc: %s]", doc_type_for_log)
self._append_response("\n\n[Error: %s]\n" % str(e))
self.dispatch(SendEvent(SendEventKind.ERROR_OCCURRED))
finally:
update_activity_state("")
if self._terminal_status == "Error":
self.dispatch(SendEvent(SendEventKind.ERROR_OCCURRED))
else:
self.dispatch(SendEvent(SendEventKind.SEND_COMPLETED))
if self._terminal_status:
self._set_status(_(self._terminal_status))
case StopSendEffect():
scope = getattr(self, "_send_cancellation", None)
if scope is not None:
scope.cancel()
self._stop_requested_fallback = True
case _:
log.debug("SendButtonListener: unhandled effect type %s", type(effect).__name__)
def on_action_performed(self, rEvent):
from plugin.framework.i18n import _
if getattr(self, "_approval_event", None) is not None and self.send_control and self.send_control.getModel():
if self.send_control.getModel().Label == _("Accept"):
self._finish_inline_web_approval(True)
return
btn_model = self.send_control.getModel()
label = btn_model.Label
if label == _("Record"):
self.dispatch(SendEvent(SendEventKind.RECORD_CLICKED))
elif label == _("Stop Rec"):
self.dispatch(SendEvent(SendEventKind.STOP_REC_CLICKED))
elif label == _("Send"):
self.dispatch(SendEvent(SendEventKind.SEND_CLICKED))