Skip to content

Commit 0a0b368

Browse files
Merge pull request #265 from pieces-app/fix-context
fix context command
2 parents 4964f97 + 9c249bb commit 0a0b368

File tree

8 files changed

+69
-37
lines changed

8 files changed

+69
-37
lines changed

_pieces_lib/aenum/_py2.py

-7
This file was deleted.

_pieces_lib/pieces_os_client/wrapper/basic_identifier/anchor.py

+5-4
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ def create(cls,type: AnchorTypeEnum,path: str) -> "BasicAnchor":
8282
type = type,
8383
fullpath = path
8484
))
85+
AnchorSnapshot.identifiers_snapshot[anchor.id] = anchor # Update the local cache
8586
return BasicAnchor(anchor.id)
8687

8788
@staticmethod
@@ -125,10 +126,10 @@ def exists(cls, paths: List[str]) -> Optional["BasicAnchor"]:
125126
Returns:
126127
The existing anchor if found, otherwise None.
127128
"""
128-
for anchor in AnchorSnapshot.identifiers_snapshot.values():
129+
for anchor in AnchorSnapshot.identifiers_snapshot.keys():
129130
a = BasicAnchor(anchor)
130131
if a.fullpath == paths:
131-
return BasicAsset(a.id)
132+
return BasicAnchor(a.id)
132133

133134
@property
134135
def assets(self) -> Optional[List["BasicAsset"]]:
@@ -138,7 +139,7 @@ def assets(self) -> Optional[List["BasicAsset"]]:
138139
Returns:
139140
The assets of the anchor.
140141
"""
141-
return [BasicAsset(asset.id) for asset in self.anchor.assets.iterable] if self.anchor.assets else None
142+
return [(asset.id) for asset in self.anchor.assets.iterable] if self.anchor.assets else None
142143

143144
@property
144145
def chats(self) -> Optional[List["BasicChat"]]:
@@ -172,7 +173,7 @@ def from_raw_content(cls, path: str) -> "BasicAnchor":
172173
Returns:
173174
The created BasicAnchor instance.
174175
"""
175-
anchor = cls.exists(path)
176+
anchor = cls.exists([path])
176177
if anchor:
177178
return anchor
178179
else:

_pieces_lib/pieces_os_client/wrapper/context.py

+41-11
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from typing import TYPE_CHECKING, List, Callable, Optional
1+
from typing import TYPE_CHECKING, List, Callable, Optional, SupportsIndex
22
import os
33

44
from Pieces._pieces_lib.pieces_os_client.models.anchors import Anchors
@@ -8,14 +8,14 @@
88
from Pieces._pieces_lib.pieces_os_client.models.seeds import Seeds
99
from Pieces._pieces_lib.pieces_os_client.models.flattened_conversation_messages import FlattenedConversationMessages
1010
from Pieces._pieces_lib.pieces_os_client.models.temporal_range_grounding import TemporalRangeGrounding
11-
from Pieces._pieces_lib.pieces_os_client.wrapper.basic_identifier.anchor import BasicAnchor
1211

12+
from .basic_identifier import BasicAsset, BasicMessage, BasicAnchor
1313
from .long_term_memory import LongTermMemory
1414

1515
if TYPE_CHECKING:
16-
from .basic_identifier import BasicAsset,BasicMessage
1716
from . import PiecesClient
1817
from .copilot import Copilot
18+
from .basic_identifier import BasicChat
1919

2020
class ValidatedContextList(List):
2121
"""
@@ -61,15 +61,23 @@ def __add__(self, other):
6161
new_list.append(value)
6262
return new_list
6363

64-
def pop(self, index: int = -1):
64+
def pop(self, index: SupportsIndex = -1):
6565
value = super().pop(index)
6666
self.on_remove(index)
6767
return value
6868

69+
def clear(self, **kwargs):
70+
if kwargs.get("_notifiy", True):
71+
for item in range(len(self)):
72+
self.on_remove(item)
73+
74+
super().clear()
75+
76+
6977
class Context:
7078
def __init__(self,
7179
pieces_client: "PiecesClient",
72-
copilot: "Copilot" = None,
80+
copilot: "Copilot",
7381
paths: List[str] = None,
7482
raw_assets: List[str] = None,
7583
assets: List["BasicAsset"] = None,
@@ -88,12 +96,12 @@ def __init__(self,
8896
self._messages: FlattenedConversationMessages = FlattenedConversationMessages(iterable=[])
8997
self._paths: Anchors = Anchors(iterable=[])
9098

91-
def clear(self):
99+
def clear(self, **kwargs):
92100
"""Clears the Copilot context"""
93-
self.raw_assets = []
94-
self.paths = []
95-
self.assets = []
96-
self.messages = []
101+
self.raw_assets.clear(_notifiy = kwargs.get("_notifiy", True))
102+
self.paths.clear(_notifiy = kwargs.get("_notifiy", True))
103+
self.assets.clear(_notifiy = kwargs.get("_notifiy", True))
104+
self.messages.clear(_notifiy = kwargs.get("_notifiy", True))
97105
self._paths = Anchors(iterable=[])
98106
self._assets = Assets(iterable=[])
99107
self._raw_assets = Seeds(iterable=[])
@@ -128,6 +136,8 @@ def _add_message(self, message):
128136
if not isinstance(message, BasicMessage):
129137
raise ValueError("Message should be BasicMessage type")
130138
self._messages.iterable.append(message.message)
139+
if not self.copilot.chat:
140+
self.copilot.create_chat()
131141
self.copilot.chat.associate_message(message)
132142

133143
def _remove_message(self, index: int):
@@ -138,6 +148,8 @@ def _add_asset(self, asset):
138148
if not isinstance(asset, BasicAsset):
139149
raise ValueError("Snippet content should be BasicAsset type")
140150
self._assets.iterable.append(asset.asset)
151+
if not self.copilot.chat:
152+
self.copilot.create_chat()
141153
self.copilot.chat.associate_asset(asset)
142154

143155
def _remove_asset(self, index: int):
@@ -148,7 +160,9 @@ def _add_path(self,path):
148160
if not os.path.exists(path):
149161
raise ValueError("Invalid path in the context")
150162
anchor = BasicAnchor.from_raw_content(path)
151-
self._paths.iterable.append(anchor)
163+
self._paths.iterable.append(anchor.anchor)
164+
if not self.copilot.chat:
165+
self.copilot.create_chat()
152166
self.copilot.chat.associate_anchor(anchor)
153167

154168
def _remove_path(self, index: int):
@@ -163,3 +177,19 @@ def _add_raw_asset(self, asset: str):
163177
def _remove_raw_asset(self, index: int):
164178
self._raw_assets.iterable.pop(index)
165179

180+
def _init(self, chat: "BasicChat"):
181+
self.clear(_notifiy = False)
182+
self.assets.extend(
183+
chat._from_indices(
184+
getattr(chat.conversation.assets,"indices",{}),
185+
lambda id: BasicAsset(id)
186+
)
187+
)
188+
ls = chat._from_indices(
189+
getattr(chat.conversation.anchors,"indices",{}),
190+
lambda id: BasicAnchor(id).fullpath
191+
)
192+
ls = [item for sublist in ls for item in sublist]
193+
194+
self.paths.extend(ls)
195+

_pieces_lib/pieces_os_client/wrapper/copilot.py

+5-2
Original file line numberDiff line numberDiff line change
@@ -154,11 +154,14 @@ def chat(self, chat: Optional[BasicChat]):
154154
use chat = None if you want to create a new conversation on asking
155155
"""
156156
self._chat = chat
157-
self.context.clear() # clear the context on changing the conversation
157+
if chat:
158+
self.context._init(chat)
159+
else:
160+
self.context.clear()
158161
self._chat_id = chat._id if chat else None
159162

160163

161-
def create_chat(self, name:Optional[str]=None):
164+
def create_chat(self, name:str = "New Conversation"):
162165
"""
163166
Creates a New Chat and change the current Copilot chat state to the new generated one
164167
"""

copilot/ask_view.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434

3535
ENABLE_LTM = f"""
3636
In order to get the most out of Long-Term Memory (LTM) Context, you need to enable the Long-Term Memory Engine, which provides time-based contextua awareness for your Copilot.
37-
<br>
37+
<br><br>
3838
<div style="padding-right:2px;padding-left:2px;padding-buttom:2px">
3939
<a style="{PHANTOM_A_TAG_STYLE}" href = "enable">Activiate Long-Term Engine</a>
4040
<a style="{PHANTOM_A_TAG_STYLE}" href = "learn">Learn about LTM context</a>

copilot/context_manager.py

+12-9
Original file line numberDiff line numberDiff line change
@@ -8,12 +8,8 @@
88

99
class PiecesContextManagerCommand(sublime_plugin.WindowCommand):
1010
@check_pieces_os()
11-
def run(self,context:str,pieces_asset_id=None,context_remove=None):
12-
if context == "ltm_on":
13-
PiecesSettings.api_client.copilot.context.ltm.chat_enable_ltm()
14-
copilot.gpt_view.run_command('pieces_show_qr_codes',args={"force":True})
15-
elif context == "ltm_off":
16-
PiecesSettings.api_client.copilot.context.ltm.chat_disable_ltm()
11+
def run(self,context:str, pieces_asset_id=None, context_remove=None):
12+
self.handle_ltm(context)
1713

1814
if context_remove:
1915
key,idx = context_remove.split("_")
@@ -27,6 +23,13 @@ def run(self,context:str,pieces_asset_id=None,context_remove=None):
2723

2824
if pieces_asset_id:
2925
PiecesSettings.api_client.copilot.context.assets.append(BasicAsset(pieces_asset_id))
26+
27+
def handle_ltm(self, context):
28+
if context == "ltm_on":
29+
PiecesSettings.api_client.copilot.context.ltm.chat_enable_ltm()
30+
copilot.gpt_view.run_command('pieces_show_qr_codes',args={"force":True})
31+
elif context == "ltm_off":
32+
PiecesSettings.api_client.copilot.context.ltm.chat_disable_ltm()
3033

3134
def is_enabled(self):
3235
v = sublime.active_window().active_view()
@@ -85,9 +88,9 @@ class PiecesAddContextCommand(sublime_plugin.ApplicationCommand):
8588
@check_pieces_os()
8689
def run(self,paths = None):
8790
if paths == None:
88-
paths = [sublime.active_window().active_view().file_name()]
89-
if paths[0] == None: return # check the file already exists
90-
91+
paths = sublime.active_window().active_view().file_name()
92+
if paths == None: return # check the file already exists
93+
paths = [paths]
9194
if not copilot._gpt_view: # check if the Copilot is running
9295
copilot.render_conversation(None) # Create a new conversation
9396
PiecesSettings.api_client.copilot.context.paths.extend(paths)

event_listener.py

+1
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ def _render_conversation(self, views):
101101
for view in views:
102102
if view.settings().get("PIECES_GPT_VIEW"):
103103
conv = view.settings().get("conversation_id")
104+
copilot.gpt_view = view
104105
if conv in ConversationsSnapshot.identifiers_snapshot:
105106
copilot.render_conversation(conv)
106107
else:

misc/reload_command.py

+4-3
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
1+
from .._pieces_lib.pieces_os_client.wrapper.websockets.health_ws import HealthWS
12
from ..settings import PiecesSettings
23
from .._pieces_lib.pieces_os_client.wrapper.websockets import BaseWebsocket
34
import sublime
45
import sublime_plugin
6+
import traceback
57

68

79

@@ -13,11 +15,10 @@ def run(self):
1315
def reload_async(self):
1416
if PiecesSettings.api_client.is_pieces_running():
1517
try:
16-
PiecesSettings.api_client._startup() # Running the startup command
17-
PiecesSettings.on_settings_change()
18-
BaseWebsocket.reconnect_all()
18+
HealthWS.instance.start()
1919
sublime.status_message(f"Reloading [completed]")
2020
except Exception as e:
21+
print(traceback.format_exc())
2122
sublime.error_message(f"Error during reload: {e}")
2223
else:
2324
sublime.status_message(f"PiecesOS is offline")

0 commit comments

Comments
 (0)